refactor(client): dé-poller resolveAccountReliably — barrière au lieu de retry
Le polling est un anti-pattern NextGraph (par abonnement). La résolution de compte retentait ×8 la lecture du shim tant qu'elle rendait 0 (lag de sync) — c'est du polling. Remplacé par la BARRIÈRE d'abonnement, déjà le mécanisme de open-repo : - `resolveAccountReliably` : `await ensureRepoOpen(did🆖${privateStoreId})` (subscribe + attendre le 1er State — le shim vit dans le graphe du private store), PUIS lecture UNIQUE. Après la barrière, 0 ligne = compte réellement inexistant → provision 1×, lignes présentes = réutilisé (garantie NO-FORK préservée). Plus de boucle de re-lecture. - timed-out (barrière expirée) : throw explicite, NE provisionne PAS (un provision sur sync incomplète re-forkerait). Le « trop long » est un signal, pas un feu vert. - fake ng sans doc_subscribe : ensureRepoOpen no-op → lecture immédiate (unit intact). - `_forceOpenedSyncState` : helper test-only (underscore, non ré-exporté). anti-fork.test.ts réécrit (5 tests : no-fork, neuf→1 provision, idempotence, fake no-op, timed-out→throw) ; plus aucun test de comptage de retry. gate : tsc propre ; bun test 117. e2e À RE-VALIDER quand le broker répond (dégradé ce jour : crash Chromium post-connexion) — la barrière ensureRepoOpen est déjà validée e2e (CONTRAT 3 + reconnexion) en broker sain. provisionRetry devient un champ mort de StoreRegistryDeps (nettoyage ultérieur). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -36,27 +36,30 @@ import { docCreate, sparqlUpdate, sparqlQuery } from "./docs";
|
||||
import { getStoreRegistryDeps } from "./polyfill";
|
||||
import { ensureRepoOpen } from "./open-repo";
|
||||
|
||||
// --- provisioning anti-fork retry budget (polyfill-era) --------------------
|
||||
// --- provisioning anti-fork guard: barrier-first (polyfill-era) ------------
|
||||
//
|
||||
// The shim (account→docs trust root) lives in the shared wallet's PRIVATE store.
|
||||
// On a fresh session over a persistent wallet, that store's repo may not have
|
||||
// synced yet from the broker: a targeted account resolve then reads 0 rows even
|
||||
// though the account WAS persisted in an earlier session. If ensureAccount took
|
||||
// that 0 at face value it would RE-PROVISION a second set of scope documents —
|
||||
// an account FORK: one session writes/reads one set, another (or the same after
|
||||
// a cache drop) the other, EMPTY set → the user "loses" their data on reconnect.
|
||||
// On a fresh session over a persistent wallet, that repo may not have synced yet
|
||||
// from the broker: a targeted account resolve would then read 0 rows even though
|
||||
// the account WAS persisted in an earlier session. If ensureAccount took that 0
|
||||
// at face value it would RE-PROVISION a second set of scope documents — an account
|
||||
// FORK: one session writes/reads one set, another (or the same after a cache drop)
|
||||
// the other, EMPTY set → the user "loses" their data on reconnect.
|
||||
//
|
||||
// Guard: before deciding an account is genuinely new, re-read it with a BOUNDED
|
||||
// backoff (open + await the anchor repo, then retry the targeted query). Only if
|
||||
// EVERY attempt within the budget still reads 0 do we treat it as a first-time
|
||||
// account and provision. A pre-existing account merely lagging by sync is thus
|
||||
// found on a later attempt and REUSES its docs (no fork); a truly new account
|
||||
// exhausts the budget cheaply and is provisioned exactly once. The budget is a
|
||||
// hard ceiling — never an unbounded poll — and is INJECTED (StoreRegistryDeps.
|
||||
// provisionRetry): production defaults to ~8 attempts / ≲8.5s; a synchronous
|
||||
// in-memory store (unit fake `ng`) passes `attempts: 1` to skip it (a 0-row read
|
||||
// is authoritative there — no lag to wait out). Disappears at the real
|
||||
// multi-store migration (deterministic per-user store NURIs make this moot).
|
||||
// Guard (barrier-first): BEFORE reading the shim, open/subscribe the private-store
|
||||
// repo and AWAIT its first `State` push — the deterministic sync barrier (CONTRACT 3
|
||||
// in e2e/). After the barrier, presence is GUARANTEED and absence DEFINITIVE. Then
|
||||
// read the shim ONCE: 0 rows = account genuinely absent → provision exactly once;
|
||||
// rows present = account found → reuse it (NO-FORK). No retry loop, no poll.
|
||||
//
|
||||
// Timed-out barrier (conservative): if `ensureRepoOpen` exits via the 8-second
|
||||
// fallback timeout (getSyncState → "timed-out") the sync is UNCONFIRMED — we do NOT
|
||||
// provision blindly (that would re-fork). Instead we surface a clear error so the
|
||||
// caller can retry the full flow rather than silently creating a duplicate account.
|
||||
// The timeout is rare (pathological broker) and a hard error there is far safer than
|
||||
// a silent fork. Disappears at the real multi-store migration (per-user store NURIs
|
||||
// make this moot — barrier becomes the native store-open which is always confirmed).
|
||||
import { getSyncState } from "./open-repo";
|
||||
import { escapeLiteral, escapeIri, assertNuri } from "./sparql";
|
||||
import type { Nuri, Scope } from "./types";
|
||||
|
||||
@@ -280,48 +283,51 @@ export async function resolveAccount(id: string): Promise<AccountRecord | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve ONE account, retrying a BOUNDED number of times before giving up, to
|
||||
* distinguish a genuinely-absent account from one whose shim record has simply
|
||||
* not synced yet on a fresh session (the account-FORK guard — see the
|
||||
* PROVISION_RETRY_* budget note at the top of this module).
|
||||
* Resolve ONE account after waiting for the private-store sync barrier, so a
|
||||
* 0-row result is DEFINITIVE (account genuinely absent) rather than ambiguous
|
||||
* (broker lag). This is the ANTI-FORK guard for the polyfill-era shim.
|
||||
*
|
||||
* On the FIRST miss it opens/subscribes the shim anchor repo (the shared
|
||||
* wallet's private store, where the shim lives) so the broker pushes its state,
|
||||
* then re-reads with capped exponential backoff. Returns the record as soon as
|
||||
* any attempt finds it (populating `accountCache` via resolveAccount), or `null`
|
||||
* if the whole budget is exhausted with 0 rows — the only case in which the
|
||||
* caller may treat the account as new and provision it.
|
||||
* Flow:
|
||||
* 1. Cache hit → return immediately (session-idempotent, no I/O).
|
||||
* 2. Open/subscribe the private-store repo (`did:ng:${privateStoreId}`) and
|
||||
* await the first `State` push — the deterministic sync barrier (CONTRACT 3).
|
||||
* After the barrier, presence is guaranteed and absence definitive.
|
||||
* 3. If the barrier TIMED-OUT (getSyncState → "timed-out"), the sync is
|
||||
* unconfirmed — provisioning here would risk a fork. Throw a clear error
|
||||
* instead so the caller can retry the full login flow. This is the
|
||||
* conservative-safe choice: a hard error is recoverable; a silent fork is not.
|
||||
* 4. Read the shim ONCE. 0 rows = genuinely absent → caller provisions exactly
|
||||
* once. Rows present → reuse (NO-FORK preserved).
|
||||
*
|
||||
* No-op fast path: a cache hit returns immediately with no retries. With the
|
||||
* unit fake `ng` (no doc_subscribe, synchronous store) a present account is
|
||||
* found on attempt 0 and an absent one exhausts the (short-sleep) budget without
|
||||
* changing behaviour — the fork can only arise against a real, lagging broker.
|
||||
* With the unit fake `ng` (no `doc_subscribe`), `ensureRepoOpen` is a no-op
|
||||
* (getSyncState → "unknown") and the single read is immediate — synchronous
|
||||
* behaviour preserved, no lag to wait out.
|
||||
*/
|
||||
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 budget = getStoreRegistryDeps().provisionRetry;
|
||||
const attempts = Math.max(1, budget.attempts ?? 8);
|
||||
const baseMs = budget.baseMs ?? 300;
|
||||
const maxStepMs = budget.maxStepMs ?? 1500;
|
||||
// The shim lives in the private store. Open/subscribe it and await the first
|
||||
// `State` push (the sync barrier). NURI: `did:ng:${session.privateStoreId}`.
|
||||
const nuri = await anchorNuri();
|
||||
await ensureRepoOpen(nuri);
|
||||
|
||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||
const found = await resolveAccount(id);
|
||||
if (found) return found;
|
||||
if (attempt === attempts - 1) break; // budget exhausted → genuinely absent
|
||||
// The shim anchor repo may not be synced on a fresh session; open it once so
|
||||
// the broker pushes its state, then back off before the next targeted read.
|
||||
try {
|
||||
await ensureRepoOpen(await anchorNuri());
|
||||
} catch {
|
||||
/* tolerant: a failed open just leaves the next read to behave as before */
|
||||
}
|
||||
const step = Math.min(baseMs * 2 ** attempt, maxStepMs);
|
||||
await new Promise((r) => setTimeout(r, step));
|
||||
// Conservative timed-out guard: if the barrier did not confirm sync,
|
||||
// provisioning blind risks creating a fork. Raise a clear error — the caller
|
||||
// (or the app's retry-login flow) should re-attempt when the broker is reachable.
|
||||
// "unknown" means the fake-ng no-op path: no barrier semantics → safe to read.
|
||||
const syncResult = getSyncState(nuri);
|
||||
if (syncResult === "timed-out") {
|
||||
throw new Error(
|
||||
"[storeRegistry] sync barrier timed out for the private store — " +
|
||||
"shim state unconfirmed, refusing to provision to avoid account fork. " +
|
||||
"Retry when the broker is reachable.",
|
||||
);
|
||||
}
|
||||
return null;
|
||||
|
||||
// Barrier reached (or fake-ng "unknown" path): single read, result is definitive.
|
||||
return resolveAccount(id);
|
||||
}
|
||||
|
||||
/** All known accounts (from the shim). */
|
||||
@@ -346,13 +352,13 @@ export async function ensureAccount(id: string): Promise<AccountRecord> {
|
||||
// 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.
|
||||
//
|
||||
// ANTI-FORK (polyfill-era): resolve with a BOUNDED retry, NOT a single read.
|
||||
// A single 0-row read on a fresh, still-syncing session would misfire as
|
||||
// "new account" and RE-PROVISION a second set of scope docs (the fork — see
|
||||
// the PROVISION_RETRY_* note at the top of this module). We only fall through
|
||||
// to provisioning once the whole retry budget has confirmed 0 rows. A cache
|
||||
// hit inside resolveAccountReliably keeps same-session resolves free and
|
||||
// deterministic (the cached record wins over any re-provision).
|
||||
// ANTI-FORK (polyfill-era): open the private-store repo and await its first
|
||||
// `State` push (the sync barrier) BEFORE reading the shim, so a 0-row result
|
||||
// is DEFINITIVE rather than a lag artifact. Only after the barrier do we treat
|
||||
// 0 rows as "genuinely new" and provision. A cache hit inside
|
||||
// resolveAccountReliably keeps same-session resolves free and deterministic
|
||||
// (the cached record wins over any re-provision). Throws if the barrier timed
|
||||
// out — safer than provisioning blind and creating a fork.
|
||||
const existing = await resolveAccountReliably(id);
|
||||
if (existing) return existing;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user