Skip to content

fix(ai): agent toolset instructions, deferred-tool context, the sampling-model stub, harness memory and shell process groups #958

Closed

Description

@dan-petty

Problem

The devsecops review session 20261001-224227 (2026-10-02, a path review of the whole repository with local models) raised 563 findings. A triage of every finding against release/v0.2.25 (c279c18) judged 489 false. Each of the 5 defects below was confirmed with code evidence and then upheld by a second agent that tried to refute it. The severities are re-rated; the review's own ratings were inflated.

Coroutine Leak in Tool Instructions Extraction (src/devops_cli/ai/agents/agent.py:114, LOW, correctness)

  • Defect: Closing the coroutine is correct cleanup and leaks nothing. The real defect is at the same lines: if inspect.iscoroutine(instructions): instructions.close(); return [] silently drops toolset instructions whenever ctx is passed. devops-cli's FunctionToolset.get_instructions returns super().get_instructions(ctx) (pydantic_ai's async method) when ctx is not None (toolsets/init.py:352-359), and AbstractToolset returns self._async_get_instructions(ctx) (toolsets/init.py:111-118). run() always builds a RunContext and calls _build_system_prompt_with_tools(ctx=ctx) (agent.py:809-825), and so does iter() (agent.py:1081). Probe against the assess tree: _extract_single_toolset_instructions(FunctionToolset(instructions='X'), None) returned ['X'], and with a RunContext it returned []. The system prompt contained X without ctx and lacked it with ctx, so run_stream (no ctx) and …
  • Skeptic's ruling: The original finding is wrong: calling close() on the never-awaited coroutine is correct cleanup, nothing leaks, CWE-400 and CRITICAL do not apply, and the suggested await cannot work inside this sync function. A real functional defect sits on the same lines, so the triage's reframed finding is upheld. In src/devops_cli/ai/agents/agent.py::_extract_single_toolset_instructions, a non-None ctx makes it call ts.get_instructions(ctx). For devops-cli FunctionToolset …
  • Fix: In _extract_single_toolset_instructions, first try the synchronous path for devops-cli toolsets: for an instance of devops_cli.ai.toolsets.FunctionToolset or AbstractToolset, call ts.get_instructions() with no ctx, which returns a sync list. Only for native pydantic_ai toolsets, call get_instructions(ctx). If that returns a coroutine and no event loop is running, drive it with asyncio.run(...). Otherwise close it and logger.debug that the instructions were skipped, so they are never dropped silently. Better still, make prompt assembly async in the async paths. Keep handling of the str, list, tuple and .content result shapes unchanged.
  • Regression test: In tests/test_pydantic_agent.py, add test_toolset_instructions_reach_run_system_prompt. Build ts = FunctionToolset(instructions='Always follow semver.') and mock_client = MagicMock(model='test-model') with chat_messages.return_value='done'. Create agent = PydanticAgent(client=mock_client, name='R', system_prompt='Base.', toolsets=[ts]) and call agent.run('hi', max_turns=1, skip_rag=True). Assert that 'Always follow semver.' is in mock_client.chat_messages.call_args_list[0].args[0]. Also assert …

Inconsistent Handler Signature Detection in HandleDeferredToolCalls (src/devops_cli/ai/agents/capabilities.py:516, LOW, correctness)

  • Defect: capabilities.py:516-521 calls self.handler(ctx, requests) if (len(sig.parameters) >= 2 and ctx is not None) else self.handler(requests). The agent loop never passes a ctx: agent.py:701 calls _find_deferred_tool_handler(self.capabilities, req) and runner.py:252-253 calls cap.handle_deferred(req). A two-argument (ctx, requests) handler, which test_ai_agent_deferred_tools.py documents and tests only by direct call, therefore gets handler(requests) during a real run. Reproduced with _find_deferred_tool_handler([HandleDeferredToolCalls(two)], req) -> TypeError: two() missing 1 required positional argument: 'requests'. The sibling capabilities at capabilities.py:1047-1053 and 1089-1095 substitute RunContext() when ctx is None. The finding's wording has the direction backwards, but the inconsistency it points at is a real crash. No production code builds …
  • Skeptic's ruling: I could not refute it. In the real loop, agent.py:701 calls _find_deferred_tool_handler(self.capabilities, req) without the ctx it already has in scope; the run builds that ctx at agent.py:809 and passes it into dispatch at :664. runner.py:252-253 then calls cap.handle_deferred(req), so ctx is always None. capabilities.py:517-521 only passes ctx when len(sig.parameters) >= 2 and ctx is not None. A (ctx, requests) handler therefore gets called as handler(requests). I reproduced this …
  • Fix: Give runner.py _find_deferred_tool_handler(capabilities, req, ctx: RunContext | None = None). Pass ctx on (cap.handle_deferred(req, ctx), and pass it to the generic handle_deferred_tool_calls/handle_deferred hooks when their signatures take it). Call it with the loop's ctx at agent.py:701. In HandleDeferredToolCalls.handle_deferred, choose the call by the handler's signature alone: 2+ params -> self.handler(ctx if ctx is not None else RunContext(), requests), else self.handler(requests). This matches the RunContext() fallback at capabilities.py:1051/1093. Land it before or with feat(mcp): mcp tools declare ToolAnnotations, and mutating tools require approval in devops-cli's own agent loop #857.
  • Regression test: In tests/test_pydantic_agent.py, add test_deferred_handler_two_arg_receives_run_context_in_agent_run. Build a PydanticAgent with mock client.chat_messages.side_effect = ['{"tool": "delete_prod_cluster", "arguments": {"cluster_name": "x"}}', 'done'], a tool_plain registered with requires_approval=True, and capabilities=[HandleDeferredToolCalls(handler=two)]. two(ctx, reqs) asserts isinstance(ctx, RunContext) and returns reqs.build_results(approve_all=True). Assert res.content == 'done' and …

