Repository navigation
feat(broker): a hosted-MCP credential, and the refresh fence (TASK-172 slice 3b) - #2001
Merged
Merged
Conversation
… cannot happen (TASK-172) `credentialFor`'s loser decided the winner had written by comparing refs: `current.config.credentialRef !== startRef` (or the refresh ref having moved). `connectorSecrets.put` upserts on `(integrationId, kind)`, so the ref for a given kind is STABLE across puts — a refresh that replaces both halves leaves `config.credentialRef` byte-identical. A row that already held an expired credential, which is the only kind of row that reaches this path, therefore never satisfied the test: the loser polled out `WINNER_WAIT_MS` and reported the retryable `credential_refreshing` against a row the winner had committed milliseconds in. Harmless to the Connection (the refusal is retryable and the next call finds the fresh token), but the fence's losing half never served anything in the ordinary case, and the module comment claimed the opposite. The signal that is actually observable is the one the caller could not have seen before: **the row's credential is fresh.** The path is entered only because the pre-image was not fresh, so a fresh re-read is the winner's commit — the pre-image's own staleness is now passed in and checked rather than assumed, so "fresh" cannot be satisfied by a row that was always fresh. A re-read holding the OLD expiry still means the commit has not landed, even though `put` has already overwritten the secret in place: serving the new token under the stale expiry would hand the caller a credential it would immediately discard. Arms: 24 over one suite, baseline `(1, 24)`, all passing. The harness models `put`'s upsert semantics by default (`newRefPerPut` models the other world), and the write's correctness is asserted against the real `Integration` schema rather than against the mock — a mock records what it was handed, not what a strict subdocument kept. Measured, not argued: with the OLD ref-diffing condition restored as a mutant, exactly one arm fails and it is the arm whose name states the claim — `serves the winner credential when the store kept the ref and only the secret moved`. A first attempt at that mutant (3 edits) failed to LOAD the suite (`runtime=1, tests=0`), which is a compiler refusal, not a kill; the param type had to be widened too. `__tests__/utils/schemaPathGuard.js` is copied from the intake branch that introduces it (`925526a6`); this branch is cut before that and rebases onto main after, where it will come from main instead.
…re measuring themselves (TASK-172) The ledger's first run reported three survivors. Two of them were the same defect in the arms, not in the service: the skew-boundary fixture was built from `EXPIRY_SKEW_MS` and the loser's expectation was written as `WINNER_WAIT_MS` — both the CONSTANT UNDER TEST. Setting the skew to zero moved the fixture's boundary to zero with it, and multiplying the wait by 1000 moved the expectation with it, so an arm written to witness each bound passed under the very mutant that removed it. Both are literals now — 60s at the boundary, 30s inside it, 60s + 1ms outside; 15 polls of 100ms totalling 1500ms for the loser's bound — with the constant's value asserted where the numbers would otherwise look arbitrary. The ledger that found this: 31 mutations, 28 killed, 83 reds, no survivors, no named-arm misses, none unapplied, service restored byte-identical after every run. One more mutant was recorded rather than run, with its argument: telling the loser the pre-image was null instead of stale is unreachable, because this path is entered only when the pre-image is not fresh and `null` is never fresh. Also models `connectorSecrets.put`'s refusal of empty material, so a caller that puts a token it never received fails in the harness instead of silently keeping the old secret. Two mutations could not be applied at all, which is a finding rather than a gap: removing the missing-refresh-token guard is refused by the compiler at `hostedMcpCredentialService.ts:275` (`secrets.get(refreshTokenRef)` — argument of type 'string | undefined') and putting a refresh token the vendor did not return is refused at `:298` (the same TS2345). The narrowings that guard the fence cannot be removed without a type error, so those two bugs are unbuildable rather than merely unwitnessed; the same guard's behaviour is still witnessed by a mutant that mistypes the refusal it raises.
…fusal (TASK-172) `credentialFor` refused a no-refresh-token row without marking it, and an arm pinned that behaviour. Scope §4 says the other thing: the spec lets an AS issue no refresh token at all, and when the access token's expiry passes "the row goes to `error` with 'reconnect'". Without the mark the row keeps reading `connected` on the page while every call fails, and the member is never told what would fix it — the one outcome they cannot act on. The mark is guarded on the generation the winner just bumped, so a concurrent loser cannot overwrite a newer verdict, and `assertUsable` then refuses later calls as a mismatch rather than re-entering the fence against a row nothing can serve. A rotating vendor does not reach this path: a response that omits the new refresh token keeps the ref the row already holds. Ledger 32/32 (29 killed, 2 compiler-refused, 1 equivalent, no survivors, no named-arm misses); the new mutant that drops the mark is killed by the arm whose name states the claim.
…ge won its own (TASK-172) `refreshGeneration` stops a caller holding a STALE pre-image. It does not stop one holding a FRESH one: a call that reads the row after the winner's bump and before its commit sees a generation nobody has consumed yet, bumps from it, wins its OWN fence, and spends the same single-use refresh token twice. Three things then go wrong at once — the token is spent twice, the second caller's `markError` lands because it genuinely holds the current generation, and the true winner's commit matches nothing and is discarded — leaving a Connection bricked at `error` after a race no member caused. The window is the vendor round-trip, which is exactly when broker calls pile up. So the bump also takes a short LEASE (`config.refreshingUntil`): the winner holds it across its provider call, and a caller arriving mid-flight FAILS the bump and becomes a loser — where it already behaved correctly. The lease expires, so a winner that crashed cannot strand the row, and the generation guard on `commit`/`markError` is what makes that expiry safe: a timed-out winner returning late can no longer overwrite its successor. The filter names THREE takeable states, not two: absent, released-as-null, and elapsed. `$lte: now` is type-bracketed in MongoDB and does NOT match a null, so a filter carrying only `$exists: false` and `$lte` would wedge every row after its first refresh — the state a commit writes. That is asserted, not argued: the `a lease released by its winner is takeable` arm fails if the null arm is dropped. `refreshingUntil` is declared on `Integration`'s config subdocument because it is STRICT — an undeclared path is dropped in silence, and the fence would then read armed while no lease ever landed. The new suite injects everything EXCEPT the row, so the real query and the real schema are what the arms measure. Evidence: 30 tests in 2 suites, baseline `(2, 30)`, 0 failed, 0 runtime errors; `tsc:check` clean; eslint 0. Mutation ledger: 40 mutants, and the lease mutants each named the arm that kills them (M33 no lease guard; M34 elapsed not takeable; M35 absent not takeable; M36 released not takeable; M37 the commit does not release; M38 the mark does not release; M39 a zero-length lease; M40 a permanent one).
samxu01
pushed a commit
that referenced
this pull request
Sep 29, 2026
…the retryable backoff is deliberate (TASK-172) Vera's review of #2001 named a residual rather than holding on it: a RETRYABLE vendor failure throws without releasing the lease, so for up to REFRESH_LEASE_MS every caller fails the bump and gets `credential_refreshing`. Both readings were defensible and nothing in the file said which one the code means. It means the backoff. Releasing the lease there would let every caller queued behind the failure retry a vendor that has just answered 500 or 429, which is the storm the lease exists to damp; the cost is bounded and retryable; and the generation the failed call bumped cannot strand anything, because the fence is relative to the generation a caller read — whatever refresh follows the lapsed lease starts from the value on the row and commits normally. The arm that follows from that sentence: a retryable failure leaves `refreshingUntil` at the literal `T0 + 30s` with the generation bumped and nothing marked; a queued caller is refused retryably with the vendor NOT called again; and the expiry is the recovery path (second call refreshes, generation 5, lease released). Mutant M41 — release the lease on the retryable path, which is the "fix" a later reader would apply — is killed by that arm. Also here, from Vera's review of the same suite: the two fence arms no longer POLL for the winner's bump to land. `waitForGeneration` was the file's only wall-clock budget, and its expiry failed a security arm in the direction that reads as the fence having broken — she saw exactly one such run (1 failed / 29 passed, message `row never reached refreshGeneration 4`) and neither of us could confirm it in 20+ runs since. The landing is observable at the seam instead: `defaultRowDeps()` is exported so a test can wrap `bumpGeneration` around the REAL implementation while the other three row methods stay real, and the mid-flight pre-image is taken after that signal rather than after a poll. A wholesale `row` override is required because the deps merge is one level deep, and spreading a wrapper onto `store.deps.row` finds nothing there — measured, not assumed: it is `TypeError: Cannot read properties of undefined (reading 'bumpGeneration')`. No wall-clock wait remains in either arm, so there is no budget left to expire under load. Evidence: baseline `(2, 31)`, `tsc:check` exit 0. Ledger: 41 mutants, 37 killed, 2 compiler-refused, 2 recorded equivalent, no survivors, no named-arm misses, no not-applied.
samxu01
pushed a commit
that referenced
this pull request
Sep 29, 2026
…the retryable backoff is deliberate (TASK-172) Vera's review of #2001 named a residual rather than holding on it: a RETRYABLE vendor failure throws without releasing the lease, so for up to REFRESH_LEASE_MS every caller fails the bump and gets `credential_refreshing`. Both readings were defensible and nothing in the file said which one the code means. It means the backoff. Releasing the lease there would let every caller queued behind the failure retry a vendor that has just answered 500 or 429, which is the storm the lease exists to damp; the cost is bounded and retryable; and the generation the failed call bumped cannot strand anything, because the fence is relative to the generation a caller read — whatever refresh follows the lapsed lease starts from the value on the row and commits normally. The arm that follows from that sentence: a retryable failure leaves `refreshingUntil` at the literal `T0 + 30s` with the generation bumped and nothing marked; a queued caller is refused retryably with the vendor NOT called again; and the expiry is the recovery path (second call refreshes, generation 5, lease released). Mutant M41 — release the lease on the retryable path, which is the "fix" a later reader would apply — is killed by that arm. Also here, from Vera's review of the same suite: the two fence arms no longer POLL for the winner's bump to land. `waitForGeneration` was the file's only wall-clock budget, and its expiry failed a security arm in the direction that reads as the fence having broken — she saw exactly one such run (1 failed / 29 passed, message `row never reached refreshGeneration 4`) and neither of us could confirm it in 20+ runs since. The landing is observable at the seam instead: `defaultRowDeps()` is exported so a test can wrap `bumpGeneration` around the REAL implementation while the other three row methods stay real, and the mid-flight pre-image is taken after that signal rather than after a poll. A wholesale `row` override is required because the deps merge is one level deep, and spreading a wrapper onto `store.deps.row` finds nothing there — measured, not assumed: it is `TypeError: Cannot read properties of undefined (reading 'bumpGeneration')`. No wall-clock wait remains in either arm, so there is no budget left to expire under load. Evidence: baseline `(2, 31)`, `tsc:check` exit 0. Ledger: 41 mutants, 37 killed, 2 compiler-refused, 2 recorded equivalent, no survivors, no named-arm misses, no not-applied.
lilyshen0722
added a commit
to thantiklermcirony/commonly
that referenced
this pull request
Oct 9, 2026
…the retryable backoff is deliberate (TASK-172) (Team-Commonly#2004) Vera's review of Team-Commonly#2001 named a residual rather than holding on it: a RETRYABLE vendor failure throws without releasing the lease, so for up to REFRESH_LEASE_MS every caller fails the bump and gets `credential_refreshing`. Both readings were defensible and nothing in the file said which one the code means. It means the backoff. Releasing the lease there would let every caller queued behind the failure retry a vendor that has just answered 500 or 429, which is the storm the lease exists to damp; the cost is bounded and retryable; and the generation the failed call bumped cannot strand anything, because the fence is relative to the generation a caller read — whatever refresh follows the lapsed lease starts from the value on the row and commits normally. The arm that follows from that sentence: a retryable failure leaves `refreshingUntil` at the literal `T0 + 30s` with the generation bumped and nothing marked; a queued caller is refused retryably with the vendor NOT called again; and the expiry is the recovery path (second call refreshes, generation 5, lease released). Mutant M41 — release the lease on the retryable path, which is the "fix" a later reader would apply — is killed by that arm. Also here, from Vera's review of the same suite: the two fence arms no longer POLL for the winner's bump to land. `waitForGeneration` was the file's only wall-clock budget, and its expiry failed a security arm in the direction that reads as the fence having broken — she saw exactly one such run (1 failed / 29 passed, message `row never reached refreshGeneration 4`) and neither of us could confirm it in 20+ runs since. The landing is observable at the seam instead: `defaultRowDeps()` is exported so a test can wrap `bumpGeneration` around the REAL implementation while the other three row methods stay real, and the mid-flight pre-image is taken after that signal rather than after a poll. A wholesale `row` override is required because the deps merge is one level deep, and spreading a wrapper onto `store.deps.row` finds nothing there — measured, not assumed: it is `TypeError: Cannot read properties of undefined (reading 'bumpGeneration')`. No wall-clock wait remains in either arm, so there is no budget left to expire under load. Evidence: baseline `(2, 31)`, `tsc:check` exit 0. Ledger: 41 mutants, 37 killed, 2 compiler-refused, 2 recorded equivalent, no survivors, no named-arm misses, no not-applied.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TASK-172 slice 3b — reading a hosted-MCP credential, and the refresh fence
Step 4's first half (scope §4): a call on a hosted connection needs a live
access token, the row holds only a ref to it, and more than one caller can
arrive at the same expiring credential at once. This is the reader and the
fence — the piece every vendor call will sit on.
Cut from
main(87c73258). 3a landed as87c73258and all ten of its paths are byte-identical between the cleared head905e21b7andorigin/main; this branch is rebased onto it withgit rebase --onto origin/main fce2c2ae^. Delta: 2 files, +920.git range-diffshows the two later commits as=and the first differing only by a dropped hunk — theschemaPathGuardhelper, which 3a already landed with identical content, so re-adding it would have been a duplicate rather than a change.git diff origin/main HEAD -- backend/__tests__/utils/schemaPathGuard.jsis empty.What lands
backend/services/hostedMcpCredentialService.tscredentialFor— ref resolution, freshness, the refresh fence, the row's error statesbackend/__tests__/unit/services/hostedMcpCredential.test.jsIntegrationschemabackend/__tests__/utils/schemaPathGuard.jsmain, not in this deltaThe shape, and why
The row is checked before the credential is.
status !== 'connected'isrefused as
connection_mismatchbefore any ref is read, so a row that iserroror mid-reconnect cannot serve a token on the strength of a ref that wasleft behind.
An absent
expires_inis NOT fresh.expires_inis only RECOMMENDED inRFC 6749, so a vendor may omit it; reading a missing lifetime as "never expires"
would serve a dead token until the vendor refused it. Refreshing is the safe
reading, and the no-refresh path below is what makes the case visible instead of
silent.
The fence picks a winner by claim, and the loser serves the winner's work.
refreshGenerationis bumped under a guardedfindOneAndUpdate, so exactly onecaller wins; the loser polls for up to
WINNER_WAIT_MSand then serves thecredential the winner wrote. Only the winner may touch the row's status: a
loser that marked the row
erroror revoked the pair would turn a transientvendor blip into a dead connection.
The loser detects the winner by FRESHNESS, not by a changed ref. This was a
defect, found here rather than in review:
connectorSecrets.putupserts on(integrationId, kind), so a ref is STABLE across puts — the original codecompared the pre-image ref with the post-read ref and could therefore never see
a winner, and would have called
refreshAtVendora second time. It now askswhether the re-read credential is fresh, with the pre-image's staleness checked
first so "fresh" is not vacuously true.
Two defects the plan and the arms each pinned, and both are fixed here
inequality where refs are stable. Now freshness.
marked. Scope §4: an authorization server that issues no refresh token
gives a row whose
expiresAtis the access token's, and when that passes therow must go to
errorwith a "reconnect" message — reconsent is the onlyfix, so a refusal that leaves the row reading
connectedtells the membernothing and fails every call in silence. The old arm justified the refusal
with a case (a vendor that rotates refresh tokens) that cannot reach the
line: the commit keeps the previous ref when a response omits a new one, so
rotating vendors never get there. The path now marks the row
errorwith… reconnect to continue, guarded on the freshly-bumped generation so aconcurrent loser cannot overwrite a newer verdict, and
assertUsablemakesthat state terminal rather than a source of fence churn.
Evidence
(1, 24), 0 failed, 0 runtime errors.tsc:checkexit 0; eslintclean on the service; the test file carries only the standard
.ts-importfinding class (not linted in CI).
/tmp/kai-172s3b-ledger.py: 32 mutations, baseline(1, 24)asserted before every run — 29 killed, 2 refused by the compiler(
TS2345, both on thehostedMcpCredentialKindunion — recorded as findings,not kills), 1 equivalent under the test environment, NO SURVIVORS, NO
NAMED-ARM MISSES, NO NOT-APPLIED. The ledger's own
appliedcolumn is whatcaught the third item below.
(
EXPIRY_SKEW_MS = 0) and M24 (WINNER_WAIT_MS × 1000) SURVIVED, because thetest computed its fixture and its expectation FROM the constants under test —
every value moved together. Both now assert literals (the freshness
bound as
T0 + 60 * 1000andT0 + 60 * 1000 + 1— never60_000, which thetest harness's eslint config cannot parse — and the loser's total wait as 1500 ms,
15 polls of 100 ms), and
expect(EXPIRY_SKEW_MS).toBe(60 * 1000)pins the constant itself. This is theclass the review checklist calls a tautological arm: an expectation derived
from the function under test is not an expectation.
Integrationschema, not againsta mock: the harness models
connectorSecrets.put's upsert semantics bydefault (a
newRefPerPutvariant models the other world), and the row fixtureis built as a real document so a strict-subdocument write that lands nowhere
cannot pass.
Disclosed gaps
credentialForuntil step 4'scatalogue registration lands (see slice 3c's note): the broker looks a tool up
in the literal
TOOL_DEFINITIONS, and no hosted definition can be registeredthere until an entry can carry a
call. That is a scheduling fact, not adesign choice, and it is why the broker half of step 4 is deliberately not in
this PR.
against a real authorization server (rotation, revocation, expiry clock skew).
Review round: the fence admitted a second winner (fixed)
Vera's hold at
8ab1a586, with a reproduction:refreshGenerationstops acaller holding a STALE pre-image, not a FRESH one. A call that reads the row
after the winner's bump and before its commit sees
refreshGeneration: G+1, avalue nobody has consumed yet, bumps from it, wins its OWN fence, and spends the
same single-use refresh token twice — while its
markError, which genuinelyholds the current generation, lands and bricks the Connection.
The remedy is the second half of the shape the file already had: the bump also
takes a short lease (
config.refreshingUntil, 30s), so a caller arrivingmid-flight FAILS the bump and becomes a loser — where it already behaved
correctly. The lease expires so a crashed winner cannot strand the row, and the
generation guard on
commit/markErroris what makes expiry safe. Both exitsrelease it.
Three takeable states, and the third is the one that is easy to miss. The
first draft of the filter's comment claimed
$exists: falseand$ltewere thetwo load-bearing arms. Neither claim survived measurement:
$eq: nullmatches aMISSING field as well as a null one, so a mutant dropping the
$exists: falsearm changed no test (recorded as EQUIVALENT, and the arm kept for the reader);
and
$ltealone would have been a BUG, because its range operators aretype-bracketed and match neither a null nor a missing value — a released lease
would have wedged every later refresh. The
nullarm's removal is killed bya lease released by its winner is takeable;$lte's byan elapsed lease is takeable.refreshingUntilis declared onIntegration's config subdocument because it isSTRICT: an undeclared path is silently dropped, and the fence would then read
armed while no lease ever landed.
The new suite injects everything EXCEPT the row, so the real
findOneAndUpdatefilter and the real schema are what its arms measure.
Evidence at this head
(2, 30)— 30 tests in 2 suites, 0 failed, 0 runtime errors;tsc:checkexit 0.TS2345, thehostedMcpCredentialKindunion), 2 recorded equivalent-and-unreachable,NO SURVIVORS, NO NAMED-ARM MISSES, NO NOT-APPLIED.
not takeable; M35 (equivalent, above); M36 released not takeable; M37 the
commit does not release; M38 the mark does not release; M39 a zero-length
lease; M40 a permanent one.
arm first advanced the clock by
REFRESH_LEASE_MS— the constant under test —so a mutant setting the lease to 10^9 ms moved the arm's own boundary with it
and the arm stayed green. The offset is now the literal
30 * 1000 + 1, withexpect(REFRESH_LEASE_MS).toBe(30 * 1000)pinning the constant, which is whatthe skew-margin arm in the sibling suite already did.