Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(retention): sweep expired dashboard sessions like every other TTL store (#1535)

tashdroid06aa20604ad6
diff --git a/server/src/__tests__/services/request-retention.test.ts b/server/src/__tests__/services/request-retention.test.ts
index 7c3a9d01..f960c9ca 100644
--- a/server/src/__tests__/services/request-retention.test.ts
+++ b/server/src/__tests__/services/request-retention.test.ts
@@ -164,6 +164,28 @@ describe('request analytics retention', () => {
expect((db.prepare("SELECT COUNT(*) AS n FROM response_cache WHERE cache_key = 'cache-live'").get() as { n: number }).n).toBe(1);
});
+ it('sweeps expired dashboard sessions on the prune pass', () => {
+ // Expired session rows used to be uncollectable: validateSession only
+ // deletes the row it is validating, and an expired token is never re-sent,
+ // while every login mints a fresh row. Seed one of each and require the
+ // prune to take only the expired half.
+ const db = getDb();
+ const now = new Date('2026-05-31T00:00:00Z').getTime();
+ const userId = db
+ .prepare("INSERT INTO users (email, password_hash) VALUES ('[email protected]', 'x')")
+ .run().lastInsertRowid as number;
+ const session = db.prepare(
+ 'INSERT INTO sessions (token_hash, user_id, expires_at_ms) VALUES (?, ?, ?)',
+ );
+ session.run('hash-expired-session', userId, now - 1000);
+ session.run('hash-live-session', userId, now + 3600_000);
+
+ const result = pruneRequestAnalytics({ db, force: true, now: new Date(now) });
+ expect(result.deleted).toBe(1);
+ expect((db.prepare("SELECT COUNT(*) AS n FROM sessions WHERE token_hash = 'hash-expired-session'").get() as { n: number }).n).toBe(0);
+ expect((db.prepare("SELECT COUNT(*) AS n FROM sessions WHERE token_hash = 'hash-live-session'").get() as { n: number }).n).toBe(1);
+ });
+
it('bounds the web-search attempt log by age and count', () => {
process.env.SEARCH_LOGS_RETENTION_DAYS = '7';
process.env.SEARCH_LOGS_MAX_ROWS = '2';
diff --git a/server/src/services/request-retention.ts b/server/src/services/request-retention.ts
index 0d6517ce..8ed4dd3a 100644
--- a/server/src/services/request-retention.ts
+++ b/server/src/services/request-retention.ts
@@ -219,25 +219,34 @@ export function pruneServerLogs(db: RetentionDb, nowMs: number): number {
}
/**
- * Sweep expired rows from the two short-lived replay stores.
+ * Sweep expired rows from the short-lived replay stores and the session table.
*
- * Both tables are write-once with a TTL that readers already filter on
- * (`expires_at_ms > now`), and both are indexed on `expires_at_ms`. Neither
- * had a sweeper: `storeIdempotencyResult` only deletes expired rows for the
- * SAME key hash it is about to overwrite, so a claim whose hash never repeats
- * — the common case, since clients send a fresh UUID per request — sat in the
- * DB forever with its full response JSON. A busy install replaying
- * Idempotency-Key traffic grew this table monotonically. `response_cache`
- * swept expired rows only at startup, so a long-running server accumulated
- * them between restarts too.
+ * idempotency_claims and response_cache are write-once with a TTL that readers
+ * already filter on (`expires_at_ms > now`), and both are indexed on
+ * `expires_at_ms`. Neither had a sweeper: `storeIdempotencyResult` only deletes
+ * expired rows for the SAME key hash it is about to overwrite, so a claim
+ * whose hash never repeats — the common case, since clients send a fresh UUID
+ * per request — sat in the DB forever with its full response JSON. A busy
+ * install replaying Idempotency-Key traffic grew this table monotonically.
+ * `response_cache` swept expired rows only at startup, so a long-running
+ * server accumulated them between restarts too.
*
- * The deletes are plain index-range walks over `expires_at_ms`, so cost scales
- * with what is actually expired. Guarded against the tables being absent the
- * same way every other prune here is.
+ * `sessions` joins the sweep for the same reason (#1510-era retention series):
+ * validateSession only deletes a row when its OWN token is checked again — and
+ * an expired token is by definition never re-sent — while login mints a new
+ * row per sign-in (30-day TTL). Desktop installs that mint a session on every
+ * dashboard load leak one row per load. Expired rows are dead weight for every
+ * reader (validateSession filters on expires_at_ms), so deleting them is safe.
+ * sessions has no index on expires_at_ms; the delete is a scan of a table that
+ * is at most a few hundred rows on any install, once per prune gate.
+ *
+ * The claims/cache deletes are plain index-range walks over `expires_at_ms`,
+ * so cost scales with what is actually expired. Guarded against the tables
+ * being absent the same way every other prune here is.
*/
export function pruneExpiredClaims(db: RetentionDb, nowMs: number): number {
let deleted = 0;
- for (const table of ['idempotency_claims', 'response_cache'] as const) {
+ for (const table of ['idempotency_claims', 'response_cache', 'sessions'] as const) {
const present = db
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?")
.get(table);
@@ -321,8 +330,9 @@ export function pruneRequestAnalytics(options: {
// Persisted server logs, on the same 60s gate as the requests prune above.
deleted += pruneServerLogs(db, nowMs);
- // Expired idempotency claims and cache rows, on the same 60s gate. Both are
- // TTL'd replay stores with no reader past expiry and no other sweeper.
+ // Expired idempotency claims, cache rows and dashboard sessions, on the
+ // same 60s gate. All are TTL'd stores with no reader past expiry and no
+ // other sweeper.
deleted += pruneExpiredClaims(db, nowMs);
// Web-search attempt log, same gate (see pruneSearchLogs).
deleted += pruneSearchLogs(db, nowMs);