Skip to content

fix(claims): a claim is a lease on a message that exists, in this pod (TASK-118) - #1852

Merged
lilyshen0722 merged 4 commits into
mainfrom
kai/claim-message-exists
Sep 23, 2026
Merged

lilyshen0722 merged 4 commits into
mainfrom
kai/claim-message-exists

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

TASK-118. POST /api/agents/runtime/messages/<id>/claim answered 200 {claimed:true} for an id with no message row anywhere — measured live with 999999999999. The CAS is a statement about a lease, not about the thing leased, and message_claims carries no foreign key to messages (deliberate: the busiest table in the system takes no retrofit DDL), so nothing in the write path objected. Such a lease is un-renewable, can never be completed, and the prune collects terminal states only.

The gate's four traps, and where each landed

  1. Numeric shape before the query. messages.id is SERIAL (config/schema.sql:43), so 'TASK-110' reaches Postgres as invalid input syntax for type integer and the route's catch turns that into a 500 — the phantom claim in new clothes. The guard answers a non-numeric id without issuing a query at all, so the test asserts no query was issued rather than a false returned from the database: a query that comes back empty still 500s when the column is an integer.
  2. Scoped to the pod. SELECT 1 FROM messages WHERE id = $1 AND pod_id = $2 LIMIT 1. Existence alone would let a seat installed in pod A lease a message in pod B; membership is still answered first, so an uninstalled caller gets 403 either way and cannot probe. The refusal is 404 {claimed:false, reason:'message_not_found'} for malformed / absent-from-this-pod / absent entirely — one answer, no membership oracle.
  3. The harness trap. testUtils.js:159 builds messages with id VARCHAR(24) while the shipped schema says SERIAL, so a test in that harness can pass on a value production rejects. Fixed by refusing to trust the harness instead of changing it: the suite reads config/schema.sql and asserts the messages block still declares id SERIAL PRIMARY KEY — the premise the numeric guard rests on — and reddens if anyone changes the id type. The divergence is disclosed in the test comment; the harness is not changed, because several suites insert explicit string ids into that table and retyping it is a separate change with its own blast radius.
  4. The prune gap — filed as its own row (TASK-121), not smuggled in here. Measured, and slightly narrower than the row text I was given: the prune at messageClaimService.ts:167 covers terminal states only, so an expired claimed row has no collector — but message_id is the PRIMARY KEY, so re-claims reuse the row and the table is bounded by distinct message ids ever claimed rather than by events. I looked for a functional consequence and did not find one: the CAS (:193) and holder() (:404) both treat an expired lease as absent, so re-delivery works — the laptop-lid case ADR-018 D4 exists for is answered. What is missing is collection, not correctness. A loser read (:216) can report a stale holder, which its own comment calls harmless.

Digits are not the shape — SERIAL is int4 (vera 71928, HOLD, folded)

/^\d+$/ admitted 999999999999, and that is not a syntax error: messages.id is int4, so Postgres raises 22003 value "999999999999" is out of range for type integer, which the route's catch turns into the same 500 by a different route — on this PR's own headline reproduction. Measured read-only against the live database: 999999999999 and 2147483648 throw, 5 and 00000000005 are simply absent.

The predicate is now the shape test it was always described as: Number.isInteger(n) && n >= 1 && n <= 2147483647, with the bound named (MESSAGE_ID_MAX) so it is one reviewable fact. Two tests pin the first out-of-range value and the headline id to no-query-false; a third asserts 2147483647 is asked, so the bound is load-bearing from the inside too; a fourth asserts a 100-digit input is not an escape (Number.isInteger accepts it — only the bound rejects it). Ledger M7: dropping the upper bound reds exactly that test.

And this is the honest limit of the suite. Every messageExists test mocks pool.query, so nothing here ever hands a value to Postgres — which is precisely why the first version passed. The tests pin the predicate; the end-to-end proof that 999999999999 is a 404 rather than a 500 is the live check below.

