diff --git a/doc/idle-voice-call-reports.md b/doc/idle-voice-call-reports.md index a7c436a0b7a..2a8b665bf84 100644 --- a/doc/idle-voice-call-reports.md +++ b/doc/idle-voice-call-reports.md @@ -26,8 +26,9 @@ yielding after at most 100 rows per scope refresh. Re-registering the same owner resets partial scan cursors. The explicit one-shot inventory still loads every page when requested. A partial index selects terminal sessions with provider IDs. The query uses -its ended-at range to restrict reads to the current 24-hour window. The cursor retains PostgreSQL timestamp precision. Committed hints reload their -session, endpoint, connection, or company scope. Each cached entry carries the +its ended-at range to restrict reads to the current 24-hour window. The cursor retains PostgreSQL timestamp precision. Committed report hints reload the exact changed session. Configuration, +authority and connection metadata changes do not alter report eligibility or +saved retries, so they do not wake report reconstruction. Each cached entry carries the saved report deadline or the first millisecond after the refresh window ends, whichever comes first. Submillisecond PostgreSQL timestamps round in the safe direction. Expiring the window removes the cached obligation without a provider @@ -90,3 +91,9 @@ records 302 distinct passing cases, the bounded startup and same-owner restart regressions, deterministic company fairness, generated migration 0396 and the preserved failures. The report owner keeps its finite provider refresh obligation; this is not an unconditional idle scan or proof of deployed suspension. + + +The subsequent [configuration-scope repair](plans/2026-10-25-voice-call-report-sleep-audit.md#configuration-scope-review-repair-october-28) +records the current 303-case acceptance. Five real connection saves over 205 saved +reports select zero session rows, after reproducing 1,025 selected rows before +the repair. The notification helper accepts only an exact session scope. diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index 64ad4d634a6..e51747d7775 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -1798,3 +1798,14 @@ retains the five newest snapshots. The [report acceptance ledger](2026-10-25-voi records 302 passing cases, types/build, migration/plan checks, guarded restart and fairness probes, failures and limits. Current-head review, all CI and parent landing still gate this slice. The full remaining stack stays in scope. + + +## Report notification review follow-up, October 28 + +Report reconstruction also received configuration hints that could not alter +its eligibility or saved retry. Five real connection saves over 205 saved +reports selected 1,025 session rows. The report owner now accepts exact session +notifications and startup; those saves select zero rows and preserve the deadline. +The [report notification ledger](2026-10-25-voice-call-report-sleep-audit.md#configuration-scope-review-repair-october-28) +records 303 passing cases, types/build, the narrower contract and limits. Fresh +exact-head review and CI are required after the repair. diff --git a/doc/plans/2026-10-25-voice-call-report-sleep-audit.md b/doc/plans/2026-10-25-voice-call-report-sleep-audit.md index 7e82eba4ecc..c343f161fc8 100644 --- a/doc/plans/2026-10-25-voice-call-report-sleep-audit.md +++ b/doc/plans/2026-10-25-voice-call-report-sleep-audit.md @@ -304,3 +304,47 @@ parent `b8b12199b9` completed green CI after its single recorded E2E retry, but lacks current Ponytail acceptance. Retention's earlier 4/5 review was repaired in `68b62b6d13`; that new parent still requires its own fresh reviews and CI. Neither parent state is a waiver for reports or for remaining stack duties. + + +## Configuration scope review repair, October 28 + +The earlier security thread correctly identified another source of repeated +report inventory. A voice connection save reached `notifyVoiceChange`, which +notified reports for connection, endpoint, company or global scopes. Bounded +paging controlled each burst but still reloaded the whole eligible set after +separate saves. A real producer regression seeds 205 terminal sessions with saved +future report deadlines, then performs five separate connection saves. It selects +1,025 session rows before repair and zero afterward. The original next deadline +is unchanged, and no provider GET occurs during the saves. + +The composed notification now signals reports only for actual session changes. +The report-specific helper accepts only an exact session scope, preventing a +future configuration caller from reintroducing broad hints through that boundary. +Startup still uses the shared worker's initial paged reconstruction. Report claims, +receipts and signed callbacks keep exact session notifications. Existing terminal +hangup and reply-ended paths remain covered through their real producer APIs. +Live recovery, replies and inbound cleanup retain their own broader authority +and configuration signals; their eligibility can depend on those changes. + +The report predicate depends on session terminal state, provider identity and +endedAt, plus saved report state. A configuration save changes none of them. +Previously such a save only reloaded nextCheckAt and did not advance a future +provider attempt; the repair retains that same saved retry. There is no new +credential policy, refresh cadence, schema or scheduler contract. Manual inventory +APIs remain complete. Unsupported external SQL still needs its own wake contract. + +303 distinct cases pass after the repair: 132 complete voice integration cases, +170 complete lifecycle/shared/startup cases, and the unchanged schema/snapshot +case. The voice suite uses a fresh separate DB; the lifecycle suites use their +existing dedicated isolated DBs. Server typecheck/build and module boundaries +pass. The earlier 302 count applies to `80207ba6bb` and is not added to this count. +The current Ponytail 5/5 on that earlier head cannot be reused after this edit; +fresh exact-head review and all CI remain required. + +Logs: `/tmp/sleep25-config-amplification-red.log`, +`/tmp/sleep25-scope-final-voice-consumers.log`, +`/tmp/sleep25-scope-final-lifecycle-consumers.log`, +`/tmp/sleep25-scope-final-types.log`, `/tmp/sleep25-scope-final-build.log`, and +`/tmp/sleep25-scope-final-module-boundaries.log`. No full local repository suite, +live provider, Cloud wake or physical suspension claim is added. The original +20-path report scope and the existing finite 24-hour obligation remain intact. diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index 2b891a9c296..31cf6dbda13 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -82,6 +82,55 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu return { companyId, endpointId, agentId, connectionId, issueId, conversationId, callerId, sessionId, store, request, reserved, accept, toolInput, publication }; } + it("keeps saved report deadlines quiet across repeated voice connection saves", async () => { + const f = await nativeServiceFixture(); + const [seed] = await db.select().from(chatVoiceSessions).where(eq(chatVoiceSessions.id, f.sessionId)); + const endedAt = new Date(), deadline = Date.now() + 600_000; + await db.update(chatVoiceSessions).set({ state: "ended", endedAt }).where(eq(chatVoiceSessions.id, seed.id)); + const ids = [seed.id, ...Array.from({ length: 204 }, () => randomUUID())]; + await db.insert(chatVoiceSessions).values(ids.slice(1).map(id => ({ + ...seed, id, callerId: randomUUID(), idempotencyKey: id, providerSessionId: randomUUID(), + state: "ended" as const, endedAt, + }))); + await db.insert(chatVoiceReports).values(ids.map(sessionId => ({ companyId: f.companyId, sessionId, nextCheckAt: new Date(deadline) }))); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const onError = vi.fn(), coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError }); + const settle = () => vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(1000); + expect(idleWorkSnapshot().active).toBe(0); + expect(coordinator.nextWakeAt()).toBe(deadline); + }, { timeout: 5000 }); + let selected = 0; const select = db.select.bind(db); + try { + await f.service.registerReportWork(coordinator, () => true).ready; await settle(); + const reads = vi.spyOn(db, "select").mockImplementation((...args) => { + const selection = select(...args), from = selection.from.bind(selection); + vi.spyOn(selection, "from").mockImplementation(table => { + const query = from(table); + if (table === chatVoiceSessions) { + const execute = query.execute.bind(query); + vi.spyOn(query, "execute").mockImplementation(async () => { + const rows = await execute(); selected += rows.length; return rows; + }); + } + return query; + }); + return selection; + }); + try { + for (let index = 0; index < 5; index++) { + await toolAccessService(db).updateConnection(f.connectionId, { name: `Saved report ${index}` }); + await settle(); + } + expect(selected).toBe(0); expect(f.transport.callReport).not.toHaveBeenCalled(); + expect(onError).not.toHaveBeenCalled(); + } finally { reads.mockRestore(); } + } finally { + await coordinator.stop(); vi.useRealTimers(); vi.restoreAllMocks(); + await db.update(chatVoiceSessions).set({ endedAt: new Date(Date.now() - 2 * 86_400_000) }).where(eq(chatVoiceSessions.companyId, f.companyId)); + } + }); + it.each(["hangup", "signed callback", "reply ended"])("wakes report refresh from real %s and advances it on a later callback", async trigger => { const f = await inboundFixture(); await db.update(chatVoiceSessions).set({ endedAt: new Date(Date.now() - 2 * 86_400_000) }).where(eq(chatVoiceSessions.id, f.sessionId)); diff --git a/server/src/services/voice/voice-recovery-notifications.ts b/server/src/services/voice/voice-recovery-notifications.ts index f8445911370..05ac776a646 100644 --- a/server/src/services/voice/voice-recovery-notifications.ts +++ b/server/src/services/voice/voice-recovery-notifications.ts @@ -21,7 +21,7 @@ export async function notifyVoiceChange(tx: object, scope?: VoiceRecoveryScope) await notifyVoiceRecovery(tx, scope); await notifyVoiceReplies(tx, scope); await notifyVoiceInbound(tx, scope); - await notifyVoiceReports(tx, scope); + if (scope?.kind === "session") await notifyVoiceReports(tx, { kind: "session", id: scope.id }); } export function withVoiceSessionChange(db: Db, id: string, write: (tx: Parameters[0]>[0]) => PromiseLike, options: { replyDelivery?: boolean } = {}): Promise { return db.transaction(async tx => { diff --git a/server/src/services/voice/voice-report-notifications.ts b/server/src/services/voice/voice-report-notifications.ts index 0dbff5eaae3..077b6939c90 100644 --- a/server/src/services/voice/voice-report-notifications.ts +++ b/server/src/services/voice/voice-report-notifications.ts @@ -1,6 +1,5 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js"; -import type { VoiceRecoveryScope } from "./voice-recovery-notifications.js"; -export function notifyVoiceReports(tx: object, scope?: VoiceRecoveryScope) { - return notifyDeliveryWork(tx, DELIVERY_QUEUES.voiceReports, scope ? `${scope.kind}:${scope.id}` : "*"); +export function notifyVoiceReports(tx: object, scope: { kind: "session"; id: string }) { + return notifyDeliveryWork(tx, DELIVERY_QUEUES.voiceReports, `${scope.kind}:${scope.id}`); }