test: property-check SessionAffinityStore TTL, eviction, and reindex contracts
Summary
- Third entry in the resilience-primitive property series (#592 circuit breaker, #593 auth rate limiter): a fast-check suite for
SessionAffinityStore, the TTL/LRU store that keeps follow-up turns on the same account during rotation and whoseclearAll/reindex semantics back the #474 pin-invalidation flow.
What Changed
New test/property/session-affinity.property.test.ts (5 properties, real store driven through its injectable now parameters — no fake timers needed):
- Model-based TTL/upsert equivalence — for any interleaving of remember/update-response/forget/advance events, routed through whitespace-decorated key spellings,
getPreferredAccountIndexandgetLastResponseIdmatch a trivial TTL map. This pins the non-obvious upsert rules:rememberpreserves the prior continuation id, response-id writes refresh the session's TTL, andupdateLastResponseIdnever creates entries. (Eviction is excluded here via a largemaxEntriesso the model stays exact; capacity is its own property.) - Capacity —
size()never exceedsmaxEntriesunder any write stream, and LRU eviction (oldestupdatedAt) can never evict the entry that was just written. - Write-version conflicts — a stale
writeVersionloses to a live entry on both the account-index and response-id channels, but the same stale version may rebind the session once the entry expires. - Account-removal splice —
forgetAccount(removed)+reindexAfterRemoval(removed)produce exactly the mapping of an account-array splice (equal indices dropped, higher indices decremented, lower untouched), with both methods' return counts pinned against the model. - Prune exactness —
prune(now)removes exactly the expired entries and is invisible to readers. The subtle case fast-check itself surfaced: sessions touched byupdateLastResponseIdwhile expired are lazily reaped on access, so they must not count as prunable — my initial model missed that and fast-check produced the 8-event counterexample on run 48; the model now mirrors the lazy reap.
No SUT bugs found; the store's documented contract held everywhere.
Validation
- [x]
npm test -- test/property/session-affinity.property.test.ts test/session-affinity.test.ts test/session-affinity-entry.test.ts test/issue-474-affinity-invalidation.test.ts— 43/43 (new 5 + all existing affinity suites untouched) - [x]
npm run typecheck(also via pre-commit hook) - [x]
npx eslint test/property/session-affinity.property.test.ts --max-warnings=0
Docs and Governance Checklist
- [x] Test-only; no behavior or docs surface changed
Risk and Rollback
- Risk level: minimal — additive test file; conventions match the existing
test/property/suites (explicit vitest imports, plainfc.assert). - Rollback plan: revert the single commit.
https://claude.ai/code/session_01XNtnkLbBiXZxfQQYLMpucB
Generated by Claude Code
note: greptile review for oc-chatgpt-multi-auth. cite files like lib/foo.ts:123. confirm regression tests + windows concurrency/token redaction coverage.
Greptile Summary
adds test/property/session-affinity.property.test.ts, a 6-property fast-check suite for SessionAffinityStore driven through injectable now — no fake timers required. it addresses the clearAll coverage gap from the previous review round and fixes the model-divergence bug where lazy reaping during assertions caused responseId to drift.
- property 1 (TTL model): routes all writes through whitespace-decorated keys and uses
liveModel(notmodel.get) so the model correctly reflects lazy reaping afteradvanceevents — the regression fix from round 1. - properties 2–5: cap/LRU, stale-version conflicts, account-array splice, and prune exactness all use injected
nowand stay in sync with the SUT's internal eviction semantics. - property 6 (clearAll): closes the gap called out in the prior round; confirms
size() === 0immediately after and that the store accepts new writes without state corruption.
Confidence Score: 5/5
additive test-only file; no production code is touched, and all 6 properties correctly model the SUT's documented contracts.
the model-divergence fix (using liveModel instead of model.get in the remember branch) correctly handles lazy reaping during the assertion loop. the clearAll property closes the gap from the prior review round. the only open item is a narrow test-coverage gap in property 3 — the stale response-id channel test only exercises the null-baseline case, leaving the non-null preservation path untested — but no SUT bug is present.
test/property/session-affinity.property.test.ts — property 3's response-id stale-overwrite sub-test could be strengthened to catch regressions where a rejected write silently clears an existing response id.
Important Files Changed
| Filename | Overview |
|---|---|
| test/property/session-affinity.property.test.ts | adds 6 fast-check properties covering TTL model equivalence, LRU capacity, stale-version conflicts, splice reindex, prune exactness, and clearAll invalidation; all logic is sound with one minor test-coverage gap in property 3's response-id channel |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[fc.assert arbSequence] --> B{event.kind}
B -->|advance| C[now += ms]
B -->|remember| D[store.remember\nspell key]
B -->|updateResponse| E[store.updateLastResponseId\nspell key]
B -->|forget| F[store.forgetSession\nspell key]
D --> G[liveModel check\npreserve responseId only\nif entry still live]
E --> H{entry live\nin model?}
H -->|yes| I[model: update responseId\n+ refresh expiresAt]
H -->|no| J[model: no-op\nlazy reap on next access]
C --> K[assertion block\nafter every event]
D --> K
E --> K
F --> K
K --> L[for each KEYS\nliveModel vs\nstore.getPreferredAccountIndex\nstore.getLastResponseId]
L --> M{match?}
M -->|yes| N[continue]
M -->|no| O[fast-check\ncounterexample]
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 1
test/property/session-affinity.property.test.ts:159-184
**response-id channel only tests null → null, misses non-null preservation**
the comment on line 171 claims the stale write loses on "both channels," but the response-id sub-test only checks that a stale `updateLastResponseId` can't set a value that was never there (`null → attempt → still null`). the `"resp-fresh" → stale attempt → still "resp-fresh"` path is never exercised — a regression where the rejected write path clobbers an existing id (e.g., clears `lastResponseId` to `undefined` before returning) would pass. to close the gap, call `store.updateLastResponseId("session", "resp-fresh", T0, freshVersion)` before the stale attempt and assert `getLastResponseId` still returns `"resp-fresh"` afterward.
Reviews (2): Last reviewed commit: "test: fix remember model after lazy reap..." | Re-trigger Greptile
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. Credits must be used to enable repository wide code reviews.
[!CAUTION]
Review failed
The pull request is closed.
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 91bc26bb-99d9-4eae-bd45-8f809ecd386b
📥 Commits
Reviewing files that changed from the base of the PR and between fa9bde30aea8a966d717907cb005dea514d59927 and 1c5d836fea4dd4f36b98ff99b57271123a5a4095.
📒 Files selected for processing (1)
test/property/session-affinity.property.test.ts
Cache: Disabled due to data retention organization setting
Knowledge base: Disabled due to data retention organization setting
📝 Walkthrough
Pull Request Summary
Severity: Minor — This is a test-only addition (307 lines) with no production code changes. It adds property-based regression tests for SessionAffinityStore using fast-check, complementing the existing 16 unit tests in the session affinity test suite with 6 new randomized property verifications. No security, data-loss, or production risks.
Details
The PR introduces six property-based tests that verify core SessionAffinityStore invariants across arbitrary event interleavings and key normalizations:
-
TTL/upsert equivalence — Validates that preferred account index and last response ID match a reference TTL model across any sequence of remember/updateResponse/forget/advance operations, with key contracts pinned:
rememberpreserves prior response-id only from live entries, response-id writes refresh TTL, andupdateLastResponseIdnever creates entries. -
LRU capacity enforcement — Ensures
size()never exceedsmaxEntriesand the most recently written live session always survives potential eviction. -
Write-version conflict handling — Confirms stale
writeVersionloses to live entries on both account-index and response-id channels, but may rebind after expiry. -
Account-removal splice semantics — Validates that
forgetAccount()plusreindexAfterRemoval()produce the exact mapping of account-array splice semantics with correct return counts. -
Prune exactness — Verifies
prune(now)removes only expired entries; lazy reaping on read access is correctly invisible to the model (survivors resolvable, pruned sessions read as null). -
ClearAll invalidation — Confirms
clearAll()empties the store and leaves it usable for subsequent writes (referenced to issue#474).
The second commit fixes a model-divergence bug where lazy reaping during test assertions caused responseId to drift; the fix ensures the model only inherits responseId from live entries. The test suite uses injectable now parameters to avoid fake timers and randomized key decorations to verify trim normalization. All 43 tests pass (5 existing affinity tests unchanged).
Walkthrough
adds a vitest property-based test suite (fast-check) for SessionAffinityStore in test/property/session-affinity.property.test.ts. seven property groups cover: ttl reference model, maxEntries eviction, stale writeVersion, forgetAccount/reindexAfterRemoval splice, prune, and clearAll invalidation.
Changes
SessionAffinityStore Property-Based Tests
| Layer / File(s) | Summary |
|---|---|
Test scaffolding: imports, fixtures, arbitraries, event model test/property/session-affinity.property.test.ts |
fixed ttl/time/key constants, key-decoration arbitraries for normalized-spelling coverage, and the randomized event union type (remember, updateResponse, forget, advance) consumed by all property groups. |
TTL reference model invariant test/property/session-affinity.property.test.ts |
primary property replays arbitrary event interleavings against a ttl reference model and asserts getPreferredAccountIndex and getLastResponseId match after every single event step. |
maxEntries enforcement and LRU survival test/property/session-affinity.property.test.ts |
confirms size() never exceeds maxEntries across time-advancing writes and that the most-recently-written live session is always the preferred account for its key. |
rememberWithVersion staleness test/property/session-affinity.property.test.ts |
verifies stale writeVersion cannot overwrite a live entry on either the preferred-account or response-id channel, but can replace an expired entry after ttl elapses. |
forgetAccount / reindexAfterRemoval splice model test/property/session-affinity.property.test.ts |
models an account-array splice, checks return counts from forgetAccount and reindexAfterRemoval, and validates getPreferredAccountIndex reflects splice semantics. |
prune(now) expiry and survivor resolution test/property/session-affinity.property.test.ts |
computes the expected expired set, asserts prune count and size() decrease match, confirms pruned sessions read null, and verifies surviving sessions remain resolvable. |
clearAll() invalidation and post-clear writes test/property/session-affinity.property.test.ts |
asserts clearAll() empties the store and all reads return null, then confirms subsequent remember writes succeed (tied to issue #474 invalidation). |
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~20 minutes
a few things worth flagging while reading test/property/session-affinity.property.test.ts:
missing regression coverage:
test/property/session-affinity.property.test.ts:57— the ttl model test advances virtual time but never exercises arememberfollowed immediately byforgeton the same key within the same tick. a dedicated regression for that zero-duration window would catch off-by-one comparisons in the expiry predicate.- no concurrent write simulation anywhere in the suite. if the store has any shared mutable state (map, lru, version counter), concurrent
remember+pruneinterleaving is unmodeled here. worth flagging explicitly.
windows edge cases:
test/property/session-affinity.property.test.ts:1— key decoration arbitraries look purely ascii. if normalized key paths ever go throughpath.normalizeor similar, windows\vs/can produce divergent lookups. not covered.
prune property:
test/property/session-affinity.property.test.ts:226— the "survivors remain resolvable" check iterates the surviving set after prune. confirm the store doesn't have a secondary index that prune leaves stale; if it does, this property would pass even with a ghost entry.
clearAll operability check:
test/property/session-affinity.property.test.ts:278— post-clearrememberwrite is good, but there's no assertion thatsize()returns 1 after that single write. easy to add and would catch a cleared-but-broken-counter regression.
overall the suite is well-structured and the reference-model approach in test/property/session-affinity.property.test.ts:57 is the right pattern. the gaps above are low-hanging follow-ups, not blockers.
✨ Finishing Touches
📝 Generate docstrings
- [ ] Create stacked PR
- [ ] Commit on current branch
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
- [ ] Commit unit tests in branch
claude/audit-75-session-affinity-property
✨ Simplify code
- [ ] Create PR with simplified code
- [ ] Commit simplified code in branch
claude/audit-75-session-affinity-property
[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
🔧 ESLint
If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.
test/property/session-affinity.property.test.ts
Oops! Something went wrong! :(
ESLint: 10.0.0
Error: The 'jiti' library is required for loading TypeScript configuration files. Make sure to install it. at /node_modules/eslint/lib/config/config-loader.js:145:10 at async loadTypeScriptConfigFileWithJiti (/node_modules/eslint/lib/config/config-loader.js:144:3) at async loadConfigFile (/node_modules/eslint/lib/config/config-loader.js:265:11) at async ConfigLoader.calculateConfigArray (/node_modules/eslint/lib/config/config-loader.js:588:23) at async
#calculateConfigArray(/node_modules/eslint/lib/config/config-loader.js:369:19) at async Promise.all (index 0) at async findFiles (/node_modules/eslint/lib/eslint/eslint-helpers.js:635:25) at async ESLint.lintFiles (/node_modules/eslint/lib/eslint/eslint.js:1014:21) at async Object.execute (/node_modules/eslint/lib/cli.js:386:14) at async main (/node_modules/eslint/bin/eslint.js:175:19)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.