Skip to content

feat(attention): a created-since window on the decision queue — whole-set counts, windowCount, nextSince (TASK-177) - #1987

Merged
lilyshen0722 merged 6 commits into
mainfrom
kai/task177-queue-since
Sep 28, 2026
Merged

lilyshen0722 merged 6 commits into
mainfrom
kai/task177-queue-since

Conversation

@lilyshen0722

@lilyshen0722 lilyshen0722 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

What this is

GET /api/activity/decision-queue gains since: a window on the open queue — work created at or after an instant. It is what makes an operator watcher tick one request instead of paging the whole queue.

The shape follows the row's amended spec (connector-ops, after Wren's probe): since on createdAt, inclusive, on the existing index with no new index; the counts do not narrow; a bounded call adds windowCount and nextSince; pagination happens inside the window. My first cut narrowed count/countsByKind/countsByPod/remaining with the bound, which is what the ruling rejects — an Activity badge, or any caller passing no bound, must read exactly what it read before.

The cost it removes, measured

An operator watcher asking "what is new since my last tick" had to page the whole queue — 550 open items is 11 requests, every tick. /api/activity is limited to 60 requests a minute keyed on the client IP (backend/routes/activity.ts:43-53, router.use on the whole router), so those 11 requests share one bucket with every other session on the host and with the person's own Activity page. Tripped live on 2026-09-28 while reading a real operator queue (TASK-176).

A client cannot work around it by reading pages: the queue is ordered priority-then-createdAt desc, so a page that looks entirely older than the cursor can still be followed by rows the cursor should see — an old mention sorts into a later priority bucket than a fresh approval.

Why createdAt and not updatedAt

Vera argued for updatedSince on the grounds that a late insert carries a fresh updatedAt; Wren measured that no writer in this codebase produces that shape. Every row comes from one $setOnInsert upsert through recordForRecipients, mongoose stamps createdAt and updatedAt from a single now, and the source's own time lives in a separate field, sourceCreatedAt. No column choice closes the gap; a caller-side lookback does. Vera then conceded with the same mechanism.

createdAt being insert-now is the positive argument for this bound and for the index that already exists: {recipientUserId: 1, status: 1, createdAt: -1} orders rows by when they were STAMPED, which is what the existing find().sort({ createdAt: -1 }) rides. The bound does not touch that index — the whole-set counts above require the whole open set, so the window is applied in memory after the read. It cuts the response and the round trips (the watcher tick that motivated it: eleven requests to one), not the database work.

Inclusive, pinned, with the residual stated rather than implied

createdAt >= since, and the route comment says so. A caller's cursor is a bare timestamp, and one sitting at millisecond T cannot know about a row INSERTED at T after it was written — an exclusive bound drops that row from that read and from every later read. Re-delivering a row the caller already has is recoverable; never delivering it is not, and callers dedupe on attentionItemId.

The residual is bounded, not closed, and it is not backdating alone: stamp order is not commit order. A row stamped before a cursor can become visible after it (its write had not committed when the caller read), and a writer whose clock lags stamps a new row behind a cursor the caller already passed — the bound misses both. Only a caller-side lookback W closes them, and W must exceed write-commit latency plus writer clock offset. An earlier revision of the comment under test said "not skew"; a probe falsified it (a stamped-before/committed-after row was missed, and a lagging-clock row was caught only with W). The client half therefore resumes from nextSince - W and dedupes on attentionItemId.

Response shape

count, countsByPod, countsByKind, composePodId   whole open set, unchanged
windowCount                                      rows in the window
nextSince                                        newest createdAt DELIVERED (ISO), null when nothing
items, offset, limit, remaining, hasMore         page INSIDE the window

windowCount and nextSince are present for every caller (windowCount === count with no bound), so a consumer can read them unconditionally rather than branching on whether it passed a parameter.

nextSince is the max over the page, not over the window: a caller resumes from it, and a value it has not seen must not be skipped past.

