fix!: un scope nomme refuse se rouvre quand la cle arrive, et la barriere cesse d-etre serie

Revue adversariale : la barriere livree au tour precedent rendait le refus
TERMINAL. Le signal du trousseau s'ecrit `if (query !== null) publish(...)`, parce
qu'avant la barriere il n'y avait qu'une seule raison de n'avoir pas de requete -
rien n'avait encore ete tente - et qu'une cle qui arrive ne pouvait changer que ce
qu'une requete OUVERTE avait le droit de montrer. La barriere en a ajoute une
seconde : elle abandonne AVANT que la requete existe, donc le seul canal qui fait
converger une cle tardive passait a cote de l'etat qui en avait le plus besoin.
Une page qui s'abonne pendant que son trousseau se restaure, ou un document
partage sous les yeux de son destinataire, publiait `isError` et y restait. Ce
n'est pas une surface plus stricte, c'est une pire : echanger un vide mensonger
contre une erreur bloquee ne repare rien, et cela casse une garantie que ce paquet
publie.

Le signal rouvre donc un scope refuse, et seulement quand le refus est leve
(`namedDocumentsReachable`). Le garde-fou porte autant que la reouverture :
rouvrir a chaque changement de trousseau rejouerait la barriere pour chaque cle
qu'une connexion depose, redemanderait au reseau tout document dont le
telechargement avait ECHOUE - un echec n'est deliberement pas memoise - et
republierait la meme erreur a chaque abonne. La variante indiscriminee casse deux
tests, dont celui de demontage qui preexistait.

La barriere passe en parallele. Elle etait serie, donc N documents qui ne poussent
jamais de `State` coutaient N replis bornes, 8s chacun en production. Les refus
restent lus dans l'ordre du scope apres coup.

