feat(kanban): bound durable replay

req: sync/014\nreq: performance/005
This commit is contained in:
slhx agent
2026-07-13 15:20:00 +02:00
parent 54b706b706
commit bf10d1e3ce
3 changed files with 174 additions and 3 deletions
+3 -3
View File
@@ -33,11 +33,11 @@ encryption, retention, backup, and deployment policy remain host concerns.
## Slice 3 — durable offline command log
- [ ] **User value:** an opted-in Kanban mutation remains available after network loss and browser reload without storing DOM patches as truth.
- **State:** In progress — the first app-owned `reorder_card` command is transactionally persisted with schema, actor, session, causal id, and app payload before projection; an app-owned service worker caches only the generated shell/resources, and reload restores the projection after the fixture server is stopped and proven unreachable. Native recovery controls export a versioned credential-free command envelope, delete queued commands while preserving actor/causal identity, and reset command data, identity, cache, and registration behind explicit confirmation. Unknown schemas stop with an explicit diagnostic. An injected transactional conflict proves failed persistence neither projects nor emits a durability claim, exposes stage/code without command payload, and remains recoverable through deletion. Malformed current-schema records are rejected field-specifically without partial projection while export/delete recovery remains available. Quota-specific recovery, bounded replay, and performance proof remain.
- **State:** In progress — the first app-owned `reorder_card` command is transactionally persisted with schema, actor, session, causal id, and app payload before projection; an app-owned service worker caches only the generated shell/resources, and reload restores the projection after the fixture server is stopped and proven unreachable. Native recovery controls export a versioned credential-free command envelope, delete queued commands while preserving actor/causal identity, and reset command data, identity, cache, and registration behind explicit confirmation. Unknown schemas stop with an explicit diagnostic. An injected transactional conflict proves failed persistence neither projects nor emits a durability claim, exposes stage/code without command payload, and remains recoverable through deletion. Malformed current-schema records are rejected field-specifically without partial projection while export/delete recovery remains available. Replay is preflighted before effects, capped by the app at 64 commands, measured against a 100 ms browser budget, and over-limit queues fail closed with export/delete recovery. Quota-specific recovery remains.
- **Build:** add an optional durable command-log adapter around platform transactional storage; persist versioned command ids and app payload before projection; restore projection after reload; expose queue state, export/delete/reset, quota/corruption failure, and migration refusal.
- **Refusals:** no server reconciliation, CRDT, mandatory IndexedDB, credential storage, or policy hidden in core.
- **Requirements:** `local/001-004`, `sync/009`, `sync/014-015`, `sync/020`, `security/007`, `performance/006`.
- **Proof:** `cargo test -p hemx-wasm --test browser kanban_command_persists_before_projection_and_restores_after_reload -- --exact` proves transactional persist-before-project ordering, app-owned shell caching, current-version replay after a real Firefox reload with the fixture server unreachable, stable identity metadata, and explicit unknown-schema refusal through real WASM. `cargo test -p hemx-wasm --test browser kanban_command_export_delete_and_reset_are_recoverable -- --exact` proves accessible export/delete/reset entry points, versioned credential-free export, confirmation before destructive actions, preserved identity after queue deletion, and fresh identity/baseline projection after reset. `cargo test -p hemx-wasm --test browser kanban_persistence_failure_does_not_project_and_recovers -- --exact` proves transactional failure does not project or emit `kanban:command-persisted`, reports non-payload stage/code diagnostics, and recovers through the ordinary deletion path. `cargo test -p hemx-wasm --test browser kanban_corrupt_command_refuses_projection_and_recovers -- --exact` proves strict current-schema validation, no partial projection, visible non-payload diagnostics, raw versioned export for recovery, and ordinary deletion recovery. The completed slice proof must additionally cover quota specifically, bound replay, and satisfy the performance budget.
- **Requirements:** `local/001-004`, `sync/009`, `sync/014-015`, `sync/020`, `security/007`, `performance/005-006`.
- **Proof:** `cargo test -p hemx-wasm --test browser kanban_command_persists_before_projection_and_restores_after_reload -- --exact` proves transactional persist-before-project ordering, app-owned shell caching, current-version replay after a real Firefox reload with the fixture server unreachable, stable identity metadata, and explicit unknown-schema refusal through real WASM. `cargo test -p hemx-wasm --test browser kanban_command_export_delete_and_reset_are_recoverable -- --exact` proves accessible export/delete/reset entry points, versioned credential-free export, confirmation before destructive actions, preserved identity after queue deletion, and fresh identity/baseline projection after reset. `cargo test -p hemx-wasm --test browser kanban_persistence_failure_does_not_project_and_recovers -- --exact` proves transactional failure does not project or emit `kanban:command-persisted`, reports non-payload stage/code diagnostics, and recovers through the ordinary deletion path. `cargo test -p hemx-wasm --test browser kanban_corrupt_command_refuses_projection_and_recovers -- --exact` proves strict current-schema validation, no partial projection, visible non-payload diagnostics, raw versioned export for recovery, and ordinary deletion recovery. `cargo test -p hemx-wasm --test browser kanban_replay_is_bounded_and_within_budget -- --exact` proves 64-command preflight/replay within the 100 ms browser budget, zero partial projection at 65 commands, and export/delete recovery. The completed slice proof must additionally cover quota specifically.
## Slice 4 — authoritative reconnect and convergence
+17
View File
@@ -3,6 +3,8 @@ const COMMANDS = "commands";
const META = "meta";
const COMMAND_SCHEMA = 1;
const EXPORT_SCHEMA = 1;
const MAX_REPLAY_COMMANDS = 64;
const REPLAY_BUDGET_MS = 100;
const SESSION = "hemx-kanban-session-v1";
const ROOT = '[data-hemx-root][data-hemx-client-module="/kanban_client.js"]';
@@ -110,6 +112,13 @@ async function storedCommands(database) {
return commands.sort((left, right) => left.causal - right.causal);
}
class ReplayLimitError extends Error {
constructor(actual) {
super(`durable replay limit exceeded: ${actual} > ${MAX_REPLAY_COMMANDS}`);
this.name = "ReplayLimitError";
}
}
function invalidCommand(command, field) {
const id = command && typeof command.id === "string" && command.id ? command.id : "record";
throw new Error(`invalid durable command ${id}: ${field}`);
@@ -279,9 +288,17 @@ async function start() {
if (typeof wasmHandler !== "function") throw new Error("reorder_card WASM handler is not registered");
const database = await databasePromise;
installRecoveryControls(root, database);
root.setAttribute("data-kanban-replay-limit", String(MAX_REPLAY_COMMANDS));
try {
const commands = await storedCommands(database);
if (commands.length > MAX_REPLAY_COMMANDS) throw new ReplayLimitError(commands.length);
commands.forEach(validate);
const replayStarted = performance.now();
for (const command of commands) window.hemx.applyBatch(await project(root, wasmHandler, command), root);
const replayMs = performance.now() - replayStarted;
root.setAttribute("data-kanban-replay-ms", replayMs.toFixed(3));
root.setAttribute("data-kanban-replay-budget-ms", String(REPLAY_BUDGET_MS));
root.toggleAttribute("data-kanban-replay-over-budget", replayMs > REPLAY_BUDGET_MS);
root.setAttribute("data-kanban-command-count", String(commands.length));
root.setAttribute("data-kanban-command-ready", "");
await offlineReady;
+154
View File
@@ -636,6 +636,118 @@ async fn kanban_persistence_failure_does_not_project_and_recovers() -> WebDriver
result.and(quit)
}
#[tokio::test]
async fn kanban_replay_is_bounded_and_within_budget() -> WebDriverResult<()> {
// test req: sync/014 req: performance/005
const REPLAY_LIMIT: u64 = 64;
const REPLAY_BUDGET_MS: f64 = 100.0;
let workspace = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("workspace root")
.to_owned();
let (package, bootstrap, rendered) = build_kanban_artifact(&workspace);
let runtime = workspace.join("hemx-js/runtime/hemx.js");
let server = StaticServer::start(
package,
runtime,
bootstrap,
rendered,
"kanban_client",
Some(kanban_app_assets(&workspace)),
);
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 = ProcessGuard::start(webdriver, &webdriver_addr);
let mut caps = DesiredCapabilities::firefox();
caps.set_headless()?;
let driver = WebDriver::new(&format!("http://{webdriver_addr}"), caps).await?;
let result = async {
driver.goto(&server.url()).await?;
wait_until(
&driver,
"return document.querySelector('[data-hemx-root]').hasAttribute('data-kanban-command-ready')",
)
.await?;
store_replay_commands(&driver, 1, REPLAY_LIMIT).await?;
driver
.execute("window.__reloadPending = true; location.reload()", Vec::new())
.await?;
wait_until(
&driver,
"const root = document.querySelector('[data-hemx-root]'); return !window.__reloadPending && root.hasAttribute('data-kanban-command-ready') && root.getAttribute('data-kanban-command-count') === '64'",
)
.await?;
let within_bound = driver
.execute(
"const root = document.querySelector('[data-hemx-root]'); return { order: [...root.querySelectorAll('[data-key]')].map((node) => node.dataset.key).join('|'), limit: root.getAttribute('data-kanban-replay-limit'), elapsed: Number(root.getAttribute('data-kanban-replay-ms')), budget: Number(root.getAttribute('data-kanban-replay-budget-ms')), over: root.hasAttribute('data-kanban-replay-over-budget') }",
Vec::new(),
)
.await?
.json()
.clone();
assert_eq!(within_bound["order"], "2|1");
assert_eq!(within_bound["limit"], REPLAY_LIMIT.to_string());
assert_eq!(within_bound["budget"], REPLAY_BUDGET_MS);
assert_eq!(within_bound["over"], false);
assert!(
within_bound["elapsed"].as_f64().is_some_and(|elapsed| elapsed <= REPLAY_BUDGET_MS),
"replay exceeded budget: {within_bound}"
);
store_replay_commands(&driver, REPLAY_LIMIT + 1, REPLAY_LIMIT + 1).await?;
driver
.execute("window.__reloadPending = true; location.reload()", Vec::new())
.await?;
wait_until(
&driver,
"const root = document.querySelector('[data-hemx-root]'); return !window.__reloadPending && root.getAttribute('data-kanban-command-error-code') === 'ReplayLimitError'",
)
.await?;
let refused = driver
.execute(
"const root = document.querySelector('[data-hemx-root]'); return { order: [...root.querySelectorAll('[data-key]')].map((node) => node.dataset.key).join('|'), ready: root.hasAttribute('data-kanban-command-ready'), error: root.getAttribute('data-kanban-command-error'), stage: root.getAttribute('data-kanban-command-error-stage') }",
Vec::new(),
)
.await?
.json()
.clone();
assert_eq!(refused["order"], "1|2");
assert_eq!(refused["ready"], false);
assert_eq!(
refused["error"],
"restore: durable replay limit exceeded: 65 > 64"
);
assert_eq!(refused["stage"], "restore");
let recovery_export = export_commands(&driver).await?.json().clone();
assert_eq!(
recovery_export["commands"].as_array().map(Vec::len),
Some(65)
);
driver
.execute("window.__reloadPending = true", Vec::new())
.await?;
let delete = driver
.find(By::Css("[data-kanban-command-action='delete']"))
.await?;
delete.click().await?;
delete.click().await?;
wait_until(
&driver,
"const root = document.querySelector('[data-hemx-root]'); return !window.__reloadPending && root.hasAttribute('data-kanban-command-ready') && root.getAttribute('data-kanban-command-count') === '0'",
)
.await?;
Ok(())
}
.await;
let quit = driver.quit().await;
result.and(quit)
}
#[tokio::test]
async fn kanban_corrupt_command_refuses_projection_and_recovers() -> WebDriverResult<()> {
// test req: sync/015
@@ -1148,6 +1260,48 @@ fn fixture_html(rendered: &str, has_app_module: bool) -> String {
)
}
async fn store_replay_commands(driver: &WebDriver, first: u64, last: u64) -> WebDriverResult<()> {
let stored = driver
.execute_async(
r#"
const first = arguments[0];
const last = arguments[1];
const done = arguments[arguments.length - 1];
const open = indexedDB.open('hemx-kanban-v1', 1);
open.onerror = () => done({ error: open.error && open.error.name });
open.onsuccess = () => {
const tx = open.result.transaction('commands', 'readwrite');
const commands = tx.objectStore('commands');
for (let causal = first; causal <= last; causal += 1) {
commands.add({
id: `replay:${causal}`,
schemaVersion: 1,
actor: 'replay',
session: 'replay',
causal,
kind: 'reorder_card',
cardId: '1',
eventKind: 'click',
key: null,
});
}
tx.oncomplete = () => done({ count: last - first + 1 });
tx.onabort = () => done({ error: tx.error && tx.error.name });
};
"#,
vec![first.into(), last.into()],
)
.await?
.json()
.clone();
assert_eq!(
stored["count"],
last - first + 1,
"failed to store replay commands: {stored}"
);
Ok(())
}
async fn store_malformed_command(driver: &WebDriver) -> WebDriverResult<()> {
let stored = driver
.execute_async(