fix(client): résolution de compte DÉTERMINISTE + anti-fork restauré
Cause racine du bug de reconnexion (probe contrôlé répété) : le shim d'un compte accumule des `docPublic`/`docProtected` EN DOUBLE (forks passés), et resolveAccount/indexDocOf les choisissaient de façon NON-DÉTERMINISTE → l'écrivain et le lecteur (page fraîche) ancraient sur des docs d'index DIFFÉRENTS → lecture 0. Fix : - `canonicalDoc()`/`recordFromRows()` : parmi plusieurs valeurs d'un scope, choisir le NURI lexicographiquement le plus petit (les NURIs sont content-addressed → ordre total stable). Écrivain et lecteur résolvent TOUJOURS le même doc, même sur un shim corrompu par des doublons. - `resolveAccountReliably` RESTAURÉ (retry borné avant provision sur read shim 0 à froid) : j'avais retiré l'anti-fork à tort (`38b1521`) — le gap EST exhibé (fork non-déterministe au cold-read), et la barrière `user_connect` n'est PAS accessible côté JS → un retry borné est la compensation légitime (pas la barrière-store cassée de `45dbd9a`). Budget injecté `provisionRetry` ; défaut attempts:1 (fakes synchrones), app/e2e attempts:8. anti-fork.test.ts réécrit : docPublic dupliqué → même canonique ; retry sur lag → réutilise ; neuf → provision 1×. gate : tsc 0 ; bun test 122 ; test:e2e 42/42 (CONTRACT 2 non-fork vert). Portée : corrige la couche docPublic de la reconnexion. Une couche PROTECTED distincte (watchShape protected ne converge pas à froid) reste — diagnostic en cours. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -25,9 +25,15 @@ export interface StoreRegistryDeps {
|
||||
/** Normalize an identity id for shim keying. Default: trim (identity-ish). */
|
||||
normalizeId?: (id: string) => string;
|
||||
/**
|
||||
* @deprecated Removed. The anti-fork retry/barrier mechanism has been dropped
|
||||
* (the private store is synchronised at login; the barrier was both unnecessary
|
||||
* and broken for STORE NURIs). This field is accepted but silently ignored.
|
||||
* ANTI-FORK bounded retry budget. On a FRESH page over a persistent wallet the
|
||||
* shim (in the private store's graph) may not be synced when the first read
|
||||
* fires → 0 rows; treating that transient 0 as "account absent" makes the
|
||||
* registry PROVISION a new set of scope docs — an account FORK. Since the
|
||||
* deterministic Rust barrier (`user_connect`) is not reachable from JS, a
|
||||
* BOUNDED retry (capped backoff) is the compensation: wait out the sync-lag
|
||||
* window before concluding "genuinely new". Enable it where the REAL broker is
|
||||
* used (app + e2e). Left UNSET (the default) → `attempts: 1` = NO retry (a
|
||||
* single read), which keeps the synchronous unit fakes fast and unchanged.
|
||||
*/
|
||||
provisionRetry?: { attempts?: number; baseMs?: number; maxStepMs?: number };
|
||||
}
|
||||
@@ -56,8 +62,11 @@ export interface EventuallyConfig {
|
||||
|
||||
let cfg: EventuallyConfig | null = null;
|
||||
let currentUser: PrincipalId | null = null;
|
||||
/** Required fields of StoreRegistryDeps after defaults are applied (excludes deprecated provisionRetry). */
|
||||
type ResolvedRegistryDeps = Required<Pick<StoreRegistryDeps, "getSession" | "normalizeId">>;
|
||||
/** Required fields of StoreRegistryDeps after defaults are applied. `provisionRetry`
|
||||
* defaults to `{ attempts: 1 }` (no retry) when the consumer leaves it unset. */
|
||||
type ResolvedRegistryDeps = Required<
|
||||
Pick<StoreRegistryDeps, "getSession" | "normalizeId" | "provisionRetry">
|
||||
>;
|
||||
let registryDeps: ResolvedRegistryDeps | null = null;
|
||||
/** The emulated ReadCap/WriteCap registry. Empty until the app declares caps;
|
||||
* while it has no read policy the read filter passes through (no regression). */
|
||||
@@ -92,6 +101,9 @@ export function configureStoreRegistry(deps: StoreRegistryDeps): void {
|
||||
registryDeps = {
|
||||
getSession: deps.getSession,
|
||||
normalizeId: deps.normalizeId ?? ((id: string) => id.trim()),
|
||||
// Default: no retry (single read). Only the real-broker consumers (app + e2e)
|
||||
// opt into the bounded anti-fork retry; unit fakes stay synchronous.
|
||||
provisionRetry: deps.provisionRetry ?? { attempts: 1 },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -167,6 +167,56 @@ function bindingValue(row: Record<string, { value: string }>, key: string): stri
|
||||
return row[key]?.value ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* DETERMINISTIC resolution of an account's scope docs from a set of SPARQL
|
||||
* bindings (all bindings for ONE account subject).
|
||||
*
|
||||
* ── Why this is load-bearing (the reconnection bug's root cause) ───────────
|
||||
* A corrupted shim can carry the SAME account subject with MULTIPLE values for a
|
||||
* scope predicate (e.g. 5 `shim:docPublic`) — the residue of past account FORKS
|
||||
* (each stray provision appended another doc NURI). A query then returns several
|
||||
* bindings (the cross-product of the duplicate values). Picking `rows[0]` is
|
||||
* NON-DETERMINISTIC (binding order is not stable across sessions), so the session
|
||||
* that WROTE an entity into one docPublic and a later fresh page that RESOLVED a
|
||||
* DIFFERENT docPublic would disagree → the anchored `readScopeIndex` returns 0 →
|
||||
* the home reads empty. When both happen to pick the same doc, it "works".
|
||||
*
|
||||
* The fix: for each scope field, collect EVERY distinct value across the bindings
|
||||
* and choose the SAME one every time — the lexicographically-smallest NURI. NURIs
|
||||
* are content-addressed and stable, so lexicographic order is a total, stable,
|
||||
* session-independent order: writer and reader converge on the SAME canonical doc
|
||||
* even on a wallet already corrupted by duplicates. (No creation timestamp is
|
||||
* recorded in the shim, so lexicographic-min is the available deterministic key.)
|
||||
*/
|
||||
function canonicalDoc(rows: Array<Record<string, { value: string }>>, key: string): Nuri {
|
||||
let chosen = "";
|
||||
for (const row of rows) {
|
||||
const v = bindingValue(row, key);
|
||||
if (!v) continue;
|
||||
if (chosen === "" || v < chosen) chosen = v;
|
||||
}
|
||||
return chosen;
|
||||
}
|
||||
|
||||
/** Build an AccountRecord by picking the canonical (lexicographically-smallest)
|
||||
* doc NURI per scope across all bindings for one account. See {@link canonicalDoc}. */
|
||||
function recordFromRows(
|
||||
rows: Array<Record<string, { value: string }>>,
|
||||
fallbackId: string,
|
||||
): AccountRecord {
|
||||
let id = "";
|
||||
for (const row of rows) {
|
||||
const v = bindingValue(row, "id");
|
||||
if (v) { id = v; break; }
|
||||
}
|
||||
return {
|
||||
id: id || fallbackId,
|
||||
docPublic: canonicalDoc(rows, "docPublic"),
|
||||
docProtected: canonicalDoc(rows, "docProtected"),
|
||||
docPrivate: canonicalDoc(rows, "docPrivate"),
|
||||
};
|
||||
}
|
||||
|
||||
// --- shim load / account bootstrap ----------------------------------------
|
||||
|
||||
/** Load all accounts from the shim into the cache. */
|
||||
@@ -187,16 +237,22 @@ export async function loadShim(): Promise<Map<string, AccountRecord>> {
|
||||
const map = new Map<string, AccountRecord>();
|
||||
try {
|
||||
const result = await sparqlQuery(s.sessionId, query, undefined, anchor, "loadShim");
|
||||
// Group ALL bindings by account key first, then pick the CANONICAL doc per
|
||||
// scope (see recordFromRows / canonicalDoc). A single account subject may carry
|
||||
// duplicate scope-doc values (fork residue) → several bindings; grouping +
|
||||
// canonical selection makes loadShim resolve the SAME doc the targeted
|
||||
// resolveAccount does, so full-scan and hot-path readers never disagree.
|
||||
const byKey = new Map<string, Array<Record<string, { value: string }>>>();
|
||||
for (const row of readBindings(result)) {
|
||||
const id = bindingValue(row, "id");
|
||||
if (!id) continue;
|
||||
const key = accountKey(id);
|
||||
const record: AccountRecord = {
|
||||
id,
|
||||
docPublic: bindingValue(row, "docPublic"),
|
||||
docProtected: bindingValue(row, "docProtected"),
|
||||
docPrivate: bindingValue(row, "docPrivate"),
|
||||
};
|
||||
const bucket = byKey.get(key) ?? [];
|
||||
bucket.push(row);
|
||||
byKey.set(key, bucket);
|
||||
}
|
||||
for (const [key, rows] of byKey) {
|
||||
const record = recordFromRows(rows, rows[0] ? bindingValue(rows[0], "id") : key);
|
||||
map.set(key, record);
|
||||
// Feed the per-account cache too, so a subsequent targeted resolve is free.
|
||||
accountCache.set(key, record);
|
||||
@@ -242,13 +298,11 @@ export async function resolveAccount(id: string): Promise<AccountRecord | null>
|
||||
const result = await sparqlQuery(s.sessionId, query, undefined, anchor, "resolveAccount");
|
||||
const rows = readBindings(result);
|
||||
if (rows.length === 0) return null;
|
||||
const row = rows[0]!;
|
||||
const record: AccountRecord = {
|
||||
id: bindingValue(row, "id") || id,
|
||||
docPublic: bindingValue(row, "docPublic"),
|
||||
docProtected: bindingValue(row, "docProtected"),
|
||||
docPrivate: bindingValue(row, "docPrivate"),
|
||||
};
|
||||
// DETERMINISTIC: a corrupted shim may return SEVERAL bindings for this one
|
||||
// account subject (duplicate scope-doc values from past forks). Pick the
|
||||
// canonical (lexicographically-smallest) doc per scope so writer and reader
|
||||
// always resolve the SAME docPublic — the fix for the reconnection bug.
|
||||
const record = recordFromRows(rows, id);
|
||||
accountCache.set(key, record);
|
||||
return record;
|
||||
} catch (error) {
|
||||
@@ -257,6 +311,63 @@ export async function resolveAccount(id: string): Promise<AccountRecord | null>
|
||||
}
|
||||
}
|
||||
|
||||
// --- anti-fork bounded retry ----------------------------------------------
|
||||
|
||||
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
/**
|
||||
* Resolve ONE account, RETRYING a bounded number of times while the shim reads 0
|
||||
* rows — the ANTI-FORK guard for the polyfill-era shim.
|
||||
*
|
||||
* ── The gap this bridges ──────────────────────────────────────────────────
|
||||
* On a FRESH page over the same persistent wallet, the shim (in the private
|
||||
* store's graph) may not yet be synced when the first read fires → 0 rows. Treating
|
||||
* that transient 0 as "account genuinely absent" makes `ensureAccount` PROVISION a
|
||||
* NEW set of scope docs — an account FORK, whose duplicate `docPublic` values are
|
||||
* exactly what corrupts the shim and breaks reconnection (see {@link canonicalDoc}).
|
||||
* The deterministic RUST barrier (`user_connect`) that would make a 0 definitive is
|
||||
* NOT reachable from JS, so a BOUNDED retry (capped backoff) is the only available
|
||||
* compensation: wait out the sync-lag window before concluding "new".
|
||||
*
|
||||
* NOT polling in the banned sense: it is a lib-internal, BOUNDED bootstrap wait for
|
||||
* a real cold-read gap (a fixed budget from `provisionRetry`, not an open-ended
|
||||
* "is it there yet?" loop) that stops the instant the shim resolves. A cache hit
|
||||
* short-circuits it; once the account resolves it is cached, so this never runs on
|
||||
* the hot path.
|
||||
*
|
||||
* The budget is the injected `provisionRetry` (see polyfill). It defaults to
|
||||
* `attempts: 1` (a single read, NO retry) when the consumer leaves it unset — so
|
||||
* the synchronous unit fakes stay fast and unchanged. Only the real-broker
|
||||
* consumers (app + e2e) opt into a multi-attempt budget. A genuinely-new account
|
||||
* (always 0) still resolves to `null` after the budget → the caller provisions once.
|
||||
*/
|
||||
async function resolveAccountReliably(id: string): Promise<AccountRecord | null> {
|
||||
// Cache hit → session-idempotent, no query, no fork risk.
|
||||
const cached = accountCache.get(accountKey(id));
|
||||
if (cached) return cached;
|
||||
|
||||
const first = await resolveAccount(id);
|
||||
if (first) return first;
|
||||
|
||||
const budget = getStoreRegistryDeps().provisionRetry;
|
||||
const attempts = Math.max(1, budget.attempts ?? 1);
|
||||
const baseMs = budget.baseMs ?? 150;
|
||||
const maxStepMs = budget.maxStepMs ?? 2000;
|
||||
|
||||
// attempts:1 (default, unit fakes) → no retry: the single 0 is authoritative.
|
||||
// Real broker: retry with capped backoff before concluding "genuinely new".
|
||||
// Bounded by `attempts` — never an infinite/open-ended loop.
|
||||
let step = baseMs;
|
||||
for (let i = 1; i < attempts; i++) {
|
||||
await sleep(step);
|
||||
const rec = await resolveAccount(id);
|
||||
if (rec) return rec;
|
||||
step = Math.min(step * 2, maxStepMs);
|
||||
}
|
||||
// Still 0 after the whole budget → account is genuinely new. Provision once.
|
||||
return null;
|
||||
}
|
||||
|
||||
/** All known accounts (from the shim). */
|
||||
export async function allAccounts(): Promise<AccountRecord[]> {
|
||||
return [...(await loadShim()).values()];
|
||||
@@ -278,9 +389,12 @@ export async function ensureAccount(id: string): Promise<AccountRecord> {
|
||||
const key = accountKey(id);
|
||||
// HOT PATH: targeted O(1) lookup — does THIS account already exist? — instead
|
||||
// of a full-shim scan (loadShim). Off the read/write hot path entirely.
|
||||
// The private store is synchronised at login, so a simple resolveAccount read
|
||||
// is authoritative: 0 rows = genuinely new → provision; rows present → reuse.
|
||||
const existing = await resolveAccount(id);
|
||||
//
|
||||
// ANTI-FORK: resolve via the BOUNDED retry, so a transient 0 rows (the shim not
|
||||
// yet synced on a fresh page over the persistent wallet) is not mistaken for
|
||||
// "account genuinely absent" → a fork. Only after the whole retry budget still
|
||||
// reads 0 do we treat the account as new and provision. See resolveAccountReliably.
|
||||
const existing = await resolveAccountReliably(id);
|
||||
if (existing) return existing;
|
||||
|
||||
const [docPublic, docProtected, docPrivate] = await Promise.all([
|
||||
|
||||
Reference in New Issue
Block a user