Incomplete Exception Handling in MCP Sampling Model (src/devops_cli/ai/agents/models.py:181, LOW, correctness)

  • Defect: models.py:181-192: try: res = self.session.create_message(...) ... except Exception: pass then return "MCP sampling response generated via client session callback.". Any sampling failure, and the no-session case, returns made-up placeholder text as if it were the model's completion; the caller can't tell it apart from real output. Reproduced: a session whose create_message raises RuntimeError returns that placeholder. Separately, the MCP SDK's ServerSession.create_message is async def (mcp/server/session.py:249) and also expects SamplingMessage objects. Called synchronously it returns a coroutine, which str() turns into the 'completion' (reproduced: '<coroutine object ...>'). The class works only against the MagicMock in tests/test_ai_agent_capabilities.py:761-778. It has no production caller, so the impact is limited to exported API. The blind-handler part also falls under …
  • Skeptic's ruling: I could not refute it. models.py:183-192 (MCPSamplingModel.chat) catches every exception from session.create_message with except Exception: pass. It then returns the fixed string 'MCP sampling response generated via client session callback.', which looks the same as a real completion. That string is also what comes back when no session is attached. I reproduced it: a session whose create_message raises RuntimeError('auth failed') returns the placeholder. Worse, the real MCP SDK …
  • Fix: Preferred, pre-1.0 with no legacy shims: delete MCPSamplingModel from models.py, its re-exports in ai/agents/init.py (:123, :835) and pydantic_agent.py (:125, :612), and step 7 of tests/test_ai_agent_capabilities.py. If it must stay, make it a real adapter: async def chat, map ChatMessage to mcp.types.SamplingMessage(role=..., content=TextContent(type='text', text=...)), and await session.create_message(messages=..., max_tokens=self.max_tokens, system_prompt=self.system_prompt, temperature=self.temperature). Return res.content.text. When the session is missing or the call fails, raise AIClientError (chained with from exc) instead of returning placeholder text.
  • Regression test: If deleted: add an assertion to an API-surface test that not hasattr(devops_cli.ai.agents, 'MCPSamplingModel'). It fails today and passes after the deletion. If kept: test_mcp_sampling_model_raises_on_session_failure uses a session whose create_message raises RuntimeError and asserts that chat() raises AIClientError, where today it returns the placeholder. test_mcp_sampling_model_awaits_async_session uses a session with async def create_message(messages, *, max_tokens, **kw) returning …

