Bound voice recovery refreshes and separate health observations

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-27 23:13:59 -05:00
1 parent f8d7dd2d14
commit 1493a0bc43
9 files changed
+364 -26

No files matched your search

+33 -2
View File
@@ -10,6 +10,10 @@ obligations; their existing maintenance remains until their own migrations land.
Existing `chat_voice_sessions` rows are authoritative. Startup reconstructs live
sessions in UUID pages of 100, joined to their same-company endpoint and connection.
Each background refresh reads at most one inventory page. An unfinished pass has
a one-second continuation; it does not create a permanent empty scan. Only timing
and eligibility fields are selected for discovery. The explicit foreground
reconciliation method keeps its complete inventory behavior.
Terminal history does not create a live-session recovery obligation. With no live
sessions, the worker also avoids reading experimental settings after reconstruction.
@@ -64,10 +68,37 @@ a bounded empty voice lookup after a chat configuration write. It does not creat
idle polling or a recurring deadline. The shared helper contains only routing;
voice eligibility, authority and provider policy stay with the voice owner.
## Bounded configuration refreshes
The voice owner remembers the endpoint/connection fields that affect its existing
deadline policy: endpoint status, runtime generation, connection enabled state,
connection identity, and the chat feature flag. A broad configuration hint first
reads a bounded page of these parent records. If those facts are unchanged, the
cached call deadlines stay in place and no call inventory is read. Metadata-only
writes do not move business deadlines. An unknown or changed parent requires
bounded reconstruction; a real disablement still settles every affected call.
Only the voice owner interprets these facts. The generic health producer now
sends a health-observation notification through the existing chat routing owner.
It preserves receiver and command signals without generating a voice-configuration
wake. An observation changes neither voice eligibility nor the saved call deadline.
Supported session producers continue to signal their exact session ID.
The worker processes at most 25 dirty scopes and 25 provider checks per pass.
Scope pagination continues without restarting on every newer hint. Failures retain
their backoff and block stale entries in the failed scope. Successful pages can
make progress while the remaining inventory is discovered. The existing
coordinator can use the actual error deadline, including an already-due healthy
backlog, rather than postponing it to an unrelated fallback retry.
## Failure and lifecycle behavior
Refreshes coalesce by scope, with a full refresh covering already pending narrower
hints. Changes arriving during refresh remain dirty. Failed refreshes block use of
Refreshes coalesce by scope. Paged reconstruction keeps narrower producer hints,
including a newly committed session behind the UUID cursor. A scope generation
retains configuration changes that arrive between pages. Seen IDs protect
concurrent refresh results; absent cached entries are removed only when the
scope's inventory is complete. A new worker resets partial inventory state before
reconstructing its saved obligations. Changes arriving during refresh remain dirty. Failed refreshes block use of
stale cached entries in that scope. Per-scope and per-call failure backoff starts
at 30 seconds and caps at five minutes. New hints do not erase failure backoff.
Batches rotate across companies, process at most 25 calls, and continue an already
@@ -1561,3 +1561,17 @@ proofs, 131 targeted cases pass, and both newly supported external fixtures
self-migrate. See [the owning audit](2026-10-25-chat-receiver-discovery-sleep-audit.md#current-parent-and-review-acceptance-october-27)
for exact evidence and the older CI runner-loss failure. Fresh CI/reviews and
parent landing are still required. The original remaining-duty inventory is unchanged.
## Voice inventory amplification acceptance, October 27
The voice recovery slice keeps the original single-duty scope and adds the
normalized health-observation notification contract. Five real metadata writes
and one health check over 205 future calls previously selected 1,230 call rows;
they now select zero and preserve the saved deadline. Startup and changed-parent
reconstruction use bounded pages and retain concurrent wakes.
The updated [voice audit](2026-10-25-voice-maintenance-sleep-audit.md#voice-session-inventory-amplification-repair-october-27)
records all 725 distinct targeted passing cases, typecheck, build, failed attempts
and guarded regressions. This is worker acceptance, not deployed sleep proof.
Fresh exact-head review and CI remain required before the voice PR can merge.
@@ -164,3 +164,59 @@ cases. Workspace typechecking passes. A fresh final voice/receiver/startup selec
and the full local test command are running; build/publication/remote gates remain.
No full local matrix result is claimed from targeted tests. Initial fixture errors
and the reproduced provider-binding race remain recorded above and in test logs.
## Voice session inventory amplification repair, October 27
The voice branch normally integrates receiver parent #17572 at `841d451164`
through `f8d7dd2d14`. The initial single-duty scope is 21 files, with no database
changes. The health-observation routing repair adds one related production path,
`tool-access/catalog/health.ts`, because an observation must not claim that voice
configuration changed. The existing routing helper owns receiver and command
fanout; the voice service owns eligibility and deadline comparison.
A real-API regression with 205 future live calls reproduced 1,230 selected call
rows across five metadata updates and one health observation. The row count
measures executed database selects, rather than timer calls or helper invocations.
After repair these operations read zero call rows, preserve the exact saved next
deadline, and issue no voice wake for the health-only operation. A separate real
SDK health case confirms receiver and command topics still settle after commit.
The background path now uses one inventory page of at most 100 lean call headers
per refresh. Parent state is probed separately, in bounded pages, and unchanged
state keeps existing deadlines. Unknown or genuinely changed parent state has a
bounded reconstruction. Foreground reconciliation keeps its complete scan API.
The worker retains a generation and seen IDs across pages, processes at most 25
scopes per pass, rechecks call state before provider effects, and preserves failed
scope/call backoff. It resets partial state when the same service starts a new
worker. No per-worker table, migration, extra scheduler, or route recovery wrapper
is introduced.
Real database regressions cover all 205 deadlines after paging and partial-scan
restart, a new session behind the cursor, a feature change between pages, and
connection disablement settling all 205 calls. Guarded production mutations
reproduce the page-size violation, lost global generation (cleanup delayed past
its prompt-recovery assertion), and health-only wake. Each original file is
restored after the mutation. These checks supplement the existing outer-commit,
rollback, drain, current-authority, late-provider-binding and shutdown cases.
Both newly supported external fixture paths skipped migrations. Empty-database
runs failed with missing instance_settings before the worker or provider action.
The worker and complete voice-store fixtures now apply pending migrations before
creating the client and use the shared PostgreSQL bootstrap budget. The initial
amplification fixture also omitted its required Speko provider config, then used
the wrong public health method name; those failures preceded the actual 1,230-row
baseline. Initial quiet checks counted the observer's previous calls; measurement
is now stopped before an independent quiet-window spy is created. The quiet
assertion itself is unchanged. The first typecheck exposed timing-only rows being
used for full provider operations; the timing-header type stays separate from full
rows at that operation boundary. All failures remain recorded as such.
Current targeted acceptance passes 725 distinct cases: 18 voice lifecycle, 94
shared coordinator/batching/startup/hostname, 97 complete voice-store, 469
tool-access, and 47 health/receiver cases. Production typecheck and server build
pass. The 18 lifecycle cases replace the earlier 16-case result; these counts do
not add repeated runs. Full suites ran unless a narrower selection is explicitly
named above. No full local repository matrix, actual host suspension, Cloud wake,
multi-writer support, or savings is inferred from this worker migration. The original remaining-duty inventory stays
in scope. Current exact-head reviews, security, CI, and parent landing are still
required before merging #17576.
@@ -1,7 +1,9 @@
import { HttpError } from "../errors.js";
import { toolAccessService } from "../services/tool-access.js";
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import { agents, chatConversations, chatEndpoints, chatVoiceSessions, companies, createDb, issues, toolApplications, toolConnections } from "@paperclipai/db";
import { applyPendingMigrations, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, agents, chatConversations, chatEndpoints, chatVoiceSessions, companies, createDb, issues, subscribeDatabaseWork, toolApplications, toolConnections } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
@@ -9,6 +11,7 @@ import { instanceSettingsService } from "../services/instance-settings.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
import { voiceSessionRecovery } from "../services/voice/voice-session-recovery.js";
import { registerVoiceRecoveryWork } from "../services/voice/voice-recovery-work.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { notifyVoiceRecovery, withVoiceSessionChange } from "../services/voice/voice-recovery-notifications.js";
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_VOICE_TEST_DATABASE_URL");
@@ -26,9 +29,10 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
});
beforeAll(async () => {
if (!external) temporary = await startEmbeddedPostgresTestDatabase("voice-recovery-");
if (external) await applyPendingMigrations(external);
db = createDb(external ?? temporary!.connectionString, { idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true });
}, 60_000);
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
async function fixture() {
const companyId = randomUUID(), endpointId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), conversationId = randomUUID();
fixtureCompanies.push(companyId);
@@ -37,7 +41,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await db.insert(agents).values({ id: agentId, companyId, name: "Voice", adapterType: "paperclip_runner" });
await db.insert(issues).values({ id: issueId, companyId, title: "Voice", assigneeAgentId: agentId, status: "in_progress" });
await db.insert(toolApplications).values({ id: applicationId, companyId, name: "Voice", type: "chat" });
await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "Voice", uid: connectionId, transport: "voice", connectionPurpose: "channel", enabled: true, status: "active" });
await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "Voice", uid: connectionId, transport: "voice", connectionPurpose: "channel", config: { provider: "speko" }, enabled: true, status: "active" });
await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, assignedAgentId: agentId, publicId: endpointId, provider: "speko", status: "active", setup: { step: "complete", runtimeGeneration: 1 } });
await db.insert(chatConversations).values({ id: conversationId, companyId, endpointId, issueId, externalConversationId: conversationId, externalThreadId: conversationId, externalLabel: "Voice", isDirectMessage: true });
return { companyId, endpointId, assignedAgentId: agentId, issueId, conversationId };
@@ -61,7 +65,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
});
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); });
async function session(patch: Partial<typeof chatVoiceSessions.$inferInsert> = {}, writer = db) {
const id = randomUUID();
const id = patch.id ?? randomUUID();
return withVoiceSessionChange(writer, id, tx => tx.insert(chatVoiceSessions).values({ id, companyId, endpointId, conversationId, issueId, assignedAgentId: agentId,
callerId: randomUUID(), callerAuthority: "member", mode: "browser", state: "active", generation: 1, credentialFingerprint: "test", providerSessionId: randomUUID(),
toolTokenHash: "a".repeat(64), idempotencyKey: id, requestFingerprint: id, createdAt: new Date(Date.now() - 60_000), updatedAt: new Date(Date.now() - 60_000), expiresAt: new Date(Date.now() + 600_000), ...patch }).returning()).then(rows => rows[0]);
@@ -79,6 +83,139 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
try { await vi.advanceTimersByTimeAsync(ms); expect(reads).not.toHaveBeenCalled(); expect(writes).not.toHaveBeenCalled(); }
finally { reads.mockRestore(); writes.mockRestore(); }
}
async function futureInventory(count: number) {
const row = await session({ updatedAt: new Date(), expiresAt: new Date(Date.now() + 3_600_000) });
await db.insert(chatVoiceSessions).values(Array.from({ length: count - 1 }, () => {
const id = randomUUID();
return { ...row, id, callerId: randomUUID(), providerSessionId: id, idempotencyKey: id, requestFingerprint: id };
}));
return row.updatedAt.getTime() + 30_000;
}
function voiceReads() {
const counts: number[] = [], select = db.select.bind(db);
const measurement = 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(); counts.push(rows.length); return rows;
});
}
return query;
});
return selection;
});
return { counts, stop: () => measurement.mockRestore() };
}
async function futureSettled(at: number) {
await vi.waitFor(async () => {
await vi.advanceTimersByTimeAsync(1000);
expect(idleWorkSnapshot().active).toBe(0);
expect(coordinator!.nextWakeAt()).toBe(at);
}, { timeout: 5000 });
}
it("bounds startup pages and retains every saved deadline", async () => {
const due = await futureInventory(205), reads = voiceReads(), counts = reads.counts;
await start();
expect(counts).toHaveLength(1); expect(counts[0]).toBe(100);
await futureSettled(due);
expect(counts.reduce((sum, count) => sum + count, 0)).toBe(205);
expect(Math.max(...counts)).toBe(100);
await vi.advanceTimersByTimeAsync(due - Date.now()); await settled();
expect(new Set(inspect.mock.calls.map(([row]) => row.id)).size).toBe(205);
reads.stop(); await quiet();
});
it("reconstructs every page when the same service restarts after a partial scan", async () => {
const due = await futureInventory(205), service = voiceSessionRecovery(db, { authorize, inspect, close });
await start(service); expect(inspect).not.toHaveBeenCalled(); await coordinator!.stop();
await start(service); await futureSettled(due);
await vi.advanceTimersByTimeAsync(due - Date.now()); await settled();
expect(new Set(inspect.mock.calls.map(([row]) => row.id)).size).toBe(205);
await quiet();
});
it("retains a new session behind the cursor during paged reconstruction", async () => {
const due = await futureInventory(205), service = voiceSessionRecovery(db, { authorize, inspect, close });
const refresh = service.refresh; let inserted = false, newcomer = "";
service.refresh = async (...args) => {
const result = await refresh(...args);
if (!args[0] && !result.complete && !inserted) {
inserted = true; newcomer = (await session({ id: "00000000-0000-4000-8000-000000000001" })).id;
}
return result;
};
await start(service); await futureSettled(due);
expect(inspect.mock.calls.map(([row]) => row.id)).toEqual([newcomer]);
expect((await db.select().from(chatVoiceSessions).where(eq(chatVoiceSessions.id, newcomer)))[0].state).toBe("ended");
await quiet(5000);
});
it("reapplies a feature change that arrives between inventory pages", async () => {
await futureInventory(205);
const settings = instanceSettingsService(db), service = voiceSessionRecovery(db, { authorize, inspect, close });
const refresh = service.refresh; let changedAt: number | undefined;
service.refresh = async (...args) => {
const result = await refresh(...args);
if (!args[0] && !result.complete && changedAt === undefined) {
changedAt = Date.now(); await settings.updateExperimental({ enableChatConnectors: false });
}
return result;
};
try {
await start(service); await settled();
expect(new Set(close.mock.calls.map(([row]) => row.id)).size).toBe(205);
expect(Date.now() - changedAt!).toBeLessThan(25_000);
await quiet();
} finally {
await coordinator?.stop(); coordinator = undefined;
await settings.updateExperimental({ enableChatConnectors: true });
}
});
it("pages actual connection disablement and settles every cached live call", async () => {
const due = await futureInventory(205); await start(); await futureSettled(due);
const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpointId));
const reads = voiceReads();
authorize.mockRejectedValue(new HttpError(403, "Connection disabled"));
try {
await toolAccessService(db).updateConnection(endpoint.connectionId, { enabled: false });
await settled();
expect(new Set(close.mock.calls.map(([row]) => row.id)).size).toBe(205);
expect(inspect).not.toHaveBeenCalled(); expect(Math.max(...reads.counts)).toBe(100);
reads.stop(); await quiet();
} finally { authorize.mockResolvedValue(undefined); reads.stop(); }
});
it("does not reread live calls after repeated real connection metadata and health writes", async () => {
const due = await futureInventory(205);
await start(); await futureSettled(due);
const reads = voiceReads(), counts = reads.counts;
const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpointId));
const tools = toolAccessService(db);
for (let index = 0; index < 5; index++) {
await tools.updateConnection(endpoint.connectionId, { name: `Metadata ${index}` });
await futureSettled(due);
}
let observations = 0;
const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.voiceSessionRecovery, event => { if (event === "settled") observations++; });
try {
await expect(tools.checkHealth(endpoint.connectionId)).rejects.toMatchObject({ status: 422 });
await futureSettled(due);
expect(counts.reduce((sum, count) => sum + count, 0)).toBe(0);
expect(observations).toBe(0);
expect(inspect).not.toHaveBeenCalled(); reads.stop(); await quiet(5000);
} finally { unsubscribe(); }
});
it("preserves receiver and command wakes for SDK health observations", async () => {
const id = randomUUID();
await db.insert(toolConnections).values({ id, companyId, applicationId: (await db.select().from(toolApplications).where(eq(toolApplications.companyId, companyId)))[0].id,
name: "SDK observation", uid: id, transport: "chat_sdk", connectionPurpose: "channel", config: { provider: "discord" }, enabled: true, status: "active" });
const seen = new Set<string>();
const topics = [DELIVERY_QUEUES.chatReceivers, DELIVERY_QUEUES.chatCommandRegistration, DELIVERY_QUEUES.voiceSessionRecovery];
const stops = topics.map(topic => subscribeDatabaseWork(db, topic, event => { if (event === "settled") seen.add(topic); }));
try {
await expect(toolAccessService(db).checkHealth(id)).rejects.toMatchObject({ status: 422 });
expect(seen).toEqual(new Set([DELIVERY_QUEUES.chatReceivers, DELIVERY_QUEUES.chatCommandRegistration]));
} finally { for (const stop of stops) stop(); }
});
it("leaves configured terminal history quiet", async () => {
await session({ state: "ended", endedAt: new Date() }); await start(); await settled(); await quiet(); expect(inspect).not.toHaveBeenCalled();
});
@@ -121,9 +258,9 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
await vi.advanceTimersByTimeAsync(due - Date.now()); await settled(); expect(inspect).toHaveBeenCalledOnce(); await quiet();
});
it("preserves a session committed during a full refresh", async () => {
const service = voiceSessionRecovery(db, { authorize, inspect, close }), original = service.load;
const service = voiceSessionRecovery(db, { authorize, inspect, close }), original = service.refresh;
await start(service); await settled(); let inserted = false;
service.load = async (...args) => { const rows = await original(...args); if (!inserted) { inserted = true; await session(); } return rows; };
service.refresh = async (...args) => { const rows = await original(...args); if (!inserted) { inserted = true; await session(); } return rows; };
await db.transaction(tx => notifyVoiceRecovery(tx)); await settled(); expect(inspect).toHaveBeenCalledOnce(); await quiet();
});
it("pages saved sessions and drains healthy work while one provider fails", async () => {
@@ -154,12 +291,12 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
});
it("does not inspect stale cached work until a failed scope refresh succeeds", async () => {
const row = await session({ updatedAt: new Date(Date.now() - 20_000) });
const service = voiceSessionRecovery(db, { authorize, inspect, close }), original = service.load;
await start(service); service.load = async () => { throw new Error("scope unavailable"); };
const service = voiceSessionRecovery(db, { authorize, inspect, close }), original = service.refresh;
await start(service); service.refresh = async () => { throw new Error("scope unavailable"); };
await db.transaction(tx => notifyVoiceRecovery(tx, { kind: "session", id: row.id }));
await vi.waitFor(async () => { await vi.advanceTimersByTimeAsync(1000); expect(errors).toHaveLength(1); });
await quiet(15_000); expect(inspect).not.toHaveBeenCalled();
service.load = original; await settled(); expect(inspect).toHaveBeenCalledOnce(); errors.length = 0; await quiet();
service.refresh = original; await settled(); expect(inspect).toHaveBeenCalledOnce(); errors.length = 0; await quiet();
});
it("does not expire a provider identity bound after the grace-period read", async () => {
const row = await session({ state: "creation_unknown", providerSessionId: null,
@@ -15,7 +15,7 @@ import { VOICE_RESULT_NOTIFICATION } from "@paperclipai/shared";
import { createHash, createHmac, randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { chatActions, instanceUserRoles, principalPermissionGrants, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, toolProfileBindings, chatVoiceCallbacks, agentWakeupRequests, issueThreadInteractions, issueQuestionResponseDeliveries, issueComments, agents, chatConversations, chatDeliveries, chatEndpoints, chatPublications, chatVoiceReplies, chatVoiceSessions, chatVoiceToolCalls, companies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, issues, toolApplications, toolConnections, toolConnectionInstalls } from "@paperclipai/db";
import { applyPendingMigrations, chatActions, instanceUserRoles, principalPermissionGrants, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, toolProfileBindings, chatVoiceCallbacks, agentWakeupRequests, issueThreadInteractions, issueQuestionResponseDeliveries, issueComments, agents, chatConversations, chatDeliveries, chatEndpoints, chatPublications, chatVoiceReplies, chatVoiceSessions, chatVoiceToolCalls, companies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, issues, toolApplications, toolConnections, toolConnectionInstalls } from "@paperclipai/db";
import { configureSpekoSessionTools } from "../services/voice/speko-tool-setup.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { chatChannelService } from "../services/chat-channels.js";
@@ -39,6 +39,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
beforeAll(async () => {
if (!external) database = await startEmbeddedPostgresTestDatabase("paperclip-speko-store-");
if (external) await applyPendingMigrations(external);
db = createDb(external ?? database!.connectionString, { idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await database?.cleanup(); });
@@ -13,6 +13,10 @@ export async function notifyChatEndpointConfiguration(transaction: object, endpo
export async function notifyChatConnectionConfiguration(transaction: object, connectionId: string, transport: ToolConnectionTransport = "chat_sdk") {
if (transport === "chat_sdk" || transport === "voice") await notifyVoiceRecovery(transaction, { kind: "connection", id: connectionId });
await notifyChatConnectionObservation(transaction, connectionId, transport);
}
export async function notifyChatConnectionObservation(transaction: object, connectionId: string, transport: ToolConnectionTransport) {
await notifyChatConnectionReceiver(transaction, connectionId, transport);
if (transport === "chat_sdk") {
await notifyDiscordCommandRegistration(transaction, { kind: "connection", id: connectionId });
@@ -1,4 +1,4 @@
import { notifyChatConnectionConfiguration } from "../../chat-channels/configuration-work-notifications.js";
import { notifyChatConnectionObservation } from "../../chat-channels/configuration-work-notifications.js";
import { writeToolConnectionHealthChange } from "../../tool-connection-health-notifications.js";
import { connectionActorUserId } from "../actor.js";
import { assertSupportedConnection } from "../connections/setup-policy.js";
@@ -50,7 +50,7 @@ export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, d
) {
const now = new Date();
const [updated] = await writeToolConnectionHealthChange(db, connection, async tx => {
await notifyChatConnectionConfiguration(tx, connection.id, connection.transport);
await notifyChatConnectionObservation(tx, connection.id, connection.transport);
return tx.update(toolConnections)
.set({
healthStatus: status,
@@ -12,7 +12,10 @@ export function registerVoiceRecoveryWork(
service: ReturnType<typeof voiceSessionRecovery>,
canRun: () => boolean,
) {
service.reset();
const dirty = new Set<string>(["*"]);
const versions = new Map<string, number>();
const scans = new Map<string, { version: number; seen: Set<string> }>();
const entries = new Map<string, VoiceRecoveryEntry>();
const failures = new Map<string, { count: number; retryAt: number }>();
const scopeFailures = new Map<string, { count: number; retryAt: number }>();
@@ -23,7 +26,8 @@ export function registerVoiceRecoveryWork(
map.set(id, { count, retryAt: Date.now() + Math.min(300_000, 30_000 * 2 ** (count - 1)) });
}
function dirtyScopes() {
return [...dirty].map(hint => { try { return voiceRecoveryScope(hint); } catch { return undefined; } });
return [...dirty].filter(hint => !scans.has(hint) || scopeFailures.has(hint))
.map(hint => { try { return voiceRecoveryScope(hint); } catch { return undefined; } });
}
function next() {
let nextAt: number | null = null;
@@ -37,29 +41,42 @@ export function registerVoiceRecoveryWork(
const worker = coordinator.register(DELIVERY_QUEUES.voiceSessionRecovery, {
retryMs: 30_000,
pausePassiveMaintenance: true,
onSettled: hints => { for (const hint of hints ?? ["*"]) dirty.add(hint); },
onSettled: hints => { for (const hint of hints ?? ["*"]) {
dirty.add(hint); versions.set(hint, (versions.get(hint) ?? 0) + 1);
} },
run: async signal => {
if (!canRun() || Date.now() < earliest) return;
earliest = Date.now() + 1000;
const errors: unknown[] = [];
const requested = (dirty.has("*") ? ["*"] : [...dirty]).filter(hint => (scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now());
const covered = requested.includes("*") ? [...dirty] : requested;
for (const hint of covered) dirty.delete(hint);
const ready = [...dirty].filter(hint => (scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now());
const requested = dirty.has("*")
? ready.includes("*") ? ["*", ...ready.filter(hint => hint !== "*")].slice(0, 25) : []
: ready.slice(0, 25);
for (const hint of requested) dirty.delete(hint);
for (let index = 0; index < requested.length; index++) {
if (signal.aborted || !canRun()) { for (const hint of requested.includes("*") ? covered : requested.slice(index)) dirty.add(hint); return; }
if (signal.aborted || !canRun()) { for (const hint of requested.slice(index)) dirty.add(hint); return; }
const hint = requested[index];
let scope: VoiceRecoveryScope | undefined;
let decoded = false;
try {
scope = voiceRecoveryScope(hint); decoded = true;
const rows = await service.load(scope, signal), retained = new Set(rows.map(row => row.id));
for (const entry of entries.values()) if (matches(entry, scope) && !retained.has(entry.id)) {
const scan = scans.get(hint) ?? { version: versions.get(hint) ?? 0, seen: new Set<string>() };
scans.set(hint, scan);
const result = await service.refresh(scope, signal);
for (const entry of result.rows ?? []) {
entries.set(entry.id, entry);
for (const [other, progress] of scans) if (matches(entry, voiceRecoveryScope(other))) progress.seen.add(entry.id);
}
if (!result.complete) { dirty.add(hint); continue; }
if (result.rows !== null) for (const entry of entries.values()) if (matches(entry, scope) && !scan.seen.has(entry.id)) {
entries.delete(entry.id); failures.delete(entry.id);
}
for (const entry of rows) entries.set(entry.id, entry);
scans.delete(hint);
if ((versions.get(hint) ?? 0) !== scan.version) dirty.add(hint); else versions.delete(hint);
if (!scope) scopeFailures.clear(); else scopeFailures.delete(hint);
} catch (error) {
const retryHint = decoded ? hint : "*";
if (!decoded) { scans.delete(hint); versions.delete(hint); }
dirty.add(retryHint); failed(scopeFailures, retryHint); errors.push(error);
}
}
@@ -82,6 +99,7 @@ export function registerVoiceRecoveryWork(
// idle hold during drain. The coordinator still fences unresolved XIDs.
hasPending: async () => canRun() && dirty.size > 0,
nextRunAt: next,
nextRunAtOnError: next,
});
return worker;
}
@@ -7,7 +7,7 @@ import { withVoiceSessionChange, type VoiceRecoveryScope } from "./voice-recover
export const LIVE_VOICE_STATES = ["reserved", "creating", "creation_unknown", "connecting", "active", "ending"] as const;
type Session = typeof chatVoiceSessions.$inferSelect;
export type VoiceRecoveryEntry = { id: string; companyId: string; endpointId: string; connectionId: string; dueAt: number };
type Candidate = { session: Session; connectionId: string; endpointStatus: string; enabled: boolean; generation: number };
type Candidate<T = Pick<Session, "id" | "companyId" | "endpointId" | "providerSessionId" | "expiresAt" | "updatedAt" | "generation" | "state" | "errorCode">> = { session: T; connectionId: string; endpointStatus: string; enabled: boolean; generation: number };
export function voiceSessionRecoveryAt(row: Candidate, featureEnabled: boolean): number {
const session = row.session;
@@ -25,7 +25,7 @@ export function voiceSessionRecovery(db: Db, operations: {
close(session: Session): Promise<unknown>;
}) {
async function candidates(scope?: VoiceRecoveryScope, signal?: AbortSignal) {
const rows: Candidate[] = [];
const rows: Candidate<Session>[] = [];
let cursor: string | undefined;
for (;;) {
signal?.throwIfAborted();
@@ -53,6 +53,83 @@ export function voiceSessionRecovery(db: Db, operations: {
return rows.map(row => ({ id: row.session.id, companyId: row.session.companyId, endpointId: row.session.endpointId,
connectionId: row.connectionId, dueAt: voiceSessionRecoveryAt(row, enabled) }));
}
type Parent = { id: string; companyId: string; connectionId: string; signature: string | null };
type Scan = { phase: "parents" | "sessions"; cursor?: string; parents: Map<string, Parent> };
const parents = new Map<string, Parent>();
const scans = new Map<string, Scan>();
function scopeKey(scope?: VoiceRecoveryScope) { return scope ? `${scope.kind}:${scope.id}` : "*"; }
function parentMatches(row: Parent, scope?: VoiceRecoveryScope) {
return !scope || (scope.kind === "endpoint" ? row.id : scope.kind === "connection" ? row.connectionId : row.companyId) === scope.id;
}
function remember(target: Map<string, Parent>, row: Parent) {
const prior = target.get(row.id);
target.set(row.id, prior && prior.signature !== row.signature ? { ...row, signature: null } : row);
}
async function refresh(scope?: VoiceRecoveryScope, signal?: AbortSignal): Promise<{ rows: VoiceRecoveryEntry[] | null; complete: boolean }> {
const key = scopeKey(scope);
const scan = scans.get(key) ?? { phase: scope && scope.kind !== "session" ? "parents" as const : "sessions" as const, parents: new Map<string, Parent>() };
signal?.throwIfAborted();
if (scan.phase === "parents") {
const page = await db.select({ id: chatEndpoints.id, companyId: chatEndpoints.companyId, connectionId: toolConnections.id,
endpointStatus: chatEndpoints.status, enabled: toolConnections.enabled,
generation: sql<number>`coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::integer, 0)` })
.from(chatEndpoints).innerJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId), eq(toolConnections.companyId, chatEndpoints.companyId)))
.where(and(scope?.kind === "endpoint" ? eq(chatEndpoints.id, scope.id) : undefined,
scope?.kind === "connection" ? eq(toolConnections.id, scope.id) : undefined,
scope?.kind === "company" ? eq(chatEndpoints.companyId, scope.id) : undefined,
scan.cursor ? gt(chatEndpoints.id, scan.cursor) : undefined))
.orderBy(chatEndpoints.id).limit(100);
const enabled = page.length ? (await instanceSettingsService(db).getExperimental()).enableChatConnectors : false;
const next = new Map(scan.parents);
for (const row of page) remember(next, { id: row.id, companyId: row.companyId, connectionId: row.connectionId,
signature: JSON.stringify([row.connectionId, row.endpointStatus, row.enabled, row.generation, enabled]) });
signal?.throwIfAborted();
if (page.length === 100) {
scans.set(key, { phase: "parents", cursor: page[page.length - 1].id, parents: next });
return { rows: [], complete: false };
}
const previous = [...parents.values()].filter(row => parentMatches(row, scope));
if (previous.length === next.size && previous.every(row => row.signature !== null && next.get(row.id)?.signature === row.signature)) {
scans.delete(key); return { rows: null, complete: true };
}
scans.set(key, { phase: "sessions", parents: next });
return { rows: [], complete: false };
}
const page = await db.select({ session: { id: chatVoiceSessions.id, companyId: chatVoiceSessions.companyId,
endpointId: chatVoiceSessions.endpointId, state: chatVoiceSessions.state, providerSessionId: chatVoiceSessions.providerSessionId,
expiresAt: chatVoiceSessions.expiresAt, updatedAt: chatVoiceSessions.updatedAt, generation: chatVoiceSessions.generation,
errorCode: chatVoiceSessions.errorCode }, connectionId: toolConnections.id,
endpointStatus: chatEndpoints.status, enabled: toolConnections.enabled,
generation: sql<number>`coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::integer, 0)` })
.from(chatVoiceSessions)
.innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatVoiceSessions.endpointId), eq(chatEndpoints.companyId, chatVoiceSessions.companyId)))
.innerJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId), eq(toolConnections.companyId, chatVoiceSessions.companyId)))
.where(and(inArray(chatVoiceSessions.state, [...LIVE_VOICE_STATES]),
scope?.kind === "session" ? eq(chatVoiceSessions.id, scope.id) : undefined,
scope?.kind === "endpoint" ? eq(chatVoiceSessions.endpointId, scope.id) : undefined,
scope?.kind === "connection" ? eq(toolConnections.id, scope.id) : undefined,
scope?.kind === "company" ? eq(chatVoiceSessions.companyId, scope.id) : undefined,
scan.cursor ? gt(chatVoiceSessions.id, scan.cursor) : undefined))
.orderBy(chatVoiceSessions.id).limit(100);
const enabled = page.length ? (await instanceSettingsService(db).getExperimental()).enableChatConnectors : false;
const next = new Map(scan.parents);
for (const row of page) remember(next, { id: row.session.endpointId, companyId: row.session.companyId, connectionId: row.connectionId,
signature: JSON.stringify([row.connectionId, row.endpointStatus, row.enabled, row.generation, enabled]) });
const rows = page.map(row => ({ id: row.session.id, companyId: row.session.companyId, endpointId: row.session.endpointId,
connectionId: row.connectionId, dueAt: voiceSessionRecoveryAt(row, enabled) }));
signal?.throwIfAborted();
const complete = page.length < 100;
if (!complete) scans.set(key, { phase: "sessions", cursor: page[page.length - 1].session.id, parents: next });
else {
scans.delete(key);
if (scope?.kind !== "session") {
for (const row of parents.values()) if (parentMatches(row, scope)) parents.delete(row.id);
for (const [id, row] of next) parents.set(id, row);
}
}
return { rows, complete };
}
function reset() { scans.clear(); parents.clear(); }
async function check(id: string, signal?: AbortSignal): Promise<VoiceRecoveryEntry | null> {
const scope = { kind: "session", id } as const;
const [row] = await candidates(scope, signal);
@@ -85,5 +162,5 @@ export function voiceSessionRecovery(db: Db, operations: {
}
return (await load(scope, signal))[0] ?? null;
}
return { load, check };
return { load, refresh, reset, check };
}