Files
buzz/desktop/src/features/channels/readState/readStateStorage.test.mjs
Duncan 24e87e85c7 fix(readState): v4 plan conformance — pending-intents consolidation, single-flight retry controller, biting witnesses
Closes all 7 IMPORTANT + 2 MINOR findings from Thufir pass-1.

Core changes:
- Consolidate pending-intents storage into override-state.v2 blob (Paul's
  design ruling). Single write point for registers, receipts, and intents
  eliminates the double-commit window; no migration needed since
  pending-intents.v1 never shipped.
- Implement retryLoad() single-flight controller: bounded exponential backoff
  (1s->2s->4s...60s cap), reconnect coalescing into pendingRetryOnComplete,
  destroy/identity cancellation, retryAttempt reset on complete verdict.
- sourceScope + readTarget captured in enqueue path so drain performs exact
  source cleanup at the correct frontier position.
- refused-unread rollback: snapshot prior forced-unread entry before ordered
  write; restore exact snapshot on refusal; delete only when no prior existed.
- Surfaced drain outcomes via onDrainOutcome hook; genuine refusals
  (uint32_overflow, budget_exhausted, storage_failed) trigger toast;
  already_inactive is silent success; load_incomplete never surfaces.
- Cleanup atomicity: intent + receipt deleted in a single persistLocalState()
  call (one v2 blob write) so they are never observable separately.
- createDrainContext typed factory replaces this-as-unknown-as-DrainContext cast.
- NIP-RS.md: added normative refusal-reason vocabulary list.

Biting witnesses added (readStateManager.test.mjs, +12 tests):
- Amendment A: gen2 enqueued mid-replay, gen1 register rolled back
- Both inversion directions (unread->read, read->unread in-flight)
- compare-delete preserves newer intent
- Amendment C via production fetchAndMerge load path (not direct register write)
- Atomic intent+receipt deletion witness
- Controller: automatic backoff, reconnect during loadInFlight, stale-gen ordering
- Controller: destroy-with-timer, exactly-one-drain-per-generation
- Store/UI: identity-swap-during-drain, deferred refusal surfaces outcome

Co-authored-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
2026-08-07 18:53:39 -04:00

179 lines
5.2 KiB
JavaScript

