fix(client): résolution de compte barrière-autoritative — fin du fork à la reconnexion

Bug: à la reconnexion, resolveAccount lisait le shim depuis le store-root
(did🆖${privateStoreId}), NON abonnable → pas de barrière first-State → un "0 rows"
à froid est ambigu → le retry (resolveAccountReliably/provisionRetry) échoue → nouveau
compte provisionné → FORK → données du compte invisibles.

Cause NextGraph (vérifiée nextgraph-rs): "trouvable-sans-lookup" (store-root) et
"abonnable" (did:ng:o:<RepoID aléatoire>) sont DISJOINTS — pas de doc à la fois
devinable et attendable → une résolution shim purement barrière est impossible.

Fix (indirection pointeur → doc-shim abonnable):
- Les AccountRecord migrent dans un doc-shim doc_create'd (did:ng:o:..., a une barrière).
- Un pointeur écrit-une-fois dans le store-root (<shim:root> <shim:shimDoc> <docShim>)
  le nomme. resolveShimDoc lit le pointeur → ensureRepoOpen(docShim) [barrière] → lecture
  de compte AUTORITATIVE (cold 0 = absent pour de vrai). Retry de compte SUPPRIMÉ.
- Micro-garde résiduel (pointerGuard, ex-provisionRetry) sur le SEUL triple pointeur
  écrit-une-fois; ne peut jamais forker un compte; fork de pointeur réconcilié au
  doc-shim canonique (lexicographiquement-min), sans perte.
- Migration: migrateLegacyRecords copie (pas déplace) les comptes de l'ancien store-root
  vers le doc-shim avant toute conclusion "absent"; idempotent; wallet neuf → no-op.

