Skip to content

fix(dash): keep one tenant's rows out of another's session figures, archives and seeds (#501 #1069 #1070 #1071) - #1064

Merged
amiddavid merged 5 commits into
mainfrom
repro/501-tenant-session
Nov 11, 2026
Merged

amiddavid merged 5 commits into
mainfrom
repro/501-tenant-session

Conversation

@boazdavid

@boazdavid boazdavid commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #501, #1069, #1070, #1071.

Behavior changes (need the owner's confirmation):

  1. The cache-split stable half is now each tenant's own measurement. A tenant with no measurement of its own gets no historical credit for a model; before, it borrowed another tenant's. A tenant whose own spread is constant is now credited even when another tenant's spread differs; before, it lost the credit.
  2. The archived_sessions index is rebuilt on open with PRIMARY KEY (tenant_id, session_id) (was session_id). The rebuild runs in one transaction, is idempotent, and keeps every row. No schemaVersion bump.
  3. Exported functions change: Recorder.FetchArchived and FetchArchivedContent take the tenant. New DB.ArchivedSessionOf. ArchivedSessionByID stays, for a manager's view, and returns the most recently archived row when two tenants share the id.
  4. KeepAliveSessions breaks cost ties by tenant and session. Ties were arbitrary before. The ka_sessions golden file is regenerated: eight sessions tie at the LIMIT 20 edge, so four rows of one tenant leave the list and four of another enter. Every other field is unchanged.
  5. Rollback: schemaVersion stays 6, so an older binary opens a migrated database, but its archive write (ON CONFLICT(session_id)) then fails until the file is rebuilt. Reads still work. This follows the tool_uses rebuild precedent; a line in the release notes is enough.

Data dependence: none. All changes are SQL over metadata columns already stored.

How reachable this is

On the hosted path the stored id is tenant:base (session.Scoped, dash/event.go:778), and tenant ids are hex. So two tenants cannot normally share a session_id. These are defense-in-depth fixes for rows written another way (tests, direct inserts, an import). The wording in the earlier code comments and in #1069-#1071, "session ids are client-supplied, so two tenants can present the same one", described the raw header, not the stored id. It is corrected here.

Problem

Per-session queries keyed rows by session_id alone. If two tenants share an id, tenant B's rows change tenant A's figures. Reproduced on main: ReplayProjectedTokens 30 -> 330 and CompactionResets 1 -> 0.

Changes

Not covered

go test ./dash, go build ./... and go vet ./... pass.

Assisted-By: Claude Sonnet 5.5 [email protected]

#501)

The per-session window queries and correlated counts partitioned by
session_id alone. Session ids are client-supplied, so two tenants can
share one, and tenant B's rows then changed tenant A's
ReplayProjectedTokens (30 -> 330 in the new test) and CompactionResets
(1 -> 0).

Changes:
- Partition by (tenant_id, session_id) in the replay ceiling, the
  inflation correction, the compaction-reset LAG and both cache-split
  ranking CTEs.
- Add p.tenant_id = r.tenant_id to the correlated counts, including
  splitMoved and afterOurMutation.
- Scope session CTEs with sessionScope(f), shared with the cache-split
  query that #502 already scoped.
- CachesplitSizeSpread is now per tenant and model, so one tenant's
  recorded stable size cannot decide whether another tenant's credit
  applies (the second comment on #501).
- Add idx_requests_session_tenant(session_id, tenant_id, ts) so the
  correlated counts stay index-only.

Behavior change: a tenant with no cachesplit rows of its own gets no
historical cache-split credit for a model; it used to borrow another
tenant's measurement. TestHistoricalSplitValuationByTenantMatchesPerTenant
now gives t-y its own measurement.

Tests: dash/tenant_session_isolation_test.go builds one database with
only tenant A and one with A plus B under the same session id, and
checks A reads the same figures from both. All four fail on main. Full
./dash suite passes.

Assisted-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 2 of 2 1 of 2 f0c407401866 blocking

Verdict: blocking

Findings

  1. dash/schema.go:351 — the new index never reaches an existing database
    • What fails: a deployment already stamped schema_version = 6 never gets idx_requests_session_tenant. migrate() skips ddl for a database at the current version (dash/schema.go:1119-1133: the default branch runs only additiveDDL2 and backfillDeferCost), and schemaVersion stays 6. So every existing deployment — the multi-tenant ones this fix targets — keeps the old indexes. There, the per-session correlated counts in replayCeilingQuery (dash/overview.go:1185-1188) do a row fetch per candidate, the exact cost the new schema comment says the index avoids. Fresh databases do get the index, so the test suite (all tests open fresh databases) cannot catch this. It also leaves version 6 naming two different physical schemas, the failure mode the additiveColumns comment warns about (dash/schema.go:826-833).
    • Proof: grep -n idx_requests_session_tenant dash/schema.go shows the only definition at line 351, inside ddl (const starts at dash/schema.go:49). additiveDDL2 starts at dash/schema.go:731 and holds every other index added to requests for existing databases: idx_requests_project (751), idx_requests_session_alias (758), idx_requests_session_tb (791), idx_requests_keepalive_strategy (799) — each placed there precisely because ddl is skipped on an already-stamped file. The index names only original columns (session_id, tenant_id, ts), so the repo's stated reason for other orderings (a column addColumns adds) does not apply here.
    • Fix: add the same CREATE INDEX IF NOT EXISTS idx_requests_session_tenant ON requests(session_id, tenant_id, ts); to additiveDDL2. Do not bump schemaVersion — that path discards request history.

Non-blocking

  • Stale comments that now contradict the code. (a) dash/overview.go:747-748 says "Neither statement is scoped to the window or the tenant on its INNER side … session ids are tenant:uuid so a cross-tenant collision is not reachable". This PR adds the tenant term to both inner sides, and sessionScope's own comment (dash/overview.go:1474-1480) says collisions are reachable. (b) dash/cachehistory.go:173 says "overview.go's and this file's other per-session queries still have it … not a general pass over #501". This PR is that pass for overview.go. Update both so a future reader does not rely on a false safety claim.
  • Index overlap. idx_requests_session_tenant (session_id, tenant_id, ts) duplicates what idx_requests_tenant_session (tenant_id, session_id, ts) at dash/schema.go:381 already covers for tenant_id = ? AND session_id = ? AND ts predicates, and it subsumes idx_requests_session (session_id, ts) at dash/schema.go:349. Three overlapping indexes on the hottest table add write cost per insert. If a measurement says the session-leading order wins for the correlated counts, say so in the comment and consider dropping idx_requests_session.
  • priced[tenant+"|"+model] (dash/cachehistory.go:135, 254, 262) is a string-concat key. A tenant id and a model name that both contain | can collide across pairs. A struct key {tenant, model} cannot.
  • Same-class isolation gaps this PR does not cover, for the team to triage against #501's scope: KeepAliveSessions groups by session_id alone under TenantAll and picks MIN(tenant_id) as the owner (dash/keepalive.go:959-961), so a shared session id still merges two tenants' expiries in the manager's view. The recorder's seed paths carry no tenant either: seedOneHourTiers partitions by session_id, thread_id, model (dash/capture.go:902-904) and SeedGraceSessions groups by session_id, thread_id (dash/capture.go:955-959), and thread.Key has no tenant (internal/thread/thread.go:49-55). These are live-path, not dash figures, so they may be a separate issue.
  • CLAUDE.md's behavior-change rule applies: per-tenant valuation can only add credit (a model one tenant measured constant is now credited even when another tenant's spread differs). The PR title names the change; make sure the human's yes is recorded before merge, per RELEASING.md.

What I checked

  • The full diff 9d34f00f..HEAD, every hunk read against its surrounding code.
  • Every window and correlated subquery this PR touches, traced for the three caller shapes: tenant-scoped, tenant-scoped plus session, TenantAll plus session. In each, the partition is (tenant_id, session_id) or the inner predicate names p.tenant_id = r.tenant_id, so a shared session id cannot mix tenants. sessionScope's TenantAll branch is safe for the same reason; I checked each window it feeds.
  • SQL placeholder order against argument order at all three sessionScope call sites (dash/cachehistory.go:179-190, dash/overview.go:895-908, dash/overview.go:1213-1222). The CTE's own placeholders come before cond's in the SQL text, and the code appends the scope args first. Correct.
  • The inflation before CTE with default scope: a ping of tenant B in a shared session now sums 0 instead of tenant A's rows. Fixed by the partition change; pre-fix it inflated the correction.
  • The new tests in dash/tenant_session_isolation_test.go: I derived each expected number by hand (30 = 10 x (2+1+0); 1 reset; rn = 1 per tenant; per-tenant spread). Each test fails on the pre-fix SQL and passes on the new SQL. The helpers (mkEvent, openTestDB, insertBatch, staticPricer, ibmSonnet, Event.Price) exist with matching signatures, and insertBatch writes tenant_id from Event.TenantID.
  • CachesplitSizeSpread callers: only dash/cachehistory.go:75 and :205 in non-test code, both updated; no caller outside dash, so the signature change is contained.
  • The schema and migration path for the new index (finding 1).
  • Existing tests that pin the changed queries (overview_session_scope_test.go, overview_lean_test.go, cachecost_test.go) still match the new SQL shapes.
  • I did not run builds or tests. Live tests are not approved and Go is not installed on this machine.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session fresh 1 of 2 1 of 2 f0c407401866 blocking

Verdict: blocking

Findings

  1. dash/overview.go:895 — the changed inflation correction (before CTE) has no test

    • What fails: this PR changes that CTE's behavior (partition by (tenant_id, session_id), the pair IN subquery, sessionScope), but no test covers it. The change is not internal-only. At base, with tenants A and B sharing a session id and cond scoped to A, every ping row joined with no tenant term (FROM requests p ... WHERE p.keepalive = 1), and the window partitioned by session_id alone. So B's ping carried the running sum of A's qualifying rows, and A's inflation figure counted A's savings once per B's ping. The head fixes that. A regression in this CTE would silently change ReplayProjectedTokens (raw minus inflation, overview.go:1103-1105), and no test would fail.
    • Proof: base SQL at 9d34f00, overview.go: PARTITION BY r.session_id and the ping join with no tenant term. The new test file dash/tenant_session_isolation_test.go covers the replay ceiling, compaction resets, the historical cache-split and the size spread — not this CTE. The PR body itself lists it under "Not covered".
    • Fix: add a fifth case to dash/tenant_session_isolation_test.go. Tenant A: rows with saved_unique > 0 plus one A ping. Tenant B: rows plus a B ping under the same session id. Assert A's ReplayProjectedTokens is the same from the alone and the mixed database.
  2. dash/schema.go:351 — the new index sits in ddl, so existing databases never get it

    • What fails: a database already at schema version 6 skips ddl on open (dash/schema.go:1121-1130 runs only additiveDDL2), and this PR does not bump schemaVersion. So the index is created on fresh databases only. The comment at dash/schema.go:350 claims the per-session correlated counts "stay index-only" thanks to it. On every existing deployment that claim holds only because idx_requests_tenant_session (schema.go:381) already covers the same count (tenant_id, session_id, ts plus the rowid). The new index does not exist where the data is.
    • Proof: migrate's default branch returns before db.Exec(ddl) when have == schemaVersion; schemaVersion stays 6 in this diff. The repo's own convention places indexes that must reach existing databases in additiveDDL2 (idx_requests_session_tb, idx_requests_keepalive_strategy, schema.go:786-800), and additiveDDL's comment (schema.go:475-485) documents exactly this trap.
    • Fix: move the CREATE INDEX into additiveDDL2, or drop it and rely on idx_requests_tenant_session. Note the index is also redundant for every query that binds both columns by equality: both permutations cover the count, so keeping both adds write cost per insert for no read gain.

Non-blocking

  • dash/cachehistory.go:170-176 — the comment says overview.go's and this file's other per-session queries "still have" #501's bug. This PR fixes them, so the claim is now false. Lines 105-107 ("Restricting to r.session_id = ?", "PARTITION BY session_id") are stale the same way. Update the wording so the next fix is not sent hunting for a bug that is gone.
  • dash/cachehistory.go:135 and 254 — the priced key tenant+"|"+model can collide in the by-tenant pass if a tenant id or a model name contains | (tenant "a" with model "b|c" against tenant "a|b" with model "c"). The second group then reuses the first's value. A tenant-scoped call cannot collide, because all its rows share one tenant. Nested maps, like seen already is, would be exact.
  • Same-family spots left open, for a follow-up issue rather than this PR: the Sessions tab groups by session_id alone under TenantAll (dash/query.go:724-746); the recorder's thread keys carry no tenant (internal/thread/thread.go:49, dash/capture.go:800-806 and 902-907); archive and janitor delete by session_id only (dash/archive.go:297, 345; dash/janitor.go:382; dash/store.go:1032) — archiving a shared session id for one tenant deletes the other tenant's rows. That last one is data loss of the same class #501 reports.

What I checked

  • The full diff 9d34f00..HEAD, one commit, and the code around every changed hunk.
  • Placeholder order in the three rebuilt queries (cachesplitHistoricalQuery, compactionResetsQuery, the before CTE): the args arrays match the placeholder order in the SQL text in all three.
  • The four new tests' arithmetic by hand: replay 30 = 10 x (2+1+0); at base the shared session gives 330 and 0 resets, which matches the PR's repro numbers. The added t-y teach row in TestHistoricalSplitValuationByTenantMatchesPerTenant is required by the per-tenant spread and keeps the Requests = 1 assertion valid.
  • Equivalence of the pair IN forms to the old session_id IN forms for sessions not shared across tenants: a row's window values never depend on which other partitions the CTE includes.
  • TenantAll paths: sessionScope keeps the bare session term there, and every window now partitions by (tenant_id, session_id), so the two tenants' rows stay apart; the manager's view sums both, which matches the declared semantics.
  • The schema path: migrate skips ddl on an existing version-6 database; additiveDDL2 runs on both paths. This is the basis of finding 2.
  • The lean path (OverviewLean) and the EXPLAIN tests still build their statements through the same functions the server calls.
  • The PR body: it names the behavior change at the top, states "Data dependence: none", and the changes are SQL over metadata columns already stored. This matches the repo rules.

- Drop idx_requests_session_tenant. It sat in ddl, which an existing
  version-6 database skips, so it never reached the deployments this
  fixes; and idx_requests_tenant_session(tenant_id, session_id, ts)
  already covers the (tenant, session) correlated counts.
- Add a test for the inflation correction: tenant B's ping in a shared
  session id no longer deducts tenant A's savings. It fails when the
  partition in that CTE is reverted.
- Key the per-model valuation by a tenantModel struct, not tenant+"|"+model.
- Correct two comments that still said the bug was open or unreachable.

Behavior change: none beyond the PR's first commit. Data dependence: none.

Assisted-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Replies to round 1. Fix commit: f89d7e7.

Reviewer 1, finding 1 (no test for the before CTE): fixed.
Test TestInflationCorrectionIgnoresOtherTenantsPingsInTheSameSession is added.
I reverted the partition in that CTE. The test then fails: A's ReplayProjectedTokens goes 30 -> 0. With the fix it stays 30.

Reviewer 1 finding 2 and reviewer 2 finding 1 (index not in additiveDDL2): fixed by removing the index.
The index sat in ddl, which a version-6 database skips. Also idx_requests_tenant_session(tenant_id, session_id, ts) already covers the correlated counts. I removed idx_requests_session_tenant. No schema change remains in this PR.

Non-blocking, fixed:

  • Stale comments in dash/overview.go and dash/cachehistory.go are corrected.
  • The priced key is now a tenantModel struct, not a joined string.

Non-blocking, not fixed here:

Behavior change.
Reviewer 2 is right. Per-tenant valuation can add credit as well as remove it. A tenant that measured a constant stable half is now credited, even when another tenant's spread differs. A tenant with no measurement of its own loses the credit it borrowed. I will correct the PR body. This change needs the owner's yes before merge.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 1 of 2 2 of 2 f89d7e7f6443 approve

Verdict: approve

Findings

None.

Earlier findings

  • My finding 1 (no test for the changed before CTE): fixed. TestInflationCorrectionIgnoresOtherTenantsPingsInTheSameSession (dash/tenant_session_isolation_test.go:201) covers it. I verified the numbers by hand. Alone: the raw ceiling is 50 (partition of 4 rows, agent rows get n = 3, 2, 0 at 10 tokens each), the correction deducts 20 (A's ping at ts 1150 sees the two earlier saving rows), so the net is 30. Mixed: B's ping's window is the (B, session) partition, where the tenant-A cond is false for every row, so it deducts 0 and the net stays 30. With the partition reverted to session_id, B's ping at ts 2500 would carry A's three saving rows (deduction 30) plus A's own ping (20) — inflation 50 against raw 50, net 0. This matches the author's stated revert check. The test pins the fix.
  • My finding 2 (index in ddl, never reaching existing databases): fixed by removal. dash/schema.go is now byte-identical to base (git diff 9d34f00..HEAD -- dash/schema.go is empty), and no reference to idx_requests_session_tenant remains anywhere in dash/. The pre-existing idx_requests_tenant_session covers the correlated counts, and the corrected comment at dash/overview.go:747-751 now says so.
  • Reviewer 2's finding 1 (the same index defect): fixed the same way. I checked it myself; the proof above is mine.
  • Reviewer 2's non-blocking items: stale comments — fixed (dash/overview.go:747-751 and dash/cachehistory.go:105-109, 173-178 both rewritten and now accurate); priced string key — fixed with the tenantModel struct at dash/cachehistory.go:69, used at both call sites; index overlap — resolved by the removal; behavior change — the author accepted and will correct the PR body and record the owner's yes before merge; remaining same-class gaps — the author will open a follow-up issue. I accept the deferral. The archive and janitor deletes by session_id alone are the serious one; track them.

Non-blocking

  • The new test's inline comment (dash/tenant_session_isolation_test.go:226) says "10 x (2+1+0) = 30". That is the net figure. The raw ceiling is 50, because the ping sits inside the partition, and the correction deducts the 20. A reader computing the raw sum by hand may read the comment as the raw arithmetic. The referenced TestTheReplayCeilingCountsAgentTurnsNotPings explains the 30-versus-50 effect. One clarifying sentence would help.
  • Merge precondition, not a code defect: the behavior change (per-tenant valuation both adds and removes credit) still needs the owner's recorded yes, per CLAUDE.md and RELEASING.md. The author committed to this in the reply.

What I checked

  • Last review: round 1, f0c4074, 2026-11-11T06:47:02Z
  • New commits read: 1 (f89d7e7 "fix(dash): address round-1 review of the tenant/session fix (#501)")
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from the three files)
  • New items since my last review: the fix commit f89d7e7 (full diff read, each changed file read around the changes); the author's reply comment of 2026-11-11T06:51:02Z (each claim checked against the code); reviewer 2's round-1 review of 2026-11-11T06:46:49Z (read now, after my round 1 was posted; its finding checked independently above).
  • The new commit's changes in detail: the tenantModel struct key is exact and used consistently at both priced maps; the comment rewrites match the code at head; kaPing exists in dash/keepalivetab_test.go:48 with the signature the new test uses, and sets KeepAlive: true; isolationDB overwrites TenantID on both batches, so the ping rows carry the right tenant.
  • The new test's arithmetic, derived by hand for both databases and for the reverted-partition case (see "Earlier findings").
  • That the index removal leaves nothing behind: no occurrences of the index name in dash/, and dash/schema.go diff against base is empty, so no schema change remains in this PR and no schemaVersion question is open.
  • That no test required the removed index: assertSessionOrTimeIndexed accepts idx_requests_session as a substring of the other session indexes, and the EXPLAIN tests build through the same functions the server calls.
  • The rest of the PR is unchanged since my round-1 review, which covered the full diff against base.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 2 of 2 2 of 2 f89d7e7f6443 approve

Verdict: approve

Findings

None.

Earlier findings, resolved

  • My finding 1 (index in ddl never reaches an existing database): fixed by removal. The fix commit deletes idx_requests_session_tenant from dash/schema.go. The removal is the right resolution, not just a valid one: idx_requests_tenant_session (tenant_id, session_id, ts) at dash/schema.go:381 already serves the correlated count in replayCeilingQuery (dash/overview.go:1185-1188) as an index-only COUNT(*) — equality on both leading columns, range on ts, and p.id is the rowid every index carries. grep -rn idx_requests_session_tenant over the repo shows no reference left. No schema change remains in this PR, so the version-6 two-shapes problem is gone with it.
  • Reviewer 1, finding 1 (no test for the before CTE): fixed. I checked the new test myself; see "What I checked" for the arithmetic.
  • My non-blocking items: all fixed or accepted. The two stale comments are rewritten and now match the code (dash/overview.go:747-751, dash/cachehistory.go:105-108 and 172-176). The priced key is a tenantModel struct at all six use sites; no tenant+"|"+model string remains. The index-overlap note is resolved by the removal. The same-class gaps (KeepAliveSessions under TenantAll, the recorder seed paths, the Sessions tab, the archive and janitor deletes by session_id alone) are acknowledged by the author with a planned follow-up issue; I agree they are outside #501's figures, and the archive delete (dash/archive.go:297, 345) does deserve that follow-up — it can remove another tenant's rows.
  • Author's reply on the behavior change: the reply states the change can remove credit too (a tenant that borrowed another tenant's measurement loses it), and that the owner's yes is needed before merge. Correct on both points, and broader than my round-1 note, which said "can only add credit". The author's reading is the right one.

Non-blocking

  • The author's PR comment says reverting the before CTE's partition makes the new test fail with ReplayProjectedTokens "30 -> 0". My trace gives a different value: with only that partition reverted, B's ping also sums A's earlier savings (inflation 40) and the result is 10; with both CTEs reverted it is 70. Either way the test fails pre-fix, so the regression protection holds. The stated value looks wrong; the test does not depend on it.
  • The new test's inline comment says A's ping "deducts nothing a later turn could replay". The ping's before.s is 20 and that 20 IS deducted — correctly, because the raw ceiling counted the ping as a later turn for A's first two rows. The assertion is right; the sentence may confuse a future reader.

What I checked

  • Last review: round 1, f0c4074, 2026-11-11T06:46:49Z.
  • New commits read: 1 (f89d7e7f "fix(dash): address round-1 review of the tenant/session fix (#501)").
  • Read in full: 2 reviews, 1 comment, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt — the inline file is empty).
  • New items since my last review: the fix commit f89d7e7f (reviewed hunk by hunk below) and the author's reply comment (checked against the code, item by item above).
  • The full diff f0c40740..HEAD, and the code around each hunk: the tenantModel type and its six use sites in dash/cachehistory.go, the two rewritten comments in dash/cachehistory.go and dash/overview.go, the index deletion in dash/schema.go, and the new test in dash/tenant_session_isolation_test.go.
  • The new test's arithmetic, derived by hand against the current SQL. Alone and mixed both give raw ceiling 50 (A's three saving rows at n = 3, 2, 0 in the (tenant_id, session_id) partition, 10 tokens each) minus inflation 20 (A's ping sums A's two earlier in-scope savings; B's ping sums 0 because cond excludes B's rows inside the CASE) = 30. The assertion a.ReplayProjectedTokens != 30 and the alone/mixed comparison both hold.
  • That the test fails on the pre-fix SQL: with the before CTE's partition reverted to session_id, both tenants' pings sit in one window and B's ping carries A's running sum, inflation becomes 40, and the result is 10 (or 70 with both CTEs reverted). Not 30, so the test protects the fix.
  • That removing the index leaves the queries it was added for still covered: idx_requests_tenant_session serves the session-scoped correlated count as a covering COUNT(*), and the EXPLAIN assertions in overview_lean_test.go and overview_session_scope_test.go accept idx_requests_tenant_session by name.
  • That no schema change remains: migrate() behavior is back to the base shape, and no test or comment names the dropped index.
  • Reviewer 1's round-1 findings re-checked independently before accepting them as fixed (the before-CTE test and the index placement).
  • I did not run builds or tests. Live tests are not approved and Go is not installed on this machine.

