perf(chat): schedule Telegram maintenance from commits and deadlines (#16094)

Replace periodic Telegram discovery and maintenance scans with bounded startup recovery, connection-specific commit notifications, and durable action deadlines. Preserve ownership, inactive subscription parking, retry and cleanup recovery, and atomic credential binding updates.

Verified full typecheck/build, 30 focused scheduler tests, 12 database-backed recovery cases, all current-head CI checks, and Greptile 5/5 with no unresolved threads.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-10-13 07:55:27 -07:00
1 parent 69f4bfc3c5
commit 833769ab55
20 files changed
+479 -99

No files matched your search

@@ -456,7 +456,20 @@ Longer polling intervals alone do not complete an item.
for both stale-claim expiry and any saved retry time. Startup recovers unfinished for both stale-claim expiry and any saved retry time. Startup recovers unfinished
requests. Claim and settlement writes signal in their own short transactions, requests. Claim and settlement writes signal in their own short transactions,
with agent wakeup outside those transactions. Empty and terminal queues disarm. with agent wakeup outside those transactions. Empty and terminal queues disarm.
Remaining **1s** maintenance: provider runtimes, Telegram maintenance, Telegram maintenance now has separate commit-driven discovery and action
workers. Discovery restores legacy subscription obligations on startup and
after endpoint or chat-connection configuration commits, without recurring
empty scans. Startup walks keyset pages with at most 100 endpoints per run,
so endpoints beyond the first page remain discoverable. Configuration commits
carry connection hints through outer settlement and uncertainty recovery;
they only revisit the changed connection. Failed discovery retains its page,
and concurrent edits queue a fresh scoped pass. Existing action rows provide retry and stale-claim
deadlines. Stop-subscription repair parks while the endpoint or connection
is inactive; registration and removal keep their existing eligibility.
The explicit bounded recovery helper remains available. Provider subscription
proof, credential ownership, and idempotent provider mutations stay in the
Telegram service. Provider responses are simulated in the PostgreSQL tests.
Remaining **1s** maintenance: provider runtimes,
run milestone/wake-notice projection, GitHub operation run milestone/wake-notice projection, GitHub operation
recovery, and Teams protocol maintenance. GitHub pre-ingress recovery recovery, and Teams protocol maintenance. GitHub pre-ingress recovery
must still inspect provider history: a lost callback has no local queue row. must still inspect provider history: a lost callback has no local queue row.
@@ -181,6 +181,14 @@ own policy and access review.
Gaps: Provider endpoint, represented agent and linked sender are operator choices today. Gaps: Provider endpoint, represented agent and linked sender are operator choices today.
Internal recovery: Telegram discovery walks bounded pages at startup. Configuration
commits only queue the changed connection; durable maintenance rows supply retry deadlines. Inactive subscription
repair is parked until an endpoint or connection change. This creates no agent
management permission or new API. Local database-backed provider-fixture tests in
[channel integration](../../server/src/__tests__/chat-channels.integration.test.ts)
cover recovery, rollback, retries and idle query silence; they do not establish
live provider or agent access.
## `failure` ## `failure`
Review: `baseline`. Review: `baseline`.
+6
View File
@@ -132,6 +132,12 @@ Automated: [setup routing](../../ui/src/pages/apps/chat/ChatEndpointSetup.routin
[identity confirmation](../../ui/src/pages/apps/chat/ChatIdentityConfirm.test.tsx) [identity confirmation](../../ui/src/pages/apps/chat/ChatIdentityConfirm.test.tsx)
cover shared UI logic with fixtures. Provider-specific live setup is not implied. cover shared UI logic with fixtures. Provider-specific live setup is not implied.
[Channel integration](../../server/src/__tests__/chat-channels.integration.test.ts)
also covers bounded Telegram subscription recovery at startup and after committed
configuration changes, saved retry deadlines, rollback, and parking pending
repair while an endpoint or connection is inactive. The provider responses are
fixtures. Settled maintenance leaves no discovery timer or database scans.
Manual: complete setup for one named provider, reload endpoint settings, link Manual: complete setup for one named provider, reload endpoint settings, link
the intended sender, and send a disposable message. Verify one task and a useful the intended sender, and send a disposable message. Verify one task and a useful
reply in the originating conversation. Inspect an unlinked sender's denial and reply in the originating conversation. Inspect an unlinked sender's denial and
+26 -2
View File
@@ -48,6 +48,24 @@ const support = await getEmbeddedPostgresTestSupport();
expect(await db.execute(sql`select * from work_signal_test where id = 'rollback'`)).toHaveLength(0); expect(await db.execute(sql`select * from work_signal_test where id = 'rollback'`)).toHaveLength(0);
}); });
it("coalesces scoped hints and publishes them only when the outer transaction settles", async () => {
const settled: string[][] = [];
const unsubscribe = subscribeDatabaseWork(db, "scoped", (event, hints) => {
if (event === "settled") settled.push([...(hints ?? [])]);
});
try {
await db.transaction(async tx => {
await signalDatabaseWork(tx, "scoped", "connection-a");
await tx.transaction(async nested => {
await signalDatabaseWork(nested, "scoped", "connection-b");
await signalDatabaseWork(nested, "scoped", "connection-a");
});
expect(settled).toEqual([]);
});
expect(settled).toEqual([["connection-a", "connection-b"]]);
} finally { unsubscribe(); }
});
it("keeps outer ownership after a caught savepoint rollback", async () => { it("keeps outer ownership after a caught savepoint rollback", async () => {
const events: string[] = []; const events: string[] = [];
const unsubscribe = subscribeDatabaseWork(db, "savepoint", event => events.push(event)); const unsubscribe = subscribeDatabaseWork(db, "savepoint", event => events.push(event));
@@ -92,19 +110,25 @@ const support = await getEmbeddedPostgresTestSupport();
}) as typeof raw.transaction; }) as typeof raw.transaction;
const owner = installDatabaseWorkSignals(raw); const owner = installDatabaseWorkSignals(raw);
const topic = `late-${outcome}`; const topic = `late-${outcome}`;
const settled: string[][] = [];
const unsubscribe = subscribeDatabaseWork(owner, topic, (event, hints) => {
if (event === "settled") settled.push([...(hints ?? [])]);
});
try { try {
await expect(owner.transaction(async tx => { await expect(owner.transaction(async tx => {
await signalDatabaseWork(tx, topic); await signalDatabaseWork(tx, topic, "connection-late");
await tx.execute(sql`insert into work_signal_test values (${topic})`); await tx.execute(sql`insert into work_signal_test values (${topic})`);
})).rejects.toThrow("lost transaction response"); })).rejects.toThrow("lost transaction response");
await reconcileDatabaseWork(owner, topic); await reconcileDatabaseWork(owner, topic);
expect(databaseWorkPending(owner, topic)).toBe(true); expect(databaseWorkPending(owner, topic)).toBe(true);
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(0); expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(0);
settled.length = 0;
release(); await serverDone.catch(() => {}); release(); await serverDone.catch(() => {});
await reconcileDatabaseWork(owner, topic); await reconcileDatabaseWork(owner, topic);
expect(settled).toEqual([["connection-late"]]);
expect(databaseWorkPending(owner, topic)).toBe(false); expect(databaseWorkPending(owner, topic)).toBe(false);
expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(outcome === "commit" ? 1 : 0); expect(await db.execute(sql`select * from work_signal_test where id = ${topic}`)).toHaveLength(outcome === "commit" ? 1 : 0);
} finally { release(); await serverDone?.catch(() => {}); } } finally { release(); await serverDone?.catch(() => {}); unsubscribe(); }
}); });
it("recovers after a real backend disconnect without replaying the queue write", async () => { it("recovers after a real backend disconnect without replaying the queue write", async () => {
+14 -9
View File
@@ -3,16 +3,16 @@ import { sql } from "drizzle-orm";
// Process-local hints about existing durable queues. No SQL triggers, tables, // Process-local hints about existing durable queues. No SQL triggers, tables,
// background timers, or driver query replay. Only opted-in transactions fetch // background timers, or driver query replay. Only opted-in transactions fetch
// an XID, so unrelated transactions keep their existing SQL behavior. // an XID, so unrelated transactions keep their existing SQL behavior.
type Listener = (event: "intent" | "settled") => void; type Listener = (event: "intent" | "settled", hints?: ReadonlySet<string>) => void;
type Transaction = { topics: Set<string>; xid?: Promise<string>; uncertain: boolean }; type Transaction = { topics: Set<string>; hints: Map<string, Set<string>>; xid?: Promise<string>; uncertain: boolean };
type Scope = { listeners: Map<string, Set<Listener>>; transactions: Set<Transaction>; root: Connection }; type Scope = { listeners: Map<string, Set<Listener>>; transactions: Set<Transaction>; root: Connection };
type Context = { scope: Scope; transaction?: Transaction }; type Context = { scope: Scope; transaction?: Transaction };
type Connection = { transaction: (...args: any[]) => Promise<any>; execute: (...args: any[]) => Promise<any> }; type Connection = { transaction: (...args: any[]) => Promise<any>; execute: (...args: any[]) => Promise<any> };
const contexts = new WeakMap<object, Context>(); const contexts = new WeakMap<object, Context>();
function publish(scope: Scope, topic: string, event: "intent" | "settled" = "settled") { function publish(scope: Scope, topic: string, event: "intent" | "settled" = "settled", hints?: ReadonlySet<string>) {
for (const listener of scope.listeners.get(topic) ?? []) { for (const listener of scope.listeners.get(topic) ?? []) {
try { listener(event); } try { listener(event, hints); }
catch (error) { process.emitWarning(`Database work listener failed: ${String(error)}`); } catch (error) { process.emitWarning(`Database work listener failed: ${String(error)}`); }
} }
} }
@@ -30,7 +30,7 @@ function install(connection: Connection, context: Context) {
connection.transaction = async function (callback, ...options) { connection.transaction = async function (callback, ...options) {
// Nested savepoints belong to the outermost transaction. Even a released // Nested savepoints belong to the outermost transaction. Even a released
// savepoint must not wake a consumer before its parent commits. // savepoint must not wake a consumer before its parent commits.
const state = context.transaction ?? { topics: new Set<string>(), uncertain: false }; const state = context.transaction ?? { topics: new Set<string>(), hints: new Map<string, Set<string>>(), uncertain: false };
try { try {
const result = await transaction.call(this, async (tx: Connection) => { const result = await transaction.call(this, async (tx: Connection) => {
install(tx, { scope: context.scope, transaction: state }); install(tx, { scope: context.scope, transaction: state });
@@ -47,20 +47,25 @@ function install(connection: Connection, context: Context) {
} }
throw error; throw error;
} finally { } finally {
if (!context.transaction) for (const topic of state.topics) publish(context.scope, topic); if (!context.transaction) for (const topic of state.topics) publish(context.scope, topic, "settled", state.hints.get(topic));
} }
}; };
} }
/** Await BEFORE the queue write, on its transaction. Nested transactions work. */ /** Await BEFORE the queue write, on its transaction. Nested transactions work. */
export async function signalDatabaseWork(connection: object, topic: string): Promise<void> { export async function signalDatabaseWork(connection: object, topic: string, hint?: string): Promise<void> {
const context = contexts.get(connection); const context = contexts.get(connection);
if (!context) return; // Lightweight service test doubles have no DB lifecycle. if (!context) return; // Lightweight service test doubles have no DB lifecycle.
const state = context.transaction; const state = context.transaction;
if (!state) throw new Error("Database work must be registered inside a transaction"); if (!state) throw new Error("Database work must be registered inside a transaction");
state.topics.add(topic); state.topics.add(topic);
if (hint !== undefined) {
let hints = state.hints.get(topic);
if (!hints) state.hints.set(topic, hints = new Set());
hints.add(hint);
}
context.scope.transactions.add(state); context.scope.transactions.add(state);
publish(context.scope, topic, "intent"); publish(context.scope, topic, "intent", state.hints.get(topic));
if (!state.xid) { if (!state.xid) {
state.xid = (connection as Connection).execute(sql`select pg_current_xact_id()::text as xid`) state.xid = (connection as Connection).execute(sql`select pg_current_xact_id()::text as xid`)
.then((rows: { xid: string }[]) => rows[0]!.xid); .then((rows: { xid: string }[]) => rows[0]!.xid);
@@ -91,7 +96,7 @@ export async function reconcileDatabaseWork(owner: object, topic: string): Promi
throw new Error("Unexpected database transaction status"); throw new Error("Unexpected database transaction status");
} }
scope.transactions.delete(state); scope.transactions.delete(state);
for (const affected of state.topics) publish(scope, affected); for (const affected of state.topics) publish(scope, affected, "settled", state.hints.get(affected));
} }
} }
@@ -107,6 +107,7 @@ describe("createChatReconciliationCoordinator", () => {
// scheduled method returns; app shutdown must also join those workers. // scheduled method returns; app shutdown must also join those workers.
expect(source).toContain("await chatChannels.shutdown()"); expect(source).toContain("await chatChannels.shutdown()");
expect(source).not.toContain("chatChannels.processPendingSlackSessionSyncs()"); expect(source).not.toContain("chatChannels.processPendingSlackSessionSyncs()");
expect(source).not.toContain("chatChannels.processPendingChatMaintenance()");
const service = readFileSync(new URL("../services/chat-channels.ts", import.meta.url), "utf8"); const service = readFileSync(new URL("../services/chat-channels.ts", import.meta.url), "utf8");
const actionMaintenance = service.slice(service.indexOf("async function processPendingChatMaintenance("), const actionMaintenance = service.slice(service.indexOf("async function processPendingChatMaintenance("),
service.indexOf("async function processPendingDeliveries(")); service.indexOf("async function processPendingDeliveries("));
+34 -3
View File
@@ -20,6 +20,10 @@ function setup() {
coordinators.push(coordinator); coordinators.push(coordinator);
const service = { const service = {
processFailedChatRunRetries: vi.fn(async () => {}), processFailedChatRunRetries: vi.fn(async () => {}),
processPendingTelegramActions: vi.fn(async () => {}),
processTelegramSubscriptionDiscovery: vi.fn(async () => {}),
scheduleTelegramSubscriptionDiscovery: vi.fn(),
hasPendingTelegramSubscriptionDiscovery: vi.fn(() => false),
processPendingProviderEffects: vi.fn(async () => {}), processPendingProviderEffects: vi.fn(async () => {}),
processPendingGitHubWebhookIngress: vi.fn(async () => {}), processPendingGitHubWebhookIngress: vi.fn(async () => {}),
processPendingSlackSessionSyncs: vi.fn(async () => {}), processPendingSlackSessionSyncs: vi.fn(async () => {}),
@@ -31,17 +35,40 @@ function setup() {
nextChatActionAt: vi.fn(async (): Promise<number | null> => null), nextChatActionAt: vi.fn(async (): Promise<number | null> => null),
nextVerificationMessageAt: vi.fn(async (): Promise<number | null> => null), nextVerificationMessageAt: vi.fn(async (): Promise<number | null> => null),
}; };
const runs = [service.processFailedChatRunRetries, service.processPendingProviderEffects, service.processPendingGitHubWebhookIngress, service.processPendingSlackSessionSyncs, service.processPendingSlackBoardMessages, service.processPendingSlackTaskStarts, const runs = [service.processFailedChatRunRetries, service.processPendingTelegramActions, service.processPendingProviderEffects, service.processPendingGitHubWebhookIngress, service.processPendingSlackSessionSyncs, service.processPendingSlackBoardMessages, service.processPendingSlackTaskStarts,
service.processPendingReceiptReactions, service.processPendingSlackSessionStops, service.processPendingVerificationMessages]; service.processPendingReceiptReactions, service.processPendingSlackSessionStops, service.processPendingVerificationMessages];
return { owner, service, runs, coordinator, enabled, onError, start: () => registerChatActionWork(coordinator, service, enabled) }; return { owner, service, runs, coordinator, enabled, onError, start: () => registerChatActionWork(coordinator, service, enabled) };
} }
describe("chat action scheduling", () => { describe("chat action scheduling", () => {
it("retains configuration commits during discovery and retries discovery failures", async () => {
const s = setup();
let release!: () => void;
s.service.processTelegramSubscriptionDiscovery.mockImplementationOnce(() => new Promise<void>(resolve => { release = resolve; }));
const work = s.start();
await vi.advanceTimersByTimeAsync(1);
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(1);
await s.owner.transaction(tx => notifyChatEndpointWork(tx, "connection-fixture"));
expect(s.service.scheduleTelegramSubscriptionDiscovery).toHaveBeenCalledWith("connection-fixture");
s.service.processTelegramSubscriptionDiscovery.mockRejectedValueOnce(new Error("discovery unavailable"));
release();
await work.ready;
await vi.advanceTimersByTimeAsync(1);
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(2);
expect(s.onError).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1000);
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(3);
await vi.advanceTimersByTimeAsync(3_600_000);
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(3);
expect(s.coordinator.nextWakeAt()).toBeNull();
});
it("does one startup scan per lane and no more SQL or timers during an idle hour", async () => { it("does one startup scan per lane and no more SQL or timers during an idle hour", async () => {
const s = setup(); const s = setup();
await s.start().ready; await s.start().ready;
await vi.advanceTimersByTimeAsync(3_600_000); await vi.advanceTimersByTimeAsync(3_600_000);
for (const run of s.runs) expect(run).toHaveBeenCalledTimes(1); for (const run of s.runs) expect(run).toHaveBeenCalledTimes(1);
expect(s.service.nextChatActionAt).toHaveBeenCalledTimes(8); expect(s.service.nextChatActionAt).toHaveBeenCalledTimes(9);
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(1);
expect(s.service.scheduleTelegramSubscriptionDiscovery).not.toHaveBeenCalled();
expect(s.service.nextVerificationMessageAt).toHaveBeenCalledTimes(1); expect(s.service.nextVerificationMessageAt).toHaveBeenCalledTimes(1);
expect(s.coordinator.nextWakeAt()).toBeNull(); expect(s.coordinator.nextWakeAt()).toBeNull();
expect(vi.getTimerCount()).toBe(0); expect(vi.getTimerCount()).toBe(0);
@@ -58,9 +85,12 @@ describe("chat action scheduling", () => {
await s.owner.transaction(tx => notifyChatVerificationWork(tx)); await s.owner.transaction(tx => notifyChatVerificationWork(tx));
await vi.advanceTimersByTimeAsync(1); await vi.advanceTimersByTimeAsync(1);
for (const run of s.runs) expect(run).toHaveBeenCalledTimes(2); for (const run of s.runs) expect(run).toHaveBeenCalledTimes(2);
await s.owner.transaction(tx => notifyChatEndpointWork(tx)); // Queue claims/settlements do not rediscover every configured endpoint.
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(1);
await s.owner.transaction(tx => notifyChatEndpointWork(tx, "connection-fixture"));
await vi.advanceTimersByTimeAsync(1); await vi.advanceTimersByTimeAsync(1);
for (const run of s.runs) expect(run).toHaveBeenCalledTimes(3); for (const run of s.runs) expect(run).toHaveBeenCalledTimes(3);
expect(s.service.processTelegramSubscriptionDiscovery).toHaveBeenCalledTimes(2);
expect(vi.getTimerCount()).toBe(0); expect(vi.getTimerCount()).toBe(0);
}); });
it("restores durable deadlines and reschedules when a foreground send moves a retry earlier", async () => { it("restores durable deadlines and reschedules when a foreground send moves a retry earlier", async () => {
@@ -101,6 +131,7 @@ describe("chat action scheduling", () => {
await s.start().ready; await s.start().ready;
await vi.advanceTimersByTimeAsync(2000); await vi.advanceTimersByTimeAsync(2000);
expect(s.service.nextChatActionAt).not.toHaveBeenCalled(); expect(s.service.nextChatActionAt).not.toHaveBeenCalled();
expect(s.service.processTelegramSubscriptionDiscovery).not.toHaveBeenCalled();
for (const run of s.runs) expect(run).not.toHaveBeenCalled(); for (const run of s.runs) expect(run).not.toHaveBeenCalled();
s.enabled.mockReturnValue(true); s.enabled.mockReturnValue(true);
s.service.processPendingSlackTaskStarts.mockRejectedValueOnce(new Error("DB unavailable")); s.service.processPendingSlackTaskStarts.mockRejectedValueOnce(new Error("DB unavailable"));
@@ -1,5 +1,7 @@
import { idleWorkSnapshot } from "../services/task-admission.js"; import { idleWorkSnapshot } from "../services/task-admission.js";
import type { Db } from "@paperclipai/db";
import * as activityLogModule from "../services/activity-log.js"; import * as activityLogModule from "../services/activity-log.js";
import * as connectionCredentialBindings from "../services/connection-credential-bindings.js";
import { chatSlackManagerGrants, chatSlackRegistrations, toolOauthStates } from "@paperclipai/db"; import { chatSlackManagerGrants, chatSlackRegistrations, toolOauthStates } from "@paperclipai/db";
import type { PaperclipCloudConnector, SealedConnectorCredentials } from "../services/paperclip-cloud-connector.js"; import type { PaperclipCloudConnector, SealedConnectorCredentials } from "../services/paperclip-cloud-connector.js";
import { buildSlackAppManifest, SLACK_MANAGER_SCOPES } from "@paperclipai/shared"; import { buildSlackAppManifest, SLACK_MANAGER_SCOPES } from "@paperclipai/shared";
@@ -33061,7 +33063,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
try { try {
for (const kind of Object.keys(CHAT_ACTION_QUEUES) as (keyof typeof CHAT_ACTION_QUEUES)[]) { for (const kind of Object.keys(CHAT_ACTION_QUEUES) as (keyof typeof CHAT_ACTION_QUEUES)[]) {
const [action] = await db.insert(chatActions).values({ companyId: f.companyId, endpointId: lane.endpoint.id, const [action] = await db.insert(chatActions).values({ companyId: f.companyId, endpointId: lane.endpoint.id,
kind, providerActionId: randomUUID(), status: "received", updatedAt: at }).returning(); kind, providerActionId: randomUUID(), status: "received", updatedAt: at,
...(kind === "telegram_maintenance" ? { payload: { operation: "register_commands" } } : {}) }).returning();
const set = (status: string, result: Record<string, unknown> = {}) => db.update(chatActions) const set = (status: string, result: Record<string, unknown> = {}) => db.update(chatActions)
.set({ status, result, updatedAt: at }).where(eq(chatActions.id, action!.id)); .set({ status, result, updatedAt: at }).where(eq(chatActions.id, action!.id));
const due = async () => db.select({ id: chatActions.id }).from(chatActions) const due = async () => db.select({ id: chatActions.id }).from(chatActions)
@@ -70635,6 +70638,195 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
}; };
} }
it.each(["startup", "connection_commit", "rollback", "retry", "stale_claim"] as const)(
"recovers Telegram maintenance from committed work and becomes SQL quiet: %s",
async mode => {
const lane = await draftFixture();
const onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
const maintenance = () => db.select().from(chatActions).where(and(
eq(chatActions.endpointId, lane.endpoint.id), eq(chatActions.kind, "telegram_maintenance"),
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
));
try {
await db.delete(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
eq(chatActions.kind, "telegram_stop_subscription")));
lane.setSubscriptionInfo({});
if (mode === "connection_commit" || mode === "rollback") {
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: false });
}
if (mode === "stale_claim") {
// Leave committed legacy work behind before starting the workers.
await lane.context.service.processTelegramSubscriptionDiscovery();
const [action] = await maintenance();
expect(action).toBeDefined();
await db.update(chatActions).set({ status: "processing", updatedAt: new Date(Date.now() - 120_000) })
.where(eq(chatActions.id, action!.id));
}
let failedAt = 0;
let sends = 0;
if (mode === "retry") lane.setMaintenanceHook(async method => {
if (method === "setWebhook" && sends++ === 0) {
failedAt = Date.now();
throw new Error("temporary subscription transport outage");
}
if (method === "setWebhook") expect(Date.now() - failedAt).toBeGreaterThanOrEqual(1000);
return undefined;
});
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
if (mode === "connection_commit" || mode === "rollback") {
expect(lane.maintenanceRequests).toEqual([]);
if (mode === "rollback") {
await expect(db.transaction(async tx => {
await toolAccessService(tx as unknown as Db).updateConnection(lane.endpoint.connectionId, { enabled: true });
await new Promise(resolve => setTimeout(resolve, 25));
expect(lane.maintenanceRequests).toEqual([]);
throw new Error("rollback connection wake");
})).rejects.toThrow("rollback connection wake");
await vi.waitFor(() => {
expect(coordinator.nextWakeAt()).toBeNull();
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 10_000 });
expect(lane.maintenanceRequests).toEqual([]);
expect(await maintenance()).toEqual([]);
}
await db.transaction(async tx => {
await toolAccessService(tx as unknown as Db).updateConnection(lane.endpoint.connectionId, { enabled: true });
await new Promise(resolve => setTimeout(resolve, 25));
expect(lane.maintenanceRequests).toEqual([]);
});
}
await vi.waitFor(async () => {
const actions = await maintenance();
expect(actions).toHaveLength(1);
expect(actions[0]?.status).toBe("processed");
expect(actions[0]?.result.attempts).toBe(mode === "retry" ? 2 : 1);
expect(coordinator.nextWakeAt()).toBeNull();
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 10_000 });
expect(lane.maintenanceRequests.filter(x => x.method === "setWebhook")).toHaveLength(mode === "retry" ? 2 : 1);
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
eq(chatActions.kind, "telegram_stop_subscription"), eq(chatActions.status, "processed")))).toHaveLength(1);
const scans = vi.spyOn(db, "select");
try {
await new Promise(resolve => setTimeout(resolve, 1200));
expect(scans).not.toHaveBeenCalled();
} finally { scans.mockRestore(); }
expect(onError).not.toHaveBeenCalled();
} finally { await coordinator.stop(); await lane.close(); }
},
);
it("commits chat connection credentials atomically before waking maintenance", async () => {
const lane = await draftFixture();
const onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
const bindings = () => db.select({ secretId: companySecretBindings.secretId, configPath: companySecretBindings.configPath })
.from(companySecretBindings).where(and(eq(companySecretBindings.companyId, lane.fixture.companyId),
eq(companySecretBindings.targetType, "tool_connection"), eq(companySecretBindings.targetId, lane.endpoint.connectionId)))
.orderBy(asc(companySecretBindings.configPath));
let release!: () => void;
let entered!: () => void;
const held = new Promise<void>(resolve => { release = resolve; });
const rebuilding = new Promise<void>(resolve => { entered = resolve; });
let update: Promise<unknown> | undefined;
const original = connectionCredentialBindings.syncConnectionCredentialBindings;
const spy = vi.spyOn(connectionCredentialBindings, "syncConnectionCredentialBindings");
try {
await db.delete(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
eq(chatActions.kind, "telegram_stop_subscription")));
lane.setSubscriptionInfo({});
await lane.context.service.processTelegramSubscriptionDiscovery();
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: false });
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
const before = await bindings();
expect(before.length).toBeGreaterThan(0);
spy.mockImplementation(async (database, connection, refs, client = database) => {
if (connection.id === lane.endpoint.connectionId) {
// Hold the real binding rebuild after its delete boundary. Another
// connection must still see the old bindings until outer commit.
await client.delete(companySecretBindings).where(and(eq(companySecretBindings.companyId, connection.companyId),
eq(companySecretBindings.targetType, "tool_connection"), eq(companySecretBindings.targetId, connection.id)));
entered();
await held;
}
return original(database, connection, refs, client);
});
update = toolAccessService(db).updateConnection(lane.endpoint.connectionId, { name: "Renamed fixture", enabled: true });
await rebuilding;
expect(await bindings()).toEqual(before);
await new Promise(resolve => setTimeout(resolve, 25));
expect(lane.maintenanceRequests).toEqual([]);
release();
await update;
await vi.waitFor(async () => {
expect(await db.select({ status: chatActions.status }).from(chatActions).where(and(
eq(chatActions.endpointId, lane.endpoint.id), eq(chatActions.kind, "telegram_maintenance"),
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
))).toEqual([{ status: "processed" }]);
expect(coordinator.nextWakeAt()).toBeNull();
}, { timeout: 10_000 });
expect(await bindings()).toEqual(before);
expect(lane.maintenanceRequests.filter(x => x.method === "setWebhook")).toHaveLength(1);
expect(onError).not.toHaveBeenCalled();
} finally { release(); await update; spy.mockRestore(); await coordinator.stop(); await lane.close(); }
});
it.each(["endpoint", "connection"] as const)("parks pending Telegram subscription repair while its %s is inactive", async inactive => {
const lane = await draftFixture();
const onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
const actions = () => db.select().from(chatActions).where(and(
eq(chatActions.endpointId, lane.endpoint.id), eq(chatActions.kind, "telegram_maintenance"),
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
));
try {
await db.delete(chatActions).where(and(eq(chatActions.endpointId, lane.endpoint.id),
eq(chatActions.kind, "telegram_stop_subscription")));
lane.setSubscriptionInfo({});
await lane.context.service.processTelegramSubscriptionDiscovery();
expect(await actions()).toEqual([expect.objectContaining({ status: "received" })]);
if (inactive === "endpoint") {
await lane.context.service.configure(lane.endpoint.id, { action: "pause" }, "owner-user");
} else {
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: false });
}
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
await vi.waitFor(() => {
expect(coordinator.nextWakeAt()).toBeNull();
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 10_000 });
expect(await lane.context.service.nextChatActionAt("telegram_maintenance")).toBeNull();
expect(lane.maintenanceRequests).toEqual([]);
expect(await actions()).toEqual([expect.objectContaining({ status: "received" })]);
const scans = vi.spyOn(db, "select");
try {
await new Promise(resolve => setTimeout(resolve, 1200));
expect(scans).not.toHaveBeenCalled();
} finally { scans.mockRestore(); }
if (inactive === "endpoint") {
await lane.context.service.configure(lane.endpoint.id, { action: "resume" }, "owner-user");
} else {
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { enabled: true });
}
await vi.waitFor(async () => {
const rows = await actions();
expect(rows.filter(row => row.status === "processed")).toEqual([
expect.objectContaining({ result: expect.objectContaining({ attempts: 1 }) }),
]);
// Endpoint pause/resume advances its ownership generation. The old
// obligation must settle without touching the provider again.
expect(rows.filter(row => row.status !== "processed")).toEqual(inactive === "endpoint" ? [
expect.objectContaining({ status: "cancelled", result: expect.objectContaining({ code: "telegram_maintenance_credentials_superseded" }) }),
] : []);
expect(coordinator.nextWakeAt()).toBeNull();
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 10_000 });
expect(lane.maintenanceRequests.filter(x => x.method === "setWebhook")).toHaveLength(1);
expect(onError).not.toHaveBeenCalled();
} finally { await coordinator.stop(); await lane.close(); }
});
it("durably stops during the first draft RPC without cancelling a run, and never reuses its ID after restart", async () => { it("durably stops during the first draft RPC without cancelling a run, and never reuses its ID after restart", async () => {
const lane = await draftFixture(); const lane = await draftFixture();
try { try {
@@ -70850,11 +71042,14 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
}, },
); );
it.each(["explicit", "empty", "omitted"] as const)( it.each(["explicit", "empty", "omitted", "worker"] as const)(
"automatically repairs an existing %s subscription after restart without dropping updates", "automatically repairs an existing %s subscription after restart without dropping updates",
async (shape) => { async (mode) => {
const shape = mode === "worker" ? "explicit" : mode;
const lane = await draftFixture(); const lane = await draftFixture();
const prefixIds: string[] = []; const prefixIds: string[] = [];
const onError = vi.fn();
const coordinator = mode === "worker" ? createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError }) : null;
try { try {
// Scheduler-only fixtures model a full already-confirmed first page. // Scheduler-only fixtures model a full already-confirmed first page.
// They have no credentials; no provider qualification is claimed for // They have no credentials; no provider qualification is claimed for
@@ -70862,7 +71057,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
const [templateEndpoint] = await readChatEndpointsById(lane.endpoint.id); const [templateEndpoint] = await readChatEndpointsById(lane.endpoint.id);
const [templateConnection] = await readToolConnectionsById(lane.endpoint.connectionId); const [templateConnection] = await readToolConnectionsById(lane.endpoint.connectionId);
const fingerprint = createHash("sha256").update("[]").digest("hex"); const fingerprint = createHash("sha256").update("[]").digest("hex");
for (let index = 0; index < 25; index++) { for (let index = 0; index < (mode === "worker" ? 105 : 25); index++) {
const id = `00000000-${randomUUID().slice(9)}`; const id = `00000000-${randomUUID().slice(9)}`;
expect(id < lane.endpoint.id).toBe(true); expect(id < lane.endpoint.id).toBe(true);
const connectionId = randomUUID(); const connectionId = randomUUID();
@@ -70959,7 +71154,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
const targetIndex = eligible.findIndex( const targetIndex = eligible.findIndex(
({ id }) => id === lane.endpoint.id, ({ id }) => id === lane.endpoint.id,
); );
expect(targetIndex).toBeGreaterThanOrEqual(25); expect(targetIndex).toBeGreaterThanOrEqual(mode === "worker" ? 105 : 25);
const discoveryPasses = Math.floor(targetIndex / 25) + 1; const discoveryPasses = Math.floor(targetIndex / 25) + 1;
const targetActions = () => const targetActions = () =>
db db
@@ -70972,7 +71167,17 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
sql`${chatActions.payload}->>'operation' = 'stop_subscription'`, sql`${chatActions.payload}->>'operation' = 'stop_subscription'`,
), ),
); );
for (let page = 1; page <= discoveryPasses; page++) { if (coordinator) {
await registerChatActionWork(coordinator, lane.context.service, () => true).ready;
// Startup recovery uses successive bounded pages. The target is
// beyond a complete 100-row confirmed prefix and is not in page one.
expect(await targetActions()).toEqual([]);
await vi.waitFor(async () => {
expect((await targetActions())[0]?.status).toBe("processed");
expect(coordinator.nextWakeAt()).toBeNull();
}, { timeout: 30_000 });
expect(onError).not.toHaveBeenCalled();
} else for (let page = 1; page <= discoveryPasses; page++) {
await lane.context.service.processPendingDeliveries(); await lane.context.service.processPendingDeliveries();
if (page < discoveryPasses) { if (page < discoveryPasses) {
expect(await targetActions()).toEqual([]); expect(await targetActions()).toEqual([]);
@@ -71025,6 +71230,21 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
({ method }) => method === "setWebhook", ({ method }) => method === "setWebhook",
); );
expect(mutations).toHaveLength(1); expect(mutations).toHaveLength(1);
if (coordinator) {
// A committed edit must not rediscover another connection, even
// when its durable proof is absent. Startup covers that inventory.
const foreignEndpoint = prefixIds[0]!;
await db.delete(chatActions).where(and(eq(chatActions.endpointId, foreignEndpoint),
eq(chatActions.kind, "telegram_stop_subscription")));
await toolAccessService(db).updateConnection(lane.endpoint.connectionId, { name: "Scoped Telegram edit" });
await vi.waitFor(() => {
expect(coordinator.nextWakeAt()).toBeNull();
expect(idleWorkSnapshot().active).toBe(0);
}, { timeout: 10_000 });
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, foreignEndpoint),
eq(chatActions.kind, "telegram_maintenance")))).toEqual([]);
expect(lane.maintenanceRequests.filter(({ method }) => method === "setWebhook")).toHaveLength(1);
}
expect(mutations[0]!.body).toEqual({ expect(mutations[0]!.body).toEqual({
url: lane.configuredWebhook.url, url: lane.configuredWebhook.url,
secret_token: lane.configuredWebhook.secret_token, secret_token: lane.configuredWebhook.secret_token,
@@ -71071,6 +71291,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
).toHaveLength(1); ).toHaveLength(1);
} finally { } finally {
try { try {
await coordinator?.stop();
if (prefixIds.length) if (prefixIds.length)
await db await db
.update(chatEndpoints) .update(chatEndpoints)
+3 -1
View File
@@ -1269,7 +1269,9 @@ export async function createApp(
await chatChannels.reconcileProviderRuntimes(); await chatChannels.reconcileProviderRuntimes();
await chatChannels.voice.reconcile(); await chatChannels.voice.reconcile();
}, },
processPendingDeliveries: () => chatChannels.processPendingChatMaintenance(), // Chat delivery, action, and Telegram discovery workers now own these
// duties. Keep the coordinator's other maintenance lanes independent.
processPendingDeliveries: async () => undefined,
processFailedGitHubWebhookDeliveries: () => processFailedGitHubWebhookDeliveries: () =>
chatChannels.processFailedGitHubWebhookDeliveries(), chatChannels.processFailedGitHubWebhookDeliveries(),
projectRunMilestones: () => projectRunMilestones: () =>
+27 -2
View File
@@ -1,5 +1,5 @@
import { and, eq, inArray, lte, or, sql } from "drizzle-orm"; import { and, eq, inArray, lte, or, sql } from "drizzle-orm";
import { chatActions, chatEndpoints, type Db } from "@paperclipai/db"; import { chatActions, chatEndpoints, toolConnections, type Db } from "@paperclipai/db";
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { CHAT_ACTION_QUEUES, type ScheduledChatAction } from "./chat-work-notifications.js"; import { CHAT_ACTION_QUEUES, type ScheduledChatAction } from "./chat-work-notifications.js";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
@@ -50,7 +50,17 @@ function pendingChatAction(kind: ScheduledChatAction) {
? inArray(chatActions.status, ["received", "processing"]) ? inArray(chatActions.status, ["received", "processing"])
: or(inArray(chatActions.status, ["received", "processing"]), : or(inArray(chatActions.status, ["received", "processing"]),
and(eq(chatActions.status, "failed"), sql`${chatActions.result}->>'retryable' = 'true'`)); and(eq(chatActions.status, "failed"), sql`${chatActions.result}->>'retryable' = 'true'`));
return and(eq(chatActions.kind, kind), status); // Subscription repair is parked while its current endpoint/connection is
// inactive. Registration and removal retain their existing dispatch rules.
const telegramEligible = kind === "telegram_maintenance" ? sql`(
${chatActions.payload}->>'operation' <> 'stop_subscription' or exists (
select 1 from ${chatEndpoints} inner join ${toolConnections}
on ${toolConnections.id} = ${chatEndpoints.connectionId} and ${toolConnections.companyId} = ${chatEndpoints.companyId}
where ${chatEndpoints.id} = ${chatActions.endpointId} and ${chatEndpoints.companyId} = ${chatActions.companyId}
and ${chatEndpoints.provider} = 'telegram' and ${chatEndpoints.status} = 'active'
and ${toolConnections.status} = 'active' and ${toolConnections.enabled} = true
))` : undefined;
return and(eq(chatActions.kind, kind), status, telegramEligible);
} }
export function dueChatAction(kind: ScheduledChatAction, now = Date.now()) { export function dueChatAction(kind: ScheduledChatAction, now = Date.now()) {
@@ -67,6 +77,10 @@ export async function nextChatActionAt(db: Db, kind: ScheduledChatAction): Promi
type ChatActionService = { type ChatActionService = {
processFailedChatRunRetries(): Promise<unknown>; processFailedChatRunRetries(): Promise<unknown>;
processPendingTelegramActions(): Promise<unknown>;
processTelegramSubscriptionDiscovery(signal?: AbortSignal): Promise<unknown>;
scheduleTelegramSubscriptionDiscovery(connectionId: string): void;
hasPendingTelegramSubscriptionDiscovery(): boolean;
processPendingProviderEffects(): Promise<unknown>; processPendingProviderEffects(): Promise<unknown>;
processPendingGitHubWebhookIngress(): Promise<unknown>; processPendingGitHubWebhookIngress(): Promise<unknown>;
processPendingSlackSessionSyncs(): Promise<unknown>; processPendingSlackSessionSyncs(): Promise<unknown>;
@@ -86,6 +100,7 @@ export function registerChatActionWork(
) { ) {
const actions = [ const actions = [
{ kind: "failed_run_retry", run: service.processFailedChatRunRetries }, { kind: "failed_run_retry", run: service.processFailedChatRunRetries },
{ kind: "telegram_maintenance", run: service.processPendingTelegramActions },
{ kind: "provider_effect", run: service.processPendingProviderEffects }, { kind: "provider_effect", run: service.processPendingProviderEffects },
{ kind: "github_webhook_ingress", run: service.processPendingGitHubWebhookIngress }, { kind: "github_webhook_ingress", run: service.processPendingGitHubWebhookIngress },
{ kind: "slack_session_sync", run: service.processPendingSlackSessionSyncs }, { kind: "slack_session_sync", run: service.processPendingSlackSessionSyncs },
@@ -101,5 +116,15 @@ export function registerChatActionWork(
queue: DELIVERY_QUEUES.chatVerification, queue: DELIVERY_QUEUES.chatVerification,
run: service.processPendingVerificationMessages, next: service.nextVerificationMessageAt, run: service.processPendingVerificationMessages, next: service.nextVerificationMessageAt,
}, canRun)); }, canRun));
// Startup recovery visits the full inventory in bounded pages. Configuration
// commits only enqueue the changed connection, never restart a global sweep.
const discovery = coordinator.register(DELIVERY_QUEUES.chatTelegramSubscriptions, {
retryMs: 1000,
run: signal => service.processTelegramSubscriptionDiscovery(signal),
onSettled: hints => { for (const id of hints ?? []) service.scheduleTelegramSubscriptionDiscovery(id); },
// Preserve a configuration wake received during idle drain without SQL.
hasPending: async () => !canRun() || service.hasPendingTelegramSubscriptionDiscovery(),
});
workers.push(discovery);
return { ready: Promise.all(workers.map(worker => worker.ready)) }; return { ready: Promise.all(workers.map(worker => worker.ready)) };
} }
+6 -2
View File
@@ -1380,7 +1380,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
const { handleTelegramSlashCommand } = createTelegramCommands({ runtime, runtimeFor, handleSdkMessage }); const { handleTelegramSlashCommand } = createTelegramCommands({ runtime, runtimeFor, handleSdkMessage });
const { stageGitHubWebhookIngress, githubIngressAcceptedResponse, processGitHubWebhookIngress, processFailedGitHubWebhookDeliveries, processPendingGitHubWebhookIngress } = createGitHubWebhookIngress(db, { endpointRecord, runtimeContextForRecord, resolveCredentialRefs, runtimeGeneration, credentialFingerprint, getWebhookPublicBaseUrl, redactError, handleWebhook, runtimeCallbackEndpoint, fetchImpl, persistence, withCredentialMutationLease, isShuttingDown: () => shuttingDown, get githubWebhookReplayBarrier() { return options.githubWebhookReplayBarrier; }, supportedWebhookEvents: SUPPORTED_GITHUB_WEBHOOK_EVENTS }); const { stageGitHubWebhookIngress, githubIngressAcceptedResponse, processGitHubWebhookIngress, processFailedGitHubWebhookDeliveries, processPendingGitHubWebhookIngress } = createGitHubWebhookIngress(db, { endpointRecord, runtimeContextForRecord, resolveCredentialRefs, runtimeGeneration, credentialFingerprint, getWebhookPublicBaseUrl, redactError, handleWebhook, runtimeCallbackEndpoint, fetchImpl, persistence, withCredentialMutationLease, isShuttingDown: () => shuttingDown, get githubWebhookReplayBarrier() { return options.githubWebhookReplayBarrier; }, supportedWebhookEvents: SUPPORTED_GITHUB_WEBHOOK_EVENTS });
const { stageSlackSessionStop, processSlackSessionStop, processPendingSlackSessionStops } = createSlackSessionStop(db, { runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, nonDirectDestinationAllowed, stageAuthorizedTaskControlPublication, getPublicBaseUrl, get heartbeat() { return options.heartbeat; }, redactError }); const { stageSlackSessionStop, processSlackSessionStop, processPendingSlackSessionStops } = createSlackSessionStop(db, { runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, nonDirectDestinationAllowed, stageAuthorizedTaskControlPublication, getPublicBaseUrl, get heartbeat() { return options.heartbeat; }, redactError });
const { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, hasTelegramStopSubscription, recordTelegramStopSubscription } = createTelegramMaintenance(db, { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS }); const { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, processPendingTelegramActions, processTelegramSubscriptionDiscovery, scheduleTelegramSubscriptionDiscovery, hasPendingTelegramSubscriptionDiscovery, hasTelegramStopSubscription, recordTelegramStopSubscription } = createTelegramMaintenance(db, { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS });
const { reconcileGitHubWebhookRepository, reconcileProviderResourceRows, listResources, listGitHubRepositories, replaceResources, toggleAllGitHubRepositories, hasNewerProcessedProviderLifecycleEffect, applyProviderAvailability } = createChatResourceReconciliation(db, { endpointRecord, withCredentialMutationLease, runtimeGeneration, maxErrorText: MAX_ERROR_TEXT }); const { reconcileGitHubWebhookRepository, reconcileProviderResourceRows, listResources, listGitHubRepositories, replaceResources, toggleAllGitHubRepositories, hasNewerProcessedProviderLifecycleEffect, applyProviderAvailability } = createChatResourceReconciliation(db, { endpointRecord, withCredentialMutationLease, runtimeGeneration, maxErrorText: MAX_ERROR_TEXT });
const { applyGitHubInstallationLifecycle } = createGitHubInstallationLifecycle(db, { const { applyGitHubInstallationLifecycle } = createGitHubInstallationLifecycle(db, {
endpointRecord, resolveCredentials, runtimeCallbackEndpoint, runtimeGeneration, credentialFingerprint, endpointRecord, resolveCredentials, runtimeCallbackEndpoint, runtimeGeneration, credentialFingerprint,
@@ -1546,7 +1546,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
if (!current) return; if (!current) return;
const connection = await tx.select().from(toolConnections).where(eq(toolConnections.id, current.connectionId)).then((rows) => rows[0]); const connection = await tx.select().from(toolConnections).where(eq(toolConnections.id, current.connectionId)).then((rows) => rows[0]);
if (!connection?.enabled) throw new Error("Photon endpoint requires operator recovery"); if (!connection?.enabled) throw new Error("Photon endpoint requires operator recovery");
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
await tx.update(chatEndpoints).set({ status: current.setup.step === "complete" ? "active" : "verifying", healthMessage: "Photon receiver connected", lastError: null, updatedAt: new Date() }).where(eq(chatEndpoints.id, endpoint.id)); await tx.update(chatEndpoints).set({ status: current.setup.step === "complete" ? "active" : "verifying", healthMessage: "Photon receiver connected", lastError: null, updatedAt: new Date() }).where(eq(chatEndpoints.id, endpoint.id));
}); });
}, },
@@ -7854,6 +7854,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {
processQueuedDeliveries: () => processPendingDeliveries(25, undefined, false), processQueuedDeliveries: () => processPendingDeliveries(25, undefined, false),
scheduleQueuedPublications: () => processPendingPublications(25, { waitForCompletion: false, maintenance: false }), scheduleQueuedPublications: () => processPendingPublications(25, { waitForCompletion: false, maintenance: false }),
processPendingChatMaintenance, processPendingChatMaintenance,
processPendingTelegramActions,
processTelegramSubscriptionDiscovery,
scheduleTelegramSubscriptionDiscovery,
hasPendingTelegramSubscriptionDiscovery,
processPendingSlackBoardMessages, processPendingSlackBoardMessages,
processPendingSlackTaskStarts, processPendingSlackTaskStarts,
processPendingVerificationMessages: slackRegistration.processPendingVerificationMessages, processPendingVerificationMessages: slackRegistration.processPendingVerificationMessages,
@@ -181,7 +181,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
code: "chat_endpoint_not_active", code: "chat_endpoint_not_active",
}); });
} }
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
await tx await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -317,7 +317,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
inArray(chatDeliveries.state, ["received", "retry"]), inArray(chatDeliveries.state, ["received", "retry"]),
), ),
); );
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
[activatedEndpoint] = await tx [activatedEndpoint] = await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -364,7 +364,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
const failedAt = new Date(); const failedAt = new Date();
await db.transaction(async (tx) => { await db.transaction(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
await tx await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -467,7 +467,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
code: "chat_endpoint_already_removed", code: "chat_endpoint_already_removed",
}); });
} }
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
await tx await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -698,7 +698,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
try { try {
const claimed = await db.transaction(async (tx) => { const claimed = await db.transaction(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
const rows = await tx const rows = await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -778,7 +778,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
const preserveSlackVerification = isProvisionedSlackSetup(current.setup.slackSetupMethod) const preserveSlackVerification = isProvisionedSlackSetup(current.setup.slackSetupMethod)
&& (current.setup as InternalSetupState).slackVerificationSigningFingerprint === createHash("sha256").update(credentials.signingSecret ?? "").digest("hex") && (current.setup as InternalSetupState).slackVerificationSigningFingerprint === createHash("sha256").update(credentials.signingSecret ?? "").digest("hex")
&& Boolean(observedSlackUrl && slackCallbackMatchesPublicUrl(observedSlackUrl, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${endpoint.publicId}/slack`)); && Boolean(observedSlackUrl && slackCallbackMatchesPublicUrl(observedSlackUrl, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${endpoint.publicId}/slack`));
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
await tx await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -863,7 +863,7 @@ export function createChatConfiguration(db: Db, options: ChatConfigurationOption
await invalidateRuntime(endpoint.id).catch(() => undefined); await invalidateRuntime(endpoint.id).catch(() => undefined);
await db.transaction(async (tx) => { await db.transaction(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
await tx await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -157,7 +157,7 @@ export function createDiscordGatewayEvents(db: Db, options: DiscordGatewayEvents
if (current.status === "attention" && !gatewayOwnedAttention) return; if (current.status === "attention" && !gatewayOwnedAttention) return;
const status = const status =
current.setup.step === "complete" ? "active" : "verifying"; current.setup.step === "complete" ? "active" : "verifying";
if (status !== current.status) await notifyChatEndpointWork(tx); if (status !== current.status) await notifyChatEndpointWork(tx, current.connectionId);
await tx await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -508,7 +508,7 @@ export function createChatResourceReconciliation(db: Db, options: ResourceReconc
: currentEndpoint.status === "attention" : currentEndpoint.status === "attention"
? "verifying" ? "verifying"
: currentEndpoint.status; : currentEndpoint.status;
if (status !== currentEndpoint.status) await notifyChatEndpointWork(tx); if (status !== currentEndpoint.status) await notifyChatEndpointWork(tx, currentEndpoint.connectionId);
await tx await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -296,7 +296,7 @@ export function createSetupProbes(db: Db, options: SetupProbesOptions) {
)).limit(1).then((rows) => rows[0]); )).limit(1).then((rows) => rows[0]);
if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your connected account is no longer authorized"); if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your connected account is no longer authorized");
} }
await notifyChatEndpointWork(tx); await notifyChatEndpointWork(tx, endpoint.connectionId);
const [activated] = await tx const [activated] = await tx
.update(chatEndpoints) .update(chatEndpoints)
.set({ .set({
@@ -1,6 +1,7 @@
import type { EndpointRow, DbTransaction, LifecycleRuntimeFence } from "../runtime-types.js"; import type { EndpointRow, DbTransaction, LifecycleRuntimeFence } from "../runtime-types.js";
import { PROVIDER_EFFECT_STALE_MS } from "../../chat-action-work.js"; import { PROVIDER_EFFECT_STALE_MS, dueChatAction } from "../../chat-action-work.js";
import { notifyChatActionWork } from "../../chat-work-notifications.js";
import type { chatCredentialMutationLease, CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js"; import type { chatCredentialMutationLease, CredentialMutationLeaseGuard } from "../../chat-credential-mutation-lease.js";
@@ -12,8 +13,6 @@ import {
asc, asc,
eq, eq,
gt, gt,
lte,
or,
sql, sql,
} from "drizzle-orm"; } from "drizzle-orm";
@@ -103,6 +102,16 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
const { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS } = options; const { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS } = options;
let telegramSubscriptionScanAfter: string | null = null; let telegramSubscriptionScanAfter: string | null = null;
let startupDiscoveryPending = true;
let startupDiscoveryAfter: string | null = null;
const pendingDiscovery = new Map<string, { after: string | null }>();
function withMaintenanceWrite<T>(write: (tx: DbTransaction) => Promise<T>): Promise<T> {
return db.transaction(async tx => {
await notifyChatActionWork(tx, "telegram_maintenance");
return write(tx);
});
}
async function stageTelegramMaintenance( async function stageTelegramMaintenance(
endpoint: EndpointRow, endpoint: EndpointRow,
@@ -122,7 +131,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
? `${context.generation}:${record.endpoint.setup.testStartedAt ?? record.endpoint.updatedAt.toISOString()}` ? `${context.generation}:${record.endpoint.setup.testStartedAt ?? record.endpoint.updatedAt.toISOString()}`
: String(context.generation); : String(context.generation);
const providerActionId = `telegram_maintenance:${operation}:${operationGeneration}`; const providerActionId = `telegram_maintenance:${operation}:${operationGeneration}`;
const [inserted] = await db const [inserted] = await withMaintenanceWrite(tx => tx
.insert(chatActions) .insert(chatActions)
.values({ .values({
companyId: endpoint.companyId, companyId: endpoint.companyId,
@@ -144,7 +153,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
status: "received", status: "received",
}) })
.onConflictDoNothing() .onConflictDoNothing()
.returning(); .returning());
return ( return (
inserted ?? inserted ??
(await db (await db
@@ -241,7 +250,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
if (action.status === "processed") return "processed"; if (action.status === "processed") return "processed";
const payload = telegramMaintenancePayload(action.payload); const payload = telegramMaintenancePayload(action.payload);
if (!payload) { if (!payload) {
await db await withMaintenanceWrite(tx => tx
.update(chatActions) .update(chatActions)
.set({ .set({
status: "failed", status: "failed",
@@ -251,18 +260,18 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
}, },
updatedAt: new Date(), updatedAt: new Date(),
}) })
.where(eq(chatActions.id, action.id)); .where(eq(chatActions.id, action!.id)));
return "failed"; return "failed";
} }
if (action.status === "processing") { if (action.status === "processing") {
if (action.updatedAt > new Date(Date.now() - PROVIDER_EFFECT_STALE_MS)) if (action.updatedAt > new Date(Date.now() - PROVIDER_EFFECT_STALE_MS))
return "pending"; return "pending";
await db await withMaintenanceWrite(tx => tx
.update(chatActions) .update(chatActions)
.set({ .set({
status: "failed", status: "failed",
result: { result: {
...(action.result ?? {}), ...(action!.result ?? {}),
retryable: true, retryable: true,
retryAt: new Date().toISOString(), retryAt: new Date().toISOString(),
}, },
@@ -270,11 +279,11 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
}) })
.where( .where(
and( and(
eq(chatActions.id, action.id), eq(chatActions.id, action!.id),
eq(chatActions.status, "processing"), eq(chatActions.status, "processing"),
eq(chatActions.updatedAt, action.updatedAt), eq(chatActions.updatedAt, action!.updatedAt),
), ),
); ));
action = await db action = await db
.select() .select()
.from(chatActions) .from(chatActions)
@@ -297,7 +306,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
? action.result.attempts ? action.result.attempts
: 0) + 1; : 0) + 1;
let providerConfirmed = action.result?.providerConfirmed === true; let providerConfirmed = action.result?.providerConfirmed === true;
const [claimed] = await db.transaction(async (tx) => { const [claimed] = await withMaintenanceWrite(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
const rows = await tx const rows = await tx
.update(chatActions) .update(chatActions)
@@ -334,7 +343,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
// Empty refs prove removal cleanup crossed its final local boundary; // Empty refs prove removal cleanup crossed its final local boundary;
// settle the idempotent action instead of misclassifying it as a // settle the idempotent action instead of misclassifying it as a
// credential rotation. // credential rotation.
await db.transaction(async (tx) => { await withMaintenanceWrite(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
await tx await tx
.update(chatActions) .update(chatActions)
@@ -361,7 +370,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
runtimeGeneration(record.endpoint.setup) !== runtimeGeneration(record.endpoint.setup) !==
payload.runtimeGeneration) payload.runtimeGeneration)
) { ) {
await db.transaction(async (tx) => { await withMaintenanceWrite(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
await tx await tx
.update(chatActions) .update(chatActions)
@@ -422,7 +431,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
providerConfirmed = true; providerConfirmed = true;
} }
await credentialLease.assertOwned(); await credentialLease.assertOwned();
await db.transaction(async (tx) => { await withMaintenanceWrite(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
const confirmed = await tx const confirmed = await tx
.update(chatActions) .update(chatActions)
@@ -450,7 +459,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
await credentialLease.assertOwned(); await credentialLease.assertOwned();
await clearCredentials(record.endpoint, credentialLease); await clearCredentials(record.endpoint, credentialLease);
} }
await db.transaction(async (tx) => { await withMaintenanceWrite(async (tx) => {
await credentialLease.assertOwned(tx); await credentialLease.assertOwned(tx);
const processed = await tx const processed = await tx
.update(chatActions) .update(chatActions)
@@ -499,7 +508,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
? new Date(Date.now() + retryAfterMs).toISOString() ? new Date(Date.now() + retryAfterMs).toISOString()
: null; : null;
const diagnostic = redactError(error); const diagnostic = redactError(error);
await db await withMaintenanceWrite(tx => tx
.update(chatActions) .update(chatActions)
.set({ .set({
status: "failed", status: "failed",
@@ -507,7 +516,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
attempts: attempt, attempts: attempt,
code: `telegram_maintenance_${disposition.kind}`, code: `telegram_maintenance_${disposition.kind}`,
providerConfirmed: providerConfirmed:
providerConfirmed || action.result?.providerConfirmed === true, providerConfirmed || action!.result?.providerConfirmed === true,
redactedError: diagnostic, redactedError: diagnostic,
retryable, retryable,
retryAt, retryAt,
@@ -516,11 +525,11 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
}) })
.where( .where(
and( and(
eq(chatActions.id, action.id), eq(chatActions.id, action!.id),
eq(chatActions.status, "processing"), eq(chatActions.status, "processing"),
sql`(${chatActions.result}->>'attempts')::int = ${attempt}`, sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,
), ),
); ));
await logActivity(db, { await logActivity(db, {
companyId: action.companyId, companyId: action.companyId,
actorType: "system", actorType: "system",
@@ -554,7 +563,7 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
} }
} }
async function processPendingTelegramMaintenance(limit = 25) { async function discoverTelegramSubscriptions(limit: number, after: string | null, connectionId?: string, signal?: AbortSignal) {
// Keyset scanning bounds each sweep without starving endpoints behind a // Keyset scanning bounds each sweep without starving endpoints behind a
// page whose subscriptions were already confirmed. No provider I/O here. // page whose subscriptions were already confirmed. No provider I/O here.
const candidates = await db const candidates = await db
@@ -573,18 +582,16 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
eq(chatEndpoints.status, "active"), eq(chatEndpoints.status, "active"),
eq(toolConnections.status, "active"), eq(toolConnections.status, "active"),
eq(toolConnections.enabled, true), eq(toolConnections.enabled, true),
telegramSubscriptionScanAfter connectionId !== undefined ? eq(chatEndpoints.connectionId, connectionId) : undefined,
? gt(chatEndpoints.id, telegramSubscriptionScanAfter) after
? gt(chatEndpoints.id, after)
: undefined, : undefined,
), ),
) )
.orderBy(asc(chatEndpoints.id)) .orderBy(asc(chatEndpoints.id))
.limit(Math.max(1, Math.min(limit, 100))); .limit(Math.max(1, Math.min(limit, 100)));
telegramSubscriptionScanAfter =
candidates.length >= Math.max(1, Math.min(limit, 100))
? candidates.at(-1)!.endpoint.id
: null;
for (const { endpoint } of candidates) { for (const { endpoint } of candidates) {
signal?.throwIfAborted();
try { try {
const record = await endpointRecord(endpoint.id); const record = await endpointRecord(endpoint.id);
if ( if (
@@ -595,42 +602,58 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
)) ))
) )
await stageTelegramMaintenance(record.endpoint, "stop_subscription"); await stageTelegramMaintenance(record.endpoint, "stop_subscription");
} catch { } catch (error) {
logger.warn( logger.warn(
{ endpointId: endpoint.id }, { endpointId: endpoint.id },
"Telegram subscription maintenance could not be staged", "Telegram subscription maintenance could not be staged",
); );
// Keep the pass recoverable. Earlier staged rows are idempotent, and
// failed discovery must not become invisible until the next restart.
throw error;
} }
} }
const now = new Date(); return candidates.length >= Math.max(1, Math.min(limit, 100))
const staleBefore = new Date(now.getTime() - PROVIDER_EFFECT_STALE_MS); ? candidates.at(-1)!.endpoint.id : null;
}
async function processTelegramSubscriptionDiscovery(signal?: AbortSignal) {
signal?.throwIfAborted();
const scoped = pendingDiscovery.entries().next().value;
if (scoped) {
const [connectionId, request] = scoped;
const after = await discoverTelegramSubscriptions(100, request.after, connectionId, signal);
// A commit during this page replaces the request and requires a fresh
// scoped pass, including changes behind its cursor.
if (pendingDiscovery.get(connectionId) === request) {
if (after === null) pendingDiscovery.delete(connectionId);
else request.after = after;
}
} else if (startupDiscoveryPending) {
startupDiscoveryAfter = await discoverTelegramSubscriptions(100, startupDiscoveryAfter, undefined, signal);
startupDiscoveryPending = startupDiscoveryAfter !== null;
}
}
function scheduleTelegramSubscriptionDiscovery(connectionId: string) {
pendingDiscovery.set(connectionId, { after: null });
}
function hasPendingTelegramSubscriptionDiscovery() {
return startupDiscoveryPending || pendingDiscovery.size > 0;
}
async function processPendingTelegramMaintenance(limit = 25) {
// Preserve the explicit bounded recovery helper. The app's periodic
// reconciliation no longer calls it; registered workers own both lanes.
telegramSubscriptionScanAfter = await discoverTelegramSubscriptions(limit, telegramSubscriptionScanAfter);
return processPendingTelegramActions(limit);
}
async function processPendingTelegramActions(limit = 25) {
const actions = await db const actions = await db
.select({ id: chatActions.id }) .select({ id: chatActions.id })
.from(chatActions) .from(chatActions)
.where( .where(dueChatAction("telegram_maintenance"))
and(
eq(chatActions.kind, "telegram_maintenance"),
sql`(${chatActions.payload}->>'operation' <> 'stop_subscription' or exists (
select 1 from ${chatEndpoints} inner join ${toolConnections}
on ${toolConnections.id} = ${chatEndpoints.connectionId} and ${toolConnections.companyId} = ${chatEndpoints.companyId}
where ${chatEndpoints.id} = ${chatActions.endpointId} and ${chatEndpoints.companyId} = ${chatActions.companyId}
and ${chatEndpoints.provider} = 'telegram' and ${chatEndpoints.status} = 'active'
and ${toolConnections.status} = 'active' and ${toolConnections.enabled} = true
))`,
or(
eq(chatActions.status, "received"),
and(
eq(chatActions.status, "processing"),
lte(chatActions.updatedAt, staleBefore),
),
and(
eq(chatActions.status, "failed"),
sql`coalesce(${chatActions.result}->>'retryable', 'false') = 'true'`,
sql`(${chatActions.result}->>'retryAt' is null or (${chatActions.result}->>'retryAt')::timestamptz <= ${now.toISOString()}::timestamptz)`,
),
),
),
)
.orderBy(asc(chatActions.createdAt)) .orderBy(asc(chatActions.createdAt))
.limit(limit); .limit(limit);
for (const action of actions) await processTelegramMaintenance(action.id); for (const action of actions) await processTelegramMaintenance(action.id);
@@ -927,5 +950,5 @@ export function createTelegramMaintenance(db: Db, options: TelegramMaintenanceOp
await assertCurrent(); await assertCurrent();
await recordTelegramStopSubscription(endpoint, context, lease); await recordTelegramStopSubscription(endpoint, context, lease);
} }
return { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, hasTelegramStopSubscription, recordTelegramStopSubscription }; return { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, processPendingTelegramActions, processTelegramSubscriptionDiscovery, scheduleTelegramSubscriptionDiscovery, hasPendingTelegramSubscriptionDiscovery, hasTelegramStopSubscription, recordTelegramStopSubscription };
} }
@@ -14,6 +14,7 @@ export const CHAT_ACTION_QUEUES = {
provider_effect: DELIVERY_QUEUES.chatProviderEffects, provider_effect: DELIVERY_QUEUES.chatProviderEffects,
github_webhook_ingress: DELIVERY_QUEUES.chatGitHubIngress, github_webhook_ingress: DELIVERY_QUEUES.chatGitHubIngress,
failed_run_retry: DELIVERY_QUEUES.chatFailedRunRetries, failed_run_retry: DELIVERY_QUEUES.chatFailedRunRetries,
telegram_maintenance: DELIVERY_QUEUES.chatTelegramMaintenance,
slack_session_sync: DELIVERY_QUEUES.chatSessionSyncs, slack_session_sync: DELIVERY_QUEUES.chatSessionSyncs,
slack_board_message: DELIVERY_QUEUES.chatBoardMessages, slack_board_message: DELIVERY_QUEUES.chatBoardMessages,
slash_task_start: DELIVERY_QUEUES.chatTaskStarts, slash_task_start: DELIVERY_QUEUES.chatTaskStarts,
@@ -30,9 +31,10 @@ export async function notifyChatVerificationWork(tx: object): Promise<void> {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatVerification); await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatVerification);
} }
export async function notifyChatEndpointWork(tx: object): Promise<void> { export async function notifyChatEndpointWork(tx: object, connectionId: string): Promise<void> {
await notifyChatDeliveryWork(tx); await notifyChatDeliveryWork(tx);
await notifyChatPublicationWork(tx); await notifyChatPublicationWork(tx);
for (const queue of Object.values(CHAT_ACTION_QUEUES)) await notifyDeliveryWork(tx, queue); for (const queue of Object.values(CHAT_ACTION_QUEUES)) await notifyDeliveryWork(tx, queue);
await notifyChatVerificationWork(tx); await notifyChatVerificationWork(tx);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatTelegramSubscriptions, connectionId);
} }
@@ -22,6 +22,8 @@ export function createDeliveryWorkCoordinator(input: {
retryMs: number; retryMs: number;
run: (signal: AbortSignal) => Promise<unknown>; run: (signal: AbortSignal) => Promise<unknown>;
hasPending: () => Promise<boolean>; hasPending: () => Promise<boolean>;
// Scoped hints belong to the outer transaction, including uncertainty recovery.
onSettled?: (hints?: ReadonlySet<string>) => void;
// Optional maintenance/retry deadline restored from durable state. // Optional maintenance/retry deadline restored from durable state.
nextRunAt?: () => number | null; nextRunAt?: () => number | null;
}) { }) {
@@ -72,7 +74,7 @@ export function createDeliveryWorkCoordinator(input: {
dirty = true; dirty = true;
if (!running) schedule(0); if (!running) schedule(0);
} }
const unsubscribe = subscribeDatabaseWork(input.owner, queue, event => { const unsubscribe = subscribeDatabaseWork(input.owner, queue, (event, hints) => {
if (workerStopped) return; if (workerStopped) return;
if (databaseWorkPending(input.owner, queue)) { if (databaseWorkPending(input.owner, queue)) {
finishIntent ??= beginIdleTrackedWork(); finishIntent ??= beginIdleTrackedWork();
@@ -80,7 +82,7 @@ export function createDeliveryWorkCoordinator(input: {
// replaces this deadline with an immediate wake on the normal path. // replaces this deadline with an immediate wake on the normal path.
if (!running) schedule(task.retryMs); if (!running) schedule(task.retryMs);
} }
if (event === "settled") wake(); if (event === "settled") { task.onSettled?.(hints); wake(); }
}); });
const worker = { wake, async stop() { const worker = { wake, async stop() {
workerStopped = true; workerStopped = true;
@@ -9,6 +9,8 @@ export const DELIVERY_QUEUES = {
chatProviderEffects: "chat-provider-effects", chatProviderEffects: "chat-provider-effects",
chatGitHubIngress: "chat-github-ingress", chatGitHubIngress: "chat-github-ingress",
chatFailedRunRetries: "chat-failed-run-retries", chatFailedRunRetries: "chat-failed-run-retries",
chatTelegramMaintenance: "chat-telegram-maintenance",
chatTelegramSubscriptions: "chat-telegram-subscriptions",
chatSessionSyncs: "chat-session-syncs", chatSessionSyncs: "chat-session-syncs",
chatVerification: "chat-verification", chatVerification: "chat-verification",
chatInbound: "chat-inbound", chatInbound: "chat-inbound",
@@ -25,8 +27,8 @@ export const DELIVERY_QUEUES = {
} as const; } as const;
export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES]; export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES];
export async function notifyDeliveryWork(transaction: object, queue: DeliveryQueue): Promise<void> { export async function notifyDeliveryWork(transaction: object, queue: DeliveryQueue, hint?: string): Promise<void> {
await signalDatabaseWork(transaction, queue); await signalDatabaseWork(transaction, queue, hint);
} }
// Public delivery notification observers only see settled work. The coordinator // Public delivery notification observers only see settled work. The coordinator
// uses the lower-level lifecycle subscription to also fence in-flight writes. // uses the lower-level lifecycle subscription to also fence in-flight writes.
+13 -2
View File
@@ -1,4 +1,5 @@
import { chatCredentialMutationLease } from "./chat-credential-mutation-lease.js"; import { chatCredentialMutationLease } from "./chat-credential-mutation-lease.js";
import { notifyChatEndpointWork } from "./chat-work-notifications.js";
import { removeSlackRegistration } from "./chat-slack-registration-cleanup.js"; import { removeSlackRegistration } from "./chat-slack-registration-cleanup.js";
import { chatEndpoints } from "@paperclipai/db"; import { chatEndpoints } from "@paperclipai/db";
import { AGGREGATOR_NAMES, isAppAggregator, type AggregatorAppsResponse, type ArcadeDiscoverySetupInput } from "@paperclipai/shared/aggregator-apps"; import { AGGREGATOR_NAMES, isAppAggregator, type AggregatorAppsResponse, type ArcadeDiscoverySetupInput } from "@paperclipai/shared/aggregator-apps";
@@ -19047,7 +19048,7 @@ export function toolAccessService(
...(input.credentialRefs ?? existing.credentialRefs), ...(input.credentialRefs ?? existing.credentialRefs),
...(input.credentialSecretRefs ?? existing.credentialSecretRefs), ...(input.credentialSecretRefs ?? existing.credentialSecretRefs),
]); ]);
const [row] = await db const write = (database: Db) => database
.update(toolConnections) .update(toolConnections)
.set({ .set({
name: input.name ?? existing.name, name: input.name ?? existing.name,
@@ -19066,7 +19067,17 @@ export function toolAccessService(
}) })
.where(eq(toolConnections.id, connectionId)) .where(eq(toolConnections.id, connectionId))
.returning(); .returning();
await syncCredentialBindings(row); const [row] = existing.transport === "chat_sdk"
? await db.transaction(async tx => {
await notifyChatEndpointWork(tx, existing.id);
const rows = await write(tx as unknown as Db);
// Credential resolution must never observe the binding rebuild's
// delete/insert gap after a configuration wake.
await syncCredentialBindings(rows[0]!, [], tx);
return rows;
})
: await write(db);
if (existing.transport !== "chat_sdk") await syncCredentialBindings(row);
await ensureRuntimeSlot(row); await ensureRuntimeSlot(row);
emitConnectionUpdated(row, existing, "api"); emitConnectionUpdated(row, existing, "api");
return toConnection(row); return toConnection(row);