From 6d502d8ff57a9226a3d81675588d518c80ad69e5 Mon Sep 17 00:00:00 2001 From: slhx agent Date: Mon, 13 Jul 2026 21:08:51 +0200 Subject: [PATCH] test(sync): prove deterministic reconciliation req: sync/022 --- PLAN.md | 4 +- examples/kanban/static/sync.js | 44 +++++++++++- examples/kanban/templates/sync_shell.heml | 2 +- examples/kanban/tests/browser_e2e.rs | 84 +++++++++++++++++++++++ 4 files changed, 130 insertions(+), 4 deletions(-) diff --git a/PLAN.md b/PLAN.md index 5391333..03dc397 100644 --- a/PLAN.md +++ b/PLAN.md @@ -42,11 +42,11 @@ encryption, retention, backup, and deployment policy remain host concerns. ## Slice 4 — authoritative reconnect and convergence - [ ] **User value:** offline and concurrent work reconnects without duplicate mutation, silent loss, stale authorization, or ambiguous conflict. -- **State:** In progress — one app-owned `move_card` server command validates a durable client command id, applies the authoritative canonical column once, returns the same acknowledgement for an identical retry, rejects id reuse with a different payload, assigns one server sequence, and redelivers that canonical acknowledgement after a real EventSource disconnect/reconnect. Canonical acknowledgements and the next sequence are durably stored in a strict versioned JSON envelope using fsync plus atomic replacement; startup refuses malformed/unknown state, rebuilds the canonical board, and preserves idempotency and event replay across a real process restart. A dedicated opt-in sync route reads one pending IndexedDB command, retries transient failures with capped exponential backoff and randomized jitter, exposes online/offline state plus an accessible manual retry after exhaustion, waits for canonical acknowledgement on the reconnecting transport, and only then removes the durable command; later retry converges without a new local mutation. Canonical payload conflicts are not retried and remain durable with a visible reason. If requested history predates retained events, the stream emits a typed snapshot-required event and the client loads a versioned canonical snapshot. One deterministic rebase rule treats `reorder_card` as converged only when the canonical snapshot already places that card in `done`; it then atomically stores the snapshot/cursor and removes the satisfied command. If a later canonical command instead places the same card in `doing`, the rebase is explicitly `conflicted`, retains the local command and last committed snapshot/cursor unchanged, and exposes the divergent canonical column/reason. Two same-origin tabs coordinate an app-owned expiring IndexedDB lease so only one uploads; the standby exposes its role without issuing a request, and after the leader closes it takes over, receives one canonical acknowledgement/sequence, and removes the queue once. Each activation serializes uploads with one in flight, processes at most two acknowledged commands, exposes the retained durable count when backpressured, and resumes the next bounded run only through the visible retry action. A mixed queue commits and removes its accepted prefix exactly once, then stops on the first permanent rejection with the typed server cause visible, the rejected command plus untouched suffix durable, and blind retry disabled. The IndexedDB v1-to-v2 command migration transactionally adds the explicit target column, records a typed migration receipt, preserves causal order and interaction intent through an interrupted upload, and later drains in the original order. Every command POST now derives its principal, permission, and tenant from the current same-origin session before idempotency lookup or mutation; authenticated mode accepts only app-configured opaque session tokens and fails closed when signed out. Direct cross-tenant and stale-permission command attempts receive typed authorization denial before mutation. IndexedDB v3 additionally indexes every command and lease by the current server-derived tenant/principal partition: switched users enumerate zero foreign commands, issue no foreign replay, cannot export foreign payloads, and the owning account can export then resume its intact queue. Signed-out context lookup fails closed before opening the queue. Canonical snapshots and replayable acknowledgement history now derive the same current session, filter card state and events by tenant before serialization, use tenant-local sequence cursors, and reject signed-out reads. A divergent snapshot enables explicit “Use canonical state” and “Keep local change” actions. Canonical resolution removes only the conflicted head before resuming the ordered suffix. Keep-local resolution derives one deterministic retry identity from the original command and snapshot, keeps the original head and suffix durable through permanent rejection and bounded transport failure, re-enables the explicit decision after rejection, and removes the head only after canonical acceptance before resuming the suffix. The accessible sync shell exposes bounded redacted diagnostics for queue count/age bucket, cursor, acknowledgement-latency bucket, conflicts, and rejections; durable commands carry a migration-safe enqueue timestamp, while ids, payload fields, actor/session values, cookies, and exact timing stay out of diagnostics. The optional public `hemx-sync` crate now provides the strict versioned flat scalar `FlatPatch` schema and `SyncEffect::send_patch`; a generated client handler emits it in the ordinary `EffectBatch`, the runtime assigns one opaque interaction identity to both operation/idempotency fields, persists it before any offline request, then uploads and removes it only after a matching acknowledgement. Broader domain-specific merge choices remain. +- **State:** In progress — one app-owned `move_card` server command validates a durable client command id, applies the authoritative canonical column once, returns the same acknowledgement for an identical retry, rejects id reuse with a different payload, assigns one server sequence, and redelivers that canonical acknowledgement after a real EventSource disconnect/reconnect. Canonical acknowledgements and the next sequence are durably stored in a strict versioned JSON envelope using fsync plus atomic replacement; startup refuses malformed/unknown state, rebuilds the canonical board, and preserves idempotency and event replay across a real process restart. A dedicated opt-in sync route reads one pending IndexedDB command, retries transient failures with capped exponential backoff and randomized jitter, exposes online/offline state plus an accessible manual retry after exhaustion, waits for canonical acknowledgement on the reconnecting transport, and only then removes the durable command; later retry converges without a new local mutation. Canonical payload conflicts are not retried and remain durable with a visible reason. If requested history predates retained events, the stream emits a typed snapshot-required event and the client loads a versioned canonical snapshot. One deterministic rebase rule treats `reorder_card` as converged only when the canonical snapshot already places that card in `done`; it then atomically stores the snapshot/cursor and removes the satisfied command. If a later canonical command instead places the same card in `doing`, the rebase is explicitly `conflicted`, retains the local command and last committed snapshot/cursor unchanged, and exposes the divergent canonical column/reason. Two same-origin tabs coordinate an app-owned expiring IndexedDB lease so only one uploads; the standby exposes its role without issuing a request, and after the leader closes it takes over, receives one canonical acknowledgement/sequence, and removes the queue once. Each activation serializes uploads with one in flight, processes at most two acknowledged commands, exposes the retained durable count when backpressured, and resumes the next bounded run only through the visible retry action. A mixed queue commits and removes its accepted prefix exactly once, then stops on the first permanent rejection with the typed server cause visible, the rejected command plus untouched suffix durable, and blind retry disabled. The IndexedDB v1-to-v2 command migration transactionally adds the explicit target column, records a typed migration receipt, preserves causal order and interaction intent through an interrupted upload, and later drains in the original order. Every command POST now derives its principal, permission, and tenant from the current same-origin session before idempotency lookup or mutation; authenticated mode accepts only app-configured opaque session tokens and fails closed when signed out. Direct cross-tenant and stale-permission command attempts receive typed authorization denial before mutation. IndexedDB v3 additionally indexes every command and lease by the current server-derived tenant/principal partition: switched users enumerate zero foreign commands, issue no foreign replay, cannot export foreign payloads, and the owning account can export then resume its intact queue. Signed-out context lookup fails closed before opening the queue. Canonical snapshots and replayable acknowledgement history now derive the same current session, filter card state and events by tenant before serialization, use tenant-local sequence cursors, and reject signed-out reads. A divergent snapshot enables explicit “Use canonical state” and “Keep local change” actions. Canonical resolution removes only the conflicted head before resuming the ordered suffix. Keep-local resolution derives one deterministic retry identity from the original command and snapshot, keeps the original head and suffix durable through permanent rejection and bounded transport failure, re-enables the explicit decision after rejection, and removes the head only after canonical acceptance before resuming the suffix. The accessible sync shell exposes bounded redacted diagnostics for queue count/age bucket, cursor, acknowledgement-latency bucket, conflicts, and rejections; durable commands carry a migration-safe enqueue timestamp, while ids, payload fields, actor/session values, cookies, and exact timing stay out of diagnostics. The optional public `hemx-sync` crate now provides the strict versioned flat scalar `FlatPatch` schema and `SyncEffect::send_patch`; a generated client handler emits it in the ordinary `EffectBatch`, the runtime assigns one opaque interaction identity to both operation/idempotency fields, persists it before any offline request, then uploads and removes it only after a matching acknowledgement. Missing-history recovery now calls one named, exported `server-authoritative-v1` reconciliation function with the canonical snapshot, full ordered command sequence, and observed server results; it validates result cursors, returns a mutation-free deterministic decision/retained-count record, and leaves custom merge or CRDT policy as an explicit replacement module rather than an implicit mode. Broader domain-specific merge choices remain. - **Build:** materialize `hemx-sync` over an integration transport with idempotent server command processing, snapshot/change cursor, durable acknowledgements, bounded ordered replay, current auth checks, rejection/conflict results, canonical replacement, reconnect jitter/backoff, multi-tab coordination, and redacted diagnostics. - **Refusals:** no default CRDT, transport in core, cached enqueue-time permission, unbounded queue, or silent last-write-wins policy. - **Requirements:** `sync/001-023`, `operations/001-005`, `security/002-005`, `performance/004-005`. -- **Proof:** `cargo test -p hemx-wasm --test browser flat_patch_persists_offline_then_uploads_with_same_operation_identity -- --exact` proves `sync/002` and `sync/003` through generated real WASM: `SyncEffect::send_patch` travels beside ordinary DOM effects, the strict flat scalar schema is accepted, the offline interaction performs zero patch requests while remaining durable, and reconnect uploads with identical opaque operation/idempotency identity before matching acknowledgement removes it. `cargo test -p hemx-wasm --test browser kanban_public_api_offline_sync_journey_converges_without_duplicate_replay -- --exact` proves `sync/023` through the public generated client handler and real WASM: offline durable mutation, unavailable-origin reload projection, reconnect upload, canonical convergence, duplicate idempotency without a second event, conflicting duplicate rejection, invalid-command rejection, and an empty local queue. `cargo test -p hemx-kanban-example --test browser_e2e idempotent_server_command_is_acknowledged_after_reconnect -- --exact` proves duplicate POST delivery yields one identical canonical acknowledgement/sequence, conflicting id reuse is rejected, EventSource reconnects after a server-closed first stream, the acknowledgement is delivered once with its sequence as event id, and a page reload shows the authoritative card in the canonical column. `cargo test -p hemx-kanban-example --test browser_e2e pending_local_command_uploads_with_bounded_retry_and_is_removed_on_ack -- --exact` proves automatic platform-store upload, one explicit transient failure, bounded exponential backoff plus jitter, reconnect acknowledgement, pending-before-ack ordering, acknowledged removal, canonical board convergence, and non-retried 409 rejection remaining durable with a visible reason. `cargo test -p hemx-kanban-example --test browser_e2e canonical_acknowledgement_survives_server_restart -- --exact` proves the versioned store is materialized before success, a real process restart reloads the same idempotent acknowledgement/sequence, EventSource replays it by id, and canonical board state is rebuilt. `cargo test -p hemx-kanban-example --test browser_e2e exhausted_offline_retries_keep_command_until_later_reconnect -- --exact` proves three bounded retries exhaust into visible offline/manual-recovery state while the command remains durable, then a later retry acknowledges/removes it and converges canonically. `cargo test -p hemx-kanban-example --test browser_e2e missing_history_rebase_and_user_conflict_resolution_preserve_suffix -- --exact` proves retained-history gap detection, typed/versioned snapshot fallback, deterministic already-canonical convergence, atomic snapshot/cursor commit, then a divergent canonical update producing explicit conflict with a two-command queue; the user’s canonical-state action removes only the conflicted head, retains and resumes the suffix, and reaches canonical convergence with an empty queue. `cargo test -p hemx-kanban-example --test browser_e2e keep_local_retry_preserves_conflicted_command_and_suffix_order -- --exact` proves the keep-local action derives one resolution identity; a permanent rejection preserves order and re-enables the choice; three later transport failures still preserve the original conflicted head plus suffix and expose manual recovery; final acceptance removes only the head and converges the untouched suffix without duplication or loss. `cargo test -p hemx-kanban-example --test browser_e2e redacted_sync_diagnostics_are_bounded_and_leak_no_sensitive_material -- --exact` proves a 15-second-old queue is bucketed rather than timestamped, cursor and acknowledgement latency advance after recovery, diagnostics stay under a fixed small readout, and command id/payload/actor/session/cookie material never reaches the diagnostics surface; the conflict and keep-local tests additionally assert conflict/rejection counters at their actual failure boundaries. `cargo test -p hemx-kanban-example --test browser_e2e two_tabs_coordinate_single_uploader_and_takeover_without_duplicate_application -- --exact` proves one retry-exhausted leader/one explicit standby, zero follower upload before takeover, lease takeover after the leader closes, one canonical sequence/event, one queue removal, and one board application. `cargo test -p hemx-kanban-example --test browser_e2e upload_backpressure_keeps_pending_work_visible_and_recoverable -- --exact` proves one in-flight upload, a two-acknowledgement activation limit, one retained durable command with visible recovery state, and explicit retry draining the final command without loss. `cargo test -p hemx-kanban-example --test browser_e2e mixed_queue_removes_accepted_prefix_and_retains_rejected_tail -- --exact` proves an accepted prefix is canonically applied and removed once before a permanent rejection stops processing, exposes its typed HTTP/server cause, disables blind retry, and leaves both the rejected command and untouched suffix durable. `cargo test -p hemx-kanban-example --test browser_e2e schema_upgrade_preserves_queued_order_and_local_intent -- --exact` proves a three-command v1 queue migrates atomically to the explicit-target v2 schema, remains byte-for-intent ordered after interrupted upload, then receives canonical sequences 1–3 in original order and drains without loss. `cargo test -p hemx-kanban-example --test browser_e2e account_partition_hides_replay_and_export_until_owner_returns -- --exact` proves a beta editor and alpha viewer enumerate zero commands and issue no replay for an alpha owner queue, signed-out startup cannot open a partition, no foreign id/export surface leaks, and only the returning alpha owner can export the intact command then resume it exactly once. `cargo test -p hemx-kanban-example --test browser_e2e canonical_snapshot_and_history_are_tenant_scoped -- --exact` proves alpha and beta sessions receive only their own canonical cards and acknowledgement events with independent sequence 1 cursors, while signed-out snapshot/history reads receive 401 and expose no stream. Per-requirement audit: `sync/002`, `sync/003`, and `sync/023` are browser-proven, but Slice 4 cannot close. `sync/022` has no strict proof that identical snapshots, command sequences, and server results produce identical reconciliation output. All other `sync/*` rows have concrete browser proof citations. The next slice must prove deterministic reconciliation for identical snapshots, command sequences, and server results. +- **Proof:** `cargo test -p hemx-wasm --test browser flat_patch_persists_offline_then_uploads_with_same_operation_identity -- --exact` proves `sync/002` and `sync/003` through generated real WASM: `SyncEffect::send_patch` travels beside ordinary DOM effects, the strict flat scalar schema is accepted, the offline interaction performs zero patch requests while remaining durable, and reconnect uploads with identical opaque operation/idempotency identity before matching acknowledgement removes it. `cargo test -p hemx-wasm --test browser kanban_public_api_offline_sync_journey_converges_without_duplicate_replay -- --exact` proves `sync/023` through the public generated client handler and real WASM: offline durable mutation, unavailable-origin reload projection, reconnect upload, canonical convergence, duplicate idempotency without a second event, conflicting duplicate rejection, invalid-command rejection, and an empty local queue. `cargo test -p hemx-kanban-example --test browser_e2e idempotent_server_command_is_acknowledged_after_reconnect -- --exact` proves duplicate POST delivery yields one identical canonical acknowledgement/sequence, conflicting id reuse is rejected, EventSource reconnects after a server-closed first stream, the acknowledgement is delivered once with its sequence as event id, and a page reload shows the authoritative card in the canonical column. `cargo test -p hemx-kanban-example --test browser_e2e pending_local_command_uploads_with_bounded_retry_and_is_removed_on_ack -- --exact` proves automatic platform-store upload, one explicit transient failure, bounded exponential backoff plus jitter, reconnect acknowledgement, pending-before-ack ordering, acknowledged removal, canonical board convergence, and non-retried 409 rejection remaining durable with a visible reason. `cargo test -p hemx-kanban-example --test browser_e2e canonical_acknowledgement_survives_server_restart -- --exact` proves the versioned store is materialized before success, a real process restart reloads the same idempotent acknowledgement/sequence, EventSource replays it by id, and canonical board state is rebuilt. `cargo test -p hemx-kanban-example --test browser_e2e exhausted_offline_retries_keep_command_until_later_reconnect -- --exact` proves three bounded retries exhaust into visible offline/manual-recovery state while the command remains durable, then a later retry acknowledges/removes it and converges canonically. `cargo test -p hemx-kanban-example --test browser_e2e missing_history_rebase_and_user_conflict_resolution_preserve_suffix -- --exact` proves retained-history gap detection, typed/versioned snapshot fallback, deterministic already-canonical convergence, atomic snapshot/cursor commit, then a divergent canonical update producing explicit conflict with a two-command queue; the user’s canonical-state action removes only the conflicted head, retains and resumes the suffix, and reaches canonical convergence with an empty queue. `cargo test -p hemx-kanban-example --test browser_e2e keep_local_retry_preserves_conflicted_command_and_suffix_order -- --exact` proves the keep-local action derives one resolution identity; a permanent rejection preserves order and re-enables the choice; three later transport failures still preserve the original conflicted head plus suffix and expose manual recovery; final acceptance removes only the head and converges the untouched suffix without duplication or loss. `cargo test -p hemx-kanban-example --test browser_e2e redacted_sync_diagnostics_are_bounded_and_leak_no_sensitive_material -- --exact` proves a 15-second-old queue is bucketed rather than timestamped, cursor and acknowledgement latency advance after recovery, diagnostics stay under a fixed small readout, and command id/payload/actor/session/cookie material never reaches the diagnostics surface; the conflict and keep-local tests additionally assert conflict/rejection counters at their actual failure boundaries. `cargo test -p hemx-kanban-example --test browser_e2e two_tabs_coordinate_single_uploader_and_takeover_without_duplicate_application -- --exact` proves one retry-exhausted leader/one explicit standby, zero follower upload before takeover, lease takeover after the leader closes, one canonical sequence/event, one queue removal, and one board application. `cargo test -p hemx-kanban-example --test browser_e2e upload_backpressure_keeps_pending_work_visible_and_recoverable -- --exact` proves one in-flight upload, a two-acknowledgement activation limit, one retained durable command with visible recovery state, and explicit retry draining the final command without loss. `cargo test -p hemx-kanban-example --test browser_e2e mixed_queue_removes_accepted_prefix_and_retains_rejected_tail -- --exact` proves an accepted prefix is canonically applied and removed once before a permanent rejection stops processing, exposes its typed HTTP/server cause, disables blind retry, and leaves both the rejected command and untouched suffix durable. `cargo test -p hemx-kanban-example --test browser_e2e schema_upgrade_preserves_queued_order_and_local_intent -- --exact` proves a three-command v1 queue migrates atomically to the explicit-target v2 schema, remains byte-for-intent ordered after interrupted upload, then receives canonical sequences 1–3 in original order and drains without loss. `cargo test -p hemx-kanban-example --test browser_e2e account_partition_hides_replay_and_export_until_owner_returns -- --exact` proves a beta editor and alpha viewer enumerate zero commands and issue no replay for an alpha owner queue, signed-out startup cannot open a partition, no foreign id/export surface leaks, and only the returning alpha owner can export the intact command then resume it exactly once. `cargo test -p hemx-kanban-example --test browser_e2e canonical_snapshot_and_history_are_tenant_scoped -- --exact` proves alpha and beta sessions receive only their own canonical cards and acknowledgement events with independent sequence 1 cursors, while signed-out snapshot/history reads receive 401 and expose no stream. `cargo test -p hemx-kanban-example --test browser_e2e identical_sync_inputs_reconcile_deterministically -- --exact` proves `sync/022` through a real browser and live sync endpoints: one accepted server result and canonical snapshot plus an ordered command sequence produce byte-equivalent structured reconciliation records on independent cloned inputs, do not mutate inputs, and select the explicit server-authoritative model. Per-requirement audit: every `sync/001-023` row now has concrete browser proof. Slice 4 remains open pending a strict citation/proof audit of its cross-cutting `operations/001-005`, `security/002-005`, and `performance/004-005` requirements; the next slice must close those requirements from existing proof or identify the smallest real missing behavior. ## Slice 5 — local-first multiplayer Kanban milestone diff --git a/examples/kanban/static/sync.js b/examples/kanban/static/sync.js index f85191c..dfcf376 100644 --- a/examples/kanban/static/sync.js +++ b/examples/kanban/static/sync.js @@ -114,6 +114,41 @@ function decideRebase(snapshot, command) { return { kind: "conflicted", reason: "canonical-state-diverged", canonicalColumn: canonical.column }; } +// The built-in policy is deliberately a named module export: applications that +// need custom merge or CRDT semantics must import and wire a different policy. +export function reconcileServerAuthoritative(snapshot, commandSequence, serverResults) { + if (!snapshot || !Array.isArray(snapshot.cards) || !Number.isSafeInteger(snapshot.serverSequence)) { + throw new TypeError("reconciliation snapshot is invalid"); + } + if (!Array.isArray(commandSequence) || !Array.isArray(serverResults)) { + throw new TypeError("reconciliation commands and server results must be arrays"); + } + const resultCursor = serverResults.reduce((cursor, result) => { + if (!result || !Number.isSafeInteger(result.serverSequence)) { + throw new TypeError("reconciliation server result is invalid"); + } + return Math.max(cursor, result.serverSequence); + }, 0); + if (resultCursor > snapshot.serverSequence) { + throw new RangeError("reconciliation server result is newer than the canonical snapshot"); + } + const command = commandSequence[0]; + const decision = command + ? decideRebase(snapshot, command) + : { kind: "idle", reason: "no-pending-command", canonicalColumn: "unchanged" }; + return { + model: "server-authoritative-v1", + snapshotSequence: snapshot.serverSequence, + serverResultCursor: resultCursor, + serverResultCount: serverResults.length, + commandCount: commandSequence.length, + retainedCommandCount: decision.kind === "converged" + ? Math.max(0, commandSequence.length - 1) + : commandSequence.length, + decision, + }; +} + async function claimUploaderLease(database) { const transaction = database.transaction("meta", "readwrite"); const done = transactionDone(transaction); @@ -423,8 +458,15 @@ async function synchronize(command) { if (!response.ok) throw new Error(`snapshot failed with ${response.status}`); const snapshot = await response.json(); const queued = await pendingCommands(database); - const decision = decideRebase(snapshot, command); + const reconciliation = reconcileServerAuthoritative(snapshot, queued, [{ + status: "snapshot-required", + serverSequence: missing.latest, + }]); + const decision = reconciliation.decision; const converged = decision.kind === "converged"; + root.setAttribute("data-sync-reconciliation-model", reconciliation.model); + root.setAttribute("data-sync-reconciliation-result-cursor", String(reconciliation.serverResultCursor)); + root.setAttribute("data-sync-reconciliation-retained-count", String(reconciliation.retainedCommandCount)); root.setAttribute("data-sync-snapshot-sequence", String(snapshot.serverSequence)); root.setAttribute("data-sync-snapshot-schema", String(snapshot.schemaVersion)); root.setAttribute("data-sync-snapshot-card-count", String(snapshot.cards.length)); diff --git a/examples/kanban/templates/sync_shell.heml b/examples/kanban/templates/sync_shell.heml index 9457fc1..1b49ba8 100644 --- a/examples/kanban/templates/sync_shell.heml +++ b/examples/kanban/templates/sync_shell.heml @@ -16,6 +16,6 @@ - + diff --git a/examples/kanban/tests/browser_e2e.rs b/examples/kanban/tests/browser_e2e.rs index 00ccf04..7076a63 100644 --- a/examples/kanban/tests/browser_e2e.rs +++ b/examples/kanban/tests/browser_e2e.rs @@ -2077,6 +2077,90 @@ async fn keep_local_retry_preserves_conflicted_command_and_suffix_order() -> Web result.and(quit) } +#[tokio::test] +async fn identical_sync_inputs_reconcile_deterministically() -> WebDriverResult<()> { + // test req: sync/022 + let app_port = available_port(); + let app_addr = format!("127.0.0.1:{app_port}"); + let mut app_command = Command::new(env!("CARGO_BIN_EXE_hemx-kanban-example")); + app_command.env("HEMX_KANBAN_ADDR", &app_addr); + let _app = TestProcess::start(app_command, "hemx-kanban", &app_addr, STARTUP_TIMEOUT) + .expect("start hemx-kanban"); + + let webdriver_port = available_port(); + let webdriver_addr = format!("127.0.0.1:{webdriver_port}"); + let mut webdriver = Command::new("geckodriver"); + webdriver.arg("--port").arg(webdriver_port.to_string()); + let _webdriver = TestProcess::start(webdriver, "geckodriver", &webdriver_addr, STARTUP_TIMEOUT) + .expect("start ready geckodriver"); + let mut caps = DesiredCapabilities::firefox(); + caps.set_headless()?; + let driver = WebDriver::new(&format!("http://{webdriver_addr}"), caps).await?; + + let result = async { + driver.goto(&format!("http://{app_addr}/sync-demo")).await?; + wait_until( + &driver, + "return document.querySelector('[data-kanban-sync]')?.hasAttribute('data-sync-database-version')", + ) + .await?; + let proof = driver + .execute_async( + r#" + const done = arguments[arguments.length - 1]; + (async () => { + const acceptedResponse = await fetch('/sync/commands?command_id=deterministic%3A1&card_id=1&column=done', { method: 'POST' }); + const accepted = await acceptedResponse.json(); + const snapshotResponse = await fetch('/sync/snapshot'); + const snapshot = await snapshotResponse.json(); + const commands = [{ id: accepted.commandId, cardId: String(accepted.cardId), kind: 'reorder_card' }]; + const results = [accepted]; + const before = JSON.stringify({ snapshot, commands, results }); + const { reconcileServerAuthoritative } = await import('/sync.js'); + const first = reconcileServerAuthoritative(snapshot, commands, results); + const second = reconcileServerAuthoritative( + structuredClone(snapshot), + structuredClone(commands), + structuredClone(results), + ); + done({ + acceptedStatus: acceptedResponse.status, + snapshotStatus: snapshotResponse.status, + first, + second, + inputsUnchanged: before === JSON.stringify({ snapshot, commands, results }), + }); + })().catch((error) => done({ error: String(error), stack: error?.stack })); + "#, + Vec::new(), + ) + .await? + .json() + .clone(); + assert!(proof["error"].is_null(), "reconciliation failed: {proof}"); + assert_eq!(proof["acceptedStatus"], 200); + assert_eq!(proof["snapshotStatus"], 200); + assert_eq!(proof["first"], proof["second"]); + assert_eq!(proof["inputsUnchanged"], true); + assert_eq!(proof["first"]["model"], "server-authoritative-v1"); + assert_eq!(proof["first"]["snapshotSequence"], 1); + assert_eq!(proof["first"]["serverResultCursor"], 1); + assert_eq!(proof["first"]["serverResultCount"], 1); + assert_eq!(proof["first"]["commandCount"], 1); + assert_eq!(proof["first"]["retainedCommandCount"], 0); + assert_eq!(proof["first"]["decision"]["kind"], "converged"); + assert_eq!( + proof["first"]["decision"]["reason"], + "intent-already-canonical" + ); + assert_eq!(proof["first"]["decision"]["canonicalColumn"], "done"); + Ok(()) + } + .await; + let quit = driver.quit().await; + result.and(quit) +} + #[tokio::test] async fn canonical_acknowledgement_survives_server_restart() -> WebDriverResult<()> { // test req: sync/001 req: sync/005 req: sync/007 req: sync/008 req: sync/013