Skip to content

feat(broker): a hosted-MCP credential, and the refresh fence (TASK-172 slice 3b) - #2001

Merged
lilyshen0722 merged 4 commits into
mainfrom
kai/task172-credential
Sep 29, 2026
Merged

lilyshen0722 merged 4 commits into
mainfrom
kai/task172-credential

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

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 as 87c73258 and all ten of its paths are byte-identical between the cleared head 905e21b7 and origin/main; this branch is rebased onto it with git rebase --onto origin/main fce2c2ae^. Delta: 2 files, +920. git range-diff shows the two later commits as = and the first differing only by a dropped hunk — the schemaPathGuard helper, 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.js is empty.

What lands

file
backend/services/hostedMcpCredentialService.ts credentialFor — ref resolution, freshness, the refresh fence, the row's error states
backend/__tests__/unit/services/hostedMcpCredential.test.js 24 arms, against the real Integration schema
backend/__tests__/utils/schemaPathGuard.js 3a's helper — landed with 3a, so the rebase drops this branch's identical copy; the file is on main, not in this delta

The shape, and why

The row is checked before the credential is. status !== 'connected' is
refused as connection_mismatch before any ref is read, so a row that is
error or mid-reconnect cannot serve a token on the strength of a ref that was
left behind.

An absent expires_in is NOT fresh. expires_in is only RECOMMENDED in
RFC 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.
refreshGeneration is bumped under a guarded findOneAndUpdate, so exactly one
caller wins; the loser polls for up to WINNER_WAIT_MS and then serves the
credential the winner wrote. Only the winner may touch the row's status: a
loser that marked the row error or revoked the pair would turn a transient
vendor 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.put upserts on
(integrationId, kind), so a ref is STABLE across puts — the original code
compared the pre-image ref with the post-read ref and could therefore never see
a winner, and would have called refreshAtVendor a second time. It now asks
whether 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

  1. The fence loser watched for a change that cannot happen (above): ref
    inequality where refs are stable. Now freshness.
  2. A row whose vendor issues no refresh token was refused without being
    marked.
    Scope §4: an authorization server that issues no refresh token
    gives a row whose expiresAt is the access token's, and when that passes the
    row must go to error with a "reconnect" message — reconsent is the only
    fix, so a refusal that leaves the row reading connected tells the member
    nothing 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 error with
    … reconnect to continue, guarded on the freshly-bumped generation so a
    concurrent loser cannot overwrite a newer verdict, and assertUsable makes
    that state terminal rather than a source of fence churn.

Evidence

  • 24 arms, (1, 24), 0 failed, 0 runtime errors. tsc:check exit 0; eslint
    clean on the service; the test file carries only the standard .ts-import
    finding class (not linted in CI).
  • Mutation ledger /tmp/kai-172s3b-ledger.py: 32 mutations, baseline
    (1, 24) asserted before every run — 29 killed, 2 refused by the compiler
    (TS2345, both on the hostedMcpCredentialKind union — recorded as findings,
    not kills), 1 equivalent under the test environment, NO SURVIVORS, NO
    NAMED-ARM MISSES, NO NOT-APPLIED.
    The ledger's own applied column is what
    caught the third item below.
  • Two tautological arms, found by the ledger and corrected. M03
    (EXPIRY_SKEW_MS = 0) and M24 (WINNER_WAIT_MS × 1000) SURVIVED, because the
    test 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 * 1000 and T0 + 60 * 1000 + 1 — never 60_000, which the
    test 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 the
    class the review checklist calls a tautological arm: an expectation derived
    from the function under test is not an expectation.
  • Correctness is asserted against the real Integration schema, not against
    a mock: the harness models connectorSecrets.put's upsert semantics by
    default (a newRefPerPut variant models the other world), and the row fixture
    is built as a real document so a strict-subdocument write that lands nowhere
    cannot pass.

Disclosed gaps

  • No caller yet. Nothing in production calls credentialFor until step 4's
    catalogue registration lands (see slice 3c's note): the broker looks a tool up
    in the literal TOOL_DEFINITIONS, and no hosted definition can be registered
    there until an entry can carry a call. That is a scheduling fact, not a
    design choice, and it is why the broker half of step 4 is deliberately not in
    this PR.
  • The live vendor measurement is owed with the rest of the flow: refresh
    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: refreshGeneration stops a
caller 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, a
value nobody has consumed yet, bumps from it, wins its OWN fence, and spends the
same single-use refresh token twice — while its markError, which genuinely
holds 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 arriving
mid-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/markError is what makes expiry safe. Both exits
release 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: false and $lte were the
two load-bearing arms. Neither claim survived measurement: $eq: null matches a
MISSING field as well as a null one, so a mutant dropping the $exists: false
arm changed no test (recorded as EQUIVALENT, and the arm kept for the reader);
and $lte alone would have been a BUG, because its range operators are
type-bracketed and match neither a null nor a missing value — a released lease
would have wedged every later refresh. The null arm's removal is killed by
a lease released by its winner is takeable; $lte's by
an elapsed lease is takeable.

refreshingUntil is declared on Integration's config subdocument because it is
STRICT: 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 findOneAndUpdate
filter 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:check exit 0.
  • Ledger: 40 mutants — 36 killed, 2 compiler-refused (TS2345, the
    hostedMcpCredentialKind union), 2 recorded equivalent-and-unreachable,
    NO SURVIVORS, NO NAMED-ARM MISSES, NO NOT-APPLIED.
  • Lease mutants, each naming its killing arm: M33 no lease guard; M34 elapsed
    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.
  • One of my own arms was tautological, and the ledger caught it. The expiry
    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, with
    expect(REFRESH_LEASE_MS).toBe(30 * 1000) pinning the constant, which is what
    the skew-margin arm in the sibling suite already did.

… 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).
@lilyshen0722
lilyshen0722 added this pull request to the merge queue Sep 29, 2026
Merged via the queue into main with commit e4918aa Sep 29, 2026
19 of 23 checks passed
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.
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.

1 participant