Repository navigation
Closed
Labels
priority/p3-lowPriority P3: a small improvementscope/aiAI review pipeline, personas, prompts, LLM client, or RAGtype/bugType bug: the code does not do what it must
Milestone
Description
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 returnssuper().get_instructions(ctx)(pydantic_ai's async method) when ctx is not None (toolsets/init.py:352-359), and AbstractToolset returnsself._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 doesiter()(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, sorun_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
awaitcannot 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 callscap.handle_deferred(req). A two-argument(ctx, requests)handler, which test_ai_agent_deferred_tools.py documents and tests only by direct call, therefore getshandler(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 substituteRunContext()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 callscap.handle_deferred(req), so ctx is always None. capabilities.py:517-521 only passes ctx whenlen(sig.parameters) >= 2 and ctx is not None. A(ctx, requests)handler therefore gets called ashandler(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 generichandle_deferred_tool_calls/handle_deferredhooks when their signatures take it). Call it with the loop's ctx at agent.py:701. InHandleDeferredToolCalls.handle_deferred, choose the call by the handler's signature alone: 2+ params ->self.handler(ctx if ctx is not None else RunContext(), requests), elseself.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: passthenreturn "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'sServerSession.create_messageisasync def(mcp/server/session.py:249) and also expects SamplingMessage objects. Called synchronously it returns a coroutine, whichstr()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_messagewithexcept 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 tomcp.types.SamplingMessage(role=..., content=TextContent(type='text', text=...)), andawait session.create_message(messages=..., max_tokens=self.max_tokens, system_prompt=self.system_prompt, temperature=self.temperature). Returnres.content.text. When the session is missing or the call fails, raise AIClientError (chained withfrom 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 withasync 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 runssqlite3.connect(self.database, ...)on every read, write, delete, list and search and closes it infinally, 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 thens.read('MEMORY.md').content == ''ands.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.databasedefaults to ":memory:"._get_conn()(src/devops_cli/ai/harness/memory.py, class SqliteMemoryStore) runssqlite3.connect(self.database, ...)on every read, write, delete, list_paths and search, and each method closes it infinally. With ":memory:", every … - Fix: Preferred: drop the ":memory:" default and make
databasea 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 createdsqlite3.Connectionper 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 becomeswith 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)withexcept ProcessLookupError, PermissionError: passhas two gaps. (1) The group is looked up through the leader's pid. Once the leader has exited and been reaped (check_command'srecord.process.poll()at line 304 and start_command's active-count poll at line 355 both reap it),getpgidraises 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 spawnssleep 300and exits; after poll(),os.killpg(os.getpgid(pid), SIGTERM)raises ProcessLookupError,pgrep -g <pid>still showssleep 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
Shellclass in the assess tree.Shell._terminate_process_group(src/devops_cli/ai/harness/shell.py) doesos.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 throughgetpgid. Send SIGTERM and treat ProcessLookupError as 'group already gone'. Then loop until a deadline, callingproc.poll()to reap the leader so its zombie does not keep the group visible, and probingos.killpg(pgid, 0)until ProcessLookupError. If the deadline passes, sendkillpg(pgid, SIGKILL)andproc.wait(). Replace the bareexcept Exception: passwith 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'"); pollcheck_commanduntil 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 cipasses.
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.
Metadata
Metadata
Assignees
Labels
priority/p3-lowPriority P3: a small improvementscope/aiAI review pipeline, personas, prompts, LLM client, or RAGtype/bugType bug: the code does not do what it must
Type
Projects
- StatusShow more project fieldsDone
Activity
dan-petty commentedon Oct 2, 2026
More dead code for this item, found while building #947 (2026-10-02). With
CodeModedeleted, nothing usesMountDirorOSAccess(ai/harness/os_access.py); only their exports remain.The harness
ToolSearchhas no production caller either. Onlytest_tool_search_discovery_and_strategiesuses it. Note thatdevops_cli.ai.agents.ToolSearchis 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.
fix(ai): toolset instructions and deferred-tool hooks get the run's c…
dan-petty commentedon Oct 3, 2026
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.feat(release): v0.2.25 (#1089)
test(cli): tests wait for a background thread with one generous bound…
feat(release): v0.2.37 (#1720)