Test

  • Route: a missing message → 404 and no lease minted; a non-numeric id → the same 404; the check is asked with id and pod; membership is answered before the message is (uninstalled caller probes nothing).
  • Service: the numeric guard issues no query; empty id/pod likewise; the query is exactly pod-scoped (asserted on SQL and params); a numeric id with no row in that pod is false, not an error.
  • Schema: the SERIAL premise, scoped to the messages block.

Ledger: 6 mutations, all killed, every revert verified clean.

mutation killed by
drop the route 404 route: no lease minted
widen the numeric guard to everything service: no query for a non-numeric id
drop AND pod_id = $2 service: pod-scope assertion
accept an empty pod service: empty id/pod
messages.id → UUID service: the schema premise
decide the 404 after the CAS route: no lease minted
mutation (new head) killed by
comment arm removed — the shipped regression, reverted service: an ObjectId is claimable with no query
third arm widened to any alphanumeric service: TASK-110 still 404s without a query
comment arm placed above the pod guard service: an ObjectId with no pod is refused
canonical case widened to accept uppercase service: uppercase is refused
digits-first, digits arm returns false (71962's warning) service: the all-digit 24-hex witness

Two findings from the ledger itself, both fixed rather than hidden. (a) M5 first survived, and the survivor was my own assertion: schema.slice(indexOf('CREATE TABLE ... messages')) runs to end-of-file, so a later table's id SERIAL PRIMARY KEY satisfied the regex. Now scoped to the messages block — an unexplained survivor is a hole, and this one was a real one. (b) My first version of the CAS-order mutation was malformed (it spliced the guard inside the call's braces and died at compile time), which would have read as a behavioural kill. Replaced with a valid reorder; reported here so the table above is not a compile error wearing a kill's clothes.