Et ce qui a laisse passer les deux : l'e2e ne parcourait pas ce chemin. Les deux
journeys `useShapeQuery` lisent `{graphs: "did:ng:i"}`, donc 43/43 n'a jamais rien
prouve sur la barriere. Quatre controles ajoutes sur un scope NOMME, contre le
vrai broker : la proprietaire lit son document, un porteur de rien recoit
`isError` et jamais un succes vide, un document PUBLIC s'ouvre pour lui depuis la
seule reference via la requete de la barriere, et une cle qui tombe pour un AUTRE
document laisse le scope refuse en place.
This commit is contained in:
Sylvain Duchesne
2026-09-21 15:57:56 +02:00
parent aa38b37f33
commit f36ed5c164
6 changed files with 413 additions and 19 deletions
@@ -105,6 +105,25 @@
* The barrier is why the open below is asynchronous: it prolongs `isPending`, and nothing
* else about the states moves.
*
* -- A refusal that could not be re-tried would be worse than the defect ------------
* The first version of this barrier was TERMINAL, and an adversarial pass found it. The
* keyring signal below is written as `if (query !== null) publish(...)` because until the
* barrier existed there was only ever one reason to have no query - nothing had been
* tried yet - and a cap arriving could only ever change what an OPEN query was allowed to
* show. The barrier added a second reason: it aborts BEFORE the query is created, so the
* one channel that makes a late cap converge went straight past the state that needed it
* most. A page subscribing while its keyring was still being restored, or a document
* shared with someone while they watched, published `isError` and stayed there for the
* life of the view. Trading a silent empty answer for a stuck error is not a stricter
* surface, it is a worse one - and it broke a guarantee this package publishes, which
* `emulated-verifier/read-filter.ts` and `surface/inbox.ts` both restate.
*
* So the signal re-OPENS a refused scope, and does it only when the refusal has actually
* been lifted ({@link namedDocumentsReachable}). Re-opening on any keyring change would
* re-run the barrier for every cap a connection files - re-asking the network for any
* document whose fetch had FAILED, since a failure is deliberately not memoised, and
* re-publishing the same error to every subscriber each time.
*
* -- An observable cannot un-emit: `data` survives an error -----------------
* A one-shot call rejects and is done. An observable has already handed a list to a
* subscriber that rendered it, so its failure snapshot has to say something about
@@ -117,7 +136,7 @@
import { getCaps, getConfig } from "../shared-wallet/bootstrap";
import { filterReadable } from "../emulated-verifier/read-filter";
import { ensureRepoOpen } from "../emulated-verifier/open-repo";
import { assertMayReach } from "../emulated-verifier/reach";
import { assertMayReach, mayReach } from "../emulated-verifier/reach";
import { isNuri } from "../model/nuri";
import type { Nuri, OrmSubscriptionHandle, OrmSubscriptionLike } from "../model/types";
// The SDK's own types, imported as TYPES (erased at build, so no runtime `@ng-org`
@@ -239,6 +258,16 @@ export function useShapeQuery<T extends BaseType = BaseType>(
/** Has the CURRENT generation's initial payload arrived? Gates every publication:
* a change signal that beats `readyPromise` must not be read as an answer. */
let ready = false;
/**
* Why there is no query in force: the BARRIER refused this scope, rather than the
* shape query failing to open or nothing having been tried yet.
*
* The distinction is what the keyring signal needs. A cap arriving can lift a refusal
* and can lift nothing else - a `configure` with no `ormSubscription` is not going to
* be fixed by one - so re-opening on any keyring change while any error stood would
* churn for a misconfiguration that no amount of retrying repairs.
*/
let barrierRefused = false;
function emit(): void {
for (const l of listeners) {
@@ -362,16 +391,36 @@ export function useShapeQuery<T extends BaseType = BaseType>(
* `assertMayReach` says it out loud immediately after - without that, an unheld
* document would simply produce no objects and read as a document holding none.
*
* Sequential rather than parallel, deliberately: the first document that cannot be
* reached is the one reported, and there is no batch policy to own (`ensureReposOpen`,
* the parallel form, was removed in `1.0.0-dev.8`/`.9` for having none worth keeping).
* The opens run TOGETHER and the refusals are read afterwards, in scope order. A first
* pass ran them one at a time so that the first unreachable document would be the one
* reported; that determinism is preserved by the loop below, while the cost of the
* serial form was not acceptable - each open waits on the sync barrier, bounded by
* `OPEN_TIMEOUT_MS` (8s) for a document that never pushes a `State`, so a scope naming
* N of them paid N timeouts before answering anything. `Promise.all` attaches a handler
* to every one of them, so a rejection never escapes as an unhandled one, and the opens
* that did succeed are memoised per session exactly as they would have been.
*
* Each open is memoised per session, so a re-subscribe costs a map hit.
*/
async function reachNamedDocuments(): Promise<void> {
for (const doc of namedDocuments(scope)) {
await ensureRepoOpen(doc);
assertMayReach(doc, "useShapeQuery");
}
const docs = namedDocuments(scope);
if (docs.length === 0) return;
await Promise.all(docs.map((doc) => ensureRepoOpen(doc)));
for (const doc of docs) assertMayReach(doc, "useShapeQuery");
}
/**
* Does the holder now reach every document the scope NAMES? The precondition for
* re-opening a scope the barrier refused - and the whole of it.
*
* Synchronous and cap-only, so it asks nothing of the network: it answers "has the
* thing that blocked us been lifted", which is exactly what a keyring change can have
* done and the only question worth spending a re-open on. A scope that is still
* unreachable is left alone, so a connection filing a dozen caps does not buy a dozen
* round-trips for a view none of them was about.
*/
function namedDocumentsReachable(): boolean {
return namedDocuments(scope).every((doc) => mayReach(doc));
}
/**
@@ -386,11 +435,13 @@ export function useShapeQuery<T extends BaseType = BaseType>(
function open(): void {
closeQuery();
const gen = ++generation;
barrierRefused = false;
void (async () => {
try {
await reachNamedDocuments();
} catch (error) {
if (gen !== generation) return;
barrierRefused = true;
setUnknown(error);
return;
}
@@ -435,7 +486,17 @@ export function useShapeQuery<T extends BaseType = BaseType>(
// ROTATION uses too, which is why keeping an access needs no subscription
// obligation on the consumer's side.
capsUnsub = getCaps().onChange(() => {
if (query !== null) publish(query, generation);
if (query !== null) {
publish(query, generation);
return;
}
// No query in force. Since `1.0.0-dev.9` there is a second way to be here, and it
// is the one this signal exists for: the BARRIER refused the scope, so the query
// was never created and there is nothing for `publish` to re-filter. A view left
// like that would be TERMINAL - the very case this channel was added to prevent,
// arriving by a door that did not exist when the channel was written. So re-open,
// and only when the refusal has actually been lifted.
if (barrierRefused && namedDocumentsReachable()) open();
});
open();
}