Skip to content

feat(identitybroker): record who acted, for whom, and what was decided - #2985

Merged
rdimitrov merged 10 commits into
mainfrom
claude/broker-audit-records-90c878
Nov 26, 2026
Merged

rdimitrov merged 10 commits into
mainfrom
claude/broker-audit-records-90c878

Conversation

@rdimitrov

@rdimitrov rdimitrov commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

What this does

The identity broker now records who acted, for whom, and what was decided. Before, it kept only ID-JAG and call-decision records. Now every event audit.md assigns to the broker produces a record, kept in memory behind one sink (Recorder) that can refuse a record. #2566 writes these records in the AuditEvent profile and delivers them; this PR builds no delivery.

Each record:

  • has its own AuditID (rec_…), minted once, and a mecatl_ type;
  • has Subjects() keyed by the profile's Subjects keys, each marked verified, credential-verified, record:<AuditID>, reported:mecak8s, or unavailable;
  • refers to earlier records by AuditID: the session open that verified the user, the acting instance's registration, the parent's registration, and the delegation a run acts under. When the broker undoes an event after sending its success record, it records a refusal whose Supersedes names that record (the profile's Metadata.Extra["mecatl.supersedes"]), because a sink can store a record and still fail to confirm it;
  • marks lineage facts, which only mecak8s observes, as reported:mecak8s (LineageProvenance on registration and delegation records), and qualifies a verified workload by the issuer its authenticator verified (workload_iss; no authenticator verifies one yet, so it is unavailable today);
  • names credentials only by (iss, jti) or by record reference. A test runs every event and checks that no access token, refresh token, agent credential, ID-JAG, or gateway token value appears in any record or its subjects.

Records each event produces

Event Record type Outcome Notes
Session open, converted token mecatl_session_open success Kind converted; user (owner, AS-1 iss/sub, and the token's client as user_client_id/user_client_iss) marked verified, kept only after AS-1 accepts the token; source jti; hard expiry; any replaced refresh token by the AuditID of the open that stored it plus that open's source jti
Session open, token AS-1 already converted mecatl_session_open success Kind already_converted; user from the converting open's record
Session open, tokenless mecatl_session_open success Kind tokenless; owner reported:mecak8s, user and client unavailable unless an earlier open verified them
Refused open mecatl_session_open denied / error Code and reason for every refusal session open returns ("Error reasons"); no user. A session the refused open created is closed. A request that fails validation is recorded with only its workload, since its fields were not validated
Close mecatl_session_close success Once per session, from every path: requested (by broker session or by host session), hard expiry found by any lookup, mismatched AS-1 answer, grant lost, open refused (naming the refusal's record)
Agent registration mecatl_instance_registered success ag_ ID and SPIFFE ID (verified), incarnation (reported:mecak8s), definition, parent and parent host session, parent's registration AuditID, new / moved / previous registration
Refused registration mecatl_instance_registered denied / error Reason; names the instance its incarnation registered as, if any. An invalid request is recorded with only its workload
Delegation report, accepted mecatl_delegation success Delegation ID, delegating run and agent (with its incarnation), receiving run and agent, run owner (RunOwner), all reported:mecak8s; registration references; parent delegation's AuditID; whether this report recorded the delegating run as a root run; PreviousRecord, the AuditID of the same delegation's report in an earlier broker session of the root, as when mecak8s reports it again after a reopen (forgotten when mecak8s closes the host session, as on a delete, or closes its current broker session itself). An identical repeat makes no second record
Delegation report, refused mecatl_delegation denied Reason, including ALREADY_EXISTS for a changed repeat. An invalid request is recorded with only its workload
Grant (ID-JAG) mecatl_id_jag success ID-JAG (iss, jti), user from the grant's open record, run, delegation and registration references
Unrecorded grant mecatl_id_jag error record_not_accepted, superseding the ID-JAG record the sink did not accept; the ID-JAG is not redeemed
Call decision mecatl_tool_decision success / denied / error As before, plus the same references

Write order and failure

Settled in design PR #2984 (docs/audit-write-order), which should merge first:

  • Open: returns only after its record is accepted. Otherwise it changes nothing: a session it created is closed, a held refresh token stays, a new one is discarded (not revoked until Sign-out and revocation #2568; a code shortcut), and the broker still remembers the source jti it converted, so the spent token never reaches AS-1 again. It fails with reason record_not_accepted: as for token_used (UNAUTHENTICATED, which mecak8s answers with 401 bearer_rejected so the client refreshes) when it converted the request's token, and UNAVAILABLE otherwise. If the session closes while the record is sent, the open fails with the closing reason. Either way a refused-open record follows, superseding the success.
  • A new session is unreachable until its open is recorded. It enters the session table only once its open record is accepted, so no registration, report, call, or close by broker session ID reaches it while the record is in flight, and no accepted record refers to an open the sink did not accept. A FindSession of that host session waits for the open to end, and checks again in case another open started a new session meanwhile; a lookup of an existing session never waits.
  • Closing a host session reaches an open in progress. CloseSessionRequest.RootHostSessionID closes the host session's open broker session and the new one an open of it is creating, without waiting for that open. The open then fails with session_closed and stores no refresh token. If the close came before the open's record was sent, the open records only a refusal; if it came while the record was sent, a refusal superseding the success. The new session's close record is held until that refusal is queued and names it, so no close names a record the sink was not given first. mecak8s closes a deleted session, or a scheduled run that ended, this way, so a delete no longer depends on its find outlasting the open. An existing session can still close while an open's record is sent; that open fails the same way.
  • A closed host session gets no new broker session for five minutes. A close by host session marks that host session's incarnation, per workload: CloseSessionRequest.RootHostIncarnation names it. An open of a marked incarnation fails with session_closed before it converts or stores anything. An open of another incarnation, as when the host session is created again under the same ID, is unaffected. That covers an open queued behind the one the close ended, and a request that loaded the session before its delete. Five minutes is well past the longest an open holds its host session's lock (two AS-1 requests of at most 30 seconds and one 10-second record send). Shortcut: the mark is in memory and per replica, so an open on a replica that did not serve the delete, after a restart, or more than five minutes later still gets a broker session that nothing closes before its hard expiry; removed by [Phase 3] Run mecak8s with the identity broker on more than one replica #2805 and Durable broker state and recovery #2563.
  • Refused open: never leaves a session it created, whatever happens to its record. The close (open_refused) names the refusal's record, which is queued before it. An open refused on an existing session leaves that session as it was.
  • Registration: admitted only after its record is accepted; otherwise it fails UNAVAILABLE with record_not_accepted, nothing is registered, and a refusal superseding the success is recorded. A new helper's or team member's first registration is not retried: it does not run. The root's registration is retried when its run starts, and a re-registration after a reopen on the agent's next call. Registrations of one incarnation are serialized around check, record, and admission. Signing stays outside the lock.
  • Delegation report: stored only after its record is accepted; otherwise it fails UNAVAILABLE with record_not_accepted, nothing is stored, and a superseding refusal is recorded. A new helper's first report is not sent again: it does not run. A delegation reported again after a reopen is reported again on the helper's next call. When a helper moves, the holder reports its current delegation to the new session too; if that report fails, it puts the helper's old entry back, so the next lookup moves it and reports again. Reports to one broker session are serialized.
  • Every send has a deadline. A record an event waits for gets 10 seconds; a slow sink then fails the event with record_not_accepted instead of holding the call.
  • Closes and refusals do not wait. Their records, a denied call's decision included, go through one bounded in-memory queue, so neither a call nor a per-key lock (open, registration, report) waits on the sink for them, and a denied call does not hold AS-2's binding while its refusal is sent. Records are queued under the session table's lock, so they keep the order the events happened in. A refused open's close follows its refusal, and a mismatched AS-1 answer's close follows the refused-open record it names. A drainer goroutine sends them one at a time, each within the same 10 seconds, and runs only while records wait. A record pushed past the bound (1,024) is reported as a delivery failure and dropped. The last 256 slots take only closes and the records queued with one, so an agent looping on denied calls while the sink is slow cannot push closes out. A refused open's refusal and its close enter the queue together, whole or not at all, so a close never names a refusal the queue dropped. Broker.Close, called at mecak8s shutdown after AS-1 stops taking requests, sends what is queued until its deadline. It reports each record it could not send, and the one still being sent, and counts both in its error. That record's send finishes on its own, so the sink may still accept it, or refuse it and have it reported a second time; the DeliveryFailure contract says so. A refused open's close names the refusal's record even when the sink refused it; that is part of the [Phase 3] Authorization server and gateway audit records, and reconciliation #2848 shortcut.
  • Numbering at emission, which gap detection needs, is left to Audit records and delivery #2566 and [Phase 3] Tamper-evident audit records #2808. Records are numbered where they are emitted there, so a drop shows as a gap.
  • A decision names the grant it used. Its user and user record come from the grant each exchange attempt uses, a retry's newer grant included, so a decision and its ID-JAG name the same open; the session's user is kept only for refusals before a grant is selected.
  • ID-JAG and decision keep audit.md's order. An unaccepted ID-JAG or success decision fails the call UNAVAILABLE with record_not_accepted. An unaccepted ID-JAG record is followed by an ID-JAG refusal that supersedes it, and a withheld success decision by a decision refusal that supersedes it.
  • Supersedes (Metadata.Extra["mecatl.supersedes"]) is set on a refusal that undoes an earlier record of the same event: after the record was not accepted, or after it was accepted and the session closed while it was recorded. That refusal's outcome is error for record_not_accepted and denied when a close undid the event, decisions included. A converted open's record_not_accepted is error too, though its code is UNAUTHENTICATED.
  • Refused and dropped records are reported through WithDeliveryFailures (AuditID and type, never content). mecak8s logs them as warnings.
  • Matching the reason: record_not_accepted has code UNAUTHENTICATED for a converted open and UNAVAILABLE otherwise, so callers match on the reason, not on errors.Is with its usual code.

mecak8s

  • An open that converted the request's token but whose record was not accepted (record_not_accepted with UNAUTHENTICATED) is answered with 401 bearer_rejected, as for token_used. When the same caller's previous open, of any host session, failed the same way within the last minute, it gets 503 identity_broker_unavailable instead, so a sink outage does not have the client spend fresh tokens. The rule keys on the verified owner alone, since a create, fork, or clear opens a new host session on every attempt (scheduled runs present no token, so they do not count; schedule setup and renewal will count toward it once Phase 2, Slice 3: Scheduled runs — A scheduled run calls gateway tools on its own grant, with no one present #2569 adds them). Only a successful open ends it: a token_used from presenting the token the 503 spent keeps it. It is per replica and best effort.
  • An open of a saved session that the broker refuses with session_closed, with or without a token, is answered by what the store holds: 404 session_not_found when the session is gone or was created again under its ID, and 503 identity_broker_unavailable, which the client retries, when it is still stored, as after a scheduled run ends and the session is kept for result delivery, or when a concurrent close lands while the open records. It is never 401: a refusal for a closed host session converted nothing, and after a 503 on a request that presented a token the client refreshes it anyway. Before, a tokenless one got 500. Every other record_not_accepted maps to identity_broker_unavailable by its code.
  • Deleting a session, or ending a scheduled run, closes its broker session by host session and incarnation in one call that does not wait for an open in progress.
  • A failed first registration or delegation report of a new helper already stops it before it runs; nothing retries it.
  • Shutdown releases AS-1, then calls Broker.Close with a 10-second deadline, so close and refusal records still queued are sent or reported, and an end-to-end test can read them after Built.Close.
  • app.Built.IdentityBrokerRecords() returns the in-memory records, so the harness test reads the sink rather than the diagnostics line (a shortcut that Audit records and delivery #2566 removes).
  • The app's sink logs one debug line per record (type, AuditID, outcome, refusal; no subjects). This is a shortcut that Audit records and delivery #2566 removes. It is how the harness and operators see records while they live only in memory.

Shortcuts

Left for other tickets

These are noted on #2569, #2805, #2562, #2727, #2566, #2563, and #2568.

Merging with #2727

The #2727 branch also edits authorize.go and recorder.go. Here, RecordIDJAG and RecordDecision become one Record method, and DecisionRecord and IDJAGRecord embed RecordHeader, so the second PR to land rebases. IDJAGRecord.User keeps its old name and type (the grant's company identity) to keep that rebase small; aligning it with the other records (Owner and User) is left for then.

API compatibility

Assessment: no wire change, no break. The gRPC and HTTP APIs keep their messages and codes. identity_broker_unavailable (503) gains a cause, an audit sink that does not accept a record the request needs, and its documentation in user-docs/reference/http-sse-api.md and user-docs/features/security-and-execution/caller-identity.md now says so, including that after a 503 on a request that presented a token, the client refreshes the token before retrying. Clients already retry it. Everything else is in-process Go: the broker's Service/Core contract (Workload.Issuer, set only by a verifying authenticator; CloseSessionRequest.RootHostSessionID and RootHostIncarnation; Broker.Close), the Recorder interface (now one Record method; implementations are in this repo only), new record types, and a new broker reason, record_not_accepted.

Behaviour a client can observe, none of it breaking:

  • Registrations of one incarnation now wait for each other, and delegation reports to one broker session wait for each other, around check, record, and store. A wait that the caller's context ends fails UNAVAILABLE, which mecak8s reports as identity_broker_unavailable, a retryable error clients already handle.
  • An open, registration, report, or call waits for its own record, for at most 10 seconds. With the in-memory sink this is immediate, and a refused or late record (record_not_accepted) reaches clients as identity_broker_unavailable, or 401 bearer_rejected for a converted open, so the client refreshes its token as after token_used. A repeat of that converted-open failure by the same caller within a minute, for any session, is answered 503 identity_broker_unavailable. The 503 has spent the token too, so a conforming client refreshes it before retrying, as for any 503 after a token was presented; presenting the spent token again gets bearer_rejected (token_used) and the rule still holds. The rule is per replica, so a retry another replica serves can get 401 again.
  • mecak8s's lookup of a root host session, when a request opens or pairs it, waits while an open of it is creating a new broker session, until that open ends. A request that opens the same session was already serialized behind that open, so it already waited. A delete never opened and does not look up: it closes by host session without waiting.
  • An open of an existing broker session can fail with session_closed if a close lands while its record is sent, and an open of a host session incarnation closed in the last five minutes, on the same replica, fails the same way. mecak8s used to answer a converting open's session_closed with 401 bearer_rejected and a tokenless one with 500. It now re-checks the store: 404 session_not_found when the session was deleted, otherwise 503 identity_broker_unavailable, a retryable error clients already handle. A host session created again under the same ID is not affected by the mark.
  • A refused open no longer leaves the broker session it created. Broker sessions are internal to mecak8s, and the next open creates one again.
  • Closes and refusals, denied calls included, no longer wait for their records.

No stored data changes: broker state is in memory. No major or feature change, no approval needed.

Testing

  • internal/identitybroker/records_test.go: each kind of open, every refused-open reason with the session it created closed (including an open cancelled while waiting for its host session), provenance after a tokenless open, every close path recorded once (including a hard expiry found by a lookup), registrations (main, helpers, re-admitted, moved, refused), delegation reports (accepted, nested, another root run, identical repeat, every refusal), the ID-JAG and decision references, a refused record per event, an undone open, registration, and delegation recorded as a refusal superseding the unaccepted success, a converted jti still remembered after an unrecorded open, the profile's Subjects keys, no credential value in any record, and the user from a real AS-1 token.
  • Session-open tests now expect no session after any refused open, including the token_used refusal seen leaving one in a Kind run.
  • A new session is unreachable by RegisterAgent, ReportDelegation, and CloseSession while its open record is in flight. A FindSession waits for that open, and a find-then-close racing the open closes the session it made and discards its refresh token. A refusal returns, and the next registration of the same incarnation proceeds, while the sink is stalled on the refusal's record. Every send carries a deadline of at most 10 seconds. Broker.Close sends what is queued and reports what it cannot send, and app shutdown sends queued close records. A re-reported delegation's PreviousRecord is only set across sessions and is forgotten on a requested close. The holder undoes a move whose second report fails. A mismatched answer's close is neither queued nor sent before the refusal it names. A close returns while the sink is stalled on its record. The queue keeps order, gives each send a deadline, and drops and reports a record past its bound. A re-reported delegation links to its earlier record. Invalid requests are recorded with only the workload. The workload issuer is used only when verified, and lineage is marked reported:mecak8s.
  • mecak8s: TestIdentityBrokerOpenRefusalMapping covers an unrecorded converted open answered as a refused token, with no broker session left. TestIdentityBrokerRepeatedUnrecordedOpenIsUnavailable covers a create, on a new host session, answered 503 after a prompt's refusal; a token_used with the spent token keeping the rule; and a success ending it. TestOpenRecordRefusalsRepeatPerCaller covers the one-minute window per caller. TestIdentityBrokerOpenOfAClosedHostSession covers a session deleted while its request opened it (404), a kept session whose scheduled run ended (503), and an open presenting a token (503, not 401). TestIdentityBrokerRecreatedSessionOpensAfterADelete deletes a session and creates it again under the same ID within the window. TestIdentityBrokerDeleteClosesAnOpenInProgress deletes a session, with a 50 ms broker timeout, while another replica's open of it is stalled in its exchange; the open then fails and no broker session is left.
  • End to end: cmd/mecak8s TestIdentityBrokerRecordsWhoActed runs mecak8s with the real AS-1 and gateway and reads the broker's record sink. A main-agent gateway call, then a subagent's, produce an open, two registrations, a delegation, and an ID-JAG and decision for each call. The sink refuses nothing.
  • Mutation check: 20 mutants of the important guarantees (unrecorded open, grant, registration, or delegation taking effect; a refused open's new session left open; an open cancelled while waiting not recorded; user kept before AS-1 accepts; tokenless or unverified marked verified; a Token held in a record; duplicate records; missing close; swallowed or missing follow-up refusals; dropped references), and 11 more for the revised write order (a refused open's session kept when its refusal is recorded; a converted unrecorded open failing UNAVAILABLE; each rollback without Supersedes; an unrecorded registration not recorded as refused; a reasonless error; the mecak8s mapping; the key rename; a converted jti forgotten), and 13 for the review fixes (a new session reachable before its record, or never added; a mismatched answer's close queued early, or never sent; a queue that waits, is unbounded, or sends without a deadline; a delegation's previous record lost; an invalid open not recorded; the workload issuer ignored, or taken from an unverified workload; delegation lineage unmarked), and 11 for the second review (refusals sent synchronously; a waited record without a deadline; a lookup not waiting for, or not told of, a new open; a queue keeping overflow; Close not reporting what it could not send, or queueing after Close; a previous record within the same session, or never forgotten; a refused open's close before its refusal; the holder keeping a move whose second report failed). For the third review, the delete test fails against the old find-then-close, and the refusal test fails when decision refusals are sent synchronously. All were caught. The repeated check in FindSession after its wait has no dedicated test.
  • Reviews: /code-review and a four-axis panel (spec, standards, tests, security, architecture, reuse, duplication) found no blockers. Their important findings are fixed here: the owner naming in the record family, the follow-up refusal records, and four test gaps. A design-fit check found no open decisions. This revision follows docs(agent-identity): settle the broker's write order for every audit event #2984's answer to its design review: the open's failure codes, no retry of an unrecorded registration or report, no session left by a refused open, Supersedes on every rollback, the user's client keys, and the stand-in marks moved to Mark team members created over the API as having a stand-in parent #2986. It also follows docs(agent-identity): settle the broker's write order for every audit event #2984 at 6ec9bda: retries only after a reopen, refusal outcomes, and the 503 for a repeated unrecorded open.
  • Tests added for Broker audit records: follow-ups from the implementation review #2999: denied-call refusals flood the queue until a refusal alone is dropped, then a new session's open is refused, and its refusal still reaches the sink before the close that names it; the queue takes a refusal with its close into the reserve and drops both when they do not fit together; an unaccepted ID-JAG record is followed by an ID-JAG refusal superseding it; a host session created again under the same ID opens during the closed incarnation's mark, while an open queued behind the delete is refused; the conformance contract checks both and the new close-request validation; after a retried exchange with a newer grant, the decision names the same open and user as its ID-JAG; mecak8s answers a session_closed open by the store, and a recreated session opens after a delete. TestIdentityBrokerCloseDuringConversionIsRetryable and the mapping table's close-during-exchange case now expect 503 rather than 401. Mutants caught: a refusal and its close queued separately, a group checked one record at a time, no ID-JAG refusal, a mark that ignores the incarnation (broker and mecak8s tests), a delete that names no incarnation, the decision keeping the session's user after a retry, and the old 404/401 mapping of session_closed.
  • Broker tests added in the fourth review: a close of the host session during a new session's exchange, while its open record is sent, and when the sink refuses that record, each with the close following and naming the open's refusal; a close during an exchange with a malformed answer recorded once; an open queued behind a closed host session failing without an AS-1 exchange or a stored session, and the mark ending after five minutes; the queue keeping its last 256 slots for closes; the conformance contract now refusing an open of a closed host session. Mutants caught: the close not held, the held close naming the superseded record, no mark, a held close overwritten, closes without a reserve, and token_used ending the 503 rule. Not dedicated-tested: the check of a closed session just before the success record is sent, a window no test can reach without a hook.
  • Broker tests added in the third review: a close of the host session during a new session's open closes it and the open stores nothing; a close of a host session with none succeeds; closing an earlier, already closed session keeps the current session's history, and closing the host session with no open broker session forgets it (another workload's close forgets nothing); a denied call returns while the sink is stalled on its refusal; outcomes of record_not_accepted and session_closed refusals; the queue counts a record in flight at close; conformance for closing by host session and its invalid requests.
  • task lint and task docs are clean. go test -race passes on internal/identitybroker/... (three runs), internal/agentcredential, internal/adapter/server, internal/app, and cmd/mecak8s.

Closes #2541
Closes #2999

🤖 Generated with Claude Code

rdimitrov and others added 3 commits November 25, 2026 03:10
The broker now records every event audit.md assigns to it: each session
open (converted token, token AS-1 already converted, tokenless) and each
refused open, every close path once (including a hard expiry a lookup
finds), each agent registration and refused registration as a lineage
event, each accepted or refused delegation report as a lineage event,
and each ID-JAG and call decision. Every record has its own AuditID, the
audit profile's Subjects keys with provenance marks, and AuditID
references to the session open, the acting instance's registration, and
the delegation it runs under. No record carries a credential value.

Records go through one Recorder sink that can refuse a record. A
successful open, registration, or delegation report takes effect only
after its record is accepted, and otherwise fails UNAVAILABLE and changes
nothing; refusals and closes take effect anyway, and a refused record is
reported on a separate delivery-failure channel. The ID-JAG and decision
keep their existing write order.

mecak8s reports a team member's parent, and its delegation, as the
root's main agent standing in for the RunTeam API request.

Closes #2541

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Name a delegation's run owner RunOwner and the session owner Owner, as
in the other records, and the stand-in mark DelegatingStandIn. A refusal
recorded after an accepted success that could not take effect names it
in Supersedes. The delegation record carries the delegating agent's
incarnation. WithDeliveryFailures is marked as a shortcut removed by
#2848.

Tests now cover a refused open whose record is refused, an open
cancelled while waiting for its host session, registrations and
delegations whose session closes while they are recorded, a Token held
in any record, and the app's record summary line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review against #2541 and the agent identity design (including #2984's write-order table), and against the tickets that build on this. Each point is a question with the code to check, so it can be verified or rejected point by point; I may be wrong on any of them. Line references are at c816bb7.

1. Can a new session be used before its open record is accepted?

pairLocked adds a new session to t.byID and t.open (internal/identitybroker/sessions.go:280-281) during b.open, before b.record sends the open record (sessions.go:161). The open lock only makes other opens of the same host session wait.

  • While the record is in flight, can FindSession, RegisterAgent, ReportDelegation, or CloseSession reach the session? The comment at sessions.go:309-313 ("A registration made while the open was recorded may [refer to it]") suggests yes.
  • If the open record is then refused, accepted records point at an AuditID the sink never accepted. #2984 says "a session … without its record would leave those references unresolved, so it is not kept." Should the session stay pending (refused by lookups and registrations) until its record is accepted?
  • On the mismatched-answer path in sessionopen.go, is the close record sent before the refused-open record it points to?

2. Who sends close records, and with what deadline?

Close records are queued under the table lock and sent in tableMutex.Unlock (sessions.go:69-80) by whichever goroutine releases the lock, using context.Background() (broker.go:130).

  • Can that goroutine be an AuthorizeCall, or a registration holding its own lock? If so, a slow sink, or a blocking one in #2848's lossless mode, stalls unrelated calls with no bound.
  • Records leave in unlock order, not event order, and RecordHeader has no sequence field. Will #2566/#2848/#2808 need ordering assigned when the record is queued?
  • Would a bounded queue drained by its own goroutine fit better?

3. A refused open record after conversion is mapped as retryable

After a token conversion, a refused open record returns errNotRecorded (UNAVAILABLE), which internal/adapter/server/identity_broker.go:624 maps to ErrIdentityBrokerUnavailable. The close-after-conversion case just above it returns errBrokerSessionClosedAfterToken ("fail as for a refused token").

  • Should a refused record after conversion take the same path? Otherwise the client retries with a spent token and gets token_used.
  • errNotRecorded has no reason. Should it carry one (for example not_recorded), so #2559's ErrorInfo can express it?

4. Who retries a refused registration or delegation report?

#2984 says mecak8s retries a registration and reports a delegation again. Here, a failed registration stops the helper (identity_broker_helpers.go:25), and I couldn't find a retry for a failed ReportDelegation (the holder in internal/agentcredential/holder.go). Is a retry planned, or should #2984 say the helper fails? See the matching question on #2984.

5. Rollbacks after a refused record leave no follow-up

When the sink refuses an open, registration, or delegation success record, the code returns errNotRecorded and records nothing after it (sessions.go:161-169, and the matching paths in agents.go and runs.go). A sink that timed out after storing the record leaves a success for something that was rolled back. The decision path does write a follow-up error record (authorize.go, via refuse), and the close-during-record path uses Supersedes.

  • Should every rollback after a refused record write a refusal through recordAnyway with Supersedes set to the attempted AuditID?
  • Supersedes isn't in the design yet; see #2984.

6. Re-reported delegations after a reopen

A close drops the per-session run and delegation ledger (sessions.go:305). When the holder reports delegations again into the reopened session, each gets a new mecatl_delegation success with a fresh AuditID and no link to the earlier one. Registrations carry PreviousRecord; DelegationRecord doesn't.

  • Should delegation records keep the delegation ID → AuditID mapping outside the per-session ledger and carry a PreviousRecord, so #2844's lineage walk doesn't see one delegation recorded several times with no link?

7. Grant provenance for schedule grants

heldGrant.user and openRecord (sessionopen.go) feed ID-JAG and decision subjects as record:<open AuditID>, and OpenKind has converted, already_converted, and tokenless. #2569's scheduled runs open from a schedule grant, and #2843 requires that no scheduled-run record present the saved owner as a fresh sign-in.

  • Would a typed provenance reference (open record or schedule-setup record) now avoid reshaping these types in #2569?

8. One record per event across replicas

The new per-incarnation (registering) and per-session (reporting) locks are what keep an identical repeat from producing a second success record. They are in-process.

  • With replicas (#2805, #2558), can two replicas each record the same registration or delegation under different AuditIDs? If so, should #2805's scope gain "one accepted record per registration and delegation across replicas"?

9. Smaller points

  • DelegatingRunRecorded: the flag is set from the first check in runs.go, but AuthorizeCall can add the root run without the reporting lock before the second check. Can the record claim the report recorded a run it didn't?
  • Malformed requests: when validation fails, OpenSession, RegisterAgent, and ReportDelegation return before a record exists. Should a refused-as-invalid request still be recorded, as #2541 and step (3)/(4) "Evidence" say for refusals?
  • workload_iss is always set unavailable (records.go, the subjects builder), even for a verified workload. audit.md says to qualify workload subjects by issuer or trust domain. Intended, or a shortcut?
  • Registration lineage: only agent_instance_ref is marked reported:mecak8s; Parent, ParentHostSessionID, ParentStandIn, Definition, and HostSessionID carry no mark. audit.md "Lineage" says these are marked as reported by mecak8s.
  • Stand-in detection: helperParentHost treats any helper with no parent session as a stand-in (identity_broker_helpers.go:146). Should it also require the team-member session kind, so a future parentless helper kind isn't marked?
  • Diagnostics: loggedRecorder (internal/app/identitybroker.go:750-767) writes each record's type, AuditID, outcome, code, and reason to diagnostics, and the harness test reads that line. AGENTS.md keeps audit and diagnostics separate, and #2566 removes diagnostic lines that only repeat a broker event. Could the test read the sink directly instead?
  • The MemoryRecorder shortcut names #2563 as a remover. Isn't storage and delivery of audit records #2566's?
  • Renewal re-registers, so each renewal now waits on the sink and writes a mecatl_instance_registered, and a child's ParentRecord points at the latest renewal. Is that the intended lineage, or should #2562 record renewal as credential issuance?
  • API compatibility: the statement says clients see no new behaviour. Registrations of one incarnation and reports to one session now wait for each other, a cancelled wait returns UNAVAILABLE, and an open can fail with session_closed if a close lands during its record. Not breaking, I think, but worth listing.
  • IDJAGRecord.User is an Owner while other records use User and Owner separately; align now, or leave it for #2727?

rdimitrov and others added 2 commits November 25, 2026 14:46
- An open whose record is not accepted changes nothing and still
  remembers the converted source jti. It fails with record_not_accepted:
  as for token_used when it converted the request's token, which mecak8s
  answers with bearer_rejected, and UNAVAILABLE otherwise.
- A refused open never leaves the broker session it created, whatever
  happens to its record. The close names the refusal's record.
- Every event undone after its success record was sent records a
  refusal that supersedes that record: an open, a registration, a
  delegation report, and a withheld call decision.
- Registrations and delegation reports whose record is not accepted fail
  with record_not_accepted; mecak8s does not retry them.
- The user's token client is recorded as user_client_id and
  user_client_iss.
- The stand-in marks on registrations and delegation reports move to
  #2557.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A new broker session enters the table only once its open record is
  accepted, so nothing reaches it while the record is in flight and no
  accepted record refers to an unaccepted open. A mismatched answer's
  close is queued after the refused-open record it names.
- Close records go through a bounded queue drained by its own
  goroutine, each send with a deadline, so no call waits on the sink for
  them. A record past the bound is dropped and reported.
- A delegation reported again into a reopened session refers to its
  earlier record (PreviousRecord).
- Requests that fail validation are recorded as refusals with only the
  calling workload.
- A verified workload is qualified by its authenticator's issuer, and
  registration and delegation lineage is marked as reported by mecak8s.
- The harness reads the broker's record sink instead of the diagnostics
  line, and the MemoryRecorder shortcut names #2566 only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov

Copy link
Copy Markdown
Member Author

Thanks, these checked out. ee547bf follows #2984's revised write order (cf42713), and a89b2eb addresses the rest; the PR body is updated.

  1. Session usable before its record is accepted. Fixed. A new session enters the table only after its open record is accepted, so lookups, registrations, delegation reports, calls, and closes cannot reach it while the record is in flight. On the mismatched-answer path, the close record is queued after the refused-open record it names.
  2. Who sends close records. Fixed. Close records go to a bounded queue drained by its own goroutine, one record at a time with a 10-second deadline, so no call or registration waits on the sink. They are queued under the table lock, so they keep the order the closes happened in. A record past the bound is dropped and reported as a delivery failure, as a shortcut naming [Phase 3] Authorization server and gateway audit records, and reconciliation #2848. Sequence numbers are left to Audit records and delivery #2566/[Phase 3] Tamper-evident audit records #2808, where the sink receives records.
  3. Refused open record after conversion. Fixed. It fails with reason record_not_accepted, as for a refused token when the open converted the request's token (the client refreshes), and as UNAVAILABLE otherwise. The broker still remembers the converted jti.
  4. Retries. None, as docs(agent-identity): settle the broker's write order for every audit event #2984 now says: a refused registration or report stops the helper or team member.
  5. Rollbacks. Every rollback after a refused record (open, registration, delegation report, withheld decision) now writes a refusal with Supersedes set to the attempted AuditID.
  6. Re-reported delegations. DelegationRecord gains PreviousRecord. The broker keeps each delegation's latest accepted record by root host session, outside the per-session ledger a close drops.
  7. Schedule-grant provenance. Left for Phase 2, Slice 3: Scheduled runs — A scheduled run calls gateway tools on its own grant, with no one present #2569; noted in the PR body.
  8. One record per event across replicas. Left for [Phase 3] Run mecak8s with the identity broker on more than one replica #2805; noted.
  9. Smaller points.
    • DelegatingRunRecorded: no change. A call can record the same root run between the two checks, but with identical content; a different owner makes the recheck refuse the report and supersede its success record. Making it exact would need calls to take the reporting lock.
    • Malformed opens, registrations, and reports are now recorded as refusals, with only the calling workload. AuthorizeCall follows with Bind each gateway token to its call #2727, which changes that code.
    • workload_iss is set when the workload is verified; no authenticator verifies one yet, so it is still empty today.
    • Registration and delegation records now mark their lineage fields reported:mecak8s.
    • The stand-in marks are removed (moved to Runs, delegations, and the run owner #2557), so the detection question is moot.
    • The harness test reads the in-memory records directly instead of the diagnostics line.
    • The MemoryRecorder shortcut names only Audit records and delivery #2566.
    • Renewal lineage is left as is for Identity broker credential renewal and key rotation #2562 to decide.
    • The API compatibility statement now lists the new waits, the UNAVAILABLE from a cancelled wait, session_closed during a record, unreachable new sessions, and closes that no longer wait.
    • IDJAGRecord.User alignment is left for Bind each gateway token to its call #2727, which edits the same code.

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the fixes. Points 1, 3, 5, 6, and most of the smaller points check out at a89b2eb, and the focused race tests pass. A few things remain, two of them new with the fixes. As before, each is a question with lines to check, and I may be wrong on any of them. Line references are at a89b2eb.

1. Refusal records wait on the sink with no deadline, under per-key locks

recordAnyway sends with context.WithoutCancel(ctx) and no timeout (internal/identitybroker/records.go:563-565). refuseOpen is called while the host session's open lock is held (taken at sessions.go:139, released by the deferred unlock at :143). The registration and report refusals run under the registering and reporting locks (agents.go, runs.go).

  • The usual way into record_not_accepted is the success record's context ending against a slow sink. The superseding refusal is then sent with no deadline at all. Can that hang the call, and every later open, registration, or report for the same key behind it, once #2566's HTTP sink is in place?
  • #2984 says a refusal is never held back. Should refusals go through the same queue as closes, or at least get a deadline like queuedRecordTimeout and be sent after unlocking?
  • Waited records use the caller's context with no broker-side deadline either. Is that intended?

2. Can a delete or sign-out close an open that is still being recorded?

A new session enters t.byID and t.open only once its record is accepted (sessions.go:172-182). FindSession reads only t.open (sessions.go:384). mecak8s closes by find-then-close, on delete or session end (internal/adapter/server/identity_broker.go:553-556) and in closeUnsavedPairing (:282).

  • If a delete races an open, does the find miss the in-flight session, so the open then completes and holds a fresh refresh token for a host session that no longer exists, until hard expiry?
  • The comment at sessions.go:402-404 ("an open converting a token for the session meanwhile discards the new one") seems to no longer hold for new sessions.
  • Would a pending entry that closes can mark (and lookups can't use), or having the close path take the host session's open lock, cover it? #2568's sign-out everywhere would need the same.

3. Is the close queue bounded, and can drops be detected?

  • Past 1024 waiting records, overflow goes into q.full, which has no limit (recordqueue.go:55-57), and is only reported between sends, each of which can take up to 10 s. A sink that ignores its context blocks drain, so full grows and its drops are never reported. Should push report and discard instead of storing?
  • A drop is reported only as a diagnostics warning (internal/app/identitybroker.go:657-660). Nothing in the audit trail marks the gap for #2808/#2846/#2848's gap detection, and the PR body says sequence numbers are assigned where the sink receives records, which is after the drop. Should a record be numbered when it is emitted, before the queue?
  • There's no Broker.Close that drains the queue; wait() is only called from tests (export_test.go:105). Are close records still queued at shutdown lost without a report? End-to-end tests (#2817, #2457) also have no way to wait for them outside the package.

4. Stand-in marks went to a closed ticket

The marks moved to #2557, which closed on 2026-11-23 (via #2930) and doesn't mention them. An API-created team member now registers with the root as its parent and no mark (internal/adapter/server/identity_broker_helpers.go:46-49), so the trail states that as fact for #2844 and #2817. Should a new ticket track this, with a code shortcut naming it at that line?

5. Deferrals named only in the PR description

The description defers several things, but the target tickets haven't changed. Should each get a line, so the work isn't lost?

  • #2569: grant provenance for schedule grants;
  • #2805: one accepted record per registration and delegation across replicas (its scope still says only run records and delegation reports);
  • #2562: renewal recorded as credential issuance rather than registration (#2848 also lists credential issuance events);
  • #2727: IDJAGRecord naming;
  • #2566: whether mecak8s retries after record_not_accepted;
  • #2563: the new in-memory reference state (openRecord, user.openRecord, registrationRecord, runLedger.previous, heldClose);
  • #2568: the refresh-token discard site at sessions.go:155, which its list of four sites doesn't include.

6. Smaller points

  • runLedger.previous is keyed by root host session and never pruned (runs.go:50-100). It also sets PreviousRecord on a changed repeat refused in the same session, while the field doc (records.go:423-427) says "in an earlier broker session". Prune on root close, and set it only across sessions?
  • internal/agentcredential/holder.go:329-334: when the second report after a move fails, is the moved entry already stored, so the next lookup doesn't see again and never reports it? If so, that helper's gateway calls fail closed for the rest of its run. Store the moved entry only after the report succeeds, or say this case fails closed?
  • record_not_accepted maps to UNAVAILABLE from Reason.Code() (errors.go:85-86) but the converted open returns UNAUTHENTICATED, so errors.Is(err, ReasonError(ReasonRecordNotAccepted, "")) misses that variant. Worth a note at errors.go:68, and for #2559's ErrorInfo mapping to match on reason?
  • The errors.go:68-72 comment says to retry the reason, while #2984's failure tables say registrations and reports aren't retried. See question 1 on #2984.
  • With mecatui's single refresh-and-retry (cmd/mecatui/client/client.go:319-335), a sink outage during an open spends two tokens and reaches the user as Unauthenticated. Is that the intended experience, or should #2457 check it?

rdimitrov and others added 2 commits November 25, 2026 16:23
- Every send to the sink has a 10-second deadline, so a slow sink fails
  a waited record with record_not_accepted instead of holding the call.
- Refusals go through the queue closes use, so no caller and no
  open, registration, or report lock waits on the sink for them. A
  refused open's close follows its refusal.
- The queue reports and drops a record past its bound, and
  Broker.Close, called at shutdown, sends what is queued until its
  deadline and reports what it could not send.
- A lookup of a host session whose open is creating a new broker
  session waits for that open, so a delete's find-then-close closes the
  session the open made.
- PreviousRecord links only across broker sessions and is forgotten
  when mecak8s closes the root's session itself.
- The holder puts a helper's old entry back when the report after its
  move fails, so the next lookup moves it and reports again.
- record_not_accepted documents its outcome per event, and that the
  converted open's code differs from the reason's usual one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A team member created over the API registers with the root's main agent
as its parent, and its delegation from the team run, with no mark that
the main agent only stands in for the API request. Name #2986, which
tracks the marks, in a code shortcut there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov

Copy link
Copy Markdown
Member Author

Thanks. 90f700c addresses these and aligns the code with #2984 at ce51086; 4ba4514 adds the #2986 shortcut. The PR body is updated.

  1. Refusal records under per-key locks. Changed. Refusals for opens, registrations, and delegation reports now go through the same queue as closes, so no caller and no open, registration, or report lock waits on the sink for a refusal; a refused open's close is queued after its refusal. Every send to the sink has a 10-second broker-side deadline, so a slow sink fails a waited record with record_not_accepted instead of holding the call. Decision refusals stay synchronous with that deadline, since AuthorizeCall holds no per-key lock and Bind each gateway token to its call #2727 is changing that code.
  2. A delete racing an open. Changed. While an open is creating a new broker session, FindSession for that host session waits for the open to finish, so mecak8s's find-then-close closes the session the open made and discards its refresh token. Lookups of existing sessions never wait. Sign-out everywhere (Sign-out and revocation #2568) closes the same way. The CloseSession and FindSession comments say so, and a test covers the race.
  3. Queue bound, drops, and shutdown. Changed. push reports and drops a record past the 1,024 bound; there is no unbounded overflow. A new Broker.Close(ctx) sends what is queued until its deadline and reports each record it could not send, and app shutdown calls it with a 10-second deadline, so an end-to-end test can read every record after Built.Close(). Numbering at emission is left to Audit records and delivery #2566/[Phase 3] Tamper-evident audit records #2808, with a shortcut naming [Phase 3] Authorization server and gateway audit records, and reconciliation #2848 and [Phase 3] Tamper-evident audit records #2808.
  4. Stand-in marks. Tracked in Mark team members created over the API as having a stand-in parent #2986 (child of Phase 2, Slice 5: Attributed trail — Every decision and call is recorded and traced to the agent, its parents, the session, and the user #2565, blocked by Broker records of who acted #2541, blocking Trace an agent to its parents, session, and user from the audit records #2844). A code shortcut naming it sits where an API-created team member registers.
  5. Deferrals. Each now has a note on its ticket: Phase 2, Slice 3: Scheduled runs — A scheduled run calls gateway tools on its own grant, with no one present #2569, [Phase 3] Run mecak8s with the identity broker on more than one replica #2805, Identity broker credential renewal and key rotation #2562, Bind each gateway token to its call #2727, Audit records and delivery #2566, Durable broker state and recovery #2563, and Sign-out and revocation #2568. Sign-out and revocation #2568's note covers the refresh token an unrecorded open discards.
  6. Smaller points.

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks. Round 2 checks out at 4ba4514: refusals are queued, sends have a deadline, the queue is bounded, Broker.Close drains it, and the ticket notes and #2986 are in place. Focused race tests pass with -count=3. Nothing here blocks; question 1 is the one I'd look at before merge. Same format: questions with lines to check, and I may be wrong on any. Line references are at 4ba4514.

1. Can the delete path still miss an open in progress?

closeIdentityBrokerSession bounds its find with engineCloseTimeout, 10 s (internal/adapter/server/service.go:1158, used at identity_broker.go:550). The open that FindSession waits for (internal/identitybroker/sessions.go:400-416) can take up to the AS-1 request timeout plus recordTimeout.

  • If the find gives up first, the close is skipped and only logged, so the open completes and keeps its refresh token until hard expiry. Is that the round-2 race again, just narrower?
  • FindSession checks for an in-flight new open once. Can another open create a new session between its wait ending and its t.mu.Lock()?
  • Would marking the host session deleted in the broker (so an open in progress closes its own session when it finishes) close it fully? Or a find timeout longer than the open's worst case, with a recheck?
  • The API compatibility note says a concurrent request "already waited". Does that hold for delete, which never opened?

2. Denied calls still wait on the sink, under the AS-2 read lock

recordDecision sends synchronously with context.WithoutCancel (recorder.go:186-193). In AuthorizeCall, refuse at authorize.go:88 runs after acquireAS2 and before the deferred release().

  • #2984 says a denied call's refusal is never waited for. Here a call can take up to 10 s past its own deadline, and unbind and new calls queue behind a slow sink. Queue decision refusals too, or keep this with a shortcut naming #2727?
  • The PR body's "closes and refusals no longer wait for their records" isn't true for calls yet.

3. CloseSession forgets history even when the close changed nothing

sessions.go:452-456 calls forgetPreviousLocked(s.HostSessionID) unconditionally, including when s was already closed or isn't the host session's current broker session. closePreOpenedBrokerSession closes by broker session ID precisely so it doesn't touch the winner of a create race (identity_broker.go:260-263), but this erases the winner's history, so its next re-report has no PreviousRecord. Forget only when the close took effect and s was the host's current session?

Related: the history is still never pruned when a host session is deleted while it has no open broker session (after hard expiry, a lost grant, or a refused open), since the find returns not found and no CloseSession runs.

4. Smaller points

  • A refused open's close always names the refusal's AuditID (sessions.go:268-273). If the queue drops that refusal or the sink refuses it, the close points at a record that doesn't exist. Document that in the SessionRecord field, or cover it under the #2848 shortcut?
  • recordQueue.close (recordqueue.go:115-129): when the deadline passes with one record in flight and none queued, it reports "0 records not sent", and that record may still be sent after Close returns.
  • Shutdown order (internal/app/build.go:3161-3168): Broker.Close runs before ib.release() stops AS-1, so requests arriving in between have their records dropped (reported, not silent). Release the servers first?
  • Holder (internal/agentcredential/holder.go:222-224, :326, :339): between storing the moved entry and restoring the old one, a non-renewing lookup returns the new session's credential. It's transient and fails closed; worth a comment?
  • #2563's note lists close records waiting to be sent, but not queued refusals or heldClose.
  • identity_broker_unavailable gains a new cause (an audit sink refusing a record). Should the wire API statement say so, and user-docs/reference/http-sse-api.md:33 and user-docs/features/security-and-execution/caller-identity.md stop describing it only as "unreachable"? See question 7 on #2984.
  • errors.go:79-81 applies "move, renewal" retries to delegation re-reports, which #2984 limits to "after a reopen". See question 1 on #2984.

- Close a host session in the broker: CloseSessionRequest gains
  RootHostSessionID, which closes the open broker session and the new
  one an open in progress is creating, without waiting. That open then
  fails and stores nothing. mecak8s closes deleted sessions and ended
  scheduled runs this way, so a delete no longer misses a slow open.
  FindSession checks again for a new open after its wait.
- Queue decision refusals like other refusals, so a denied call never
  waits on the sink or holds AS-2's binding while its record is sent.
- Forget a root's delegation history only when a close took effect on
  its current broker session, or when its host session is closed.
- Give record_not_accepted refusals the outcome error, and refusals a
  close caused denied.
- Answer a converted open's repeated record_not_accepted, from the same
  caller for the same host session within a minute, with 503
  identity_broker_unavailable.
- Count and report the record in flight when the queue's close gives
  up; release AS-1 before draining at shutdown; read MemoryRecorder's
  slices under its lock.
- Document the new cause of identity_broker_unavailable.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov

Copy link
Copy Markdown
Member Author

Thanks. e3c9a5f addresses these and follows #2984 at 6ec9bda; the PR body is updated.

  1. Delete missing an open in progress. Fixed. CloseSessionRequest gains RootHostSessionID: a close by host session closes its open broker session and also a new one an open is still creating, without waiting for that open. When the open finishes, it fails with session_closed, records a refusal that supersedes its success record, and keeps no refresh token. mecak8s now closes deleted sessions and ended scheduled runs this way, so the delete's 10-second timeout no longer matters. FindSession also checks again after its wait, in case another open started meanwhile. The API compatibility note no longer says a delete waited. A new test deletes with a 50 ms timeout while another replica's open is stalled, and fails against the old find-then-close code.
  2. Denied calls waiting on the sink. Fixed. Decision refusals go through the same queue as the other refusals, so a denied call never waits on the sink or holds the AS-2 lock while its refusal is sent. The PR body's claim now names denied calls, and the refusal test fails if decision refusals are sent synchronously.
  3. History forgotten too eagerly. Fixed. A close by broker session ID forgets the delegation history only if it closed the host session's current broker session. A close by host session always forgets it, including when no broker session is open. History is kept per workload.
  4. Smaller points.

From #2984's round 3: a repeated record_not_accepted on a converted open within a minute, for the same caller and host session, answers 503 identity_broker_unavailable, with tests for the repeat, recovery, and the window. Superseding refusals use error for record_not_accepted and denied when a close caused them, decisions included. The race detector also caught a data race in this PR's MemoryRecorder accessors, now fixed.

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks. Round 3 checks out at e3c9a5f: a delete closes by host session without waiting, FindSession re-checks, decision refusals are queued, history is forgotten only when a close takes effect, and shutdown order is fixed. Race tests pass with -count=3 and go vet is clean (task lint hit unrelated typecheck errors in cmd/mecatui/ui locally, so CI is the check there). Questions 1 and 2 are the ones I'd want answered before approval; the rest is minor. Same format: questions with lines to check, and I may be wrong on any. Line references are at e3c9a5f.

1. The 503 repeat rule for creates, and after the 503

openRecordRefusals keys on owner and host session (internal/adapter/server/identity_broker.go:658-697).

  • A create without an explicit ID gets a new host session ID on every attempt (preOpenIdentityBrokerSession, :243-252), and fork and clear open a new host session too. Does the repeat ever match for them, or does every create during a sink outage get 401 and spend a fresh token?
  • After the 503, the token is spent. If the client retries with it, the broker answers token_used, and note "forgets the previous refusal" for any other outcome, so the next refreshed attempt is a first failure again. Should a token_used following a counted refusal keep the window? The PR body's "a conforming client retries without spending another token" seems not to hold yet.
  • The state is per replica; a retry reaching another replica gets 401. Worth a line in the docs?

See questions 1–3 on #2984 for the design side.

2. Can a deleted host session get a new broker session?

closeHostLocked (internal/identitybroker/sessions.go:478-486) closes t.open[host] and t.newOpens[host] but leaves no mark. An open queued on t.opening behind the one being closed then gets the lock, pairLocked creates a new session, converts, and stores a refresh token. An open from another replica that loaded the session before the delete can do the same. Either way the deleted host session gets a broker session nothing closes before hard expiry. Would a bounded, time-limited "host closed" marker that pairLocked checks cover it, or should a shortcut name the remaining window? The commit message's "a delete no longer misses a slow open" and the CloseSessionRequest doc may overstate it as is.

3. Close records from closeHostLocked for a session still opening

closeHostLocked queues a CloseRequested record naming the open's AuditID (sessions.go:479-481) before that open's record is sent.

  • Close during the AS-1 exchange: the close is queued before the refusal it names, and refuseOpen then skips its own close because the session is already closed. Doesn't that contradict refuseOpen's "queued after the refusal"?
  • Close between open() returning and b.record: does the open still send its success record for a closed session, possibly after the close?
  • Open record refused by the sink: does the close then name a record the sink never accepted? The comment at sessions.go:189-194 says no accepted record refers to an open the sink did not accept; the close record queued by closeHostLocked seems to be the exception.

Would holding the close in s.heldClose for a session in newOpens, and checking s.closed before sending the success record, fix all three?

4. Smaller points

  • Denied-call refusals now share the 1,024-entry queue with closes (recorder.go:192-197, recordqueue.go:57-66). An agent looping on denied calls while the sink is slow can push close records out; the drops are reported, but closes matter for revocation. Reserve room for closes, or note it under the #2848/#2563 shortcut?
  • A record in flight at close is reported as errRecordInFlightAtClose (recordqueue.go:138-141), and the drainer's b.record reports it again if the sink then refuses it (records.go:533-536); if the sink accepts it, the first report was wrong. Worth a note in the DeliveryFailure contract?
  • A tokenless open on another replica closed by a delete now fails with session_closed, which maps to errBrokerSessionClosedAfterToken and then ErrInternal (identity_broker.go:183-190, :623-627), so the caller sees 500. Map it to not found or unavailable instead?
  • user-docs/features/security-and-execution/caller-identity.md:220-230: "If the broker is unreachable, or its audit sink, the destination of its audit records, does not accept…" is hard to parse; split it, and add the limits from question 1?

- Key mecak8s's 503 rule for a repeated unrecorded converted open on the
  verified owner alone, so creates, forks, and clears, which open a new
  host session each time, reach it. Only a successful open ends it; a
  token_used from presenting the token the 503 spent keeps it. The state
  is per replica and best effort.
- Mark a host session closed by host session, per workload, for five
  minutes. An open of a marked host session fails with session_closed
  before it converts or stores anything, so an open queued behind the
  one a delete ended, or one whose request loaded the session before the
  delete, gives it no new broker session. A replica that did not serve
  the close, a restart, or a later open is a shortcut under #2805 and
  #2563.
- Hold the close of a new session an open is still creating until that
  open's refusal is queued, and have it name the refusal. Check for a
  close before sending an open's success record, so a closed session gets
  only a refusal. A close no longer precedes, or names, a record the sink
  was not given first.
- Keep the last 256 of the record queue's 1,024 slots for closes, so
  refusals from denied calls cannot push them out.
- State in the DeliveryFailure contract that a record in flight at Close
  may still be accepted, or be reported again.
- Answer a tokenless open refused with session_closed, as after a delete,
  with 404 session_not_found instead of 500.
- Rewrite the caller-identity doc's 503 paragraph and add the rule's
  limits: the spent token after a 503, per replica, best effort. The
  HTTP reference's 503 row says the token is spent in that case too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov

Copy link
Copy Markdown
Member Author

Thanks. 7bab17a answers these and follows #2984 at 00ae95c; the PR body is updated.

  1. The 503 rule.
    • The rule now keys on the verified owner alone. Creates, forks and clears get 503 on the repeat even though each opens a new host session. Scheduled sessions never present a token, so the rule doesn't apply to them.
    • Only a successful open ends the minute. Any other failure keeps it, including a token_used from presenting the spent token. mecak8s doesn't read the token's jti, so it can't compare by it.
    • The PR body no longer says the client retries without spending a token. After a 503 the token is spent, and the client refreshes before retrying.
    • The code comment, caller-identity.md and http-sse-api.md say the rule is per replica and best effort.
    • TestIdentityBrokerRepeatedUnrecordedOpenIsUnavailable covers, in order: a first refusal, a create on a new host session, the spent token, and recovery after a success.
  2. A deleted host session.
    • A close by host session marks it closed for its workload for 5 minutes. pairLocked checks the mark first, so a later open fails with session_closed before any conversion and stores nothing.
    • Why 5 minutes: an open holds its host session's lock for at most 70 s (two AS-1 requests and one record send).
    • A shortcut note names what is left, under [Phase 3] Run mecak8s with the identity broker on more than one replica #2805 and Durable broker state and recovery #2563: a replica that did not serve the delete, a restart, or an open more than five minutes later.
    • Tests:
      • an open queued behind the closed one fails with no AS-1 call;
      • the mark expires at five minutes;
      • the conformance suite expects a reopen of a closed host session to fail.
    • The CloseSessionRequest doc matches.
  3. Closes of a session still opening. Fixed as you suggested.
    • closeHostLocked holds the close of a new session in heldClose, and refuseOpen queues it after the refusal, naming the refusal's record.
    • OpenSession checks s.closed before sending the success record.
    • Tests cover a close during the AS-1 exchange, while the success record is being sent, when the sink refuses the open record, and during an exchange with a malformed answer. Each checks that the close follows the refusal and names it.
    • One gap: the check made just before the success record is sent has no dedicated test, because that window can't be reached without a test hook in production code.
  4. Smaller points.
    • The last 256 of the queue's 1,024 slots take only closes, with a test.
    • The DeliveryFailure contract says a record still being sent at Close may later be accepted or reported a second time.
    • A tokenless open closed by a delete now gets 404 session_not_found instead of 500.
    • caller-identity.md: the hard sentence is split, and the limits from point 1 are added.

Known and left as is: an open that presents a token for a deleted host session within the five minutes gets 401 bearer_rejected, although no token was spent. The client refreshes, retries, and then gets 404.

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving. Round 4 checks out at 7bab17a, and the focused race tests pass with -count=3. The points below are minor and fine as follow-ups; I may be wrong on any of them. Line references are at 7bab17a.

  • refuseOpen sends an open's refusal through the queue, which drops non-close records once 768 slots are full, while the held close that follows can still take a reserved slot and names that refusal (recordqueue.go:74, sessions.go:343, :357-360). Under a flood of denied calls, the sink can accept a close naming a record it never got, so the comment at sessions.go:352-355 and the PR body's "no close names a record the sink was not given first" don't quite hold. Letting open refusals use the reserved slots, or reserving room for the refusal and its close together, would fix it.
  • An ID-JAG record that isn't accepted returns errNotRecorded without a superseding refusal (authorize.go, around :175), while #2984's audit.md:142 asks for one when an event is undone.
  • The PR body says "schedules present no token, so never reach it". It's scheduled runs that present no token; schedule setup and renewal, which #2984 counts toward the rule, aren't in this PR (#2569).
  • user-docs/reference/http-sse-api.md:33 says to refresh "when the cause is the audit sink refusing your repeated session opens", but the 503 carries the same code either way. "After a 503 on a request that presented a token, refresh the token before retrying" is something a client can act on.
  • The host-closed mark ignores incarnation. Only the scheduler creates with an explicit ID today, so it can't block a re-create in practice; worth keying on incarnation if that changes.

@ChrisJBurns ChrisJBurns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

See the inline comments.

At: now, SessionID: s.ID, Workload: workload, Owner: owner, OwnerVerified: s.verifiedOwner != nil,
RecordHeader: RecordHeader{Type: TypeToolDecision, At: now},
SessionID: s.ID, Workload: workload, Owner: owner, OwnerVerified: s.verifiedOwner != nil,
UserRecord: userRecord, User: user,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important · security — Decision provenance remains attached to the old grant after a retry

decisionRecord snapshots UserRecord and User before the call selects its grant, and neither field is updated when authorizeAtGateway retries with a replacement grant. The supported replacement path—already exercised by “a newer grant is retried” in authorize_integration_test.go:533—therefore produces an ID-JAG record referencing the new open but a successful decision referencing the old open; if the replacement token has a different client identity, the decision also records the wrong verified client. This makes the newly added provenance inconsistent with the credentials actually us

Recommendation: Update the decision’s user provenance from the specific heldGrant selected for each exchange attempt, including retries, so the final decision and its ID-JAG reference the same grant; retain the initial session snapshot only for refusals before a grant is selected. --- ## No Issues

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 14d7da2. A decision's user and user record now come from the grant each exchange uses, a retry's newer grant included, so the final decision and its ID-JAG name the same open. The session snapshot is used only for refusals before a grant is selected. The "a newer grant is retried" test now checks that both records name the reopen; it fails against the old code.

- Queue a refused open's refusal and its close as one group, whole or
  not at all, and let a group with a close use the queue's reserve. A
  flood of denied-call refusals can no longer drop the refusal while its
  close, which names it, is sent.
- Follow an ID-JAG record the sink did not accept with an ID-JAG refusal
  that supersedes it (record_not_accepted, outcome error), as audit.md
  asks whenever the broker undoes an event.
- Take a decision's user and user record from the grant each exchange
  attempt uses, a retry's newer grant included, so the decision and its
  ID-JAG name the same open. The session's user stays only for refusals
  before a grant is selected.
- Key the host-closed mark on the closed incarnation as well:
  CloseSessionRequest gains RootHostIncarnation, required with
  RootHostSessionID, and mecak8s passes the deleted session's. A session
  deleted and created again under the same ID opens, while an open
  queued behind the delete is still refused.
- Answer an open of a saved session that the broker refuses with
  session_closed, with or without a token, by what the store holds: 404
  session_not_found when the session is gone or was created again, and
  the retryable 503 identity_broker_unavailable when it remains, as after
  a scheduled run ends. It is no longer 401 or 500.
- Tell clients to refresh the token after any 503 on a request that
  presented one, and name the closed-while-opening cause, in the HTTP
  reference and the caller-identity page.

Closes #2999

Co-Authored-By: Claude Opus 5.5 <[email protected]>
rdimitrov added a commit that referenced this pull request Nov 26, 2026
An open whose broker session closes after it converted the token is refused
with session_closed, which mecak8s answers 503 while it still has the session
and 404 once it is gone, as #2985 does. A create, fork, or clear, whose
session is not saved yet, still fails as for a refused token.

Refs #2998

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@rdimitrov

Copy link
Copy Markdown
Member Author

14d7da2 answers your inline comments and the points from your approval (tracked in #2999, which this PR now closes). The comments on sessions.go and identity_broker.go are no longer on the PR, so I'm answering them here:

Host-closed mark and incarnation (sessions.go). CloseSessionRequest gains RootHostIncarnation, required with RootHostSessionID, and the mark is keyed on workload, host session, and incarnation. Every delete path and EndScheduledRun pass it. A new server test deletes a session, creates it again with the same explicit ID within five minutes, and expects its broker session to open; it fails when the mark ignores the incarnation. #3000 puts the same rule in the design.

404 only when the session is gone (identity_broker.go). As you suggested: After a session_closed refusal, with or without a token, mecak8s checks its store:

  • the session is gone, or was created again under its ID: 404 session_not_found;
  • it is still stored: 503 identity_broker_unavailable, which clients retry after refreshing a token they presented.

Tests cover a session deleted during the open, a kept session whose scheduled run ended, and an open that presented a token. The comment is corrected. One consequence: a broker session closed while the open converted the token now answers 503 rather than 401 when the session is still stored. #3000 updates the design to match.

A create's open still answers session_closed with 401, because the session is not saved yet, so there is nothing to check.

#2999:

  • An open's refusal and its close now enter the queue together, all or nothing, and a pair holding a close may use the reserved slots, so the sink never gets a close without its refusal. There is a test that fills the queue with denied-call refusals and then refuses an open.
  • An ID-JAG record that is not accepted is followed by a superseding refusal (error, record_not_accepted), with a test.
  • The 503 advice in http-sse-api.md and caller-identity.md is now one rule: after a 503 on a request that presented a token, refresh the token before retrying.
  • The PR body says scheduled runs present no token, and that schedule setup and renewal count toward the rule once Phase 2, Slice 3: Scheduled runs — A scheduled run calls gateway tools on its own grant, with no one present #2569 adds them.

The design side is #3000.

@rdimitrov
rdimitrov merged commit 69d1894 into main Nov 26, 2026
50 checks passed
@rdimitrov
rdimitrov deleted the claude/broker-audit-records-90c878 branch November 26, 2026 14:00

This branch was successfully deployed

1 active deployment
Preview — 14d7da2c Deployed Nov 26, 2026 by vercel[bot]
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.

Broker audit records: follow-ups from the implementation review Broker records of who acted

2 participants