…s by tenant (#1069 #1070 #1071)

Same class as #501: session_id alone keyed rows that two tenants could
share. The hosted path namespaces ids as tenant:base (session.Scoped),
so these are defense in depth; rows written another way can collide.

#1069 (data loss):
- Archive candidates, the archive's reads and deletes, the janitor's
  fallback delete and DropOldestSessions work per (tenant, session).
  A shared id used to merge both tenants' transcripts into one object
  filed under the higher tenant id, then delete both tenants' rows.
- archived_sessions is keyed (tenant_id, session_id). Existing
  databases are rebuilt on open (migrateArchivedSessionsKey, one
  transaction, idempotent, rows kept).
- FetchArchived, FetchArchivedContent take the tenant; new
  ArchivedSessionOf. ArchivedSessionByID stays for a manager's view.

#1070:
- KeepAliveSessions and the Sessions tab group by (tenant, session);
  the per-session maps are keyed by sessKey. KeepAliveSessions breaks
  cost ties by tenant and session, so ties no longer depend on the
  planner; the ka_sessions golden file is regenerated for that swap.

#1071:
- seedOneHourTiers ranks and SeedGraceSessions groups per tenant.
  thread.Key is unchanged (74 callers; its ids already carry the tenant).

Behavior change: the archive index migration, the exported signature
changes above, and the tie order in KeepAliveSessions. Data dependence:
none; metadata columns only.

Tests: five new tests in dash/tenant_session_isolation_test.go. Each
fails when its fix is reverted.

Assisted-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid boazdavid changed the title fix(dash): keep one tenant's rows out of another's per-session figures (#501) fix(dash): keep one tenant's rows out of another's session figures, archives and seeds (#501 #1069 #1070 #1071) Nov 11, 2026
@boazdavid

Copy link
Copy Markdown
Collaborator Author

New commit 84553fb adds the fixes for #1069, #1070 and #1071 to this PR. It also changes the PR title and body.

The two reviews above approved f89d7e7, before this commit. The new commit is large: a schema rebuild of archived_sessions, signature changes in dash/archive.go and dash/api.go, and per-tenant keys in the keep-alive and Sessions queries. It has had no review. The round budget (2 of 2) is used. I ask the owner for a third round.

A finding from my own reading of the code: on the hosted path the stored session id is tenant:base, so a shared id between two tenants is normally not reachable. I corrected the earlier wording in the code comments, the PR body and the three issues.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Round 3 review — PR #1064

Reviewer 1 of 2 (glm, user of @boazdavid)
Backend GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241
Context offload-review skill, @boazdavid's session
Session resumed
Round 3 of 3
Head reviewed 84553fb055c6
Verdict approve

What I checked

  • Last review: round 2, f89d7e7f6443, posted 2026-11-11T06:53:39Z.
  • New commits read: 1 — 84553fb0 "fix(dash): scope archive, eviction, all-tenant session views and seeds by tenant (#1069 #1070 #1071)".
  • Read in full: 4 reviews, 2 comments, 0 inline comments.
  • New items since last review: commit 84553fb0 (13 files under dash/), the PR title and body change, and the author's comment of 2026-11-11T07:32:03Z.

I read the full diff of 84553fb0 line by line. I read each changed file around the changes, not only the diff lines. I did not build or run tests. Go is not installed, and live tests are not approved.

Earlier findings

  • Round 1, finding 1 (no test for the before CTE): fixed in f89d7e7f. Verified in round 2. No regression in 84553fb0.
  • Round 1, finding 2 (idx_requests_session_tenant in ddl never reaches a v6 database): fixed by removing the index. Verified in round 2. 84553fb0 adds a schema change outside ddl; I checked it separately below.

The new commit, 84553fb0

This commit closes the gaps the author listed as not-fixed in round 2. I verified each part.

#1069, archive and eviction by tenant.

  • dash/schema.go: the archived_sessions primary key becomes (tenant_id, session_id). migrateArchivedSessionsKey rebuilds an old-shape table in one transaction. I traced three cases. Fresh database: ddl creates the new shape, the probe exits. Existing database with the old shape: the rebuild copies every column, drops, renames, and recreates idx_archived_tenant. Second open: tenant_id is already in the primary key, the probe exits. The rebuild is idempotent.
  • dash/janitor.go: evictSessions deletes with tenant_id = ? AND session_id = ?.
  • dash/store.go: DropOldestSessions picks victims with oldestSessionKeys, GROUP BY tenant_id, session_id, and deletes with row-value IN (VALUES ...), chunked by chunkKeys. I checked the cap math: 250 pairs bind 500 variables, under the driver's 32,766 limit.
  • dash/store.go: victims stays a list of bare session ids for sessionAliases and deleteSessionState. I checked this is safe. inUseIDs tests each key against every tenant's remaining rows, so a state key the other tenant still uses is kept. The failure direction keeps state, and retention bounds it.
  • dash/archive.go: candidates group by (tenant_id, session_id); the notYet predicates use pair NOT IN; markArchived conflicts on (tenant_id, session_id); content and full archives delete tenant-scoped rows; sessionEvents reads with Filter{Tenant: tenant}. New ArchivedSessionOf serves tenant callers. ArchivedSessionByID stays for the manager view, and its comment states that scope.
  • dash/api.go: hosted lookups use ArchivedSessionOf(f.Tenant, ...); FetchArchived calls carry arch.TenantID or meta.TenantID. In sessionTranscript, the owner pinning runs before the archive lookup, so the archive row belongs to the same tenant as the turns shown.

#1070, all-tenant session views.

  • dash/query.go: SessionsOrdered groups by (tenant_id, session_id). The Scan order matches the new SELECT column order. The total counts DISTINCT pairs. pingsBySession and sessionTokens are joined by sessKey{TenantID, SessionID}.
  • dash/keepalive.go: KeepAliveSessions groups by (tenant_id, session_id) with the deterministic tie-break ORDER BY 4 DESC, tenant_id, session_id. The per-session follow-up queries pin r.tenant_id = ?. The ledger nets, sumBySession, countBySession and KeepAliveLive rows are keyed by sessKey.

#1071, seed paths.

  • dash/capture.go: seedOneHourTiers partitions by tenant_id, session_id, thread_id, model. SeedGraceSessions groups by tenant_id, session_id, thread_id, session_alias. A key two tenants share keeps the newer qualifying timestamp.
  • thread.Key stays tenant-free by design. The comment says the hosted session id already carries the tenant. I confirmed this: session.Scoped in apply/ namespaces ids as tenant:base.

Tests.

Five new tests in dash/tenant_session_isolation_test.go. I read each and traced the SQL it exercises. I checked that each fails on the pre-fix behavior:

  • TestArchiveMovesOnlyTheOwningTenantsSession: with the old single-column grouping, archiving one candidate deletes both tenants' rows, and the remaining-candidate count reads wrong.
  • TestDropOldestSessionsKeepsTheOtherTenantsRows: with the old session_id IN (...) delete, one victim removes both tenants' rows, and the test's n = 1 fails.
  • TestArchivedSessionsKeyMigrationKeepsRowsAndAllowsASharedId: rebuilds the old-shape table, runs the migration twice, and checks both idempotence and the shared-id insert that the old primary key rejected.
  • TestAllTenantsSessionViewsKeepTenantsApart: Sessions and KeepAliveSessions under TenantAll return two rows for one shared id, not one merged row.
  • TestSeedOneHourTiersRanksPerTenant: with the old partition, both tenants' rows share one rn = 1, and the one-hour write of the first tenant never seeds.

The golden file, dash/testdata/golden/ka_sessions.json.

The row set changes, not only the order. Four t2 rows leave and four t1 rows enter. Cause: the LIMIT 20 cuts inside the expiry_usd = 0.018 tie group, and the new tie-break (tenant_id, session_id) picks different rows from that group. This is the deterministic rule working as intended. I compared both files row by row. Every field outside the tie group is unchanged.

One point in the conversation

Reviewer 2's round-2 note doubted the author's "30 -> 0" revert value for the before CTE test. I re-derived the arithmetic by hand, in round 2 and again now. Mixed database: B's ping carries 30 of inflation against B's raw 50, so the net is 0. The author's number is right.

Non-blocking

  • KeepAliveLedger.WorstSession reports the bare session id. When two tenants share an id, the field cannot say which tenant holds the worst net. Display only.
  • seedOneHourTiers comment says "on a key two rows still share, the newer write stands". The code keeps the newer qualifying write: an older row with write1h >= write still seeds the key when the newer row does not qualify. The comment could say "qualifying".

Verdict

Verdict: approve. The migration is idempotent. The deletes are tenant-scoped. The views group by (tenant_id, session_id). The seeds rank per tenant. The tests cover each path with a shared session id.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 2 of 2 3 of 3 84553fb055c6 approve

Verdict: approve

Findings

None.

Earlier findings, resolved

  • My round-1 finding (index in ddl never reaches an existing database): still fixed. The removal in f89d7e7f stands. The new commit adds a schema change again, so I re-checked the reach question for it: migrateArchivedSessionsKey runs from migrate() on every open, before the version check, exactly like migrateToolUsesProject. An existing version-6 database gets the rebuild. Verified in dash/schema.go:1178-1186.
  • Reviewer 1's round-1 findings (missing before-CTE test, same index defect): still fixed. No regression in 84553fb0.
  • My round-2 note doubting the author's "30 -> 0" revert value: I was wrong, and I withdraw it. I re-derived the trace by hand. A's three agent rows give a raw ceiling of 10 x (3+2+0) = 50. With the before CTE's partition reverted to session_id alone, both tenants' rows share one window in (ts, id) order. B's ping at ts 2500 then carries the running sum of all three of A's qualifying savings, which is 30. Total inflation is A's ping 20 plus B's ping 30 = 50. The net is 50 - 50 = 0. The author's number is right. My round-2 trace stopped the running sum one row early. The test itself was never in doubt: it fails pre-fix either way.

Non-blocking

  • Rollback after the archive migration. schemaVersion stays 6, so an old binary accepts a migrated database without a version mismatch. The old markArchived upsert says ON CONFLICT(session_id) (base 9d34f00, dash/archive.go). On the rebuilt table, session_id alone carries no uniqueness constraint, so that statement fails to prepare. After a binary rollback, every archive write errors until the operator rebuilds the file. Reads still work, and the archive job's error does not stop the proxy. The same hazard class already shipped with migrateToolUsesProject (the old binary's tool_uses upsert keys on the pre-project shape, dash/toolinventory.go:1004), so this follows repo precedent. Suggestion: one line in the release notes.
  • Agree with reviewer 1's WorstSession note. I checked it myself: dash/keepalive.go keeps o.WorstSession = net, s.session, so the ledger's worst-session field drops the tenant. Display only. I add no new proof.
  • Merge gate, not a code defect. The commit message declares three behavior changes: the archive index migration, the exported signature changes, and the KeepAliveSessions tie order. Per CLAUDE.md and RELEASING.md, the owner's yes must be recorded before merge. The commit also states "Data dependence: none; metadata columns only". I checked: archived_sessions stores ids, timestamps, counts, paths and byte sizes. No new data dependence.

What I checked

  • Last review: round 2, f89d7e7, 2026-11-11T06:54:00Z.
  • New commits read: 1 (84553fb "fix(dash): scope archive, eviction, all-tenant session views and seeds by tenant (#1069 #1070 #1071)").
  • Read in full: 5 reviews, 2 comments, 0 inline comments (from the three files; the inline file is empty).
  • New items since my last review: commit 84553fb (full diff, every changed file read around the changes); the author's comment of 2026-11-11T07:32:03Z (new commit announcement, third-round request, and the reachability correction — the hosted path namespaces ids as tenant:base via session.Scoped, so a shared id is defense in depth, not the normal case; I checked the claim against apply/); the PR title and body change; reviewer 1's round-3 review of 2026-11-11T07:44:55Z (each claim checked independently; see the "30 -> 0" correction above).
  • The migration, migrateArchivedSessionsKey (dash/schema.go:1100-1164), case by case. Fresh database: ddl creates the new shape, the probe exits. Old shape: the rebuild copies all 11 named columns, drops, renames, and recreates idx_archived_tenant, all in one transaction. Second open: tenant_id is in the primary key, the probe exits. Missing table: zero columns, return nil. The copy cannot violate the new key: the old table's session_id primary key makes every session_id unique, so every (tenant_id, session_id) pair is too. The column list matches every shape the table ever shipped: git log -S shows the table was created in 3fabf51 with the same 11 columns, and additiveColumns never touched it. So no old-version database can fail the rebuild on a missing column.
  • Migration concurrency. Two writer processes: archived_sessions_new never exists outside the migration's own transaction (create, copy, drop and rename are all inside it), so a second opener either sees the new primary key in its probe and skips, or waits on SQLite's write lock and re-runs the rebuild on the already-migrated table, with the same result. No orphaned _new table is possible.
  • The archive and eviction scoping, end to end. Candidates group by (tenant_id, session_id) (dash/archive.go:103-121, 134-137, 160-165); the notYet predicates use pair NOT IN; ArchiveSessionContent and ArchiveSessionFull delete WHERE tenant_id = ? AND session_id = ?; the janitor fallback delete is pair-scoped; markArchived conflicts on (tenant_id, session_id) and its update is pair-scoped; sessionEvents reads with Filter{Tenant: tenant}; FetchArchived and FetchArchivedContent take the tenant. Scan orders match SELECT orders in every changed query.
  • The API layer. sessionTranscript: the owner pinning sets f.Tenant and clears TenantAll before the lookup closure runs, so ArchivedSessionOf(f.Tenant, session) reads the owning tenant's row; the TenantAll branch with no events keeps ArchivedSessionByID and the ownership test. archivedSession: ByID only for no-auth or manager, ArchivedSessionOf(p.TenantID, ...) otherwise. request: the row's own e.TenantID drives both the lookup and the fetch.
  • DropOldestSessions (dash/store.go): victims come from oldestSessionKeys (GROUP BY tenant_id, session_id), the delete uses row-value IN (VALUES ...), and chunkKeys halves the chunk to 250 pairs, which binds the same 500 variables as before. I also checked the state cleanup that still uses bare session ids: deleteSessionState calls inUseIDs, which tests each key against every tenant's remaining rows, so a state key the other tenant still uses is kept. The failure direction keeps state.
  • #1070, the all-tenant views. SessionsOrdered groups by (tenant_id, session_id), the correlated model subquery pins r2.tenant_id, and the total counts DISTINCT pairs. sumBySession, countBySession, pingsBySession, sessionTokens, KeepAliveSessions and KeepAliveLive key by sessKey; each scan order matches its SELECT; the per-row follow-up queries add r.tenant_id = ?; KeepAliveLive rows carry TenantID from the SELECT. sessionTokensQuery groups by 1, 2, so a session id two tenants share yields two map entries, and callers look up by (row.TenantID, row.SessionID).
  • The golden file, dash/testdata/golden/ka_sessions.json. I compared the old and new files as sets with a script. All 20 rows have the same fields except the tie group at the LIMIT 20 boundary: eight sessions all at expiry_usd = 0.018000000000000002. The new deterministic order (tenant_id, session_id) keeps the four t1 rows and drops the four t2 rows from that group. Every field outside the tie group is unchanged, and the within-tie order in the rest of the file matches the new ORDER BY. The regeneration is a faithful capture of the deterministic rule, not a masked value change.
  • #1071, the seeds. seedOneHourTiers partitions by (tenant_id, session_id, thread_id, model); SeedGraceSessions groups by (tenant_id, session_id, thread_id, session_alias); on a key two groups share, the newer qualifying timestamp wins, and out[k] starts at 0 so the first write always lands. thread.Key stays tenant-free by design, and the commit message says so.
  • The five new tests in dash/tenant_session_isolation_test.go. I traced each by hand against the pre-fix and post-fix SQL. Each fails pre-fix: the archive test merges both tenants into one candidate and one archive object; the drop test deletes both tenants' rows with n = 1 failing; the migration test rebuilds the exact pre-PR table shape (it matches the base-commit ddl line for line) and runs the migration twice; the all-tenant views test gets one merged row instead of two, with A's ping attributed to the merged row; the seed test's one-hour write of tenant A is hidden by tenant B's later write in the shared partition.
  • The changed exported signatures (FetchArchived, FetchArchivedContent, ArchivedSessionOf). I grepped the repo: every caller is inside dash or its tests. The proxy reaches these only through dash's own handlers.
  • I did not run builds or tests. Live tests are not approved and Go is not installed on this machine.

…ment (#1064 review)

- KeepAliveLedger gains worst_session_tenant (omitted when empty), so a
  session id two tenants share no longer hides whose net is the worst.
  The keepalive golden file gains that one field.
- seedOneHourTiers comment says "qualifying write", which is what the
  code keeps.

Behavior change: one added JSON field. Data dependence: none.

Assisted-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>
@boazdavid

Copy link
Copy Markdown
Collaborator Author

Fix commit 97d6110 answers the two non-blocking notes of round 3.

  • KeepAliveLedger has a new field, worst_session_tenant (omitted when empty). It names the tenant of worst_session. The keepalive golden file gains that one field.
  • The seedOneHourTiers comment now says "qualifying write".

The PR body lists the rollback note for the archived_sessions rebuild. The round budget (3 of 3) is used, so this commit has no review. It adds one JSON field and changes one comment.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 1 of 2 4 of 4 97d611030917 approve

Verdict: approve

Findings

None.

Earlier findings and notes

  • My round-1 finding 1 (no test for the before CTE): fixed in f89d7e7f. Verified in round 2. No regression in the commits after it.
  • My round-1 finding 2 (idx_requests_session_tenant in ddl): fixed by removal. Verified in round 2. Nothing reinstates it.
  • My round-3 non-blocking note 1 (WorstSession cannot name the tenant on a shared id): fixed in 97d61103. KeepAliveLedger gains WorstSessionTenant (dash/keepalive.go:284), set with the same net test as WorstSession (dash/keepalive.go:421). s.tenant exists on sessKey (dash/keepalive.go:523).
  • My round-3 non-blocking note 2 (the seedOneHourTiers comment): fixed. The comment now says "the newer qualifying write stands" (dash/capture.go:923). That is what the code keeps.
  • Reviewer 2's round-3 non-blocking (rollback hazard after the archived_sessions rebuild): addressed. The PR body lists it as behavior change 5, with the scope (old binary's ON CONFLICT(session_id) fails; reads still work) and the tool_uses precedent. I read the body; the wording matches the code.
  • Reviewer 2's round-3 withdrawal of the "30 -> 0" doubt: agree. The withdrawal matches my round-2 and round-3 derivations. Inflation 50 against raw 50 gives net 0.

The new commit, 97d61103

Three files. I read the full diff and the code around each change.

  • dash/keepalive.go: the new field serializes as worst_session_tenant, omitted when empty. It is set only when net < o.WorstNetUSD, together with WorstSession and WorstNetUSD. The commit message states the behavior change (one added JSON field) and "Data dependence: none". Both statements are right: the ledger reads the same metadata columns, and the new field is additive.
  • dash/testdata/golden/keepalive.json: the file gains worst_session_tenant: "t1" and nothing else. worst_session stays absent because the golden test drops it (tieKeys, dash/golden_endpoints_test.go:195) — its value depends on map iteration order. The new field does not. I traced the fixture: only sessions with s%4 == 0 get a ping, every such s is even, and even s means tenant t1 (dash/golden_endpoints_test.go:64, 101-107). So every session in the worst-net tie group is a t1 session, and the tenant is "t1" whatever iteration order picks. Deterministic.
  • dash/capture.go: one comment word. Verified above.

Non-blocking

  • worst_session_tenant is not in tieKeys. It is deterministic only because of the fixture's structure: the worst-net tie is single-tenant by construction, since only t1 sessions carry pings. A future fixture change that gives a t2 session the same worst net makes the golden test flaky. Adding the key to tieKeys removes that hazard, but it also drops the field's only golden coverage. Either choice is defensible; note the coupling when the fixture next changes.

What I checked

  • Last review: round 3, 84553fb055c6, posted 2026-11-11T07:44:55Z.
  • New commits read: 1 — 97d61103 "fix(dash): name the tenant of the worst keep-alive session; fix a comment (#1064 review)".
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from the three files; the inline file is empty).
  • New items since my last review: reviewer 2's round-3 review of 2026-11-11T07:50:20Z (each claim checked: the rollback note, the WorstSession agreement, the "30 -> 0" withdrawal — all verified against the code and my own derivations); the author's comment of 2026-11-11T08:00:38Z (fix-commit announcement; the PR-body rollback claim verified by reading the body); commit 97d61103 (full diff read, each changed file read around the changes).
  • The worst_session_tenant determinism trace over the golden fixture (see "The new commit").
  • The golden file's key set against the struct's JSON tags, and the dropTies mechanism that removes worst_session.
  • The PR title and body at head: behavior changes 1-5 are named at the top, with the data-dependence statement. The new commit's behavior change (one JSON field) is stated in its commit message.
  • I did not run builds or tests. Go is not installed, and live tests are not approved.

