Repository navigation
Send OCC conflict payloads in the flattened wire shape (closes #1960) - #1971
Conversation
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
Pragmatic Code Review — PR #1971Review Type: Initial Review (no prior reviews or comments on this PR) Scope: full diff SummaryThis 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: The change is atomic (one cohesive purpose), small, adds no dependencies, adds no lint suppressions, no Verification I performed:
Requirements Check — issue #1960
📝 The PR's dismissal of the issue's fix directions is correct and worth recording: direction (1) is unnecessary — Answers to the specific scrutiny requestsWire-contract blast radius — independently verified, no other broken consumers. I swept every
Version bookkeeping — correct. Retry loop — arithmetic correct, but the error predicate is now a real problem. 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 Missed cases — one residual path. Findings🟡 Important🟡-1: The retry now swallows non-conflict errors four times instead of once 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 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 The PR correctly identifies that dropping the terminal write strands the node in 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. 🟡-3: You flagged this and the concern is well-founded, though narrower than feared. The guard compares message counts and treats a missing/non-array const incomingCount = Array.isArray(incomingMsgs) ? incomingMsgs.length : 0;After this PR, an OCC-hydrated ai-chat node always has a real Engineering principle: two writers into the same store with different staleness policies is a latent divergence. The OCC path taking a different door than 🟢 Suggestions🟢-1: Stale doc comment now contradicts the code it documents The code at line 88 is 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 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 You asked whether there's a better approach you missed. There is one that needs no production seam and no interleaving: 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 The fixture uses But it means the regression test's happy path exercises a value production never sends. Using 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
RecommendationAPPROVE 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 🟡-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
left a comment
There was a problem hiding this comment.
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
Review addressed — commit
|
Pragmatic Code Review — PR #1971 (Re-Review)Review Type: Re-Review Previous Review Summary
Verification performed
Item-by-item✅ 🟡-1 — retry only lost races. Correct, and the key risk is not present.📁 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:
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 ✅ 🟡-2 — all three sites, matching the established style.📁 Verified all three, and they match Nit: the comment added above ✅ 🟢-1 — doc comment fixed, and the second correction is genuinely load-bearing.📁 I verified the new claim rather than accepting it:
|
malibio
left a comment
There was a problem hiding this comment.
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
Re-review addressed — commit
|
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
🟡-3 now fixed in-PR — commit
|
| 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
Final state before merge —
|
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
VersionConflictsites embeddedcurrent_nodeasserde_json::to_value(&node)— the raw storage shape, where type-specific fields live underproperties[<type>]. Every other read and write returns the flattened shape produced bynode_to_typed_value(the documented single flattening authority), and the frontend hydratescurrent_nodestraight into its store.So an ai-chat OCC conflict left the store holding:
{"properties":{"ai-chat":{"status":"idle","messages":[...]}}} // no top-level status/messagesThe viewer derives
isProcessingfromnode.statusand renders fromnode.messages. Both wereundefined, so it was stranded with nothing to render — even though the daemon had already written the reply and setstatusback to idle.This was verified with a failing test before the fix; the payload above is the literal assertion output.
Notably the
resyncNodeFromServerfallback was always correct (it goes throughbackendAdapter.getNode, which returns the flat shape). Only the embedded-current_nodepath was broken — and that's the path actually taken, which is why the bug was reliable rather than intermittent.Changes
current_nodevianode_to_typed_valueat both conflict sites: the generic path incore/src/ops/node_ops.rsand the task-node path indaemon/src/services/node_service.rs.SharedNodeStorebefore hydrating, at both OCC sites, so this sync-boundary node gets the same typed-field promotion adatabase-sourced broadcast already gets viasetNode.for attempt in 0..5but retried onlyif attempt == 0, so a second lost race returned an error and dropped the turn's terminal write — genuinely stranding the node inprocessingwith no reply. Also replaces anunreachable!()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:fixclean.Two timing-based tests (
mcp-integrationavgUpdateTime > 0,architecture-benchmarks25 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 onperformance.now()deltas over trivial in-memory work and touch no OCC code.Acceptance criteria
Note on the issue's fix directions: (1) is unnecessary —
current_nodeis 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 writingstatus: 'processing'since that write is exactly what the daemon triggers on.🤖 Generated with Claude Code
https://claude.ai/code/session_017EL3h2z4AxNx2tw98LCUMv