One place the ruling is self-contradictory, resolved in the direction that terminates: its §3 lists remaining among the whole-set numbers and also says pagination applies within the window. Both cannot hold — rows outside the window are never delivered, so a whole-set remaining could never be worked off and hasMore would stay true forever. I took window-relative remaining/hasMore; whole-set count/countsByKind/countsByPod/composePodId are untouched. Flagged on the row for the spec owner rather than settled silently.

What counts as an acceptable bound — the message says ISO-8601, so it has to be

400 {"error":"since must be an ISO-8601 timestamp"} — refused rather than dropped, because a caller that asked to narrow and silently received the whole queue cannot tell. Three separate checks, because they catch three different callers:

  • Type — a repeated query parameter arrives as an array, and Date.parse(String([one])) parses fine. ?since=<a>&since=<b> comma-joins into something unparseable and 400s even without this check; the single-element ?since[]=<iso> form is the one that discriminates, and it is the arm.
  • Shape — Date.parse is not an ISO-8601 parser. 'Sep 28 2026' and '2026' are accepted, and a zone-less date-time is read in the SERVER's local zone: '2026-09-28T04:00:00' is 11:00Z on this host and 04:00Z on a UTC one, against a UTC-stored createdAt. The same request would mean a different instant per host, and a bound that moves silently hides rows. ^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2}))?$ requires a zone whenever a time is present; date-only stays accepted because ISO reads it as UTC. Refusing a zone-less timestamp is the same trade the cursor already makes: a refusal is visible, a shifted bound is not.
  • Value — in shape but impossible ('2026-13-45T00:00:00Z') is caught by the parse itself.

Service (second line, reachable — it is exported and called directly): an unusable bound narrows nothing rather than raising or emptying the queue. Of the ways to be wrong, a superset is the one that cannot hide a row; a malformed podId is treated the same way beside it.

Not in this PR: the client half

The ruling's §2 is a CLI change — request from nextSince - W (default 60 s, flag) and drop attentionItemIds already delivered inside W, with the dedupe set bounded by W rather than growing. It needs nextSince to exist, so it lands after this, in its own PR: #1985 is under gate and its head must not move for an unrelated feature.

Evidence

Tests (+4 arms; the file is 6). The page narrows while every count stays whole-set; an empty window still reports the total count and the whole-set countsByKind; pagination reaches remaining: 0 inside the window while count stays 4; nextSince is asserted with a one-row page, where window-max and delivered-max differ; a second row on the boundary instant — ticked from the nextSince the first tick returned — must come back, which is the arm an exclusive bound dies on; and a lookback containing a near row and excluding a far one, with a control behind it so the arm cannot pass on a query that ignores the bound. Route tier: the millisecond of the instant is forwarded, and unreadable values are refused without calling the service — 'not-a-date', '', '2026-13-45T00:00:00Z', 'Sep 28 2026', a zone-less date-time, a two-element repeat and the single-element ?since[]= form. Beside them is the control the refusal arm needs to not be over-strict: date-only ISO and a +02:00 offset are both accepted and forwarded, so a regex that refused legitimate forms would fail.

Rows are placed in time with explicit createdAt values. Nothing asserts that a backdated row survives a bound — per the ruling's caution that no writer produces that shape; the gap W bounds is stamp-to-commit, and it is the caller's window.

Mutation ledger: 18 mutations, NO SURVIVORS (/tmp/kai-177-ledger.py). Every mutation prints applied (a needle that stops matching otherwise reads as a survivor), moved, killed, the failing-test count, and named_arm_hit as a substring match against jest's fullName; a (2, 20) baseline is asserted before and after, and the mutated files are verified clean at the end. Killed: the window not applied at all; >= → >; the Date branch of the parse dropped; the readability check dropped; an unreadable bound emptying the queue; the window applied to the page instead of before the slice; count reporting the window; windowCount reporting the whole set; nextSince taken from the window; nextSince taken from the whole set; remaining counting the whole set; the route accepting an unreadable bound; the route reading since without forwarding it; the forwarded instant truncated to the second.