@boazdavid boazdavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @boazdavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.241 offload-review skill, @boazdavid's session resumed 2 of 2 4 of 4 97d611030917 approve

Verdict: approve

Findings

None.

Earlier findings, resolved

  • My round-1 finding (index in ddl never reaches an existing database): still fixed. No schema change in the new commit.
  • My round-3 non-blocking notes: all addressed.
    • Rollback note: the PR body now lists it as behavior change 5, with the tool_uses precedent and the release-notes line. I read the body; the wording matches what I verified in round 3.
    • WorstSession drops the tenant: fixed by the new WorstSessionTenant field. Verified below.
    • The seedOneHourTiers comment: fixed. The comment now says "newer qualifying write stands", which is what the code keeps (if write1h >= write guards the ts > out[k] update).
  • Reviewer 1's round-3 non-blocking notes: both fixed by this commit. The WorstSession note is the same fix as mine; the "qualifying" comment note is the same fix. I checked both myself.
  • The owner's yes on the declared behavior changes remains a merge gate, not a code defect. The PR body lists five behavior changes at the top and asks for the owner's confirmation.

Non-blocking

  • worst_session_tenant is not in tieKeys (dash/golden_endpoints_test.go:195), while worst_session is. In the current fixture this is safe: the ledger's nets keys are exactly the pinged sessions, the fixture pings only sessions with s%4 == 0, and all of those are even s, so every candidate for the worst net is tenant t1. The worst-net tie never spans tenants, so the tenant is deterministic while the session is not. If a future fixture ever pings both tenants at the same worst net, add worst_session_tenant to tieKeys then.

