The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Lag-tolerant reads go to the idle secondaries (#3043)
harness-for-autonomous[bot]617a08215768
diff --git a/backend/integration/atlasSnapshot.test.ts b/backend/integration/atlasSnapshot.test.tsindex cc9de2fd1..bf85daf4c 100644--- a/backend/integration/atlasSnapshot.test.ts+++ b/backend/integration/atlasSnapshot.test.ts@@ -22,14 +22,15 @@ type Seen = { method: string; path: string; query: URLSearchParams; accept?: strconst PROCESSES = [{ id: 'autonomous-code-prod-shard-00-00.x.mongodb.net:27017', hostname: 'autonomous-code-prod-shard-00-00.x.mongodb.net', port: 27017, typeName: 'REPLICA_PRIMARY', userAlias: 'autonomous-code-prod-shard-00-00.x.mongodb.net' },{ id: 'autonomous-code-prod-shard-00-01.x.mongodb.net:27017', hostname: 'autonomous-code-prod-shard-00-01.x.mongodb.net', port: 27017, typeName: 'REPLICA_SECONDARY', userAlias: 'autonomous-code-prod-shard-00-01.x.mongodb.net' },+ { id: 'autonomous-code-prod-shard-00-02.x.mongodb.net:27017', hostname: 'autonomous-code-prod-shard-00-02.x.mongodb.net', port: 27017, typeName: 'REPLICA_SECONDARY', userAlias: 'autonomous-code-prod-shard-00-02.x.mongodb.net' },{ id: 'other-cluster-shard-00-00.x.mongodb.net:27017', hostname: 'other-cluster-shard-00-00.x.mongodb.net', port: 27017, typeName: 'REPLICA_PRIMARY', userAlias: 'other-cluster-shard-00-00.x.mongodb.net' },]/** Two points a metric: CPU 40 then 80 on the primary, so the average is 60 and the peak 80. */function measurements(processId: string, metrics: string[]) {- const primary = processId === PROCESSES[0]!.id+ const primary = processId === PROCESSES[0]!.id, second = processId === PROCESSES[2]!.idconst values: Record<string, [number, number]> = {- PROCESS_NORMALIZED_CPU_USER: primary ? [30, 70] : [5, 5], PROCESS_NORMALIZED_CPU_KERNEL: primary ? [10, 10] : [1, 1],+ PROCESS_NORMALIZED_CPU_USER: primary ? [30, 70] : second ? [8, 12] : [5, 5], PROCESS_NORMALIZED_CPU_KERNEL: primary ? [10, 10] : second ? [2, 2] : [1, 1],OPCOUNTER_QUERY: [600, 800], NETWORK_BYTES_OUT: [10_000_000, 20_000_000], QUERY_TARGETING_SCANNED_OBJECTS_PER_RETURNED: [2, 3],}return { processId, granularity: 'PT5M', measurements: metrics.map(name => ({ name, units: 'SCALAR',@@ -147,7 +148,7 @@ describe('runSnapshot', () => {expect(result).toEqual({ ok: true, skipped: [], failed: [] })// Only the named cluster's processes, a day at 5-minute points, every metric the roadmap lists.const asked = seen.filter(s => s.path.endsWith('/measurements') && s.auth?.startsWith('Digest '))- expect(asked.map(s => decodeURIComponent(s.path.split('/')[7]!)).sort()).toEqual([PROCESSES[0]!.id, PROCESSES[1]!.id])+ expect(asked.map(s => decodeURIComponent(s.path.split('/')[7]!)).sort()).toEqual([PROCESSES[0]!.id, PROCESSES[1]!.id, PROCESSES[2]!.id])expect(asked[0]!.query.get('granularity')).toBe('PT5M')expect(asked[0]!.query.get('period')).toBe('P1D')expect(asked[0]!.query.getAll('m')).toEqual(expect.arrayContaining(['PROCESS_NORMALIZED_CPU_USER', 'OPCOUNTER_QUERY', 'DOCUMENT_METRICS_RETURNED',@@ -161,6 +162,11 @@ describe('runSnapshot', () => {// CPU is user + kernel: (30+10, 70+10) → average 60, peak 80.expect(summary.primary.PROCESS_CPU).toEqual({ average: 60, peak: 80, latest: 80 })expect(summary.primary.OPCOUNTER_QUERY).toEqual({ average: 700, peak: 800, latest: 800 })+ // Each secondary's CPU beside the primary's (task #2970): the reads moved off the primary land there.+ expect(summary.secondaries).toEqual([+ { process: PROCESSES[1]!.id, cpu: { average: 6, peak: 6, latest: 6 } },+ { process: PROCESSES[2]!.id, cpu: { average: 12, peak: 14, latest: 14 } },+ ])// 30 s and 40 s in the same minute, then 0.5 s: 70.5 s in all, 70 s in the worst minute; the unreadable line counted.expect(summary.slowOps).toMatchObject({ count: 3, unreadable: 1, totalSeconds: 70.5, peakSecondsPerMinute: 70 })expect(summary.slowOps.top[0]).toMatchObject({ ns: 'prod.users', op: 'find', shape: '{"autonomousEnv":"?","email":"?"}', count: 3, seconds: 70.5 })@@ -176,6 +182,8 @@ describe('runSnapshot', () => {expect(port(sizes.readFrom)).not.toBe(port(sizes.primary))const markdown = await readFile(join(out, 'summary.md'), 'utf8')expect(markdown).toContain('| Process CPU (%) | 60 | 80 | 80 |')+ expect(markdown).toContain('| Secondary CPU (%), autonomous-code-prod-shard-00-01 | 6 | 6 | 6 |')+ expect(markdown).toContain('| Secondary CPU (%), autonomous-code-prod-shard-00-02 | 12 | 14 | 14 |')expect(printed.join('\n')).toContain(out)expect(printed.join('\n')).not.toMatch(/priv-secret|pub-key/)})@@ -255,7 +263,8 @@ describe('compareSnapshots', () => {const write = async (name: string, cpu: number, slow: number) => {await mkdir(join(dir, name))await writeFile(join(dir, name, 'summary.json'), JSON.stringify({ label: name, takenAt: '2026-10-29T08:00:00.000Z',- primary: { PROCESS_CPU: { average: cpu, peak: cpu * 2, latest: cpu } }, slowOps: { count: 1, totalSeconds: slow, peakSecondsPerMinute: slow, unreadable: 0, top: [] },+ primary: { PROCESS_CPU: { average: cpu, peak: cpu * 2, latest: cpu } },+ secondaries: [{ process: 'b:27017', cpu: { average: 80 - cpu, peak: 90 - cpu, latest: 1 } }, { process: 'c:27017', cpu: { average: 15, peak: 20, latest: 1 } }], slowOps: { count: 1, totalSeconds: slow, peakSecondsPerMinute: slow, unreadable: 0, top: [] },sizes: { collections: [], dataBytes: 100, indexBytes: 50 } }))return join(dir, name)}@@ -263,5 +272,7 @@ describe('compareSnapshots', () => {JSON.parse(await readFile(join(await write('after', 10, 6), 'summary.json'), 'utf8')))expect(table).toContain('| Process CPU (%), average | 40 | 10 | -75% |')expect(table).toContain('| Slow operations, seconds | 60 | 6 | -90% |')+ expect(table).toContain('| Secondary 1 CPU (%), average | 40 | 70 | +75% |')+ expect(table).toContain('| Secondary 2 CPU (%), peak | 20 | 20 | +0% |')})})diff --git a/backend/integration/queryStats.test.ts b/backend/integration/queryStats.test.tsindex e75112348..db4b14b8e 100644--- a/backend/integration/queryStats.test.ts+++ b/backend/integration/queryStats.test.ts@@ -133,3 +133,17 @@ it('logs every interval once started, flushes the last window on stop, and recorawait new Promise(resolve => setTimeout(resolve, 120))expect(lines).toHaveLength(after)})++it('names the secondary client\'s queries apart, so `db by shape` tells the reads it moved off the primary', async () => {+ const someone = person()+ await db.user.create({ data: someone })+ const secondary = withQueryStats(base, () => stats, undefined, undefined, 'secondary')+ await runWork('http GET /api/users/:id', async () => {+ await secondary.user.findMany({ where: { email: someone.email } })+ await secondary.$runCommandRaw({ ping: 1 })+ })+ const ops = flushed().map(r => r.op)+ expect(ops).toContain('secondary:User.findMany')+ expect(ops).toContain('secondary:-.$runCommandRaw ping')+ expect(ops).not.toContain('User.findMany')+})diff --git a/backend/integration/secondaryReads.test.ts b/backend/integration/secondaryReads.test.tsnew file mode 100644index 000000000..0147029cd--- /dev/null+++ b/backend/integration/secondaryReads.test.ts@@ -0,0 +1,209 @@+import { randomUUID } from 'node:crypto'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient, type Prisma } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { secondaryReadsUrl } from '../src/lib/databaseUrl.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import type { Command } from '../src/superTabs/commands.js'+import { heldPast } from '../src/superTabs/pageReads.js'+import { plan, planDatabase, profiled, reads } from './plans.test-support.js'++// Task #2970: the reads that tolerate a few seconds of lag go to the secondary client, everything that must see the latest+// write stays on the primary. A single-node replica set: the secondary client's `secondaryPreferred` reads its one member,+// so a moved read must return exactly the rows the primary gives.+let replica: MongoMemoryReplSet+let uri: string+let db: PrismaClient+const clients: PrismaClient[] = []+const owner: AuthUser = { sub: '510000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const host: AuthUser = { sub: '510000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }++type Op = { model: string; operation: string; args: unknown }+/** A client that keeps the operations it sends, by model and action. */+function recorded(base: PrismaClient): { client: PrismaClient; ops: Op[] } {+ const ops: Op[] = []+ const client = base.$extends({ query: { async $allOperations({ model, operation, args, query }) {+ ops.push({ model: model ?? '-', operation, args })+ return query(args)+ } } }) as unknown as PrismaClient+ return { client, ops }+}+const client = (url: string) => { const made = new PrismaClient({ datasources: { db: { url } } }); clients.push(made); return made }+const models = (ops: Op[]) => [...new Set(ops.map(o => o.model))].sort()+/** The message reads among `ops` that page by sequence: an older or newer page's batches. */+const pageBatches = (ops: Op[]) => ops.filter(o => o.model === 'SuperTabMessage' && JSON.stringify(o.args).includes('"sequence":{'))++beforeAll(async () => {+ ({ replica, db, uri } = await planDatabase('secondary_reads_test'))+ for (const user of [owner, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: 'prod', name: user.email.split('@')[0] } })+ await db.machine.create({ data: { machineId: 'test-host', userId: host.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId: 'test-host', ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })+})+afterAll(async () => {+ await Promise.allSettled([db?.$disconnect(), ...clients.map(c => c.$disconnect())])+ await replica?.stop()+})++/** A store whose primary and secondary clients each record what they read; [secondaryUrl] is where the secondary reads. */+function stores(secondaryUrl = secondaryReadsUrl(uri)) {+ const primary = recorded(client(uri)), secondary = recorded(client(secondaryUrl))+ const store = new SuperTabStore(primary.client, Date.now, null, { replica: secondary.client })+ const clear = () => { primary.ops.length = 0; secondary.ops.length = 0 }+ return { store, reads: new SwarmReads(store), primary: primary.ops, secondary: secondary.ops, clear }+}++async function fixture(store: SuperTabStore) {+ const run = (command: Command) => store.execute(owner, tab, { operationId: randomUUID(), command })+ const tab = (await store.create(owner, randomUUID(), 'Secondary reads')).id+ await run({ type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(), name: 'Lead', configuration: config, lead: true })+ const rows: Prisma.SuperTabMessageCreateManyInput[] = Array.from({ length: 250 }, (_, i) => {+ const id = `${tab}-m${String(i).padStart(4, '0')}`+ return { id, tabId: tab, conversationId: 'lead', sequence: 1000 + i, author: { kind: 'person', id: owner.sub, name: owner.email, membershipGeneration: 'g' },+ text: `row ${i}`, replyTo: null, recipientIds: [], mentions: [], thread: id }+ })+ await db.superTabMessage.createMany({ data: rows })+ return { tab, run }+}++const ids = (page: { messages: Array<{ id: string }> }) => page.messages.map(m => m.id)++describe('older history pages', () => {+ it('read their rows on the secondary, the same rows the primary gives, and their access on the primary', async () => {+ const s = stores()+ const { tab } = await fixture(s.store)+ const only = new SuperTabStore(db)+ const newest = await s.store.messages(owner, tab, 'lead', {})+ s.clear()+ const older = await s.store.messages(owner, tab, 'lead', { before: newest.next!.sequence, beforeId: newest.next!.id })+ expect(ids(older)).toEqual(ids(await only.messages(owner, tab, 'lead', { before: newest.next!.sequence, beforeId: newest.next!.id })))+ expect(ids(older)).toHaveLength(100)+ expect(pageBatches(s.secondary).length).toBeGreaterThan(0)+ expect(pageBatches(s.primary)).toEqual([])+ // What decides what this reader may see: the Swarm and its parts, read on the primary only.+ expect(models(s.secondary).filter(m => !['SuperTabDelivery', 'SuperTabMessage', 'SuperTabReaction', 'SuperTabReceipt', 'SuperTabThread'].includes(m))).toEqual([])+ expect(models(s.primary).length).toBeGreaterThan(0)++ // The oldest page, which reaches the end, and a thread's older page read the same way.+ s.clear()+ const oldest = await s.store.messages(owner, tab, 'lead', { before: older.next!.sequence, beforeId: older.next!.id })+ expect(ids(oldest)).toEqual(ids(await only.messages(owner, tab, 'lead', { before: older.next!.sequence, beforeId: older.next!.id })))+ expect(oldest.next).toBeNull()+ expect(pageBatches(s.primary)).toEqual([])+ })++ it('read a page without the edge id on the secondary too', async () => {+ const s = stores()+ const { tab } = await fixture(s.store)+ const only = new SuperTabStore(db)+ s.clear()+ const older = await s.store.messages(owner, tab, 'lead', { before: 1100 })+ expect(ids(older)).toEqual(ids(await only.messages(owner, tab, 'lead', { before: 1100 })))+ expect(ids(older).at(-1)).toBe(`${tab}-m0099`)+ expect(pageBatches(s.primary)).toEqual([])+ })++ it('read on the primary when the secondary does not hold the row the reader pages from yet, so lag never skips a row', async () => {+ // A secondary that holds nothing yet: another database on the same server.+ const behind = secondaryReadsUrl(uri.replace(/\/([^/?]+)(\?|$)/, `/behind_${randomUUID().replaceAll('-', '_')}$2`))+ const s = stores(behind)+ const { tab } = await fixture(s.store)+ const only = new SuperTabStore(db)+ const newest = await s.store.messages(owner, tab, 'lead', {})+ s.clear()+ const older = await s.store.messages(owner, tab, 'lead', { before: newest.next!.sequence, beforeId: newest.next!.id })+ expect(ids(older)).toEqual(ids(await only.messages(owner, tab, 'lead', { before: newest.next!.sequence, beforeId: newest.next!.id })))+ expect(ids(older)).toHaveLength(100)+ expect(pageBatches(s.primary).length).toBeGreaterThan(0)+ })+})++describe('the edge check', () => {+ it('reads the page and its edge through the conversation\'s sequence index, about the rows it returns', async () => {+ const s = stores()+ const { tab } = await fixture(s.store)+ const entries = await profiled(db, () => heldPast(db, { tabId: tab, conversationId: 'lead' }, { sequence: 1200, id: `${tab}-m0200` }, 101))+ const rows = reads(entries, 'SuperTabMessage', ['sequence'])+ expect(rows).toHaveLength(1)+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, conversationId: 1, sequence: 1/)+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(102)+ })++ it('leaves to the primary an edge whose row it lacks, a row at the edge that is not the reader\'s, and two rows at one sequence', async () => {+ const s = stores()+ const { tab } = await fixture(s.store)+ const at = { tabId: tab, conversationId: 'lead' }+ expect(await heldPast(db, at, { sequence: 5000 }, 10)).toBeNull()+ expect(await heldPast(db, at, { sequence: 1200, id: `${tab}-m0199` }, 10)).toBeNull()+ await db.superTabMessage.create({ data: { id: `${tab}-twin`, tabId: tab, conversationId: 'lead', sequence: 1200,+ author: { kind: 'person', id: owner.sub, name: owner.email, membershipGeneration: 'g' }, text: 'twin', recipientIds: [], mentions: [] } })+ expect(await heldPast(db, at, { sequence: 1200, id: `${tab}-twin` }, 10)).toBeNull()+ expect((await heldPast(db, at, { sequence: 1100, id: `${tab}-m0100` }, 10))!.map(m => m.sequence)).toEqual([1099, 1098, 1097, 1096, 1095, 1094, 1093, 1092, 1091, 1090])+ })+})++describe('reads that must see the latest write', () => {+ it('stay on the primary: the newest page, a newer page, one message, the change feed and a write with its reads', async () => {+ const s = stores()+ const { tab, run } = await fixture(s.store)+ s.clear()+ const first = await s.reads.firstLoad(owner, tab)+ const newest = await s.store.messages(owner, tab, 'lead', {})+ await s.store.messages(owner, tab, 'lead', { after: 1200, afterId: `${tab}-m0200` })+ await s.store.messages(owner, tab, 'lead', { messageId: `${tab}-m0010` })+ await run({ type: 'message.send', conversationId: 'lead', text: 'a new one', replyTo: null, recipientIds: [] })+ const changed = await s.reads.changes(owner, tab, first.cursor)+ expect(newest.messages).toHaveLength(100)+ expect(changed).toBeTruthy()+ expect(s.secondary).toEqual([])+ expect(pageBatches(s.primary).length).toBeGreaterThan(0)+ })+})++describe('reports', () => {+ it('costs read their decisions on the secondary and who may read them on the primary', async () => {+ const s = stores()+ const { tab } = await fixture(s.store)+ s.clear()+ const summary = await s.store.costSummary(owner, tab, 7)+ expect(summary).toMatchObject({ days: 7, truncated: false })+ expect(models(s.secondary)).toEqual(['SuperTabRouteDecision'])+ expect(s.primary.some(o => o.model === 'SuperTabRouteDecision')).toBe(false)+ })++ it('the leaderboard reads its people\'s names on the secondary', async () => {+ const s = stores()+ const { tab } = await fixture(s.store)+ s.clear()+ const board = await s.reads.leaderboard(owner, tab, 'lead')+ expect(board).toBeTruthy()+ expect(models(s.secondary)).toEqual(['User'])+ expect(s.primary.some(o => o.model === 'User' && o.operation === 'findMany')).toBe(false)+ })+})++describe('on a replica set with secondaries', () => {+ it('the secondary client\'s reads are served by a secondary, the main client\'s by the primary', async () => {+ const three = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 3, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ try {+ await three.waitUntilRunning()+ const url = three.getUri(`three_${randomUUID().replaceAll('-', '_')}`)+ const main = client(url), secondary = client(secondaryReadsUrl(url))+ await main.user.create({ data: { externalId: `fixture-${randomUUID()}`, email: `${randomUUID()}@example.com`, autonomousEnv: 'prod' } })+ const { primary } = await main.$runCommandRaw({ hello: 1 }) as unknown as { primary: string }+ // $collStats names the member that answered.+ const host = async (db: PrismaClient) => (await db.user.aggregateRaw({ pipeline: [{ $collStats: { count: {} } }] }) as unknown as Array<{ host: string }>)[0]!.host+ const port = (address: string) => address.split(':').at(-1)+ expect(port(await host(main))).toBe(port(primary))+ // A secondary answers once the collection has replicated to it.+ await expect.poll(async () => port(await host(secondary)), { timeout: 20_000 }).not.toBe(port(primary))+ } finally {+ await three.stop()+ }+ }, 120_000)+})diff --git a/backend/scripts/atlas-snapshot.ts b/backend/scripts/atlas-snapshot.tsindex 7a5983eff..07952e689 100644--- a/backend/scripts/atlas-snapshot.ts+++ b/backend/scripts/atlas-snapshot.ts@@ -52,8 +52,11 @@ export type SlowSummary = { count: number; unreadable: number; totalSeconds: numtop: { ns: string; op: string; shape: string; count: number; seconds: number }[] }export type Sizes = { primary: string; readFrom: string; dataBytes: number; indexBytes: numbercollections: { name: string; count: number; dataBytes: number; storageBytes: number; indexBytes: number; nindexes: number }[] }+/** A secondary's process CPU (user + kernel) over the day, by its process id: where the reads moved off the primary land+ * (task #2970). */+export type SecondaryCpu = { process: string; cpu: Stat }export type Summary = { label: string; takenAt: string; skipped: string[]; failed: string[]; primaryProcess?: string- primary?: Record<string, Stat>; units?: Record<string, string>; slowOps?: SlowSummary; sizes?: Sizes }+ primary?: Record<string, Stat>; units?: Record<string, string>; secondaries?: SecondaryCpu[]; slowOps?: SlowSummary; sizes?: Sizes }/* ---------- safety ---------- */@@ -223,8 +226,12 @@ async function snapshotAtlas(get: ReturnType<typeof atlasClient>, groupId: strin}}const primaryProcess = processes.find(p => p.typeName === 'REPLICA_PRIMARY') ?? processes[0]!+ const secondaries = processes.filter(p => p.id !== primaryProcess.id).sort((a, b) => a.id.localeCompare(b.id)).flatMap(p => {+ const cpu = summarizeMeasurements(measurements[p.id] ?? []).primary.PROCESS_CPU+ return cpu ? [{ process: p.id, cpu }] : []+ })return { processes, measurements, slow, primaryProcess: primaryProcess.id, ...summarizeMeasurements(measurements[primaryProcess.id] ?? []),- slowOps: summarizeSlow(Object.values(slow).flat(), unreadable) }+ secondaries, slowOps: summarizeSlow(Object.values(slow).flat(), unreadable) }}/* ---------- sizes from a secondary ---------- */@@ -271,6 +278,10 @@ function markdown(summary: Summary): string {const f = label.includes('MB') ? (BYTES[summary.units?.[name] ?? ''] ?? 1) * factor : factorlines.push(`| ${label} | ${fmt(s.average * f)} | ${fmt(s.peak * f)} | ${fmt(s.latest * f)} |`)}+ // Each secondary by its host's name, without the domain the primary's row already names.+ for (const { process, cpu } of summary.secondaries ?? []) {+ lines.push(`| Secondary CPU (%), ${process.split(/[.:]/)[0]} | ${fmt(cpu.average)} | ${fmt(cpu.peak)} | ${fmt(cpu.latest)} |`)+ }lines.push('')}if (summary.slowOps) {@@ -303,7 +314,8 @@ export async function runSnapshot({ env, out, label, now = Date.now(), print = celse {try {const atlas = await snapshotAtlas(atlasClient(base, auth), env.ATLAS_GROUP_ID, env.ATLAS_CLUSTER, now)- Object.assign(summary, { primaryProcess: atlas.primaryProcess, primary: atlas.primary, units: atlas.units, slowOps: atlas.slowOps })+ Object.assign(summary, { primaryProcess: atlas.primaryProcess, primary: atlas.primary, units: atlas.units, secondaries: atlas.secondaries,+ slowOps: atlas.slowOps })files['measurements.json'] = { processes: atlas.processes, measurements: atlas.measurements }files['slow-queries.json'] = atlas.slow} catch (error) {@@ -341,6 +353,11 @@ export function compareSnapshots(before: Summary, after: Summary): string {if (b !== undefined || a !== undefined) rows.push([`${label}, ${key}`, b === undefined ? b : b * f, a === undefined ? a : a * f])}}+ // Secondaries in host order: a failover can swap which member is which, so compare them by place.+ const secondaries = Math.max(before.secondaries?.length ?? 0, after.secondaries?.length ?? 0)+ for (let i = 0; i < secondaries; i++) {+ for (const key of ['average', 'peak'] as const) rows.push([`Secondary ${i + 1} CPU (%), ${key}`, before.secondaries?.[i]?.cpu[key], after.secondaries?.[i]?.cpu[key]])+ }rows.push(['Slow operations, seconds', before.slowOps?.totalSeconds, after.slowOps?.totalSeconds],['Slow operations, worst minute (s)', before.slowOps?.peakSecondsPerMinute, after.slowOps?.peakSecondsPerMinute],['Data (MB)', before.sizes && before.sizes.dataBytes / 1e6, after.sizes && after.sizes.dataBytes / 1e6],diff --git a/backend/src/config/env.ts b/backend/src/config/env.tsindex 8af13ab54..e4020abf3 100644--- a/backend/src/config/env.ts+++ b/backend/src/config/env.ts@@ -17,6 +17,10 @@ const envSchema = z.object({// Same MongoDB (and database) as the agent-manager — backend owns `users` +// `machines`; reads `managers`/`machine_nodes` via raw queries when needed.DATABASE_URL: z.string().default('mongodb://localhost:27017/harness?replicaSet=rs0'),+ // The reads that tolerate a few seconds of lag (older history pages, costs, search, usage totals) go to the secondaries+ // through a second client on DATABASE_URL (lib/prisma.ts prismaSecondary, task #2970). 'off' sends them back to the+ // primary at the next start, with no code change.+ DATABASE_SECONDARY_READS: z.enum(['on', 'off']).default('on'),// Redis for the cross-instance data bus. Behind a load balancer an agent's web socket and its// manager socket may land on different backend instances; Redis pub/sub bridges themdiff --git a/backend/src/lib/analyticsQuery.test.ts b/backend/src/lib/analyticsQuery.test.tsnew file mode 100644index 000000000..00f83bcd9--- /dev/null+++ b/backend/src/lib/analyticsQuery.test.ts@@ -0,0 +1,21 @@+import { beforeEach, expect, it, vi } from 'vitest'++const m = vi.hoisted(() => {+ const table = () => ({ findMany: vi.fn(async () => []) })+ return { primary: { machine: table(), analyticsDailyBucket: table(), analyticsDailyMachine: table(), analyticsMachineState: table() },+ secondary: { machine: table(), analyticsDailyBucket: table(), analyticsDailyMachine: table(), analyticsMachineState: table() } }+})+vi.mock('./prisma.js', () => ({ prisma: m.primary, prismaSecondary: m.secondary, machineAlive: {} }))+import { analyticsOverview } from './analyticsQuery.js'++beforeEach(() => vi.clearAllMocks())++it('reads the usage totals on the secondaries and which machines are the person\'s on the primary (task #2970)', async () => {+ await analyticsOverview({ userId: 'u1', days: 7, now: new Date('2026-11-04T12:00:00Z') })+ for (const model of ['analyticsDailyBucket', 'analyticsDailyMachine', 'analyticsMachineState'] as const) {+ expect(m.secondary[model].findMany).toHaveBeenCalledOnce()+ expect(m.primary[model].findMany).not.toHaveBeenCalled()+ }+ expect(m.primary.machine.findMany).toHaveBeenCalledOnce()+ expect(m.secondary.machine.findMany).not.toHaveBeenCalled()+})diff --git a/backend/src/lib/analyticsQuery.ts b/backend/src/lib/analyticsQuery.tsindex 25dcb7001..97d2889a7 100644--- a/backend/src/lib/analyticsQuery.ts+++ b/backend/src/lib/analyticsQuery.ts@@ -12,7 +12,7 @@* - `AnalyticsDailyMachine.wallClockActiveMs` is summed across machines only under the label* "sum across machines". It is a union within a machine and cannot become a union across them.*/-import { prisma } from './prisma.js'+import { prisma, prismaSecondary } from './prisma.js'import { machineAlive } from './prisma.js'import {MIN_DAYS_FOR_BASELINE,@@ -131,18 +131,19 @@ export async function analyticsOverview(opts: OverviewOptions): Promise<Analyticconst machineFilter = opts.machineId ? { machineId: opts.machineId } : {}+ // The totals are days of rollups, read on the secondaries (task #2970); which machines are the person's, on the primary.const [machineRows, buckets, machineDays, states] = await Promise.all([prisma.machine.findMany({where: { userId: opts.userId, ...machineFilter, ...machineAlive },select: { machineId: true, name: true, hostname: true, authMode: true, billingStatus: true },}),- prisma.analyticsDailyBucket.findMany({+ prismaSecondary.analyticsDailyBucket.findMany({where: { userId: opts.userId, ...machineFilter, dayUtc: { gte: fromDay, lte: toDay } },}),- prisma.analyticsDailyMachine.findMany({+ prismaSecondary.analyticsDailyMachine.findMany({where: { userId: opts.userId, ...machineFilter, dayUtc: { gte: fromDay, lte: toDay } },}),- prisma.analyticsMachineState.findMany({ where: { userId: opts.userId, ...machineFilter } }),+ prismaSecondary.analyticsMachineState.findMany({ where: { userId: opts.userId, ...machineFilter } }),])const stateByMachine = new Map(states.map((s) => [s.machineId, s]))diff --git a/backend/src/lib/communityFeed.ts b/backend/src/lib/communityFeed.tsindex b998c6879..352bcbd2d 100644--- a/backend/src/lib/communityFeed.ts+++ b/backend/src/lib/communityFeed.ts@@ -1,4 +1,5 @@import { likeCounts, likesSince } from './communityLikes.js'+import type { PrismaClient } from '@prisma/client'import { prisma } from './prisma.js'export const feedSorts = ['newest', 'trending', 'popular'] as const@@ -12,8 +13,8 @@ type FeedWhere = NonNullable<NonNullable<Parameters<typeof prisma.communityHarneconst newest = [{ createdAt: 'desc' as const }, { id: 'desc' as const }]/** One page newest first, the indexed order, after the last id read. One row more tells whether there is another page. */-function newestPage(where: FeedWhere, cursor?: string) {- return prisma.communityHarness.findMany({+function newestPage(db: PrismaClient, where: FeedWhere, cursor?: string) {+ return db.communityHarness.findMany({where, select: feedSelect, orderBy: newest, take: feedPageSize + 1,...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),})@@ -26,11 +27,11 @@ type Ranked = { id: string; likes: number }* Among equal likes publications come first, newest first, then the starters in the Hub's order. A* cursor that has since gone ends the feed rather than starting it over.*/-async function after(where: FeedWhere, starters: Ranked[], cursor?: string): Promise<{ next: FeedWhere; starters: Ranked[] } | null> {+async function after(db: PrismaClient, where: FeedWhere, starters: Ranked[], cursor?: string): Promise<{ next: FeedWhere; starters: Ranked[] } | null> {if (!cursor) return { next: {}, starters }const at = starters.findIndex(starter => starter.id === cursor)if (at >= 0) return { next: { likeCount: { lt: starters[at].likes } }, starters: starters.slice(at + 1) }- const last = await prisma.communityHarness.findFirst({ where: { AND: [where, { id: cursor }] }, select: { likeCount: true, createdAt: true } })+ const last = await db.communityHarness.findFirst({ where: { AND: [where, { id: cursor }] }, select: { likeCount: true, createdAt: true } })if (!last) return nullconst { likeCount, createdAt } = lastreturn {@@ -44,13 +45,13 @@ async function after(where: FeedWhere, starters: Ranked[], cursor?: string): Pro* examples, which are not stored here — are ranked alongside, after publications with as many likes,* so the page's order names them too.*/-async function popularPage(where: FeedWhere, autonomousEnv: string, starters: readonly string[], cursor?: string) {+async function popularPage(db: PrismaClient, where: FeedWhere, autonomousEnv: string, starters: readonly string[], cursor?: string) {const counts = await likeCounts(starters, autonomousEnv)// Array sort is stable, so equals keep the Hub's order.const ranked = starters.map(id => ({ id, likes: counts.get(id) ?? 0 })).sort((a, b) => b.likes - a.likes)- const start = await after(where, ranked, cursor)+ const start = await after(db, where, ranked, cursor)if (!start) return { rows: [], order: [] }- const found = await prisma.communityHarness.findMany({+ const found = await db.communityHarness.findMany({where: { AND: [where, start.next] }, select: { ...feedSelect, likeCount: true },orderBy: [{ likeCount: 'desc' }, ...newest], take: feedPageSize + 1,})@@ -70,9 +71,9 @@ const trendingWindowMs = 7 * 24 * 60 * 60 * 1000* this week. The week's likes are few, so they are ranked here; the rest is the newest feed's keyset.* A cursor that moved since (a publication liked this week after it was read) may repeat a few cards.*/-async function trendingPage(where: FeedWhere, autonomousEnv: string, starters: readonly string[], cursor?: string) {+async function trendingPage(db: PrismaClient, where: FeedWhere, autonomousEnv: string, starters: readonly string[], cursor?: string) {const recent = await likesSince(autonomousEnv, new Date(Date.now() - trendingWindowMs))- const liked = await prisma.communityHarness.findMany({ where: { AND: [where, { id: { in: [...recent.keys()] } }] }, select: feedSelect, orderBy: newest })+ const liked = await db.communityHarness.findMany({ where: { AND: [where, { id: { in: [...recent.keys()] } }] }, select: feedSelect, orderBy: newest })// Array sort is stable: publications stay newest first, ahead of the starters, which keep the Hub's order.const hot = [...liked.map(row => row.id), ...starters.filter(id => recent.has(id))].sort((a, b) => recent.get(b)! - recent.get(a)!)const cold = starters.filter(id => !recent.has(id))@@ -81,7 +82,7 @@ async function trendingPage(where: FeedWhere, autonomousEnv: string, starters: rlet tail: typeof liked = []if (coldAt < 0 && order.length <= feedPageSize) {const after = cursor && hotAt < 0 ? cursor : undefined- tail = await prisma.communityHarness.findMany({+ tail = await db.communityHarness.findMany({where: { AND: [where, { id: { notIn: liked.map(row => row.id) } }] }, select: feedSelect, orderBy: newest,take: feedPageSize + 1 - order.length, ...(after ? { cursor: { id: after }, skip: 1 } : {}),})@@ -94,14 +95,16 @@ async function trendingPage(where: FeedWhere, autonomousEnv: string, starters: r/*** A feed page in the reader's order, and the cursor for the next one (null on the last). A popular or* trending page also returns `order`: its publications' and [starters]' ids as the reader should see them.+ * [db] reads the publications: the secondaries for a search (routes/community.ts, task #2970).*/-export async function feedPage(where: FeedWhere, autonomousEnv: string, sort: FeedSort, starters: readonly string[], cursor?: string) {+export async function feedPage(where: FeedWhere, autonomousEnv: string, sort: FeedSort, starters: readonly string[], cursor?: string,+ db: PrismaClient = prisma) {if (sort === 'newest') {- const rows = await newestPage(where, cursor)+ const rows = await newestPage(db, where, cursor)const page = rows.slice(0, feedPageSize)return { page, nextCursor: rows.length > feedPageSize ? page[page.length - 1].id : null }}- const { rows, order } = sort === 'popular' ? await popularPage(where, autonomousEnv, starters, cursor) : await trendingPage(where, autonomousEnv, starters, cursor)+ const { rows, order } = sort === 'popular' ? await popularPage(db, where, autonomousEnv, starters, cursor) : await trendingPage(db, where, autonomousEnv, starters, cursor)const shown = order.slice(0, feedPageSize)const byId = new Map(rows.map(row => [row.id, row]))return {diff --git a/backend/src/lib/databaseUrl.test.ts b/backend/src/lib/databaseUrl.test.tsindex 1b712adf6..cfcce524f 100644--- a/backend/src/lib/databaseUrl.test.ts+++ b/backend/src/lib/databaseUrl.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { withPoolDefaults } from './databaseUrl.js'+import { secondaryReadsUrl, withPoolDefaults } from './databaseUrl.js'const defaults = { maxPoolSize: 20, serverSelectionTimeoutMS: 10000 }@@ -24,3 +24,28 @@ describe('withPoolDefaults', () => {expect(withPoolDefaults('mongodb://h/db?maxPoolSize=50', defaults)).toBe('mongodb://h/db?maxPoolSize=50&serverSelectionTimeoutMS=10000')})})++describe('secondaryReadsUrl', () => {+ const set = 'readPreference=secondaryPreferred&maxStalenessSeconds=90&appName=autonomous-code-prod-secondary'++ it('adds the three options to a connection string with none, after the database', () => {+ expect(secondaryReadsUrl('mongodb+srv://user:p%[email protected]/harness')).toBe(`mongodb+srv://user:p%[email protected]/harness?${set}`)+ })++ it('adds the path the options need to one with no database', () => {+ expect(secondaryReadsUrl('mongodb+srv://user:[email protected]')).toBe(`mongodb+srv://user:[email protected]/?${set}`)+ })++ it('keeps every other option and replaces its own, in any letter case, where they stood', () => {+ expect(secondaryReadsUrl('mongodb+srv://u:[email protected]/harness?retryWrites=true&w=majority&appname=autonomous-code-prod&ReadPreference=primary'))+ .toBe('mongodb+srv://u:[email protected]/harness?retryWrites=true&w=majority&appName=autonomous-code-prod-secondary&readPreference=secondaryPreferred&maxStalenessSeconds=90')+ expect(secondaryReadsUrl('mongodb://localhost:27017/harness?replicaSet=rs0&maxStalenessSeconds=120'))+ .toBe('mongodb://localhost:27017/harness?replicaSet=rs0&maxStalenessSeconds=90&readPreference=secondaryPreferred&appName=autonomous-code-prod-secondary')+ })++ it('leaves the main string as it is', () => {+ const main = 'mongodb://localhost:27017/harness?replicaSet=rs0'+ secondaryReadsUrl(main)+ expect(main).toBe('mongodb://localhost:27017/harness?replicaSet=rs0')+ })+})diff --git a/backend/src/lib/databaseUrl.ts b/backend/src/lib/databaseUrl.tsindex 3dc928f40..2a2887315 100644--- a/backend/src/lib/databaseUrl.ts+++ b/backend/src/lib/databaseUrl.ts@@ -21,3 +21,25 @@ export function withPoolDefaults(url: string, defaults: PoolDefaults): string {const hosts = url.indexOf('://') + 3return `${url}${url.indexOf('/', hosts) < 0 ? '/' : ''}?${missing.join('&')}`}++/** What the second client's reads ask for (task #2970): any secondary no more than 90 s behind (the least MongoDB allows),+ * the primary when none is, and a name of its own in Atlas's connection and slow-query views. */+export const SECONDARY_READS = { readPreference: 'secondaryPreferred', maxStalenessSeconds: '90', appName: 'autonomous-code-prod-secondary' } as const++/** The main connection string with SECONDARY_READS set: each replaces the same option where it stood (MongoDB option names+ * are case-insensitive), the rest follow, and every other option stays. A `mongodb+srv` host already lists every member.+ * Never parsed as a URL, as withPoolDefaults. */+export function secondaryReadsUrl(url: string): string {+ const query = url.indexOf('?')+ const wanted = new Map(Object.entries(SECONDARY_READS).map(([name, value]) => [name.toLowerCase(), `${name}=${value}`]))+ const pairs = (query < 0 ? '' : url.slice(query + 1)).split('&').filter(Boolean).flatMap(pair => {+ const name = pair.split('=')[0]!.toLowerCase(), set = wanted.get(name)+ if (!set) return [pair]+ wanted.delete(name)+ return [set]+ })+ const options = [...pairs, ...wanted.values()].join('&')+ if (query >= 0) return `${url.slice(0, query)}?${options}`+ const hosts = url.indexOf('://') + 3+ return `${url}${url.indexOf('/', hosts) < 0 ? '/' : ''}?${options}`+}diff --git a/backend/src/lib/prisma.test.ts b/backend/src/lib/prisma.test.tsindex f59a24379..abbc1d105 100644--- a/backend/src/lib/prisma.test.ts+++ b/backend/src/lib/prisma.test.ts@@ -1,5 +1,7 @@-import { expect, it, vi } from 'vitest'-import { prisma } from './prisma.js'+import type { PrismaClient } from '@prisma/client'+import { describe, expect, it, vi } from 'vitest'+import { env } from '../config/env.js'+import { prisma, prismaSecondary, readReplica } from './prisma.js'it('leaves the database connected on a shutdown signal, for the process to close after its drain', () => {const disconnect = vi.spyOn(prisma, '$disconnect').mockResolvedValue()@@ -10,3 +12,27 @@ it('leaves the database connected on a shutdown signal, for the process to closeexpect(disconnect).not.toHaveBeenCalled()} finally { disconnect.mockRestore() }})++describe('readReplica', () => {+ const main = 'mongodb+srv://user:[email protected]/harness?retryWrites=true&appName=autonomous-code-prod'+ const fake = () => ({ $extends: () => ({ fake: true }) }) as unknown as PrismaClient++ it('is a second client on the main connection string with the secondary options and the pool defaults, by default', () => {+ const make = vi.fn(fake)+ const replica = readReplica(prisma, main, 'on', make)+ expect(replica).not.toBe(prisma)+ expect(make).toHaveBeenCalledWith('mongodb+srv://user:[email protected]/harness?retryWrites=true&appName=autonomous-code-prod-secondary'+ + '&readPreference=secondaryPreferred&maxStalenessSeconds=90&maxPoolSize=20&serverSelectionTimeoutMS=10000')+ })++ it('is the main client itself when the switch is off: every moved read goes back to the primary', () => {+ const make = vi.fn(fake)+ expect(readReplica(prisma, main, 'off', make)).toBe(prisma)+ expect(make).not.toHaveBeenCalled()+ })++ it('is on unless the setting says off', () => {+ expect(env.DATABASE_SECONDARY_READS).toBe('on')+ expect(prismaSecondary).not.toBe(prisma)+ })+})diff --git a/backend/src/lib/prisma.ts b/backend/src/lib/prisma.tsindex 9146ddc67..e58e28b05 100644--- a/backend/src/lib/prisma.ts+++ b/backend/src/lib/prisma.ts@@ -1,6 +1,6 @@import { PrismaClient, type Prisma } from '@prisma/client'import { env } from '../config/env.js'-import { POOL_DEFAULTS, withPoolDefaults } from './databaseUrl.js'+import { POOL_DEFAULTS, secondaryReadsUrl, withPoolDefaults } from './databaseUrl.js'import { withQueryStats } from './queryStats.js'import { metrics } from './metrics.js'@@ -13,6 +13,19 @@ export const prisma = withQueryStats(new PrismaClient({datasources: { db: { url: withPoolDefaults(env.DATABASE_URL, POOL_DEFAULTS) } },}), undefined, undefined, metrics.observeQuery)+/** The client for reads that tolerate a few seconds of lag, on [url] with the secondary options (databaseUrl.ts+ * secondaryReadsUrl) and the pool defaults, its queries logged as `secondary:` in `db by shape`; [primary] itself when+ * [reads] is off. Only reads go through it, never inside a transaction (a transaction reads the primary). */+export function readReplica(primary: PrismaClient, url: string, reads: 'on' | 'off',+ make: (url: string) => PrismaClient = url => new PrismaClient({ datasources: { db: { url } } })): PrismaClient {+ if (reads === 'off') return primary+ return withQueryStats(make(withPoolDefaults(secondaryReadsUrl(url), POOL_DEFAULTS)), undefined, undefined, metrics.observeQuery, 'secondary')+}++/** Older history pages, costs, search, leaderboard names and usage totals (task #2970). It connects on its first query. On a+ * failover `secondaryPreferred` reads the primary by itself. */+export const prismaSecondary = readReplica(prisma, env.DATABASE_URL, env.DATABASE_SECONDARY_READS)+/** "Not soft-deleted" filter for Machine findMany where-clauses. Mongo-Prisma gotcha: legacy* rows have NO `deletedAt` field and `{deletedAt: null}` matches only an explicit null, so the* filter must accept both null and absent. `findUnique` can't take this — post-checkdiff --git a/backend/src/lib/queryStats.ts b/backend/src/lib/queryStats.tsindex 6744fd12c..80b8fa047 100644--- a/backend/src/lib/queryStats.ts+++ b/backend/src/lib/queryStats.ts@@ -219,7 +219,8 @@ export type QueryStatsOptions = {}export type QueryStats = {- record(model: string | undefined, action: string, args: unknown, ms: number, result: unknown, failed?: boolean): void+ /** [label] names the client a query ran on (`secondary`), ahead of its operation. */+ record(model: string | undefined, action: string, args: unknown, ms: number, result: unknown, failed?: boolean, label?: string): void/** Logs the window so far and starts a new one. */flush(): void}@@ -231,8 +232,8 @@ export function createQueryStats({ pod = `${hostname()}:${process.pid}`, slowMslet entries = new Map<string, Entry>()let overflowQueries = 0, slowLogged = 0, slowSuppressed = 0, slowQueries = 0, slowTotalMs = 0, bytesCapped = 0, started = performance.now()- const record: QueryStats['record'] = (model, action, args, ms, result, failed = false) => {- const op = opName(model, action, args), shape = filterShape(action, args), route = workKind()+ const record: QueryStats['record'] = (model, action, args, ms, result, failed = false, label) => {+ const op = `${label ? `${label}:` : ''}${opName(model, action, args)}`, shape = filterShape(action, args), route = workKind()let key = `${op}\0${shape}\0${route}`let entry = entries.get(key)if (!entry) {@@ -317,16 +318,17 @@ export function startQueryStats(options: QueryStatsOptions & { reportMs?: number/** The client with one query hook that times every operation, model calls and raw commands alike, for `db by shape` and* for `observe` (the Prometheus histogram, lib/metrics.ts; `raw` for a call without a model). Query extensions keep the- * client's types, so it is still a PrismaClient to its callers. A failure of either never reaches the query: it is warned+ * client's types, so it is still a PrismaClient to its callers. [label] names this client's queries in `db by shape`+ * (`secondary:User.findMany`, lib/prisma.ts prismaSecondary). A failure of either never reaches the query: it is warned* about once per client, and the query's own result or error goes back unchanged. */export function withQueryStats(client: PrismaClient, stats: () => QueryStats | undefined = () => active,warn: (message: string, context: Record<string, unknown>) => void = (m, c) => logger.warn(m, c),- observe?: (model: string, operation: string, seconds: number) => void): PrismaClient {+ observe?: (model: string, operation: string, seconds: number) => void, label?: string): PrismaClient {let warned = falseconst note = (model: string | undefined, operation: string, args: unknown, ms: number, result: unknown, failed: boolean) => {try {observe?.(model ?? 'raw', operation, ms / 1000)- stats()?.record(model, operation, args, ms, result, failed)+ stats()?.record(model, operation, args, ms, result, failed, label)} catch (error) {if (warned) returnwarned = truediff --git a/backend/src/lib/teamSession.test.ts b/backend/src/lib/teamSession.test.tsindex 845328f07..c548027c8 100644--- a/backend/src/lib/teamSession.test.ts+++ b/backend/src/lib/teamSession.test.ts@@ -30,7 +30,7 @@ const m = vi.hoisted(() => {bus: { changed: vi.fn(), listChanged: vi.fn(), presence: vi.fn() },}})-vi.mock('./prisma.js', () => ({ prisma: m.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))+vi.mock('./prisma.js', () => ({ prisma: m.prisma, prismaSecondary: m.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))// `pub`: the Swarm routes' store shares its delivery poll memory through it (routes/superTabs.ts); these tests never poll.vi.mock('./bus.js', () => ({ publishShareChanged: m.bus.changed, publishDeviceMachineListChanged: m.bus.listChanged, getAgentPresenceMany: m.bus.presence,pub: {} }))diff --git a/backend/src/routes/community.test.ts b/backend/src/routes/community.test.tsindex e3a0cc1e4..94580b024 100644--- a/backend/src/routes/community.test.ts+++ b/backend/src/routes/community.test.ts@@ -84,7 +84,12 @@ const db = vi.hoisted(() => {return { communityHarness: table({ defaults: { likeCount: 0 } }), communityLike: table({ unique: ['autonomousEnv', 'harnessId', 'userId'] }), communityComment: table(), communityFollow: table(),communityReport: table({ unique: ['autonomousEnv', 'targetType', 'targetId', 'userId'] }), communityHidden: table(), communityNotification: table(), user: { findUnique: vi.fn(async ({ where }: { where: { id: string } }) => ({ name: where.id === 'alice' ? 'Alice' : 'Bob' })) } }})-vi.mock('../lib/prisma.js', () => ({ prisma: db }))+/** The secondary client (lib/prisma.ts prismaSecondary): the same rows, with the models each read asked it for. */+const secondary = vi.hoisted(() => ({ asked: [] as string[] }))+vi.mock('../lib/prisma.js', () => ({ prisma: db, prismaSecondary: new Proxy(db, { get: (target, model: string) => {+ secondary.asked.push(model)+ return target[model as keyof typeof target]+} }) }))import { communityRoutes, publicationSchema } from './community.js'import { communityCommentRoutes } from './communityComments.js'import { communityCreatorRoutes } from './communityCreators.js'@@ -344,6 +349,17 @@ describe('persistent social actions', () => {expect(await search('q=lantern')).toHaveLength(2)expect(await search('q=lantern&mine=true', 'alice')).toEqual(['Lantern room'])expect(await search('q=nothing-like-this')).toEqual([])+ // A search's unanchored match is read on the secondaries (task #2970); the plain feed stays on the primary.+ expect(secondary.asked).toContain('communityHarness')+ secondary.asked.length = 0+ expect(await search('sort=newest')).toHaveLength(2)+ expect(await search('sort=popular&q=lantern')).toHaveLength(2)+ expect(await search('sort=trending&q=orbit')).toEqual(['Orbit study'])+ expect(secondary.asked.length).toBeGreaterThan(0)+ secondary.asked.length = 0+ await search('sort=popular')+ await search('sort=trending')+ expect(secondary.asked).toEqual([])expect((await call('GET', 'harnesses?q=')).statusCode).toBe(400)expect((await call('GET', `harnesses?q=${'x'.repeat(81)}`)).statusCode).toBe(400)})diff --git a/backend/src/routes/community.ts b/backend/src/routes/community.tsindex b25cb9558..60d6d13e0 100644--- a/backend/src/routes/community.ts+++ b/backend/src/routes/community.ts@@ -1,6 +1,6 @@import type { FastifyInstance, FastifyRequest } from 'fastify'import { z } from 'zod'-import { prisma } from '../lib/prisma.js'+import { prisma, prismaSecondary } from '../lib/prisma.js'import { parseAutonomousEnvironment } from '../lib/autonomousEnvironment.js'import { communityStarterAuthor, communityStarters } from '../lib/communityAccess.js'import { feedPage, feedSorts, feedStats } from '../lib/communityFeed.js'@@ -196,7 +196,8 @@ export async function communityRoutes(app: FastifyInstance): Promise<void> {// the reader follows Harness, and on a creator's page only on Harness's.const followed = new Set(follows.map(row => row.authorId))const starters = mine === 'true' || forkedFrom || (following === 'true' && !followed.has(communityStarterAuthor)) || (author && author !== communityStarterAuthor) ? [] : [...communityStarters]- const { page, order, nextCursor } = await feedPage(where, autonomousEnv, sort, starters, cursor)+ // A search matches text anywhere in the publications, which no index bounds: read on the secondaries (task #2970).+ const { page, order, nextCursor } = await feedPage(where, autonomousEnv, sort, starters, cursor, q ? prismaSecondary : prisma)const ids = [...page.map(row => row.id), ...communityStarters]const [stats, covered] = await Promise.all([feedStats(ids, autonomousEnv, req.user?.sub),diff --git a/backend/src/routes/control.test.ts b/backend/src/routes/control.test.tsindex 457d32adb..d9450acd3 100644--- a/backend/src/routes/control.test.ts+++ b/backend/src/routes/control.test.ts@@ -39,7 +39,7 @@ const fakes = vi.hoisted(() => {}})vi.mock('../lib/bus.js', () => ({ pub: fakes.pub }))-vi.mock('../lib/prisma.js', () => ({ prisma: fakes.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))+vi.mock('../lib/prisma.js', () => ({ prisma: fakes.prisma, prismaSecondary: fakes.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))// The real hub starts its heartbeat timers on import; these tests never attach a hub client, so it is a stub with none.vi.mock('../lib/hub.js', () => ({CLIENTS_FRAME: '__clients', CLIENTS_DIRTY: '__clients_dirty', LIVENESS_TICK_MS: 5_000, CLIENT_IDLE_DEADLINE_MS: 75_000,diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 3592f2caf..a46c2c2b7 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -1,7 +1,7 @@import { declaredHttpClient } from '../superTabs/refusalLog.js'import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'import { z, ZodError } from 'zod'-import { prisma } from '../lib/prisma.js'+import { prisma, prismaSecondary } from '../lib/prisma.js'import { env } from '../config/env.js'import multipart from '@fastify/multipart'import { attachmentsFromEnv, formFileBody, FORM_TOO_LARGE_MESSAGE, MAX_FORM_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, stopUnpacking, unpackFailed } from '../superTabs/attachments.js'@@ -249,8 +249,10 @@ async function productionStore(github: GitHubTokens | null): Promise<SuperTabStoimport('../lib/bus.js'), import('../lib/swarmDeliveryPushes.js'), import('../lib/swarmHostPushes.js'), import('../lib/swarmClientPushes.js'),import('./harnessLinks.js'), import('../lib/voiceQuota.js'), import('../lib/deepgramWav.js')])return new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),- // A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.- { workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) },+ // Older history pages and the costs report read the secondaries (lib/prisma.ts, task #2970).+ { replica: prismaSecondary,+ // A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.+ workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) },workStarted: (tabId, started) => { void github?.resume(tabId, started).catch(error => logger.warn('[github] resume failed', { tabId, error: String(error) })) },// A team account has no git login of its own: without the app it takes no teammates' work.teamAccountsIdle: !github,diff --git a/backend/src/server.ts b/backend/src/server.tsindex b4e8b5259..68e50bd65 100644--- a/backend/src/server.ts+++ b/backend/src/server.ts@@ -24,7 +24,7 @@ import { startLastHour } from './lib/lastHour.js'import { WORKER_INDEX } from './lib/instance.js'import { startTurnCredentialRefresh } from './lib/turnCredentials.js'import { closeBus, pub, redisCount, redisSsoProfileStore, redisSwarmStamps } from './lib/bus.js'-import { prisma } from './lib/prisma.js'+import { prisma, prismaSecondary } from './lib/prisma.js'import { backendReadinessChecks, createReadiness, drainBeforeClosing, processDrain } from './lib/readiness.js'import { configureSwarmStamps, swarmReadCache } from './superTabs/cache.js'import { startCacheStats } from './superTabs/cacheStats.js'@@ -279,7 +279,7 @@ async function start(): Promise<void> {stopRelayStats()stopPodRoutes()// The database stays connected through the drain, for the requests still being served (lib/prisma.ts).- await Promise.allSettled([prisma.$disconnect(), closeBus()])+ await Promise.allSettled([prisma.$disconnect(), ...prismaSecondary === prisma ? [] : [prismaSecondary.$disconnect()], closeBus()])process.exit(exitCode)} catch (err) {logger.error('Error during shutdown', err)diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex cdb08039f..54faf3d1a 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -159,6 +159,24 @@ export async function messagesPast(tx: Transaction, at: { tabId: string; conversreturn [...same, ...await read(edge ? { [op]: edge.sequence } : undefined, undefined, limit - same.length)]}+/**+ * Up to `limit` messages before `edge`, newest first, as the client `tx` holds them, or null when it does not hold the row+ * at `edge` yet: an older page read on a secondary (task #2970). One read of `sequence <= edge`, so the row the reader+ * pages from and the rows before it come from one member at once. A member that holds the edge holds every row before it:+ * a Swarm's messages are numbered in the write that stores them, one write at a time, and a secondary reads whole applied+ * writes. More than one row at the edge's sequence (one command's rows from before the store by parts) is left to the+ * primary, as is an edge with no row, so a page never skips a row the primary has.+ */+export async function heldPast(tx: Transaction, at: { tabId: string; conversationId: string; thread?: string }, edge: MessageEdge,+ limit: number): Promise<SuperTabMessage[] | null> {+ const rows = (await readBy(tx, 'SuperTabMessage', at.thread ? 'thread' : 'sequence', [+ { $match: { tabId: at.tabId, conversationId: at.conversationId, ...at.thread ? { thread: at.thread } : {}, sequence: { $lte: edge.sequence } } },+ { $sort: { sequence: -1, _id: -1 } }, { $limit: limit + 1 }])).map(row => prismaRow<SuperTabMessage>('SuperTabMessage', row))+ const atEdge = rows.filter(m => m.sequence === edge.sequence)+ if (atEdge.length !== 1 || (edge.id !== undefined && atEdge[0]!.id !== edge.id)) return null+ return rows.filter(m => m.sequence < edge.sequence)+}+/*** The messages of one conversation with these ids, by the id index: what a page's rows name as their thread or reply-to but* the page does not hold (store.ts messages), so what this reader may see of them can be checked. Named, not Prisma's `id in`,diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex e9103e6cd..4c4e67321 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -504,7 +504,8 @@ export class SwarmReads {const readable = allProjects ? projectsOf(state).filter(p => canReadProject(state, actor, p)).map(p => p.id) : undefinedconst dormant = await recentDormantGroups(tx, cached, tabId, readable ?? projectId, now - LEDGER_WEEKS * WEEK_MS)const groups = [...state.conversations.filter(g => !g.dormant), ...dormant].filter(g => !isLeads(g) && canReadGroup(state, actor, g))- const names = await profileNames(tx, state.people.map(p => p.id))+ // Names change rarely and show on a board: read on the secondary (task #2970).+ const names = await profileNames(this.store.replica, state.people.map(p => p.id))// Which machines the reader sees, with the daily rows no other read carries.const machines = (visibleState(state, actor, now).machines ?? []).map(m => ({ ...m, lentDays: state.machines?.find(own => own.machineId === m.machineId)?.lentDays }))diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 7087bd857..213a72b15 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -22,7 +22,7 @@ import { applyCommand, authorizeCommandAccess, IGNORED_NOTE, LOOP_NOTICE_AT, mayimport { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'import { reactionCounts, type ReactionTarget } from './reactions.js'-import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCELLABLE_DELIVERY, compactedDelivery, deliveredCopies, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, refreshThreads, storedMessages, type PageDelivery, type ThreadFacet } from './pageReads.js'+import { agentGatheredCount, agentGatheredDeliveries, agentOpenDeliveries, CANCELLABLE_DELIVERY, compactedDelivery, deliveredCopies, heldPast, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, refreshThreads, storedMessages, type PageDelivery, type ThreadFacet } from './pageReads.js'import { deliveriesByMessage } from './read/pageDeliveries.js'import { restoreDelivery } from './deliveryCompaction.js'import { threadSummaries } from './threads.js'@@ -336,6 +336,9 @@ async function abandonedStarts(tx: Transaction, tabId: string, state: SuperTabSt}export interface SuperTabStoreHooks {+ /** The client for reads that tolerate a few seconds of lag (lib/prisma.ts prismaSecondary, task #2970): older history+ * pages and the costs report. Without it they read the store's own client. */+ replica?: PrismaClient/** Tasks that stopped being in an agent's hands with this write (github/holds.ts): done, cancelled, stopped, given to* another attempt, or their agent removed. Called after the write commits; it must not throw. */workEnded?: (tabId: string, ended: WorkHold[]) => void@@ -594,6 +597,8 @@ async function outsiderRefusal(state: SuperTabState, userId: string, check: () =}export class SuperTabStore {+ /** Where lag-tolerant reads go (SuperTabStoreHooks.replica); the store's own client without one. */+ readonly replica: PrismaClientreadonly native: SuperTabNativeStorereadonly workspaces: SwarmWorkspaces/** Where avatars are kept, whose links member reads carry (read/service.ts); null when avatar uploads are off. */@@ -608,6 +613,7 @@ export class SuperTabStore {constructor(readonly db: PrismaClient, readonly now: () => number = Date.now,private readonly attachments: Attachments | null = null, private readonly hooks: SuperTabStoreHooks = {}) {+ this.replica = hooks.replica ?? dbthis.fileLinks = attachments ? new FileLinks(attachments.store, attachments.publicBase, attachments.prefix) : nullthis.polls = hooks.polls ?? localPollMemory(now)this.autoJoins = hooks.autoJoins ?? localAutoJoinMemory(now)@@ -3000,8 +3006,14 @@ export class SuperTabStore {// only about what is still missing (nextBatch): one hidden row once cost a whole second batch of 101.const rows: SuperTabMessage[] = []let batches = 0, decoded = 0+ // An older page reads its rows on the secondary (task #2970): history before a row the reader holds does not change as+ // new messages arrive. A batch whose edge the secondary does not hold yet is read on the primary (pageReads.ts heldPast),+ // and so is the rest of the page's rows then. The access checks above and the hidden-row checks stay on the primary.+ let replica = !forward && start !== undefined && !cursor.messageId && this.replica !== this.dbfor (let edge = start, size = PAGE_BATCH; rows.length < PAGE_BATCH;) {- const batch = await messagesPast(tx, at, edge, forward, size)+ const held = replica && edge ? await heldPast(this.replica, at, edge, size) : null+ if (!held) replica = false+ const batch = held ?? await messagesPast(tx, at, edge, forward, size)batches++decoded += batch.length// A task chat's copy of a Lead's notice stored before it was marked is that notice: read by no one (pageReads.ts).@@ -3015,8 +3027,9 @@ export class SuperTabStore {recordMessageRead({ reader: readerKind(actor, buddy), cursor: read, session: sessionKind(user) }, batches, decoded, page.length)const next = rows.length > 100 ? { sequence: page.at(-1)!.sequence, id: page.at(-1)!.id } : nullif (!forward) page.reverse()- const reactions = page.length ? reactionCounts(state, await pageReactions(tx, tabId, page.map(m => m.id))) : new Map()- const deliveries = page.length ? await pageDeliveries(tx, tabId, page.map(m => m.id)) : []+ const rowsOf = replica ? this.replica : tx+ const reactions = page.length ? reactionCounts(state, await pageReactions(rowsOf, tabId, page.map(m => m.id))) : new Map()+ const deliveries = page.length ? await pageDeliveries(rowsOf, tabId, page.map(m => m.id)) : []// What the page's rows point at that this reader may not see (an agent-only note to someone else; for a Buddy, a routing// row): such a reply reads as a message of its own, with no thread or reply-to naming it and no reply line for it// (review 1 of #2168). Rows on the page are readable already; the rest are read by id, at most two per row.@@ -3028,7 +3041,7 @@ export class SuperTabStore {const hidden = new Set(pointedRows.filter(m => !readable(m) || pointedCopies.has(m.id)).map(m => m.id))// The threads the page's rows are in, so a poll that brings only a reply still moves its root's reply line.const roots = [...new Set(page.flatMap(m => m.thread && !hidden.has(m.thread) ? [m.thread] : []))]- const threadRows = roots.length ? await pageThreads(tx, tabId, conversationId, roots) : []+ const threadRows = roots.length ? await pageThreads(rowsOf, tabId, conversationId, roots) : []// The main Buddy counts none of a session thread's replies, as it reads none (buddySessions.ts).const counted = buddy ? threadRows.filter(r => !r.routing && (own || !(isBuddyChat(group) && r.session))) : threadRowsconst summaries = counted.length ? threadSummaries(state, group, counted) : []@@ -3214,7 +3227,8 @@ export class SuperTabStore {* The decisions are read first, by index, so only the groups they name are loaded. */async costSummary(user: AuthUser, tabId: string, days: number, asAgentId?: string) {const until = this.now(), since = until - days * 24 * 60 * 60_000- const { rows, truncated } = await costRows(this.db, tabId, since)+ // A report over days: its decisions are read on the secondary (task #2970), who may read them on the primary.+ const { rows, truncated } = await costRows(this.replica, tabId, since)// Through the read cache, as every read: only what the Swarm's stamp says changed is read again (task #2596).const { state } = await this.readLoad(user, tabId, { groupIds: [...new Set(rows.map(r => r.conversationId))] })const actor = await this.actor(this.db, user, state, asAgentId)diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 086216bba..f6fc59c00 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts','integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/docs/plans/2026-11-04-secondary-reads-plan.md b/docs/plans/2026-11-04-secondary-reads-plan.mdnew file mode 100644index 000000000..e4c0b7ddb--- /dev/null+++ b/docs/plans/2026-11-04-secondary-reads-plan.md@@ -0,0 +1,113 @@+# Lag-tolerant reads on the secondaries: implementation plan++> Implemented by the task's Engineer task by task, each failing test committed before its code (project instructions,+> Engineer). One independent review on the pull request.++**Goal:** At the 11-04 peak (05–10Z) the Atlas primary of the M20 cluster averaged 69% CPU while the two secondaries sat+at 19% and 15%, and the backend reads from the primary only (task #2970). Move the reads that tolerate a few seconds of+lag to the secondaries; everything that must see the latest write stays on the primary.++**Architecture:**+- `lib/databaseUrl.ts secondaryReadsUrl(url)`: the main `DATABASE_URL` with `readPreference=secondaryPreferred`,+ `maxStalenessSeconds=90` and `appName=autonomous-code-prod-secondary` set (each replacing the same option, matched+ case-insensitively, and every other option kept), then the pool defaults. No new connection string (Ken, 11-04):+ the `mongodb+srv` host already lists all three members.+- `lib/prisma.ts prismaSecondary`: a second Prisma client on that string, timed by `withQueryStats` under the label+ `secondary` so `db by shape` tells its reads apart. `DATABASE_SECONDARY_READS=off` (default `on`) makes it the main+ client itself: one setting, no code change, sends every moved read back to the primary.+- Moved reads take the client explicitly; nothing else changes client:+ - Older history pages (`SuperTabStore.messages` with a `before` cursor, chat and thread): the message batches, their+ reactions, receipts and thread summaries. A batch is read from the secondary only with its edge: one query+ `sequence <= edge` that must return the row the reader already holds. A secondary that does not hold it yet (lag)+ reads that batch from the primary, so lag never opens a gap in history.+ - Costs (`SuperTabStore.costSummary` → `costs/read.ts costRows`): a report over days of route decisions.+ - Leaderboard people names (`leaderboard/read.ts profileNames`). The board's groups stay on the read cache, which+ holds what it loads at the Swarm's stamp; a stale load there would stay stale until the next change.+ - Community search (`GET /api/community/harnesses?q=`): the feed page's unanchored text match.+ - Usage totals (`GET /api/analytics/overview`): the daily buckets, machine days and machine states.+- Kept on the primary: the change feeds (`changedAt`/`readAt $gt`), the newest page, `after` pages and exact messages,+ the Swarm load and every access check (`readLoad`, `actor`, `canReadGroup`), the hidden-copy and pointed-row checks+ that decide what a reader may see, status, sign-in, and every read inside a write's transaction.+- `scripts/atlas-snapshot.ts`: the summary table gains each secondary's process CPU next to the primary's.++**Tech Stack:** TypeScript, Prisma 5 on MongoDB (`aggregateRaw`), Vitest, mongodb-memory-server replica sets.++**Spec:** task #2970's brief and Ken's two follow-ups of 11-04 (derive the string from `DATABASE_URL`; one off switch).++## Global Constraints++- Only reads move. A moved read never runs inside a transaction (a transaction reads the primary).+- A failing test first for each change; red/green evidence in a PR comment; backend `npm test` before Ready. The Super+ Tab integration suite runs in PR CI.+- Swarm code stays out of `cli/src/core`. Temp files only in `mktemp -d` folders.++## Design++- growth: N/A because nothing new is stored.+- concurrency: N/A because only reads move; writes and their transactions stay on the primary.+- read cost: the same queries and indexes; the secondaries serve them. An older page's edge check reads one row more.+- scale: at 10x the moved reads grow with people scrolling and reporting, not with Swarm size. The first warning is+ the secondaries' process CPU, now in Ken's snapshot table, and `secondary:` rows in `db by shape`.+- compatibility: no response changes; clients see the same rows.+- migration + rollback: none to migrate. Rollback is `DATABASE_SECONDARY_READS=off` and a restart, no code change.+- audience: N/A because access checks stay on the primary and run before any moved read.+- identity: N/A because it uses the backend's own database login.+- failure: on a failover `secondaryPreferred` reads the primary by itself; an edge the secondary lacks reads the primary.+ Both show in `db by shape` as the moved shapes without the `secondary:` label.+- platforms: backend only.++## Review Focus++- Every moved read tolerates up to 90 s of lag, and none decides a write or an access.+- The edge check: an older page from the secondary can never skip a row the primary has before the edge.+- The off switch returns exactly the main client.++## Task 1: the secondary connection string and client++**Files:** `backend/src/lib/databaseUrl.ts`, `backend/src/lib/databaseUrl.test.ts`, `backend/src/lib/prisma.ts`,+`backend/src/lib/prisma.test.ts`, `backend/src/config/env.ts`, `backend/src/lib/queryStats.ts`,+`backend/src/lib/queryStats.test.ts`, `backend/src/server.ts`++**Interfaces:** `secondaryReadsUrl(url: string): string`; `readReplica(primary, url, reads: 'on' | 'off', make?)`;+`prismaSecondary: PrismaClient`; `withQueryStats(client, stats?, warn?, label?)`.++- [ ] Test: a URL without options, with options (an old `readPreference`, `appName`, other options kept), and an SRV URL+ without a path get the three options; the off switch returns the main client, on returns another client.+- [ ] Watch them fail.+- [ ] Implement; the server disconnects the second client on shutdown when it is one.+- [ ] Test: a labelled client's queries show as `secondary:Model.action` in `db by shape`; watch it fail; implement.++## Task 2: older history pages on the secondary++**Files:** `backend/src/superTabs/pageReads.ts`, `backend/src/superTabs/store.ts`, `backend/src/routes/superTabs.ts`,+`backend/integration/secondaryReads.test.ts`, `backend/vitest.super-tabs.config.ts`++**Interfaces:** `SuperTabStoreHooks.replica?: PrismaClient` (default: the store's own client); `heldPast(tx, at, edge,+limit): Promise<SuperTabMessage[] | null>` (null: the secondary does not hold the edge).++- [ ] Integration test on a single-node replica set, with the primary and secondary clients recorded apart: an older+ page reads its rows on the secondary and returns the same rows as the primary alone; the newest page, an `after`+ page, the Swarm change feed and the access checks read the primary only; a secondary without the edge (another+ database) reads the page from the primary and returns the same rows.+- [ ] Watch it fail.+- [ ] Implement `heldPast` and the store's older-page path; the production store passes `prismaSecondary`.++## Task 3: costs, leaderboard names, search and usage totals++**Files:** `backend/src/superTabs/store.ts`, `backend/src/superTabs/read/service.ts`, `backend/src/lib/communityFeed.ts`,+`backend/src/routes/community.ts`, `backend/src/routes/community.test.ts`, `backend/src/lib/analyticsQuery.ts`,+`backend/integration/secondaryReads.test.ts`++- [ ] Tests: costs read their decisions on the secondary and their access on the primary; the leaderboard's names come+ from the secondary; a community search reads its page through the secondary client and an unsearched feed does+ not; the analytics overview reads its buckets through the secondary client.+- [ ] Watch them fail.+- [ ] Implement.++## Task 4: secondary CPU in Ken's snapshot++**Files:** `backend/scripts/atlas-snapshot.ts`, `backend/integration/atlasSnapshot.test.ts`++- [ ] Test: a snapshot with a primary and two secondaries lists each secondary's process CPU (average, peak, latest)+ in `summary.md`, and `--compare` shows them; watch it fail.+- [ ] Implement.