Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(mcp-host): add property-based session summary/pagination suite (R1-M4)
Diego Zacarias0c694b2a1e56
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 9cfe7a6a0..77a8287b5 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.225",+ "version": "0.1.226","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.225",+ "version": "0.1.226","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",@@ -49,6 +49,7 @@"@typescript-eslint/eslint-plugin": "^8.59.0","@typescript-eslint/parser": "^8.59.0","eslint": "^10.2.1",+ "fast-check": "^4.9.0","supertest": "^7.2.2","typescript": "^5.3.0","vitest": "^4.0.18"@@ -4069,6 +4070,29 @@"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==","license": "MIT"},+ "node_modules/fast-check": {+ "version": "4.9.0",+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.9.0.tgz",+ "integrity": "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg==",+ "dev": true,+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "pure-rand": "^8.0.0"+ },+ "engines": {+ "node": ">=12.17.0"+ }+ },"node_modules/fast-csv": {"version": "4.3.6","resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz",@@ -6535,6 +6559,23 @@"node": ">=6"}},+ "node_modules/pure-rand": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-8.4.2.tgz",+ "integrity": "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==",+ "dev": true,+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT"+ },"node_modules/qs": {"version": "6.15.3","resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex f2df9537a..879770a09 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.225",+ "version": "0.1.226","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {@@ -26,8 +26,8 @@"license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",- "@clerum/llm-providers": "file:../packages/llm-providers","@aws-sdk/client-bedrock-runtime": "^3.895.0",+ "@clerum/llm-providers": "file:../packages/llm-providers","@google/genai": "^2.10.0","@kubernetes/client-node": "^1.0.0","@modelcontextprotocol/sdk": "^1.0.0",@@ -65,6 +65,7 @@"@typescript-eslint/eslint-plugin": "^8.59.0","@typescript-eslint/parser": "^8.59.0","eslint": "^10.2.1",+ "fast-check": "^4.9.0","supertest": "^7.2.2","typescript": "^5.3.0","vitest": "^4.0.18"diff --git a/mcp-host/src/db/worker/__tests__/sessionSummary.property.test.ts b/mcp-host/src/db/worker/__tests__/sessionSummary.property.test.tsnew file mode 100644index 000000000..83c0fc721--- /dev/null+++ b/mcp-host/src/db/worker/__tests__/sessionSummary.property.test.ts@@ -0,0 +1,155 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import Database from 'better-sqlite3'+import fc from 'fast-check'+import { runMigrations } from '../../migrate'+import { applyPragmas } from '../../pragmas'+import { createDispatcher, dispatch } from '../dispatcher'+import type { MessageRow, SessionRow } from '../protocol'++// R1-M4 — property-based coverage for the two ways a session's summary counters+// are maintained: incrementally (updateSessionSummaryAfterInsert, run per+// inserted message) and by full recomputation (recomputeSessionMessageSummary).+// Every fixture is produced by the REAL dispatcher (insert_session /+// insert_message), never hand-built, so the shapes under test are exactly the+// ones production emits (T1).++interface SummarySnapshot {+ turn_count: number+ message_count: number+ last_activity_at: number | null+}++const messageArb = fc.record({+ role: fc.constantFrom('user', 'assistant', 'tool', 'system'),+ turnNumber: fc.option(fc.integer({ min: 1, max: 6 }), { nil: null }),+ hasToolCalls: fc.boolean(),+ timestamp: fc.integer({ min: 1, max: 100_000 }),+})++const seedArb = fc.record({+ startedAt: fc.integer({ min: 1, max: 100_000 }),+ messages: fc.array(messageArb, { minLength: 0, maxLength: 24 }),+})++interface Seed {+ startedAt: number+ messages: Array<{+ role: string+ turnNumber: number | null+ hasToolCalls: boolean+ timestamp: number+ }>+}++describe('session summary counters — property based (R1-M4)', () => {+ let db: Database.Database++ beforeEach(() => {+ db = new Database(':memory:')+ applyPragmas(db)+ runMigrations(db)+ })++ afterEach(() => {+ db.close()+ })++ async function seedSession(seed: Seed): Promise<string> {+ const deps = createDispatcher(db)+ const id = 'conv-prop'+ const session: SessionRow = {+ ...baseSession(id, 'u-prop:rpc:agent:prop'),+ started_at: seed.startedAt,+ }+ await dispatch({ kind: 'insert_session', payload: session }, deps)+ let ordinal = 0+ for (const m of seed.messages) {+ const message: MessageRow = {+ session_id: id,+ ordinal: ordinal++,+ role: m.role as MessageRow['role'],+ content: `${m.role}-${ordinal}`,+ content_parts: null,+ tool_call_id: null,+ tool_calls: m.hasToolCalls && m.role === 'assistant' ? '[{"name":"search"}]' : null,+ tool_name: null,+ timestamp: m.timestamp,+ token_count: null,+ finish_reason: null,+ spillover_ref: null,+ is_error: 0,+ turn_number: m.turnNumber,+ }+ await dispatch({ kind: 'insert_message', payload: message }, deps)+ }+ return id+ }++ function readSummary(id: string): SummarySnapshot {+ return db+ .prepare('SELECT turn_count, message_count, last_activity_at FROM sessions WHERE id = ?')+ .get(id) as SummarySnapshot+ }++ it('P6 — incremental counters equal a full recomputation', async () => {+ await fc.assert(+ fc.asyncProperty(seedArb, async seed => {+ db.exec('DELETE FROM messages; DELETE FROM sessions')+ const id = await seedSession(seed as Seed)+ const incremental = readSummary(id)+ const deps = createDispatcher(db)+ deps.statements.recomputeSessionMessageSummary.run({ id })+ const recomputed = readSummary(id)+ expect(incremental).toEqual(recomputed)+ }),+ { numRuns: 60 }+ )+ })++ it('P4 — recomputeSessionMessageSummary is idempotent', async () => {+ await fc.assert(+ fc.asyncProperty(seedArb, async seed => {+ db.exec('DELETE FROM messages; DELETE FROM sessions')+ const id = await seedSession(seed as Seed)+ const deps = createDispatcher(db)+ deps.statements.recomputeSessionMessageSummary.run({ id })+ const once = readSummary(id)+ deps.statements.recomputeSessionMessageSummary.run({ id })+ const twice = readSummary(id)+ expect(twice).toEqual(once)+ }),+ { numRuns: 60 }+ )+ })+})++function baseSession(id: string, sessionKey: string): SessionRow {+ return {+ id,+ session_key: sessionKey,+ source: 'rpc',+ user_id: id,+ team_id: null,+ channel_type: 'rpc',+ channel_id: 'agent',+ thread_id: null,+ model: null,+ model_selections: null,+ system_prompt_stable_hash: null,+ parent_session_id: null,+ started_at: 1,+ ended_at: null,+ end_reason: null,+ message_count: 0,+ tool_call_count: 0,+ input_tokens: 0,+ output_tokens: 0,+ cache_read_tokens: 0,+ cache_write_tokens: 0,+ cache_tokens_reported: 0,+ title: null,+ state: 'idle',+ active_task_id: null,+ active_trace_context: null,+ }+}diff --git a/mcp-host/src/server/__tests__/sessionsPagination.property.test.ts b/mcp-host/src/server/__tests__/sessionsPagination.property.test.tsnew file mode 100644index 000000000..f98e8e892--- /dev/null+++ b/mcp-host/src/server/__tests__/sessionsPagination.property.test.ts@@ -0,0 +1,159 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import { ConversationManager } from '../../core/conversation/conversation'+import {+ type ConversationSessionSummary,+ InMemoryConversationStore,+} from '../../core/conversation/conversationStore'+import { makeSqliteStore } from '../../core/conversation/persistence/__tests__/testHelpers'+import {+ decodeSessionsCursor,+ encodeSessionsCursor,+ paginateSessionSummaries,+ sessionsCursorScope,+} from '../wireProjections'++// R1-M4 — property-based coverage for the session-list wire contract. Every+// summary is produced by the REAL stores (SqliteConversationStore /+// InMemoryConversationStore driven by ConversationManager), and paging runs+// through the REAL wire helpers (paginateSessionSummaries + encode/decode+// cursor). No hand-built fixtures (T1); assertions are on the observable list+// the desktop would see (T4).++const USER = 'u-1'+const AGENT = 'a'+const PREFIX = `${USER}:rpc:${AGENT}:`++interface Seed {+ sessions: Array<{ id: number; turns: number }>+ limit: number+}++const seedArb: fc.Arbitrary<Seed> = fc.record({+ sessions: fc.uniqueArray(+ fc.record({ id: fc.integer({ min: 0, max: 400 }), turns: fc.integer({ min: 0, max: 3 }) }),+ { selector: s => s.id, minLength: 1, maxLength: 10 }+ ),+ limit: fc.integer({ min: 1, max: 4 }),+})++async function seedInto(manager: ConversationManager, seed: Seed): Promise<string[]> {+ const keys: string[] = []+ for (const s of seed.sessions) {+ const key = `${PREFIX}c${s.id}`+ keys.push(key)+ const conv = await manager.getOrCreate(key, { userId: USER })+ for (let t = 0; t < s.turns; t += 1) {+ await manager.startTurn(conv, `q${t}`, `task-${s.id}-${t}`)+ await manager.completeTurn(conv, `a${t}`)+ }+ }+ return keys+}++/** a must not sort AFTER b under (lastActivityAt desc, key asc). */+function notOutOfOrder(a: ConversationSessionSummary, b: ConversationSessionSummary): boolean {+ const at = a.lastActivityAt.getTime()+ const bt = b.lastActivityAt.getTime()+ if (at !== bt) return at > bt // newer first+ return a.key <= b.key+}++function project(s: ConversationSessionSummary) {+ return {+ key: s.key,+ chatId: s.chatId,+ agent: s.agent,+ turnCount: s.turnCount,+ messageCount: s.messageCount,+ state: s.state,+ }+}++describe('session list pagination — property based (R1-M4)', () => {+ it('P1/P2/P3 — cursor paging yields a total order, unique pages, exact-once coverage', async () => {+ await fc.assert(+ fc.asyncProperty(seedArb, async seed => {+ const sqlite = makeSqliteStore({ cacheSize: 4 })+ try {+ const manager = new ConversationManager(sqlite.store)+ const keys = await seedInto(manager, seed)+ for (const key of keys) await sqlite.persistQueue.drainSessionKey(key)++ // Ground truth from the real producer, unbounded.+ const eligible = await manager.listSessionSummariesForUserAsync(PREFIX, { agent: AGENT })++ const scope = sessionsCursorScope(USER, AGENT)+ const encodeKey = (k: string) => k.slice(PREFIX.length)+ const pages: ConversationSessionSummary[][] = []+ let cursorStr: string | undefined+ for (let guard = 0; guard <= eligible.length + 2; guard += 1) {+ const decoded = decodeSessionsCursor(cursorStr, scope)+ const entries = await manager.listSessionSummariesForUserAsync(PREFIX, {+ limit: seed.limit + 1,+ cursor: decoded+ ? { updatedAt: new Date(decoded.updatedAt), key: `${PREFIX}${decoded.key}` }+ : undefined,+ agent: AGENT,+ })+ const { page, nextCursor } = paginateSessionSummaries(+ entries,+ seed.limit,+ encodeKey,+ scope+ )+ pages.push(page)+ // P2 — no key repeats within a page and the page honors the limit.+ expect(page.length).toBeLessThanOrEqual(seed.limit)+ expect(new Set(page.map(p => p.key)).size).toBe(page.length)+ if (!nextCursor) break+ cursorStr = nextCursor+ }++ const flat = pages.flat()++ // P1 — the concatenation is a total order (lastActivityAt desc, key asc).+ for (let i = 1; i < flat.length; i += 1) {+ expect(notOutOfOrder(flat[i - 1]!, flat[i]!)).toBe(true)+ }++ // P3 — every eligible session appears exactly once across all pages.+ expect(flat.map(s => s.key)).toEqual(eligible.map(s => s.key))+ expect(new Set(flat.map(s => s.key)).size).toBe(eligible.length)+ } finally {+ await sqlite.shutdown()+ }+ }),+ { numRuns: 40 }+ )+ })++ it('P5 — InMemory and SQLite summaries agree for the same data', async () => {+ await fc.assert(+ fc.asyncProperty(seedArb, async seed => {+ const sqlite = makeSqliteStore({ cacheSize: 4 })+ try {+ const memory = new InMemoryConversationStore()+ const memManager = new ConversationManager(memory)+ const sqlManager = new ConversationManager(sqlite.store)++ await seedInto(memManager, seed)+ const keys = await seedInto(sqlManager, seed)+ for (const key of keys) await sqlite.persistQueue.drainSessionKey(key)++ const memList = await memory.listSessionSummariesByPrefix(PREFIX, { agent: AGENT })+ const sqlList = await sqlite.store.listSessionSummariesByPrefix(PREFIX, { agent: AGENT })++ // Parity is on WHICH sessions and their counters — ordering-by-activity+ // is a separate concern proven in P1. Sort by key so sub-millisecond+ // clock jitter between the two stores cannot cause a spurious mismatch.+ const byKey = (a: { key: string }, b: { key: string }) => (a.key < b.key ? -1 : 1)+ expect(memList.map(project).sort(byKey)).toEqual(sqlList.map(project).sort(byKey))+ } finally {+ await sqlite.shutdown()+ }+ }),+ { numRuns: 40 }+ )+ })+})