What I checked

  • Last review: round 3, 84553fb, 2026-11-11T07:50:20Z.
  • New commits read: 1 (97d6110 "fix(dash): name the tenant of the worst keep-alive session; fix a comment (#1064 review)").
  • Read in full: 6 reviews, 3 comments, 0 inline comments (from the three files; the inline file is empty).
  • New items since my last review: commit 97d6110 (full diff, 3 files, each read around the changes); the author's comment of 2026-11-11T08:00:38Z (announces the fix commit and says the PR body lists the rollback note — verified against the PR body); the PR title and body update (read in full; the rollback note is behavior change 5, and the reachability section matches the hosted-path scoping I verified in round 3).
  • The new field, WorstSessionTenant (dash/keepalive.go:284). It is set in the same statement as WorstNetUSD and WorstSession, from s.tenant of the same sessKey, so the three fields cannot disagree (dash/keepalive.go:421). omitempty keeps the JSON unchanged when no session has a negative net. The commit message declares the added JSON field as a behavior change.
  • That the field is deterministic in the golden test. The golden comparison drops worst_session via tieKeys because the nets map iterates in random order. I checked whether worst_session_tenant needs the same treatment: the ledger's nets keys are the pinged sessions, and the fixture (dash/golden_endpoints_test.go:104-109) adds a ping only when s%4 == 0. Every such s is even, so every pinged session belongs to t1. The worst-net tie (-0.0004, five sessions visible in the goldens) is within t1 only, so the tenant is stable across map iteration orders. The regenerated keepalive.json gains exactly one field, worst_session_tenant: "t1", beside the unchanged worst_net_usd: -0.0004.
  • That nothing else reads the field: a repo-wide grep for WorstSession and worst_session finds only the struct, the assignment, and the golden test. No UI or library code consumes it, so the added field cannot break a reader.
  • The seedOneHourTiers comment change (dash/capture.go:923). One word, and the word matches the code: the ts > out[k] update runs only inside the write1h >= write guard, so an older qualifying write beats a newer non-qualifying one. The comment now says exactly that.
  • That the commit changes nothing else: git diff 84553fb0..HEAD touches only dash/capture.go (the comment), dash/keepalive.go (the field and its assignment, plus struct realignment), and dash/testdata/golden/keepalive.json (the one field).
  • I did not run builds or tests. Live tests are not approved and Go is not installed on this machine. The PR body states go test ./dash, go build ./... and go vet ./... pass; I could not verify that myself.