import assert from "node:assert/strict";
import test from "node:test";
import {
pruneStaleContexts,
readStoredReadState,
writeStoredReadState,
} from "./readStateStorage.ts";
import {
LOCAL_MAX_PRUNABLE_CONTEXTS,
READ_STATE_HORIZON_SECONDS,
localPublishableContextKey,
localReadStateKey,
localSourceCreatedAtKey,
} from "./readStateFormat.ts";
function makeLocalStorage() {
const store = new Map();
return {
get size() {
return store.size;
},
get length() {
return store.size;
},
key: (i) => [...store.keys()][i] ?? null,
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => store.set(key, value),
removeItem: (key) => store.delete(key),
};
}
function installLocalStorage() {
const ls = makeLocalStorage();
if (typeof globalThis.window === "undefined") {
globalThis.window = {};
}
globalThis.window.localStorage = ls;
globalThis.localStorage = ls;
return ls;
}
const NOW = 1_750_000_000;
test("pruneStaleContexts drops msg/thread markers older than horizon", () => {
const cutoff = NOW - READ_STATE_HORIZON_SECONDS;
const contexts = new Map([
["channel-1", cutoff - 999_999],
[`thread:${"a".repeat(64)}`, cutoff - 1],
[`thread:${"b".repeat(64)}`, cutoff + 1],
[`msg:${"c".repeat(64)}`, cutoff - 1],
[`msg:${"d".repeat(64)}`, cutoff + 1],
]);
const pruned = pruneStaleContexts(contexts, NOW);
assert.equal(pruned.has("channel-1"), true, "channel keys never pruned");
assert.equal(pruned.has(`thread:${"a".repeat(64)}`), false);
assert.equal(pruned.has(`thread:${"b".repeat(64)}`), true);
assert.equal(pruned.has(`msg:${"c".repeat(64)}`), false);
assert.equal(pruned.has(`msg:${"d".repeat(64)}`), true);
});
test("pruneStaleContexts caps within-horizon prunable entries, newest kept", () => {
const contexts = new Map();
const total = LOCAL_MAX_PRUNABLE_CONTEXTS + 50;
for (let i = 0; i < total; i++) {
contexts.set(`msg:${String(i).padStart(64, "0")}`, NOW - i);
}
const pruned = pruneStaleContexts(contexts, NOW);
assert.equal(pruned.size, LOCAL_MAX_PRUNABLE_CONTEXTS);
// Newest (i=0) survives; oldest (i=total-1) evicted.
assert.equal(pruned.has(`msg:${String(0).padStart(64, "0")}`), true);
assert.equal(pruned.has(`msg:${String(total - 1).padStart(64, "0")}`), false);
});
test("writeStoredReadState prunes all three keys consistently", () => {
installLocalStorage();
const pubkey = "f".repeat(64);
const staleThread = `thread:${"a".repeat(64)}`;
const freshThread = `thread:${"b".repeat(64)}`;
const nowSeconds = Math.floor(Date.now() / 1_000);
const stale = nowSeconds - READ_STATE_HORIZON_SECONDS - 10;
writeStoredReadState(
pubkey,
new Map([
["channel-1", stale],
[staleThread, stale],
[freshThread, nowSeconds],
]),
new Set(["channel-1", staleThread, freshThread]),
new Map([
["channel-1", stale],
[staleThread, stale],
[freshThread, nowSeconds],
]),
new Map(),
new Map(),
new Map(),
1,
);
const state = JSON.parse(
window.localStorage.getItem(localReadStateKey(pubkey)),
);
assert.deepEqual(Object.keys(state).sort(), ["channel-1", freshThread]);
const publishable = JSON.parse(
window.localStorage.getItem(localPublishableContextKey(pubkey)),
);
assert.deepEqual(publishable.sort(), ["channel-1", freshThread]);
const sourceCreatedAt = JSON.parse(
window.localStorage.getItem(localSourceCreatedAtKey(pubkey)),
);
assert.deepEqual(Object.keys(sourceCreatedAt).sort(), [
"channel-1",
freshThread,
]);
});
test("writeStoredReadState round-trips through readStoredReadState", () => {
installLocalStorage();
const pubkey = "e".repeat(64);
const nowSeconds = Math.floor(Date.now() / 1_000);
writeStoredReadState(
pubkey,
new Map([["channel-9", nowSeconds]]),
new Set(["channel-9"]),
new Map([["channel-9", nowSeconds]]),
new Map([["channel-9", { s: 3, c: 1, b: nowSeconds, f: nowSeconds }]]),
new Map(),
new Map(),
1,
);
const stored = readStoredReadState(pubkey);
assert.equal(stored.contexts.get("channel-9"), nowSeconds);
assert.equal(stored.publishableContextIds.has("channel-9"), true);
assert.equal(stored.contextSourceCreatedAt.get("channel-9"), nowSeconds);
const reg = stored.overrideRegisters.get("channel-9");
assert.ok(reg, "overrideRegisters must round-trip");
assert.equal(reg.s, 3, "register S must round-trip");
assert.equal(reg.c, 1, "register C must round-trip");
assert.equal(reg.b, nowSeconds, "register B must round-trip");
});
test("writeStoredReadState_survives_throwing_localStorage_and_returns_false", () => {
const ls = installLocalStorage();
ls.setItem = () => {
throw new Error("QuotaExceededError");
};
const pubkey = "d".repeat(64);
const nowSeconds = Math.floor(Date.now() / 1_000);
let result;
assert.doesNotThrow(() => {
result = writeStoredReadState(
pubkey,
new Map([["channel-1", nowSeconds]]),
new Set(["channel-1"]),
new Map([["channel-1", nowSeconds]]),
new Map(),
new Map(),
new Map(),
1,
);
});
assert.equal(
result,
false,
"writeStoredReadState must return false on quota failure",
);
});