Skip to content

Automate agent-flow (stuck-state) coverage as e2e with a stub model - #1621

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1526-agent-flow-stub-coverage
Jul 11, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1526-agent-flow-stub-coverage

Conversation

@malibio

@malibio malibio commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

Closes #1526

…covery, download terminal states (closes #1526)

Covers the acceptance criteria that existing tests structurally couldn't reach:
- Daemon-level ai-chat tests (real NodeService + SQLite, stub inference engine):
  send->idle with no stuck processing, stuck-processing recovery on watcher
  restart, turn cancellation resetting to idle with no stray token, and
  engine reuse across a second message.
- Model-download terminal-state tests driving perform_download directly
  against a hand-rolled local HTTP server (the real catalog only resolves
  against hardcoded multi-GB HuggingFace URLs, so this is the actual seam):
  successful download + SHA-256 verification, progress events, verification
  failure cleanup, and mid-stream cancellation leaving no partial file.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011wp5Fqs59SBSGYNvejgWqC
@malibio

malibio commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1621 — Automate agent-flow (stuck-state) coverage as e2e with a stub model

Review type: Initial review (no prior reviews found on the PR).

Summary

This PR adds 8 new #[tokio::test] functions across two existing test modules — zero production code is touched (confirmed via diff: both hunks start well inside pre-existing #[cfg(test)] mod tests blocks, +549/-0 total). It closes out issue #1526's first acceptance criterion cleanly: agent-loop / daemon-service-layer coverage with a stub engine that asserts loop termination, engine reuse, and no stuck state. It does not add a new Tauri-layer e2e test file, but investigation shows the issue's second criterion ("an e2e covers ai-chat send→idle and download terminal state") was already satisfied by two pre-existing files on main (ai_chat_send_to_idle_test.rs, model_download_terminal_state_test.rs, merged via PR #1563 / #1610, well before this PR). This PR's new tests are a distinct, complementary layer, not a duplicate of those — see the Requirements Check and the overlap analysis below for the reasoning and the residual gaps that remain.

All 8 new tests pass locally (cargo test --lib in packages/agent and packages/daemon), are fast (~0.3s combined), stable across 5 repeated runs, use no #[ignore], no network access, and no special env vars — they run in the default cargo test / bun run test:all path.

Requirements Check (issue #1526)

  • "Agent-loop tests assert termination, engine reuse, and no stuck state with a stub engine" — Fully met, and at a good seam. send_message_reaches_idle_with_stub_engine (termination + no-stuck-state), second_message_reuses_loaded_engine (engine reuse via replace_engine_if_changed no-op-swap assertion), stuck_processing_node_recovered_on_watcher_restart (startup recovery), turn_cancelled_via_cancel_turn_resets_to_idle (cancellation) all directly assert the named properties, driving the real LocalAgentServiceImpl against a real SqliteStore-backed NodeService, substituting only the inference engine. This is arguably a better seam than agent_loop.rs unit tests alone (mentioned in the issue's reference files) because it exercises the daemon's event-watcher wiring and node-persistence side effects, not just the in-memory loop.
  • [~] "An e2e covers ai-chat send→idle and download terminal state" — Not added by this PR, but already satisfied on main prior to this PR by packages/desktop-app/src-tauri/tests/ai_chat_send_to_idle_test.rs (ai_chat_send_reaches_idle_with_no_stuck_processing_state, merged in PR Test the real Tauri-to-daemon seam end-to-end (ADR-048) #1563/ADR-048 Tauri-seam e2e tests flake under machine load with daemon-health timeouts #1610) and model_download_terminal_state_test.rs (cancel_of_a_download_with_no_stray_downloading_state_left_behind, download_of_an_already_present_model_reaches_ready_with_no_error, same PRs). These go through the actual Tauri command bindings → gRPC → daemon, which is the literal "e2e" layer. See the overlap analysis below — there is a real, currently-unclosed gap that neither the pre-existing e2e tests nor this PR's new tests cover.
  • "Code passes bun run quality:fix; tests pass" — Confirmed via direct cargo test runs (all pass); did not re-run the full bun run quality:fix workspace-wide format pass in this review to avoid reformatting unrelated files, but the diff is idiomatic Rust matching surrounding style and the PR author's baseline comment records a clean frontend baseline.

Step 6 — Overlap / Redundancy Investigation (as requested)

Layer comparison:

Pre-existing (main, PR #1563/#1610) This PR
ai_chat_send_to_idle_test.rs Tauri command (create_node/update_node/get_node) → GrpcClient → real headless daemon subprocess → real ministral-3b-q4km GGUF inference —
local_agent_service.rs tests — In-process LocalAgentServiceImpl (no Tauri, no gRPC, no subprocess) → real SqliteStore/NodeService → stub StubEngine/BlockingEngine
model_download_terminal_state_test.rs Tauri command → GrpcClient → real daemon subprocess → real CompositeModelManager/catalog, but only against an already-downloaded model (no real network fetch) and only a no-op cancel (nothing in flight) —
model_manager.rs tests — Direct call to perform_download (a private free function, not the public ModelManager trait) against a hand-rolled local HTTP server, with a genuinely in-flight download that gets cancelled mid-stream

Findings:

  1. These are not duplicates. The pre-existing Tauri tests are genuine e2e (full stack, real model, real daemon process) but by their own doc comments are deliberately narrow: ai_chat_send_to_idle_test.rs only exercises the happy-path send→idle turn (no stuck-state injection, no cancellation, no engine-reuse assertion — a real model doesn't let you deterministically simulate "engine never emits done" or force a crash-mid-turn). model_download_terminal_state_test.rs explicitly avoids exercising an in-flight cancel or a real network fetch ("too slow/flaky for a test gate"), so it only proves cancelling a non-active download is a clean no-op — it does not prove a genuinely in-flight download's partial file gets cleaned up. This PR's new tests fill exactly those two gaps: BlockingEngine deterministically holds a turn open so turn_cancelled_via_cancel_turn_resets_to_idle can cancel it mid-flight, and spawn_slow_fake_model_server + a background cancel task let perform_download_cancellation_removes_partial_and_terminates cancel a real in-progress transfer and assert the partial file is deleted. Neither pre-existing e2e test can reach these states because they use a real model/network dependency that can't be paused or corrupted on demand.
  2. The pre-existing e2e tests have a coverage hole this PR does not close: ai_chat_send_reaches_idle_with_no_stuck_processing_state silently returns (skips) if the ministral-3b-q4km GGUF file isn't already present under ~/.nodespace/models/ — which is the default state of a fresh CI runner or fresh clone, since nothing in bun install/test-gate.ts provisions it. So in most environments, including a clean CI machine, this is the only test that would have caught issue Automate agent-flow (stuck-state) coverage as e2e with a stub model #1526's literal originally-reported bug (stuck processing via the real Tauri→daemon wiring) and it does not run there. This PR's daemon-service-layer tests are a good substitute for logic coverage but they bypass the Tauri command layer and the gRPC boundary entirely — a regression introduced purely in chat_model_download's Tauri command proxying, or in GrpcClient wiring, would not be caught by either this PR's tests or (on a model-less CI box) the pre-existing e2e test.
  3. Is this PR's contribution valuable or redundant? Valuable and complementary — not redundant. It adds coverage at a lower layer with precise failure injection (stub engine that never completes, hand-rolled server that can be paused/corrupted) that the real-model e2e tests structurally cannot provide, and it runs deterministically and fast in every environment (no model-provisioning dependency). It does not, however, "close" the e2e acceptance criterion in the sense of adding new Tauri-layer test files — that criterion was closed earlier by unrelated PRs. The commit message and PR body's claim "Covers the acceptance criteria that existing tests structurally couldn't reach" is accurate for criterion 1, but slightly overstates coverage of criterion 2: it doesn't add e2e coverage; it explains (correctly) why the existing e2e tests can't reach these specific failure modes, and adds non-e2e coverage for those specific modes instead.
  4. Is "e2e" the right word for the issue title given what actually got built? The issue title says "Automate agent-flow (stuck-state) coverage as e2e with a stub model." Read literally, that already implies a Tauri/daemon e2e run against a stub model — which does not exist anywhere in the codebase (the pre-existing e2e doc comments explicitly say so: "No lightweight stub/test-double model backend exists anywhere in this codebase... Adding one would mean carving a test-only code path into the production model-selection logic — a change to a real inference subsystem's behavior, not a test concern"). This PR's authors reached the same conclusion and instead added the stub at a lower architectural seam (daemon-service and model-manager, in-process) rather than plumbing a stub through the Tauri/gRPC stack. That is a defensible, pragmatic call — a "stub model through full Tauri e2e" would require either a test-only code path in production model-selection (explicitly rejected as bad practice by prior authors) or an actual fake GGUF-compatible inference server reachable by the real ChatInferenceEngine trait's production implementors, which is materially more invasive than what was built. Recommendation: these tests are best characterized as integration tests (real DB, real service composition, fake I/O boundary), not e2e in the Tauri-stack sense. The PR should be understood as satisfying the acceptance criterion's intent (deterministic, fast, stub-driven coverage of the stuck-state/termination/reuse bugs) rather than its literal wording.

Architectural Design & Integrity

No concerns — this PR touches only test modules, uses the existing ChatInferenceEngine/ModelManager trait seams that production code already defines, and does not introduce any new test-only production code paths (unlike the alternative the pre-existing e2e tests explicitly rejected). StubEngine/BlockingEngine are private to the test module and mirror the naming/pattern of agent_loop.rs's existing MockEngine, per the PR's own comment — consistent with established test-double conventions in this codebase.

Functionality & Correctness

  • send_message_reaches_idle_with_stub_engine, second_message_reuses_loaded_engine: correctly rely on maybe_handle_ai_chat_node awaiting run_ai_chat_turn synchronously (verified: not spawned on that path — only recover_stuck_turns's retry is spawned), so no sleep/poll is needed and none is used. Good instinct to avoid unnecessary synchronization here.
  • stuck_processing_node_recovered_on_watcher_restart, turn_cancelled_via_cancel_turn_resets_to_idle: correctly identify that recover_stuck_turns and the cancellation race are the two paths that do need to await an async side effect, and use bounded polling loops (for _ in 0..50 { sleep(20ms) }, i.e., 1s ceiling) rather than a fixed sleep — appropriate given the operations are in-memory/local-DB only (no real inference latency).
  • perform_download_cancellation_removes_partial_and_terminates deliberately delays the cancel signal (150ms) past the first slow-server chunk (100ms delay per 16-byte chunk) to guarantee a genuine mid-stream cancel rather than a pre-cancelled no-op — this is exactly the scenario the pre-existing e2e test explicitly couldn't cover.
  • perform_download_reports_progress_events: the comment on the 250ms progress-report throttle vs. 260ms simulated chunk delay is a bit tight (a 10ms margin), but observed 5/5 stable locally, and this margin is inherent to the throttle logic in perform_download, not something the test can improve without also slowing itself down further.

Security

No production code changed. The two hand-rolled fake HTTP servers:

  • Bind to 127.0.0.1:0 (loopback-only, OS-assigned ephemeral port) — no external exposure, no port-collision risk since the OS picks a free port.
  • Do not parse the incoming request at all (try_read into a discarded buffer) — acceptable for a test-only, same-process, same-test-body server that only the test itself ever connects to; not a general-purpose HTTP mock, and not marketed as one.
  • Detached listener tasks (tokio::spawn with an unbounded loop { accept }) are never explicitly joined/shut down, but since they're scoped to the test binary's process lifetime and only ever accept one connection from the same test, this is standard practice for this kind of throwaway test fixture and matches patterns used elsewhere in Rust test suites. Nit-level only.

Maintainability & Readability

Strong. Both new test blocks are prefaced with clear "why this seam, not that one" doc comments explaining exactly why perform_download/local_agent_service.rs's in-process seam was chosen over the real network/GRPC path — this mirrors the excellent doc-comment style already established in the pre-existing e2e test files, and will make it easy for a future reader to understand why there appear to be two layers of coverage for "download terminal state" rather than assuming duplication. Naming (StubEngine, BlockingEngine, spawn_fake_model_server, spawn_slow_fake_model_server) is descriptive and self-documenting. Assertions carry clear failure messages tied to the specific acceptance-criterion language ("turn must terminate, never stuck processing", "no lingering turn token after completion").

Nit: The comment block starting at model_manager.rs:1165 and the one at local_agent_service.rs:1536 both reference the GitHub issue number directly ("Issue #1526") as a section header inside the test module. Per this repo's own documentation standard (no issue/ticket references embedded in code/docs — describe the behavior directly), these should be either removed or reworded to describe the coverage itself (e.g., "-- Stuck-state / termination coverage with a stub engine --") without the issue number. This is a CLAUDE.md-documented convention for docs, and while it's slightly ambiguous whether it extends to inline test-section comments (vs. commit messages, which explicitly may reference issues), the safest reading given "Do not embed GitHub issue numbers in documentation content or code comments" is to drop it here too.

Testing Strategy & Robustness

Excellent test-to-risk ratio for a test-only PR. Each of the 8 new tests targets a distinct, previously-unreachable failure mode (termination, reuse, recovery, cancellation, checksum success, checksum failure, progress reporting, cancel-with-cleanup) rather than re-asserting the same path repeatedly. Confirmed via direct execution: all pass, ~0.3s combined, no flakiness across 5 repeated runs, no #[ignore], no external network/model dependency — meaning (unlike the pre-existing e2e tests) these will actually execute on every CI run and every contributor's machine without silent skips.

Performance & Scalability

Not applicable — test-only change, and the tests themselves are fast (sub-second), so no negative impact on CI wall-clock time.

Dependencies & Documentation

No new third-party dependencies — tokio::net::TcpListener, reqwest, sha2 were already present in packages/agent/Cargo.toml. No documentation changes needed or made; this repo's docs live in nodespace-docs and this is a test-only change with no architectural/behavioral impact requiring a doc update.

Triage Matrix

[Critical/Blocker]: None.

[Improvement]:

  • Consider filing a small follow-up issue (not blocking this PR) to close the residual gap identified in the overlap investigation: the pre-existing Tauri-layer e2e test for ai-chat send→idle silently skips on any machine/CI runner without the ministral-3b-q4km GGUF file pre-provisioned, meaning the literal originally-reported bug (stuck processing through the real Tauri→gRPC→daemon path) has no guaranteed-to-run e2e coverage today. Neither this PR nor the pre-existing tests close that gap; it would need either a provisioning step in bun install/test-gate.ts or a genuine stub inference backend reachable through the real command/gRPC stack.
  • Nit-adjacent but worth a decision either way: clarify in the PR description or a follow-up comment that this PR intentionally does not add "e2e" tests in the Tauri-stack sense, and instead closes the issue's first bullet plus documents (via doc comments) why the second bullet was already closed by prior work. This avoids future confusion about whether "e2e" in the issue title was satisfied by this PR specifically.

[Nit]:

Recommendation

APPROVE.

This is a clean, well-reasoned, test-only PR that measurably improves coverage of a real, previously-manual-only bug class (stuck processing state, engine-reuse correctness, download cancellation cleanup) at an appropriate and well-justified architectural seam. It does not, by itself, add new Tauri-stack e2e test files, but a full investigation confirms that ask was already satisfied by unrelated prior PRs (#1563/#1610), and this PR's own doc comments correctly and transparently explain why those existing e2e tests can't reach the specific failure modes covered here. The one improvement worth tracking (real e2e coverage silently skipping without a pre-provisioned model) is a pre-existing gap this PR does not worsen, and is better addressed as separate follow-up work rather than a blocker on this PR.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RECOMMENDATION: APPROVE (posted as --comment because GitHub blocks self-approval on your own PR; author and reviewing account are the same here). Test-only PR (+549/-0, both hunks entirely inside pre-existing #[cfg(test)] mod tests blocks, verified via diff). All 8 new tests pass, stable across 5 repeated runs, no #[ignore], no network/model dependency. Confirmed via investigation that this closes acceptance criterion 1 (stub-engine agent-loop coverage: termination, reuse, recovery, cancellation) at a well-justified integration seam; criterion 2 (e2e ai-chat send/idle + download terminal state) was already closed by pre-existing Tauri-layer tests in PR #1563/#1610 — this PR's new tests are complementary (cover failure modes the real-model e2e tests structurally can't reach), not duplicative. One follow-up worth tracking separately: the pre-existing e2e test silently skips without a pre-provisioned GGUF file, so the original bug has no guaranteed-to-run e2e coverage on a clean CI box — not a regression from this PR, but still an open gap. Full review posted as a separate PR comment above.

Per project convention, code comments describe behavior directly rather
than referencing ticket numbers.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011wp5Fqs59SBSGYNvejgWqC
@malibio
malibio merged commit b33239e into main Jul 11, 2026
@malibio
malibio deleted the worktree-issue-1526-agent-flow-stub-coverage branch July 11, 2026 05:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Automate agent-flow (stuck-state) coverage as e2e with a stub model

1 participant