amiddavid added a commit that referenced this pull request Nov 11, 2026
The go test time limit goes from 20m to 40m on the test and cover
targets. On main's CI, the dash package took 1140 s of the 1200 s
limit, so PRs that add dash tests (#1001, #1064, #1068) failed
build-test with "test timed out after 20m0s".

Behavior change: none (CI and local test limits only). Data
dependence: none. Follow-up: speed up or split the dash tests.

Reviews: 2 offload reviews (GLM), round 1, both approve at 0612436,
which is the PR head.

Signed-off-by: DAVID AMID <[email protected]>
Assisted-By: Claude Opus 5.5 <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator

Integrator note: #1082 is on main (3c876dc). It raises the go test time limit to 40m. The build-test failure here ("test timed out after 20m0s" in the dash package) came from the old limit. Please merge origin/main into this PR, so CI runs with the new limit.

Keep both sides in dash/capture.go and dash/keepalive.go: the tenant-keyed
grouping from this branch with main's cache_write grace condition and
keep-alive tier tokens. The token lookup is now keyed by tenant and session.
Regenerate the ka_sessions golden.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: DAVID BOAZ <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session fresh 2 of 2 5 of 5 e6557755e357 approve

Verdict: approve

Findings

None.

What changed since round 4

One commit on the branch: e6557755, a merge of origin/main (3c876dcb) into the PR branch. The integrator asked for it (#1082 raises the go test limit to 40m). The merge is the whole change. No main-side commit was authored here.

The merge, checked hunk by hunk

git diff-tree --cc names seven files where the result differs from both parents. I read each resolution against both sides.

  • dash/capture.go (SeedGraceSessions). The merge keeps main's grace condition (cache_read > 0 OR cache_write > 0, #1066) and this branch's GROUP BY r.tenant_id, r.session_id, ... (#1071). The function comment was updated to say "READ or WROTE", so it matches the merged condition. The selected columns are all in the GROUP BY, so the SQL is valid.
  • dash/keepalive.go. Main's token tables (#1048, #1065) are re-keyed to this branch's sessKey. I traced every lookup: keepAliveSessionTokens now builds map[sessKey] from sessionTokens (which returns map[sessKey], dash/query.go:656, groups by 1, 2); KeepAliveSessions and KeepAliveLive look up with sessKey{row.TenantID, row.SessionID}. The ids slice holds bare session ids and feeds f.SessionIn, which is correct under both a tenant filter and TenantAll. The SELECT column order (session_id, tenant_id, ...) matches the Scan order. The ORDER BY keeps this branch's tie-break 4 DESC, tenant_id, session_id.
  • dash/overview.go, dash/query.go, dash/schema.go, dash/store.go. Each hunk is main's restored_tokens column (#1067, #481) applied onto this branch's tenant-keyed code. I checked the three orderings: requestCols adds r.restored_tokens before requestTokenSelect and scanRequest scans &e.RestoredTokens in the same place; insertBatch adds the column, one ?, and e.RestoredTokens in matching positions; the Overview SELECT and its Scan each gain the term in the same position. The column is in additiveColumns (dash/schema.go:944-947), so existing databases get it. This was the trap of my round-1 finding; main placed it correctly.
  • dash/testdata/golden/ka_sessions.json. Regenerated, and the regeneration is faithful to both sides. Against the PR parent the diff is purely additive: the same 20 sessions, same order, same dollar figures, plus the token fields (540 added lines = 20 rows x 27). Against main the diff is only row swaps inside equal-expiry_usd groups, and the session set differs from main's exactly by the LIMIT-20 tie group: the four t1 rows in, the four t2 rows out, the selection round 3 verified. I also checked the file against the merged ORDER BY with a script: expiry_usd desc, then (tenant_id, session_id) asc, holds on every adjacent pair.
  • Makefile. The 40m limit from #1082 is in both test and cover. This answers the integrator's comment.

I also checked what the merge did NOT touch: dash/archive.go, dash/api.go, dash/cachehistory.go, dash/janitor.go and dash/tenant_session_isolation_test.go are byte-identical to the PR parent, so no fix from rounds 1-4 was lost. WorstSessionTenant (dash/keepalive.go:299, 436) and the "newer qualifying write" comment (dash/capture.go:923) both survive. keepalive.json is unchanged. No conflict markers remain anywhere. Main's new katabletokens_test.go uses one tenant and value types only, so it compiles and behaves the same against the re-keyed maps.

Earlier findings, resolved

  • My round-1 finding (index in ddl never reaches an existing database): still fixed. No index from this branch remains. The schema change the merge brings in is main's restored_tokens column, and it sits in additiveColumns, which every open runs. I checked this myself.
  • Round-1 findings of reviewer 1 (missing before-CTE test, same index defect): still fixed. The test file is unchanged by the merge.
  • Round-3 and round-4 non-blocking notes: all still in place (WorstSessionTenant, the "qualifying" comment, the rollback note in the PR body, the tieKeys coupling note).
  • The owner's yes on the declared behavior changes remains a merge gate, as in rounds 3 and 4. The merge commit adds no behavior change of its own beyond combining the two reviewed sides.

Non-blocking

  • dash/keepalive.go:999-1001 — the comment on keepAliveSessionTokens says "keyed by session id". The map is keyed by sessKey (tenant and session). One stale sentence from the merge; the code is right.
  • dash/keepalive.go:1035 — byID is written and never read. This is pre-existing on both parents, not a merge regression. Dead code; drop it when the file is next touched.

What I checked

  • Last review: round 4, 97d6110, 2026-11-11T08:09:10Z
  • New commits read: 12 in the range. One is authored on the branch: e6557755 "Merge origin/main into repro/501-tenant-session". Eleven come from main through it: 3c876dcb (ci: 40m test timeout), 43802c5a (test(proxy): dashboard timing), 27c0c406 (fix(dash): fixed_restore copy in the saved figure), 8b311f10 (feat(dash): Cache strategy tables in tokens), 62289d9a (fix(keepalive): ping that re-wrote the cache restarts the clock), d865b250 (feat(agent): client-agent extension point), fd6f3865 (chore(plugins): v0.7.2 bumps), 2f61a327 (feat(plugin): read cache strategies from the proxy), 00ff1dbe (test(proxy): two-silences result), 05696977 (test(keepalive): warm sweep at the 20k floor), a067848b (test(bob-plugin): shell-change checks). The main-side commits were each reviewed in their own PRs; I read them here as they touch the files this PR changes.
  • Read in full: 8 reviews, 4 comments, 0 inline comments (from .review-in-reviews.txt, .review-in-comments.txt, .review-in-inline.txt — the inline file is empty).
  • New items since my last review: the integrator's comment of 2026-11-11T09:38:59Z (asked for the main merge; verified the Makefile now carries the 40m limit) and the merge commit e6557755 (reviewed above, resolution by resolution).
  • The merge resolution in all seven files that differ from both parents, read against both sides, plus the four files where main's restored_tokens changes land on this branch's code.
  • That no PR-side file or fix was reverted: a per-file diff of the merge against the PR parent over every file the PR touched.
  • The regenerated golden, checked two ways: as a diff against each parent, and programmatically against the merged ORDER BY and the LIMIT-20 tie selection.
  • The merged SQL by hand: GROUP BY validity in SeedGraceSessions, SELECT/Scan order in KeepAliveSessions, column/placeholder/argument order in insertBatch, and the sessKey plumbing from sessionTokens through keepAliveSessionTokens to both callers.
  • I did not run builds or tests. Live tests are not approved and Go is not installed on this machine. CI on the merged head is the check for the golden files; the analysis above says it should pass.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session fresh 1 of 2 5 of 5 e6557755e357 approve

Verdict: approve

Findings

None.

What I checked

  • Last review: round 4, 97d6110, 2026-11-11T08:09:08Z.
  • New commits read: 12 — e6557755 (merge of origin/main), and from main: 3c876dcb (CI timeout 40m), 43802c5a (dash latency guard), 27c0c406 (restored_tokens), 8b311f10 (Cache strategy tab tokens), 62289d9a (refresh clock on a writing ping), d865b250 (agent/ package), fd6f3865 (plugin versions), 2f61a327 (plugin cache strategies), 00ff1dbe (late-first-byte test), 05696977 (sweep floor test), a067848b (bob-plugin test).
  • Read in full: 8 reviews, 4 comments, 0 inline comments (from the three files; the inline file is empty).
  • New items since my last review: reviewer 2's round-4 review of 08:09:10Z (read; its tieKeys note matches my round-4 note, nothing to act on); the integrator comment of 09:38:59Z (asked for a merge of origin/main so CI runs the 40m limit — the merge e6557755 answers it, 3c876dcb is the second parent); commit e6557755 and the 11 main commits it brings (all read; the merge resolution reviewed hunk by hunk, both directions).

Earlier findings

  • My round-1 findings (missing before-CTE test; index in ddl): fixed in f89d7e7f, verified in round 2. No regression: the merge leaves dash/schema.go's migration path intact, and the branch's migrateArchivedSessionsKey still runs from migrate() on every open.
  • Reviewer 2's round-1 finding (same index defect): fixed, unchanged.
  • Round-3/4 non-blocking notes (WorstSessionTenant, "qualifying write" comment): fixed in 97d61103, verified in round 4. The merge keeps both: WorstSessionTenant is set at dash/keepalive.go:436 and the golden still carries worst_session_tenant: "t1".
  • Reviewer 2's round-3 rollback note: still addressed by the PR body's behavior-change list.

The merge commit, e6557755

Seven files were changed by both sides since the merge base 9d34f00f: dash/capture.go, dash/keepalive.go, dash/overview.go, dash/query.go, dash/schema.go, dash/store.go, and the ka_sessions golden. I read each resolution against both parents.

  • dash/keepalive.go — the one real hand resolution, and it is right. Main's 8b311f10 added keepAliveSessionTokens keyed by bare session id; the branch keyed every per-session map by sessKey{tenant, session}. The merge re-keys keepAliveSessionTokens to sessKey and looks up with toks[sessKey{s.TenantID, s.SessionID}] in both KeepAliveSessions and KeepAliveLive. I traced the path end to end: sessionTokens groups by (tenant_id, session_id) and scans into a sessKey, so a session id two tenants share yields two map entries and each row picks its own tenant's figures. Both callers return early on zero rows, so ids is never empty at the call. Main's tier-token columns (expiryTierTerms, expiryTierCols, tierDest) and the branch's tenant grouping, pinning and tie-break (ORDER BY 4 DESC, tenant_id, session_id) are all present in the merged SQL; every SELECT column count matches its Scan count (4 + 4 in all three token queries).
  • dash/capture.go — main's 62289d9a grace condition (a 2xx ping that read or wrote the cache moves the clock, in Record and in SeedGraceSessions) applied onto the branch's tenant-keyed GROUP BY r.tenant_id, ... and the newer-qualifying-write seed rule. Both sides survive; the branch's isolation tests do not pin the ping condition, so main's change cannot break them.
  • dash/overview.go, dash/query.go, dash/schema.go, dash/store.go — main's 27c0c406 (restored_tokens) applied onto the branch's versions. The column is added to ddl and additiveColumns, so existing databases get it — the correct pattern, unlike the round-1 index defect. SELECT/Scan orders match in requestCols/scanRequest and insertBatch (one column, one placeholder, one arg). The branch's oldestSessionKeys/chunkKeys pair-scoped deletes are unchanged.
  • dash/testdata/golden/ka_sessions.json — regenerated faithfully. I compared the old and new files row by row with a script: the same 20 (tenant_id, session_id) rows in the same order, no existing field changed, only the 4 new token fields added (expiry_tokens, keepalive_tokens, keepalive_ping_tokens, tokens_unmeasured_requests). The values are populated and self-consistent (pinged sessions show ping tokens; tokens_unmeasured_requests matches the fixture's unmeasured agent rows; keepalive_tokens is zero because the fixture writes no tok_ka_* columns).

The main commits

Each shipped on main with two approving offload reviews (per the commit messages). I read them for interaction with this branch, not as first reviews:

  • 62289d9a: the five clock sites (record1, manual ping, substitute, dash recorder, restart seed) all gate on the same 2xx && (read || write) condition. Consistent with the merged Record/SeedGraceSessions.
  • 27c0c406, 8b311f10: dash changes verified above as merge inputs.
  • 3c876dcb: the Makefile limit is now 40m, which answers the integrator's CI-timeout request.
  • The rest (d865b250 agent/, plugin and test commits) touch no file this branch changed; git diff --name-only of both sides against the merge base confirms the overlap is exactly the seven files above.

Non-blocking

  • The comment on keepAliveSessionTokens (dash/keepalive.go:999) still says "keyed by session id". After the merge the map is keyed by sessKey, tenant and session. One stale line.
  • byID in KeepAliveSessions (dash/keepalive.go:1037) is written in the scan loop and never read. Dead code, inherited from main's version, not introduced here.
  • I did not run builds or tests. Live tests are not approved and Go is not installed. The merge message states the golden was regenerated by running the test; I verified the file's content against the old golden instead.

@amiddavid
amiddavid merged commit d501cdb into main Nov 11, 2026
7 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 11, 2026
amiddavid added a commit that referenced this pull request Nov 17, 2026
The owner's new invariant, with #1183/#1184 as the example and #1064 as
earlier kin. I1-I2 check that a summary or sweep fires only on its own
thread's size, I3 reports the exposure (19% of laptop subagent requests
read another thread's figure today), I4 checks tenant isolation, and I5
is a code check that no component reads the session-wide figure.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

dash: per-session queries partition by session only, so one tenant's rows change another tenant's figures

2 participants