fix: un rejet tardif ne ferme plus un canal vivant, un registre illisible ne perd plus toutes les inbox

This commit is contained in:
Sylvain Duchesne
2026-08-17 12:17:59 +02:00
parent 6eaff0b985
commit 7b35300723
5 changed files with 364 additions and 62 deletions
@@ -35,6 +35,7 @@ import { resolveAccount, userInbox } from "../src/shared-wallet/account-registry
import { observationSettled } from "../src/emulated-verifier/inbox-observer";
import { cancelScheduledInboxProcessing } from "../src/emulated-verifier/inbox-processor";
import { connectedUser } from "../src/emulated-verifier/connect";
import { enumerateMyInboxes, myInboxes } from "../src/emulated-verifier/branch-registers";
import { setOpenTimeoutForTests } from "../src/emulated-verifier/open-repo";
import { bootPage, forgetEverything, signIn, type FakeWallet, type Quad } from "./wallet-fake";
import type { Nuri } from "../src/model/types";
@@ -353,7 +354,7 @@ describe("a deposit that cannot be applied", () => {
expect(getCaps().capForHolder("alice", first.doc)).toBeDefined();
});
test("because its inbox could not be WATCHED is reported, and attempted again", async () => {
test("because its inbox could not be WATCHED is reported, and the next signal re-attempts it", async () => {
const { doc, inTransit } = await bobSharesWithAlice();
const aliceInbox = await userInbox("alice", "protected");
@@ -387,9 +388,14 @@ describe("a deposit that cannot be applied", () => {
await converge();
expect(getCaps().capForHolder("alice", doc)).toBeUndefined();
// The broker recovers and Alice does something ordinary. The inbox that could not be
// opened was not written off for the session: it is subscribed to on the next
// enumeration, and its initial push finds the deposit still waiting.
// The broker recovers and Alice does something ordinary — which is a SIGNAL, not a
// coincidence: creating anything files caps, and the held-caps channel re-enters the
// enumeration. That is the whole of the repair, and it is deliberately the whole of it:
// a re-attempt fired from the rejection itself asks the broker that has just refused, in
// the same turn, with nothing having changed. The inbox that could not be opened was not
// written off for the session — the failed entry is forgotten, so this enumeration
// subscribes again as if it had never been attempted, and the initial push of that new
// subscription finds the deposit still waiting.
refusing = false;
await storeRegistry.createEntityDoc("protected");
await converge();
@@ -422,18 +428,30 @@ describe("a deposit that cannot be applied", () => {
});
describe("a connection whose own work FAILED", () => {
test("still leaves the identity watched — being connected is what is observed", async () => {
/**
* Aimed at the PRIVATE store, and that is the whole test.
*
* It used to fail reads on `docPublic`, which makes the restore reject and leaves the
* enumeration of the inboxes untouched — so it proved that watching survives a failure that
* was never going to threaten it. The private store is the one the connection restores from
* AND the register that says which inboxes exist, so failing it is the case that actually
* decides: listing the inboxes reads it, and one throw used to discard the two user inboxes
* that had ALREADY been listed before it. The identity was then connected with nothing
* watched at all, and a person who only reads — who never creates anything, so never fires
* a signal — had no way back for the rest of the session.
*/
test("still leaves the identity watched — including when the failing store is the register", async () => {
const { doc, inTransit } = await bobSharesWithAlice();
// The broker cannot answer for one of Alice's own stores, so the RESTORE fails and the
// The broker cannot answer for Alice's private store, so the RESTORE fails and the
// connection rejects. She is connected regardless: `setCurrentUser` is synchronous and
// took effect before any of this ran, and nothing signs her back out.
const store = (await resolveAccount("alice"))?.docPublic;
if (store === undefined) throw new Error("the fixture did not give Alice a public store");
const store = (await resolveAccount("alice"))?.docPrivate;
if (store === undefined) throw new Error("the fixture did not give Alice a private store");
fake._failReadsOn.add(store);
setCurrentUser("alice");
let rejected = false;
await whileWatchingTheLog(async () => {
const reported = await whileWatchingTheLog(async () => {
try {
await connectedUser();
} catch {
@@ -444,17 +462,86 @@ describe("a connection whose own work FAILED", () => {
// The caller is still TOLD, and that rule is not what changes here: failing to reach the
// registers rejects, exactly as before.
expect(rejected).toBe(true);
// …and so is the log, about the half of the list that could not be read. A short list
// that says nothing is a failure wearing the face of an absence, which is the one thing
// this package will not do — the inboxes it names are watched, the ones it does not are
// owed a next enumeration, and both facts have to be legible.
expect(reported.filter((l) => /could not all be listed/.test(l)).length).toBeGreaterThan(0);
expect(reported.find((l) => /could not all be listed/.test(l))).toContain("[alice][polyfill]");
// The hiccup passes. Alice never touched the page.
// The hiccup passes. Alice never touched the page — no sign-in, no document created,
// nothing that could stand in for the watching she is owed.
fake._failReadsOn.delete(store);
fake._deliver(inTransit);
await converge();
// What she is owed is not the restore she lost — it is that a deposit made while she sits
// there converges. Watching used to be the LAST line of the connection work, so a restore
// that rejected skipped it and left her connected with nothing observing her inboxes: one
// hiccup at sign-in, and every share made afterwards was lost to her for the session.
// there converges. Her own two inboxes are where a share addressed to her by NAME lands,
// and they were listed before the register threw; watching them is what makes this
// session behave like every other one.
expect(getCaps().capForHolder("alice", doc)).toBeDefined();
expect(await documentsGivenTo("alice")).toContain(doc);
});
});
/**
* The list the observation works from, asked directly.
*
* It is built from two independent registers — the account record, which names the user's own
* two store inboxes, and the User branch, which names one per document it opened an inbox on
* — and the two fail independently. What a caller may do with a half-read list depends
* entirely on being TOLD it is half-read, so both halves of that answer are pinned here
* rather than only through the behaviour above.
*/
describe("listing the inboxes when one of the two registers cannot be read", () => {
test("comes back as what WAS listed plus the failure — never as a short list", async () => {
await signIn("alice");
// A document inbox: a record on the User branch of the private store, which is the
// register the broker is about to stop answering for.
const note = await storeRegistry.createEntityDoc("public");
await storeRegistry.openDocumentInbox(note);
await converge();
const store = (await resolveAccount("alice"))?.docPrivate;
if (store === undefined) throw new Error("the fixture did not give Alice a private store");
const whole = await enumerateMyInboxes();
expect(whole.incomplete).toBeNull();
expect(whole.inboxes).toContain(inboxOnTheNote(note));
fake._failReadsOn.add(store);
const partial = await enumerateMyInboxes();
fake._failReadsOn.delete(store);
// Her own two inboxes were in hand before the second register threw. Discarding them
// with it is what left an identity connected with ZERO inboxes watched.
expect(partial.inboxes).toEqual([
await userInbox("alice", "public"),
await userInbox("alice", "protected"),
]);
// …and the shortfall travels WITH them: an answer that came back short while looking
// complete is a failure disguised as an absence, which is the fault this package keeps
// closing. The document inbox is missing from the list and that fact is legible.
expect(partial.incomplete).not.toBeNull();
expect(String(partial.incomplete?.error)).toContain("RepoNotFound");
expect(partial.inboxes).not.toContain(inboxOnTheNote(note));
});
test("still REJECTS for the caller that cannot use a partial list", async () => {
await signIn("alice");
await storeRegistry.openDocumentInbox(await storeRegistry.createEntityDoc("public"));
await converge();
const store = (await resolveAccount("alice"))?.docPrivate;
if (store === undefined) throw new Error("the fixture did not give Alice a private store");
fake._failReadsOn.add(store);
try {
// `connect.connectedUser` drains this list, and a queue missing from it is a delivered
// share silently never applied. Not knowing which queues exist is the session failing
// to establish, and that contract is not what the partial answer above relaxes.
await expect(myInboxes()).rejects.toThrow(/RepoNotFound/);
} finally {
fake._failReadsOn.delete(store);
}
});
});
+97 -4
View File
@@ -1,6 +1,7 @@
import { test, expect, mock, afterAll } from "bun:test";
import {
docChangeType,
resubscribeDocs,
subscribeDoc,
subscribeDocReportingSetupFailure,
subscribeDocs,
@@ -40,10 +41,19 @@ const SESSION: RegistrySession = { sessionId: "sid-1", privateStoreId: "PRIV" };
* exactly the assumption that cost this package a view that never re-read and an inbox that
* never notified, and a fake that holds it cannot fail on either.
*/
function makeFakeNg(failFor: Set<string> = new Set()) {
function makeFakeNg(failFor: Set<string> = new Set(), hangFor: Set<string> = new Set()) {
const subs = new Map<string, (r: unknown) => void>();
// A call the broker has neither answered nor refused yet, so a LATER call can overtake it
// and this one can settle afterwards. Held on an object rather than in a `let` so its
// type survives being written from one closure and read from another.
const hung: { reject: ((error: unknown) => void) | null } = { reject: null };
const doc_subscribe = mock(async (nuri: string, _sid: unknown, cb: (r: unknown) => void) => {
if (failFor.has(nuri)) throw new Error(`RepoNotFound: ${nuri}`);
if (hangFor.has(nuri)) {
return await new Promise((_resolve, reject) => {
hung.reject = reject;
});
}
subs.set(nuri, cb); // whoever held this branch is dropped, without a word
// Initial State push, delivered async (as the real RPC does) — and only while this
// callback still holds the branch.
@@ -58,11 +68,17 @@ function makeFakeNg(failFor: Set<string> = new Set()) {
subs.get(nuri)?.({ V0: { Patch: { doc: nuri } } });
};
const isSubscribed = (nuri: string): boolean => subs.has(nuri);
return { doc_subscribe, push, isSubscribed, _subs: subs };
/** The call that was left hanging finally answers — with a refusal. */
const rejectHung = (): void => {
const reject = hung.reject;
hung.reject = null;
reject?.(new Error("RepoNotFound: late"));
};
return { doc_subscribe, push, isSubscribed, rejectHung, _subs: subs };
}
function inject(failFor?: Set<string>) {
const ng = makeFakeNg(failFor);
function inject(failFor?: Set<string>, hangFor?: Set<string>) {
const ng = makeFakeNg(failFor, hangFor);
configure({ ng: ng as any, useShape: (() => {}) as any });
// Synchronous fake store → no sync lag; disable the anti-fork retry backoff.
configureStoreRegistry({ getSession: async () => SESSION });
@@ -321,3 +337,80 @@ test("a caller that asks to be told learns its subscription could not be opened"
expect(String(failures[0])).toContain("RepoNotFound");
stop();
});
/**
* Two establishes over ONE fan-out, and the first one answering last.
*
* `resubscribeDocs` re-opens the channel of a fan-out whose first `doc_subscribe` has not
* settled yet — that is the whole point of it, since the session it was opened against is
* gone — and it re-opens it on the SAME entry so the listeners are kept. The two calls
* therefore race, and the broker is under no obligation to answer them in order.
*/
async function hangingThenReopened(): Promise<{
ng: ReturnType<typeof makeFakeNg>;
failures: unknown[];
seen: unknown[];
stop: Unsubscribe;
}> {
const hangFor = new Set([A]);
const ng = inject(new Set(), hangFor);
const failures: unknown[] = [];
const seen: unknown[] = [];
const stop = subscribeDocReportingSetupFailure(
A,
(r) => seen.push(r),
(error) => failures.push(error),
);
// Awaited before the broker is allowed to answer: `establish` resolves the session id
// first, so the call this has to leave hanging has not been placed yet.
await tick();
hangFor.delete(A);
return { ng, failures, seen, stop };
}
test("a SUPERSEDED setup rejecting late is not reported as this document failing", async () => {
const { ng, failures, seen, stop } = await hangingThenReopened();
expect(ng.isSubscribed(A)).toBe(false); // the first call has not answered
resubscribeDocs(); // the session rotated: a second establish, on the same fan-out
await tick();
expect(ng.isSubscribed(A)).toBe(true);
const before = seen.length;
expect(before).toBeGreaterThan(0); // …and it is pushing
ng.rejectHung(); // …and only now does the first call refuse
await tick();
// Nothing failed: the document is subscribed and pushing. Told otherwise, the caller whose
// job depends on this subscription (the inbox observation) releases the entry it holds —
// which closes the WORKING channel and reports an inbox that is watched as unwatchable.
expect(failures).toEqual([]);
expect(ng.isSubscribed(A)).toBe(true);
ng.push(A);
expect(seen.length).toBeGreaterThan(before);
stop();
});
test("a SUPERSEDED setup rejecting late does not let the next joiner evict the live channel", async () => {
const { ng, stop } = await hangingThenReopened();
resubscribeDocs();
await tick();
expect(ng.doc_subscribe).toHaveBeenCalledTimes(2);
ng.rejectHung();
await tick();
// The second establish still stands, so this joiner must join it. Counting the late
// rejection as "nothing is running any more" opens a THIRD `doc_subscribe` — and a second
// subscribe on a branch evicts the one before it, so the joiner's own call is what silences
// everybody already listening.
const late: unknown[] = [];
const stopLate = subscribeDoc(A, (r) => late.push(r));
await tick();
expect(ng.doc_subscribe).toHaveBeenCalledTimes(2);
expect(late.length).toBeGreaterThan(0); // replayed the barrier, as any late joiner is
ng.push(A);
expect(late.length).toBeGreaterThan(1);
stopLate();
stop();
});