mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
fix(connections): remove connection content when a task or company is deleted (#22636)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents call connected apps, such as Google Workspace, and Paperclip keeps parts of the results in tool-call records, approvals, run transcripts and files > - #22010 added "Delete data" on a connection. It removes that content for one connection. > - Deleting a task or a company did not run the same cleanup. Task deletion set the task link to null on tool calls, approvals and runs, so their previews and transcripts stayed. Company deletion removed the rows but left run logs and files in storage. > - Google's restricted-scope review requires that users can delete the Google data we hold, and that the policy matches the product > - This pull request runs the "Delete data" steps when a task is deleted, and removes a deleted company's run logs and files from storage in the background > - The benefit is that deleting a task or a company removes every copy of connection content, and a canary test makes sure that a new store cannot skip these paths ## Linked Issues or Issue Description Refs #22010 **Problem** Deleting a task leaves connection content in tool-call previews, audit history, approval requests, results passed to later runs, run transcripts (events, excerpts, result text and the run log in every copy) and saved tool results over 500,000 bytes. Deleting a company leaves run logs (object journal, archive, local file, S3 mirror) and all stored files, including attachments and saved tool results. "Delete data" on a connection also left saved tool results over 500,000 bytes in storage. **Expected behavior** Deleting a task removes the connection content of the task's runs and calls. Deleting a company removes its run logs and files from storage, not only its rows. "Delete data" removes saved tool results of the runs whose transcripts it deletes. **Steps to reproduce** 1. Let an agent call a connection on a task, so that the run has a log, events and a saved tool result. 2. Delete the task, or delete the company. 3. Look in `tool_invocations`, `heartbeat_runs`, `heartbeat_run_events` and object storage. The content is still there. ## What Changed - New table `issue_connection_content_deletions`. Task deletion records, in the same transaction and before the task row goes, the task's runs that used a connection or are still working, the task's calls without a run, and the task's call events that belong to neither. Audit entries are matched by run, call or task. The background worker then runs the existing "Delete data" steps for that scope. Runs of the task that are still working are recorded too, even if they have not used a connection yet, so a connection call they make after the deletion is also cleared. The job rechecks every 1 to 5 minutes while runs or approvals are open and finishes as soon as they settle, for up to a day. It writes an `issue.connection_content_deleted` activity entry with counts only, and only when it deleted something. - New table `stored_object_deletions`. Company deletion records every run log and every file of the company before the rows go. The table has no foreign key to the company, so the removal continues after the company is gone. Each object is retried with backoff until storage confirms the deletion. Task deletion also records the task's attached files here, so a failed best-effort delete in the route is retried. - `content-deletion.ts` stays the one owner of "remove connection content". Each job table has its own typed store (load, save, finish, activity, failure), so no per-table column can compile against the other table. The storage ledger is in `stored-object-deletion.ts`, and the task request is in `issue-content-deletion.ts`. The steps now take a scope (one connection, or the runs and calls of one deleted task). The connection path behaves as before. - "Delete data" and task deletion now also delete saved tool results over 500,000 bytes (`runner-api` assets) of each run whose transcript they delete: the object in storage and the asset row. Files attached to a task, a case or a company logo are not touched. - The canary test scans every text and JSON column and every storage copy (object journal, legacy mirror, local files and file storage) after a connection deletion, a task deletion and a company deletion. It also checks that another task and another company keep their content. - Docs: the store inventory in `doc/memory/google-connector-memory.md` has columns for task and company deletion. The production checklist, the code-fixes plan, the connector playbook and the user help page `docs/guides/board-operator/deleting-connection-data.md` are updated. ## Verification - `cd server && npx vitest run src/__tests__/tool-connection-content-deletion-canary.test.ts` (12 tests). Before the fix, the new task and company tests failed: the scan found the marker in run logs, the legacy mirror, local files, saved results and attachments. The connection test also failed on the saved tool result file. - `cd server && npx vitest run src/__tests__/tool-connection-content-deletion.test.ts src/__tests__/google-managed-connection-removal.test.ts src/__tests__/git-restore-point-ledger.test.ts src/__tests__/agent-observability.test.ts` (85 tests pass). - Nine more suites that delete tasks or companies pass (456 tests), for example `decision-target-work`, `approval-retention-work`, `cleanup-removal-service` and `tool-gateway-service`. - `pnpm --filter @paperclipai/db typecheck` passes, including the migration compatibility guard (`0501` is `online_compatible`: two new tables and their indexes). - `cd server && pnpm typecheck` passes. - `pnpm verify` exits 2 because a global CI input changed. Required CI supplies the broad coverage. ## Risks - Migration: two new tables only. The previous release does not read them, so it keeps working during the overlap deploy. - Task deletion runs three more indexed queries in its transaction. It creates a job only when the task used a connection. - Company deletion inserts one ledger row per run log and per file in its existing transaction. The storage work is batched in the background, 50 objects at a time. - Company deletion now removes all of the company's files and run logs from storage. Before, they stayed in storage with no row that pointed to them. - `stored_object_deletions` keeps `company_id` without a foreign key, like `execution_workspace_restore_points`, so that removal can finish after the company is gone. It holds object keys only, no content. - A task deletion creates a job when the task used a connection or still has a run that is working. While runs or approvals are open, the job rechecks every 1 to 5 minutes. It stops waiting one day after the deletion. It then writes `issue.connection_content_deletion_incomplete` with the counts of what was still open, and that content stays. A job that deleted nothing and left nothing open writes no activity entry. - A run of the deleted task that was still working is in the scope. If it calls a connection after the task is deleted, the job waits for it and clears that content too. - Not changed: deleting a company does not ask Google to revoke the grant. Raw provider traces still expire on their own. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edit, test runs). Extended reasoning on. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ad163d0e36
commit
a3af1ac6db
17 files changed
+3068
-159
No files matched your search
@@ -4,15 +4,18 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { Readable } from "node:stream";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import {
|
||||
agentWakeupRequests,
|
||||
agents,
|
||||
assets,
|
||||
companies,
|
||||
createDb,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
issueAttachments,
|
||||
issueComments,
|
||||
issueConnectionContentDeletions,
|
||||
issues,
|
||||
issueThreadInteractions,
|
||||
toolAccessAuditEvents,
|
||||
@@ -22,6 +25,7 @@ import {
|
||||
toolConnections,
|
||||
toolInvocations,
|
||||
toolMcpAppViews,
|
||||
runnerApiResponseReservations,
|
||||
} from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { createConnectionContentDeletion } from "../services/tool-access/connections/content-deletion.js";
|
||||
@@ -29,6 +33,10 @@ import { composeRunLogStore, createDurableRunLogStore, type RunLogHandle, type R
|
||||
import { createObjectRunLogStore } from "../services/object-run-log-store.js";
|
||||
import { summarizeToolValue } from "../services/tool-content-guards.js";
|
||||
import type { StorageProvider } from "../storage/types.js";
|
||||
import { createStorageService } from "../storage/service.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { deleteCompany } from "../services/company-deletion.js";
|
||||
import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
@@ -36,6 +44,7 @@ const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe :
|
||||
const OUT_OF_SCOPE_COLUMNS = new Map([
|
||||
["issue_comments.body", "Comments an agent wrote into the task. The user removes them by editing or deleting the comment or the task."],
|
||||
]);
|
||||
const TASK_FILE_NAMESPACE = "/issues/";
|
||||
|
||||
function memoryProvider() {
|
||||
const objects = new Map<string, Buffer>();
|
||||
@@ -105,7 +114,8 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
const objects = memoryProvider();
|
||||
const local = createDurableRunLogStore({ basePath: dir, s3: { provider: mirror.provider } });
|
||||
const external = createObjectRunLogStore({ provider: objects.provider, keyPrefix: "run-logs", assertWriterAuthority: async () => undefined });
|
||||
return { dir, mirror, objects, local, external, store: composeRunLogStore(local, external) };
|
||||
const files = memoryProvider();
|
||||
return { dir, mirror, objects, files, storage: createStorageService(files.provider), local, external, store: composeRunLogStore(local, external) };
|
||||
}
|
||||
|
||||
async function writeLog(store: RunLogStore, ids: { companyId: string; agentId: string; runId: string }, text: string) {
|
||||
@@ -195,6 +205,15 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
|
||||
await db.insert(issueComments).values({ companyId, issueId: base.issue.id, authorAgentId: base.agent.id, body: `Agent note: ${marker}` });
|
||||
|
||||
const saved = await logs.storage.putFile({ companyId, namespace: "runner-api", originalFilename: "response.json", contentType: "application/json",
|
||||
body: Buffer.from(JSON.stringify({ text: `Oversized result ${marker}` })) });
|
||||
const [savedAsset] = await db.insert(assets).values({ companyId, ...saved, createdByAgentId: base.agent.id }).returning();
|
||||
await db.insert(runnerApiResponseReservations).values({ companyId, runId: callingRunId, assetId: savedAsset!.id, reservedBytes: saved.byteSize });
|
||||
const attached = await logs.storage.putFile({ companyId, namespace: "issues", originalFilename: "notes.txt", contentType: "text/plain",
|
||||
body: Buffer.from(`Attached copy of ${marker}`) });
|
||||
const [attachedAsset] = await db.insert(assets).values({ companyId, ...attached, createdByAgentId: base.agent.id }).returning();
|
||||
await db.insert(issueAttachments).values({ companyId, issueId: base.issue.id, assetId: attachedAsset!.id });
|
||||
|
||||
return { connection: connection!, actionRequest: actionRequest!, result, callingRunId };
|
||||
}
|
||||
|
||||
@@ -225,13 +244,13 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
return runId;
|
||||
}
|
||||
|
||||
async function scan(markers: string[], logs: ReturnType<typeof stores>) {
|
||||
async function scan(markers: string[], logs: ReturnType<typeof stores>, options: { taskOwnedCopies?: boolean } = {}) {
|
||||
const columns = await db.execute(sql`select table_name, column_name from information_schema.columns
|
||||
where table_schema = 'public' and data_type in ('text', 'character varying', 'jsonb', 'json')`);
|
||||
const hits: string[] = [];
|
||||
for (const row of columns as unknown as Array<{ table_name: string; column_name: string }>) {
|
||||
const name = `${row.table_name}.${row.column_name}`;
|
||||
if (OUT_OF_SCOPE_COLUMNS.has(name)) continue;
|
||||
if (!options.taskOwnedCopies && OUT_OF_SCOPE_COLUMNS.has(name)) continue;
|
||||
for (const marker of markers) {
|
||||
const found = await db.execute(sql`select 1 from ${sql.identifier(row.table_name)}
|
||||
where ${sql.identifier(row.column_name)}::text like ${`%${marker}%`} limit 1`);
|
||||
@@ -239,17 +258,28 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
}
|
||||
}
|
||||
for (const marker of markers) {
|
||||
for (const [label, objects] of [["object store", logs.objects.objects], ["legacy mirror", logs.mirror.objects]] as const) {
|
||||
for (const [key, bytes] of objects) if (bytes.includes(marker)) hits.push(`${label} ${key} contains ${marker}`);
|
||||
for (const [label, objects] of [["object store", logs.objects.objects], ["legacy mirror", logs.mirror.objects], ["file storage", logs.files.objects]] as const) {
|
||||
for (const [key, bytes] of objects) {
|
||||
if (!options.taskOwnedCopies && key.includes(TASK_FILE_NAMESPACE)) continue;
|
||||
if (bytes.includes(marker)) hits.push(`${label} ${key} contains ${marker}`);
|
||||
}
|
||||
}
|
||||
for (const file of await filesContaining(logs.dir, marker)) hits.push(`file ${file} contains ${marker}`);
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
async function outOfScopeStillHolds(marker: string) {
|
||||
async function outOfScopeStillHolds(marker: string, logs: ReturnType<typeof stores>) {
|
||||
const rows = await db.execute(sql`select 1 from issue_comments where body like ${`%${marker}%`}`);
|
||||
return (rows as unknown as unknown[]).length > 0;
|
||||
return (rows as unknown as unknown[]).length > 0
|
||||
&& [...logs.files.objects].some(([key, bytes]) => key.includes(TASK_FILE_NAMESPACE) && bytes.includes(marker));
|
||||
}
|
||||
|
||||
async function drainPending(service: ReturnType<typeof createConnectionContentDeletion>) {
|
||||
for (let i = 0; i < 200 && await service.nextDeadline() !== null; i++) {
|
||||
await service.processPending(new AbortController().signal);
|
||||
}
|
||||
expect(await service.nextDeadline()).toBeNull();
|
||||
}
|
||||
|
||||
async function drain(service: ReturnType<typeof createConnectionContentDeletion>, deletionIds: string[]) {
|
||||
@@ -276,17 +306,241 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]);
|
||||
await seenBefore([marker], logs);
|
||||
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store });
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
const before = await service.storedContent(flow.connection);
|
||||
expect(before.stored).toMatchObject({ toolCalls: 2, approvals: 1, appViews: 1, runs: 2, runsInProgress: 0 });
|
||||
const { deletion } = await service.request(flow.connection, { actorType: "user", actorId: "board-user" });
|
||||
await drain(service, [deletion.id]);
|
||||
|
||||
expect(await scan([marker], logs)).toEqual([]);
|
||||
expect(await outOfScopeStillHolds(marker)).toBe(true);
|
||||
expect(await outOfScopeStillHolds(marker, logs)).toBe(true);
|
||||
expect((await service.storedContent(flow.connection)).stored).toEqual({ toolCalls: 0, approvals: 0, appViews: 0, runs: 0, runsInProgress: 0 });
|
||||
});
|
||||
|
||||
it("leaves the marker nowhere after the task is deleted, and keeps another task's content", async () => {
|
||||
const logs = stores(path.join(baseDir, "task"));
|
||||
const base = await seedCompany();
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const kept = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const flow = await seedConnectionFlow(base, logs, marker);
|
||||
await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]);
|
||||
const [otherIssue] = await db.insert(issues).values({ companyId: base.company.id, title: "Another task" }).returning();
|
||||
const otherBase = { ...base, issue: otherIssue! };
|
||||
const otherFlow = await seedConnectionFlow(otherBase, logs, kept);
|
||||
await seedDeliveryRun(otherBase, logs, [{ actionRequestId: otherFlow.actionRequest.id, marker: kept }]);
|
||||
await seenBefore([marker, kept], logs);
|
||||
expect((await scan([marker], logs, { taskOwnedCopies: true })).filter((hit) => hit.startsWith("file storage"))).toHaveLength(2);
|
||||
|
||||
await issueService(db).remove(base.issue.id);
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await drainPending(service);
|
||||
|
||||
expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]);
|
||||
const remaining = await scan([kept], logs, { taskOwnedCopies: true });
|
||||
expect(remaining.some((hit) => hit.startsWith("tool_invocations."))).toBe(true);
|
||||
expect(remaining.some((hit) => hit.startsWith("object store"))).toBe(true);
|
||||
expect(remaining.some((hit) => hit.startsWith("file storage"))).toBe(true);
|
||||
const [activity] = await db.execute(sql`select entity_type, entity_id, details from activity_log
|
||||
where company_id = ${base.company.id} and action = 'issue.connection_content_deleted'`) as unknown as Array<{ entity_type: string; entity_id: string; details: Record<string, number> }>;
|
||||
expect(activity).toMatchObject({ entity_type: "issue", entity_id: base.issue.id });
|
||||
expect(activity!.details).toMatchObject({ toolCalls: 2, runs: 2 });
|
||||
});
|
||||
|
||||
it("leaves the marker nowhere after deleting a task whose connection call had no run", async () => {
|
||||
const logs = stores(path.join(baseDir, "task-runless"));
|
||||
const base = await seedCompany();
|
||||
const companyId = base.company.id;
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const [connection] = await db.insert(toolConnections).values({
|
||||
companyId, applicationId: base.application.id, name: "Docs runless", uid: randomUUID(), transport: "mcp_remote", status: "active",
|
||||
}).returning();
|
||||
const args = summarizeToolValue({ query: marker });
|
||||
const result = summarizeToolValue({ text: `Result ${marker}` });
|
||||
const [call] = await db.insert(toolInvocations).values({
|
||||
companyId, connectionId: connection!.id, runId: null, issueId: base.issue.id, toolName: "read_doc", status: "succeeded",
|
||||
argumentsSummary: args, resultSummary: result, createdAt: new Date(Date.now() - 30_000),
|
||||
}).returning();
|
||||
await db.insert(toolCallEvents).values([
|
||||
{ companyId, connectionId: connection!.id, issueId: base.issue.id, eventType: "policy_decision", argumentsSummary: args },
|
||||
{ companyId, connectionId: connection!.id, issueId: base.issue.id, invocationId: call!.id, eventType: "call_completed", resultSummary: result },
|
||||
]);
|
||||
await db.insert(toolAccessAuditEvents).values({
|
||||
companyId, connectionId: connection!.id, action: "tool_access.policy_decision", outcome: "success",
|
||||
details: { decision: "allow", issueId: base.issue.id, runId: null, toolName: "read_doc", argumentsSummary: args },
|
||||
});
|
||||
expect((await scan([marker], logs)).length).toBeGreaterThan(0);
|
||||
|
||||
await issueService(db).remove(base.issue.id);
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await drainPending(service);
|
||||
expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]);
|
||||
});
|
||||
|
||||
it("removes content a run of the task writes after the task is deleted", async () => {
|
||||
const logs = stores(path.join(baseDir, "task-late"));
|
||||
const base = await seedCompany();
|
||||
const companyId = base.company.id;
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const [connection] = await db.insert(toolConnections).values({
|
||||
companyId, applicationId: base.application.id, name: "Docs late", uid: randomUUID(), transport: "mcp_remote", status: "active",
|
||||
}).returning();
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: base.agent.id, issueId: base.issue.id, status: "running" });
|
||||
|
||||
await issueService(db).remove(base.issue.id);
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await service.processPending(new AbortController().signal);
|
||||
|
||||
const summary = summarizeToolValue({ text: `Late ${marker}` });
|
||||
await db.insert(toolInvocations).values({
|
||||
companyId, connectionId: connection!.id, runId, agentId: base.agent.id, toolName: "read_doc", status: "succeeded",
|
||||
argumentsSummary: summary, resultSummary: summary,
|
||||
});
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId: base.agent.id, seq: 1, eventType: "tool.execution.completed", message: marker, payload: { output: marker } });
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(), stdoutExcerpt: `read_doc -> ${marker}` }).where(eq(heartbeatRuns.id, runId));
|
||||
expect((await scan([marker], logs)).length).toBeGreaterThan(0);
|
||||
await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.issueId, base.issue.id));
|
||||
await drainPending(service);
|
||||
expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]);
|
||||
});
|
||||
|
||||
it("waits for a run that is still going when the task is deleted, then removes its content", async () => {
|
||||
const logs = stores(path.join(baseDir, "task-live"));
|
||||
const base = await seedCompany();
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const flow = await seedConnectionFlow(base, logs, marker);
|
||||
await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, flow.callingRunId));
|
||||
|
||||
await issueService(db).remove(base.issue.id);
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await service.processPending(new AbortController().signal);
|
||||
const [waiting] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id));
|
||||
expect(waiting).toMatchObject({ status: "pending", lastError: null });
|
||||
expect(waiting!.notBefore.getTime()).toBeGreaterThan(Date.now());
|
||||
expect((await scan([marker], logs)).some((hit) => hit.startsWith("object store"))).toBe(true);
|
||||
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, flow.callingRunId));
|
||||
await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, waiting!.id));
|
||||
await drainPending(service);
|
||||
expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]);
|
||||
});
|
||||
|
||||
it("stops waiting a day after the task was deleted and records what was still in progress", async () => {
|
||||
const logs = stores(path.join(baseDir, "task-stuck"));
|
||||
const base = await seedCompany();
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const flow = await seedConnectionFlow(base, logs, marker);
|
||||
await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }).where(eq(heartbeatRuns.id, flow.callingRunId));
|
||||
await issueService(db).remove(base.issue.id);
|
||||
const old = new Date(Date.now() - 25 * 60 * 60_000);
|
||||
await db.update(issueConnectionContentDeletions).set({ requestedAt: old }).where(eq(issueConnectionContentDeletions.issueId, base.issue.id));
|
||||
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await drainPending(service);
|
||||
const [job] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id));
|
||||
expect(job!.status).toBe("completed");
|
||||
const [activity] = await db.execute(sql`select details from activity_log
|
||||
where company_id = ${base.company.id} and action = 'issue.connection_content_deletion_incomplete'`) as unknown as Array<{ details: Record<string, number> }>;
|
||||
expect(activity!.details.runsInProgress + activity!.details.itemsInProgress).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("finishes without an activity entry when the deleted task's open run never calls a connection", async () => {
|
||||
const logs = stores(path.join(baseDir, "task-open-quiet"));
|
||||
const base = await seedCompany();
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: base.company.id, agentId: base.agent.id, issueId: base.issue.id, status: "running" });
|
||||
await issueService(db).remove(base.issue.id);
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await service.processPending(new AbortController().signal);
|
||||
const [waiting] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id));
|
||||
expect(waiting!.status).toBe("pending");
|
||||
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
||||
await db.update(issueConnectionContentDeletions).set({ notBefore: new Date() }).where(eq(issueConnectionContentDeletions.id, waiting!.id));
|
||||
await drainPending(service);
|
||||
const [finished] = await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.id, waiting!.id));
|
||||
expect(finished!.status).toBe("completed");
|
||||
expect(await db.execute(sql`select 1 from activity_log where company_id = ${base.company.id}
|
||||
and action like 'issue.connection_content_%'`)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("queues nothing when the deleted task never used a connection", async () => {
|
||||
const base = await seedCompany();
|
||||
await issueService(db).remove(base.issue.id);
|
||||
expect(await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.issueId, base.issue.id))).toEqual([]);
|
||||
});
|
||||
|
||||
it("wakes the cleanup worker when the deleted task has files but never used a connection", async () => {
|
||||
const logs = stores(path.join(baseDir, "task-files"));
|
||||
const base = await seedCompany();
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const attached = await logs.storage.putFile({ companyId: base.company.id, namespace: "issues", originalFilename: "notes.txt", contentType: "text/plain",
|
||||
body: Buffer.from(`Attached copy of ${marker}`) });
|
||||
const [asset] = await db.insert(assets).values({ companyId: base.company.id, ...attached }).returning();
|
||||
await db.insert(issueAttachments).values({ companyId: base.company.id, issueId: base.issue.id, assetId: asset!.id });
|
||||
let woken = 0;
|
||||
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.toolConnectionContentDeletion, () => { woken += 1; });
|
||||
try {
|
||||
await issueService(db).remove(base.issue.id);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
expect(woken).toBeGreaterThan(0);
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await drainPending(service);
|
||||
expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]);
|
||||
});
|
||||
|
||||
it("leaves the marker nowhere after the company is deleted, and keeps another company's content", async () => {
|
||||
const logs = stores(path.join(baseDir, "company"));
|
||||
const base = await seedCompany();
|
||||
const otherBase = await seedCompany();
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const kept = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
const flow = await seedConnectionFlow(base, logs, marker);
|
||||
await seedDeliveryRun(base, logs, [{ actionRequestId: flow.actionRequest.id, marker }]);
|
||||
const otherFlow = await seedConnectionFlow(otherBase, logs, kept);
|
||||
await seedDeliveryRun(otherBase, logs, [{ actionRequestId: otherFlow.actionRequest.id, marker: kept }]);
|
||||
await seenBefore([marker, kept], logs);
|
||||
|
||||
await db.update(agents).set({ lifecycleState: "terminated" }).where(eq(agents.companyId, base.company.id));
|
||||
await deleteCompany(db, base.company.id);
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
await drainPending(service);
|
||||
|
||||
expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]);
|
||||
const remaining = await scan([kept], logs, { taskOwnedCopies: true });
|
||||
expect(remaining.some((hit) => hit.startsWith("object store"))).toBe(true);
|
||||
expect(remaining.some((hit) => hit.startsWith("file storage"))).toBe(true);
|
||||
expect(remaining.some((hit) => hit.startsWith("file "))).toBe(true);
|
||||
});
|
||||
|
||||
it("finishes removing a deleted company's files after storage fails once", async () => {
|
||||
const logs = stores(path.join(baseDir, "company-retry"));
|
||||
const base = await seedCompany();
|
||||
const marker = `CANARY${randomUUID().replace(/-/g, "")}`;
|
||||
await seedConnectionFlow(base, logs, marker);
|
||||
await db.update(agents).set({ lifecycleState: "terminated" }).where(eq(agents.companyId, base.company.id));
|
||||
await deleteCompany(db, base.company.id);
|
||||
|
||||
let failures = 1;
|
||||
const flaky = {
|
||||
...logs.storage,
|
||||
deleteObject: async (...args: Parameters<typeof logs.storage.deleteObject>) => {
|
||||
if (failures > 0) {
|
||||
failures -= 1;
|
||||
throw new Error("object storage unavailable");
|
||||
}
|
||||
return logs.storage.deleteObject(...args);
|
||||
},
|
||||
};
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => flaky, objectRetryMs: 0 });
|
||||
await expect(service.processPending(new AbortController().signal)).rejects.toThrow("object storage unavailable");
|
||||
expect(await service.nextDeadline()).not.toBeNull();
|
||||
await drainPending(service);
|
||||
expect(await scan([marker], logs, { taskOwnedCopies: true })).toEqual([]);
|
||||
});
|
||||
|
||||
it("leaves the marker nowhere after an interrupted deletion resumes", async () => {
|
||||
const logs = stores(path.join(baseDir, "interrupted"));
|
||||
const base = await seedCompany();
|
||||
@@ -306,7 +560,7 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
return logs.store.remove!(handle, signal);
|
||||
},
|
||||
};
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => flaky });
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => flaky, storage: () => logs.storage });
|
||||
const { deletion } = await service.request(flow.connection, { actorType: "user", actorId: "board-user" });
|
||||
let interrupted = 0;
|
||||
for (let i = 0; i < 200; i++) {
|
||||
@@ -318,7 +572,7 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
}
|
||||
expect(interrupted).toBe(2);
|
||||
expect(await scan([marker], logs)).toEqual([]);
|
||||
expect(await outOfScopeStillHolds(marker)).toBe(true);
|
||||
expect(await outOfScopeStillHolds(marker, logs)).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves no marker after two deletions for different connections run at the same time on one task", async () => {
|
||||
@@ -334,13 +588,13 @@ describeEmbeddedPostgres("deleting a connection's stored content leaves no copy
|
||||
]);
|
||||
await seenBefore([first, second], logs);
|
||||
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store });
|
||||
const service = createConnectionContentDeletion(db, { runLogStore: () => logs.store, storage: () => logs.storage });
|
||||
const one = await service.request(flowOne.connection, { actorType: "user", actorId: "board-user" });
|
||||
const two = await service.request(flowTwo.connection, { actorType: "user", actorId: "board-user" });
|
||||
await drain(service, [one.deletion.id, two.deletion.id]);
|
||||
|
||||
expect(await scan([first, second], logs)).toEqual([]);
|
||||
expect(await outOfScopeStillHolds(first)).toBe(true);
|
||||
expect(await outOfScopeStillHolds(second)).toBe(true);
|
||||
expect(await outOfScopeStillHolds(first, logs)).toBe(true);
|
||||
expect(await outOfScopeStillHolds(second, logs)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,7 @@ import type { Db } from "@paperclipai/db";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { createAgentLifecycle, processAgentLifecycle } from "./agent-lifecycle.js";
|
||||
import { requestRestorePointDeletion } from "./git-restore-point-ledger.js";
|
||||
import { requestCompanyStoredObjectDeletion } from "./tool-access/connections/stored-object-deletion.js";
|
||||
import { agentLifecycleCompanyDeletion } from "../modules/agent-lifecycle/company-deletion.js";
|
||||
import { executionAdmissionCompanyDeletion } from "../modules/execution-admission/company-deletion.js";
|
||||
import {
|
||||
@@ -78,6 +79,7 @@ export async function deleteCompany(db: Db, id: string) {
|
||||
const [existing] = await tx.select({ id: companies.id }).from(companies)
|
||||
.where(eq(companies.id, id)).for("no key update");
|
||||
if (!existing) return null;
|
||||
await requestCompanyStoredObjectDeletion(tx as unknown as Db, id);
|
||||
await mcpCompanyDeletion.deleteCompanyData(tx, id);
|
||||
await notifyExternalObjectRefresh(tx, id);
|
||||
await notifyIssueRecovery(tx, { companyId: id });
|
||||
|
||||
@@ -45,6 +45,7 @@ import { executionWorkspaceService } from "./execution-workspaces.js";
|
||||
import { notifyChatPublicationWork } from "./chat-work-notifications.js";
|
||||
import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js";
|
||||
import { requestRestorePointDeletion } from "./git-restore-point-ledger.js";
|
||||
import { requestIssueConnectionContentDeletion } from "./tool-access/connections/issue-content-deletion.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import { recordChatHandoff, recordAcceptedChatHandoff, lockAcceptedChatHandoffSource, recordChatCompletion, existingChatCompletionReply, acknowledgeChatCompletionReply } from "./chat-completion-delivery.js";
|
||||
import { mirrorSlackBoardComment, slackBoardReplyBindings } from "./slack-board-messages.js";
|
||||
@@ -12793,6 +12794,9 @@ export function issueService(db: Db) {
|
||||
}
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
|
||||
await notifyRoutineExecutionStatus(tx, id);
|
||||
if (owner) {
|
||||
await requestIssueConnectionContentDeletion(tx as unknown as Db, { companyId: owner.companyId, issueId: id, actorAgentId });
|
||||
}
|
||||
removedIssue = await tx
|
||||
.delete(issues)
|
||||
.where(eq(issues.id, id))
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { and, asc, desc, eq, gt, inArray, lte, sql, type SQL } from "drizzle-orm";
|
||||
import {
|
||||
agentWakeupRequests,
|
||||
assets,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
issueConnectionContentDeletions,
|
||||
issueThreadInteractions,
|
||||
runnerApiResponseReservations,
|
||||
toolAccessAuditEvents,
|
||||
toolActionRequests,
|
||||
toolCallEvents,
|
||||
@@ -19,7 +22,10 @@ import type {
|
||||
} from "@paperclipai/shared";
|
||||
import { isRunLogStoreType, type RunLogHandle, type RunLogStore } from "../../run-log-store.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js";
|
||||
import { logActivity } from "../../activity-log.js";
|
||||
import { logActivity, type LogActivityInput } from "../../activity-log.js";
|
||||
import { getStorageService } from "../../../storage/index.js";
|
||||
import type { StorageService } from "../../../storage/types.js";
|
||||
import { createStoredObjectDeletion } from "./stored-object-deletion.js";
|
||||
|
||||
const BATCH_SIZE = 200;
|
||||
const EVENT_BATCH_SIZE = 1000;
|
||||
@@ -48,6 +54,9 @@ type Phase = "invocations" | "events" | "auditEvents" | "appViews" | "deliveredR
|
||||
const PHASES: Phase[] = ["invocations", "events", "auditEvents", "appViews", "deliveredResults", "runs", "done"];
|
||||
const RUN_BATCH_SIZE = 50;
|
||||
const DELIVERY_BATCH_SIZE = 50;
|
||||
const ISSUE_WAIT_MS = 60_000;
|
||||
const ISSUE_WAIT_MAX_MS = 5 * 60_000;
|
||||
const ISSUE_WAIT_LIMIT_MS = 24 * 60 * 60_000;
|
||||
|
||||
type RunInProgress = { id: string; eventAfterId: number; changed: boolean; stage?: "events" | "log" };
|
||||
|
||||
@@ -61,6 +70,62 @@ type Progress = {
|
||||
};
|
||||
|
||||
type DeletionRow = typeof toolConnectionContentDeletions.$inferSelect;
|
||||
type IssueDeletionRow = typeof issueConnectionContentDeletions.$inferSelect;
|
||||
type JobRow = Pick<DeletionRow, "id" | "companyId" | "status" | "progress" | "updatedAt" | "requestedAt" | "requestedByActorType" | "requestedByActorId">;
|
||||
type JobActivity = Pick<LogActivityInput, "action" | "entityType" | "entityId" | "details">;
|
||||
|
||||
type JobStore<Row extends JobRow> = {
|
||||
load(id: string): Promise<Row | undefined>;
|
||||
scope(row: Row): Scope;
|
||||
waitMs(row: Row, progress: Progress): number | null;
|
||||
save(tx: Db, row: Row, progress: Progress, waitMs: number | null): Promise<Row | undefined>;
|
||||
finish(tx: Db, row: Row, now: Date): Promise<Row | undefined>;
|
||||
activity(row: Row, counts: ToolConnectionContentDeletionCounts): JobActivity | null;
|
||||
fail(row: Row, message: string): Promise<void>;
|
||||
};
|
||||
|
||||
type Scope = {
|
||||
companyId: string;
|
||||
cutoff: Date | null;
|
||||
connectionId: string | null;
|
||||
issueId: string | null;
|
||||
runIds: string[];
|
||||
invocationIds: string[];
|
||||
eventIds: string[];
|
||||
};
|
||||
|
||||
function connectionScope(connection: { id: string; companyId: string }, cutoff: Date): Scope {
|
||||
return { companyId: connection.companyId, cutoff, connectionId: connection.id, issueId: null, runIds: [], invocationIds: [], eventIds: [] };
|
||||
}
|
||||
|
||||
export function uuidList(values: string[]): SQL {
|
||||
return values.length > 0 ? sql`array[${sql.join(values.map((value) => sql`${value}::uuid`), sql`, `)}]` : sql`array[]::uuid[]`;
|
||||
}
|
||||
|
||||
function textList(values: string[]): SQL {
|
||||
return values.length > 0 ? sql`array[${listSql(values)}]::text[]` : sql`array[]::text[]`;
|
||||
}
|
||||
|
||||
function cutoffSql(column: SQL | typeof toolInvocations.createdAt, scope: Scope) {
|
||||
return scope.cutoff ? sql`${column} <= ${scope.cutoff.toISOString()}::timestamptz` : undefined;
|
||||
}
|
||||
|
||||
function callsInScopeSql(scope: Scope, columns: { connectionId: SQL; runId: SQL; invocationId: SQL }): SQL {
|
||||
if (scope.connectionId) return sql`${columns.connectionId} = ${scope.connectionId}`;
|
||||
return sql`(${columns.runId} = any(${uuidList(scope.runIds)}) or ${columns.invocationId} = any(${uuidList(scope.invocationIds)}))`;
|
||||
}
|
||||
|
||||
function invocationsInScopeSql(scope: Scope) {
|
||||
return callsInScopeSql(scope, { connectionId: sql`${toolInvocations.connectionId}`, runId: sql`${toolInvocations.runId}`, invocationId: sql`${toolInvocations.id}` });
|
||||
}
|
||||
|
||||
function savedResultSql(runId: SQL): SQL {
|
||||
return sql`exists (select 1 from ${runnerApiResponseReservations} capture
|
||||
where capture.run_id = ${runId} and capture.asset_id is not null
|
||||
and not exists (select 1 from issue_attachments link where link.asset_id = capture.asset_id)
|
||||
and not exists (select 1 from case_attachments link where link.asset_id = capture.asset_id)
|
||||
and not exists (select 1 from company_logos link where link.asset_id = capture.asset_id))`;
|
||||
}
|
||||
|
||||
export type ContentDeletionActor = { actorType: "user" | "agent" | "system"; actorId: string | null };
|
||||
|
||||
@@ -70,7 +135,7 @@ export function emptyContentDeletionCounts(): ToolConnectionContentDeletionCount
|
||||
return { toolCalls: 0, approvals: 0, auditEvents: 0, appViews: 0, runs: 0, runsInProgress: 0, itemsInProgress: 0 };
|
||||
}
|
||||
|
||||
function readProgress(row: DeletionRow): Progress {
|
||||
function readProgress(row: { progress: unknown }): Progress {
|
||||
const raw = row.progress as Partial<Progress>;
|
||||
const counts = { ...emptyContentDeletionCounts(), ...(raw.counts ?? {}) };
|
||||
const phase = PHASES.includes(raw.phase as Phase) ? raw.phase as Phase : "invocations";
|
||||
@@ -94,21 +159,34 @@ export function settledRunSql(runId: SQL | typeof toolInvocations.runId): SQL {
|
||||
and f.phase not in ('committed', 'terminal_failure', 'applied')))`;
|
||||
}
|
||||
|
||||
export function runsWithStoredContentSql(scope: { companyId: string; connectionId: string; cutoff: Date }): SQL {
|
||||
function runsCallingConnectionSql(scope: Scope & { connectionId: string; cutoff: Date }): SQL {
|
||||
const calls = sql`${toolInvocations.companyId} = ${scope.companyId} and ${toolInvocations.connectionId} = ${scope.connectionId}
|
||||
and ${toolInvocations.createdAt} <= ${scope.cutoff.toISOString()}::timestamptz`;
|
||||
const resultText = sql.join(RESULT_TEXT_KEYS.map((key) =>
|
||||
sql.raw(`jsonb_path_exists(coalesce("heartbeat_runs"."result_json", '{}'::jsonb), 'lax $.**.${key} ? (@.type() == "string" && @ != "")')`)), sql` or `);
|
||||
return sql`${heartbeatRuns.companyId} = ${scope.companyId}
|
||||
and (${heartbeatRuns.id} in (select ${toolInvocations.runId} from ${toolInvocations} where ${calls} and ${toolInvocations.runId} is not null)
|
||||
return sql`(${heartbeatRuns.id} in (select ${toolInvocations.runId} from ${toolInvocations} where ${calls} and ${toolInvocations.runId} is not null)
|
||||
or ${heartbeatRuns.id} in (select ${toolCallEvents.runId} from ${toolCallEvents} where ${toolCallEvents.companyId} = ${scope.companyId}
|
||||
and ${toolCallEvents.connectionId} = ${scope.connectionId} and ${toolCallEvents.createdAt} <= ${scope.cutoff.toISOString()}::timestamptz
|
||||
and ${toolCallEvents.runId} is not null)
|
||||
or (${heartbeatRuns.issueId} in (select ${toolActionRequests.issueId} from ${toolActionRequests}
|
||||
join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls})
|
||||
and ${heartbeatRuns.contextSnapshot}->'toolActionRequestIds' ?| array(select ${toolActionRequests.id}::text from ${toolActionRequests}
|
||||
join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls})))
|
||||
and (${heartbeatRuns.logRef} is not null or ${heartbeatRuns.logStore} is not null
|
||||
join ${toolInvocations} on ${toolInvocations.id} = ${toolActionRequests.invocationId} where ${calls})))`;
|
||||
}
|
||||
|
||||
export function runUsedToolsSql(companyId: string): SQL {
|
||||
return sql`(exists (select 1 from ${toolInvocations} where ${toolInvocations.companyId} = ${companyId} and ${toolInvocations.runId} = ${heartbeatRuns.id})
|
||||
or exists (select 1 from ${toolCallEvents} where ${toolCallEvents.companyId} = ${companyId} and ${toolCallEvents.runId} = ${heartbeatRuns.id})
|
||||
or coalesce(${heartbeatRuns.contextSnapshot} ? 'toolActionRequestIds', false))`;
|
||||
}
|
||||
|
||||
export function runsWithStoredContentSql(scope: Scope): SQL {
|
||||
const resultText = sql.join(RESULT_TEXT_KEYS.map((key) =>
|
||||
sql.raw(`jsonb_path_exists(coalesce("heartbeat_runs"."result_json", '{}'::jsonb), 'lax $.**.${key} ? (@.type() == "string" && @ != "")')`)), sql` or `);
|
||||
const inScope = scope.connectionId && scope.cutoff
|
||||
? runsCallingConnectionSql({ ...scope, connectionId: scope.connectionId, cutoff: scope.cutoff })
|
||||
: sql`${heartbeatRuns.id} = any(${uuidList(scope.runIds)}) and ${runUsedToolsSql(scope.companyId)}`;
|
||||
return sql`${heartbeatRuns.companyId} = ${scope.companyId}
|
||||
and ${inScope}
|
||||
and (${savedResultSql(sql`${heartbeatRuns.id}`)} or ${heartbeatRuns.logRef} is not null or ${heartbeatRuns.logStore} is not null
|
||||
or ${heartbeatRuns.stdoutExcerpt} is not null or ${heartbeatRuns.stderrExcerpt} is not null
|
||||
or ${resultText}
|
||||
or exists (select 1 from ${heartbeatRunEvents} where ${heartbeatRunEvents.companyId} = ${heartbeatRuns.companyId}
|
||||
@@ -179,7 +257,18 @@ function toDeletion(row: DeletionRow): ToolConnectionContentDeletion {
|
||||
};
|
||||
}
|
||||
|
||||
export function createConnectionContentDeletion(db: Db, deps: { runLogStore: () => RunLogStore }) {
|
||||
export function initialContentDeletionProgress(): Progress {
|
||||
return { phase: "invocations", cursor: null, runCursor: null, currentRun: null, pendingRuns: [], counts: emptyContentDeletionCounts() };
|
||||
}
|
||||
|
||||
export function createConnectionContentDeletion(db: Db, deps: {
|
||||
runLogStore: () => RunLogStore;
|
||||
storage?: () => StorageService;
|
||||
objectRetryMs?: number;
|
||||
}) {
|
||||
const storage = deps.storage ?? (() => getStorageService());
|
||||
const storedObjects = createStoredObjectDeletion(db, { runLogStore: deps.runLogStore, storage, retryMs: deps.objectRetryMs });
|
||||
|
||||
async function latestDeletion(connection: { id: string; companyId: string }) {
|
||||
const [latest] = await db
|
||||
.select()
|
||||
@@ -222,7 +311,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
runsInProgress: sql<number>`count(*) filter (where not ${settledRunSql(sql`${heartbeatRuns.id}`)})::int`,
|
||||
})
|
||||
.from(heartbeatRuns)
|
||||
.where(runsWithStoredContentSql({ companyId: connection.companyId, connectionId: connection.id, cutoff: new Date() }));
|
||||
.where(runsWithStoredContentSql(connectionScope(connection, new Date())));
|
||||
return {
|
||||
stored: {
|
||||
toolCalls: calls?.toolCalls ?? 0,
|
||||
@@ -260,7 +349,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
connectionId: connection.id,
|
||||
requestedByActorType: actor.actorType,
|
||||
requestedByActorId: actor.actorId,
|
||||
progress: { phase: "invocations", cursor: null, runCursor: null, currentRun: null, pendingRuns: [], counts: emptyContentDeletionCounts() },
|
||||
progress: initialContentDeletionProgress() as unknown as Record<string, unknown>,
|
||||
})
|
||||
.onConflictDoNothing()
|
||||
.returning();
|
||||
@@ -279,8 +368,8 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
return new Set(rows.map((row) => row.id));
|
||||
}
|
||||
|
||||
async function clearDeliveredResults(tx: Db, job: DeletionRow, progress: Progress, requests: Array<{ id: string; issueId: string | null }>) {
|
||||
const issueIds = [...new Set(requests.flatMap((row) => row.issueId ? [row.issueId] : []))];
|
||||
async function clearDeliveredResults(tx: Db, scope: Scope, progress: Progress, requests: Array<{ id: string; issueId: string | null }>) {
|
||||
const issueIds = scope.issueId ? [scope.issueId] : [...new Set(requests.flatMap((row) => row.issueId ? [row.issueId] : []))];
|
||||
if (issueIds.length === 0) return [];
|
||||
const ids = new Set(requests.map((row) => row.id));
|
||||
const idList = sql`array[${listSql([...ids])}]::text[]`;
|
||||
@@ -288,8 +377,8 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
.select({ id: heartbeatRuns.id, contextSnapshot: heartbeatRuns.contextSnapshot })
|
||||
.from(heartbeatRuns)
|
||||
.where(and(
|
||||
eq(heartbeatRuns.companyId, job.companyId),
|
||||
inArray(heartbeatRuns.issueId, issueIds),
|
||||
eq(heartbeatRuns.companyId, scope.companyId),
|
||||
scope.issueId ? sql`${heartbeatRuns.id} = any(${uuidList(scope.runIds)})` : inArray(heartbeatRuns.issueId, issueIds),
|
||||
sql`${heartbeatRuns.contextSnapshot}->'toolActionRequestIds' ?| ${idList}`,
|
||||
))
|
||||
.for("update");
|
||||
@@ -308,7 +397,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
.select({ id: agentWakeupRequests.id, status: agentWakeupRequests.status, payload: agentWakeupRequests.payload })
|
||||
.from(agentWakeupRequests)
|
||||
.where(and(
|
||||
eq(agentWakeupRequests.companyId, job.companyId),
|
||||
eq(agentWakeupRequests.companyId, scope.companyId),
|
||||
inArray(sql<string>`${agentWakeupRequests.payload}->>'issueId'`, issueIds),
|
||||
sql`(${agentWakeupRequests.payload}->'toolActionRequestIds' ?| ${idList}
|
||||
or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'toolActionRequestIds' ?| ${idList})`,
|
||||
@@ -326,16 +415,16 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
return runs.filter((row) => settled.has(row.id)).map((row) => row.id);
|
||||
}
|
||||
|
||||
async function invocationsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) {
|
||||
async function invocationsStep(tx: Db, scope: Scope, progress: Progress, deletedAt: string) {
|
||||
const cursor = progress.cursor;
|
||||
const page = await tx
|
||||
.select({ id: toolInvocations.id, createdAt: toolInvocations.createdAt, runId: toolInvocations.runId, status: toolInvocations.status })
|
||||
.from(toolInvocations)
|
||||
.where(and(
|
||||
eq(toolInvocations.companyId, job.companyId),
|
||||
lte(toolInvocations.createdAt, job.requestedAt),
|
||||
eq(toolInvocations.companyId, scope.companyId),
|
||||
cutoffSql(sql`${toolInvocations.createdAt}`, scope),
|
||||
cursor ? sql`(${toolInvocations.createdAt}, ${toolInvocations.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined,
|
||||
eq(toolInvocations.connectionId, job.connectionId),
|
||||
invocationsInScopeSql(scope),
|
||||
))
|
||||
.orderBy(asc(toolInvocations.createdAt), asc(toolInvocations.id))
|
||||
.limit(BATCH_SIZE);
|
||||
@@ -353,7 +442,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
progress: null,
|
||||
})
|
||||
.where(and(
|
||||
eq(toolInvocations.companyId, job.companyId),
|
||||
eq(toolInvocations.companyId, scope.companyId),
|
||||
inArray(toolInvocations.id, ids),
|
||||
sql`coalesce(${toolInvocations.resultSummary}->>'contentDeletedAt', ${toolInvocations.argumentsSummary}->>'contentDeletedAt') is null`,
|
||||
sql`(${toolInvocations.resultSummary} is not null or ${toolInvocations.argumentsSummary} is not null or ${toolInvocations.progress} is not null)`,
|
||||
@@ -363,7 +452,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
const requests = await tx
|
||||
.select({ id: toolActionRequests.id, interactionId: toolActionRequests.interactionId, issueId: toolActionRequests.issueId, status: toolActionRequests.status })
|
||||
.from(toolActionRequests)
|
||||
.where(and(eq(toolActionRequests.companyId, job.companyId), inArray(toolActionRequests.invocationId, ids)));
|
||||
.where(and(eq(toolActionRequests.companyId, scope.companyId), inArray(toolActionRequests.invocationId, ids)));
|
||||
const settledRequests = requests.filter((row) => !UNSETTLED_ACTION_REQUEST_STATUSES.includes(row.status));
|
||||
progress.counts.itemsInProgress += requests.length - settledRequests.length;
|
||||
if (settledRequests.length > 0) {
|
||||
@@ -376,7 +465,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
signedArguments: null,
|
||||
})
|
||||
.where(and(
|
||||
eq(toolActionRequests.companyId, job.companyId),
|
||||
eq(toolActionRequests.companyId, scope.companyId),
|
||||
inArray(toolActionRequests.id, requestIds),
|
||||
sql`(${toolActionRequests.canonicalArgumentsSummary}->>'contentDeletedAt' is null or ${toolActionRequests.previewMarkdown} is not null or ${toolActionRequests.signedArguments} is not null)`,
|
||||
))
|
||||
@@ -395,7 +484,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
else ${issueThreadInteractions.result} end` as never,
|
||||
})
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.companyId, job.companyId),
|
||||
eq(issueThreadInteractions.companyId, scope.companyId),
|
||||
inArray(issueThreadInteractions.id, interactionIds),
|
||||
sql`(${issueThreadInteractions.payload} ? 'detailsMarkdown'
|
||||
or ${issueThreadInteractions.payload}->'toolAction'->>'previewMarkdown' is not null
|
||||
@@ -410,16 +499,19 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
return page.length < BATCH_SIZE;
|
||||
}
|
||||
|
||||
async function eventsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) {
|
||||
async function eventsStep(tx: Db, scope: Scope, progress: Progress, deletedAt: string) {
|
||||
const cursor = progress.cursor;
|
||||
const page = await tx
|
||||
.select({ id: toolCallEvents.id, createdAt: toolCallEvents.createdAt, runId: toolCallEvents.runId })
|
||||
.from(toolCallEvents)
|
||||
.where(and(
|
||||
eq(toolCallEvents.companyId, job.companyId),
|
||||
lte(toolCallEvents.createdAt, job.requestedAt),
|
||||
eq(toolCallEvents.companyId, scope.companyId),
|
||||
cutoffSql(sql`${toolCallEvents.createdAt}`, scope),
|
||||
cursor ? sql`(${toolCallEvents.createdAt}, ${toolCallEvents.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined,
|
||||
eq(toolCallEvents.connectionId, job.connectionId),
|
||||
scope.connectionId
|
||||
? callsInScopeSql(scope, { connectionId: sql`${toolCallEvents.connectionId}`, runId: sql`${toolCallEvents.runId}`, invocationId: sql`${toolCallEvents.invocationId}` })
|
||||
: sql`(${callsInScopeSql(scope, { connectionId: sql`${toolCallEvents.connectionId}`, runId: sql`${toolCallEvents.runId}`, invocationId: sql`${toolCallEvents.invocationId}` })}
|
||||
or ${toolCallEvents.id} = any(${uuidList(scope.eventIds)}))`,
|
||||
))
|
||||
.orderBy(asc(toolCallEvents.createdAt), asc(toolCallEvents.id))
|
||||
.limit(BATCH_SIZE);
|
||||
@@ -436,7 +528,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
resultSummary: clearedSummary(sql`${toolCallEvents.resultSummary}`, deletedAt) as never,
|
||||
})
|
||||
.where(and(
|
||||
eq(toolCallEvents.companyId, job.companyId),
|
||||
eq(toolCallEvents.companyId, scope.companyId),
|
||||
inArray(toolCallEvents.id, ids),
|
||||
sql`coalesce(${toolCallEvents.resultSummary}->>'contentDeletedAt', ${toolCallEvents.requestSummary}->>'contentDeletedAt', ${toolCallEvents.argumentsSummary}->>'contentDeletedAt') is null`,
|
||||
sql`(${toolCallEvents.resultSummary} is not null or ${toolCallEvents.requestSummary} is not null or ${toolCallEvents.argumentsSummary} is not null)`,
|
||||
@@ -449,16 +541,20 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
return page.length < BATCH_SIZE;
|
||||
}
|
||||
|
||||
async function auditEventsStep(tx: Db, job: DeletionRow, progress: Progress, deletedAt: string) {
|
||||
async function auditEventsStep(tx: Db, scope: Scope, progress: Progress, deletedAt: string) {
|
||||
const cursor = progress.cursor;
|
||||
const page = await tx
|
||||
.select({ id: toolAccessAuditEvents.id, createdAt: toolAccessAuditEvents.createdAt, runId: sql<string | null>`${toolAccessAuditEvents.details}->>'runId'` })
|
||||
.from(toolAccessAuditEvents)
|
||||
.where(and(
|
||||
eq(toolAccessAuditEvents.companyId, job.companyId),
|
||||
lte(toolAccessAuditEvents.createdAt, job.requestedAt),
|
||||
eq(toolAccessAuditEvents.companyId, scope.companyId),
|
||||
cutoffSql(sql`${toolAccessAuditEvents.createdAt}`, scope),
|
||||
cursor ? sql`(${toolAccessAuditEvents.createdAt}, ${toolAccessAuditEvents.id}) > (${cursor.createdAt}::timestamptz, ${cursor.id}::uuid)` : undefined,
|
||||
eq(toolAccessAuditEvents.connectionId, job.connectionId),
|
||||
scope.connectionId
|
||||
? eq(toolAccessAuditEvents.connectionId, scope.connectionId)
|
||||
: sql`(${toolAccessAuditEvents.details}->>'runId' = any(${textList(scope.runIds)})
|
||||
or ${toolAccessAuditEvents.details}->>'invocationId' = any(${textList(scope.invocationIds)})
|
||||
or ${toolAccessAuditEvents.details}->>'issueId' = ${scope.issueId})`,
|
||||
))
|
||||
.orderBy(asc(toolAccessAuditEvents.createdAt), asc(toolAccessAuditEvents.id))
|
||||
.limit(BATCH_SIZE);
|
||||
@@ -476,7 +572,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
${toolAccessAuditEvents.details}->'argumentsSummary' || jsonb_build_object('summary', '', 'contentDeletedAt', ${deletedAt}::text))` as never,
|
||||
})
|
||||
.where(and(
|
||||
eq(toolAccessAuditEvents.companyId, job.companyId),
|
||||
eq(toolAccessAuditEvents.companyId, scope.companyId),
|
||||
inArray(toolAccessAuditEvents.id, ids),
|
||||
sql`jsonb_typeof(${toolAccessAuditEvents.details}->'argumentsSummary') = 'object'`,
|
||||
sql`${toolAccessAuditEvents.details}->'argumentsSummary'->>'contentDeletedAt' is null`,
|
||||
@@ -489,14 +585,14 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
return page.length < BATCH_SIZE;
|
||||
}
|
||||
|
||||
async function appViewsStep(tx: Db, job: DeletionRow, progress: Progress) {
|
||||
async function appViewsStep(tx: Db, scope: Scope, progress: Progress) {
|
||||
const page = await tx
|
||||
.select({ id: toolMcpAppViews.id, runId: toolMcpAppViews.runId })
|
||||
.from(toolMcpAppViews)
|
||||
.where(and(
|
||||
eq(toolMcpAppViews.connectionId, job.connectionId),
|
||||
eq(toolMcpAppViews.companyId, job.companyId),
|
||||
lte(toolMcpAppViews.createdAt, job.requestedAt),
|
||||
callsInScopeSql(scope, { connectionId: sql`${toolMcpAppViews.connectionId}`, runId: sql`${toolMcpAppViews.runId}`, invocationId: sql`${toolMcpAppViews.invocationId}` }),
|
||||
eq(toolMcpAppViews.companyId, scope.companyId),
|
||||
cutoffSql(sql`${toolMcpAppViews.createdAt}`, scope),
|
||||
progress.runCursor ? gt(toolMcpAppViews.id, progress.runCursor) : undefined,
|
||||
))
|
||||
.orderBy(asc(toolMcpAppViews.id))
|
||||
@@ -508,7 +604,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
if (ids.length > 0) {
|
||||
const removed = await tx
|
||||
.delete(toolMcpAppViews)
|
||||
.where(and(eq(toolMcpAppViews.companyId, job.companyId), inArray(toolMcpAppViews.id, ids)))
|
||||
.where(and(eq(toolMcpAppViews.companyId, scope.companyId), inArray(toolMcpAppViews.id, ids)))
|
||||
.returning({ id: toolMcpAppViews.id });
|
||||
progress.counts.appViews += removed.length;
|
||||
}
|
||||
@@ -566,6 +662,25 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
throw new Error("run_log_reference_changed");
|
||||
}
|
||||
|
||||
async function removeSavedResults(companyId: string, runId: string, signal: AbortSignal) {
|
||||
const saved = await db
|
||||
.select({ id: assets.id, objectKey: assets.objectKey })
|
||||
.from(assets)
|
||||
.where(and(
|
||||
eq(assets.companyId, companyId),
|
||||
sql`${assets.id} in (select capture.asset_id from ${runnerApiResponseReservations} capture
|
||||
where capture.company_id = ${companyId} and capture.run_id = ${runId} and capture.asset_id is not null)`,
|
||||
sql`not exists (select 1 from issue_attachments link where link.asset_id = ${assets.id})`,
|
||||
sql`not exists (select 1 from case_attachments link where link.asset_id = ${assets.id})`,
|
||||
sql`not exists (select 1 from company_logos link where link.asset_id = ${assets.id})`,
|
||||
));
|
||||
for (const asset of saved) {
|
||||
await storage().deleteObject(companyId, asset.objectKey, { signal, allVersions: true });
|
||||
await db.delete(assets).where(and(eq(assets.id, asset.id), eq(assets.companyId, companyId)));
|
||||
}
|
||||
return saved.length > 0;
|
||||
}
|
||||
|
||||
async function finishRun(tx: Db, companyId: string, run: RunInProgress) {
|
||||
const [row] = await tx
|
||||
.select({ stdoutExcerpt: heartbeatRuns.stdoutExcerpt, stderrExcerpt: heartbeatRuns.stderrExcerpt, resultJson: heartbeatRuns.resultJson })
|
||||
@@ -582,27 +697,27 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
run.changed = true;
|
||||
}
|
||||
|
||||
async function deliveredResultsStep(tx: Db, job: DeletionRow, progress: Progress) {
|
||||
async function deliveredResultsStep(tx: Db, scope: Scope, progress: Progress) {
|
||||
const requests = await tx
|
||||
.select({ id: toolActionRequests.id, issueId: toolActionRequests.issueId })
|
||||
.from(toolActionRequests)
|
||||
.innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId))
|
||||
.where(and(
|
||||
eq(toolActionRequests.companyId, job.companyId),
|
||||
eq(toolInvocations.companyId, job.companyId),
|
||||
eq(toolInvocations.connectionId, job.connectionId),
|
||||
lte(toolInvocations.createdAt, job.requestedAt),
|
||||
eq(toolActionRequests.companyId, scope.companyId),
|
||||
eq(toolInvocations.companyId, scope.companyId),
|
||||
invocationsInScopeSql(scope),
|
||||
cutoffSql(sql`${toolInvocations.createdAt}`, scope),
|
||||
progress.runCursor ? gt(toolActionRequests.id, progress.runCursor) : undefined,
|
||||
))
|
||||
.orderBy(asc(toolActionRequests.id))
|
||||
.limit(DELIVERY_BATCH_SIZE);
|
||||
if (requests.length === 0) return true;
|
||||
progress.runCursor = requests[requests.length - 1]!.id;
|
||||
await clearDeliveredResults(tx, job, progress, requests);
|
||||
await clearDeliveredResults(tx, scope, progress, requests);
|
||||
return requests.length < DELIVERY_BATCH_SIZE;
|
||||
}
|
||||
|
||||
async function runsStep(tx: Db, job: DeletionRow, progress: Progress) {
|
||||
async function runsStep(tx: Db, scope: Scope, progress: Progress) {
|
||||
if (!progress.currentRun) {
|
||||
let runId = progress.pendingRuns.shift() ?? null;
|
||||
if (!runId) {
|
||||
@@ -611,7 +726,7 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
.from(heartbeatRuns)
|
||||
.where(and(
|
||||
progress.runCursor ? gt(heartbeatRuns.id, progress.runCursor) : undefined,
|
||||
runsWithStoredContentSql({ companyId: job.companyId, connectionId: job.connectionId, cutoff: job.requestedAt }),
|
||||
runsWithStoredContentSql(scope),
|
||||
))
|
||||
.orderBy(asc(heartbeatRuns.id))
|
||||
.limit(RUN_BATCH_SIZE);
|
||||
@@ -633,129 +748,229 @@ export function createConnectionContentDeletion(db: Db, deps: { runLogStore: ()
|
||||
progress.currentRun = null;
|
||||
return false;
|
||||
}
|
||||
if (!(await runEventPage(tx, job.companyId, run))) return false;
|
||||
await finishRun(tx, job.companyId, run);
|
||||
if (!(await runEventPage(tx, scope.companyId, run))) return false;
|
||||
await finishRun(tx, scope.companyId, run);
|
||||
run.stage = "log";
|
||||
return false;
|
||||
}
|
||||
|
||||
async function step(job: DeletionRow, signal: AbortSignal) {
|
||||
const connectionJobs: JobStore<DeletionRow> = {
|
||||
load: async (id) => (await db.select().from(toolConnectionContentDeletions).where(eq(toolConnectionContentDeletions.id, id)))[0],
|
||||
scope: (row) => connectionScope({ id: row.connectionId, companyId: row.companyId }, row.requestedAt),
|
||||
waitMs: () => null,
|
||||
save: async (tx, row, progress) => (await tx
|
||||
.update(toolConnectionContentDeletions)
|
||||
.set({ progress: progress as unknown as Record<string, unknown>, updatedAt: new Date() })
|
||||
.where(and(
|
||||
eq(toolConnectionContentDeletions.id, row.id),
|
||||
eq(toolConnectionContentDeletions.status, "pending"),
|
||||
eq(toolConnectionContentDeletions.updatedAt, row.updatedAt),
|
||||
))
|
||||
.returning())[0],
|
||||
finish: async (tx, row, now) => (await tx
|
||||
.update(toolConnectionContentDeletions)
|
||||
.set({ status: "completed", completedAt: now, updatedAt: now, lastError: null })
|
||||
.where(and(
|
||||
eq(toolConnectionContentDeletions.id, row.id),
|
||||
eq(toolConnectionContentDeletions.status, "pending"),
|
||||
eq(toolConnectionContentDeletions.updatedAt, row.updatedAt),
|
||||
sql`${toolConnectionContentDeletions.progress}->>'phase' = 'done'`,
|
||||
))
|
||||
.returning())[0],
|
||||
activity: (row, counts) => ({ action: "tool_connection.content_deleted", entityType: "tool_connection", entityId: row.connectionId, details: { ...counts } }),
|
||||
fail: async (row, message) => {
|
||||
await db
|
||||
.update(toolConnectionContentDeletions)
|
||||
.set({ attempts: sql`${toolConnectionContentDeletions.attempts} + 1`, lastError: message, updatedAt: new Date() })
|
||||
.where(and(eq(toolConnectionContentDeletions.id, row.id), eq(toolConnectionContentDeletions.status, "pending")));
|
||||
},
|
||||
};
|
||||
|
||||
const issueJobs: JobStore<IssueDeletionRow> = {
|
||||
load: async (id) => (await db.select().from(issueConnectionContentDeletions).where(eq(issueConnectionContentDeletions.id, id)))[0],
|
||||
scope: (row) => ({ companyId: row.companyId, cutoff: null, connectionId: null, issueId: row.issueId,
|
||||
runIds: row.scope.runIds ?? [], invocationIds: row.scope.invocationIds ?? [], eventIds: row.scope.eventIds ?? [] }),
|
||||
waitMs: (row, progress) => {
|
||||
const waitedMs = Date.now() - row.requestedAt.getTime();
|
||||
if (waitedMs >= ISSUE_WAIT_LIMIT_MS || progress.counts.itemsInProgress + progress.counts.runsInProgress === 0) return null;
|
||||
return Math.min(Math.max(ISSUE_WAIT_MS, waitedMs / 10), ISSUE_WAIT_MAX_MS);
|
||||
},
|
||||
save: async (tx, row, progress, waitMs) => (await tx
|
||||
.update(issueConnectionContentDeletions)
|
||||
.set({
|
||||
progress: progress as unknown as Record<string, unknown>,
|
||||
updatedAt: new Date(),
|
||||
...(waitMs === null ? {} : { notBefore: new Date(Date.now() + waitMs) }),
|
||||
})
|
||||
.where(and(
|
||||
eq(issueConnectionContentDeletions.id, row.id),
|
||||
eq(issueConnectionContentDeletions.status, "pending"),
|
||||
eq(issueConnectionContentDeletions.updatedAt, row.updatedAt),
|
||||
))
|
||||
.returning())[0],
|
||||
finish: async (tx, row, now) => (await tx
|
||||
.update(issueConnectionContentDeletions)
|
||||
.set({ status: "completed", completedAt: now, updatedAt: now, lastError: null })
|
||||
.where(and(
|
||||
eq(issueConnectionContentDeletions.id, row.id),
|
||||
eq(issueConnectionContentDeletions.status, "pending"),
|
||||
eq(issueConnectionContentDeletions.updatedAt, row.updatedAt),
|
||||
sql`${issueConnectionContentDeletions.progress}->>'phase' = 'done'`,
|
||||
))
|
||||
.returning())[0],
|
||||
activity: (row, counts) => {
|
||||
const deleted = counts.toolCalls + counts.approvals + counts.auditEvents + counts.appViews + counts.runs;
|
||||
const open = counts.itemsInProgress + counts.runsInProgress;
|
||||
if (deleted === 0 && open === 0) return null;
|
||||
return { action: open > 0 ? "issue.connection_content_deletion_incomplete" : "issue.connection_content_deleted",
|
||||
entityType: "issue", entityId: row.issueId, details: { ...counts } };
|
||||
},
|
||||
fail: async (row, message) => {
|
||||
await db
|
||||
.update(issueConnectionContentDeletions)
|
||||
.set({ attempts: sql`${issueConnectionContentDeletions.attempts} + 1`, lastError: message, updatedAt: new Date() })
|
||||
.where(and(eq(issueConnectionContentDeletions.id, row.id), eq(issueConnectionContentDeletions.status, "pending")));
|
||||
},
|
||||
};
|
||||
|
||||
async function countOpenRunsWithoutTools(tx: Db, scope: Scope) {
|
||||
if (scope.runIds.length === 0) return 0;
|
||||
const [open] = await tx
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(heartbeatRuns)
|
||||
.where(and(
|
||||
eq(heartbeatRuns.companyId, scope.companyId),
|
||||
sql`${heartbeatRuns.id} = any(${uuidList(scope.runIds)})`,
|
||||
sql`not ${runUsedToolsSql(scope.companyId)}`,
|
||||
sql`not ${settledRunSql(sql`${heartbeatRuns.id}`)}`,
|
||||
));
|
||||
return open?.count ?? 0;
|
||||
}
|
||||
|
||||
async function step<Row extends JobRow>(store: JobStore<Row>, job: Row, signal: AbortSignal) {
|
||||
const scope = store.scope(job);
|
||||
const progress = readProgress(job);
|
||||
const deletedAt = job.requestedAt.toISOString();
|
||||
if (progress.currentRun?.stage === "log" && await removeRunLog(job.companyId, progress.currentRun.id, signal)) {
|
||||
progress.currentRun.changed = true;
|
||||
if (progress.currentRun?.stage === "log") {
|
||||
const removedLog = await removeRunLog(scope.companyId, progress.currentRun.id, signal);
|
||||
const removedResults = await removeSavedResults(scope.companyId, progress.currentRun.id, signal);
|
||||
if (removedLog || removedResults) progress.currentRun.changed = true;
|
||||
}
|
||||
return db.transaction(async (rawTx) => {
|
||||
const tx = rawTx as unknown as Db;
|
||||
const done = progress.phase === "invocations" ? await invocationsStep(tx, job, progress, deletedAt)
|
||||
: progress.phase === "events" ? await eventsStep(tx, job, progress, deletedAt)
|
||||
: progress.phase === "auditEvents" ? await auditEventsStep(tx, job, progress, deletedAt)
|
||||
: progress.phase === "appViews" ? await appViewsStep(tx, job, progress)
|
||||
: progress.phase === "deliveredResults" ? await deliveredResultsStep(tx, job, progress)
|
||||
: await runsStep(tx, job, progress);
|
||||
const done = progress.phase === "invocations" ? await invocationsStep(tx, scope, progress, deletedAt)
|
||||
: progress.phase === "events" ? await eventsStep(tx, scope, progress, deletedAt)
|
||||
: progress.phase === "auditEvents" ? await auditEventsStep(tx, scope, progress, deletedAt)
|
||||
: progress.phase === "appViews" ? await appViewsStep(tx, scope, progress)
|
||||
: progress.phase === "deliveredResults" ? await deliveredResultsStep(tx, scope, progress)
|
||||
: await runsStep(tx, scope, progress);
|
||||
if (done) {
|
||||
progress.phase = nextPhase(progress.phase);
|
||||
progress.cursor = null;
|
||||
progress.runCursor = null;
|
||||
progress.currentRun = null;
|
||||
progress.pendingRuns = [];
|
||||
if (progress.phase === "done" && scope.issueId) progress.counts.runsInProgress += await countOpenRunsWithoutTools(tx, scope);
|
||||
}
|
||||
const [saved] = await tx
|
||||
.update(toolConnectionContentDeletions)
|
||||
.set({ progress: progress as unknown as Record<string, unknown>, updatedAt: new Date() })
|
||||
.where(and(
|
||||
eq(toolConnectionContentDeletions.id, job.id),
|
||||
eq(toolConnectionContentDeletions.status, "pending"),
|
||||
eq(toolConnectionContentDeletions.updatedAt, job.updatedAt),
|
||||
))
|
||||
.returning();
|
||||
const waitMs = progress.phase === "done" ? store.waitMs(job, progress) : null;
|
||||
if (waitMs !== null) {
|
||||
Object.assign(progress, { ...initialContentDeletionProgress(), counts: { ...progress.counts, itemsInProgress: 0, runsInProgress: 0 } });
|
||||
}
|
||||
const saved = await store.save(tx, job, progress, waitMs);
|
||||
if (!saved) throw new ProgressConflict();
|
||||
return saved;
|
||||
return { row: saved, waiting: waitMs !== null };
|
||||
});
|
||||
}
|
||||
|
||||
async function complete(job: DeletionRow) {
|
||||
const progress = readProgress(job);
|
||||
const now = new Date();
|
||||
return db.transaction(async (tx) => {
|
||||
const [done] = await tx
|
||||
.update(toolConnectionContentDeletions)
|
||||
.set({ status: "completed", completedAt: now, updatedAt: now, lastError: null })
|
||||
.where(and(
|
||||
eq(toolConnectionContentDeletions.id, job.id),
|
||||
eq(toolConnectionContentDeletions.status, "pending"),
|
||||
eq(toolConnectionContentDeletions.updatedAt, job.updatedAt),
|
||||
sql`${toolConnectionContentDeletions.progress}->>'phase' = 'done'`,
|
||||
))
|
||||
.returning();
|
||||
async function complete<Row extends JobRow>(store: JobStore<Row>, job: Row) {
|
||||
const counts = readProgress(job).counts;
|
||||
return db.transaction(async (rawTx) => {
|
||||
const tx = rawTx as unknown as Db;
|
||||
const done = await store.finish(tx, job, new Date());
|
||||
if (!done) return null;
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId: job.companyId,
|
||||
actorType: job.requestedByActorType === "agent" ? "agent" : job.requestedByActorType === "user" ? "user" : "system",
|
||||
actorId: job.requestedByActorId ?? "tool-connection-content-deletion",
|
||||
action: "tool_connection.content_deleted",
|
||||
entityType: "tool_connection",
|
||||
entityId: job.connectionId,
|
||||
details: { ...progress.counts },
|
||||
});
|
||||
const activity = store.activity(job, counts);
|
||||
if (activity) {
|
||||
await logActivity(tx, {
|
||||
companyId: job.companyId,
|
||||
actorType: job.requestedByActorType === "agent" ? "agent" : job.requestedByActorType === "user" ? "user" : "system",
|
||||
actorId: job.requestedByActorId ?? "tool-connection-content-deletion",
|
||||
...activity,
|
||||
});
|
||||
}
|
||||
return done;
|
||||
});
|
||||
}
|
||||
|
||||
async function process(jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) {
|
||||
async function runJob<Row extends JobRow>(store: JobStore<Row>, jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) {
|
||||
const startedAt = Date.now();
|
||||
let [job] = await db.select().from(toolConnectionContentDeletions).where(eq(toolConnectionContentDeletions.id, jobId));
|
||||
if (!job || job.status !== "pending") return job ?? null;
|
||||
const loaded = await store.load(jobId);
|
||||
if (!loaded || loaded.status !== "pending") return loaded ?? null;
|
||||
let job: Row = loaded;
|
||||
try {
|
||||
while (!signal.aborted) {
|
||||
if (readProgress(job).phase === "done") return await complete(job);
|
||||
job = await step(job, signal);
|
||||
if (Date.now() - startedAt >= budgetMs) return job;
|
||||
if (readProgress(job).phase === "done") return await complete(store, job);
|
||||
const next: { row: Row; waiting: boolean } = await step(store, job, signal);
|
||||
job = next.row;
|
||||
if (next.waiting || Date.now() - startedAt >= budgetMs) return job;
|
||||
}
|
||||
return job;
|
||||
} catch (error) {
|
||||
if (error instanceof ProgressConflict) return null;
|
||||
await db
|
||||
.update(toolConnectionContentDeletions)
|
||||
.set({
|
||||
attempts: sql`${toolConnectionContentDeletions.attempts} + 1`,
|
||||
lastError: error instanceof Error ? error.message.slice(0, 500) : "content deletion failed",
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(and(eq(toolConnectionContentDeletions.id, job.id), eq(toolConnectionContentDeletions.status, "pending")));
|
||||
await store.fail(job, error instanceof Error ? error.message.slice(0, 500) : "content deletion failed");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function process(jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) {
|
||||
return runJob(connectionJobs, jobId, signal, budgetMs);
|
||||
}
|
||||
|
||||
async function processIssueDeletion(jobId: string, signal: AbortSignal, budgetMs = STEP_BUDGET_MS) {
|
||||
return runJob(issueJobs, jobId, signal, budgetMs);
|
||||
}
|
||||
|
||||
async function processPending(signal: AbortSignal) {
|
||||
const rows = await db
|
||||
let failure: unknown = null;
|
||||
const connectionPending = await db
|
||||
.select({ id: toolConnectionContentDeletions.id })
|
||||
.from(toolConnectionContentDeletions)
|
||||
.where(eq(toolConnectionContentDeletions.status, "pending"))
|
||||
.orderBy(asc(toolConnectionContentDeletions.updatedAt))
|
||||
.limit(10);
|
||||
let failure: unknown = null;
|
||||
for (const { id } of rows) {
|
||||
for (const { id } of connectionPending) {
|
||||
if (signal.aborted) break;
|
||||
try {
|
||||
await process(id, signal);
|
||||
} catch (error) {
|
||||
failure ??= error;
|
||||
}
|
||||
await process(id, signal).catch((error: unknown) => { failure ??= error; });
|
||||
}
|
||||
const issuePending = await db
|
||||
.select({ id: issueConnectionContentDeletions.id })
|
||||
.from(issueConnectionContentDeletions)
|
||||
.where(and(eq(issueConnectionContentDeletions.status, "pending"), lte(issueConnectionContentDeletions.notBefore, new Date())))
|
||||
.orderBy(asc(issueConnectionContentDeletions.notBefore))
|
||||
.limit(10);
|
||||
for (const { id } of issuePending) {
|
||||
if (signal.aborted) break;
|
||||
await processIssueDeletion(id, signal).catch((error: unknown) => { failure ??= error; });
|
||||
}
|
||||
if (!signal.aborted) await storedObjects.drain(signal).catch((error: unknown) => { failure ??= error; });
|
||||
if (failure) throw failure;
|
||||
}
|
||||
|
||||
async function nextDeadline() {
|
||||
const [row] = await db
|
||||
const [connectionJob] = await db
|
||||
.select({ id: toolConnectionContentDeletions.id })
|
||||
.from(toolConnectionContentDeletions)
|
||||
.where(eq(toolConnectionContentDeletions.status, "pending"))
|
||||
.limit(1);
|
||||
return row ? Date.now() : null;
|
||||
if (connectionJob) return Date.now();
|
||||
const [issueJob] = await db
|
||||
.select({ at: sql<Date | null>`min(${issueConnectionContentDeletions.notBefore})`.mapWith(issueConnectionContentDeletions.notBefore) })
|
||||
.from(issueConnectionContentDeletions)
|
||||
.where(eq(issueConnectionContentDeletions.status, "pending"));
|
||||
const due = [issueJob?.at?.getTime() ?? null, await storedObjects.nextDeadline()].flatMap((at) => at === null ? [] : [at]);
|
||||
return due.length > 0 ? Math.max(Date.now(), Math.min(...due)) : null;
|
||||
}
|
||||
|
||||
return { storedContent, latestDeletion, request, process, processPending, nextDeadline };
|
||||
return { storedContent, latestDeletion, request, process, processIssueDeletion, processPending, nextDeadline };
|
||||
}
|
||||
|
||||
export type ConnectionContentDeletionService = ReturnType<typeof createConnectionContentDeletion>;
|
||||
@@ -0,0 +1,57 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { heartbeatRuns, issueConnectionContentDeletions, toolCallEvents, toolInvocations, type Db } from "@paperclipai/db";
|
||||
import { initialContentDeletionProgress, runUsedToolsSql, settledRunSql, uuidList } from "./content-deletion.js";
|
||||
import { requestIssueAttachmentObjectDeletion } from "./stored-object-deletion.js";
|
||||
|
||||
export async function requestIssueConnectionContentDeletion(
|
||||
tx: Db,
|
||||
input: { companyId: string; issueId: string; actorAgentId?: string | null },
|
||||
) {
|
||||
await requestIssueAttachmentObjectDeletion(tx, input);
|
||||
const runs = await tx
|
||||
.select({ id: heartbeatRuns.id })
|
||||
.from(heartbeatRuns)
|
||||
.where(and(
|
||||
eq(heartbeatRuns.companyId, input.companyId),
|
||||
sql`(${heartbeatRuns.issueId} = ${input.issueId} or ${heartbeatRuns.contextSnapshot}->>'issueId' = ${input.issueId}::text)`,
|
||||
sql`(${runUsedToolsSql(input.companyId)} or not ${settledRunSql(sql`${heartbeatRuns.id}`)})`,
|
||||
));
|
||||
const runIds = runs.map((row) => row.id);
|
||||
const calls = await tx
|
||||
.select({ id: toolInvocations.id })
|
||||
.from(toolInvocations)
|
||||
.where(and(
|
||||
eq(toolInvocations.companyId, input.companyId),
|
||||
eq(toolInvocations.issueId, input.issueId),
|
||||
sql`(${toolInvocations.runId} is null or not (${toolInvocations.runId} = any(${uuidList(runIds)})))`,
|
||||
));
|
||||
const invocationIds = calls.map((row) => row.id);
|
||||
const events = await tx
|
||||
.select({ id: toolCallEvents.id })
|
||||
.from(toolCallEvents)
|
||||
.where(and(
|
||||
eq(toolCallEvents.companyId, input.companyId),
|
||||
eq(toolCallEvents.issueId, input.issueId),
|
||||
sql`(${toolCallEvents.runId} is null or not (${toolCallEvents.runId} = any(${uuidList(runIds)})))`,
|
||||
sql`(${toolCallEvents.invocationId} is null or not (${toolCallEvents.invocationId} = any(${uuidList(invocationIds)})))`,
|
||||
));
|
||||
const eventIds = events.map((row) => row.id);
|
||||
if (runIds.length === 0 && invocationIds.length === 0 && eventIds.length === 0) return null;
|
||||
const now = new Date();
|
||||
const [created] = await tx
|
||||
.insert(issueConnectionContentDeletions)
|
||||
.values({
|
||||
requestedAt: now,
|
||||
notBefore: now,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
companyId: input.companyId,
|
||||
issueId: input.issueId,
|
||||
scope: { runIds, invocationIds, eventIds },
|
||||
requestedByActorType: input.actorAgentId ? "agent" : "system",
|
||||
requestedByActorId: input.actorAgentId ?? null,
|
||||
progress: initialContentDeletionProgress() as unknown as Record<string, unknown>,
|
||||
})
|
||||
.returning({ id: issueConnectionContentDeletions.id });
|
||||
return created!.id;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { asc, eq, lte, sql } from "drizzle-orm";
|
||||
import { assets, heartbeatRuns, runnerApiResponseReservations, storedObjectDeletions, type Db } from "@paperclipai/db";
|
||||
import { isRunLogStoreType, type RunLogStore } from "../../run-log-store.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js";
|
||||
import type { StorageService } from "../../../storage/types.js";
|
||||
|
||||
const OBJECT_BATCH_SIZE = 50;
|
||||
const OBJECT_RETRY_MS = 30_000;
|
||||
|
||||
export async function requestIssueAttachmentObjectDeletion(tx: Db, input: { companyId: string; issueId: string }) {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolConnectionContentDeletion);
|
||||
await tx.execute(sql`insert into ${storedObjectDeletions} (company_id, kind, object_key)
|
||||
select asset.company_id, 'asset', asset.object_key from ${assets} asset
|
||||
join issue_attachments link on link.asset_id = asset.id
|
||||
where link.company_id = ${input.companyId} and link.issue_id = ${input.issueId} and asset.company_id = ${input.companyId}`);
|
||||
}
|
||||
|
||||
export async function requestCompanyStoredObjectDeletion(tx: Db, companyId: string) {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolConnectionContentDeletion);
|
||||
await tx.execute(sql`insert into ${storedObjectDeletions} (company_id, kind, log_store, object_key)
|
||||
select company_id, 'run_log', log_store, log_ref from ${heartbeatRuns}
|
||||
where company_id = ${companyId} and log_ref is not null and log_store is not null
|
||||
union all
|
||||
select company_id, 'asset', null, object_key from ${assets} where company_id = ${companyId}
|
||||
union all
|
||||
select company_id, 'asset', null, pending_delete_object_key from ${runnerApiResponseReservations}
|
||||
where company_id = ${companyId} and pending_delete_object_key is not null`);
|
||||
}
|
||||
|
||||
export function createStoredObjectDeletion(db: Db, deps: {
|
||||
runLogStore: () => RunLogStore;
|
||||
storage: () => StorageService;
|
||||
retryMs?: number;
|
||||
}) {
|
||||
const retryMs = deps.retryMs ?? OBJECT_RETRY_MS;
|
||||
|
||||
async function drain(signal: AbortSignal) {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(storedObjectDeletions)
|
||||
.where(lte(storedObjectDeletions.notBefore, new Date()))
|
||||
.orderBy(asc(storedObjectDeletions.notBefore), asc(storedObjectDeletions.id))
|
||||
.limit(OBJECT_BATCH_SIZE);
|
||||
let failure: unknown = null;
|
||||
for (const row of rows) {
|
||||
if (signal.aborted) break;
|
||||
try {
|
||||
if (row.kind === "run_log") {
|
||||
if (!isRunLogStoreType(row.logStore)) throw new Error("run_log_store_unrecognised");
|
||||
const store = deps.runLogStore();
|
||||
if (!store.remove) throw new Error("run_log_removal_unavailable");
|
||||
await store.remove({ store: row.logStore, logRef: row.objectKey }, signal);
|
||||
} else {
|
||||
await deps.storage().deleteObject(row.companyId, row.objectKey, { signal, allVersions: true });
|
||||
}
|
||||
await db.delete(storedObjectDeletions).where(eq(storedObjectDeletions.id, row.id));
|
||||
} catch (error) {
|
||||
failure ??= error;
|
||||
await db
|
||||
.update(storedObjectDeletions)
|
||||
.set({
|
||||
attempts: sql`${storedObjectDeletions.attempts} + 1`,
|
||||
lastError: error instanceof Error ? error.message.slice(0, 500) : "object deletion failed",
|
||||
notBefore: new Date(Date.now() + retryMs * 2 ** Math.min(row.attempts, 6)),
|
||||
})
|
||||
.where(eq(storedObjectDeletions.id, row.id));
|
||||
}
|
||||
}
|
||||
if (failure) throw failure;
|
||||
}
|
||||
|
||||
async function nextDeadline() {
|
||||
const [row] = await db
|
||||
.select({ at: sql<Date | null>`min(${storedObjectDeletions.notBefore})`.mapWith(storedObjectDeletions.notBefore) })
|
||||
.from(storedObjectDeletions);
|
||||
return row?.at ? row.at.getTime() : null;
|
||||
}
|
||||
|
||||
return { drain, nextDeadline };
|
||||
}
|
||||
Reference in new issue
Block a user