Skip to content

Send OCC conflict payloads in the flattened wire shape (closes #1960) - #1971

Merged
malibio merged 6 commits into
mainfrom
issue-1960-aichat-occ-stuck
Aug 4, 2026
Merged

malibio merged 6 commits into
mainfrom
issue-1960-aichat-occ-stuck

Conversation

@malibio

@malibio malibio commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Problem

An ai-chat turn could complete end-to-end — daemon logs a clean turn, the reply is correctly persisted, sqlite confirms the final state — while the viewer hung forever on the typing indicator and Stop button.

Root cause

Both VersionConflict sites embedded current_node as serde_json::to_value(&node) — the raw storage shape, where type-specific fields live under properties[<type>]. Every other read and write returns the flattened shape produced by node_to_typed_value (the documented single flattening authority), and the frontend hydrates current_node straight into its store.

So an ai-chat OCC conflict left the store holding:

{"properties":{"ai-chat":{"status":"idle","messages":[...]}}}   // no top-level status/messages

The viewer derives isProcessing from node.status and renders from node.messages. Both were undefined, so it was stranded with nothing to render — even though the daemon had already written the reply and set status back to idle.

This was verified with a failing test before the fix; the payload above is the literal assertion output.

Notably the resyncNodeFromServer fallback was always correct (it goes through backendAdapter.getNode, which returns the flat shape). Only the embedded-current_node path was broken — and that's the path actually taken, which is why the bug was reliable rather than intermittent.

Changes

  • Flatten current_node via node_to_typed_value at both conflict sites: the generic path in core/src/ops/node_ops.rs and the task-node path in daemon/src/services/node_service.rs.
  • Normalize the conflict payload in SharedNodeStore before hydrating, at both OCC sites, so this sync-boundary node gets the same typed-field promotion a database-sourced broadcast already gets via setNode.
  • Fix the ai-chat write retry loops. They ran for attempt in 0..5 but retried only if attempt == 0, so a second lost race returned an error and dropped the turn's terminal write — genuinely stranding the node in processing with no reply. Also replaces an unreachable!() that was reachable on budget exhaustion.

The Tauri IPC layer forwards the conflict payload verbatim as opaque JSON, so the flattening propagates to the frontend with no IPC changes.

Tests

  • update_node_version_conflict_embeds_flattened_current_node (daemon) — pins the flattened wire shape. Written first and confirmed failing against the old code.
  • ai-chat-occ-conflict-regression.test.ts (frontend, 3 cases) — an OCC conflict during an active turn must leave the viewer out of the processing state with the reply visible and the version tracking the winner. The nested-payload case was confirmed to fail without the store fix (expected undefined to be defined — the exact stranding condition).
  • ai_chat_write_retry_budget_spans_all_attempts (daemon) — pins the retry arithmetic. Documented in-test why the read/write interleaving isn't reachable without adding a seam to production code, so this pins the budget rather than pretending to reproduce the race.

Verification

bun run test:coverage: clean main 179 files / 4286 tests → this branch 180 / 4289, exit 0. Full pre-push gate (frontend + skill + Rust + e2e) passed. quality:fix clean.

Two timing-based tests (mcp-integration avgUpdateTime > 0, architecture-benchmarks 25 ms threshold) failed on earlier gate runs while the machine was loaded by concurrent builds, and pass on a quiet machine on both main and this branch. They assert on performance.now() deltas over trivial in-memory work and touch no OCC code.

Acceptance criteria

  • Reproduce the version-conflict race reliably — reproduced deterministically as a test rather than by hand.
  • The UI never remains stuck showing "processing" once the node's persisted state has moved past it.
  • Regression test covering an OCC conflict during an active ai-chat turn resolving to the correct final UI state.

Note on the issue's fix directions: (1) is unnecessary — current_node is fetched fresh at conflict time; it was the shape, not the timing, that was wrong. (3) is not needed for this bug, and the frontend must keep writing status: 'processing' since that write is exactly what the daemon triggers on.

🤖 Generated with Claude Code

https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv

malibio and others added 2 commits August 4, 2026 22:18
An ai-chat turn could complete and persist correctly while the viewer hung
forever on the typing indicator and Stop button.

Root cause: both VersionConflict sites embedded current_node as
serde_json::to_value(&node) — the raw storage shape, where type-specific
fields sit under properties[<type>]. Every other read/write returns the
flattened shape produced by node_to_typed_value, and the frontend hydrates
current_node straight into its store. So an ai-chat conflict left the store
holding a node with no top-level status and no messages. The viewer derives
isProcessing from node.status and renders from node.messages, so it was
stranded with nothing to show even though the daemon had already written the
reply and set status back to idle.

- Flatten current_node via node_to_typed_value at both conflict sites
  (core node_ops generic path, daemon task-node path).
- Normalize the conflict payload in SharedNodeStore before hydrating, so this
  sync-boundary node gets the same typed-field promotion a broadcast gets.
- Fix the ai-chat write retry loops: they ran 0..5 but retried only when
  attempt == 0, so a second lost race dropped the turn's terminal write and
  genuinely stranded the node in processing. Also replaces an unreachable!()
  that was reachable on budget exhaustion.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv
clippy::assertions-on-constants — the comparison was evaluated at compile
time and asserted nothing. The retry arithmetic below it is the real check.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv
@malibio

malibio commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1971

Review Type: Initial Review (no prior reviews or comments on this PR)

Scope: full diff origin/main...HEAD, 2 commits, 5 files (+387/−13).


Summary

This is a genuinely good bug fix and a net positive. The diagnosis is correct and I verified it independently rather than taking it on faith: node_to_typed_value is the single flattening authority (packages/nodespace-types/src/convert.rs:34), every successful read/write path goes through it, and both VersionConflict sites were the only two places that bypassed it with a raw serde_json::to_value(&node). For an ai-chat node that difference is exactly status/messages at the top level vs. buried under properties["ai-chat"], and ai-chat-node-viewer.svelte:88 reads node?.status === 'processing' — so the stranding mechanism described in the PR body is real and precisely located.

The change is atomic (one cohesive purpose), small, adds no dependencies, adds no lint suppressions, no any, no #[allow(dead_code)], no new .md files, no issue numbers in new code comments. It fixes the bug at the boundary where the contract is defined rather than papering over it in the viewer, and the belt-and-braces store-side normalization is defensible because it makes the OCC path consistent with the database-broadcast path (setNode at shared-node-store.svelte.ts:1504 already does exactly this).

Verification I performed:

Check Result
ai-chat-occ-conflict-regression.test.ts (3 tests) ✅ pass (3.0s)
update_node_version_conflict_embeds_flattened_current_node ✅ pass
ai_chat_write_retry_budget_spans_all_attempts ✅ pass
Mutation check: revert store fix, re-run frontend suite ✅ test 2 fails (expected undefined to be defined) — the fix is load-bearing and the test is sensitive
Adjacent OCC suites (persistence-serial-writer-regression, errors, shared-node-store-coverage) ✅ 100 passed, no regressions
Wire-contract blast radius sweep for current_node consumers ✅ no broken consumer found (details below)

Requirements Check — issue #1960

  • ✅ Reproduce the version-conflict race reliably. Reproduced deterministically as a test rather than by hand. I confirm the reproduction is real, not tautological: reverting only the store fix makes the nested-payload case fail with the exact stranding assertion.
  • ✅ The UI never remains stuck showing "processing" once the node's persisted state has moved past it. Verified for the path the issue's console capture actually exercises. See finding 🟡-3 for one residual path this doesn't close.
  • ✅ Regression test covering an OCC conflict during an active ai-chat turn resolving to the correct final UI state. Present at three levels (daemon wire shape, store hydration, user-visible notification/rollback).

📝 The PR's dismissal of the issue's fix directions is correct and worth recording: direction (1) is unnecessary — current_node is fetched fresh at conflict time (node_ops.rs:285, node_service.rs:912 both call get_node after the conflict, so it can never be a mid-turn snapshot as the issue speculated); the issue's hypothesis about timing was wrong and the shape was the real cause. Direction (3) would break the trigger the daemon watches for.


Answers to the specific scrutiny requests

Wire-contract blast radius — independently verified, no other broken consumers. I swept every current_node / conflictData reference across .rs, .ts, .svelte. Producers: exactly two set it non-null (node_ops.rs:285, node_service.rs:912) — both fixed. The other two (ops/mod.rs:63, collection_ops.rs:371) set current_node: None and route to the resyncNodeFromServer fallback, which was always shape-correct. Consumers: the two SharedNodeStore OCC blocks (fixed), types/errors.ts:95 (structural type only, no field access), and version-conflict-modal.svelte, which does read currentNode.properties and currentNode[field] — but it has zero import sites; it is dead code and this PR does not make it more dead. The Tauri IPC layer forwards the payload as opaque JSON, confirmed. No action needed.

normalizeNodeData idempotency — safe, and consistent-by-design. nodeToAiChatNode (ai-chat-node.ts:95) reads only top-level fields with ??/Array.isArray defaults; applied to an already-flat node it is a pure identity-plus-defaults operation. nodeToTaskNode is the same pattern. The properties drop you flagged is not a problem, and is correct: setNode's database path already routes every daemon broadcast through the same converter, so an ai-chat node in the store has never carried properties. Making the OCC path match removes an inconsistency rather than introducing one. I checked ai-chat-node-viewer.svelte for .properties reads on the node — the only hit is a stale doc comment (see 🟢-1).

Version bookkeeping — correct. version is a top-level field on Node and is copied verbatim by both converters, so currentNode.version ?? 1 after normalization is the winning server version. The first frontend test asserts chat?.version === 4 end-to-end, which pins this. The next write reads from this.versions, so it will carry the right OCC version.

Retry loop — arithmetic correct, but the error predicate is now a real problem. attempt + 1 < MAX_WRITE_ATTEMPTS is right: attempts 0..3 retry, attempt 4 returns Err. Replacing unreachable!() with an Err is strictly better — that unreachable!() was reachable and would have panicked the turn task. But see 🟡-1: the predicate matches any error, not just VersionConflict, and widening the retry from 1 to 4 amplifies that pre-existing flaw. And your instinct about let _ = at the call sites is right — see 🟡-2.

Test quality — three of five tests are load-bearing, two are weak. The daemon flattening test and frontend test 2 are the real ones. Frontend tests 1 and 3 pass with the store fix reverted (they cover the daemon fix's effect only, which is fine — they're not redundant, just less sensitive than the comment implies). On ai_chat_write_retry_budget_spans_all_attempts: your in-test documentation of the limitation is the right instinct and I'd rather have it than not. But it is a tautology — it re-derives the loop guard from MAX_WRITE_ATTEMPTS and asserts arithmetic about the copy, so it cannot fail if production drifts. See 🟢-2 for the cheap seam you asked about.

Missed cases — one residual path. handle.promise.catch swallowing VERSION_CONFLICT is correct by construction (the write closure already hydrated before rethrowing). resyncNodeFromServer was always correct. shouldSkipStaleAiChatUpdate is the one worth a second look — see 🟡-3.


Findings

🟡 Important

🟡-1: The retry now swallows non-conflict errors four times instead of once
📁 packages/daemon/src/services/local_agent_service.rs:755-762 and :832-839

Err(e) if attempt + 1 < MAX_WRITE_ATTEMPTS => {
    tracing::debug!(node_id, error = %e, attempt,
        "version conflict writing ai-chat status, retrying");
}

The guard matches any Err, but the log message and the doc comment both assert it is a version conflict. A non-conflict failure — update_node rejecting a malformed NodeUpdate, a DB write error, a serialization failure — now burns the full budget in a tight loop with no backoff, logs four misleading "version conflict" lines at debug, and finally surfaces a generic "after 5 attempts" message that has erased the actual cause. Before this PR the same flaw existed but cost one wasted attempt; widening the budget makes it four, and turns a fast deterministic failure into a hot retry loop.

The fix is cheap and makes the code say what it means:

Err(NodeServiceError::VersionConflict { .. }) if attempt + 1 < MAX_WRITE_ATTEMPTS => { ... }
Err(e) => return Err(e.to_string()),

Engineering principle: retry only what is retryable. A retry loop that cannot distinguish a transient race from a deterministic fault converts a clear error into a slow, mislabelled one — and discards the diagnostic that would have explained it. This matters more than usual here because the exhaustion message is the only thing a future debugger of this exact hang will see.

🟡-2: Two of the four call sites still discard the terminal-write failure with let _ =
📁 packages/daemon/src/services/local_agent_service.rs:492, :502, :705

The PR correctly identifies that dropping the terminal write strands the node in processing. But three call sites still do let _ = self.write_ai_chat_status(&node_id, "idle", None).await;. Line 650 (the main path) was already handled — it logs on Err. Lines 492 and 502 are the "history empty" and "last message is not from user" bail-outs, and 705 is the stuck-node recovery sweep. Each of those runs specifically when the node is (or may be) in processing and the whole point of the call is to get it out — so a silent failure there reproduces the exact user-visible symptom this PR exists to fix, with no log line to find it by.

Line 705 is the most consequential: it is the recovery path for nodes already stuck, so a silent failure means the recovery sweep quietly fails to recover and the node stays stuck across restarts.

Recommend matching line 650's treatment at all three:

if let Err(e) = self.write_ai_chat_status(&node_id, "idle", None).await {
    tracing::warn!(node_id, error = %e, "failed to reset ai-chat status to idle");
}

Engineering principle: an error you deliberately ignore should be ignored explicitly and observably. let _ = on an operation whose failure is the bug under repair removes the only evidence that the repair didn't take.

🟡-3: shouldSkipStaleAiChatUpdate can drop the recovery broadcast after an OCC hydration
📁 packages/desktop-app/src/lib/services/remote-update-policy.ts:112-120, interacting with shared-node-store.svelte.ts:1422

You flagged this and the concern is well-founded, though narrower than feared. The guard compares message counts and treats a missing/non-array messages as 0:

const incomingCount = Array.isArray(incomingMsgs) ? incomingMsgs.length : 0;

After this PR, an OCC-hydrated ai-chat node always has a real messages array (that is the fix), so the hydrated node is no longer a count-0 node — good. The residual risk is the inverse direction: the OCC path calls nodesSet directly at line 1422, bypassing setNode and therefore bypassing this guard entirely. So an OCC hydration can install a node whose message count is lower than what a later-arriving broadcast carries, or vice versa, with no staleness arbitration between the two writers. This is pre-existing and this PR strictly improves it (the hydrated node is now comparable at all, where before it was always count-0 and would have caused the guard to skip every subsequent broadcast for that node). I would not block on it, but it is the most likely place a residual stranding report comes from, and worth a line in the issue or a follow-up rather than being silently considered closed.

Engineering principle: two writers into the same store with different staleness policies is a latent divergence. The OCC path taking a different door than setNode means any invariant setNode enforces is not enforced for conflict hydration.

🟢 Suggestions

🟢-1: Stale doc comment now contradicts the code it documents
📁 packages/desktop-app/src/lib/components/viewers/ai-chat-node-viewer.svelte:20

- Typing indicator driven by `node.properties['ai-chat']['status'] === 'processing'`.

The code at line 88 is node?.status === 'processing', and this PR is precisely about that distinction. A comment describing the nested shape sitting above the code this bug was caused by confusing nested-vs-flat is actively hazardous to the next reader. One-line fix; would take it in this PR since it is the same conceptual change.

Engineering principle: comments must explain intent, and a comment that contradicts the code is worse than none — here it documents the exact misconception that produced the bug.

🟢-2: The retry test is a tautology — a two-line seam would make it real
📁 packages/daemon/src/services/local_agent_service.rs:2669-2700

You documented the limitation honestly, which I credit. But the test re-derives the loop guard from the same constant the loop uses, so it passes for any consistent pair of expressions and cannot detect drift in the production loop. Its stated purpose ("the retry condition must stay tied to MAX_WRITE_ATTEMPTS") is exactly what it cannot check.

You asked whether there's a better approach you missed. There is one that needs no production seam and no interleaving: write_ai_chat_status reads the node, then writes at the version it read. Call it with an intentionally raced node_service — or more simply, spawn the helper and perform a competing update_node from the test in a loop — and you can observe that it eventually succeeds rather than erroring on the second conflict. Even simpler and fully deterministic: assert the exhaustion contract instead of the arithmetic. Wrap the loop's body in a small private async fn try_write_once(&self, ...) -> Result<(), NodeServiceError> and test that write_ai_chat_status calls it up to MAX_WRITE_ATTEMPTS times against a stub that always conflicts, and returns the exhaustion Err rather than panicking. That last property — no panic on exhaustion — is the one this PR actually changed and the one currently untested.

If none of those is worth the cost right now, that's a defensible call for a bug-fix PR; but then I'd shrink the test to what it honestly covers rather than framing it as guarding the regression.

Engineering principle: a test that restates the implementation cannot fail when the implementation changes. Prefer asserting observable behavior at a boundary over re-deriving internal arithmetic.

🟢-3: The new test asserts 'active' where production writes 'idle'
📁 packages/desktop-app/src/tests/services/ai-chat-occ-conflict-regression.test.ts:103

The fixture uses status: 'active' for the completed turn, but the daemon writes the literal "idle" (local_agent_service.rs:492/502/650/705/820), and 'idle' is not a member of the AiChatStatus union (ai-chat-node.ts:3: 'active' | 'processing' | 'archived'). This is a pre-existing contract drift, not something this PR introduces, and it is harmless for the bug itself — the viewer only checks === 'processing', so any other value clears the indicator.

But it means the regression test's happy path exercises a value production never sends. Using 'idle' would make the test mirror reality and would also surface the union drift to whoever reads it. Worth either fixing the union to include 'idle' or, if 'active' is the intended vocabulary, fixing the daemon — but that is a separate change; here I'd just note it.

Engineering principle: fixtures should use the values the system actually produces. A test green on a value the producer never emits gives false confidence about the contract.

🟢-4: Nit — three fixed 1000 ms sleeps
📁 packages/desktop-app/src/tests/services/ai-chat-occ-conflict-regression.test.ts:139, :171, :200

await new Promise((resolve) => setTimeout(resolve, 1000)) costs 3 s of wall-clock on every run and is a fixed guess at the debounce/settle window rather than a condition. vi.waitFor(() => expect(readChat(store)?.status).toBe('idle')) would be both faster and more robust to timing drift on a loaded machine — which this repo has already been bitten by (the flaky timing tests noted in the PR body). Low priority given the suite is already 3 s, but it's the kind of thing that compounds.


Recommendation

APPROVE

The core fix is correct, correctly located, and correctly tested at the level that matters. I verified the diagnosis, the blast radius, the idempotency of normalizeNodeData on flat payloads, the version bookkeeping, and the sensitivity of the key regression test independently — all hold up. None of the findings above is a correctness defect in what this PR changes.

🟡-1 and 🟡-2 are worth folding in before merge — both are a few lines, both are in code this PR already touches, and both concern the same failure mode the PR is fixing (a silently dropped terminal write stranding the node). 🟡-3 is a pre-existing seam I'd rather see tracked than assumed closed. The 🟢 items are optional.


🤖 Automated pragmatic code review

@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.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

Reviewer findings on PR #1971, all in code this PR already touches and all
concerning the same failure mode it fixes — a silently dropped terminal write
stranding an ai-chat node in 'processing'.

- Retry loops matched any Err, not just VersionConflict. Widening the budget
  from 1 to 4 turned a deterministic fault into a hot retry loop that logged
  four misleading 'version conflict' lines and buried the real cause. Now
  matches NodeServiceError::VersionConflict explicitly.
- Three call sites still discarded the idle-status write with 'let _ ='. The
  recovery sweep was the worst: a silent failure there means an already-stuck
  node quietly fails to recover across restarts, with nothing in the log. All
  three now log on failure, matching the main path.
- Viewer doc comment described the nested properties['ai-chat'].status shape
  while the code reads node.status — it documented the exact misconception
  that caused this bug. Also corrected the claim that the frontend only
  appends user messages; it writes the triggering status too.
- Added 'idle' to AiChatStatus. The daemon writes it on every turn completion
  but it was absent from the union, so the regression fixture had to assert a
  value production never sends.

Replaced the retry-budget test. The original restated the loop's arithmetic
and so could not fail if production drifted. It now drives the non-retryable
branch and asserts the helpers return Err rather than panicking — the
unreachable!() this PR removed was genuinely reachable.

Not addressed: the OCC path calls nodesSet directly, bypassing
shouldSkipStaleAiChatUpdate. Pre-existing, and this PR strictly improves it
(a hydrated node now has a real messages array instead of always counting 0).
Tracked on the issue rather than folded into this fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv
@malibio

malibio commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — commit ee96c609

Thanks — 🟡-1 and 🟡-2 were both real and both landed. Summary of the disposition:

✅ Addressed

🟡-1 — retry only lost races. Correct catch, and the severity was understated in my own commit message: widening the budget from 1 to 4 turned a deterministic fault into a hot retry loop. Now matches NodeServiceError::VersionConflict { .. } explicitly; anything else returns immediately with its real cause intact. Dropped error = %e from the retry log too, since that arm is now conflicts-only.

🟡-2 — surface the dropped status writes. All three let _ = sites now log on failure, matching line 650. Your ranking of line 705 as the most consequential is right: it's the recovery sweep for already-stuck nodes, so a silent failure there meant recovery quietly didn't happen and the node stayed stuck across restarts with nothing to find it by.

🟢-1 — stale doc comment. Fixed, plus the line above it: "Frontend only writes updateNode to append user messages" was also false — handleSend writes status: 'processing', and that write is the daemon's trigger. Both lines now describe what the code does.

🟢-3 — fixture asserted a value production never sends. Rather than cast around it, I added 'idle' to AiChatStatus. The daemon writes it on every turn completion and it was simply missing from the union; the union had only two consumers and Rust types the field as a plain String. That removed the need for an as unknown as cast in the test.

🟢-2 — retry test was a tautology. You were right that it couldn't fail if production drifted. Worth reporting how this went: I first replaced it with a test asserting a non-conflict error fails fast — and it passed against the old code too, because the retry count isn't observable from the return value (both paths return the same error string). So I discarded that one rather than ship a second test that can't detect the regression. The replacement asserts the one property that is observable and that this PR actually changed: the helpers return Err instead of panicking, since the unreachable!() I removed was genuinely reachable. Making the retry count assertable needs the production seam you described, which I judged out of scope for a bug fix — flagging it as a real remaining gap rather than claiming it's covered.

⏭️ Not addressed

🟡-3 — OCC path bypasses shouldSkipStaleAiChatUpdate. Agreed on the analysis and agreed it shouldn't block. It's pre-existing, and this PR strictly improves it: a hydrated node now carries a real messages array instead of always counting 0, which is what previously made the guard skip every subsequent broadcast for that node. Two writers with different staleness policies is a genuine latent divergence, so I've written it up on #1960 rather than letting it close silently with the issue.

🟢-4 — three fixed 1s sleeps. Kept. vi.waitFor would be faster, but the 1s sleep is the established pattern in conflict-notification-integration.test.ts for exactly this path, and it also lets the handle.promise.catch microtask chain run — which a condition-poll on store state wouldn't guarantee. Consistency with the neighbouring OCC suite is worth more here than 3s of wall clock.

Verification

  • Full frontend suite: 180 files / 4289 tests, all passing.
  • cargo test -p nodespace-daemon --lib: 119 passed.
  • Re-ran the mutation check after these edits — reverting the store normalization still fails test 2 with expected undefined to be defined, so the key regression test is still load-bearing.
  • Full pre-push gate green. quality:fix clean.

@malibio

malibio commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1971 (Re-Review)

Review Type: Re-Review
Scope: git diff 9ffb1444..HEAD — one commit, ee96c609, 4 files.


Previous Review Summary

Count Detail
Previous recommendations 7 🟡-1, 🟡-2, 🟡-3, 🟢-1 … 🟢-4
Addressed 4 🟡-1 ✅, 🟡-2 ✅, 🟢-1 ✅, 🟢-3 ✅ (with a caveat)
Partially addressed 1 🟢-2 — the tautology is gone, but the replacement does not cover what it claims
Consciously not addressed 2 🟡-3 (tracked on the issue — accepted), 🟢-4 (kept for suite consistency — accepted)
New issues 2 🟡-4 (replacement test is not mutation-sensitive), 🟢-5 (AiChatStatus widening leaves a three-way vocabulary split)

Verification performed

Check Result
cargo test -p nodespace-daemon --lib ✅ 119 passed
ai-chat-occ-conflict-regression.test.ts + ai-chat-node.test.ts ✅ 14 passed
bunx eslint + svelte-check (2197 files) ✅ 0 errors, 0 warnings
cargo clippy -p nodespace-daemon --lib --all-targets ✅ clean
Mutation check: restore unreachable!() in both loops, re-run the new test ❌ test still passes — see 🟡-4
NodeServiceError variant sweep for a wrapped/converted VersionConflict ✅ no such path — see below
Every AiChatStatus / ai-chat status consumer swept (TS, Svelte, Rust) ⚠️ one dead Rust validator disagrees — see 🟢-5
Both checkouts clean after my probing ✅ no stray edits left behind

Item-by-item

✅ 🟡-1 — retry only lost races. Correct, and the key risk is not present.

📁 packages/daemon/src/services/local_agent_service.rs:773, :852

I specifically hunted for the failure mode you were asked to check — a real conflict arriving wrapped in some other variant, which would have silently stopped retrying genuine races. It does not exist here, and I traced it end to end rather than assuming:

  • LocalAgentServiceInner.node_service is Arc<NodeService> (:134) — the core service, not the daemon's gRPC wrapper. So update_node returns Result<Node, NodeServiceError> unwrapped; there is no From/Into between the call and the match.
  • The OpsError::VersionConflict re-wrappings (ops/mod.rs:52, collection_ops.rs:363, node_ops.rs:291) and ActionError::VersionConflict (playbook/actions.rs:647) all sit on paths this code never takes.
  • NodeServiceError has no other variant that can carry an OCC loss. I read the whole enum: the only conflict-shaped producer is update_with_version_check_returning_node returning None, which crud.rs:1030-1039 disambiguates into exactly two outcomes — NodeNotFound when the row is gone, VersionConflict when the version moved.

That disambiguation is worth stating explicitly because it is the one behavioural edge the narrowing introduces: a concurrent DELETE now returns immediately instead of retrying four times. That is the correct new behaviour — retrying a write against a deleted node is pure waste and the old code burned the whole budget on it — but it is a real semantic change, and it is the reason the replacement test does not test what it says (🟡-4).

Dropping error = %e from the retry log is right now that the arm is conflicts-only: attempt and the message carry everything the arm can say, and the non-conflict path keeps its real cause via Err(e) => return Err(e.to_string()).

✅ 🟡-2 — all three sites, matching the established style.

📁 :492, :504, :712 (main path at :654 was already correct)

Verified all three, and they match :654's treatment — if let Err(e) = … { tracing::warn!(node_id, error = %e, …) }. :712 correctly gets a distinct message ("failed to reset stuck ai-chat node to idle during recovery") so the recovery sweep is greppable separately from the two bail-outs, which is the right call given it is the path that matters most. There are no remaining let _ = self.write_ai_chat_status sites — I checked.

Nit: the comment added above :712 explains why the logging matters rather than why the code does what it does; it is really review-response prose promoted into a comment. It is accurate and harmless, so I would not remove it, but the tracing::warn! message already carries that meaning.

✅ 🟢-1 — doc comment fixed, and the second correction is genuinely load-bearing.

📁 packages/desktop-app/src/lib/components/viewers/ai-chat-node-viewer.svelte:15-24

I verified the new claim rather than accepting it: handleSend does write status: 'processing' (:272, with the comment at :254 confirming it is deliberately the daemon's trigger). So the old line "Frontend only writes updateNode to append user messages" was false in a way that mattered — it hid the trigger mechanism from anyone reading the architecture note. Good catch to fix both lines rather than only the one flagged.

⚠️ 🟢-3 — fixture now mirrors production, but the PR comment overstates part of this.

The fixture change ('active' → 'idle') is right and the union genuinely was missing a value the daemon writes on every single turn.

Two corrections to the disposition comment, for the record:

  1. "That removed the need for an as unknown as cast in the test" — it did not. All three casts present at 9ffb1444 are still present at ee96c609, unchanged: :45, :61, :164. They are AiChatNode↔Node structural casts and are unavoidable given the two types do not overlap nominally; nothing about the union widening touched them. No action needed on the code — just don't carry that claim forward into the merge commit.
  2. "the union had only two consumers" — accurate for AiChatStatus the type (ai-chat-node.ts:9, :82), but the values have more consumers than that, and one of them disagrees. See 🟢-5.

⏭️ 🟡-3 / 🟢-4 — both dispositions accepted.

🟡-3 tracked on the issue is the right outcome for a pre-existing seam this PR strictly improves. On 🟢-4, the reasoning you gave — the 1 s sleep also lets the handle.promise.catch microtask chain drain, which a store-state condition poll would not guarantee — is a better argument than the one I made for changing it. Withdrawn.


Findings

🟡 Important

🟡-4: The replacement test passes with unreachable!() restored — it does not cover the property it documents
📁 packages/daemon/src/services/local_agent_service.rs:2691-2727

You were right to discard the first replacement attempt for exactly this reason, and right to disclose it. Unfortunately the second one has the same defect, and I confirmed it empirically rather than by reading: I restored unreachable!("retry loop always returns") in place of both exhaustion Err(format!(…)) arms and ran the test.

test services::local_agent_service::tests::ai_chat_write_failure_returns_err_instead_of_panicking ... ok

It passes against the code it claims to guard against. The mechanism is the NodeNotFound disambiguation from 🟡-1: deleting the node makes the get_node at the top of the loop body return None, so write_ai_chat_status returns at

.ok_or_else(|| format!("node {node_id} not found"))?;   // :747

on attempt 0. Control never enters the match on update_node, never reaches attempt 4, and never reaches the exhaustion arm at all. The test proves that a missing node yields Err — which was already true before this PR — not that exhaustion yields Err instead of a panic.

The doc comment above it therefore asserts something false: "This drives the non-retryable branch (the node no longer exists) and asserts the failure is returned rather than unwound." It drives an early-return branch, not the non-retryable match branch, and the panic it names is not reachable from this test.

This is not a correctness defect in the production change — removing unreachable!() is still strictly correct and I am not disputing that. It is a claim-vs-coverage mismatch, and it is the second attempt at the same target, which is the signal worth acting on: the exhaustion path is not reachable from outside without a seam, and two tests have now been written that appear to reach it and do not.

Two honest ways out, either acceptable:

  • Shrink the claim to the coverage. Rename to something like ai_chat_writes_on_a_missing_node_return_err and rewrite the doc comment to describe the early-return path — which, post-🟡-1, is now a newly meaningful property: a concurrent delete returns immediately rather than burning four attempts. That is a real behavioural consequence of this commit and is genuinely worth pinning.
  • Or reach the arm properly with the seam I described last round (try_write_once + an always-conflicting stub) and keep the current name.

What I would not ship is the current pairing, where the name and doc comment promise the panic-on-exhaustion guarantee and the assertions cannot detect its loss. A test that names a regression it cannot catch is worse than no test, because the next person to touch the retry loop will read the name and believe they are covered.

Engineering principle: a test's name and doc comment are a contract with the next reader. Mutation-sensitivity is the only thing that makes that contract true — if reintroducing the bug leaves the suite green, the test documents a belief, not a guarantee.

🟢 Suggestions

🟢-5: Widening AiChatStatus is safe at runtime, but it leaves three components disagreeing about the vocabulary
📁 packages/desktop-app/src/lib/types/ai-chat-node.ts:9

The change itself is safe, and I verified that rather than assuming — this is the "does any exhaustive switch now behave differently" question:

  • There is no exhaustive switch/match on AiChatStatus anywhere. Every consumer is a single equality test against 'processing' (ai-chat-node-viewer.svelte:88) or a ?? 'active' default (ai-chat-node.ts:111 and three viewer write sites). Widening a union that is only ever compared for one member cannot change behaviour, and svelte-check over 2197 files is clean.
  • The Rust side types the field as a plain String (ai_chat_node.rs:147) and defaults absent to "" (:189-193), so it accepts idle and always did. No disagreement there.

The residual issue is that the codebase now carries three different answers to "what are the legal ai-chat status values", and this commit changes one of them without reconciling the other two:

  1. AiChatStatus (TS) — active | idle | processing | archived
  2. AiChatNodeBehavior::validate (packages/core/src/behaviors/mod.rs:1769-1782) — rejects anything that is not active | archived, with the message "Invalid status '{}': must be one of active, archived"
  3. ai_chat_node.rs:12-17's own module doc — still says the frontend declares active | processing | archived, which this commit just made stale

(2) is the interesting one. It does not fire today, and I checked why rather than assuming: it reads top-level node.properties.get("status"), while every daemon write splices into properties["ai-chat"]["status"] (local_agent_service.rs:759, :843). The key it guards is simply never present on a persisted ai-chat node, so the validator is dead. That is pre-existing and not caused by this PR — processing has been failing that same check on paper since long before #1960. But it means there is a core validator that would reject the daemon's own most common status writes the moment anyone "fixes" it to look under the namespace, which is a live trap for whoever next touches ai-chat validation.

Also worth noting for whoever reconciles this: 'active' is not purely "never ran a turn" as the new doc comment says. The PTY path uses it as a lifecycle marker meaning "session live", paired with 'archived' written by capture backfill (ai-chat-pty-session.svelte:56-60, :229; capture_service.rs:121). So active/archived is a PTY session-lifecycle axis and idle/processing is a native turn-state axis, and they are being stored in one field. That is the actual ambiguity — not active vs idle per se, but two orthogonal state machines sharing a key.

I would not expand this PR to fix that; the widening is the correct minimal step and the bug fix should not grow a state-model refactor. Two cheap things worth doing here, though:

Engineering principle: single source of truth. A value set defined in three places drifts, and the copy that drifts silently — here, a validator whose key never exists — is the one that bites, because nothing fails until someone corrects it.


Recommendation

APPROVE

The two Important findings from the previous round were both real and both landed correctly. 🟡-1 in particular I re-derived independently rather than accepting: the narrowing does not stop retrying real conflicts, because NodeService is called directly with no error conversion in between and NodeServiceError has exactly one conflict-carrying variant. The one behavioural change it does introduce — a concurrent delete now fails fast instead of retrying — is an improvement.

Nothing in this commit is a correctness regression, the full daemon suite, the frontend regression suite, clippy and svelte-check are all green, and the core fix remains load-bearing.

🟡-4 is worth fixing before merge, but it is a test-honesty fix, not a code fix, and the cheapest form is a rename plus a corrected doc comment — the early-return property it actually pins became newly meaningful in this very commit, so the test is salvageable as-is with accurate framing. I am flagging it at 🟡 rather than 🟢 only because this is the second test written against the same unreachable target, and the current name would tell a future maintainer they are protected when they are not.

🟢-5 needs no action in this PR beyond the optional one-line stale-doc fix; the substance belongs on #1960 next to 🟡-3.


🤖 Automated pragmatic code review (re-review)

@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.

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

Re-review caught that the test passed with unreachable!() restored — it was
the third attempt at the same unreachable target and, like the two before it,
did not test what its name claimed.

Mechanism: deleting the node makes the get_node at the top of the loop body
return None, so both helpers return at their opening ok_or_else on attempt 0.
The match on update_node is never entered and the exhaustion arm is never
reached.

Renamed to ai_chat_writes_on_a_missing_node_return_err and rewrote the doc
comment to state the property it genuinely pins — fast failure on a missing
node, which became meaningful in the previous commit since update_node now
disambiguates NodeNotFound from VersionConflict — and to state plainly that
the exhaustion arm remains unpinned by any test.

Also refreshed the ai_chat_node module doc: it claimed the frontend declares
active | processing | archived, which the AiChatStatus change made stale. It
now describes the real situation — a turn-state axis (processing/idle) and a
PTY session-lifecycle axis (active/archived) sharing one key.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv
@malibio

malibio commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed — commit 0cefca17

🟡-4 — you were right, and this was the third miss on the same target

I reproduced it: deleting the node makes the get_node at the top of the loop body return None, so both helpers return at their opening ok_or_else on attempt 0. The match on update_node is never entered and the exhaustion arm is never reached. The test name and doc comment claimed something false.

Worth stating plainly, since it's a pattern rather than a one-off: this is the third test I wrote against the retry-exhaustion arm that did not test it. The first restated the loop's arithmetic; the second asserted fast-failure and passed against the old code because retry count isn't observable from the return value; this one bailed before the loop. I've stopped trying to reach that arm indirectly.

Renamed to ai_chat_writes_on_a_missing_node_return_err, and the doc comment now (a) states the property it genuinely pins — fast failure on a missing node, which became meaningful in ee96c609 since update_node disambiguates NodeNotFound from VersionConflict, exactly as you noted — and (b) says outright that the exhaustion arm remains unpinned by any test. Reaching it needs the production seam; I'd rather leave that visible in the source than paper over it with a fourth attempt.

🟢-5 — stale doc fixed here, the ambiguity tracked

Fixed the ai_chat_node.rs module doc, which my AiChatStatus change had just made stale (it claimed the frontend declares active | processing | archived). It now describes what you identified: a turn-state axis (processing/idle) and a PTY session-lifecycle axis (active/archived) sharing one key.

I did not touch the dead AiChatNodeBehavior::validate — it reads top-level properties["status"] while every daemon write goes to properties["ai-chat"]["status"], so it's unreachable, and "fix the validator" is a different change with its own blast radius. Agreed it's a live trap; it goes on #1960 with the two-axes point.

Correction to my previous comment

You're right and I was wrong: "That removed the need for an as unknown as cast in the test" was inaccurate. Three casts remain at :45, :61, :164 — unavoidable AiChatNode↔Node structural casts, unchanged since 9ffb1444. What the union change removed was a different, fourth cast on the status field specifically, which I'd introduced in that same edit and then eliminated. I overstated it as a general cleanup.

Not addressed (unchanged)

🟡-3 and now the AiChatStatus two-axes ambiguity — both on #1960. 🟢-4 (1s sleeps) — kept for consistency with the neighbouring OCC suite.

Verification

  • cargo test -p nodespace-daemon --lib: 119 passed. nodespace-core --lib: 1133 passed.
  • bun run test:coverage on this branch: 180 files / 4289 tests, exit 0 — versus 179 / 4286 on clean main.
  • Full pre-push gate green; quality:fix clean.

One note on the gate: architecture-benchmarks failed two consecutive push attempts at 25.17ms and 25.97ms against a 25ms threshold. Since this commit changed only a Rust test name and two doc comments, I checked rather than assumed — the identical test:coverage suite passes on both clean main and this branch, and the benchmark only trips inside the gate, which runs cargo build concurrently. It passed on retry. Flagging it because that threshold has very little headroom and will keep costing push attempts.

Closes the residual gap from review: OCC hydration wrote via nodesSet,
bypassing setNode and therefore shouldSkipStaleAiChatUpdate, so conflict
hydration and daemon broadcasts could disagree about which snapshot wins.

Two changes:

- shouldSkipStaleAiChatUpdate now decides staleness by VERSION first, message
  count only as a tiebreak when versions are equal or uncomparable. Count
  alone was never a safe signal: a turn that rewrites history rather than
  appending (a cancelled turn dropping its partial reply) legitimately yields
  a newer snapshot with fewer messages, and count-only comparison discarded it
  permanently. Version is what the daemon actually increments.

- The OCC hydration site runs the same guard before installing current_node.
  In the stale case it now falls through to resyncNodeFromServer instead of
  writing an older snapshot over newer local state.

rollbackUpdate touches only the local version counter, not node.version, so
the stored node still carries its server version when the guard compares —
which is what makes the comparison meaningful at this point in the flow.

Both changes are pinned by mutation-checked tests: reverting the version
branch fails 2 of the new policy tests, and reverting the store guard fails
the new store test with the node left at version 2 instead of 4.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv
@malibio

malibio commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

🟡-3 now fixed in-PR — commit 452d8f24

I'd originally deferred this to #1960. With the context still loaded it turned out to be contained, so it's fixed here rather than left as a follow-up.

The actual defect was broader than "the OCC path skips a guard"

Applying shouldSkipStaleAiChatUpdate at the hydration site alone would have propagated a flawed policy. The guard decided staleness by message count only, and count is not a safe staleness signal: a turn that rewrites history rather than appending — a cancelled turn dropping its partial reply — legitimately produces a newer snapshot with fewer messages. Count-only comparison discards that permanently, stranding the UI on a message list the daemon has already superseded. That is the same class of bug as the one this PR set out to fix.

So two changes:

1. shouldSkipStaleAiChatUpdate is version-first. Version is what the daemon actually increments, so it decides; message count is now only the tiebreak when versions are equal or uncomparable. This also matches what decideRemoteUpdate next door already does.

2. The OCC hydration site runs that same guard before installing current_node, and in the stale case falls through to resyncNodeFromServer instead of writing an older snapshot over newer local state. The two writers into this store now share one policy.

One detail that makes this work: rollbackUpdate resets the local version counter but leaves node.version on the stored node, so the node still carries its server version when the guard compares. I checked that specifically — the comparison would be meaningless otherwise.

Verification

All new tests mutation-checked, since three earlier tests in this PR passed against the bugs they targeted:

  • Revert the version branch → 2 of the new policy tests fail.
  • Revert the store guard → the new store test fails with the node left at version 2 instead of 4.
  • Full frontend suite: 180 files / 4294 tests. Full pre-push gate green; quality:fix clean.

On the gate: this suite is nondeterministic under coverage, independent of this PR

A push attempt failed with Maximum call stack size exceeded in navigation-service.test.ts — a different failure mode from the timing flakes, so I ran it down rather than retrying. navigation-service never touches ai-chat, the policy module, or OCC, and passes standalone and alongside the new tests. Running test:coverage repeatedly:

Run Result
clean main, run 1 pass
clean main, run 2 fail — core-plugins
this branch's parent 0cefca17 fail — core-plugins
this branch 452d8f24, run 1 fail — navigation-service + 2 timing tests
this branch, gate retry pass

The failing test varies per run at every commit including unmodified main, so this is environmental, not a regression. Combined with the architecture-benchmarks 25ms threshold noted earlier, the coverage suite is costing real push attempts and is worth its own issue — I have not opened one, since that is a call about test-infra priorities rather than part of this fix.

Still deferred to #1960

The status two-axes ambiguity (turn state processing/idle vs PTY session lifecycle active/archived) and the dead AiChatNodeBehavior::validate. Deliberately not fixed here — see my next comment for why the validator in particular shouldn't be quietly repaired.

The comment still described the old message-count-only rule. Also records
why version-first is right for this caller specifically: batchSetNodes
receives a tree loaded fresh from the database, so its nodes carry current
server versions — the field the guard now compares on.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv
@malibio

malibio commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Final state before merge — 7505f96a

Two loose ends from 452d8f24 closed before merging, both raised in my own re-review decision rather than by a reviewer:

1. Stale comment at the second call site. batchSetNodes' guard comment still described the old message-count-only rule. Fixed. This was the third stale-comment instance in this PR — the reviewer flagged the first two as actively hazardous, and it's a pattern I should have caught when I changed the function rather than after.

2. The unexamined second caller. 452d8f24 changed shouldSkipStaleAiChatUpdate for both callers, but I had only analyzed the OCC path. Checked now: batchSetNodes receives a tree loaded fresh from the database (doLoadChildrenTree), so its nodes carry current server versions — the exact field the guard now compares on. Version-first is strictly more correct there for the same reason as the OCC path: a legitimately newer snapshot with fewer messages is no longer discarded. The comment now records that reasoning so the next reader doesn't have to re-derive it.

Disclosure on process

My recommendation was a re-review of 452d8f24 — it changed a shared policy function's decision basis and added a control-flow branch to the OCC path. The maintainer elected to merge instead, which is their call. Recording it here so the PR history is accurate: the last commit carrying substantive logic (452d8f24) was not independently reviewed. The two concerns I raised about it are the ones resolved above; the residual risk is whatever a fresh pass would have caught beyond them.

Reviewed and addressed across this PR: initial review (7 findings) → /address-review → re-review (2 new findings) → addressed. Both verdicts were APPROVE.

Final verification

  • Full pre-push gate green on 7505f96a.
  • Frontend: 180 files / 4294 tests. Rust: daemon 119, core 1133.
  • mergeable: MERGEABLE, mergeStateStatus: CLEAN.

Deferred to #1960 with analysis: the status two-axes ambiguity, and the dead NodeBehavior::validate — which is dead across all 29 implementations, not just ai-chat, so "repair the ai-chat validator" is the wrong fix.

@malibio
malibio merged commit a0c7fb6 into main Aug 4, 2026
2 checks passed
@malibio
malibio deleted the issue-1960-aichat-occ-stuck branch August 4, 2026 21:50
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.

1 participant