Refresh — rebased onto 9841d6e2 (#1851's merge); the cleared commits are byte-identical

d4b82ec7 → e2b692ce, code head 9cd6a9ec → 7e888f14. Main moved underneath this branch when #1851 merged, so strict: true required the refresh.

Every one of the four commits carries its pre-rebase patch-id unchanged (git log -p <base>..<head> | git patch-id --stable): 57f18651…, 840fcfb1…, 7c53aae1…, a788dada… — same set, same order, nothing missing. The rebase was conflict-free, and the intersection with #1851 is empty both ways (its ten files are ipRateLimit.ts, server.ts, the pods/admin-pods/registry-install/registry-provision/billing pair, the new scanner test and the two k8s docs; this PR touches agentsRuntime.ts and messageClaimService.ts plus tests and the AX doc) — measured independently by @vera (72120) and re-derived here, after an earlier claim of mine that agentsRuntime.ts was shared, which was wrong. Post-rebase suites pass (46/46), and the only delta the refresh adds is main's own files. So a clearance at 9cd6a9ec carries to 7e888f14: the comparison is per-commit here, not just per-file.

Gate state

  • @vera — functional CLEAR (72122) at the code head 9cd6a9ec, carried to the rebased 7e888f14 (docs e2b692ce) by the patch-id set above. She killed a mutation of her own on the ObjectId arm — deleting it reddens exactly the two witnesses that matter (comment dedupe, all-digit 24-hex) and nothing else, revert verified clean.
  • Press owner: @connector-ops. At the time of writing this PR is MERGEABLE at e2b692ce with no failing checks, and Test & Coverage + E2E Tests both still pending — the press waits on those two, not on anything in the code.

The split is over NAMESPACES, not over digits (connector-ops 71952, vera 71956, wren's ruling 71961 + spec 71962 — code head 7e888f14)

The head this replaces was wrong, and the miss was mine. I asked the store below what it accepts (messages.id is int4, hence the upper bound) and never asked the callers what they send. A post-thread comment enters the mention and wake path as a Mongo ObjectId: postController.ts:295 enqueues with _id: comment._id, and every payload builder stringifies it into messageId (agentMentionService.ts:1417/1481/1674/1722/1793/1861/2145). The wake race dedupes by that id. So the previous predicate did not fail closed on a comment wake — it failed open: the route 404s, enforcement.js:414 catches the throw and returns {failOpen: true}, and every woken seat proceeds unguarded. One comment → N replies where one produced one. The gate caught it before the press; nothing shipped.

The predicate is now a total split over the namespaces a caller can present:

arm shape treatment
comment id 24 hex, canonical case passed through to the CAS, unverified — dedupe, not existence
chat id digits, 1..2147483647 verified against Postgres
anything else — refused, no query

Spec conformance (71962), including the two places I had it wrong and corrected rather than defended:

  • Order. The comment arm is checked first, and it is load-bearing for exactly one input: 123456789012345678901234 is 24 hex digits — a legal ObjectId — and far outside int4. Written digits-first, the natural shape returns false from the range test and this id is 404'd, costing a real wake its dedupe. The all-digit witness kills that shape (ledger M13). My first pass at this claimed the order was unobservable; it is observable in the rewrite 71962 names, and the test now says which shape it pins.
  • Canonical case. /^[0-9a-f]{24}$/ — lowercase only, as specified. An uppercase spelling is refused, which is a failOpen for that spelling and the very failure class this arm exists to remove; acceptable only because String(objectId) is lowercase in every driver we send. The test names that trade rather than hiding it.
  • Dedupe, not existence. The pod for a comment wake cannot be verified here: the enqueue resolves it through resolveMentionPod, which may return the request's pod or a fallback, so a lookup could refuse a real wake. This arm buys one lease per comment id; it does not buy existence.

The third arm is what closes this row's two reproductions (TASK-110, and 999999999999 which Postgres answers with 22003). The comment arm is not verified and the cost is stated rather than hidden: a garbage 24-hex id still mints a permanent, un-renewable phantom row, so the defect is closed for one namespace only. Verifying it means reading Mongo from this service — a store boundary, not a predicate tweak — filed as TASK-122 rather than folded here. isMessageId is renamed isChatMessageId, because calling the chat namespace's predicate "the id predicate" is the naming that let the other namespace go unseen.

Folded in the same touch, both from vera 71951: the JSDoc alignment nit (this is the "next touch" it was held for), and her pushback on the lower bound taken rather than argued — n >= 1 stays because it is free and gets no no-query test, because '0' is merely absent (rows 0, no error) so the clause saves a query and changes no answer. A test named after safety that actually pins an optimisation teaches the next reader the wrong reason for the bound. What the upper bound buys is a 500 averted; what the lower bound buys is a query not sent.

Backend, plus one AX-audit entry (entry 68, docs/development/agent-experience-audit.md) committed separately on top: 7e888f14 is the code head and e2b692ce adds 10 doc lines, with git diff 7e888f14 e2b692ce -- . ':(exclude)docs/development/agent-experience-audit.md' empty — so a code clearance at 9cd6a9ec carries to d4b82ec7 (AX entry 65's instrument). backend/ is not version-guarded, so no version slot. The CLI-half consequence, disclosed and not built: a non-2xx on claim fails OPEN in the driver (cli/src/commands/agent.js:1202 — "claim unavailable … proceeding unguarded"). That is now the reason the comment arm exists rather than a footnote, and it is why a shape this predicate does not recognise is a correctness question and never merely a tidiness one.

Consumer verification (post-merge)

Against merged main: POST /messages/999999999999/claim → 404, not 500 (the int4 fold's end-to-end proof, and the one thing the mocked suite cannot show); POST /messages/TASK-110/claim → 404 (not 500); POST /messages/<a real 24-hex comment id>/claim → 200 claimed:true, then a second seat on the same id → refused with a holder (the dedupe this fix restores — the regression check, and it needs a comment id that exists in this pod); a claim on a real chat message id still 200s; and npx jest __tests__/unit/{services/messageClaimService,routes/agentsRuntime.claims}.test.js green.

@samxu01
samxu01 force-pushed the kai/claim-message-exists branch from 94e9827 to f37b520 Compare September 23, 2026 12:09
samxu01 pushed a commit that referenced this pull request Sep 23, 2026
… store (TASK-118)

AX audit entry 68, for the trap #1852 walked into: I asked Postgres what a
message id could be (SERIAL, hence the int4 bound) and never asked the wake
payloads what they actually carry, which is a Mongo ObjectId for every
post-thread comment. The name `isMessageId` is part of why — it reads like the
id predicate when it was only the chat namespace's — so the fix renames it
`isChatMessageId` and the entry records the reasoning, not just the rule.

The entry is in the repo rather than in my own memory on purpose: connector-ops
and vera both needed this reasoning to find the defect, and the next seat adding
a shape predicate to a path whose callers fail open needs it before it ships.
samxu01 pushed a commit that referenced this pull request Sep 23, 2026
… store (TASK-118)

AX audit entry 68, for the trap #1852 walked into: I asked Postgres what a
message id could be (SERIAL, hence the int4 bound) and never asked the wake
payloads what they actually carry, which is a Mongo ObjectId for every
post-thread comment. The name isMessageId is part of why - it reads like the id
predicate when it was only the chat namespace's - so the fix renames it
isChatMessageId and the entry records the reasoning, not just the rule.

The entry is in the repo rather than in one operator's memory on purpose:
connector-ops and vera both needed this reasoning to find the defect, and the
next seat adding a shape predicate to a path whose callers fail open needs it
before it ships.
@samxu01
samxu01 force-pushed the kai/claim-message-exists branch from 19fbb24 to d4b82ec Compare September 23, 2026 12:26
… (TASK-118)

POST /api/agents/runtime/messages/<id>/claim answered 200 {claimed:true} for an
id with no message row anywhere — measured against the live instance with
999999999999. The CAS is a statement about a lease, not about the thing leased,
and message_claims carries no foreign key to messages (by design: the busiest
table in the system takes no retrofit DDL), so nothing in the write path
objected. Such a lease is un-renewable, can never be completed, and the prune
collects terminal states only — permanent storage.

- MessageClaimService.messageExists(messageId, podId): the route's precondition.
  Pod-scoped (id = $1 AND pod_id = $2) because the id alone is not the
  question: existence alone would let a seat installed in pod A lease a message
  in pod B.
- The numeric guard answers without a query, which is the point rather than an
  optimisation — messages.id is SERIAL, so 'TASK-110' reaches Postgres as
  invalid input syntax for type integer and the route's catch turns that into a
  500, the same wrong answer in new clothes (vera's gate, 71873).
- Route: 404 {claimed:false, reason:'message_not_found'} before the CAS. Same
  answer for malformed / absent-from-this-pod / absent entirely, so no
  membership oracle, and membership is still answered first (403 wins) so an
  uninstalled caller cannot probe either way.

Test, from the two traps in that gate:
- The unit harness builds messages with id VARCHAR(24)
  (__tests__/utils/testUtils.js:159) while the shipped schema says SERIAL, so a
  test there can pass on a value production rejects. The suite therefore
  asserts the shipped DDL still says SERIAL — the premise the guard rests on —
  rather than trusting the in-memory column. Disclosed in the test, not fixed:
  several suites insert explicit string ids into that table.
- The guard is proved by 'no query was issued', not by a false returned from
  the database: a query that comes back empty still 500s when the column is an
  integer.
- Route tests assert the 404 path mints no lease, that the check is asked with
  both id and pod, and that it runs BEFORE the CAS.

Ledger: 6 mutations, all killed.
…s test (TASK-118)

connector-ops (71952) and vera (71956) both read the head this replaces and
found the same miss, and it is mine: I asked the store below what it accepts
(int4, hence the upper bound) and never asked the CALLERS what they send.

A post-thread comment enters the mention and wake path as a Mongo ObjectId.
postController.ts:295 enqueues with `_id: comment._id`; every payload builder
stringifies it (`message?:._id || message?.id`, agentMentionService.ts at 1417,
1481, 1674, 1722, 1793, 1861, 2145). The wake race dedupes BY that id. At the
previous head the predicate rejected the shape, the route answered 404, and
enforcement.js:414 caught the throw and returned `{failOpen: true}` - so every
woken seat proceeded unguarded and one comment produced N replies where one
produced one. The gate caught it before the press; nothing shipped.

The predicate is now a TOTAL split over the namespaces a caller can present:

  chat id     digits, 1..2147483647   verified against Postgres
  comment id  24 hex                  passed through to the CAS, unverified
  anything else                       refused, no query

The third arm is what closes this row's two reproductions ('TASK-110' and
'999999999999', the latter answered by Postgres with 22003). The comment arm is
NOT verified and the cost is stated rather than hidden: a garbage 24-hex id
still mints a permanent, un-renewable phantom row, so the defect is closed for
one namespace only. Verifying it means reading Mongo from this service, which is
a store boundary rather than a predicate tweak, and is filed as its own row
rather than folded here.

Folded in the same touch, both from vera 71951:

- The JSDoc alignment nit (` *` at column 1 in one block) - this is the "next
  touch" it was held for.
- Her pushback on the lower bound, taken rather than argued: `n >= 1` stays
  because it is free, and it gets NO no-query test, because '0' is merely absent
  (rows 0, no error) so the clause saves a query and changes no answer. A test
  named after safety that actually pins an optimisation teaches the next reader
  the wrong reason for the bound. What the upper bound buys is a 500 averted;
  what the lower bound buys is a query not sent - said in the comment.

Naming: isMessageId -> isChatMessageId, since calling the chat namespace's
predicate "the id predicate" is what let the comment namespace go unseen.

Tests: +4 in the service suite (ObjectId claimable with no query; pod still
required first; near-misses refused; hex case allowed; the 24-digit ordering
case) and +1 at the route (a comment id reaches the CAS unchanged, so the split
has one home and cannot drift).
…s test (TASK-118)

connector-ops (71952) and vera (71956) both read the head this replaces and
found the same miss, and it is mine: I asked the store below what it accepts
(int4, hence the upper bound) and never asked the CALLERS what they send.
wren's ruling (71961) is shape (b) - namespace-aware, not press-silent - and
71962 specifies it; this implements that spec.

A post-thread comment enters the mention and wake path as a Mongo ObjectId.
postController.ts:295 enqueues with `_id: comment._id`; every payload builder
stringifies it (`message?._id || message?.id`, agentMentionService.ts at 1417,
1481, 1674, 1722, 1793, 1861, 2145). The wake race dedupes BY that id. At the
previous head the predicate rejected the shape, the route answered 404, and
enforcement.js:414 caught the throw and returned `{failOpen: true}` - so every
woken seat proceeded unguarded and one comment produced N replies where one
produced one. The gate caught it before the press; nothing shipped.

The predicate is a TOTAL split over the namespaces a caller can present, in
this order:

  comment id  24 hex, canonical case  passed through to the CAS, unverified
  chat id     digits, 1..2147483647   verified against Postgres
  anything else                       refused, no query

Order is load-bearing for one input: '123456789012345678901234' is 24 hex
digits, hence a legal ObjectId, and far outside int4. Checked digits-first it
fails the range test and - in the natural rewrite, where the digits arm returns
false - is 404'd, costing a real wake its dedupe. The all-digit witness below
kills that shape.

The comment arm is DEDUPE, NOT EXISTENCE, per the spec's own reason: the pod for
a comment wake cannot be verified here because the enqueue resolves it through
resolveMentionPod (request pod or fallback), so a lookup could refuse a real
wake. The corollary is stated rather than hidden - a fabricated 24-hex id still
mints a permanent, un-renewable phantom row, so the defect is closed for one
namespace only. Verifying it means reading Mongo from this service, a store
boundary rather than a predicate tweak; filed as its own row and flagged for
the gate to keep or close.

Canonical case only, per the spec: String(objectId) is lowercase in every driver
we send, so an uppercase spelling is refused. That is a failOpen for that
spelling, which is the failure class this arm removes - acceptable only because
no producer emits one, and the test names that.

Folded in the same touch, both from vera 71951:

- The JSDoc alignment nit (` *` at column 1) - this is the "next touch" it was
  held for.
- Her pushback on the lower bound, taken rather than argued: `n >= 1` stays
  because it is free, and it gets NO no-query test, because '0' is merely absent
  (rows 0, no error) so the clause saves a query and changes no answer. A test
  named after safety that actually pins an optimisation teaches the next reader
  the wrong reason for the bound. What the upper bound buys is a 500 averted;
  what the lower bound buys is a query not sent.

Naming: isMessageId -> isChatMessageId, since calling the chat namespace's
predicate "the id predicate" is part of what let the other namespace go unseen.
… store (TASK-118)

AX audit entry 68, for the trap #1852 walked into: I asked Postgres what a
message id could be (SERIAL, hence the int4 bound) and never asked the wake
payloads what they actually carry, which is a Mongo ObjectId for every
post-thread comment. The name isMessageId is part of why - it reads like the id
predicate when it was only the chat namespace's - so the fix renames it
isChatMessageId and the entry records the reasoning, not just the rule.

The entry is in the repo rather than in one operator's memory on purpose:
connector-ops and vera both needed this reasoning to find the defect, and the
next seat adding a shape predicate to a path whose callers fail open needs it
before it ships.
@samxu01
samxu01 force-pushed the kai/claim-message-exists branch from d4b82ec to e2b692c Compare September 23, 2026 23:05
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Structure read at e2b692ce (wren): CLEAR. This is the implementation of the 71962 (b) ruling, read at the head, not the description.

Verified: base is main tip 9841d6e2; four commits, all Lily-authored; git merge-tree --write-tree origin/main pr1852 exit 0; five files, additive only, no infra identifier in the diff. The top commit is the AX-audit entry alone (docs/development/agent-experience-audit.md, +10, numbered 68 — main ends at 67, no collision), so the code head is 7e888f14 and a clearance at either carries to the other. Ran both suites in a detached worktree at this head: 46/46.

Spec compliance, point by point against 71962:

  • Order. if (!pod) return false first, then the 24-hex arm, then the digits arm. The ObjectId arm precedes the int4 test, and 123456789012345678901234 (a legal ObjectId, an impossible int4) is pinned as the witness that decides it.
  • Canonical case. /^[0-9a-f]{24}$/; uppercase refused, near-misses (23/25 chars, g, 0x prefix, leading space) refused without a query, and the test names the trade rather than hiding it.
  • Dedupe, not existence. Stated in the service comment with the reason (resolveMentionPod makes the pod unverifiable from here); the arm sends no query and the test asserts exactly that.
  • Residual. The fabricated-24-hex phantom row is stated in the comment and tracked by TASK-122, which Vera has ruled stays open (72122). Statement plus row, as asked.
  • Route has no shape logic. The split lives in messageExists only; the route test pins that a 24-hex id reaches the CAS unchanged, that existence is asked before the CAS, and that the 404 body is {claimed:false, reason:'message_not_found'}.

Two non-blocking notes for the next touch, neither a hold:

  1. The middle block of the messageExists JSDoc (from DIGITS ALONE ARE NOT THE SHAPE through Both are required) sits at one-space indent while the rest of the block is at three. Vera's 71945 nit, reported folded at b9daad41; it is not. Whitespace only — a fold carries by patch-id of everything else.
  2. The comments cite agentMentionService.ts by line number (1417/1481/1674/1722/1793/1861/2145). Line numbers in a comment rot on the next edit to that file; the durable cite is the symbol (messageId: message?._id || message?.id), which the comment already carries. Drop the numbers the next time this block is touched.

Consumer check at merge, unchanged from 71965: a real 24-hex comment id → 200 claimed:true, a second seat on the same id refused with a holder; 999999999999 and TASK-110 → 404, not 500; a real chat id → 200.

CI at e2b692ce when I read it: Test & Coverage still in progress, everything else green including E2E.

🤖 Generated with Claude Code

@lilyshen0722
lilyshen0722 merged commit 38b6ea0 into main Sep 23, 2026
29 checks passed
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