The route mutations are split because the guard is three checks: dropping the type check (Vera's survivor at ccca3e93 — a single-element array passed it), dropping the shape check, and making the zone optional in the shape check each die on the same named arm. A "countsByKind computed from the window" mutation is deliberately absent: the window is declared below that line, so replacing scoped with window throws before it asserts anything, and a mutation whose kill is a TDZ throw witnesses the throw rather than the count. count/windowCount carry that claim cleanly.

Neighbours: 8 suites / 92 tests / 0 failed (attentionQueue.counts, attentionQueue.since, attentionItemService, activityService.attentionQueue, activityService.recap, activity.read, activity.identity, activity.write-membership).

Full backend suite: 485 suites / 4528 tests / 4504 passed / 24 skipped / 0 failed. The uploads.signedurl failure seen in one earlier full run did not reproduce here — it passes 12/12 in isolation twice and no file in this diff is on the uploads path, so it is a flaky test-isolation case in that suite, now seen once failing and once passing across two full runs.

Static: npm run tsc:check clean. Lint multiset: activity.ts 10/10 unchanged, activity.read.test.js 8/8 unchanged, attentionItemService.ts 15 → 14 (one long line removed, none added); the new test file reports only the 6 import/no-unresolved/import/extensions findings that every .js test in backend/__tests__/ reports, and that directory is outside CI's lint:ts.

Files

  • backend/services/attentionItemService.ts — OpenQueueOptions.since, the parse, the window, windowCount/nextSince.
  • backend/routes/activity.ts — since validation and forwarding on /decision-queue only, plus the inclusivity/residual comment.
  • backend/__tests__/service/attentionQueue.since.test.js (new), backend/__tests__/service/attentionQueue.counts.test.js (the invalid-recipient shape assertion gains the two new fields), backend/__tests__/unit/routes/activity.read.test.js.

… (TASK-177)

An operator watcher asking "what is new since my last tick" had to page the whole
queue: `GET /api/activity/decision-queue` offered `podId`/`messageIds`/`limit`/
`offset` and nothing about time, so 550 open items was eleven requests per tick.
That is not a private cost — `/api/activity` is limited to 60 requests a minute
keyed on the client IP, shared with every other session on the host and with the
person's own Activity page, so a watcher tick spent somebody else's budget every
time. Measured live on 2026-09-28 by tripping the 429 while reading a real
operator queue (TASK-176).

A client cannot solve this by looking at page contents: the queue is ordered
priority-then-`createdAt` desc, so a page that appears entirely older than the
cursor can still be followed by rows the cursor should see — an old mention sorts
into a later priority bucket than a fresh approval. The narrowing has to be
server-side.

`since` is INCLUSIVE of its own millisecond (`createdAt >= since`), which is a
deliberate departure from the "exclusive on createdAt" shape the follow-up task
described, and the CLI's own cursor is the reason: a cursor written at T cannot
know about a row INSERTED at T after it was written, so an exclusive bound would
drop that row from every later read — silently and for good. This is the exact
failure TASK-176's cursor had to fix one layer up (Vera's HOLD on #1985:
`ms > sinceMs` lost the boundary row permanently). A caller re-printing a row it
already has is recoverable; never seeing it is not, so the bound rounds toward
visibility and the client's cursor id-set does the dedup.

The bound is applied to the QUERY — before supersession, membership, the counts
and pagination all run — so `count`, `countsByKind`, `countsByPod`, `remaining`
and `hasMore` describe the narrowed view. A narrowed list reporting a count that
contradicts its rows is worse than a slow query, and the pod scope already
follows exactly this rule for exactly this reason. The query also rides the
existing `{recipientUserId, status, createdAt}` index.

An unreadable value: the route refuses it with a 400 rather than reading the
whole queue, because a caller that asked to narrow and silently received
everything cannot tell that its bound was ignored. The service, as the second
line, treats an unusable bound as narrowing nothing — that direction can only
return a superset, never hide a row, which is how a malformed `podId` is already
treated beside it.

Not included, deliberately: `updatedSince`. Rows leave this queue when resolved,
so a modified-since bound would report work that is no longer waiting on anyone
while the created-since bound is what a watcher's cursor actually needs. No
consumer exists, and an unused parameter is a shape to maintain for nothing.