Tests: unit 128/128, e2e réel 42/42 (CONTRACT 2 = non-fork du compte à la reconnexion),
red-before/green-after prouvé. Docs: nextgraph-current-state (antagonisme + indirection),
simulation, migration-guide.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sylvain Duchesne
2026-07-13 17:46:16 +02:00
parent 5cdc6ce77f
commit 5e91771da6
17 changed files with 744 additions and 351 deletions
-1
View File
@@ -47,7 +47,6 @@ function injectFake(debugAccessLog = false) {
configure({ ng: ng as any, useShape: (() => {}) as any, debugAccessLog });
configureStoreRegistry({
getSession: async () => ({ sessionId: "sid-log", privateStoreId: "P" }),
provisionRetry: { attempts: 1 },
});
return ng;
}
+171 -107
View File
@@ -1,20 +1,27 @@
/**
* anti-fork.test.ts — behavioral tests for the reconnection fix in the
* polyfill-era shim (src/store-registry.ts). Two guards, one file:
* polyfill-era shim (src/store-registry.ts), redesigned around the
* pointer → doc-shim indirection. Three groups, one file:
*
* (1) DETERMINISTIC RESOLUTION — a shim whose account subject carries DUPLICATE
* scope-doc values (fork residue: several `shim:docPublic`) must resolve to
* the SAME canonical doc every time (lexicographically-smallest NURI), so the
* session that WROTE an entity and a fresh page that RESOLVES the doc never
* disagree. This is the root-cause fix for the reconnection bug.
* (1) DETERMINISTIC RESOLUTION — a doc-shim whose account subject carries
* DUPLICATE scope-doc values (fork residue: several `shim:docPublic`) must
* resolve to the SAME canonical doc every time (lexicographically-smallest
* NURI), so the session that WROTE an entity and a fresh page that RESOLVES
* the doc never disagree. Robustness against PAST fork residue.
*
* (2) ANTI-FORK BOUNDED RETRY — a fresh page over a persistent wallet may read
* the shim as 0 rows while the private store is still syncing. A BOUNDED retry
* (capped backoff, from the injected `provisionRetry` budget) bridges that
* window before concluding "account genuinely new" and provisioning —
* preventing new fork residue. A genuinely-new account (always 0) is still
* provisioned exactly once. The budget defaults to `attempts: 1` (no retry)
* when unset, so the synchronous unit fakes stay single-read and unchanged.
* (2) BARRIER-AUTHORITATIVE RECONNECT (the core fix) — a fresh page over a
* persistent wallet resolves the SAME account through the doc-shim's
* first-`State` BARRIER, with NO account-level retry. The account records
* live in a subscribable doc-shim (`did:ng:o:...`) reached via a write-once
* POINTER triple in the store-root; opening the doc-shim makes a cold read
* authoritative, so a genuinely-present account is found on the first read
* and never re-provisioned (no fork). This replaced the deleted
* `resolveAccountReliably` / `provisionRetry` account retry.
*
* (3) MIGRATION — a wallet whose accounts were written at the OLD location (the
* store-root graph, pre-indirection) must have those records MIGRATED into
* the doc-shim at resolution, so a legacy account resolves (is READ, not
* re-provisioned) after reconnect. No existing account is lost.
*/
import { describe, it, expect, mock, beforeEach, afterAll } from "bun:test";
@@ -41,13 +48,18 @@ afterAll(() => {
});
const SESSION: RegistrySession = { sessionId: "sid-af", privateStoreId: "PRIV-AF" };
const ROOT = "did:ng:PRIV-AF";
// ---------------------------------------------------------------------------
// Fake ng — in-memory quad store. Two variants:
// - makeFakeNg(): NO doc_subscribe → non-reactive path (no sync lag, no retry).
// - makeLaggyFakeNg({lag}): HAS doc_subscribe (so the anti-fork retry path
// fires) and can simulate a sync lag: the account SELECT returns 0 rows for the
// first `lag` reads, then the seeded data — modelling a shim not yet synced.
// Fake ng — in-memory quad store modelling the pointer → doc-shim indirection.
//
// - The POINTER (`<shim:root> <shim:shimDoc> <docShim>`) lives in the store-root
// graph (keyed by GRAPH <ROOT>).
// - AccountRecords live in the doc-shim (anchored default graph, keyed by the
// anchor arg = the doc-shim NURI). A LEGACY record may ALSO be seeded directly
// in the store-root graph (the pre-indirection location) to exercise migration.
// - doc_subscribe pushes an initial `State` so ensureRepoOpen resolves at once
// (the barrier).
// ---------------------------------------------------------------------------
interface Quad { g: string; s: string; p: string; o: string }
@@ -95,10 +107,9 @@ function makeSparqlUpdate(quads: Quad[]) {
});
}
/** Build the account-SELECT bindings from the quads (grouped per subject). Each
* (subject × docPublic × docProtected × docPrivate) combination is a binding, so
* a subject with DUPLICATE scope docs yields a cross-product of bindings — exactly
* what a corrupted shim returns. */
/** Build the account-SELECT bindings from the quads in ONE graph (the doc-shim, or
* the store-root for the migration read), grouped per subject. A subject with
* DUPLICATE scope docs yields a cross-product of bindings — a corrupted shim. */
function accountBindings(quads: Quad[], anchor: string | undefined, onlySubject: string | null) {
const bySubject = new Map<string, { id: string; pub: string[]; prot: string[]; priv: string[] }>();
for (const q of quads) {
@@ -130,19 +141,33 @@ function accountBindings(quads: Quad[], anchor: string | undefined, onlySubject:
return bindings;
}
/** Non-reactive fake ng (no doc_subscribe → no sync lag, no retry). */
/** Reactive fake ng modelling the pointer → doc-shim indirection. `doc_subscribe`
* pushes a first `State` so the doc-shim barrier resolves synchronously. */
function makeFakeNg() {
const quads: Quad[] = [];
let docCounter = 0;
let accountQueryCount = 0;
// Count account SELECTs per anchor graph. The AUTHORITATIVE account read is anchored
// to the doc-shim (a did:ng:o: NURI); the one-time legacy MIGRATION scan is anchored
// to the store-root (ROOT). Counting per-anchor lets a test assert "exactly one
// doc-shim account read" (no account RETRY) separately from the migration scan.
const accountReadsByAnchor = new Map<string, number>();
const doc_create = mock(async (..._a: unknown[]) => `did:ng:o:doc${++docCounter}`);
const sparql_update = makeSparqlUpdate(quads);
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
// Pointer SELECT (store-root).
if (query.includes("<urn:ng-eventually:shim:shimDoc>")) {
const bindings = quads
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:shimDoc")
.map((q) => ({ shimDoc: { value: q.o } }));
return { results: { bindings } };
}
// Account SELECT — anchored either to the doc-shim (authoritative read) or, for
// the migration scan, to the store-root (legacy location). Same shape either way.
if (query.includes("<urn:ng-eventually:shim:id>")) {
accountQueryCount++;
const subjM = query.match(/GRAPH <[^>]+>\s*\{\s*<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
accountReadsByAnchor.set(anchor ?? "", (accountReadsByAnchor.get(anchor ?? "") ?? 0) + 1);
const subjM = query.match(/<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
return { results: { bindings: accountBindings(quads, anchor, subjM ? subjM[1]! : null) } };
}
const bindings = quads
@@ -150,40 +175,7 @@ function makeFakeNg() {
.map((q) => ({ e: { value: q.o } }));
return { results: { bindings } };
});
return { doc_create, sparql_update, sparql_query, _quads: quads, getAccountQueryCount: () => accountQueryCount };
}
/** Fake ng with a SYNC-LAG simulation: the first `lag` account reads return 0 rows
* (shim not synced yet), then the seeded data appears — modelling a fresh page over
* a persistent wallet. Used with a fast `provisionRetry` budget to exercise the
* anti-fork retry. (Carries a `doc_subscribe` so it also passes as a reactive ng.) */
function makeLaggyFakeNg(opts: { lag?: number } = {}) {
const quads: Quad[] = [];
let docCounter = 0;
let accountQueryCount = 0;
let lag = opts.lag ?? 0;
const doc_create = mock(async (..._a: unknown[]) => `did:ng:o:doc${++docCounter}`);
const sparql_update = makeSparqlUpdate(quads);
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
if (query.includes("<urn:ng-eventually:shim:id>")) {
accountQueryCount++;
if (lag > 0) { lag--; return { results: { bindings: [] } }; } // sync not landed yet
const subjM = query.match(/GRAPH <[^>]+>\s*\{\s*<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
return { results: { bindings: accountBindings(quads, anchor, subjM ? subjM[1]! : null) } };
}
const bindings = quads
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:contains")
.map((q) => ({ e: { value: q.o } }));
return { results: { bindings } };
});
// doc_subscribe: immediately push a State (the sync barrier) so `ensureRepoOpen`
// resolves at once. `resolveAccount`/`ensureAccount` now open the anchor repo
// (open-repo.ts) before reading/writing the shim (the cold-start heal); the real
// broker pushes `TabInfo` then a first `State` on subscribe, and open-repo awaits
// that `State`. Model it: invoke the callback with a `State` AppResponse so the
// barrier is reached synchronously (no 8s fallback → the retry tests stay fast).
// Push a `State` on subscribe (the sync barrier) so ensureRepoOpen resolves at once.
const doc_subscribe = mock(async (_repo: unknown, _sid: unknown, cb: Function) => {
if (typeof cb === "function") cb({ V0: { State: {} } });
return () => {};
@@ -191,47 +183,52 @@ function makeLaggyFakeNg(opts: { lag?: number } = {}) {
return {
doc_create, sparql_update, sparql_query, doc_subscribe,
_quads: quads,
getAccountQueryCount: () => accountQueryCount,
// Total account reads across all anchors.
getAccountQueryCount: () => [...accountReadsByAnchor.values()].reduce((a, b) => a + b, 0),
// Account reads anchored to a did:ng:o: doc-shim (excludes the store-root migration scan).
getDocShimAccountReads: () =>
[...accountReadsByAnchor.entries()]
.filter(([g]) => g.startsWith("did:ng:o:"))
.reduce((a, [, n]) => a + n, 0),
};
}
function inject(
fakeNg: unknown,
provisionRetry?: { attempts?: number; baseMs?: number; maxStepMs?: number },
pointerGuard?: { attempts?: number; baseMs?: number; maxStepMs?: number },
) {
configure({ ng: fakeNg as any, useShape: (() => {}) as any });
configureStoreRegistry({
getSession: async () => SESSION,
normalizeId: (u) => u.trim().toLowerCase(),
// Default (unset) → attempts:1 (no retry). The retry tests pass a fast budget.
provisionRetry,
pointerGuard,
});
resetRegistryCache();
resetOpenedRepos();
}
// ---------------------------------------------------------------------------
// (1) Deterministic resolution
// (1) Deterministic resolution over fork residue (in the doc-shim)
// ---------------------------------------------------------------------------
describe("deterministic resolution over a shim corrupted by fork residue", () => {
describe("deterministic resolution over a doc-shim corrupted by fork residue", () => {
beforeEach(() => { resetRegistryCache(); resetOpenedRepos(); });
it("(1a) a subject with MULTIPLE docPublic values always resolves the SAME canonical (lexicographically-smallest)", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
const anchor = "did:ng:PRIV-AF";
// Same account subject with 5 duplicate docPublic values (fork residue), out of
// lexicographic order, plus one docProtected/docPrivate each.
const docShim = "did:ng:o:shimdoc";
// Seed the pointer (store-root → doc-shim) and the corrupted record IN the doc-shim.
fakeNg._quads.push({ g: ROOT, s: "urn:ng-eventually:shim:root", p: "urn:ng-eventually:shim:shimDoc", o: docShim });
const subj = "urn:ng-eventually:shim:account:dupuser";
const dupPublics = [
"did:ng:o:pub-m", "did:ng:o:pub-a", "did:ng:o:pub-z", "did:ng:o:pub-c", "did:ng:o:pub-a",
];
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:id", o: "dupuser" });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:id", o: "dupuser" });
for (const p of dupPublics)
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:docPublic", o: p });
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:prot-1" });
fakeNg._quads.push({ g: anchor, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:priv-1" });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:docPublic", o: p });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:prot-1" });
fakeNg._quads.push({ g: docShim, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:priv-1" });
const r1 = await resolveAccount("dupuser");
resetRegistryCache();
@@ -240,9 +237,7 @@ describe("deterministic resolution over a shim corrupted by fork residue", () =>
// Canonical = lexicographically smallest → "did:ng:o:pub-a".
expect(r1?.docPublic).toBe("did:ng:o:pub-a");
// Stable across independent resolves...
expect(r2?.docPublic).toBe(r1?.docPublic);
// ...and loadShim (full scan) agrees with resolveAccount (targeted).
expect(viaShim?.docPublic).toBe(r1?.docPublic);
expect(viaShim?.docProtected).toBe("did:ng:o:prot-1");
expect(viaShim?.docPrivate).toBe("did:ng:o:priv-1");
@@ -250,18 +245,21 @@ describe("deterministic resolution over a shim corrupted by fork residue", () =>
});
// ---------------------------------------------------------------------------
// (2) Anti-fork bounded retry
// (2) Barrier-authoritative reconnect — the core fix (no account retry)
// ---------------------------------------------------------------------------
describe("ensureAccount: anti-fork bounded retry", () => {
describe("reconnect resolves the SAME account through the doc-shim barrier (no fork, no account retry)", () => {
beforeEach(() => { resetRegistryCache(); resetOpenedRepos(); });
it("(2a) NO-FORK: account already in shim → reused, 0 new doc_create (non-reactive fake, single read)", async () => {
it("(2a) NO-FORK: account already in the doc-shim → reused, 0 new scope docs", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
// First login: provisions the account (1 doc-shim + 3 scope docs).
const first = await ensureAccount("LauraBarrier");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4);
// Fresh page over the SAME persistent quads: reset all in-memory caches, keep the
// quads. Reconnect must find the SAME account via the doc-shim barrier, NO new docs.
resetRegistryCache();
resetOpenedRepos();
const second = await ensureAccount("LauraBarrier");
@@ -269,56 +267,62 @@ describe("ensureAccount: anti-fork bounded retry", () => {
expect(second.docPublic).toBe(first.docPublic);
expect(second.docProtected).toBe(first.docProtected);
expect(second.docPrivate).toBe(first.docPrivate);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3); // still 3, not 6
// Still 4 — no doc-shim re-created (pointer reused), no scope docs re-created.
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4);
});
it("(2b) SYNC LAG: shim reads 0 K times then the data → RETRY reuses, no fork", async () => {
// Seed an account into an initial (non-reactive) fake, capture its NURIs.
it("(2b) barrier-authoritative: a fresh session finds the persisted account on the FIRST read — single doc-shim read, NO retry", async () => {
// Seed session 1; capture the account NURIs + the persistent quads.
const seed = makeFakeNg();
inject(seed);
const orig = await ensureAccount("LaggyUser");
expect(seed.doc_create).toHaveBeenCalledTimes(3);
const orig = await ensureAccount("BarrierUser");
expect(seed.doc_create).toHaveBeenCalledTimes(4);
// Fresh reactive session over the SAME quads, with a 3-read sync lag: the first
// 3 account reads return 0 rows (shim not synced), then the seeded data appears.
const reactive = makeLaggyFakeNg({ lag: 3 });
reactive._quads.push(...seed._quads);
inject(reactive, { attempts: 8, baseMs: 1, maxStepMs: 2 }); // fast budget
// Fresh reactive session over the SAME persistent quads. The doc-shim pushes a
// `State` on subscribe → resolveShimDoc opens the barrier → the account read is
// authoritative on the FIRST attempt. Give a MULTI-attempt pointer guard to prove
// it is NOT used for the account.
const reconnect = makeFakeNg();
reconnect._quads.push(...seed._quads);
inject(reconnect, { attempts: 8, baseMs: 1, maxStepMs: 2 });
const resolved = await ensureAccount("LaggyUser");
const resolved = await ensureAccount("BarrierUser");
// Reused the SAME account — NO fork provisioning despite the initial 0 rows.
expect(resolved.docPublic).toBe(orig.docPublic);
expect(resolved.docProtected).toBe(orig.docProtected);
expect(resolved.docPrivate).toBe(orig.docPrivate);
expect(reactive.doc_create).toHaveBeenCalledTimes(0); // no new docs → no fork
// It DID retry: more than one account read (1 initial + retries until data).
expect(reactive.getAccountQueryCount()).toBeGreaterThan(1);
expect(reconnect.doc_create).toHaveBeenCalledTimes(0); // no new docs → no fork
// Barrier-authoritative: found on the FIRST doc-shim read (the store-root migration
// scan, which finds nothing to migrate here, is separate).
expect(reconnect.getDocShimAccountReads()).toBe(1);
});
it("(2c) GENUINELY NEW: shim always reads 0 → provisioned exactly once after the budget", async () => {
const reactive = makeLaggyFakeNg({ lag: 999 }); // never resolves → genuinely new
inject(reactive, { attempts: 5, baseMs: 1, maxStepMs: 2 });
it("(2c) GENUINELY NEW: a cold doc-shim reads 0 → provisioned exactly once, no retry", async () => {
// Pointer + doc-shim exist but the doc-shim holds NO record for this account.
const fakeNg = makeFakeNg();
inject(fakeNg, { attempts: 5, baseMs: 1, maxStepMs: 2 });
const docShim = "did:ng:o:preexisting-shim";
fakeNg._quads.push({ g: ROOT, s: "urn:ng-eventually:shim:root", p: "urn:ng-eventually:shim:shimDoc", o: docShim });
const rec = await ensureAccount("BrandNewUser");
// Provisioned exactly ONE set of scope docs.
expect(reactive.doc_create).toHaveBeenCalledTimes(3);
// Provisioned exactly ONE set of 3 scope docs (the doc-shim already existed).
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
expect(rec.docPublic).toMatch(/^did:ng:o:doc/);
expect(rec.docProtected).not.toBe(rec.docPublic);
// Retry was BOUNDED: exactly `attempts` account reads, then it gave up and provisioned.
expect(reactive.getAccountQueryCount()).toBe(5);
// Barrier-authoritative: exactly ONE doc-shim account read (the 0 is definitive).
expect(fakeNg.getDocShimAccountReads()).toBe(1);
});
it("(2d) default budget (unset → attempts:1): genuinely-new account → single read, no retry", async () => {
it("(2d) default budget (unset pointer guard): genuinely-new account → single doc-shim account read", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg); // provisionRetry unset → attempts:1 (synchronous default)
inject(fakeNg); // pointerGuard unset → attempts:1 (synchronous default)
const rec = await ensureAccount("SyncUser");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
// Exactly ONE account read — the default budget does not retry.
expect(fakeNg.getAccountQueryCount()).toBe(1);
// 1 doc-shim + 3 scope docs.
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4);
expect(fakeNg.getDocShimAccountReads()).toBe(1);
expect(rec.docPublic).toMatch(/^did:ng:o:doc/);
});
@@ -328,6 +332,66 @@ describe("ensureAccount: anti-fork bounded retry", () => {
const a = await ensureAccount("SameUser");
const b = await ensureAccount("SameUser");
expect(b).toEqual(a);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(3);
expect(fakeNg.doc_create).toHaveBeenCalledTimes(4); // 1 doc-shim + 3 scope docs
});
});
// ---------------------------------------------------------------------------
// (3) Migration — legacy store-root records folded into the doc-shim
// ---------------------------------------------------------------------------
describe("migration: legacy store-root records are read (not re-provisioned) after reconnect", () => {
beforeEach(() => { resetRegistryCache(); resetOpenedRepos(); });
it("(3a) a pre-indirection account (records in the store-root, no pointer) is migrated into a new doc-shim and resolves — no fork", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
// Seed a LEGACY account directly in the store-root graph (old location), NO pointer.
const subj = "urn:ng-eventually:shim:account:legacyuser";
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:id", o: "legacyuser" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPublic", o: "did:ng:o:legacy-pub" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:legacy-prot" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:legacy-priv" });
const rec = await ensureAccount("legacyuser");
// The legacy account was READ (migrated), NOT re-provisioned: original NURIs come
// back, and NO scope docs were created (only the fresh doc-shim: 1 doc_create).
expect(rec.docPublic).toBe("did:ng:o:legacy-pub");
expect(rec.docProtected).toBe("did:ng:o:legacy-prot");
expect(rec.docPrivate).toBe("did:ng:o:legacy-priv");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(1); // only the new doc-shim
// A pointer was written, and the record now also lives in the doc-shim.
const pointerRow = fakeNg._quads.find(
(q) => q.g === ROOT && q.p === "urn:ng-eventually:shim:shimDoc",
);
expect(pointerRow?.o).toMatch(/^did:ng:o:doc/);
const inDocShim = fakeNg._quads.some(
(q) => q.g === pointerRow!.o && q.p === "urn:ng-eventually:shim:docPublic" && q.o === "did:ng:o:legacy-pub",
);
expect(inDocShim).toBe(true);
});
it("(3b) a pointer that predates migration still folds legacy store-root records into its doc-shim", async () => {
const fakeNg = makeFakeNg();
inject(fakeNg);
// A doc-shim + pointer already exist (empty doc-shim), records still only in the root.
const docShim = "did:ng:o:existing-shim";
fakeNg._quads.push({ g: ROOT, s: "urn:ng-eventually:shim:root", p: "urn:ng-eventually:shim:shimDoc", o: docShim });
const subj = "urn:ng-eventually:shim:account:oldtimer";
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:id", o: "oldtimer" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPublic", o: "did:ng:o:old-pub" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docProtected", o: "did:ng:o:old-prot" });
fakeNg._quads.push({ g: ROOT, s: subj, p: "urn:ng-eventually:shim:docPrivate", o: "did:ng:o:old-priv" });
const rec = await ensureAccount("oldtimer");
expect(rec.docPublic).toBe("did:ng:o:old-pub");
expect(fakeNg.doc_create).toHaveBeenCalledTimes(0); // doc-shim already existed
const inDocShim = fakeNg._quads.some(
(q) => q.g === docShim && q.p === "urn:ng-eventually:shim:docPublic" && q.o === "did:ng:o:old-pub",
);
expect(inDocShim).toBe(true);
});
});
+19 -4
View File
@@ -82,11 +82,19 @@ function makeColdAnchorNg() {
const sparql_update = mock(async (_sid: string, query: string, anchor?: string) => {
if (anchor === ANCHOR && !opened.has(ANCHOR)) throw new Error("RepoNotFound");
// Parse the shim INSERT (GRAPH <anchor> { <subj> a <Account> ; <p> "o" … }).
// TWO shapes: the POINTER write uses `GRAPH <root>` (keyed by IRI); the account
// record write into the doc-shim has NO explicit GRAPH (keyed by the anchor arg).
const gm = query.match(/GRAPH <([^>]+)>\s*\{([\s\S]*)\}/);
if (!gm) return undefined;
const g = gm[1]!;
const body = gm[2]!;
let g: string;
let body: string;
if (gm) {
g = gm[1]!;
body = gm[2]!;
} else {
if (!anchor) return undefined;
g = anchor;
body = query.replace(/^\s*INSERT DATA\s*\{/, "").replace(/\}\s*$/, "");
}
const sm = body.match(/<([^>]+)>/);
if (!sm) return undefined;
const s = sm[1]!;
@@ -103,6 +111,13 @@ function makeColdAnchorNg() {
const sparql_query = mock(async (_sid: string, query: string, _base: unknown, anchor?: string) => {
if (anchor === ANCHOR && !opened.has(ANCHOR)) throw new Error("RepoNotFound");
// Pointer SELECT (store-root -> doc-shim).
if (query.includes("<urn:ng-eventually:shim:shimDoc>")) {
const bindings = quads
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:shimDoc")
.map((q) => ({ shimDoc: { value: q.o } }));
return { results: { bindings } };
}
const subjM = query.match(
/<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/,
);
+13 -8
View File
@@ -119,11 +119,18 @@ function makeFakeNg() {
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
// Shim account SELECT. Two shapes: the full scan (`?acc a <Account>`) and
// the TARGETED bounded resolve (`<subj> a <Account>`), which binds one
// subject — honour that subject filter so the bounded query is O(1)/exact.
// Pointer SELECT: `<shim:root> <shim:shimDoc> ?shimDoc` in the store-root graph.
if (query.includes(`<${SHIM}:shimDoc>`)) {
const bindings = quads
.filter((q) => q.g === anchor && q.p === `${SHIM}:shimDoc`)
.map((q) => ({ shimDoc: { value: q.o } }));
return { results: { bindings } };
}
// Shim account SELECT (anchored to the doc-shim, no GRAPH wrapper). Two shapes:
// the full scan (`?acc a <Account>`) and the TARGETED bounded resolve (`<subj> a
// <Account>`) — honour that subject filter so the bounded query is O(1)/exact.
if (query.includes(`<${SHIM}:id>`)) {
const subjM = query.match(new RegExp(`GRAPH <[^>]+>\\s*\\{\\s*<([^>]+)>\\s+a\\s+<${SHIM}:Account>`));
const subjM = query.match(new RegExp(`<([^>]+)>\\s+a\\s+<${SHIM}:Account>`));
const onlySubject = subjM ? subjM[1]! : null;
const bySubject = new Map<string, Record<string, string>>();
for (const q of quads) {
@@ -188,8 +195,6 @@ function inject() {
configureStoreRegistry({
getSession: async () => SESSION,
normalizeId: (u) => u.trim().replace(/^@+/, "").toLowerCase(),
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
provisionRetry: { attempts: 1 },
});
resetRegistryCache();
setCurrentUser(null);
@@ -203,8 +208,8 @@ beforeEach(() => {
test("submitToIndex creates the @index special account on first sight (3 docs)", async () => {
await submitToIndex({ nuri: "did:ng:o:event1", title: "Concert" });
// ensureAccount('@index') created its 3 scope docs.
expect(fake.doc_create).toHaveBeenCalledTimes(3);
// ensureAccount('@index') created its 3 scope docs + 1 doc-shim (first login).
expect(fake.doc_create).toHaveBeenCalledTimes(4);
// The deposit landed in the @index public document (its inbox).
const depositCall = fake.sparql_update.mock.calls.find((c) =>
(c[1] as string).includes(`${INBOX}:Deposit`),
+1 -1
View File
@@ -153,7 +153,7 @@ function inject() {
const ng = makeFakeNg();
configure({ ng: ng as any, useShape: (() => {}) as any });
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
configureStoreRegistry({ getSession: async () => SESSION, provisionRetry: { attempts: 1 } });
configureStoreRegistry({ getSession: async () => SESSION });
setCurrentUser(null);
return ng;
}
@@ -46,7 +46,7 @@ function inject() {
};
configure({ ng: ng as any, useShape: (() => {}) as any });
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
configureStoreRegistry({ getSession: async () => SESSION, normalizeId: (id) => id.trim(), provisionRetry: { attempts: 1 } });
configureStoreRegistry({ getSession: async () => SESSION, normalizeId: (id) => id.trim() });
resetRegistryCache();
resetCaps();
setCurrentUser(null);
-2
View File
@@ -86,7 +86,6 @@ function inject(ng: ReturnType<typeof makeFakeNgWithSubscribe>) {
configureStoreRegistry({
getSession: async () => SESSION,
normalizeId: (u: string) => u,
provisionRetry: { attempts: 1 },
});
}
@@ -151,7 +150,6 @@ describe("ensureRepoOpen", () => {
configureStoreRegistry({
getSession: async () => SESSION,
normalizeId: (u: string) => u,
provisionRetry: { attempts: 1 },
});
// Must not throw; nuri is added to opened Set (guard skips subscribe)
-4
View File
@@ -35,8 +35,6 @@ function inject(triplesByDoc: Record<string, Array<[string, string]>>) {
configureStoreRegistry({
getSession: async () => ({ sessionId: "sid-rm", privateStoreId: "priv" }),
normalizeId: (u: string) => u,
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
provisionRetry: { attempts: 1 },
});
return ng;
}
@@ -99,8 +97,6 @@ test("a doc that fails to read is skipped, not aborting the batch", async () =>
configureStoreRegistry({
getSession: async () => ({ sessionId: "sid-rm", privateStoreId: "priv" }),
normalizeId: (u: string) => u,
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
provisionRetry: { attempts: 1 },
});
const subjects = await readUnion(["did:ng:o:ok", "did:ng:o:bad"]);
+30 -18
View File
@@ -112,12 +112,18 @@ function makeFakeNg() {
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
// Pointer SELECT: `<shim:root> <shim:shimDoc> ?shimDoc` in the store-root graph.
if (query.includes("<urn:ng-eventually:shim:shimDoc>")) {
const bindings = quads
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:shimDoc")
.map((q) => ({ shimDoc: { value: q.o } }));
return { results: { bindings } };
}
if (query.includes("<urn:ng-eventually:shim:id>")) {
// Account SELECT, scoped to the anchor graph. Two shapes: the full scan
// (`?acc a <Account>`) and the TARGETED bounded resolve (`<subj> a
// <Account>`) which binds one subject — honour that subject so the bounded
// query returns exactly that account (or nothing).
const subjM = query.match(/GRAPH <[^>]+>\s*\{\s*<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
// Account SELECT, anchored to the doc-shim's default graph (records live in the
// doc-shim now, no GRAPH wrapper). Two shapes: the full scan (`?acc a <Account>`)
// and the TARGETED bounded resolve (`<subj> a <Account>`) — honour the subject.
const subjM = query.match(/<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/);
const onlySubject = subjM ? subjM[1]! : null;
const bySubject = new Map<string, Record<string, string>>();
for (const q of quads) {
@@ -158,8 +164,6 @@ function inject() {
configureStoreRegistry({
getSession: async () => SESSION,
normalizeId: (u) => u.trim().replace(/^@+/, "").toLowerCase(),
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
provisionRetry: { attempts: 1 },
});
resetRegistryCache();
return ng;
@@ -170,22 +174,31 @@ beforeEach(() => {
fake = inject();
});
test("ensureAccount creates 3 scope docs and persists them to the shim", async () => {
test("ensureAccount creates 3 scope docs and persists them to the doc-shim", async () => {
const rec = await ensureAccount("Alice");
expect(rec.id).toBe("Alice");
expect(fake.doc_create).toHaveBeenCalledTimes(3);
// 4 doc_create: 1 doc-shim (first login, resolveShimDoc) + 3 scope docs.
expect(fake.doc_create).toHaveBeenCalledTimes(4);
expect(rec.docPublic).toMatch(/^did:ng:o:doc/);
expect(rec.docProtected).not.toBe(rec.docPublic);
expect(rec.docPrivate).not.toBe(rec.docProtected);
// Persisted into the shim anchor graph (did:ng:PRIV).
expect(fake.sparql_update.mock.calls[0]![2]).toBe("did:ng:PRIV");
// The pointer (store-root -> doc-shim) was written into the store-root graph.
const pointerWrite = fake.sparql_update.mock.calls.find(
(c) => (c[1] as string).includes("<urn:ng-eventually:shim:shimDoc>"),
);
expect(pointerWrite?.[2]).toBe("did:ng:PRIV");
// The account record was persisted into the doc-shim (a did:ng:o: repo), not the root.
const recordWrite = fake.sparql_update.mock.calls.find(
(c) => (c[1] as string).includes("<urn:ng-eventually:shim:docPublic>"),
);
expect(recordWrite?.[2]).toMatch(/^did:ng:o:doc/);
});
test("ensureAccount is idempotent (case/@-insensitive key), no extra docs", async () => {
const a = await ensureAccount("Alice");
const b = await ensureAccount("@alice");
expect(b).toEqual(a);
expect(fake.doc_create).toHaveBeenCalledTimes(3); // not 6
expect(fake.doc_create).toHaveBeenCalledTimes(4); // 1 doc-shim + 3 scope docs, not 7
});
test("ensureAccount de-dupes CONCURRENT provisions (anti-fork): one account, 3 docs", async () => {
@@ -202,8 +215,9 @@ test("ensureAccount de-dupes CONCURRENT provisions (anti-fork): one account, 3 d
ensureAccount("BOB"),
ensureAccount("bob"),
]);
// Exactly ONE set of 3 docs was created — not 5×3.
expect(fake.doc_create).toHaveBeenCalledTimes(3);
// ONE set of 3 scope docs + 1 doc-shim (resolveShimDoc de-dupes concurrent pointer
// resolution too) — 4 total, not 5×3.
expect(fake.doc_create).toHaveBeenCalledTimes(4);
// Every caller got the SAME record (same docs), so writer/reader can never
// disagree on the canonical scope doc.
for (const r of results) expect(r).toEqual(results[0]!);
@@ -236,8 +250,6 @@ test("resolveScopeGraph maps scopes to native store NURIs (no store-id leaks to
protectedStoreId: "PROT",
publicStoreId: "PUB",
}),
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
provisionRetry: { attempts: 1 },
});
resetRegistryCache();
expect(await resolveScopeGraph("private")).toBe("did:ng:PRIV");
@@ -384,10 +396,10 @@ test("normalizeId defaults to trim when not provided", async () => {
const ng = makeFakeNg();
configure({ ng: ng as any, useShape: (() => {}) as any });
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
configureStoreRegistry({ getSession: async () => SESSION, provisionRetry: { attempts: 1 } });
configureStoreRegistry({ getSession: async () => SESSION });
resetRegistryCache();
const a = await ensureAccount(" Ivy ");
const b = await ensureAccount("Ivy"); // trimmed key matches
expect(b).toEqual(a);
expect(ng.doc_create).toHaveBeenCalledTimes(3);
expect(ng.doc_create).toHaveBeenCalledTimes(4); // 1 doc-shim + 3 scope docs
});
+1 -1
View File
@@ -50,7 +50,7 @@ function inject(failFor?: Set<string>) {
const ng = makeFakeNg(failFor);
configure({ ng: ng as any, useShape: (() => {}) as any });
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
configureStoreRegistry({ getSession: async () => SESSION, provisionRetry: { attempts: 1 } });
configureStoreRegistry({ getSession: async () => SESSION });
return ng;
}
+17 -1
View File
@@ -103,6 +103,15 @@ function makeFake(opts?: { holdState?: boolean }) {
const p = m[1] ?? "urn:ng-eventually:shim:Account";
const o = m[2] !== undefined ? unescapeLiteral(m[2]) : (m[3] ?? "");
quads.push({ g, s, p, o });
// The doc-shim (named by the write-once pointer triple) is INFRASTRUCTURE, like
// the store-root: `doc_create` bootstrapped it into the session, so its barrier
// `State` is immediately available. Pre-release it so `holdState` (which gates the
// per-ENTITY docs the tests control) never blocks the doc-shim open. The pointer is
// published BEFORE the doc-shim barrier open (resolveShimDoc first-login order).
if (p === "urn:ng-eventually:shim:shimDoc") {
released.add(o);
for (const sub of subs) if (sub.nuri === o) sub.cb({ V0: { State: {} } });
}
}
// A write to a subscribed doc fires a Patch push (reactivity signal).
for (const sub of subs) {
@@ -114,9 +123,16 @@ function makeFake(opts?: { holdState?: boolean }) {
const sparql_query = mock(async (...a: unknown[]) => {
const query = a[1] as string;
const anchor = a[3] as string | undefined;
// Pointer SELECT (store-root -> doc-shim).
if (query.includes("<urn:ng-eventually:shim:shimDoc>")) {
const bindings = quads
.filter((q) => q.g === anchor && q.p === "urn:ng-eventually:shim:shimDoc")
.map((q) => ({ shimDoc: { value: q.o } }));
return { results: { bindings } };
}
if (query.includes("<urn:ng-eventually:shim:id>")) {
const subjM = query.match(
/GRAPH <[^>]+>\s*\{\s*<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/,
/<([^>]+)>\s+a\s+<urn:ng-eventually:shim:Account>/,
);
const onlySubject = subjM ? subjM[1]! : null;
const bySubject = new Map<string, Record<string, string>>();