Merge updated parent into sleep-company-chat-deletion

Preserve the existing PR boundary while integrating master through the sleep migration stack.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-26 18:50:33 -05:00
commit c20d3f76d8
8 files changed
+204 -45

No files matched your search

+30 -6
View File
@@ -4,7 +4,11 @@ The tool-action request and invocation are authoritative. The interaction card
is a projection of their outcome. Previously the aggregate maintenance tick
joined these tables repeatedly, even when every card already matched.
The projection worker now reconciles at startup and after committed changes.
The projection worker reconstructs affected companies at startup and reconciles
after committed changes. Producer hints carry the company ID. Subsequent
candidate discovery and paginated repair queries filter by that company; review
writes cannot drive a scan of another company's terminal history. The shared
scoped worker dispatches one company per pass with one-second minimum spacing.
It retains a 30-second retry only for a mismatch or failed reconciliation.
Configured idle tools, pending reviews without terminal outcomes, and matching
terminal history have no recurring projection SQL or provider calls. This is
@@ -14,14 +18,20 @@ worker quiet, not whole-instance suspension.
`tool-review-projection.ts` owns candidate discovery and pagination. The gateway
retains card interpretation, current-state checks, locks, activity publication,
and the existing continuation callback. The scheduler consumes only `sweep`
and the returned retry obligation. No provider payload enters shared scheduling.
and the existing continuation callback. The scheduler consumes company discovery,
`sweep(companyId)`, and the returned retry obligation. No provider payload enters shared scheduling.
No table or migration is added.
The existing review notification helper now also signals projection repair.
Notifications are awaited before writes and inherit the outer transaction's
commit, rollback, and uncertainty tracking. Unrelated review changes can cause
one empty reconciliation; they do not create a recurring deadline.
one empty company-scoped reconciliation; they do not create a recurring deadline.
Interaction-only writes first check for an actual linked tool request using the
company and affected card IDs. Generic confirmation kinds alone do not signal
any tool-review queue. This also preserves recovery for legacy linked cards
without current tool payload flags. These reads happen in the mutation owner,
not a background poll. Sibling selection shares the update predicate and runs
under the existing issue lock before publishing the notification.
| Producer | Notification ownership |
| --- | --- |
@@ -30,7 +40,7 @@ one empty reconciliation; they do not create a recurring deadline.
| Pending expiry, approved recovery, interrupted claims, Test-tab settlement | Existing review-write boundary |
| Review-queue invalidation | Existing review-write boundary |
| Interaction withdrawal, skip, terminal-issue expiry | Linked-request resolution signals before the mutation |
| Generic confirmation accept/reject, deleted-addressee cancellation | Projection notification before replacing card state in the owning transaction |
| Linked tool-card accept/reject, deleted-addressee cancellation | Projection notification before replacing card state in the owning transaction; unlinked confirmations do not notify |
| Sibling supersession, startup duplicate cleanup, new/historical comment supersession | Projection notification before card replacement, including cases where the request is already terminal |
| Comment-based confirmation resolution | Calls the interaction owner inside the same outer transaction; its later comment-ID update shares that signal |
@@ -55,7 +65,11 @@ Candidate queries page in request-ID order, 100 rows at a time. A card that cann
yet be projected does not starve later pages. Per-row failures do not prevent
attempting the remaining candidates; failures keep the retry. A final mismatch
check retains retries for no-op repairs rather than silently declaring them done.
The joins inspect existing history on activation. This change removes repeated
Failed companies retain their own backoff across notifications while other
companies progress. An unresolved no-op projection retains a 30-second deadline;
a new relevant company change can make it actionable sooner. A company pass
still drains all its pages, preserving progress past an unprojectable card.
The joins inspect that company's history on activation. This change removes repeated
idle scans; it does not introduce an indexed projection-debt table or claim that
an activated reconciliation has constant cost independent of history size.
@@ -104,3 +118,13 @@ interaction run passed 105 cases but timed out in one cleanup hook during a
change or timeout increase was made to force that result. Full repository tests
will run in CI; the local selections do not claim a complete repository test run.
Fresh PR CI/review remains required.
Company-scoping follow-up reproduced two regressions: captured recovery SQL lacked
a company predicate, and ordinary confirmation creation/replacement/cancellation
published three unnecessary tool-projection wakes. Both regressions now pass
through real producers. Additional coverage keeps failed-company retry timing
independent, proves ordinary mutations still complete without recovery scans,
and exercises administrative repair of legacy cards identified by their saved
link rather than payload flags.
Company-scoping follow-up verification: all 180 gateway and startup cases and all 152 interaction and secret-proposal route cases passed against dedicated PostgreSQL test databases. Server typechecking passed. These are local checks; stack CI and deployed sleep qualification remain separate.
@@ -1,6 +1,7 @@
import { approvalQueueSeedingService } from "../services/approval-queue-seeding-work.js";
import { joinRequestRetentionService } from "../services/join-request-retention.js";
import { approvalRetentionService } from "../services/approval-retention.js";
import { createSecretProposalsService } from "../services/secret-proposals.js";
import { logger } from "../middleware/logger.js";
import { getStartupRecoveryState } from "../startup-recovery-state.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
@@ -32,6 +33,7 @@ const {
detectPortMock,
deriveAuthTrustedOriginsMock,
deliveryWorkRegisterMock,
deliveryWorkErrors,
environmentCustomImagesServiceMock,
environmentCustomImagesServiceFactoryMock,
executionWorkspaceServiceFactoryMock,
@@ -56,11 +58,12 @@ const {
};
const caseHandoffDeliveryServiceFactoryMock = vi.fn(() => caseHandoffDeliveryServiceMock);
const completionSweepMock = vi.fn(async () => undefined);
const deliveryWorkRegisterMock = vi.fn((_queue: string, task: {
const deliveryWorkErrors: Array<{ queue: string; error: unknown }> = [];
const deliveryWorkRegisterMock = vi.fn((queue: string, task: {
retryMs?: number;
run: (signal?: AbortSignal) => Promise<unknown>;
hasPending?: () => Promise<boolean>;
}) => ({ ready: task.run(new AbortController().signal).catch(() => undefined), wake: vi.fn() }));
}) => ({ ready: task.run(new AbortController().signal).catch(error => { deliveryWorkErrors.push({ queue, error }); }), wake: vi.fn() }));
const createAppMock = vi.fn(async () => Object.assign((_: unknown, __: unknown) => {}, {
locals: {
fastResponses: { hasPending: vi.fn(async () => false), sweepPending: vi.fn(async () => undefined) },
@@ -73,6 +76,7 @@ const {
nextActionReviewInterruptionAt: vi.fn(async () => null),
recoverApprovedActionReviews: vi.fn(async () => ({ scanned: 0, retry: false })),
repairActionReviewProjections: vi.fn(async () => ({ scanned: 0, retry: false })),
actionReviewProjectionCompanies: vi.fn(async () => []),
approvedActionReviewCompanies: vi.fn(async () => []),
sweepActionReviews: vi.fn(async () => ({ scanned: 0 })),
sweepExpiredActionReviews: vi.fn(async () => ({ scanned: 0 })),
@@ -194,6 +198,7 @@ const {
detectPortMock,
deriveAuthTrustedOriginsMock,
deliveryWorkRegisterMock,
deliveryWorkErrors,
environmentCustomImagesServiceMock,
environmentCustomImagesServiceFactoryMock,
executionWorkspaceServiceFactoryMock,
@@ -480,6 +485,8 @@ vi.mock("../services/native-runtime/native-question-bridge.js", () => ({
vi.mock("../services/secret-proposals.js", () => ({
createSecretProposalsService: vi.fn(() => ({
expiryDeadlines: vi.fn(async () => []),
sweepExpiredForCompany: vi.fn(async () => 0),
nextExpiryAt: vi.fn(async () => null),
sweepExpired: vi.fn(async () => 0),
})),
@@ -529,6 +536,7 @@ async function settleStartupHousekeeping() {
describe("startServer feedback export wiring", () => {
beforeEach(() => {
vi.clearAllMocks();
deliveryWorkErrors.length = 0;
process.env.PAPERCLIP_DECISION_SIGNING_SECRET = "fedcba9876543210fedcba9876543210";
process.env.PAPERCLIP_AGENT_JWT_SECRET = "0123456789abcdef0123456789abcdef";
loadConfigMock.mockReturnValue(buildTestConfig());
@@ -894,6 +902,19 @@ describe("startServer feedback export wiring", () => {
}
});
it("loads secret expiry deadlines successfully during enabled startup", async () => {
loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: true }));
await startServer();
await settleStartupHousekeeping();
const index = deliveryWorkRegisterMock.mock.calls.findIndex(([queue]) => queue === DELIVERY_QUEUES.secretProposalExpiry);
expect(index).toBeGreaterThanOrEqual(0);
await deliveryWorkRegisterMock.mock.results[index].value.ready;
expect(deliveryWorkErrors.filter(({ queue }) => queue === DELIVERY_QUEUES.secretProposalExpiry)).toEqual([]);
const service = vi.mocked(createSecretProposalsService).mock.results[0].value;
expect(service.expiryDeadlines).toHaveBeenCalledExactlyOnceWith(undefined);
expect(service.sweepExpiredForCompany).not.toHaveBeenCalled();
});
it("registers native replacement recovery without an execution-control interval", async () => {
loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: true }));
const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
@@ -359,7 +359,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
async function startProjection() {
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining,
canReconcile: () => true, onError: error => errors.push(error) });
await registerToolReviewProjectionWork(coordinator, { sweep: gateway.repairActionReviewProjections }, () => !draining).ready;
await registerToolReviewProjectionWork(coordinator, { sweep: gateway.repairActionReviewProjections, companies: gateway.actionReviewProjectionCompanies }, () => !draining).ready;
}
async function savedOutcome(pending: Awaited<ReturnType<typeof request>>, source = db,
status: "executed" | "failed" | "expired" | "cancelled" = "executed") {
@@ -393,6 +393,63 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect((await db.select().from(activityLog).where(eq(activityLog.action, "issue.thread_interaction_updated"))).length).toBe(before);
});
it("keeps projection scans scoped to the company whose review changed", async () => {
const other = await createRunFixture(db);
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
const foreign = await request(gateway, db, other);
await gateway.approveActionRequest({ companyId: other.company.id, actionRequestId: foreign.id, actor: { userId: "board" } });
await startProjection(); await quiet();
const before = await projection(foreign);
const reads: Array<{ query: string; params: unknown[] }> = [];
const debug = db.$client.options.debug;
db.$client.options.debug = (_id, query, params) => {
if (/^select/i.test(query) && query.includes('"tool_action_requests"') && query.includes("coalesce("))
reads.push({ query, params: [...params] });
};
try {
for (let index = 0; index < 3; index++) {
const pending = await request();
await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } });
await settle(1500); expect(await projection(pending)).toMatchObject({ status: "executed" });
}
} finally { db.$client.options.debug = debug; }
expect(reads.length).toBeGreaterThan(0);
for (const read of reads) {
expect(read.query).toContain('"tool_action_requests"."company_id" =');
expect(read.params).toContain(fixture.company.id);
expect(read.params).not.toContain(other.company.id);
}
expect(await projection(foreign)).toEqual(before); await quiet();
});
it("does not wake projection repair for ordinary confirmation creation, replacement, or cancellation", async () => {
await startProjection(); await quiet();
const interactions = issueThreadInteractionService(db);
const scope = { id: fixture.issue.id, companyId: fixture.company.id };
const [recipient] = await db.insert(agents).values({ companyId: fixture.company.id,
name: "Plan recipient", role: "engineer", adapterType: "process" }).returning();
const input = { kind: "request_confirmation" as const, addresseeAgentId: recipient.id,
payload: { version: 1 as const, prompt: "Approve this plan?" } };
const signal = vi.fn();
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.toolReviewProjection, signal);
const reads: string[] = [];
const debug = db.$client.options.debug;
db.$client.options.debug = (_id, query) => {
if (/^select/i.test(query) && query.includes('"tool_action_requests"') && query.includes("coalesce(")) reads.push(query);
};
try {
const first = await interactions.create(scope, input, { agentId: fixture.agent.id });
const second = await interactions.create(scope, input, { agentId: fixture.agent.id });
const cancelled = await interactions.cancelPendingForDeletedAddressee(fixture.company.id, recipient.id);
expect(cancelled.map(row => row.id)).toEqual([second.id]);
expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, first.id)))[0].status).toBe("expired");
await settle();
expect(signal).not.toHaveBeenCalled();
expect(reads).toEqual([]);
await quiet();
} finally { unsubscribe(); db.$client.options.debug = debug; }
});
it.each(["executed", "failed", "expired", "cancelled"] as const)("reconstructs a saved %s result after restart and leaves terminal history quiet", async status => {
const pending = await request(); await acceptedCard(pending); await savedOutcome(pending, db, status);
await startProjection(); await quiet();
@@ -453,6 +510,28 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]);
});
it("backs off a failing company while another company's projection completes", async () => {
const other = await createRunFixture(db);
await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company));
const foreign = await request(gateway, db, other); await acceptedCard(foreign); await savedOutcome(foreign, db, "failed");
await db.execute(sql`create function sleep_projection_fail() returns trigger language plpgsql as $$
begin raise exception 'company projection fixture failure'; end $$`);
await db.execute(sql`create trigger sleep_projection_fail before update on issue_thread_interactions
for each row when (new.result->'toolAction'->>'status' = 'failed') execute function sleep_projection_fail()`);
await startProjection(); expect(errors).toHaveLength(1); errors.length = 0;
const retryAt = coordinator!.nextWakeAt(); expect(retryAt).not.toBeNull();
const pending = await request(); await acceptedCard(pending); await savedOutcome(pending);
await request(gateway, db, other);
await settle(5000);
expect(await projection(pending)).toMatchObject({ status: "executed" });
expect(await projection(foreign)).toBeUndefined();
expect(errors).toEqual([]); expect(coordinator!.nextWakeAt()).toBe(retryAt);
await db.execute(sql`drop trigger sleep_projection_fail on issue_thread_interactions`);
await settle(); await quiet();
expect(await projection(foreign)).toMatchObject({ status: "failed" });
expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]);
});
it("rechecks the projection under lock when foreground repair wins the race", async () => {
const pending = await request(); await acceptedCard(pending); await savedOutcome(pending);
const transaction = db.transaction.bind(db);
@@ -492,8 +571,14 @@ describeEmbeddedPostgres("tool gateway service", () => {
expect(await projection(pending)).toMatchObject({ status: "failed" });
});
it("reactivates when an administrative card mutation overwrites a settled projection", async () => {
it.each([false, true])("reactivates when an administrative card mutation overwrites a settled projection (legacy %s)", async legacy => {
const pending = await request();
if (legacy) {
const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, pending.interactionId!));
const payload = { ...card.payload } as Record<string, unknown>;
delete payload.toolAction; delete payload.target;
await db.update(issueThreadInteractions).set({ payload }).where(eq(issueThreadInteractions.id, pending.interactionId!));
}
await db.update(issueThreadInteractions).set({ addresseeAgentId: fixture.agent.id,
result: { version: 1, outcome: "accepted" } }).where(eq(issueThreadInteractions.id, pending.interactionId!));
await savedOutcome(pending, db, "failed"); await startProjection(); await quiet();
+1 -1
View File
@@ -1493,7 +1493,7 @@ async function startServerWithDatabaseTeardown(
await app.locals.toolGateway.settleInterruptedActionReviews();
}
return config.heartbeatSchedulerEnabled
? registerToolReviewProjectionWork(deliveryWork, { sweep: app.locals.toolGateway.repairActionReviewProjections },
? registerToolReviewProjectionWork(deliveryWork, { sweep: app.locals.toolGateway.repairActionReviewProjections, companies: app.locals.toolGateway.actionReviewProjectionCompanies },
() => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready
: app.locals.toolGateway.repairActionReviewProjections();
}).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed"));
@@ -1073,8 +1073,22 @@ class InteractionResolvedConcurrentlyError extends Error {
// tool_action_requests row. Administrative resolutions (withdraw, terminal-issue
// expiry) must settle that row too, or the parked call stays approvable under
// its own one-hour lifecycle after its card is gone.
async function hasLinkedToolActionRequests(db: Pick<Db, "select">, companyId: string, interactionIds: string[]) {
if (interactionIds.length === 0) return false;
const [request] = await db.select({ id: toolActionRequests.id }).from(toolActionRequests)
.where(and(eq(toolActionRequests.companyId, companyId), inArray(toolActionRequests.interactionId, interactionIds)))
.limit(1);
return request !== undefined;
}
async function notifyToolProjectionForInteractions(db: Pick<Db, "select">, companyId: string, interactionIds: string[]) {
// The persisted link also covers legacy cards without current payload flags.
if (await hasLinkedToolActionRequests(db, companyId, interactionIds))
await notifyDeliveryWork(db, DELIVERY_QUEUES.toolReviewProjection, companyId);
}
async function resolveLinkedToolActionRequests(
db: Pick<Db, "update">,
db: Pick<Db, "select" | "update">,
interaction: Pick<IssueThreadInteractionRow, "id" | "companyId" | "kind">,
outcome: {
status: "expired" | "cancelled";
@@ -1083,7 +1097,8 @@ async function resolveLinkedToolActionRequests(
now: Date;
},
) {
if (interaction.kind !== "request_confirmation") return;
if (interaction.kind !== "request_confirmation" ||
!(await hasLinkedToolActionRequests(db, interaction.companyId, [interaction.id]))) return;
await notifyToolReviewChange(db, interaction.companyId);
await db
.update(toolActionRequests)
@@ -2240,7 +2255,7 @@ export function issueThreadInteractionService(
})
: undefined;
if (lockedCurrent.kind === "request_confirmation") await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolReviewProjection);
if (lockedCurrent.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, lockedCurrent.companyId, [lockedCurrent.id]);
const [updated] = await tx
.update(issueThreadInteractions)
.set({
@@ -2518,7 +2533,7 @@ export function issueThreadInteractionService(
now,
});
if (lockedCurrent.kind === "request_confirmation") await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolReviewProjection);
if (lockedCurrent.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, lockedCurrent.companyId, [lockedCurrent.id]);
const [resolved] = await tx
.update(issueThreadInteractions)
.set({
@@ -3262,7 +3277,7 @@ export function issueThreadInteractionService(
const cancelled: IssueThreadInteraction[] = [];
for (const row of rows) {
const updated = await db.transaction(async (tx) => {
if (row.kind === "request_confirmation") await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolReviewProjection);
if (row.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, row.companyId, [row.id]);
const [resolved] = await tx
.update(issueThreadInteractions)
.set({
@@ -3347,7 +3362,7 @@ export function issueThreadInteractionService(
const expired: IssueThreadInteraction[] = [];
for (const { row, replacementInteractionId } of supersededRows) {
const updated = await db.transaction(async (tx) => {
if (row.kind === "request_confirmation") await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolReviewProjection);
if (row.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, row.companyId, [row.id]);
const [updatedRow] = await tx
.update(issueThreadInteractions)
.set({
@@ -3767,7 +3782,19 @@ export function issueThreadInteractionService(
data.kind === "ask_user_questions"
? buildSupersededByNewerInteractionResult(row.id)
: buildSupersededByNewerRequestResult(row.id);
if (data.kind === "request_confirmation") await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolReviewProjection);
const siblingCondition = and(
eq(issueThreadInteractions.companyId, issue.companyId),
eq(issueThreadInteractions.issueId, issue.id),
eq(issueThreadInteractions.kind, data.kind),
eq(issueThreadInteractions.createdByAgentId, actor.agentId),
eq(issueThreadInteractions.status, "pending"),
ne(issueThreadInteractions.id, row.id),
);
if (data.kind === "request_confirmation") {
// The issue lock above excludes concurrent interaction creation.
const siblings = await tx.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(siblingCondition);
await notifyToolProjectionForInteractions(tx, issue.companyId, siblings.map(sibling => sibling.id));
}
const supersededRows = await tx
.update(issueThreadInteractions)
.set({
@@ -3778,17 +3805,7 @@ export function issueThreadInteractionService(
resolvedAt: now,
updatedAt: now,
})
.where(
and(
eq(issueThreadInteractions.companyId, issue.companyId),
eq(issueThreadInteractions.issueId, issue.id),
eq(issueThreadInteractions.kind, data.kind),
eq(issueThreadInteractions.createdByAgentId, actor.agentId),
eq(issueThreadInteractions.status, "pending"),
ne(issueThreadInteractions.id, row.id),
),
)
.where(siblingCondition)
.returning();
for (const supersededRow of supersededRows) {
await resolveLinkedToolActionRequests(tx, supersededRow, {
@@ -4434,7 +4451,7 @@ export function issueThreadInteractionService(
.delete(toolOauthStates)
.where(eq(toolOauthStates.interactionId, row.id));
}
if (row.kind === "request_confirmation") await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolReviewProjection);
if (row.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, row.companyId, [row.id]);
const [resolved] = await tx
.update(issueThreadInteractions)
.set({
@@ -4603,7 +4620,7 @@ export function issueThreadInteractionService(
);
if (!sampleConfirmationRow) continue;
const updatedInteractions = await db.transaction(async (tx) => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolReviewProjection);
await notifyToolProjectionForInteractions(tx, issue.companyId, confirmationRowIds);
const updatedRows = await tx
.update(issueThreadInteractions)
.set({
+1
View File
@@ -9669,6 +9669,7 @@ export function createToolGatewayService(
},
repairActionReviewProjections: reviewProjection.sweep,
actionReviewProjectionCompanies: reviewProjection.companies,
settleInterruptedActionReviews: reviewInterruption.sweep,
nextActionReviewInterruptionAt: reviewInterruption.next,
sweepExpiredActionReviews: reviewExpiry.sweep,
@@ -1,6 +1,6 @@
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { registerDeadlineWork } from "./deadline-work.js";
import { registerScopedDeadlineWork } from "./scoped-deadline-work.js";
import type { toolReviewProjectionService } from "./tool-review-projection.js";
export function registerToolReviewProjectionWork(
@@ -8,13 +8,16 @@ export function registerToolReviewProjectionWork(
service: ReturnType<typeof toolReviewProjectionService>,
canRun: () => boolean,
) {
let next: number | null = null;
return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewProjection, {
retryMs: 30_000, canRun,
run: async () => {
const result = await service.sweep();
next = result.retry ? Date.now() + 30_000 : null;
return registerScopedDeadlineWork(coordinator, {
queue: DELIVERY_QUEUES.toolReviewProjection,
batchSize: 1,
decodeScope: hint => hint === "*" ? undefined : hint,
matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId,
load: async (companyId?: string) => (await service.companies(companyId))
.map(row => ({ ...row, id: row.companyId, dueAt: Date.now() })),
check: async entry => {
const result = await service.sweep(entry.companyId);
return result.retry ? { ...entry, dueAt: Date.now() + 30_000 } : null;
},
next: async () => next,
});
}, canRun);
}
+13 -5
View File
@@ -12,21 +12,29 @@ export function toolReviewProjectionService(db: Db, reflect: (input: {
inArray(toolActionRequests.status, ["executed", "failed", "expired", "cancelled"]),
sql`coalesce(${issueThreadInteractions.result}->'toolAction'->>'status', '') <> case when ${toolActionRequests.status} = 'cancelled' then 'expired' else ${toolActionRequests.status} end`,
);
const candidates = (cursor?: string) => db
const candidates = (companyId?: string, cursor?: string) => db
.select({ request: toolActionRequests, invocation: toolInvocations })
.from(toolActionRequests)
.innerJoin(issueThreadInteractions, eq(issueThreadInteractions.id, toolActionRequests.interactionId))
.innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
.where(and(mismatch, cursor ? gt(toolActionRequests.id, cursor) : undefined))
.where(and(mismatch, companyId ? eq(toolActionRequests.companyId, companyId) : undefined,
cursor ? gt(toolActionRequests.id, cursor) : undefined))
.orderBy(asc(toolActionRequests.id));
return {
async sweep() {
companies(companyId?: string) {
return db.select({ companyId: toolActionRequests.companyId }).from(toolActionRequests)
.innerJoin(issueThreadInteractions, eq(issueThreadInteractions.id, toolActionRequests.interactionId))
.innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
.where(and(mismatch, companyId ? eq(toolActionRequests.companyId, companyId) : undefined))
.groupBy(toolActionRequests.companyId);
},
async sweep(companyId?: string) {
let cursor: string | undefined;
let scanned = 0;
const failures: unknown[] = [];
for (;;) {
const rows = await candidates(cursor).limit(100);
const rows = await candidates(companyId, cursor).limit(100);
for (const { request, invocation } of rows) {
try {
await reflect({ actionRequestId: request.id,
@@ -40,7 +48,7 @@ export function toolReviewProjectionService(db: Db, reflect: (input: {
cursor = rows[rows.length - 1].request.id;
}
if (failures.length) throw new AggregateError(failures, "Tool review projection repair failed");
return { scanned, retry: (await candidates().limit(1)).length > 0 };
return { scanned, retry: (await candidates(companyId).limit(1)).length > 0 };
},
};
}