Tests (+5): the boundary row is kept and only older rows drop, with a control one
millisecond past it; every count is asserted for the narrowed view, including
`remaining`/`hasMore` where a filter applied after the slice would differ; a bound
is accepted as a `Date` or a string, and an unusable one narrows nothing rather
than emptying the queue; the route forwards the millisecond of the instant, and
refuses values it cannot read (including a repeated parameter, which arrives as
an array and parses fine as a string). Ledger 9 mutations, no survivors.
… whole-set counts, windowCount, nextSince (TASK-177)

The row's spec was amended while this PR was open (connector-ops 177, after Wren's
probe): `since` on `createdAt`, INCLUSIVE, on the EXISTING index with no new index,
and the counts do NOT narrow — a filtered call adds `windowCount` (rows in the
window) and `nextSince` (the newest instant delivered), with pagination inside the
window. My first cut narrowed `count`/`countsByKind`/`countsByPod`/`remaining` with
the bound, which is the shape the ruling rejects: an Activity badge or any caller
that passes no bound must read exactly what it read before.

Why the spec moved, and what it settles. Vera argued for `updatedSince` on the
grounds that a late insert carries a fresh `updatedAt`; Wren measured that no writer
in this codebase produces that shape — every row comes from one `$setOnInsert`
upsert through `recordForRecipients`, mongoose stamps `createdAt` and `updatedAt`
from one `now`, and the source's own time lives in a separate `sourceCreatedAt`. So
no column choice closes the gap; a lookback window does, and it needs only the
`createdAt` index that already exists. Vera then conceded with the same mechanism.

What changed:
- The query reads the whole open set again (it has to: the counts are whole-set) and
  the window is applied in JS after the counts and before the slice.
- `windowCount` and `nextSince` are on the response for EVERY caller, not only a
  bounded one, so a consumer can read them unconditionally; `windowCount === count`
  when no bound is given. `nextSince` is the max `createdAt` over the page that was
  DELIVERED, not over the window — a caller resumes from it, and a value it has not
  seen must not be skipped past.
- `offset`/`limit`/`remaining`/`hasMore` page INSIDE the window. The ruling lists
  `remaining` among the whole-set numbers and also says pagination applies within the
  window; those cannot both hold, since rows outside the window are never delivered
  and a whole-set `remaining` could never be worked off. I took the reading that
  terminates and flagged it on the row rather than guessing silently.
- The route comment pins the inclusivity and states the residual honestly: an
  arrival more than W behind a cursor already passed is missed, so W must exceed
  write-commit latency, not clock skew. Not backdating, and not closed.

