Skip to content

Serialize auth certifications. - #43

Merged
snoack merged 1 commit into
masterfrom
serialize-certifications
Sep 30, 2026
Merged

snoack merged 1 commit into
masterfrom
serialize-certifications

Conversation

@snoack

@snoack snoack commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

The bridge doesn't await our auth listeners, so consecutive callbacks could
publish out of order, losing a sign-out. Serialize certifications, and serialize
client-issued calls over their whole operation.

A call owns the auth changes delivered between its request going out and that
request settling; anything outside is background work. A certify interceptor
rejects a candidate by returning false rather than signing out itself, and every
onBefore settles before any verdict is acted on.


This change is Reviewable

@snoack
snoack requested a review from pkaminski September 11, 2026 02:30

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 potential issue.

Devin Review

Comment thread src/MetaTree.js Outdated
// publish while an earlier one is still in its own onBefore, letting the two land out of
// order. The serial below can't catch that, since it only changes when the app itself calls
// authenticate()/unauthenticate(), not between two callbacks from the bridge.
const promise = this._auth.changePromise.then(() => this._dispatcher.execute(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Queued sign-out is discarded

After an established null user, changePromise queues a sign-in but a back-to-back sign-out is discarded as already applied. The queued sign-in then publishes, leaving root.user signed in after the latest bridge callback.

Learn more

The immediate equality check compares each callback only with the currently published user. It cannot see a different certification waiting in changePromise. A later callback matching the current user is therefore dropped even when it must undo that pending certification.

Example: Start after the initial anonymous callback has set root.user to null. The bridge delivers user {uid: 'github:1'}, which queues a sign-in behind a slow certification. It then delivers null; the equality check treats this sign-out as redundant. The queued sign-in publishes last, although the bridge's latest state is signed out.

Recommended fix: Queue every non-superseded bridge callback before testing it against root.user. Keep the equality check inside the serialized executor, where all earlier certifications have completed, or explicitly track the last queued auth state.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 34bc7f6fe2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/MetaTree.js Outdated
// publish while an earlier one is still in its own onBefore, letting the two land out of
// order. The serial below can't catch that, since it only changes when the app itself calls
// authenticate()/unauthenticate(), not between two callbacks from the bridge.
const promise = this._auth.changePromise.then(() => this._dispatcher.execute(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Defer the duplicate-user check until the queued turn

When root.user is already null and the bridge delivers a sign-in followed by a sign-out before the sign-in certification runs, the sign-out is discarded by the earlier this.root.user === user check because the queued sign-in has not updated the root yet. This new chain then applies only the sign-in, leaving the application authenticated even though the last bridge event was null; duplicate detection needs to occur after prior certifications finish.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
));
// Keep the chain going even if this certification fails, but don't swallow the result for
// the caller, which needs to know whether the change was actually applied.
this._auth.changePromise = promise.catch(_.noop);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve certification failures for authenticate

When a certify interceptor rejects during authenticate(), assigning the caught promise to changePromise hides that failure from authenticate() at line 52, which waits on this chain after the bridge command completes. The public authentication promise therefore resolves even though certification failed and root.user was never published; a recovery promise can keep the queue moving, but the authentication caller still needs access to the rejecting certification result.

Useful? React with 👍 / 👎.

@snoack snoack Sep 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, but pre-existing rather than a regression here: the original assignment was this._auth.changePromise.then(() => promise).catch(), which swallows a rejected certification exactly the same way. Changing it alters authenticate()'s error contract for every consumer, so it belongs in its own PR rather than riding along with the ordering fix.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The claim that this is pre-existing is incorrect: .catch() with no rejection handler propagates the rejection; it does not swallow it. The new .catch(_.noop) does swallow it.

I checked the public authenticate() path with the same real MetaTree/Dispatcher harness on the base (c03ab21) and r4 (b741614). When the bridge delivers the authentication result and a certify.onBefore rejects with cannot certify, the base's authenticate() rejects with that error. In r4 it resolves successfully, with userid still null. Returning the rejecting promise from _handleAuthChange() does not preserve the public contract because authenticate() waits on _auth.changePromise, which is now the recovered queue tail.

Please keep a recovered scheduling tail so later certifications can run, but preserve the relevant certification result for the authentication caller. Add a test through authenticate(); the existing failed-certification test only checks direct deliver() and queue recovery.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, I checked: bare .catch() propagates, .catch(_.noop) swallows. Regression I introduced, not pre-existing. Fixed by keeping the recovered tail for scheduling and a separate result promise for authenticate(), with a test through authenticate().

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: r5 preserves the rejection in the single-authentication case, and the new public authenticate() regression test passes. Marking that specific swallowing regression resolved. The remaining overlapping-call result ownership problem is covered by the newer discussion.

@snoack
snoack force-pushed the serialize-certifications branch from 34bc7f6 to e089baa Compare September 11, 2026 02:52

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 2 comments and resolved 3 discussions.
Reviewable status: 0 of 8 files reviewed, all discussions resolved (waiting on pkaminski).

Comment thread src/MetaTree.js Outdated
// publish while an earlier one is still in its own onBefore, letting the two land out of
// order. The serial below can't catch that, since it only changes when the app itself calls
// authenticate()/unauthenticate(), not between two callbacks from the bridge.
const promise = this._auth.changePromise.then(() => this._dispatcher.execute(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
// publish while an earlier one is still in its own onBefore, letting the two land out of
// order. The serial below can't catch that, since it only changes when the app itself calls
// authenticate()/unauthenticate(), not between two callbacks from the bridge.
const promise = this._auth.changePromise.then(() => this._dispatcher.execute(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@snoack
snoack force-pushed the serialize-certifications branch from e089baa to 147c397 Compare September 11, 2026 02:54

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 147c397e97

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/MetaTree.js Outdated
// authenticate()/unauthenticate(), not between two callbacks from the bridge. Note that the
// duplicate-user check has to wait for our turn too, or a change queued behind a pending one
// would be discarded by comparing against a root the queue hasn't updated yet.
const promise = this._auth.changePromise.then(() => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Prevent nested authentication from waiting on itself

When a certify onBefore or onAfter interceptor returns/awaits authenticate() or unauthenticate(), the nested _handleAuthChange() chains its promise behind _auth.changePromise, which already represents the outer certification. The outer dispatcher waits for the interceptor, the nested auth call waits for its newly queued certification, and that certification waits for the outer dispatcher, so the auth flow hangs permanently. Authentication changes initiated from the active certification must avoid being queued behind the promise whose interceptor is awaiting them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

r4 fixes the single nested unauthenticate() covered by the new test, but clearing the shared boolean when the child completes loses the still-running parent. A certification onAfter that does the following now deadlocks:

if (!op.operand) return;
await metaTree.unauthenticate();
await metaTree.unauthenticate();

The first nested certification's finally sets certifying = false. The second logout therefore queues behind the outer certification's changePromise, while the outer interceptor is awaiting that second logout. Even though the user is already null, the duplicate check is inside the queued turn and cannot break the cycle. I reproduced this with the real Dispatcher: the base reaches both awaits and completes; r4 completes only the first await and leaves the outer promise pending.

Please preserve the entire nested certification lifetime when handling reentrancy. I also checked client #2044's expired-user rejection, which awaits one forced logout from _decorateUser: that path currently completes and needs to stay working. An awaited nested authenticate() also stalls, but it does so on the base too, so I am not counting that as a new regression here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed that r5's depth counter fixes the specific two-successive-nested-logouts regression; the new test passes.

The desired API is now explicit rejection via false from certify.onBefore, with re-entrant auth calls unsupported, as described in the serialization discussion. That replaces my earlier request to preserve the client's nested-logout pattern. Please migrate the client rejection paths and tests with that contract.

@snoack
snoack force-pushed the serialize-certifications branch from 147c397 to b741614 Compare September 11, 2026 03:16

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b74161433f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep bridge callbacks on the certification queue

When a sign-in certification is paused in an asynchronous interceptor and a later worker message delivers a sign-out, certifying is true, so this branch bypasses the queue even though the callback is not a nested change. Because the pending sign-in has not published yet, the sign-out then sees the current null user as a duplicate at line 94 and is discarded; releasing the first interceptor subsequently publishes the stale signed-in user. Fresh evidence after the earlier duplicate-check comment is that the new certifying bypass reintroduces the same failure specifically for bridge events arriving after the first queued turn has started.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested this against r4 (b741614) with client #2044 r6's actual AuthService (eadc674). I paused completion of the sign-in's worker key RPC, then delivered a null callback. Starting from a null user, sign-out is discarded and the earlier sign-in publishes afterward. Starting from an existing user, sign-out releases the key and the earlier sign-in subsequently publishes with encryption still notready.

Both callback orders pass when delivered in the same stack before the queued turn starts; delivering the second callback after entry into onBefore exposes the failure. The integration therefore still blocks #2044's ordering change, and the regression test needs that later delivery point.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and the depth counter doesn't fix this one: it's read synchronously at call time but set inside the queued turn, so a bridge callback arriving mid-certification sees a flag belonging to someone else's certification and bypasses the queue.

What I actually need is "is this call reentrant from an interceptor on the current stack", which MetaTree can't determine on its own. Dispatcher invokes the interceptors and is Object.freezed, so tracking depth there means changing that class.

Is extending Dispatcher to expose interceptor-execution depth the direction you'd want, or would you rather reentrant auth changes be handled differently? I've been wrong about this mechanism several times, so I'd rather ask than guess again.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use explicit user rejection instead of extending Dispatcher with interceptor-depth tracking. A synchronous depth misses the current client's logout, which awaits $nextTick() before unauthenticate(); keeping depth active across the promise still misclassifies unrelated bridge callbacks. I reproduced both delayed-null failures on r5 with #2044 r6's actual AuthService: starting null drops the sign-out, and starting with an existing user ends with userid === 'new' and encryption notready.

The agreed contract is:

  • Any certify.onBefore handler returning literal false rejects a non-null candidate; other return values are ignored. Wait for all handlers to settle before acting on the decision, so a rejecting handler cannot race another handler's async key setup. No rejection reasons or new methods on generic op objects.
  • Remove the reentrancy bypass and document calls to public authenticate()/unauthenticate() from certification callbacks as unsupported. Independent auth notifications must remain serialized through validation, publication, and cleanup. Do not use a global “certification running” flag to reject independent calls.
  • A rejected candidate must never publish. Complete sign-out internally within the current serialized turn, without enqueueing a public logout behind the certification awaiting it. After successful cleanup, the initiating authentication rejects with a recognizable, generic AUTH_REJECTED error.
  • Wrap the entire internal/public logout flow in an auth/unauthenticate operation, including null certification and its interceptors. Every logout failure must reach an onFailure with op.method === 'unauthenticate', even if the enclosing authentication error is caught. Reviewable will make that failure fatal.
  • Do not use an already-null client user as proof that worker sign-out is unnecessary. Preserve protection against a genuinely superseding auth request, but distinguish that from a duplicate local null.

That last pair closes existing failure paths as part of this change. With r5, a null-certification key-cleanup failure reports only certify and never calls worker sign-out. A worker sign-out failure leaves the client null; another explicit logout resolves without retrying the worker. The already-null case can skip the worker even while it is authenticated.

Please cover delayed bridge callbacks, rejection after an await, one false result alongside a still-running async handler, an already-null client with an authenticated worker, and failures in both null-certification cleanup and worker sign-out. The 39 existing library tests pass, but do not cover these boundaries. The matching client changes are tracked in #2044's existing discussion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the $nextTick() case does defeat the depth approach. Before implementing the contract, three things I'd rather confirm than guess:

  1. Honouring false from onBefore: I'd planned to have Dispatcher.begin resolve with the handler results. Should the certify decision be read there, or should MetaTree drive begin/end itself so execute() stays unchanged?
  2. Internal sign-out for a rejected candidate: call bridge.unauth directly inside the serialized turn, rather than routing through unauthenticate()?
  3. The already-null case: the duplicate check currently returns early on root.user === user. To distinguish a duplicate local null from a genuinely superseding request, is the auth serial the right discriminator, or did you have something else in mind?

AUTH_REJECTED will be error.code on a plain Error unless you'd prefer otherwise. Nothing from the contract is implemented yet, pending these answers.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The callback serialization fix still misses the preemptive certification in public unauthenticate(): _signOut() calls _certify(null) directly at r19 line 299, without adding that work to changePromise. The initial drain does not prevent a new bridge callback from arriving while its hooks are pending.

I reproduced this with r19 and worker r2 using the actual Bridge and asynchronous key-install/cleanup hooks. Start signed in with a key, pause the explicit logout's null onAfter before it releases the key, and deliver a token-refresh callback for the same uid with changed claims. That refresh certifies and republishes the user while null cleanup is still running. Releasing cleanup then clears the key; when the worker receives unauth, the client still publishes the signed-in uid but has no key. The later null notification repairs the user state, but the unsafe interval already occurred.

Please put the public logout's null certification on the same queue as bridge certifications, including its full hook lifecycle. Rejected-login cleanup must remain inline within the turn it already owns, so that path cannot enqueue behind itself. The direct extraction correctly preserves already-null cleanup and the unauthenticate operation, but public and internal callers need different scheduling. This is an uncovered serialization case, independent of the fail-fast/late-refusal issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The public logout scheduling change fixes the previous reproduction: a token refresh now waits until the paused null onAfter completes.

The queue still releases early if an onAfter sibling fails. Dispatcher.end() (r20 Dispatcher.js:255-264) still uses fail-fast Promise.all. A rejected handler reaches _afterEnd() immediately, so the new certification queue considers the turn finished while another after handler is still running.

With r20 and worker r4 through the actual Bridge, I delivered a background null callback, paused one null after handler before clearing its simulated key, and made a sibling after handler throw. A subsequent public login issued its RPC, installed a new key, published, and resolved before the old cleanup was released. Releasing it then left userid === 'new' with no key. Only certify.onFailure ran; there was no failed unauthenticate operation for the proposed fatal-logout handler to catch.

This uses controlled asynchronous key hooks to demonstrate the library's lifecycle overlap; it is not evidence that Reviewable's synchronous worker key-configuration function performs that exact delayed mutation. The fail-fast behavior in end() predates this revision, but it still defeats the required serialization through cleanup. Please keep the turn until all after handlers settle, including on error, then report the failure. Cover a failing after handler alongside a still-pending sibling.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on r21 with worker r4 using the original Bridge/worker reproduction. The failing after handler now waits for the paused sibling cleanup: the next login sends no RPC before cleanup is released, and the order is install old → clear → install new. The new user retains its key. The original failure still reaches certify.onFailure. This closes the remaining after-hook serialization issue.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 9 files and all commit messages.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on snoack).

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski+CODX reviewed 9 files and all commit messages, and made 3 comments.
Reviewable status: all files reviewed, 3 unresolved discussions (waiting on snoack).

Comment thread src/MetaTree.js Outdated
));
// Keep the chain going even if this certification fails, but don't swallow the result for
// the caller, which needs to know whether the change was actually applied.
this._auth.changePromise = promise.catch(_.noop);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The claim that this is pre-existing is incorrect: .catch() with no rejection handler propagates the rejection; it does not swallow it. The new .catch(_.noop) does swallow it.

I checked the public authenticate() path with the same real MetaTree/Dispatcher harness on the base (c03ab21) and r4 (b741614). When the bridge delivers the authentication result and a certify.onBefore rejects with cannot certify, the base's authenticate() rejects with that error. In r4 it resolves successfully, with userid still null. Returning the rejecting promise from _handleAuthChange() does not preserve the public contract because authenticate() waits on _auth.changePromise, which is now the recovered queue tail.

Please keep a recovered scheduling tail so later certifications can run, but preserve the relevant certification result for the authentication caller. Add a test through authenticate(); the existing failed-certification test only checks direct deliver() and queue recovery.

Comment thread src/MetaTree.js Outdated
// authenticate()/unauthenticate(), not between two callbacks from the bridge. Note that the
// duplicate-user check has to wait for our turn too, or a change queued behind a pending one
// would be discarded by comparing against a root the queue hasn't updated yet.
const promise = this._auth.changePromise.then(() => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

r4 fixes the single nested unauthenticate() covered by the new test, but clearing the shared boolean when the child completes loses the still-running parent. A certification onAfter that does the following now deadlocks:

if (!op.operand) return;
await metaTree.unauthenticate();
await metaTree.unauthenticate();

The first nested certification's finally sets certifying = false. The second logout therefore queues behind the outer certification's changePromise, while the outer interceptor is awaiting that second logout. Even though the user is already null, the duplicate check is inside the queued turn and cannot break the cycle. I reproduced this with the real Dispatcher: the base reaches both awaits and completes; r4 completes only the first await and leaves the outer promise pending.

Please preserve the entire nested certification lifetime when handling reentrancy. I also checked client #2044's expired-user rejection, which awaits one forced logout from _decorateUser: that path currently completes and needs to stay working. An awaited nested authenticate() also stalls, but it does so on the base too, so I am not counting that as a new regression here.

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested this against r4 (b741614) with client #2044 r6's actual AuthService (eadc674). I paused completion of the sign-in's worker key RPC, then delivered a null callback. Starting from a null user, sign-out is discarded and the earlier sign-in publishes afterward. Starting from an existing user, sign-out releases the key and the earlier sign-in subsequently publishes with encryption still notready.

Both callback orders pass when delivered in the same stack before the queued turn starts; delivering the second callback after entry into onBefore exposes the failure. The integration therefore still blocks #2044's ordering change, and the regression test needs that later delivery point.

@snoack
snoack force-pushed the serialize-certifications branch from b741614 to 7501797 Compare September 11, 2026 21:31

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 3 comments.
Reviewable status: all files reviewed, 3 unresolved discussions (waiting on pkaminski+CODX).

Comment thread src/MetaTree.js Outdated
));
// Keep the chain going even if this certification fails, but don't swallow the result for
// the caller, which needs to know whether the change was actually applied.
this._auth.changePromise = promise.catch(_.noop);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, I checked: bare .catch() propagates, .catch(_.noop) swallows. Regression I introduced, not pre-existing. Fixed by keeping the recovered tail for scheduling and a separate result promise for authenticate(), with a test through authenticate().

Comment thread src/MetaTree.js Outdated
// authenticate()/unauthenticate(), not between two callbacks from the bridge. Note that the
// duplicate-user check has to wait for our turn too, or a change queued behind a pending one
// would be discarded by comparing against a root the queue hasn't updated yet.
const promise = this._auth.changePromise.then(() => {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and the depth counter doesn't fix this one: it's read synchronously at call time but set inside the queued turn, so a bridge callback arriving mid-certification sees a flag belonging to someone else's certification and bypasses the queue.

What I actually need is "is this call reentrant from an interceptor on the current stack", which MetaTree can't determine on its own. Dispatcher invokes the interceptors and is Object.freezed, so tracking depth there means changing that class.

Is extending Dispatcher to expose interceptor-execution depth the direction you'd want, or would you rather reentrant auth changes be handled differently? I've been wrong about this mechanism several times, so I'd rather ask than guess again.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7501797413

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/MetaTree.js Outdated
// the failure from authenticate(), which waits on the result instead.
if (!nested) {
this._auth.changePromise = promise.catch(_.noop);
this._auth.resultPromise = promise;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep each authenticate tied to its certification result

When two authentication responses are handled in one inbound bridge batch, _receiveMessages() processes all callbacks synchronously before either resolved RPC promise resumes, so the second callback overwrites this shared slot before the first authenticate() reads it at line 61. If the first certification rejects and the second succeeds, both calls consequently await the second promise and the first authentication incorrectly resolves; conversely, callers can inherit another request's failure. Fresh evidence beyond the earlier failure-propagation comment is this overlapping-authentication overwrite after the recovery/result promises were split; retain the result associated with each authentication rather than a single latest value.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced on r5 using the actual Bridge/MetaTree/Dispatcher. After establishing null auth, I started two authenticate() calls and delivered one inbound batch containing callback A, RPC resolution A, callback B, and RPC resolution B.

  • A's certification rejects and B's succeeds: both authentication promises resolve.
  • A's certification succeeds and B's rejects: both promises reject with B's error.

Both callbacks update resultPromise synchronously before either RPC continuation reads it, so the callers both observe B. Please associate each authentication with its relevant certification result while keeping the recovered scheduling tail separate. A serial captured only when handling the callback does not establish that association: both callbacks can arrive after both public calls have incremented the serial.

Please add the batched public-API test in both failure orders. The single-call rejection test now passes, but does not cover this overwrite.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Each authenticate() now claims the next certification's result before its request goes out, instead of reading a shared slot. Added the batched test in both failure orders; both fail against the shared slot and pass now.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is still reproducible on r8 after the claimant implementation was removed. Using the actual Bridge, I issued A and B and delivered one batch containing callback A, resolution A, callback B, resolution B. When A's certification succeeds and B's fails, A rejects with B's error and B resolves: the first finisher consumes and clears the shared pendingFailure.

The opposite failure order happens to pass. The missing public-call serialization is tracked in the newer report; both failure orders should remain regression tests for that fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The shared slot is gone; each call holds its own collector, so there's nothing for a first finisher to consume.

But the crossing had two causes and only one was here. The other is unordered userToJson results, which is what let a callback answering B arrive during A, and that's fixed in Reviewable/firetruss-worker#27. With the results ordered, B's callback can't arrive during A at all, since B's request isn't sent until A completes.

So I couldn't write a library test that reproduces your batch and stays faithful to what an ordered worker emits. The two I added deliver each callback with its own response and pass against r8 as well, so they document the behaviour rather than pinning the fix. You asked for both failure orders as regression tests and I'd rather flag that than hand you two that can't fail.

If you want the crossing pinned it belongs in firetruss-worker, which has no test infrastructure yet.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified both failure orders with the actual Bridge. B's interceptors and RPC now wait for A's operation, and each caller receives its own result. The old batch is no longer a valid input once public calls are serialized, so the useful regression assertion is that B has not been sent while A is pending; the new withheld-RPC test covers that.

One correction to the diagnosis: the original r8 reproduction delivered callback A, response A, callback B, response B in order. Worker reordering was not required for that crossed-result failure; concurrent requests plus the shared slot were sufficient. The new public-call queue fixes that specific issue.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski+CODX reviewed 8 files and all commit messages, made 4 comments, and resolved 2 discussions.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on snoack).

Comment thread src/MetaTree.js Outdated
));
// Keep the chain going even if this certification fails, but don't swallow the result for
// the caller, which needs to know whether the change was actually applied.
this._auth.changePromise = promise.catch(_.noop);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: r5 preserves the rejection in the single-authentication case, and the new public authenticate() regression test passes. Marking that specific swallowing regression resolved. The remaining overlapping-call result ownership problem is covered by the newer discussion.

Comment thread src/MetaTree.js Outdated
// authenticate()/unauthenticate(), not between two callbacks from the bridge. Note that the
// duplicate-user check has to wait for our turn too, or a change queued behind a pending one
// would be discarded by comparing against a root the queue hasn't updated yet.
const promise = this._auth.changePromise.then(() => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed that r5's depth counter fixes the specific two-successive-nested-logouts regression; the new test passes.

The desired API is now explicit rejection via false from certify.onBefore, with re-entrant auth calls unsupported, as described in the serialization discussion. That replaces my earlier request to preserve the client's nested-logout pattern. Please migrate the client rejection paths and tests with that contract.

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use explicit user rejection instead of extending Dispatcher with interceptor-depth tracking. A synchronous depth misses the current client's logout, which awaits $nextTick() before unauthenticate(); keeping depth active across the promise still misclassifies unrelated bridge callbacks. I reproduced both delayed-null failures on r5 with #2044 r6's actual AuthService: starting null drops the sign-out, and starting with an existing user ends with userid === 'new' and encryption notready.

The agreed contract is:

  • Any certify.onBefore handler returning literal false rejects a non-null candidate; other return values are ignored. Wait for all handlers to settle before acting on the decision, so a rejecting handler cannot race another handler's async key setup. No rejection reasons or new methods on generic op objects.
  • Remove the reentrancy bypass and document calls to public authenticate()/unauthenticate() from certification callbacks as unsupported. Independent auth notifications must remain serialized through validation, publication, and cleanup. Do not use a global “certification running” flag to reject independent calls.
  • A rejected candidate must never publish. Complete sign-out internally within the current serialized turn, without enqueueing a public logout behind the certification awaiting it. After successful cleanup, the initiating authentication rejects with a recognizable, generic AUTH_REJECTED error.
  • Wrap the entire internal/public logout flow in an auth/unauthenticate operation, including null certification and its interceptors. Every logout failure must reach an onFailure with op.method === 'unauthenticate', even if the enclosing authentication error is caught. Reviewable will make that failure fatal.
  • Do not use an already-null client user as proof that worker sign-out is unnecessary. Preserve protection against a genuinely superseding auth request, but distinguish that from a duplicate local null.

That last pair closes existing failure paths as part of this change. With r5, a null-certification key-cleanup failure reports only certify and never calls worker sign-out. A worker sign-out failure leaves the client null; another explicit logout resolves without retrying the worker. The already-null case can skip the worker even while it is authenticated.

Please cover delayed bridge callbacks, rejection after an await, one false result alongside a still-running async handler, an already-null client with an authenticated worker, and failures in both null-certification cleanup and worker sign-out. The 39 existing library tests pass, but do not cover these boundaries. The matching client changes are tracked in #2044's existing discussion.

Comment thread src/MetaTree.js Outdated
// the failure from authenticate(), which waits on the result instead.
if (!nested) {
this._auth.changePromise = promise.catch(_.noop);
this._auth.resultPromise = promise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced on r5 using the actual Bridge/MetaTree/Dispatcher. After establishing null auth, I started two authenticate() calls and delivered one inbound batch containing callback A, RPC resolution A, callback B, and RPC resolution B.

  • A's certification rejects and B's succeeds: both authentication promises resolve.
  • A's certification succeeds and B's rejects: both promises reject with B's error.

Both callbacks update resultPromise synchronously before either RPC continuation reads it, so the callers both observe B. Please associate each authentication with its relevant certification result while keeping the recovered scheduling tail separate. A serial captured only when handling the callback does not establish that association: both callbacks can arrive after both public calls have incremented the serial.

Please add the batched public-API test in both failure orders. The single-call rejection test now passes, but does not cover this overwrite.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 6 files and all commit messages.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on snoack).

@snoack
snoack force-pushed the serialize-certifications branch from 7501797 to 7dd6487 Compare September 15, 2026 01:52

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 2 comments.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski+CODX).

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, the $nextTick() case does defeat the depth approach. Before implementing the contract, three things I'd rather confirm than guess:

  1. Honouring false from onBefore: I'd planned to have Dispatcher.begin resolve with the handler results. Should the certify decision be read there, or should MetaTree drive begin/end itself so execute() stays unchanged?
  2. Internal sign-out for a rejected candidate: call bridge.unauth directly inside the serialized turn, rather than routing through unauthenticate()?
  3. The already-null case: the duplicate check currently returns early on root.user === user. To distinguish a duplicate local null from a genuinely superseding request, is the auth serial the right discriminator, or did you have something else in mind?

AUTH_REJECTED will be error.code on a plain Error unless you'd prefer otherwise. Nothing from the contract is implemented yet, pending these answers.

Comment thread src/MetaTree.js Outdated
// the failure from authenticate(), which waits on the result instead.
if (!nested) {
this._auth.changePromise = promise.catch(_.noop);
this._auth.resultPromise = promise;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Each authenticate() now claims the next certification's result before its request goes out, instead of reading a shared slot. Added the batched test in both failure orders; both fail against the shared slot and pass now.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7dd6487f51

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/MetaTree.js Outdated
this._auth.serial++;
// Claim the next certification before the request goes out, so that concurrent
// authentications each await their own result rather than whichever landed last.
const certified = this._claimCertification();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove abandoned certification claims after auth failures

When an authenticate operation fails without producing an auth callback—for example, an authenticate onBefore interceptor rejects before the executor runs, or the bridge rejects an invalid token—the claimant pushed here is never removed. The next successful authentication's certification is then assigned to this abandoned claimant, leaving the current authentication waiting indefinitely for another callback. Clean up the corresponding claimant whenever its authentication request terminates without a certification.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
Comment on lines +80 to +81
const claimant = this._auth.claimants.shift();
if (claimant) promise.then(claimant.resolve, claimant.reject);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enqueue claimants in bridge request order

When an asynchronous authenticate onBefore interceptor delays call A but not a later call B, claimants are queued in invocation order A/B while the bridge requests—and therefore their auth callbacks—are issued in order B/A. This FIFO shift assigns B's certification to A and A's to B, so the two public promises can inherit each other's certification failures or wait for the wrong operation. Enqueue the claimant when the bridge request is actually issued, or otherwise correlate it with that request.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski Confirmed. Queueing the claim when the bridge request is issued still pairs requests to callbacks by position, and a callback carries a user, not a request identity. Is that pairing guaranteed? If not, should authenticate() stop waiting on certification and let callers observe root.user?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pairing is not guaranteed but we don't want to observe root.user either. My proposal:

First, fully serialize client-issued authenticate / unauthenticate calls. This will simplify a lot of things and should let us get rid of _auth.serial, though we'll still need some (simpler) mechanism to detect whether any auth call was issued to suppress the initial auth change callback.

When a call starts, ensure that changePromise is fully settled (i.e., wait on it until it stops changing), then reset it to a fresh promise. Run the call and chain any auth callbacks that invoke _handleAuthChange onto changePromise, effectively "assigning" them all to the outstanding auth request for as long as it's running. When the bridge resolves the auth call block on the then-current changePromise to finish out the client call.

There's a small twist on the worker side as userToJson is async and not guaranteed to complete in invocation order, which could move an auth callback to after the enclosing call resolves. Work around it by serializing all userToJson calls as well (or at least their output, which would help preserve concurrency on the getIdTokenResult() calls).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, with one correction to the ordering you described.

Client-issued calls are fully serialized and _auth.serial is gone, replaced by a flag that only records whether a call was issued, to suppress the initial callback. A call waits out the previous queue, runs, and blocks on the then-current changePromise to finish.

The one change: a call has to claim the queue synchronously, not after awaiting the previous tail. Settling first costs two microtasks, and a callback delivered inside that window chains onto the old tail where the call never observes it. A tick sweep showed authenticate() wrongly resolving at 0 and 1 ticks of delay and only rejecting at 2+. Claiming synchronously and swallowing the leftover tail's failures fixes it at every delay.

On userToJson: I haven't touched it, and I'd like your read on whether it's worth doing now. The function and all three of its call sites are in firetruss-worker/src/worker.js; firetruss never sees it, since Bridge._authCallback receives an already-serialized payload after the reordering has happened. So it needs a firetruss-worker release, not a call-site change here.

I measured what the library actually does without it, by delaying a callback past its call:

  • A late successful certification still publishes correctly. It just lands after the call resolved, so await authenticate() returns before info.user is set. State converges; only the await boundary is wrong.
  • A late rejecting certification is dropped: the call resolves successfully and the error surfaces nowhere.
  • It does not leak into the next call. I checked specifically, since that was the failure mode of the claimant approach: a subsequent authenticate() completes on its own certification and doesn't inherit the stale failure.

So the residual hole is "error propagation is best-effort for callbacks that outlive their call", not an ordering or attribution bug, and it's strictly narrower than what the base branch does today. It also needs a getIdTokenResult() slow enough to cross a macrotask boundary, which I'd guess means a genuine token refresh rather than a cache hit, though you'd know better than I would whether that's common in practice.

Happy to send a firetruss-worker PR if you want it closed: serializing the calls as you described, or just the _send/_lastJsonUser continuations to keep the getIdTokenResult() calls concurrent. Worth noting the dedup check sits inside that same unordered continuation, so out-of-order completion can suppress the wrong callback too; that part can only be fixed in the worker. Otherwise I'll leave it and this PR stands on its own.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't follow the need to claim the queue synchronously. The idea is to wait for the change queue to settle first (mostly just in case we got unsolicited auth callbacks from Firebase), then when it looks settled synchronously start the task.

As for userToJson ordering, yeah, I think it's important not to drop rejections. I don't know whether getIdTokenResult is slow enough to cause this in practice but even if I did we wouldn't want to rely on an implementation detail. In fact, I think it might be a good idea to make all worker returns/callbacks in the same order as we receive them from Firebase for sanity's sake, as long as it doesn't make a huge mess in the code.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current tick tests deliver an auth callback before the corresponding RPC exists. I verified that after authenticate(); await Promise.resolve(), no auth request has yet been created by Bridge. Such a callback is background work, so it should not establish that the new call must claim it before starting. Once the old certification chain is stable, resetting it and starting the task synchronously is the appropriate boundary.

There is also a separate boundary error at completion: _finishAuthCall() drains a changing chain instead of awaiting a fixed snapshot. I held A's certification open, delivered A's RPC response, let its completion continuation run, then delivered a later background certification that fails. Releasing A causes A's authentication to reject with that later error. It should finish on the snapshot captured when its RPC settled; the later callback belongs to the background chain that the next turn drains.

Please drain until stable before resetting/starting the next serialized turn, and capture a fixed certification result at RPC settlement, preserving that snapshot's errors. The current shared pendingFailure also needs to respect that boundary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented as you described: every auth change delivered while a call runs is assigned to it, the window closes once its certification queue goes quiet, and later changes go to whoever runs next. No pairing of callbacks to requests.

One hole remains, and I'd like your call on it. If a call's auth change arrives after its queue has gone quiet, the call resolves and the certification failure is reported to nobody:

callback before response -> authenticate() rejects with the certification error  (correct)
callback after  response -> authenticate() resolves, error dropped

r8 behaves the same way, so it isn't new. It's inherent to assigning by window: once the queue is quiet, nothing distinguishes a late answer from an unsolicited background change, since Bridge._authCallback(server, auth) carries only the user.

With Reviewable/firetruss-worker#27 the callback precedes the response, so the correct line is what occurs today, and per your separate point that ordering has to be guaranteed in the worker rather than assumed of the SDK. What I didn't do is encode it as an invariant the library depends on. Closing the hole properly means real correlation: a request id through the bridge and worker so a callback can name the request it answers, which is a protocol change across both repos.

So leave the hole open and documented, or do you want the request id?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No request ID is needed for the agreed design. Preserve and document the worker's output-order guarantee, then use the start-of-turn and RPC-settlement boundaries we discussed. A callback arriving before the request is issued cannot answer it; one arriving after the captured settlement boundary is background work.

The current implementation still does not implement the completion boundary: _concludeAttempt() drains until the chain goes quiet. I reproduced the same failure on r13 with the actual Bridge: hold A's certify.onBefore, deliver A's callback and RPC response, let the RPC continuation run, then deliver a later background callback that fails. Release A, and A's authentication rejects with the later background error.

Please await the fixed result captured at RPC settlement, without extending that call's result to later callbacks. The added test lets the call's window close before delivering the failing callback, so it does not cover the interval where the RPC has settled but its own certification is still pending. Keep that certification pending in the regression test. The too-early start boundary is tracked separately in the reopened drain discussion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The completion boundary is fixed: a call finishes on the result captured when its request settled, and the test keeps the call's own certification pending across that boundary. The ordering guarantee it relies on is documented in the code here and enforced in Reviewable/firetruss-worker#27, so these two need to land together.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified the completion boundary with the actual Bridge: I hold the call's own certification, deliver its callback and RPC response after the request exists, then deliver a failing background callback before releasing that certification. The initiating call now resolves without adopting the later failure.

The added test a background failure after settlement does not fail the call still delivers mine after just one microtask from public authenticate(), before its RPC has been issued, so it doesn't establish that mine is owned by that request. Please synchronize that test on request issuance before delivering its callback; the implementation passes the properly synchronized reproduction.

@snoack
snoack force-pushed the serialize-certifications branch from 7dd6487 to 409cc1a Compare September 15, 2026 02:47
@snoack
snoack requested a review from pkaminski September 15, 2026 02:47

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 2 comments and resolved 1 discussion.
Reviewable status: 1 of 9 files reviewed, 3 unresolved discussions (waiting on pkaminski and pkaminski+CODX).

Comment thread src/MetaTree.js Outdated
this._auth.serial++;
// Claim the next certification before the request goes out, so that concurrent
// authentications each await their own result rather than whichever landed last.
const certified = this._claimCertification();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
Comment on lines +80 to +81
const claimant = this._auth.claimants.shift();
if (claimant) promise.then(claimant.resolve, claimant.reject);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski Confirmed. Queueing the claim when the bridge request is issued still pairs requests to callbacks by position, and a callback carries a user, not a request identity. Is that pairing guaranteed? If not, should authenticate() stop waiting on certification and let callers observe root.user?

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the complexity here is straining the capabilities of LLMs. They can still find issues but are pretty bad at coming up with a simple, coherent design. I did my best below but this stuff is hard to don't take it at face value.

@pkaminski reviewed 6 files and all commit messages, and made 3 comments.
Reviewable status: 7 of 9 files reviewed, 3 unresolved discussions (waiting on pkaminski+CODX and snoack).

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. I think Dispatcher.begin can resolve with the results, then execute pass them into the executor for decision-making. We should not reimplement execute.
  2. We want to keep the call inside the serialized turn but bridge.unauth is too low-level: we still want to certify the logout, issue an auth/unauthenticate operation, etc. Basically, we need to factor out the guts of unauthenticate for re-entrant use here while still prohibiting re-entrancy on unauthenticate itself. (And specifically any callbacks during this nested call would still be counted against the original authenticate call, per my serialization suggestion in the other thread.)
  3. I believe the auth serial is not sufficient. My leading idea so far is to 1) serialize all client-originated auth calls and 2) have the internal unauthenticate method described above pass a new force: true flag to _handleAuthChange that bypasses the equality checks. This will force all logout calls to be issued (whether explicit or due to auth rejection) and save the bypass for auth change notification callbacks only.

The proposed AUTH_REJECTED error is fine, just make sure that any forced logout errors take precedence.

Comment thread src/MetaTree.js Outdated
Comment on lines +80 to +81
const claimant = this._auth.claimants.shift();
if (claimant) promise.then(claimant.resolve, claimant.reject);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The pairing is not guaranteed but we don't want to observe root.user either. My proposal:

First, fully serialize client-issued authenticate / unauthenticate calls. This will simplify a lot of things and should let us get rid of _auth.serial, though we'll still need some (simpler) mechanism to detect whether any auth call was issued to suppress the initial auth change callback.

When a call starts, ensure that changePromise is fully settled (i.e., wait on it until it stops changing), then reset it to a fresh promise. Run the call and chain any auth callbacks that invoke _handleAuthChange onto changePromise, effectively "assigning" them all to the outstanding auth request for as long as it's running. When the bridge resolves the auth call block on the then-current changePromise to finish out the client call.

There's a small twist on the worker side as userToJson is async and not guaranteed to complete in invocation order, which could move an auth callback to after the enclosing call resolves. Work around it by serializing all userToJson calls as well (or at least their output, which would help preserve concurrency on the getIdTokenResult() calls).

@snoack
snoack force-pushed the serialize-certifications branch from 409cc1a to ca8fa2a Compare September 16, 2026 02:45
@snoack
snoack requested a review from pkaminski September 16, 2026 02:45

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 2 comments.
Reviewable status: 7 of 9 files reviewed, 3 unresolved discussions (waiting on pkaminski and pkaminski+CODX).

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented, with one adjustment to the mechanism you described.

Dispatcher.begin() now resolves with the onBefore results and execute() passes them to the executor, so certify reads the verdict without reimplementing execute(). A literal false from any handler rejects a non-null candidate; all handlers settle first. The rejected user is signed out from inside the same turn via the factored-out logout guts, wrapped in an auth/unauthenticate operation with the null certification included, so every logout failure reaches an onFailure with op.method === 'unauthenticate'. The call then rejects with AUTH_REJECTED as error.code, and a failed sign-out takes precedence over it.

The force: true flag turned out to be unnecessary. Since _signOut() sequences bridge.unauth after the null certification rather than gating on it, an already-null client user still reaches the worker; the equality check only skips the redundant publish. I dropped the parameter rather than carry one nothing passes. If you wanted force to cover a case beyond that, say so and I'll put it back.

Reentrant public auth calls from an interceptor are now unsupported, as agreed. I encoded that as a test asserting the call hangs, which pins current behaviour rather than a designed failure mode; happy to make it throw immediately instead if you'd prefer something explicit.

Also fixed: unathenticate was misspelled in INTERCEPT_KEYS and in the type declarations, so intercept('unauthenticate', ...) threw and per-method logout interception was impossible. That was load-bearing for the onFailure requirement above.

Comment thread src/MetaTree.js Outdated
Comment on lines +80 to +81
const claimant = this._auth.claimants.shift();
if (claimant) promise.then(claimant.resolve, claimant.reject);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, with one correction to the ordering you described.

Client-issued calls are fully serialized and _auth.serial is gone, replaced by a flag that only records whether a call was issued, to suppress the initial callback. A call waits out the previous queue, runs, and blocks on the then-current changePromise to finish.

The one change: a call has to claim the queue synchronously, not after awaiting the previous tail. Settling first costs two microtasks, and a callback delivered inside that window chains onto the old tail where the call never observes it. A tick sweep showed authenticate() wrongly resolving at 0 and 1 ticks of delay and only rejecting at 2+. Claiming synchronously and swallowing the leftover tail's failures fixes it at every delay.

On userToJson: I haven't touched it, and I'd like your read on whether it's worth doing now. The function and all three of its call sites are in firetruss-worker/src/worker.js; firetruss never sees it, since Bridge._authCallback receives an already-serialized payload after the reordering has happened. So it needs a firetruss-worker release, not a call-site change here.

I measured what the library actually does without it, by delaying a callback past its call:

  • A late successful certification still publishes correctly. It just lands after the call resolved, so await authenticate() returns before info.user is set. State converges; only the await boundary is wrong.
  • A late rejecting certification is dropped: the call resolves successfully and the error surfaces nowhere.
  • It does not leak into the next call. I checked specifically, since that was the failure mode of the claimant approach: a subsequent authenticate() completes on its own certification and doesn't inherit the stale failure.

So the residual hole is "error propagation is best-effort for callbacks that outlive their call", not an ordering or attribution bug, and it's strictly narrower than what the base branch does today. It also needs a getIdTokenResult() slow enough to cross a macrotask boundary, which I'd guess means a genuine token refresh rather than a cache hit, though you'd know better than I would whether that's common in practice.

Happy to send a firetruss-worker PR if you want it closed: serializing the calls as you described, or just the _send/_lastJsonUser continuations to keep the getIdTokenResult() calls concurrent. Worth noting the dedup check sits inside that same unordered continuation, so out-of-order completion can suppress the wrong callback too; that part can only be fixed in the worker. Otherwise I'll leave it and this PR stands on its own.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca8fa2aca2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/MetaTree.js Outdated
// callbacks on the old tail, where this call would never see their outcome. Failures left
// over from before the claim belong to whoever was waiting on them, so they're swallowed here.
const previousTail = this._auth.changePromise;
this._auth.changePromise = Promise.resolve();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep in-flight certifications on the shared queue

When an existing certification is paused in an asynchronous interceptor and the application calls authenticate() or unauthenticate(), resetting the tail here detaches that certification immediately. Any subsequent bridge callback chains from this resolved promise and can certify concurrently; for example, a late sign-out can be discarded against the still-null root before the detached sign-in resumes and publishes its stale user. Fresh evidence after the earlier bridge-queue report is this synchronous queue reset, which reintroduces the bypass even though _handleAuthChange() itself now always chains.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed on r8 with the real Bridge, MetaTree, and Dispatcher. Starting at null, I paused a user certification in onBefore, called authenticate('next'), and delivered a null callback while that certification was still paused. The null callback completed against the reset tail and was discarded as a duplicate. Releasing the older certification then published the old user: final userid === 'old', despite the later sign-out notification.

The new request had not even reached the worker at the point the sign-out was lost. Keep the existing certification chain intact while waiting; reset only after the chain is fully drained and the serialized auth turn can actually start.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
Comment on lines +92 to +95
const previousTail = this._auth.changePromise;
this._auth.changePromise = Promise.resolve();
this._auth.pendingFailure = undefined;
return previousTail.catch(_.noop).then(() => run()).then(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize each public auth call through completion

When two auth methods are invoked before the promise microtasks run, the first call installs an already-resolved replacement tail and the second captures that resolved promise, so both then(() => run()) callbacks issue their bridge requests concurrently rather than waiting for the first call to finish. With two requests outstanding, callbacks that are not guaranteed to arrive in invocation order can again associate a certification failure with the wrong public promise through the shared pendingFailure. Fresh evidence beyond the earlier claimant-order finding is that this new serialization implementation only waits for the previous certification tail, not the previous auth call.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed with the actual Bridge: call authenticate('A') and authenticate('B') back to back, withhold both worker responses, and both RPCs are sent. Waiting for the previous certification tail does not wait for the previous auth operation.

The test named “a second auth call waits for the first to finish” only checks certification log order; its bridge resolves every RPC immediately. Please hold the first RPC/certification open and assert that B's authenticate interceptors and RPC have not started. The public-call queue needs to cover the entire operation and its captured certification result.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
// over from before the claim belong to whoever was waiting on them, so they're swallowed here.
const previousTail = this._auth.changePromise;
this._auth.changePromise = Promise.resolve();
this._auth.pendingFailure = undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear prior failures only after their tail settles

When previousTail is still pending and later rejects, its recovery handler in _handleAuthChange() writes that old error into pendingFailure after this assignment has cleared it. The new auth request then runs successfully, but _finishAuthCall() observes the unrelated earlier error and rejects the new caller, so clearing the shared slot before awaiting previousTail does not isolate certification failures as intended.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed with the real Bridge/Dispatcher. I paused an unsolicited certification in onBefore, queued a new authentication, then rejected the old handler with “old background failure”. The new request subsequently received its own successful user callback and RPC response; it published the new user but still rejected with the old error.

Clearing pendingFailure before the previous tail settles lets that tail's recovery handler refill the slot. Drain first, then reset the result state synchronously when starting the next serialized operation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 8 files and all commit messages, and made 2 comments.
Reviewable status: 9 of 11 files reviewed, 7 unresolved discussions (waiting on pkaminski+CODX and snoack).


src/MetaTree.js line 83 at r8 (raw file):

  // to it:  the bridge can deliver a callback and resolve the call's RPC in the same batch, and
  // the worker's `userToJson` doesn't guarantee that callbacks arrive in invocation order, so
  // waiting on the queue as it stands when the call finishes is what ties the two together.

That doesn't feel robust to me: there's no guarantee misordered callbacks will arrive in the same batch, in which case we'd miss the auth callback completely. I think we need to ensure the worker makes callbacks in order.

Comment thread src/MetaTree.js Outdated
Comment on lines +80 to +81
const claimant = this._auth.claimants.shift();
if (claimant) promise.then(claimant.resolve, claimant.reject);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't follow the need to claim the queue synchronously. The idea is to wait for the change queue to settle first (mostly just in case we got unsolicited auth callbacks from Firebase), then when it looks settled synchronously start the task.

As for userToJson ordering, yeah, I think it's important not to drop rejections. I don't know whether getIdTokenResult is slow enough to cause this in practice but even if I did we wouldn't want to rely on an implementation detail. In fact, I think it might be a good idea to make all worker returns/callbacks in the same order as we receive them from Firebase for sanity's sake, as long as it doesn't make a huge mess in the code.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski+CODX reviewed 4 files and all commit messages, and made 8 comments.
Reviewable status: all files reviewed, 8 unresolved discussions (waiting on pkaminski and snoack).


src/MetaTree.js line 83 at r8 (raw file):

Previously, pkaminski (Piotr Kaminski) wrote…

That doesn't feel robust to me: there's no guarantee misordered callbacks will arrive in the same batch, in which case we'd miss the auth callback completely. I think we need to ensure the worker makes callbacks in order.

Confirmed independently with the actual firetruss-worker/src/worker.js: the Firebase stub invokes its auth callback before resolving sign-in, but I hold that callback's getIdTokenResult() pending and let the RPC's conversion finish. The worker sends resolve in one batch and only sends callback after I release the pending conversion in a later turn.

So client-side draining cannot recover the missing callback at the await boundary. Output ordering needs to be preserved in the worker, including the _lastJsonUser deduplication update. This reproduces even when Firebase itself invokes the callback and resolves the call in the assumed order.


src/MetaTree.js line 160 at r8 (raw file):

        return true;
      }
    ).then(outcome => {

Run rejection logout even if the candidate's onAfter fails. The 'rejected' outcome is only examined after Dispatcher.execute() has successfully finished onAfter. If certify.onBefore returns false and a certify.onAfter handler throws, this continuation never runs and _signOut() is skipped entirely.

I reproduced this through the actual Bridge/MetaTree/Dispatcher: start signed out, deliver the candidate callback and successful auth RPC response, return false from its before handler, and throw “after hook failed” from its after handler. Authentication rejects, the client stays null, no worker sign-out request is issued, and the only auth.onFailure operation has method === 'certify'. Firebase therefore retains the rejected login, and the agreed fatal-logout handler cannot detect the desynchronization.

Once a rejection has been decided, preserve that decision across after-hook failure and still perform the internal logout. Report the original hook error after successful cleanup, with any logout failure taking precedence and reaching unauthenticate.onFailure. Please cover this failure path as well as a normal false rejection.

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extracted logout does satisfy the already-null cleanup requirement without a force parameter: it calls _certify(null) directly, bypassing the outer duplicate check. The remaining equality check only skips publication; Dispatcher still runs both hook stages. I verified a false rejection while another handler asynchronously installs a key: installation finishes, null onBefore and onAfter run, the key is cleared, the worker is signed out, and the caller gets AUTH_REJECTED.

One error-precedence issue remains in _runAuthCall line 99. If the public logout's bridge request fails and a certification also fails during that request, _finishAuthCall() rejects before the continuation that rethrows the original logout error. My reproduction returns the certification error instead of “worker logout failure”. Preserve the operation's own failure while awaiting certification completion; the comment currently promises the opposite of what the code does.

The normal false-rejection and failed internal-logout tests pass. I am tracking the separate case where a failing rejection onAfter prevents logout from starting in a new inline discussion.

Comment thread src/MetaTree.js Outdated
// the failure from authenticate(), which waits on the result instead.
if (!nested) {
this._auth.changePromise = promise.catch(_.noop);
this._auth.resultPromise = promise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is still reproducible on r8 after the claimant implementation was removed. Using the actual Bridge, I issued A and B and delivered one batch containing callback A, resolution A, callback B, resolution B. When A's certification succeeds and B's fails, A rejects with B's error and B resolves: the first finisher consumes and clears the shared pendingFailure.

The opposite failure order happens to pass. The missing public-call serialization is tracked in the newer report; both failure orders should remain regression tests for that fix.

Comment thread src/MetaTree.js Outdated
Comment on lines +80 to +81
const claimant = this._auth.claimants.shift();
if (claimant) promise.then(claimant.resolve, claimant.reject);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current tick tests deliver an auth callback before the corresponding RPC exists. I verified that after authenticate(); await Promise.resolve(), no auth request has yet been created by Bridge. Such a callback is background work, so it should not establish that the new call must claim it before starting. Once the old certification chain is stable, resetting it and starting the task synchronously is the appropriate boundary.

There is also a separate boundary error at completion: _finishAuthCall() drains a changing chain instead of awaiting a fixed snapshot. I held A's certification open, delivered A's RPC response, let its completion continuation run, then delivered a later background certification that fails. Releasing A causes A's authentication to reject with that later error. It should finish on the snapshot captured when its RPC settled; the later callback belongs to the background chain that the next turn drains.

Please drain until stable before resetting/starting the next serialized turn, and capture a fixed certification result at RPC settlement, preserving that snapshot's errors. The current shared pendingFailure also needs to respect that boundary.

Comment thread src/MetaTree.js Outdated
// callbacks on the old tail, where this call would never see their outcome. Failures left
// over from before the claim belong to whoever was waiting on them, so they're swallowed here.
const previousTail = this._auth.changePromise;
this._auth.changePromise = Promise.resolve();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed on r8 with the real Bridge, MetaTree, and Dispatcher. Starting at null, I paused a user certification in onBefore, called authenticate('next'), and delivered a null callback while that certification was still paused. The null callback completed against the reset tail and was discarded as a duplicate. Releasing the older certification then published the old user: final userid === 'old', despite the later sign-out notification.

The new request had not even reached the worker at the point the sign-out was lost. Keep the existing certification chain intact while waiting; reset only after the chain is fully drained and the serialized auth turn can actually start.

Comment thread src/MetaTree.js Outdated
// over from before the claim belong to whoever was waiting on them, so they're swallowed here.
const previousTail = this._auth.changePromise;
this._auth.changePromise = Promise.resolve();
this._auth.pendingFailure = undefined;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed with the real Bridge/Dispatcher. I paused an unsolicited certification in onBefore, queued a new authentication, then rejected the old handler with “old background failure”. The new request subsequently received its own successful user callback and RPC response; it published the new user but still rejected with the old error.

Clearing pendingFailure before the previous tail settles lets that tail's recovery handler refill the slot. Drain first, then reset the result state synchronously when starting the next serialized operation.

Comment thread src/MetaTree.js Outdated
Comment on lines +92 to +95
const previousTail = this._auth.changePromise;
this._auth.changePromise = Promise.resolve();
this._auth.pendingFailure = undefined;
return previousTail.catch(_.noop).then(() => run()).then(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed with the actual Bridge: call authenticate('A') and authenticate('B') back to back, withhold both worker responses, and both RPCs are sent. Waiting for the previous certification tail does not wait for the previous auth operation.

The test named “a second auth call waits for the first to finish” only checks certification log order; its bridge resolves every RPC immediately. Please hold the first RPC/certification open and assert that B's authenticate interceptors and RPC have not started. The public-call queue needs to cover the entire operation and its captured certification result.

@snoack
snoack requested a review from pkaminski September 24, 2026 01:21
@snoack
snoack force-pushed the serialize-certifications branch from 5ee262d to 4ca0a2b Compare September 29, 2026 02:39

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 2 comments.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski+CODX).

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
operation.onBeforeSettled
.then(() => this._settleChangePromise())
.then(() => {
if (refuses() && this.root.user === publishedWhenFailed) return this._signOut();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fail-fast: Done, with one thing to confirm. Certification holds its turn until every handler settles, including on rejection, the cleanup is inline again, and the out-of-band late-refusal mechanism is gone; fail-fast is retained for other operation types. On "retain both their false verdicts and errors": all verdicts are retained, but only the first error is reported and the rest are dropped, as on master. The difference now is that "first" is by registration order rather than by which rejected soonest. Say if you want every error surfaced, since that changes the public contract.

Agreed, and that's what r20 does for certification: its turn is held until every onBefore settles, rejection included, so a handler that blocks forever holds the turn rather than being rescued.

I kept fail-fast for the other operation types, since a read or write interceptor can't mutate auth state and nothing there needs a sibling's verdict. Say if you'd rather that were uniform.

Agreed, and made uniform: every onBefore settles before any verdict is acted on, whatever the operation. That dropped the settleAll option from execute and begin, and begin itself from 23 lines to 15 lines.

Worth flagging since it reaches beyond auth: an interceptor that never settles now holds its read or write instead of being rescued by a sibling's rejection. That's your point, but it's a behavior change for any app code using intercept, so say if you'd rather it stayed scoped to certification.

@snoack
snoack requested a review from pkaminski September 29, 2026 02:42

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 1 comment.
Reviewable status: 2 of 11 files reviewed, 2 unresolved discussions (waiting on pkaminski and pkaminski+CODX).

Comment thread src/MetaTree.js Outdated
operation.onBeforeSettled
.then(() => this._settleChangePromise())
.then(() => {
if (refuses() && this.root.user === publishedWhenFailed) return this._signOut();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please ignore everything but the last two paragraphs in my reply above. The first 3 paragraphs were part of an earlier draft I though I had deleted.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4ca0a2b65d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/Dispatcher.js
Comment on lines +202 to +204
(onBefore, index) => Promise.resolve()
.then(() => onBefore(operation))
.then(result => {results[index] = result;}, error => error)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve fail-fast behavior for non-certify hooks

When any non-certify operation has one onBefore interceptor reject while a sibling remains pending, converting every rejection into a fulfilled value makes the outer Promise.all wait indefinitely, so the operation never reaches its failure handling. Fresh evidence after the earlier fix is that the final begin() implementation applies this all-settled behavior to every operation without an operation.method === 'certify' guard; retain wait-for-all only for certification and preserve the previous fail-fast behavior elsewhere.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed with @pkaminski we decided to abandon the fast-fail behavior.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed with the resolution: @pkaminski explicitly chose wait-for-all for every operation, so restoring fail-fast outside certification would contradict that decision. I verified r20 with controlled read and write hooks: the operation stays pending until the sibling settles, then reports the hook error without running its executor.

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 1 comment and resolved 1 discussion.
Reviewable status: 2 of 11 files reviewed, 2 unresolved discussions (waiting on pkaminski and pkaminski+CODX).

Comment thread src/Dispatcher.js
Comment on lines +202 to +204
(onBefore, index) => Promise.resolve()
.then(() => onBefore(operation))
.then(result => {results[index] = result;}, error => error)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed with @pkaminski we decided to abandon the fast-fail behavior.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski+CODX reviewed 9 files and all commit messages, and made 3 comments.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski and snoack).

Comment thread src/Dispatcher.js
Comment on lines +202 to +204
(onBefore, index) => Promise.resolve()
.then(() => onBefore(operation))
.then(result => {results[index] = result;}, error => error)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed with the resolution: @pkaminski explicitly chose wait-for-all for every operation, so restoring fail-fast outside certification would contradict that decision. I verified r20 with controlled read and write hooks: the operation stays pending until the sibling settles, then reports the hook error without running its executor.

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The public logout scheduling change fixes the previous reproduction: a token refresh now waits until the paused null onAfter completes.

The queue still releases early if an onAfter sibling fails. Dispatcher.end() (r20 Dispatcher.js:255-264) still uses fail-fast Promise.all. A rejected handler reaches _afterEnd() immediately, so the new certification queue considers the turn finished while another after handler is still running.

With r20 and worker r4 through the actual Bridge, I delivered a background null callback, paused one null after handler before clearing its simulated key, and made a sibling after handler throw. A subsequent public login issued its RPC, installed a new key, published, and resolved before the old cleanup was released. Releasing it then left userid === 'new' with no key. Only certify.onFailure ran; there was no failed unauthenticate operation for the proposed fatal-logout handler to catch.

This uses controlled asynchronous key hooks to demonstrate the library's lifecycle overlap; it is not evidence that Reviewable's synchronous worker key-configuration function performs that exact delayed mutation. The fail-fast behavior in end() predates this revision, but it still defeats the required serialization through cleanup. Please keep the turn until all after handlers settle, including on error, then report the failure. Cover a failing after handler alongside a still-pending sibling.

Comment thread src/MetaTree.js Outdated
operation.onBeforeSettled
.then(() => this._settleChangePromise())
.then(() => {
if (refuses() && this.root.user === publishedWhenFailed) return this._signOut();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The r19 reproductions now pass: a false verdict plus a throwing sibling waits for slow key installation before cleanup, and a queued second public login starts only after that cleanup. Making this wait-for-all behavior uniform also matches @pkaminski's latest decision.

A retry can still be canceled by background rejection cleanup. _startAuthCall() drains changePromise only once (r20 MetaTree.js:111); when Dispatcher.execute() retries its executor, collect() sends the next RPC without that drain. I reproduced this with r20, worker r4, and the actual Bridge, using controlled Firebase callbacks and hook promises:

  1. The first login's RPC settles while its certification is paused.
  2. A background user callback arrives outside that RPC's window and queues behind it.
  3. The first certification fails, and authenticate.onError requests a retry. The background certification is now paused before returning false.
  4. The retry RPC nevertheless signs in. Releasing the background false verdict then issues its inline logout against that newer login.

Observed requests: authenticate, authenticate, unauth. The public authenticate() resolves successfully, but both the client and worker finish signed out. This is a remaining instance of the newer-login cancellation discussed here, without _signOutLateRefusal.

Please drain pending certifications before each public RPC attempt, including retries, and open the collector only after that drain. Keep rejection cleanup inline. A diagnostic control adding the drain before each attempt changes the order to authenticate, unauth, authenticate and leaves the retried user signed in.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 7 files and all commit messages.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on snoack).

@snoack
snoack force-pushed the serialize-certifications branch from 4ca0a2b to 2bf839b Compare September 29, 2026 21:56

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 2 comments.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski+CODX).

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread src/MetaTree.js Outdated
operation.onBeforeSettled
.then(() => this._settleChangePromise())
.then(() => {
if (refuses() && this.root.user === publishedWhenFailed) return this._signOut();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 9 files and all commit messages, and made 2 comments.
Reviewable status: all files reviewed, 4 unresolved discussions (waiting on pkaminski+CODX and snoack).


src/MetaTree.js line 88 at r21 (raw file):

  // Runs a client-issued auth call with exclusive ownership of the certification queue.  Calls are
  // serialized over their whole operation, since the bridge can deliver a callback and resolve the
  // call's RPC in the same batch, and the worker's `userToJson` doesn't guarantee that callbacks

The worker now does guarantee that callbacks arrive in invocation order. Though you probably need to bump MIN_WORKER_VERSION in Bridge.js to ensure this.


src/MetaTree.js line 102 at r21 (raw file):

  // Runs one call once it owns the queue.  Any certifications still in flight belong to whoever
  // came before, so they're drained to a standstill before this call runs:  resetting the chain

I thought that all in-flight certifications will be settled before a call completes and relinquishes the call queue? I assume you mean background certifications with no owning call.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski+CODX reviewed 9 files and all commit messages, made 4 comments, and resolved 2 discussions.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski).


src/MetaTree.js line 88 at r21 (raw file):

Previously, pkaminski (Piotr Kaminski) wrote…

The worker now does guarantee that callbacks arrive in invocation order. Though you probably need to bump MIN_WORKER_VERSION in Bridge.js to ensure this.

Confirmed: this is a required compatibility check. r21 still has MIN_WORKER_VERSION = '4.0.0', and I verified that Bridge.init() accepts 4.1.1. Worker #27 introduces the ordering guarantee in 4.1.2.

I paired this client revision with the exact pre-PR worker source (515d2f9, version 4.1.1), held an older refresh's token lookup, and called logout. Logout resolved with a null client; releasing the lookup then republished old-refresh after logout. With worker r4, logout instead waits, messages arrive as refresh → null → RPC result, and the client remains null. The old worker also allows a sign-in RPC response to precede its auth callback.

Please raise the minimum to 4.1.2 and update the stale comment about unordered worker callbacks. Parse the version components numerically when adjusting the threshold: the current string comparison would treat patch 10 as less than 2, incorrectly rejecting 4.1.10 against a 4.1.2 minimum.


src/MetaTree.js line 102 at r21 (raw file):

Previously, pkaminski (Piotr Kaminski) wrote…

I thought that all in-flight certifications will be settled before a call completes and relinquishes the call queue? I assume you mean background certifications with no owning call.

Yes: the residual work is background certification, with no owning call. _concludeAttempt() waits for collector.owned, covering callbacks delivered during the RPC's lifetime. A callback delivered after RPC settlement can still be pending when the public call finishes. I verified this with a held background hook: the first call completes, but the next call's RPC waits until that hook is released.

There is also a wording change needed for r21: the drain now lives inside collect(), immediately before each RPC attempt. The operation's onBefore hooks can already run while the background certification is pending, so “before this call runs” is no longer accurate. Describe the background drain before each RPC attempt, and the wait for owned certifications before completing that attempt.

Comment thread src/MetaTree.js Outdated
// An interceptor of the running certification may itself trigger an auth change, and queueing
// that behind the certification whose interceptor is awaiting it would deadlock both. Such a
// nested change is already ordered by the interceptor that asked for it, so run it directly.
const queue = this._auth.certifying ? Promise.resolve() : this._auth.changePromise;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on r21 with worker r4 using the original Bridge/worker reproduction. The failing after handler now waits for the paused sibling cleanup: the next login sends no RPC before cleanup is released, and the order is install old → clear → install new. The new user retains its key. The original failure still reaches certify.onFailure. This closes the remaining after-hook serialization issue.

Comment thread src/MetaTree.js Outdated
operation.onBeforeSettled
.then(() => this._settleChangePromise())
.then(() => {
if (refuses() && this.root.user === publishedWhenFailed) return this._signOut();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on r21 with the original controlled Bridge/worker reproduction, without the diagnostic workaround. While background certification is paused, only the first authenticate RPC has been issued. Releasing its false verdict produces authenticate → unauth → authenticate; the retry succeeds and both client and worker retain the retried user. The collector stays closed during the drain. This fixes the reported retry race. All 99 suite and existing diagnostic checks passed, including both r20 failures; lint passed and rebuilding dist reproduced the committed artifacts.

@snoack
snoack force-pushed the serialize-certifications branch from 2bf839b to f1a1c89 Compare September 30, 2026 00:04

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 1 comment and resolved 1 discussion.
Reviewable status: all files reviewed, 1 unresolved discussion (waiting on pkaminski+CODX).


src/MetaTree.js line 88 at r21 (raw file):

Previously, pkaminski+CODX (Agent CODX for Piotr Kaminski) wrote…

Confirmed: this is a required compatibility check. r21 still has MIN_WORKER_VERSION = '4.0.0', and I verified that Bridge.init() accepts 4.1.1. Worker #27 introduces the ordering guarantee in 4.1.2.

I paired this client revision with the exact pre-PR worker source (515d2f9, version 4.1.1), held an older refresh's token lookup, and called logout. Logout resolved with a null client; releasing the lookup then republished old-refresh after logout. With worker r4, logout instead waits, messages arrive as refresh → null → RPC result, and the client remains null. The old worker also allows a sign-in RPC response to precede its auth callback.

Please raise the minimum to 4.1.2 and update the stale comment about unordered worker callbacks. Parse the version components numerically when adjusting the threshold: the current string comparison would treat patch 10 as less than 2, incorrectly rejecting 4.1.10 against a 4.1.2 minimum.

Done, bumped to 4.1.2, with a comment on why that's the floor. Verified the gate rejects 4.1.1 and 4.0.0 and accepts 4.1.2 and above. This does mean worker 4.1.2 needs publishing before a client with this gate ships.

Unrelated, but noticed while there: the comparison in init() compares the regex capture groups as strings, so a future 4.1.10 worker would be rejected against a 4.1.2 minimum. Pre-existing, so I've left it; happy to fix separately?

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f1a1c891d3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/Bridge.js
// 4.1.2 is the first worker that delivers auth results in the order Firebase reported them, which
// the serialized certifications in `MetaTree` rely on to tell a call's own answer from a background
// change.
const MIN_WORKER_VERSION = '4.1.2';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Compare the raised worker version numerically

With the minimum raised to 4.1.2, the existing comparison now rejects valid compatible workers once the patch reaches two digits: for example, 4.1.10 is compared as strings, so '10' >= '2' is false and Bridge.init() aborts with an incompatibility error. Parse the captured major, minor, and patch components as numbers before comparing them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed in the other thread.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 7 files and all commit messages, and made 1 comment.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski+CODX and snoack).


src/MetaTree.js line 88 at r21 (raw file):

Previously, snoack (Sebastian Noack) wrote…

Done, bumped to 4.1.2, with a comment on why that's the floor. Verified the gate rejects 4.1.1 and 4.0.0 and accepts 4.1.2 and above. This does mean worker 4.1.2 needs publishing before a client with this gate ships.

Unrelated, but noticed while there: the comparison in init() compares the regex capture groups as strings, so a future 4.1.10 worker would be rejected against a 4.1.2 minimum. Pre-existing, so I've left it; happy to fix separately?

Yes, we should fix the version parsing. But also the comment here is still outdated.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski+CODX reviewed 7 files and all commit messages, and made 1 comment.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski and snoack).


src/MetaTree.js line 88 at r21 (raw file):

Previously, pkaminski (Piotr Kaminski) wrote…

Yes, we should fix the version parsing. But also the comment here is still outdated.

Verified the r22 minimum-version change through Bridge.init(): 4.0.0 and 4.1.1 are rejected, and 4.1.2 is accepted. Numeric comparison is still required in this PR: raising the floor activates the previously latent string-comparison bug. My compatibility tests reject valid 4.1.10 and 4.1.11, while accepting 4.1.9 and 4.1.20. Please convert the captured components to numbers and cover this boundary.

The MetaTree.js:87-88 comment still says the worker does not guarantee callback invocation order, so that requested correction is also outstanding. The revision otherwise only changes the minimum constant and its explanation; lint passes and rebuilt dist matches. Keeping the existing thread blocking rather than adding another finding.

@snoack
snoack force-pushed the serialize-certifications branch from f1a1c89 to d4ded27 Compare September 30, 2026 02:27

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 2 comments and resolved 1 discussion.
Reviewable status: all files reviewed, 1 unresolved discussion (waiting on pkaminski+CODX).


src/MetaTree.js line 88 at r21 (raw file):

Yes, we should fix the version parsing

#45

But also the comment here is still outdated.

Done.

Comment thread src/Bridge.js
// 4.1.2 is the first worker that delivers auth results in the order Firebase reported them, which
// the serialized certifications in `MetaTree` rely on to tell a call's own answer from a background
// change.
const MIN_WORKER_VERSION = '4.1.2';

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Discussed in the other thread.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d4ded272a3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/MetaTree.js
// Only the bridge request is wrapped: this certification can wait on its own interceptors,
// and a callback arriving during that wait predates the request, so it's background work
// rather than this call's result.
return certifyNull(null).then(() => collect(() => this._bridge.unauth(this._rootUrl)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Always clear a refused worker session

When a candidate's certify.onBefore returns false and a hook rejects during the internally generated null certification—for example, a certify.onAfter cleanup throws—this rejected .then() prevents _bridge.unauth() from running. The candidate remains authenticated in the worker even though it was explicitly refused and never published locally; the forced-rejection path should still issue the worker sign-out while preserving the cleanup error.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the forced-rejection path should still issue the worker sign-out while preserving the cleanup error

Reproduced: with a candidate refused by false and the internally generated null certification's onAfter throwing, _bridge.unauth() never runs, so the worker keeps a session the app explicitly refused while the client stays null. Same on r8, so it predates this revision rather than being new.

Before changing it, @pkaminski, I want to check which way you want this, because the contract reads two ways depending on the path and there's a test asserting the opposite of what's being asked.

From the original contract, listing the failure paths this change was meant to close:

With r5, a null-certification key-cleanup failure reports only certify and never calls worker sign-out.

But later, on the error-precedence thread:

The null-certification/worker failures still reach the unauthenticate operation, and the already-null cleanup behavior remains intact.

and a null certification failure reaches an unauthenticate onFailure asserts exactly that, unauthCalls.length === 0, with the message "signed the worker out despite failed cleanup" as its failure mode.

My reading is that those are different paths: public unauthenticate() on an already-null client can skip the worker when its cleanup fails, which is what the test pins, whereas a refused candidate was never published locally and is still signed in at the worker, so its cleanup failing shouldn't leave that session behind. If that's right, the fix is scoped to the rejection path in _certify and _signOutRejected, and the public-logout behaviour and its test are untouched.

Is that the split you intended? The part I'm least sure of: if the local key cleanup failed, is signing the worker out still the right move for a refused candidate, or does a failed cleanup mean we should leave both sides alone and report? Not touching it until you say, since the two paths are close enough that I'd rather not guess.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think any unauthenticate exception (whether public or internal call) should be treated as fatal — since it means that the worker and Firebase states are out of sync — so it doesn't much matter whether we try to force the logout anyway before rethrowing the certification exception. For simplicity's sake I'd leave it as-is. Unless I'm missing something @pkaminski+CODX?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: under the policy that every failed logout is fatal, I'd leave this as-is. _signOut() wraps the null certification in the full auth/unauthenticate operation, so its failure reaches onFailure with op.method === 'unauthenticate' even if the caller catches the enclosing authentication error.

I verified this with the actual MetaTree, Dispatcher, Bridge, and worker code connected to a controlled Firebase auth stub, covering both public logout and rejected-candidate cleanup, with failures in both null-certification onBefore and onAfter. All four cases preserve the cleanup error and notify unauthenticate.onFailure. The worker does retain its session when cleanup fails, but the app has the required signal to terminate; forcing the RPC wouldn't repair the failed local cleanup. There is no need to introduce different failure behavior for the two paths.

@snoack
snoack requested a review from pkaminski September 30, 2026 02:46

@snoack snoack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snoack made 1 comment.
Reviewable status: 6 of 12 files reviewed, 2 unresolved discussions (waiting on pkaminski and pkaminski+CODX).

Comment thread src/MetaTree.js
// Only the bridge request is wrapped: this certification can wait on its own interceptors,
// and a callback arriving during that wait predates the request, so it's background work
// rather than this call's result.
return certifyNull(null).then(() => collect(() => this._bridge.unauth(this._rootUrl)));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the forced-rejection path should still issue the worker sign-out while preserving the cleanup error

Reproduced: with a candidate refused by false and the internally generated null certification's onAfter throwing, _bridge.unauth() never runs, so the worker keeps a session the app explicitly refused while the client stays null. Same on r8, so it predates this revision rather than being new.

Before changing it, @pkaminski, I want to check which way you want this, because the contract reads two ways depending on the path and there's a test asserting the opposite of what's being asked.

From the original contract, listing the failure paths this change was meant to close:

With r5, a null-certification key-cleanup failure reports only certify and never calls worker sign-out.

But later, on the error-precedence thread:

The null-certification/worker failures still reach the unauthenticate operation, and the already-null cleanup behavior remains intact.

and a null certification failure reaches an unauthenticate onFailure asserts exactly that, unauthCalls.length === 0, with the message "signed the worker out despite failed cleanup" as its failure mode.

My reading is that those are different paths: public unauthenticate() on an already-null client can skip the worker when its cleanup fails, which is what the test pins, whereas a refused candidate was never published locally and is still signed in at the worker, so its cleanup failing shouldn't leave that session behind. If that's right, the fix is scoped to the rejection path in _certify and _signOutRejected, and the public-logout behaviour and its test are untouched.

Is that the split you intended? The part I'm least sure of: if the local key cleanup failed, is signing the worker out still the right move for a refused candidate, or does a failed cleanup mean we should leave both sides alone and report? Not touching it until you say, since the two paths are close enough that I'd rather not guess.

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 6 files and all commit messages, and made 1 comment.
Reviewable status: all files reviewed, 2 unresolved discussions (waiting on pkaminski+CODX).

Comment thread src/MetaTree.js
// Only the bridge request is wrapped: this certification can wait on its own interceptors,
// and a callback arriving during that wait predates the request, so it's background work
// rather than this call's result.
return certifyNull(null).then(() => collect(() => this._bridge.unauth(this._rootUrl)));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think any unauthenticate exception (whether public or internal call) should be treated as fatal — since it means that the worker and Firebase states are out of sync — so it doesn't much matter whether we try to force the logout anyway before rethrowing the certification exception. For simplicity's sake I'd leave it as-is. Unless I'm missing something @pkaminski+CODX?

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski+CODX reviewed 6 files and all commit messages, made 2 comments, and resolved 2 discussions.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on snoack).


src/MetaTree.js line 88 at r21 (raw file):

Previously, snoack (Sebastian Noack) wrote…

Yes, we should fix the version parsing

#45

But also the comment here is still outdated.

Done.

Verified the corrected ordering comment in r23 and the numeric comparison in #45 r2. I tested the two together through the real Bridge.init() message path with the 4.1.2 minimum: all 12 version cases pass, including accepting 4.1.10 and 4.1.11 and rejecting 4.1.1 and 5.0.0. Satisfied with the fix split into #45, provided that change lands before this one; #43 on its own still has the string comparison.

Comment thread src/MetaTree.js
// Only the bridge request is wrapped: this certification can wait on its own interceptors,
// and a callback arriving during that wait predates the request, so it's background work
// rather than this call's result.
return certifyNull(null).then(() => collect(() => this._bridge.unauth(this._rootUrl)));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: under the policy that every failed logout is fatal, I'd leave this as-is. _signOut() wraps the null certification in the full auth/unauthenticate operation, so its failure reaches onFailure with op.method === 'unauthenticate' even if the caller catches the enclosing authentication error.

I verified this with the actual MetaTree, Dispatcher, Bridge, and worker code connected to a controlled Firebase auth stub, covering both public logout and rejected-candidate cleanup, with failures in both null-certification onBefore and onAfter. All four cases preserve the cleanup error and notify unauthenticate.onFailure. The worker does retain its session when cleanup fails, but the app has the required signal to terminate; forcing the RPC wouldn't repair the failed local cleanup. There is no need to introduce different failure behavior for the two paths.

The bridge doesn't await our auth listeners, so consecutive callbacks could
publish out of order, losing a sign-out.  Serialize certifications, and serialize
client-issued calls over their whole operation.

A call owns the auth changes delivered between its request going out and that
request settling; anything outside is background work.  A `certify` interceptor
rejects a candidate by returning `false` rather than signing out itself, and every
`onBefore` settles before any verdict is acted on.
@snoack
snoack force-pushed the serialize-certifications branch from d4ded27 to 460bbaf Compare September 30, 2026 04:35

@pkaminski pkaminski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pkaminski reviewed 7 files and all commit messages.
Reviewable status: :shipit: complete! all files reviewed, all discussions resolved (waiting on snoack).

@snoack
snoack merged commit ffa659e into master Sep 30, 2026
6 checks passed
@snoack
snoack deleted the serialize-certifications branch September 30, 2026 16:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants