Skip to content

C5: Replace the client-side 5s conflict heuristic with the daemon's authoritative OCC version conflict (amends ADR-026) - #1273

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1268-occ-conflict-adjudication
May 30, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1268-occ-conflict-adjudication

Conversation

@malibio

@malibio malibio commented May 30, 2026

Copy link
Copy Markdown
Collaborator

Closes #1268

@malibio

malibio commented May 30, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — C5: Daemon-Authoritative OCC Conflict Adjudication (#1268)

Overall assessment: This is a well-executed, high-value change that closes a meaningful data-loss gap. The core pipeline — daemon embeds current_node in gRPC metadata → Tauri extracts it into CommandError → frontend rolls back and hydrates — is architecturally sound and correctly implemented for the regular-node write path. The dead-code removal is clean and complete. One outstanding issue requires a follow-up, and two findings need attention.


Findings

[Improvement] Task-node OCC conflict path silently loses current_node in v1 of this PR

Files: packages/core/src/services/node_service/schema.rs:168-172, packages/core/src/ops/mod.rs:50-58, packages/daemon/src/services/node_service.rs:633-635

update_task_node in NodeService returns NodeServiceError::VersionConflict { node_id, expected_version, actual_version } (no current_node field on this error type). The conversion From<NodeServiceError> for OpsError sets current_node: None unconditionally. As a result, when a task-node write races, the x-version-conflict header is emitted correctly (good — ops_error_to_status handles it), but current_node is always null.

The frontend task-node OCC catch site (line 1893) correctly falls through to resyncNodeFromServer, so this is not a correctness regression — the rollback and notification still fire, and the node re-hydrates after an extra round-trip. However, this diverges from the PR's stated goal of zero-round-trip hydration for task nodes, and leaves task-node conflicts with a slightly degraded UX (network round-trip visible to user, possible flicker).

The node_ops::update_node path correctly calls node_service.get_node() after a conflict and embeds the result. The same pattern should be applied to update_task_node — either at the NodeService::update_task_node level or in a dedicated ops/task_node_ops.rs layer. Tracking this as a follow-up is acceptable given the fallback is correct, but it should be filed.

The existing Rust unit test error_mapping_version_conflict_returns_aborted exercises the NodeServiceError path (which produces current_node: null), so it correctly validates the header is present but doesn't assert on current_node. That's fine as a test-of-the-test, but a future integration test exercising the real update_task_node RPC would be stronger.

[Improvement] ADR-026 amendment is missing — required acceptance criterion

Acceptance criterion from issue #1268: "ADR-026 amendment authored in nodespace-docs (doc/ branch): daemon-as-adjudicator, deletion of the unbuilt Recovered-Items/diff-merge flow, OT/CRDT deferred, consistency with ADR-027/031."

No doc/* branch exists in nodespace-docs referencing OCC/conflict/1268, and decisions/026-write-flow-conflict-resolution.md still describes "client detects empty SurrealDB result" as the detection model — the architecture this PR replaces. The code change is complete; the documentation contract is not. The ADR amendment is a separate PR in nodespace-docs, but this PR should not be considered fully merged until that PR is linked and merged.

Action required: File the ADR-026 amendment PR in nodespace-docs on a doc/occ-conflict-adjudication branch and cross-link it here before or immediately after merging this PR.

[Improvement] Integration tests rely on real wall-clock time (setTimeout(resolve, 1000))

File: packages/desktop-app/src/tests/services/conflict-notification-integration.test.ts:68,89,122

The three OCC integration tests use a 1-second setTimeout to wait for the debounced persistence path (500ms debounce) to fire and reject. This works and the tests cover the right behavior, but they add ~3 seconds to the test suite unconditionally. The debounce constant (DEBOUNCE_MS = 500) is private, making it impossible to override from tests.

The idiomatic fix is vi.useFakeTimers() + vi.advanceTimersByTimeAsync(600) in the test, combined with ensuring the mockRejectedValueOnce path fires within the fake-clock window. Alternatively, expose a package-internal __testSetDebounce(ms) helper. The current approach is functionally correct but creates slow, flaky-under-load tests.

Nit: Given the 5000ms test timeout and 1000ms wait, there is only a 4x margin. In a slow CI environment this could flake. Consider bumping either the wait or the timeout, or switching to fake timers.


Correctness: Core Pipeline (Verified)

  • Daemon ops_error_to_status: current_node is no longer dropped; JSON is serialized with serde_json::to_string which Unicode-escapes all non-ASCII content, so the ASCII MetadataValue constraint is always satisfied. Header emission is guarded by two nested if let Ok so failures silently degrade to a no-header state — the frontend fallback (resyncNodeFromServer) handles this correctly.
  • Tauri status_to_command_error: The Aborted → VERSION_CONFLICT code mapping is unchanged and correct. conflict_data is only populated for Aborted; the rename_all = "camelCase" attribute correctly serializes conflict_data → conflictData for the TypeScript consumer.
  • isVersionConflict guard: Checks code === 'VERSION_CONFLICT' then conflictData !== null then typeof conflictData.node_id === 'string'. This is necessary and sufficient — the code discriminant is produced exclusively by the Aborted gRPC code which is used only for VersionConflict in the daemon. The guard correctly passes dbError (the raw thrown value), not the Error-wrapped version created for logging.
  • Rollback + hydration ordering: rollbackUpdate fires first (line 1248), then pendingUpdates.delete clears remaining queued ops (line 1266), then notifySubscribers pushes the authoritative node to UI, then conflictNotifications.add fires. Order is correct — the notification arrives after the UI is already in the authoritative state.
  • Dead code removal: conflictWindowMs, setConflictWindow, 'concurrent-edit' branch, detectConflict time-window loop, nodeType special-case, isComputedField → skipConflictDetection auto-set, and explicit skipConflictDetection: false no-op are all removed. grep confirms no remaining references in production code.
  • Aborted exclusivity: Status::aborted/Code::Aborted appears only in the VersionConflict arm of ops_error_to_status in the daemon. No other daemon code uses Aborted, so the Tauri mapping Aborted → VERSION_CONFLICT is bijective and safe.

Security

No new attack surface introduced. The x-version-conflict header payload is the daemon's own serialized node data — it traverses an in-process Unix socket (ADR-033), not a network boundary. serde_json::from_str on the Tauri side rejects malformed JSON gracefully via .ok() chaining.


Nitpicks

  • Nit: packages/core/src/ops/mod.rs:54-58 — the From<NodeServiceError> conversion for VersionConflict unconditionally sets current_node: None. A clarifying comment ("task_node path: current_node fetched separately if needed") would make the design decision explicit rather than appearing accidental.
  • Nit: The Rust test error_mapping_version_conflict_returns_aborted does not assert json["current_node"] is null. Adding assert_eq!(json["current_node"], serde_json::Value::Null) would document the expected shape for the task-node path and make a future regression (e.g., if the field is accidentally omitted) immediately visible.

Acceptance Criteria Status

Criterion Status
Daemon no longer drops current_node; header carries full payload PASS
Tauri command preserves structured payload; old MCP -32005 machinery deleted PASS
Frontend guard matches real gRPC shape PASS
Rollback + hydrate from current_node + notification on conflict PASS (regular nodes); fallback resync for task nodes
conflictWindowMs/setConflictWindow/'concurrent-edit' removed PASS
skipConflictDetection auto-sets and nodeType special-case removed PASS
LWW remains policy; losing edit surfaced via #1231 UI PASS
ADR-026 amendment MISSING — required before/after merge

Verdict: Approve with required follow-up. The code change is correct and safe to merge. File the ADR-026 amendment PR before closing the issue, and track the task-node current_node hydration as a follow-up issue.

malibio pushed a commit that referenced this pull request May 30, 2026
…C test

- `packages/core/src/ops/mod.rs`: add comment to the `current_node: None` in
  `From<NodeServiceError> for OpsError` explaining why it's None for the task-node
  path and pointing to the follow-up issue
- `packages/daemon/src/services/node_service.rs`: extend
  `error_mapping_version_conflict_returns_aborted` to also assert
  `json["current_node"] == null`, documenting the expected shape for the
  task-node / direct-service-call path and guarding against future regressions

Addresses review recommendations from PR #1273.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 30, 2026

Copy link
Copy Markdown
Collaborator Author

Review Recommendations — Addressed

✅ Addressed

🟡 Nitpick: current_node: None in From<NodeServiceError>
Added an explanatory comment to packages/core/src/ops/mod.rs documenting that current_node is intentionally None for the task-node / direct-service-call path, and pointing to the follow-up issue (#1274).

🟢 Nitpick: Assert current_node shape in OCC test
Extended error_mapping_version_conflict_returns_aborted in packages/daemon/src/services/node_service.rs to also assert json["current_node"] == null, documenting the expected shape for the task-node path and guarding against future regressions.

🟡 ADR-026 amendment (required AC)
Filed and opened nodespace-docs#51 on branch doc/amend-adr-026-daemon-occ. The amendment covers:

  • New conflict pipeline documentation
  • Explicit deletion of: client-side 5s heuristic, MCP -32005 code
  • Explicit deferral of: Recovered Items / diff-merge flow, OT/CRDT
  • Cross-links to ADR-027, ADR-031, nodespace-core#1268, nodespace-core#1274

🟡 Task-node current_node hydration follow-up
Filed nodespace-core#1274 tracking the zero-round-trip hydration improvement for task-node OCC conflicts.

⏭️ Skipped

🟢 Integration tests: real wall-clock → fake timers
Intentionally skipped. The vi.spyOn + real 1s wait approach was chosen after vi.useFakeTimers() + vi.mock failed to intercept the MockAdapter singleton used by the store in test mode. Switching to fake timers requires either a more complex vi.spyOn setup with advanceTimersByTimeAsync or refactoring the test to bypass the PersistenceCoordinator debounce entirely. The 3s overhead is within the 5s test timeout and acceptable for this integration path. A future refactor can address this alongside the broader test isolation improvements.


Commits added: 2c110c3e (address review: document task-node gap and strengthen OCC test)

@malibio

malibio commented May 30, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up: #1274 resolved inline

The task-node current_node hydration (#1274) was straightforward enough to implement directly on this branch rather than as a separate PR:

packages/daemon/src/services/node_service.rs — update_task_node RPC handler now explicitly intercepts NodeServiceError::VersionConflict, calls self.node_service.get_node() to fetch the authoritative node, and constructs OpsError::VersionConflict { current_node: Some(...) } before returning — mirroring node_ops::update_node. New integration test update_task_node_version_conflict_embeds_current_node verifies the header carries a non-null current_node with the winning content.

The frontend task-node OCC site already handles current_node hydration correctly (C5 work) — no frontend changes needed.

Commit: 61711df8

Michael Libio and others added 3 commits May 30, 2026 17:29
…tive OCC version conflict (closes #1268)

**Daemon (`packages/daemon/src/services/node_service.rs`)**
- `ops_error_to_status`: stop dropping `current_node` from `OpsError::VersionConflict`; encode
  `{node_id, expected, actual, current_node}` as JSON in the `x-version-conflict` metadata header
  on the `Aborted` gRPC Status so clients can hydrate without a second round-trip
- Strengthen `error_mapping_version_conflict_returns_aborted` to assert the header is present and
  carries the correct payload (previously only checked the code)

**Tauri command (`packages/desktop-app/src-tauri/src/commands/nodes.rs`)**
- `CommandError`: add `conflict_data: Option<serde_json::Value>` field (serialised as `conflictData`)
- `status_to_command_error`: extract the `x-version-conflict` header when the gRPC code is `Aborted`
  and populate `conflict_data`; all other `CommandError` literals updated with `conflict_data: None`

**Frontend types (`packages/desktop-app/src/lib/types/errors.ts`)**
- Delete MCP `-32005`/`MCPError`/`VersionConflictData`/`isVersionConflict` machinery (obsolete since the
  in-process MCP layer was removed)
- Add `VersionConflictData` (gRPC shape: `{node_id, expected, actual, current_node}`) and
  `VersionConflictCommandError` (`code: 'VERSION_CONFLICT'` + `conflictData`)
- Rewrite `isVersionConflict` to match the real `CommandError` shape from the daemon

**Frontend store (`packages/desktop-app/src/lib/services/shared-node-store.svelte.ts`)**
- Both OCC catch sites (regular node + task node) now check `isVersionConflict(dbError)` against the
  new gRPC guard; on match: rollback, hydrate from `conflictData.current_node` (or fallback resync),
  add `conflictNotifications` entry with `'version-mismatch'`
- Delete `conflictWindowMs` field and `setConflictWindow()` method
- Delete time-window heuristic branch (`'concurrent-edit'`) and `nodeType` special-case from
  `detectConflict`; only the authoritative version-mismatch branch remains
- Remove `skipConflictDetection: true` auto-set in `isComputedField` path (no longer needed without
  the heuristic generating false positives)
- Remove explicit `skipConflictDetection: false` no-op at external-update site
- Remove `'concurrent-edit'` from `CONFLICT_MESSAGE` map

**Types (`packages/desktop-app/src/lib/types/update-protocol.ts`,
 `packages/desktop-app/src/lib/stores/conflict-notifications.svelte.ts`)**
- Remove `'concurrent-edit'` from `Conflict.conflictType` and `ConflictNotification.conflictType`
  unions; `'version-mismatch'` and `'deleted-node'` remain

**Tests**
- `errors.test.ts`: rewritten for gRPC guard; old MCP tests replaced with `isVersionConflict` tests
  covering the new `{ code: 'VERSION_CONFLICT', conflictData }` shape
- `conflict-notification-integration.test.ts`: replaced time-window heuristic tests with OCC
  integration tests that mock `backendAdapter.updateNode` to reject with `VERSION_CONFLICT`; assert
  rollback, hydration from `current_node`, notification emission, and rollback metric increment
- `conflict-notifications.test.ts`: `'concurrent-edit'` → `'version-mismatch'` throughout
- `shared-node-store.test.ts` / `shared-node-store-extended.test.ts`: remove `setConflictWindow`
  calls, replace heuristic-dependent tests with plain LWW / no-false-positive assertions

Co-Authored-By: Claude <[email protected]>
…C test

- `packages/core/src/ops/mod.rs`: add comment to the `current_node: None` in
  `From<NodeServiceError> for OpsError` explaining why it's None for the task-node
  path and pointing to the follow-up issue
- `packages/daemon/src/services/node_service.rs`: extend
  `error_mapping_version_conflict_returns_aborted` to also assert
  `json["current_node"] == null`, documenting the expected shape for the
  task-node / direct-service-call path and guarding against future regressions

Addresses review recommendations from PR #1273.

Co-Authored-By: Claude <[email protected]>
Before this commit the `update_task_node` RPC handler used a single
`.map_err(service_error_to_status)?` call, which converted
`NodeServiceError::VersionConflict` via `From<NodeServiceError> for OpsError`
with `current_node: None`. The client always had to make a second round-trip
via `resyncNodeFromServer` to recover the authoritative state.

After this commit, the handler intercepts `VersionConflict`, calls
`self.node_service.get_node()` to fetch the current authoritative node, and
constructs an `OpsError::VersionConflict { current_node: Some(...) }` before
calling `ops_error_to_status` — mirroring the pattern used by
`node_ops::update_node` for regular-node conflicts since C5.

The existing `error_mapping_version_conflict_returns_aborted` test now has an
updated comment clarifying it tests the generic `From<NodeServiceError>` path
(where `current_node` is still null), not the task-node handler path.

New async integration test `update_task_node_version_conflict_embeds_current_node`:
- Creates a task node at version 1
- Simulates a concurrent remote write via the core service (version 1 → 2)
- Attempts `UpdateTaskNode` with stale version 1 via the RPC handler
- Asserts Aborted status, `x-version-conflict` header present, and
  `current_node.content` reflects the remote winner

Frontend: the task-node OCC site in `shared-node-store.svelte.ts` already
checks `occError.conflictData.current_node` and hydrates directly when non-null
(implemented in C5) — no frontend changes needed.

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the worktree-issue-1268-occ-conflict-adjudication branch from 61711df to 7b344af Compare May 30, 2026 15:32
@malibio
malibio merged commit 0af7ec3 into main May 30, 2026
@malibio
malibio deleted the worktree-issue-1268-occ-conflict-adjudication branch May 30, 2026 15:32
malibio added a commit that referenced this pull request Jun 22, 2026
…uthoritative OCC version conflict (amends ADR-026) (#1273)

* C5: Replace client-side 5s conflict heuristic with daemon's authoritative OCC version conflict (closes #1268)

**Daemon (`packages/daemon/src/services/node_service.rs`)**
- `ops_error_to_status`: stop dropping `current_node` from `OpsError::VersionConflict`; encode
  `{node_id, expected, actual, current_node}` as JSON in the `x-version-conflict` metadata header
  on the `Aborted` gRPC Status so clients can hydrate without a second round-trip
- Strengthen `error_mapping_version_conflict_returns_aborted` to assert the header is present and
  carries the correct payload (previously only checked the code)

**Tauri command (`packages/desktop-app/src-tauri/src/commands/nodes.rs`)**
- `CommandError`: add `conflict_data: Option<serde_json::Value>` field (serialised as `conflictData`)
- `status_to_command_error`: extract the `x-version-conflict` header when the gRPC code is `Aborted`
  and populate `conflict_data`; all other `CommandError` literals updated with `conflict_data: None`

**Frontend types (`packages/desktop-app/src/lib/types/errors.ts`)**
- Delete MCP `-32005`/`MCPError`/`VersionConflictData`/`isVersionConflict` machinery (obsolete since the
  in-process MCP layer was removed)
- Add `VersionConflictData` (gRPC shape: `{node_id, expected, actual, current_node}`) and
  `VersionConflictCommandError` (`code: 'VERSION_CONFLICT'` + `conflictData`)
- Rewrite `isVersionConflict` to match the real `CommandError` shape from the daemon

**Frontend store (`packages/desktop-app/src/lib/services/shared-node-store.svelte.ts`)**
- Both OCC catch sites (regular node + task node) now check `isVersionConflict(dbError)` against the
  new gRPC guard; on match: rollback, hydrate from `conflictData.current_node` (or fallback resync),
  add `conflictNotifications` entry with `'version-mismatch'`
- Delete `conflictWindowMs` field and `setConflictWindow()` method
- Delete time-window heuristic branch (`'concurrent-edit'`) and `nodeType` special-case from
  `detectConflict`; only the authoritative version-mismatch branch remains
- Remove `skipConflictDetection: true` auto-set in `isComputedField` path (no longer needed without
  the heuristic generating false positives)
- Remove explicit `skipConflictDetection: false` no-op at external-update site
- Remove `'concurrent-edit'` from `CONFLICT_MESSAGE` map

**Types (`packages/desktop-app/src/lib/types/update-protocol.ts`,
 `packages/desktop-app/src/lib/stores/conflict-notifications.svelte.ts`)**
- Remove `'concurrent-edit'` from `Conflict.conflictType` and `ConflictNotification.conflictType`
  unions; `'version-mismatch'` and `'deleted-node'` remain

**Tests**
- `errors.test.ts`: rewritten for gRPC guard; old MCP tests replaced with `isVersionConflict` tests
  covering the new `{ code: 'VERSION_CONFLICT', conflictData }` shape
- `conflict-notification-integration.test.ts`: replaced time-window heuristic tests with OCC
  integration tests that mock `backendAdapter.updateNode` to reject with `VERSION_CONFLICT`; assert
  rollback, hydration from `current_node`, notification emission, and rollback metric increment
- `conflict-notifications.test.ts`: `'concurrent-edit'` → `'version-mismatch'` throughout
- `shared-node-store.test.ts` / `shared-node-store-extended.test.ts`: remove `setConflictWindow`
  calls, replace heuristic-dependent tests with plain LWW / no-false-positive assertions

Co-Authored-By: Claude <[email protected]>

* Address review: document task-node current_node gap and strengthen OCC test

- `packages/core/src/ops/mod.rs`: add comment to the `current_node: None` in
  `From<NodeServiceError> for OpsError` explaining why it's None for the task-node
  path and pointing to the follow-up issue
- `packages/daemon/src/services/node_service.rs`: extend
  `error_mapping_version_conflict_returns_aborted` to also assert
  `json["current_node"] == null`, documenting the expected shape for the
  task-node / direct-service-call path and guarding against future regressions

Addresses review recommendations from PR #1273.

Co-Authored-By: Claude <[email protected]>

* Hydrate task-node OCC conflicts from current_node (closes #1274)

Before this commit the `update_task_node` RPC handler used a single
`.map_err(service_error_to_status)?` call, which converted
`NodeServiceError::VersionConflict` via `From<NodeServiceError> for OpsError`
with `current_node: None`. The client always had to make a second round-trip
via `resyncNodeFromServer` to recover the authoritative state.

After this commit, the handler intercepts `VersionConflict`, calls
`self.node_service.get_node()` to fetch the current authoritative node, and
constructs an `OpsError::VersionConflict { current_node: Some(...) }` before
calling `ops_error_to_status` — mirroring the pattern used by
`node_ops::update_node` for regular-node conflicts since C5.

The existing `error_mapping_version_conflict_returns_aborted` test now has an
updated comment clarifying it tests the generic `From<NodeServiceError>` path
(where `current_node` is still null), not the task-node handler path.

New async integration test `update_task_node_version_conflict_embeds_current_node`:
- Creates a task node at version 1
- Simulates a concurrent remote write via the core service (version 1 → 2)
- Attempts `UpdateTaskNode` with stale version 1 via the RPC handler
- Asserts Aborted status, `x-version-conflict` header present, and
  `current_node.content` reflects the remote winner

Frontend: the task-node OCC site in `shared-node-store.svelte.ts` already
checks `occError.conflictData.current_node` and hydrates directly when non-null
(implemented in C5) — no frontend changes needed.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
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.

C5: Replace the client-side 5s conflict heuristic with the daemon's authoritative OCC version conflict (amends ADR-026)

1 participant