Tests are rewritten for the shape (+3 arms, 6 total in the file): the page narrows
while every count stays whole-set; an EMPTY window still reports the total count and
`countsByKind`; pagination reaches `remaining: 0` inside the window while `count`
stays 4; `nextSince` is asserted with a ONE-row page, where window-max and delivered-
max differ; a second row on the boundary instant, ticked from the `nextSince` the
first tick returned, must come back (this is the arm an exclusive bound dies on); and
a lookback that includes a near row and excludes a far one, with a control behind it.
Rows are placed in time with explicit `createdAt`; nothing asserts that a BACKDATED
row survives a bound, per the ruling's caution that no writer produces that shape.
@lilyshen0722 lilyshen0722 changed the title feat(attention): narrow the decision queue to a created-since instant (TASK-177) feat(attention): a created-since window on the decision queue — whole-set counts, windowCount, nextSince (TASK-177) Sep 28, 2026
@lilyshen0722
lilyshen0722 added this pull request to the merge queue Sep 28, 2026
Merged via the queue into main with commit e304c4c Sep 28, 2026
18 of 19 checks passed
lilyshen0722 added a commit to thantiklermcirony/commonly that referenced this pull request Oct 9, 2026
… (TASK-177) (Team-Commonly#1990)

* feat(cli): the inbox watcher tick reads a window, not the whole queue (TASK-177)

The route grew a created-since bound in Team-Commonly#1987; the CLI did not use it, so the
one-request tick that motivated the parameter did not exist at the consumer.
`commonly inbox list` with a cursor now asks for `createdAt >= cursor - W`
(`--window`, default 60s) and drops the ids already delivered inside W.

W is not a guess about clock skew: a row is stamped from the writer's clock when
the write happens and becomes visible only when it commits, so resuming exactly
at the cursor would never show such a row on any tick. The window re-reads that
stretch, and the delivered ids make it quiet.

Three things this required that the spec did not name:

- The cursor stamp is a HIGH-WATER MARK. A row printed from inside the window is
  older than the mark that delimited that window; letting it pull the mark back
  moved the next read's `since` back with it and moved the prune cutoff.
- The id set is the WHOLE window, not just the newest delivered row, or a tick
  re-prints every older row inside the window on the next pass.
- The previous cursor's ids are CARRIED, not recomputed from this read's items:
  `items` is post-dedupe, so a row delivered last tick is absent from it, and
  rebuilding the set from it alone alternates the dedupe every tick.

`--window 0` restores the exact-cursor behaviour. The mark is taken from what
the read PRINTED rather than the response's `nextSince`, because `--kind` is
filtered on this side and the server's window may hold kinds this read never
prints.

Tests 58 (was 52 in this file), 1030 across the cli suite; ledger 52 mutations
ported from TASK-176 plus the window arms, all applied, no survivors.

* fix(cli): page a wide inbox window to the end, and keep the mark self-consistent (TASK-177)

Two review findings, both about W being a number somebody chose.

Wren (75183): the route pages priority-then-newest, 50 at a time, so a window
taken from an old cursor can run to several pages and its OLDEST rows sit on the
last one. The loop already stopped on `hasMore`, but nothing witnessed it — a
tick that stopped after page one would print the newest 50, write a mark from
them, and move `since` past the page-two rows, which no later tick could then
see. The new arm builds that window (cursor ten minutes old, 50 rows inside the
first page, 5 older ones on the second) against a page that answers for the
window it was ASKED for, so the second tick is served the way the real route
would serve it; it asserts both pages print, two requests happen, and the mark
is the newest row across both.

Vera (75177): the window needs a row INSIDE it returned and a row BEHIND it
absent in the same read — otherwise the arms pass on a lookback that fetches
everything. That pair is now one arm, and it asserts the `since` the server is
asked for as well as the output. The id-set reset she asked about was already
armed twice over (never-carry, never-prune); the never-prune-inside-the-window
mutation has been re-attributed to the arm that actually kills it, because the
one it named only ever selected the row that IS the mark.

And one defect neither of them could see from the fixture: `nextCursorFrom`
returned `at` as the high-water mark but `ms` as the newest row printed, so the
in-process object disagreed with the cursor its own file re-reads as. `ms` is
now the mark, with an arm asserting the round trip.

Also: the README's 60s paragraph now says what 60s is (a two-to-three-order
margin over a write round trip and pod-clock offset, deliberately not a
measurement) instead of asserting it is "ample"; and it documents the paging.

Tests 61 in this file (was 58), 1033 across the cli suite; ledger 56 mutations,
no survivors and no named-arm misses; cli/src lint clean.

* docs(cli): the inbox README contradicted itself about how many requests a tick costs (TASK-177)

Vera's 75189 correction about the chat line turned out to have a sibling in the
file this PR edits: the paragraph I added says a wide window pages, and the
paragraph four lines below it said "With a cursor, the window bounds a tick to
one" — the same claim, stated as a fact about request count, in a command whose
whole point is how many requests a tick costs. A wide window is one request per
50 rows of it; the ordinary watcher tick, with a cursor seconds old, is one.

Also made the residual paragraph's "60s is ample for in-cluster writers" defer
to the margin argument instead of asserting amplitude bare, so the number is
justified once rather than twice.

Prose only: no source line changes, so the ledger and suite results are the ones
already recorded at `000fdbbd` and were re-run against this head anyway
(52 suites / 1033 tests / 0 failed; 56 mutations, no survivors, no named-arm
misses).
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