SQLite Database Connection Pooling Inefficiency (src/devops_cli/ai/harness/memory.py:344-351, LOW, correctness)

  • Defect: The performance claim is generic, but the per-call connection it points at causes real data loss. database: str = Field(default=":memory:") combined with _get_conn(), which runs sqlite3.connect(self.database, ...) on every read, write, delete, list and search and closes it in finally, means each operation gets a brand-new empty in-memory database. Reproduced against the assess tree: s = SqliteMemoryStore(); s.write('MEMORY.md','remember this') returns status='ok', and then s.read('MEMORY.md').content == '' and s.list_paths() == []. The default constructor is therefore a store that silently discards every write while reporting success. Tests (tests/test_harness.py:1757) only use a file path, so they miss it. The class is exported from devops_cli.ai and has no src caller, hence LOW.
  • Skeptic's ruling: I could not refute this. The original performance claim (no pooling under concurrent load) is generic and not the real defect. The triage's correctness reframing does hold against the assess tree at c279c18. SqliteMemoryStore.database defaults to ":memory:". _get_conn() (src/devops_cli/ai/harness/memory.py, class SqliteMemoryStore) runs sqlite3.connect(self.database, ...) on every read, write, delete, list_paths and search, and each method closes it in finally. With ":memory:", every …
  • Fix: Preferred: drop the ":memory:" default and make database a required file path, validated as not equal to ":memory:". InMemoryStore already covers process-lifetime memory. Also fix the docstring. Alternative: keep ":memory:" but hold a single lazily created sqlite3.Connection per store as a PrivateAttr, guarded by a threading.Lock, reuse it in every method instead of connect/close per call, and add an explicit close(). That also removes the per-call CREATE TABLE.
  • Regression test: tests/test_harness.py: def test_sqlite_memory_store_default_round_trips(): s = SqliteMemoryStore(); assert s.write('MEMORY.md', 'remember this').status == 'ok'; assert s.read('MEMORY.md').content == 'remember this'; assert s.list_paths() == ['MEMORY.md']; assert s.search('remember')[0].path == 'MEMORY.md'. Today the read returns '' and list_paths returns []. If the required-path fix is chosen instead, the test becomes with pytest.raises(ValidationError): SqliteMemoryStore() (today this …

Incomplete Process Group Termination with Potential SIGKILL Escalation Loop (src/devops_cli/ai/harness/shell.py:314-333, LOW, reliability)

  • Defect: The finding's specifics (repeated SIGKILL loop, missing existence check) are wrong, but its title is right: group termination is incomplete. The code os.killpg(os.getpgid(proc.pid), signal.SIGTERM); proc.wait(timeout=3.0) with except ProcessLookupError, PermissionError: pass has two gaps. (1) The group is looked up through the leader's pid. Once the leader has exited and been reaped (check_command's record.process.poll() at line 304 and start_command's active-count poll at line 355 both reap it), getpgid raises ProcessLookupError and the code silently passes. The group's remaining members keep running while stop_command (line 386-387) reports 'terminated'. Reproduced in scratch: a start_new_session child that spawns sleep 300 and exits; after poll(), os.killpg(os.getpgid(pid), SIGTERM) raises ProcessLookupError, pgrep -g <pid> still shows sleep 300, and `os.killpg(pid, …
  • Skeptic's ruling: I could not refute this. As the triage noted, the original finding's specifics (a SIGKILL loop, a missing existence check) are wrong, but its title is right, and both gaps the triage describes reproduce against the real Shell class in the assess tree. Shell._terminate_process_group (src/devops_cli/ai/harness/shell.py) does os.killpg(os.getpgid(proc.pid), SIGTERM); proc.wait(timeout=3.0) and swallows ProcessLookupError/PermissionError. (1) Once the leader has exited and been reaped, …
  • Fix: With start_new_session=True the pgid equals proc.pid for the group's whole lifetime, so signal os.killpg(proc.pid, ...) directly instead of going through getpgid. Send SIGTERM and treat ProcessLookupError as 'group already gone'. Then loop until a deadline, calling proc.poll() to reap the leader so its zombie does not keep the group visible, and probing os.killpg(pgid, 0) until ProcessLookupError. If the deadline passes, send killpg(pgid, SIGKILL) and proc.wait(). Replace the bare except Exception: pass with logging. Make the grace period a parameter so tests stay fast. Best done once in the shared process-group helper that refactor(cli): one process runner owns execution, process groups and dry-run #775 plans and reused here; until then, fix it in place.
  • Regression test: tests/test_harness.py, POSIX-only, using real processes with a short grace period (about 0.5s) so the CI gate stays fast. (a) start_command("sh -c 'sleep 30 & echo $! > <tmp>/pid; exit 0'"); poll check_command until FINISHED; stop_command; then assert that within 2s /proc/<pid> is gone or in state Z. Today the sleep keeps running. (b) start_command("sh -c \"sh -c 'trap \\\"\\\" TERM; echo $$ > <tmp>/pid; exec sleep 30' & wait\""); wait for the pidfile; stop_command; assert the …

Acceptance criteria

  • Each defect above is fixed as its Fix line describes, or the PR says why another fix is better.
  • Each has its Regression test: offline, failing on the base revision and passing after the fix.
  • Removed code goes without shims (pre-1.0), and docs that described it are corrected.
  • uv run devops ci passes.

Key questions

  • One PR for all of these? Yes (proposed). They share a module area and none needs a design decision; each fix is small.

Activity

  1. added this to the v0.2.25 milestone on Oct 2, 2026
  2. added
    type/bug
    scope/ai
    priority/p3-low
    on Oct 2, 2026
  3. dan-petty commented on Oct 2, 2026

    @dan-petty
    OwnerAuthor

    More dead code for this item, found while building #947 (2026-10-02). With CodeMode deleted, nothing uses MountDir or OSAccess (ai/harness/os_access.py); only their exports remain.

    The harness ToolSearch has no production caller either. Only test_tool_search_discovery_and_strategies uses it. Note that devops_cli.ai.agents.ToolSearch is pydantic-ai's class, re-exported eagerly, so the "ToolSearch" entry in the agents package's lazy harness name set is never reached.

    Proposed: delete all three, with their exports and tests, in this item.

  4. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    Closed by #1075, merged into release/v0.2.25.

    GitHub only acts on closing keywords when a pull request merges into the default branch, so this was closed by devops gh issues close-merged.

  5. added a commit that references this issue on Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p3-lowscope/aitype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions