@capybara-hq/kernel 0.1.0-rc.130 → 0.1.0-rc.132
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/account-erasures.d.ts +37 -0
- package/dist/admin/account-erasures.js +119 -0
- package/dist/admin/admin.controller.d.ts +35 -2
- package/dist/admin/admin.controller.js +75 -18
- package/dist/admin/admin.module.js +10 -0
- package/dist/admin/admin.schemas.d.ts +51 -0
- package/dist/admin/admin.schemas.js +20 -0
- package/dist/admin/erasure-dispositions.d.ts +23 -0
- package/dist/admin/erasure-dispositions.js +76 -0
- package/dist/admin/health.service.d.ts +6 -0
- package/dist/admin/health.service.js +27 -1
- package/dist/admin/usage.service.d.ts +5 -0
- package/dist/admin/usage.service.js +21 -2
- package/dist/agents/agents.service.d.ts +1 -1
- package/dist/catalog/plugin-import.d.ts +3 -1
- package/dist/catalog/plugin-import.js +19 -15
- package/dist/channels/connections.service.d.ts +1 -1
- package/dist/client/client-reports.service.js +12 -0
- package/dist/config/schema.d.ts +9 -1
- package/dist/config/schema.js +51 -1
- package/dist/conversations/conversations.service.d.ts +9 -1
- package/dist/conversations/conversations.service.js +112 -15
- package/dist/conversations/event-log.d.ts +2 -0
- package/dist/conversations/event-log.js +77 -0
- package/dist/conversations/events.d.ts +11 -0
- package/dist/conversations/events.js +13 -1
- package/dist/conversations/prompt-suggestions.js +4 -0
- package/dist/conversations/titles.js +3 -2
- package/dist/ctx/create-ctx.d.ts +3 -2
- package/dist/ctx/create-ctx.js +10 -7
- package/dist/db/extension-db.d.ts +30 -0
- package/dist/db/extension-db.js +91 -0
- package/dist/db/extension-schema-transfer.d.ts +6 -0
- package/dist/db/extension-schema-transfer.js +141 -0
- package/dist/db/kernel-schema.d.ts +73 -12
- package/dist/db/migrator.d.ts +6 -0
- package/dist/db/migrator.js +39 -4
- package/dist/db/pool.d.ts +4 -0
- package/dist/db/pool.js +36 -1
- package/dist/devices/devices.service.d.ts +13 -1
- package/dist/devices/devices.service.js +122 -9
- package/dist/erasure/account-batches.d.ts +9 -0
- package/dist/erasure/account-batches.js +567 -0
- package/dist/erasure/account-files.d.ts +34 -0
- package/dist/erasure/account-files.js +217 -0
- package/dist/erasure/account-residual.d.ts +15 -0
- package/dist/erasure/account-residual.js +149 -0
- package/dist/erasure/account-worker.d.ts +32 -0
- package/dist/erasure/account-worker.js +392 -0
- package/dist/erasure/device-cleanup.d.ts +23 -0
- package/dist/erasure/device-cleanup.js +221 -0
- package/dist/erasure/erasure.module.d.ts +2 -0
- package/dist/{conversations/event-org-backfill.module.js → erasure/erasure.module.js} +6 -10
- package/dist/erasure/external-evidence.d.ts +4 -0
- package/dist/erasure/external-evidence.js +28 -0
- package/dist/erasure/jobs.d.ts +5 -0
- package/dist/erasure/jobs.js +20 -0
- package/dist/erasure/org-batches.d.ts +11 -0
- package/dist/erasure/org-batches.js +159 -0
- package/dist/erasure/org-catalog.d.ts +2 -0
- package/dist/erasure/org-catalog.js +34 -0
- package/dist/erasure/org-rules.d.ts +14 -0
- package/dist/erasure/org-rules.js +227 -0
- package/dist/erasure/org-worker.d.ts +38 -0
- package/dist/erasure/org-worker.js +501 -0
- package/dist/erasure/requests.d.ts +61 -0
- package/dist/erasure/requests.js +180 -0
- package/dist/erasure/sweep.job.d.ts +19 -0
- package/dist/erasure/sweep.job.js +130 -0
- package/dist/erasure/worker.d.ts +17 -0
- package/dist/erasure/worker.js +110 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.js +4 -0
- package/dist/evals/judge.d.ts +5 -0
- package/dist/evals/judge.js +16 -1
- package/dist/evals/run-replay.js +12 -1
- package/dist/evals/step-replay.d.ts +5 -3
- package/dist/evals/step-replay.js +9 -5
- package/dist/evals/worker.d.ts +2 -0
- package/dist/evals/worker.js +60 -16
- package/dist/extensions/admin-ops.d.ts +3 -1
- package/dist/extensions/admin-ops.js +11 -7
- package/dist/extensions/extensions.module.js +3 -0
- package/dist/extensions/host.d.ts +4 -1
- package/dist/extensions/host.js +29 -6
- package/dist/extensions/instance.d.ts +3 -0
- package/dist/extensions/instance.js +3 -1
- package/dist/extensions/migrate-lock.d.ts +4 -1
- package/dist/extensions/migrate-lock.js +19 -2
- package/dist/files/blob-objects.d.ts +7 -3
- package/dist/files/blob-objects.js +39 -22
- package/dist/files/blob-sweep.job.d.ts +11 -0
- package/dist/files/blob-sweep.job.js +67 -6
- package/dist/http/api.module.js +5 -1
- package/dist/identity/accounts.js +3 -0
- package/dist/identity/api-tokens.js +5 -0
- package/dist/identity/auth.guard.d.ts +1 -0
- package/dist/identity/auth.guard.js +1 -0
- package/dist/identity/erasure-admission.d.ts +3 -0
- package/dist/identity/erasure-admission.js +14 -0
- package/dist/identity/external.js +5 -0
- package/dist/identity/sessions.js +5 -0
- package/dist/identity/settings.d.ts +86 -1
- package/dist/identity/settings.js +38 -4
- package/dist/infra/config/kernel-config.service.js +1 -0
- package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
- package/dist/infra/metrics/kernel-metrics.js +54 -0
- package/dist/infra/metrics/operational-metrics.d.ts +31 -0
- package/dist/infra/metrics/operational-metrics.js +188 -0
- package/dist/infra/outbox/registry.d.ts +23 -14
- package/dist/infra/outbox/registry.js +12 -15
- package/dist/infra/throttler/credential-throttler.js +8 -1
- package/dist/infra/throttler/named-throttlers.d.ts +6 -0
- package/dist/infra/throttler/named-throttlers.js +6 -0
- package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
- package/dist/infra/throttler/principal-throttler.guard.js +50 -0
- package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
- package/dist/infra/throttler/redis-throttler-storage.js +27 -5
- package/dist/infra/throttler/throttler.guard.d.ts +2 -3
- package/dist/infra/throttler/throttler.guard.js +2 -3
- package/dist/infra/throttler/throttler.module.js +3 -2
- package/dist/kernel.js +4 -0
- package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
- package/dist/lifecycle/kernel-lifecycle.js +26 -21
- package/dist/models/budget-admission.d.ts +31 -0
- package/dist/models/budget-admission.js +149 -0
- package/dist/models/budget-counters.d.ts +28 -0
- package/dist/models/budget-counters.js +117 -0
- package/dist/models/budget-policy.d.ts +88 -0
- package/dist/models/budget-policy.js +78 -0
- package/dist/models/embeddings.js +13 -2
- package/dist/models/images.js +12 -2
- package/dist/models/purposes.d.ts +5 -2
- package/dist/models/purposes.js +9 -5
- package/dist/orgs/invitations.service.d.ts +1 -1
- package/dist/orgs/members.service.d.ts +28 -1
- package/dist/orgs/members.service.js +74 -11
- package/dist/orgs/offboarding.js +4 -6
- package/dist/orgs/org-owner.d.ts +2 -0
- package/dist/orgs/org-owner.js +21 -6
- package/dist/orgs/orgs.controller.d.ts +22 -0
- package/dist/orgs/orgs.controller.js +24 -0
- package/dist/orgs/orgs.module.js +4 -0
- package/dist/orgs/orgs.schemas.js +7 -0
- package/dist/orgs/orgs.service.d.ts +5 -1
- package/dist/orgs/orgs.service.js +28 -3
- package/dist/orgs/settings.controller.js +6 -1
- package/dist/orgs/settings.service.d.ts +58 -1
- package/dist/orgs/settings.service.js +74 -9
- package/dist/platform/exclusions.js +20 -1
- package/dist/platform/ops/accounts.ops.js +58 -1
- package/dist/platform/ops/admin.ops.js +13 -5
- package/dist/platform/ops/org-settings.ops.js +11 -4
- package/dist/platform/ops/orgs.ops.js +28 -0
- package/dist/platform/ops/retention.d.ts +16 -0
- package/dist/platform/ops/retention.js +21 -0
- package/dist/retention/jobs.d.ts +21 -0
- package/dist/retention/jobs.js +48 -0
- package/dist/retention/policy.d.ts +70 -0
- package/dist/retention/policy.js +103 -0
- package/dist/retention/purge-batch.d.ts +17 -0
- package/dist/retention/purge-batch.js +355 -0
- package/dist/retention/report-obligations.d.ts +12 -0
- package/dist/retention/report-obligations.js +71 -0
- package/dist/retention/sweep.job.d.ts +17 -0
- package/dist/retention/sweep.job.js +95 -0
- package/dist/retention/worker.d.ts +29 -0
- package/dist/retention/worker.js +306 -0
- package/dist/roles/worker.module.js +12 -8
- package/dist/runtime/maintenance.d.ts +5 -3
- package/dist/runtime/maintenance.js +19 -12
- package/dist/runtime/model-call.d.ts +3 -1
- package/dist/runtime/model-call.js +25 -3
- package/dist/runtime/providers.d.ts +7 -2
- package/dist/runtime/providers.js +76 -10
- package/dist/runtime/quota.d.ts +12 -12
- package/dist/runtime/quota.js +42 -37
- package/dist/runtime/run-finish.js +2 -0
- package/dist/runtime/run-principal.d.ts +9 -0
- package/dist/runtime/run-principal.js +18 -0
- package/dist/runtime/run-worker.js +48 -10
- package/dist/runtime/usage-report-jobs.d.ts +4 -1
- package/dist/runtime/usage-report-jobs.js +36 -13
- package/dist/runtime/usage-report.d.ts +5 -3
- package/dist/runtime/usage-report.js +37 -19
- package/dist/sandbox/review/classifier.d.ts +2 -2
- package/dist/sandbox/review/classifier.js +6 -2
- package/dist/sandbox/sandbox.service.js +18 -7
- package/dist/storage/purge.js +5 -1
- package/dist/storage/storage.service.d.ts +17 -1
- package/dist/storage/storage.service.js +75 -4
- package/dist/tools/builtins/vision/read-image.js +3 -0
- package/dist/tools/builtins/web/extract.js +3 -0
- package/dist/tools/pipeline.js +5 -1
- package/package.json +3 -1
- package/src/migrations/0216_model_budget_counters.sql +24 -0
- package/src/migrations/0217_retention.sql +44 -0
- package/src/migrations/0218_data_erasure.sql +41 -0
- package/src/migrations/0219_event_org_constraint_check.sql +29 -0
- package/src/migrations/0220_require_event_org.sql +18 -0
- package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
- package/dist/conversations/event-org-backfill.d.ts +0 -111
- package/dist/conversations/event-org-backfill.js +0 -264
- package/dist/conversations/event-org-backfill.module.d.ts +0 -3
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { ACTIVE_RUN_STATUSES } from "../runtime/run-jobs.js";
|
|
3
|
+
import { usageReportJobId } from "../runtime/usage-report-jobs.js";
|
|
4
|
+
import { recordRetentionLoss } from "./jobs.js";
|
|
5
|
+
import { hasOwedUsageReports } from "./report-obligations.js";
|
|
6
|
+
export const PURGE_BATCH_SIZE = 128;
|
|
7
|
+
const MAX_TREE_DEPTH = 16;
|
|
8
|
+
async function leafOf(db, { orgId, conversationId }) {
|
|
9
|
+
// Follow a single branch, using the parent index at each level. A continuation re-derives
|
|
10
|
+
// the next branch after its leaf disappears, so a wide tree needs no materialized ID list.
|
|
11
|
+
const { rows } = await sql `
|
|
12
|
+
WITH RECURSIVE branch(id, depth) AS (
|
|
13
|
+
SELECT id, 0 FROM capybara.conversations
|
|
14
|
+
WHERE id = ${conversationId} AND org_id = ${orgId} AND deleted_at IS NOT NULL
|
|
15
|
+
UNION ALL
|
|
16
|
+
SELECT child.id, branch.depth + 1 FROM branch
|
|
17
|
+
CROSS JOIN LATERAL (
|
|
18
|
+
SELECT id FROM capybara.conversations
|
|
19
|
+
WHERE parent_conversation_id = branch.id AND org_id = ${orgId}
|
|
20
|
+
ORDER BY id LIMIT 1
|
|
21
|
+
) child
|
|
22
|
+
WHERE branch.depth < ${MAX_TREE_DEPTH}
|
|
23
|
+
)
|
|
24
|
+
SELECT id, depth FROM branch ORDER BY depth DESC LIMIT 1
|
|
25
|
+
`.execute(db);
|
|
26
|
+
return rows[0];
|
|
27
|
+
}
|
|
28
|
+
function eventBatch(db, orgId, leaf) {
|
|
29
|
+
// Use the parent and (conversation_id, seq) throughout the event ownership expansion.
|
|
30
|
+
return db
|
|
31
|
+
.selectFrom("conversation_events as e")
|
|
32
|
+
.innerJoin("conversations as c", "c.id", "e.conversation_id")
|
|
33
|
+
.select(["e.seq", "e.type", "e.created_at"])
|
|
34
|
+
.where("e.conversation_id", "=", leaf)
|
|
35
|
+
.where("c.org_id", "=", orgId)
|
|
36
|
+
.orderBy("e.seq")
|
|
37
|
+
.limit(PURGE_BATCH_SIZE)
|
|
38
|
+
.execute();
|
|
39
|
+
}
|
|
40
|
+
function affectedRange(dates) {
|
|
41
|
+
if (!dates.length)
|
|
42
|
+
return undefined;
|
|
43
|
+
dates.sort((a, b) => a.getTime() - b.getTime());
|
|
44
|
+
const first = dates[0];
|
|
45
|
+
const last = dates.at(-1);
|
|
46
|
+
return first && last ? { since: first, through: last } : undefined;
|
|
47
|
+
}
|
|
48
|
+
function usageReportIds(leaf, events) {
|
|
49
|
+
return events.filter((e) => e.type === "usage").map((e) => usageReportJobId(leaf, Number(e.seq)));
|
|
50
|
+
}
|
|
51
|
+
/** Check the bounded Redis obligations before opening the write transaction. */
|
|
52
|
+
export async function prepareConversationBatch(db, target, reports) {
|
|
53
|
+
const leaf = await leafOf(db, target);
|
|
54
|
+
if (!leaf || leaf.depth === MAX_TREE_DEPTH)
|
|
55
|
+
return undefined;
|
|
56
|
+
const ids = usageReportIds(leaf.id, await eventBatch(db, target.orgId, leaf.id));
|
|
57
|
+
return { leaf: leaf.id, checked: ids, clear: await reports.clear(target.orgId, ids) };
|
|
58
|
+
}
|
|
59
|
+
async function obligationsCleared(db, orgId, id) {
|
|
60
|
+
const runs = await db
|
|
61
|
+
.selectFrom("runs")
|
|
62
|
+
.select("id")
|
|
63
|
+
.where("conversation_id", "=", id)
|
|
64
|
+
.where("status", "in", ACTIVE_RUN_STATUSES)
|
|
65
|
+
.limit(1)
|
|
66
|
+
.executeTakeFirst();
|
|
67
|
+
if (runs)
|
|
68
|
+
return false;
|
|
69
|
+
const tasks = await db
|
|
70
|
+
.selectFrom("background_tasks")
|
|
71
|
+
.select("id")
|
|
72
|
+
.where("org_id", "=", orgId)
|
|
73
|
+
.where((eb) => eb.or([eb("conversation_id", "=", id), eb("sandbox_conversation_id", "=", id)]))
|
|
74
|
+
.where((eb) => eb.or([
|
|
75
|
+
eb("status", "=", "running"),
|
|
76
|
+
eb("stopping_at", "is not", null),
|
|
77
|
+
eb("launch_state", "!=", "terminal"),
|
|
78
|
+
]))
|
|
79
|
+
.limit(1)
|
|
80
|
+
.executeTakeFirst();
|
|
81
|
+
if (tasks)
|
|
82
|
+
return false;
|
|
83
|
+
const intents = await db
|
|
84
|
+
.selectFrom("sandbox_operation_intents")
|
|
85
|
+
.select("operation_id")
|
|
86
|
+
.where("org_id", "=", orgId)
|
|
87
|
+
.where((eb) => eb.or([eb("conversation_id", "=", id), eb("root_conversation_id", "=", id)]))
|
|
88
|
+
.where((eb) => eb.or([
|
|
89
|
+
eb("state", "not in", ["completed", "revoked"]),
|
|
90
|
+
eb.and([
|
|
91
|
+
eb("method", "=", "backgroundStart"),
|
|
92
|
+
eb("state", "=", "revoked"),
|
|
93
|
+
eb("execution_ref", "is not", null),
|
|
94
|
+
eb("revoke_acknowledged", "=", false),
|
|
95
|
+
]),
|
|
96
|
+
]))
|
|
97
|
+
.limit(1)
|
|
98
|
+
.executeTakeFirst();
|
|
99
|
+
if (intents)
|
|
100
|
+
return false;
|
|
101
|
+
// These legacy read copies have object keys. Let the existing attachment sweep delete bytes
|
|
102
|
+
// before the parent FK can remove their only record. Library files use independent blobs.
|
|
103
|
+
const attachment = await db
|
|
104
|
+
.selectFrom("attachments")
|
|
105
|
+
.select("id")
|
|
106
|
+
.where("org_id", "=", orgId)
|
|
107
|
+
.where("conversation_id", "=", id)
|
|
108
|
+
.limit(1)
|
|
109
|
+
.executeTakeFirst();
|
|
110
|
+
return attachment === undefined;
|
|
111
|
+
}
|
|
112
|
+
async function removeEventBatch(db, orgId, leaf, events) {
|
|
113
|
+
const removed = await db
|
|
114
|
+
.deleteFrom("conversation_events as e")
|
|
115
|
+
.using("conversations as c")
|
|
116
|
+
.whereRef("c.id", "=", "e.conversation_id")
|
|
117
|
+
.where("c.org_id", "=", orgId)
|
|
118
|
+
.where("e.conversation_id", "=", leaf.id)
|
|
119
|
+
.where("e.seq", "in", events.map((e) => e.seq))
|
|
120
|
+
.returning(["e.created_at", "e.type"])
|
|
121
|
+
.execute();
|
|
122
|
+
if (leaf.kind === "eval")
|
|
123
|
+
return;
|
|
124
|
+
const range = affectedRange(removed.filter((e) => e.type === "usage").map((e) => e.created_at));
|
|
125
|
+
if (range)
|
|
126
|
+
await recordRetentionLoss(db, orgId, { usage: range.since, usageThrough: range.through });
|
|
127
|
+
}
|
|
128
|
+
/** Remove only the next stable primary-key slice of an inventoried dependent table. */
|
|
129
|
+
async function deleteKeyBatch(db, table, keys, predicate) {
|
|
130
|
+
const columns = sql.join(keys.map((key) => sql.id(key)));
|
|
131
|
+
const name = sql.id("capybara", table);
|
|
132
|
+
const { rows } = await sql `
|
|
133
|
+
DELETE FROM ${name} WHERE (${columns}) IN (
|
|
134
|
+
SELECT ${columns} FROM ${name} WHERE ${predicate}
|
|
135
|
+
ORDER BY ${columns} LIMIT ${PURGE_BATCH_SIZE}
|
|
136
|
+
) RETURNING 1`.execute(db);
|
|
137
|
+
return rows.length > 0;
|
|
138
|
+
}
|
|
139
|
+
const leafDependents = [
|
|
140
|
+
["approvals", ["id"], true],
|
|
141
|
+
["questions", ["id"], true],
|
|
142
|
+
["file_shares", ["id"], true],
|
|
143
|
+
["conversation_files", ["conversation_id", "file_id"], true],
|
|
144
|
+
["platform_sealed_reveals", ["id"], true],
|
|
145
|
+
["device_site_grants", ["id"], true],
|
|
146
|
+
["device_loopback_grants", ["id"], true],
|
|
147
|
+
["channel_card_messages", ["conversation_id", "connection_id", "card_kind", "card_id"], false],
|
|
148
|
+
["conversation_tool_grants", ["conversation_id", "tool_key"], false],
|
|
149
|
+
["account_initial_passwords", ["account_id"], false],
|
|
150
|
+
];
|
|
151
|
+
async function removeDependentBatch(db, orgId, id) {
|
|
152
|
+
const intents = await db
|
|
153
|
+
.deleteFrom("sandbox_operation_intents")
|
|
154
|
+
.where("org_id", "=", orgId)
|
|
155
|
+
.where("operation_id", "in", (eb) => eb
|
|
156
|
+
.selectFrom("sandbox_operation_intents as i")
|
|
157
|
+
.select("i.operation_id")
|
|
158
|
+
.where("i.org_id", "=", orgId)
|
|
159
|
+
.where((b) => b.or([b("i.conversation_id", "=", id), b("i.root_conversation_id", "=", id)]))
|
|
160
|
+
.orderBy("i.operation_id")
|
|
161
|
+
.limit(PURGE_BATCH_SIZE))
|
|
162
|
+
.executeTakeFirst();
|
|
163
|
+
if (intents.numDeletedRows > 0n)
|
|
164
|
+
return true;
|
|
165
|
+
const grants = await db
|
|
166
|
+
.deleteFrom("permission_call_grants")
|
|
167
|
+
.where("org_id", "=", orgId)
|
|
168
|
+
.where("id", "in", (eb) => eb
|
|
169
|
+
.selectFrom("permission_call_grants as g")
|
|
170
|
+
.select("g.id")
|
|
171
|
+
.where("g.org_id", "=", orgId)
|
|
172
|
+
.where((b) => b.or([b("g.conversation_id", "=", id), b("g.root_conversation_id", "=", id)]))
|
|
173
|
+
.orderBy("g.id")
|
|
174
|
+
.limit(PURGE_BATCH_SIZE))
|
|
175
|
+
.executeTakeFirst();
|
|
176
|
+
if (grants.numDeletedRows > 0n)
|
|
177
|
+
return true;
|
|
178
|
+
const outputs = await db
|
|
179
|
+
.deleteFrom("tool_outputs")
|
|
180
|
+
.where("org_id", "=", orgId)
|
|
181
|
+
.where("id", "in", (eb) => eb
|
|
182
|
+
.selectFrom("tool_outputs as output")
|
|
183
|
+
.select("output.id")
|
|
184
|
+
.where("output.org_id", "=", orgId)
|
|
185
|
+
.where("output.conversation_id", "=", id)
|
|
186
|
+
.orderBy("output.id")
|
|
187
|
+
.limit(PURGE_BATCH_SIZE))
|
|
188
|
+
.executeTakeFirst();
|
|
189
|
+
if (outputs.numDeletedRows > 0n)
|
|
190
|
+
return true;
|
|
191
|
+
if (await deleteKeyBatch(db, "background_tasks", ["id"], sql `org_id = ${orgId} AND launch_state = 'terminal' AND status <> 'running'
|
|
192
|
+
AND stopping_at IS NULL AND (conversation_id = ${id} OR sandbox_conversation_id = ${id})`))
|
|
193
|
+
return true;
|
|
194
|
+
for (const [table, keys, orgScoped] of leafDependents) {
|
|
195
|
+
const scope = orgScoped ? sql `AND org_id = ${orgId}` : sql ``;
|
|
196
|
+
if (await deleteKeyBatch(db, table, keys, sql `conversation_id = ${id} ${scope}`))
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
const files = await db
|
|
200
|
+
.updateTable("files")
|
|
201
|
+
.set({ source_conversation_id: null })
|
|
202
|
+
.where("org_id", "=", orgId)
|
|
203
|
+
.where("id", "in", (eb) => eb
|
|
204
|
+
.selectFrom("files")
|
|
205
|
+
.select("id")
|
|
206
|
+
.where("org_id", "=", orgId)
|
|
207
|
+
.where("source_conversation_id", "=", id)
|
|
208
|
+
.orderBy("id")
|
|
209
|
+
.limit(PURGE_BATCH_SIZE))
|
|
210
|
+
.executeTakeFirst();
|
|
211
|
+
if (files.numUpdatedRows > 0n)
|
|
212
|
+
return true;
|
|
213
|
+
// A request belongs to the shared agent and remains reviewable without its source.
|
|
214
|
+
const requests = await db
|
|
215
|
+
.updateTable("skill_change_requests")
|
|
216
|
+
.set({ requested_in_conversation: null })
|
|
217
|
+
.where("org_id", "=", orgId)
|
|
218
|
+
.where("requested_in_conversation", "=", id)
|
|
219
|
+
.where("id", "in", (eb) => eb
|
|
220
|
+
.selectFrom("skill_change_requests")
|
|
221
|
+
.select("id")
|
|
222
|
+
.where("org_id", "=", orgId)
|
|
223
|
+
.where("requested_in_conversation", "=", id)
|
|
224
|
+
.orderBy("id")
|
|
225
|
+
.limit(PURGE_BATCH_SIZE))
|
|
226
|
+
.executeTakeFirst();
|
|
227
|
+
return requests.numUpdatedRows > 0n;
|
|
228
|
+
}
|
|
229
|
+
async function removeRuns(db, orgId, leaf) {
|
|
230
|
+
const runs = await db
|
|
231
|
+
.selectFrom("runs")
|
|
232
|
+
.select(["id", "created_at"])
|
|
233
|
+
.where("conversation_id", "=", leaf.id)
|
|
234
|
+
.orderBy("id")
|
|
235
|
+
.limit(PURGE_BATCH_SIZE)
|
|
236
|
+
.execute();
|
|
237
|
+
if (runs.length === 0)
|
|
238
|
+
return false;
|
|
239
|
+
const ids = runs.map((run) => run.id);
|
|
240
|
+
// The run can have an arbitrary number of checkpoints after a worker crash.
|
|
241
|
+
const thread = sql `thread_id = ANY(${ids}::text[])`;
|
|
242
|
+
if (await deleteKeyBatch(db, "lg_checkpoint_writes", ["thread_id", "checkpoint_ns", "checkpoint_id", "task_id", "idx"], thread))
|
|
243
|
+
return true;
|
|
244
|
+
if (await deleteKeyBatch(db, "lg_checkpoints", ["thread_id", "checkpoint_ns", "checkpoint_id"], thread))
|
|
245
|
+
return true;
|
|
246
|
+
if (await deleteKeyBatch(db, "trigger_cause_handles", ["id"], sql `org_id = ${orgId} AND run_id = ANY(${ids}::text[])`))
|
|
247
|
+
return true;
|
|
248
|
+
await db
|
|
249
|
+
.deleteFrom("runs")
|
|
250
|
+
.where("conversation_id", "=", leaf.id)
|
|
251
|
+
.where("id", "in", ids)
|
|
252
|
+
.execute();
|
|
253
|
+
if (leaf.kind !== "eval") {
|
|
254
|
+
const range = affectedRange(runs.map((run) => run.created_at));
|
|
255
|
+
if (range)
|
|
256
|
+
await recordRetentionLoss(db, orgId, { runs: range.since, runsThrough: range.through });
|
|
257
|
+
}
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
/** One slice under the worker's progress and root row locks. */
|
|
261
|
+
export async function purgeConversationBatch(db, target, prepared) {
|
|
262
|
+
const { orgId, conversationId } = target;
|
|
263
|
+
const branch = await leafOf(db, target);
|
|
264
|
+
if (!branch)
|
|
265
|
+
return "done";
|
|
266
|
+
if (branch.depth === MAX_TREE_DEPTH)
|
|
267
|
+
return "blocked";
|
|
268
|
+
const leaf = await db
|
|
269
|
+
.selectFrom("conversations")
|
|
270
|
+
.select(["id", "kind"])
|
|
271
|
+
.where("org_id", "=", orgId)
|
|
272
|
+
.where("id", "=", branch.id)
|
|
273
|
+
.forUpdate()
|
|
274
|
+
.executeTakeFirst();
|
|
275
|
+
if (!leaf)
|
|
276
|
+
return "more";
|
|
277
|
+
if (!(await obligationsCleared(db, orgId, leaf.id)))
|
|
278
|
+
return "blocked";
|
|
279
|
+
const events = await eventBatch(db, orgId, leaf.id);
|
|
280
|
+
if (events.length) {
|
|
281
|
+
const ids = usageReportIds(leaf.id, events);
|
|
282
|
+
if (ids.length) {
|
|
283
|
+
if (!prepared ||
|
|
284
|
+
prepared.leaf !== leaf.id ||
|
|
285
|
+
ids.some((id) => !prepared.checked.includes(id))) {
|
|
286
|
+
return "more";
|
|
287
|
+
}
|
|
288
|
+
if (!prepared.clear || (await hasOwedUsageReports(db, orgId, ids)))
|
|
289
|
+
return "blocked";
|
|
290
|
+
}
|
|
291
|
+
await removeEventBatch(db, orgId, leaf, events);
|
|
292
|
+
return "more";
|
|
293
|
+
}
|
|
294
|
+
if (await removeDependentBatch(db, orgId, leaf.id))
|
|
295
|
+
return "more";
|
|
296
|
+
if (await removeRuns(db, orgId, leaf))
|
|
297
|
+
return "more";
|
|
298
|
+
const child = await db
|
|
299
|
+
.selectFrom("conversations")
|
|
300
|
+
.select("id")
|
|
301
|
+
.where("org_id", "=", orgId)
|
|
302
|
+
.where("parent_conversation_id", "=", leaf.id)
|
|
303
|
+
.limit(1)
|
|
304
|
+
.executeTakeFirst();
|
|
305
|
+
if (child)
|
|
306
|
+
return "more";
|
|
307
|
+
if (await deleteKeyBatch(db, "automation_conversations", ["automation_id", "subject_kind", "subject_id"], sql `org_id = ${orgId} AND conversation_id = ${leaf.id}`))
|
|
308
|
+
return "more";
|
|
309
|
+
const runs = await db
|
|
310
|
+
.updateTable("automation_runs")
|
|
311
|
+
.set({ conversation_id: null, run_id: null })
|
|
312
|
+
.where("org_id", "=", orgId)
|
|
313
|
+
.where("id", "in", (eb) => eb
|
|
314
|
+
.selectFrom("automation_runs")
|
|
315
|
+
.select("id")
|
|
316
|
+
.where("org_id", "=", orgId)
|
|
317
|
+
.where("conversation_id", "=", leaf.id)
|
|
318
|
+
.orderBy("id")
|
|
319
|
+
.limit(PURGE_BATCH_SIZE))
|
|
320
|
+
.executeTakeFirst();
|
|
321
|
+
if (runs.numUpdatedRows > 0n)
|
|
322
|
+
return "more";
|
|
323
|
+
const automations = await db
|
|
324
|
+
.updateTable("automations")
|
|
325
|
+
.set({
|
|
326
|
+
conversation_id: null,
|
|
327
|
+
status: sql `CASE WHEN status = 'active' THEN 'paused' ELSE status END`,
|
|
328
|
+
pause_reason: sql `CASE WHEN status = 'active' THEN 'conversation_gone' ELSE pause_reason END`,
|
|
329
|
+
next_run_at: null,
|
|
330
|
+
})
|
|
331
|
+
.where("org_id", "=", orgId)
|
|
332
|
+
.where("id", "in", (eb) => eb
|
|
333
|
+
.selectFrom("automations")
|
|
334
|
+
.select("id")
|
|
335
|
+
.where("org_id", "=", orgId)
|
|
336
|
+
.where("conversation_id", "=", leaf.id)
|
|
337
|
+
.orderBy("id")
|
|
338
|
+
.limit(PURGE_BATCH_SIZE))
|
|
339
|
+
.executeTakeFirst();
|
|
340
|
+
if (automations.numUpdatedRows > 0n)
|
|
341
|
+
return "more";
|
|
342
|
+
if (leaf.id === conversationId) {
|
|
343
|
+
await db
|
|
344
|
+
.deleteFrom("permission_authority_epochs")
|
|
345
|
+
.where("kind", "=", "root")
|
|
346
|
+
.where("id", "=", leaf.id)
|
|
347
|
+
.execute();
|
|
348
|
+
}
|
|
349
|
+
await db
|
|
350
|
+
.deleteFrom("conversations")
|
|
351
|
+
.where("org_id", "=", orgId)
|
|
352
|
+
.where("id", "=", leaf.id)
|
|
353
|
+
.execute();
|
|
354
|
+
return leaf.id === conversationId ? "done" : "more";
|
|
355
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Queue } from "bullmq";
|
|
2
|
+
import type { KernelSchemaDb } from "../db/kernel-schema.js";
|
|
3
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
4
|
+
export declare function hasOwedUsageReports(db: KernelSchemaDb, orgId: string, jobIds: readonly string[]): Promise<boolean>;
|
|
5
|
+
export declare class RetentionReportObligations {
|
|
6
|
+
private readonly db;
|
|
7
|
+
private readonly queue;
|
|
8
|
+
constructor(db: KernelDb, queue: Pick<Queue, "getJobState">);
|
|
9
|
+
clear(orgId: string, jobIds: readonly string[]): Promise<boolean>;
|
|
10
|
+
}
|
|
11
|
+
export declare class RetentionReportObligationsModule {
|
|
12
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { getQueueToken } from "@nestjs/bullmq";
|
|
11
|
+
import { Inject, Injectable, Module } from "@nestjs/common";
|
|
12
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
13
|
+
import { currentStore } from "../infra/database/transaction-host.js";
|
|
14
|
+
import { UsageReportModule } from "../runtime/usage-report.js";
|
|
15
|
+
import { USAGE_REPORT_QUEUE } from "../runtime/usage-report-jobs.js";
|
|
16
|
+
export async function hasOwedUsageReports(db, orgId, jobIds) {
|
|
17
|
+
if (!jobIds.length)
|
|
18
|
+
return false;
|
|
19
|
+
const tracked = await db
|
|
20
|
+
.selectFrom("usage_report_obligations")
|
|
21
|
+
.select("job_id")
|
|
22
|
+
.where("org_id", "=", orgId)
|
|
23
|
+
.where("job_id", "in", jobIds)
|
|
24
|
+
.limit(1)
|
|
25
|
+
.executeTakeFirst();
|
|
26
|
+
if (tracked)
|
|
27
|
+
return true;
|
|
28
|
+
const owed = await db
|
|
29
|
+
.selectFrom("outbox")
|
|
30
|
+
.select("id")
|
|
31
|
+
.where("org_id", "=", orgId)
|
|
32
|
+
.where("queue", "=", USAGE_REPORT_QUEUE)
|
|
33
|
+
.where("job_id", "in", jobIds)
|
|
34
|
+
.limit(1)
|
|
35
|
+
.executeTakeFirst();
|
|
36
|
+
return owed !== undefined;
|
|
37
|
+
}
|
|
38
|
+
let RetentionReportObligations = class RetentionReportObligations {
|
|
39
|
+
db;
|
|
40
|
+
queue;
|
|
41
|
+
constructor(db, queue) {
|
|
42
|
+
this.db = db;
|
|
43
|
+
this.queue = queue;
|
|
44
|
+
}
|
|
45
|
+
async clear(orgId, jobIds) {
|
|
46
|
+
if (currentStore())
|
|
47
|
+
throw new Error("Usage report queue checks must run outside a transaction");
|
|
48
|
+
// The relay inserts the BullMQ job before deleting the outbox row. Checking in this order
|
|
49
|
+
// covers the handoff without keeping a DB transaction open across Redis calls.
|
|
50
|
+
if (await hasOwedUsageReports(this.db.db, orgId, jobIds))
|
|
51
|
+
return false;
|
|
52
|
+
const states = await Promise.all(jobIds.map((id) => this.queue.getJobState(id)));
|
|
53
|
+
return states.every((state) => state === "completed" || state === "unknown");
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
RetentionReportObligations = __decorate([
|
|
57
|
+
Injectable(),
|
|
58
|
+
__param(0, Inject(KernelDb)),
|
|
59
|
+
__param(1, Inject(getQueueToken(USAGE_REPORT_QUEUE)))
|
|
60
|
+
], RetentionReportObligations);
|
|
61
|
+
export { RetentionReportObligations };
|
|
62
|
+
let RetentionReportObligationsModule = class RetentionReportObligationsModule {
|
|
63
|
+
};
|
|
64
|
+
RetentionReportObligationsModule = __decorate([
|
|
65
|
+
Module({
|
|
66
|
+
imports: [UsageReportModule],
|
|
67
|
+
providers: [RetentionReportObligations],
|
|
68
|
+
exports: [RetentionReportObligations],
|
|
69
|
+
})
|
|
70
|
+
], RetentionReportObligationsModule);
|
|
71
|
+
export { RetentionReportObligationsModule };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
2
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
3
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
4
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
5
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
6
|
+
import type { KernelLogger } from "../log.js";
|
|
7
|
+
export declare class RetentionSweep {
|
|
8
|
+
private readonly db;
|
|
9
|
+
readonly txHost: TransactionHost;
|
|
10
|
+
private readonly outbox;
|
|
11
|
+
private readonly config;
|
|
12
|
+
readonly lockService: LockService;
|
|
13
|
+
readonly log: KernelLogger;
|
|
14
|
+
constructor(db: KernelDb, txHost: TransactionHost, outbox: OutboxService, config: KernelConfigService, lockService: LockService, log: KernelLogger);
|
|
15
|
+
sweep(): Promise<void>;
|
|
16
|
+
discover(): Promise<void>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
11
|
+
import { sql } from "kysely";
|
|
12
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
13
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
14
|
+
import { asPlatform } from "../infra/database/org-scope.js";
|
|
15
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
16
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
17
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
18
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
19
|
+
import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
|
|
20
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
21
|
+
import { enqueueRetention } from "./jobs.js";
|
|
22
|
+
let RetentionSweep = class RetentionSweep {
|
|
23
|
+
db;
|
|
24
|
+
txHost;
|
|
25
|
+
outbox;
|
|
26
|
+
config;
|
|
27
|
+
lockService;
|
|
28
|
+
log;
|
|
29
|
+
constructor(db, txHost, outbox, config, lockService, log) {
|
|
30
|
+
this.db = db;
|
|
31
|
+
this.txHost = txHost;
|
|
32
|
+
this.outbox = outbox;
|
|
33
|
+
this.config = config;
|
|
34
|
+
this.lockService = lockService;
|
|
35
|
+
this.log = log;
|
|
36
|
+
}
|
|
37
|
+
async sweep() {
|
|
38
|
+
if (!this.config.get().retention.destructiveEnabled)
|
|
39
|
+
return;
|
|
40
|
+
// org-filter: deployment-wide discovery and recovery across all orgs
|
|
41
|
+
await asPlatform("discover and recover retention work", () => this.discover());
|
|
42
|
+
}
|
|
43
|
+
async discover() {
|
|
44
|
+
if (!this.config.get().retention.destructiveEnabled)
|
|
45
|
+
return;
|
|
46
|
+
const created = await sql `
|
|
47
|
+
INSERT INTO capybara.retention_work (kind,target,org_id)
|
|
48
|
+
SELECT 'org-scan', o.id, o.id FROM (
|
|
49
|
+
SELECT id FROM capybara.orgs o WHERE deleted_at IS NULL AND NOT EXISTS (
|
|
50
|
+
SELECT 1 FROM capybara.retention_work w WHERE w.kind='org-scan' AND w.target=o.id
|
|
51
|
+
) ORDER BY id LIMIT 32
|
|
52
|
+
) o
|
|
53
|
+
UNION ALL SELECT 'platform-audit','platform',NULL
|
|
54
|
+
ON CONFLICT (kind,target) DO NOTHING RETURNING id,org_id,generation`.execute(this.db.db);
|
|
55
|
+
for (const row of created.rows)
|
|
56
|
+
await enqueueRetention(this.outbox, row);
|
|
57
|
+
// An earlier replica may have tombstoned a root without owing purge.
|
|
58
|
+
// Explicit deletion remains actionable even when an age policy cannot be parsed.
|
|
59
|
+
const untracked = await sql `
|
|
60
|
+
INSERT INTO capybara.retention_work (kind,target,org_id)
|
|
61
|
+
SELECT 'purge', c.id, c.org_id FROM capybara.conversations c
|
|
62
|
+
WHERE c.deleted_at IS NOT NULL AND c.parent_conversation_id IS NULL AND NOT EXISTS (
|
|
63
|
+
SELECT 1 FROM capybara.retention_work w WHERE w.kind='purge' AND w.target=c.id
|
|
64
|
+
)
|
|
65
|
+
ORDER BY c.deleted_at,c.id LIMIT 32
|
|
66
|
+
ON CONFLICT (kind,target) DO NOTHING RETURNING id,org_id,generation`.execute(this.db.db);
|
|
67
|
+
for (const row of untracked.rows)
|
|
68
|
+
await enqueueRetention(this.outbox, row);
|
|
69
|
+
// Recovery rotates stale job IDs even when a previous BullMQ delivery exhausted its retries
|
|
70
|
+
const recovered = await sql `
|
|
71
|
+
UPDATE capybara.retention_work w SET generation=w.generation+1,due_at=now()
|
|
72
|
+
FROM (SELECT id FROM capybara.retention_work WHERE state<>'done'
|
|
73
|
+
AND due_at < now()-interval '30 minutes' ORDER BY due_at,id LIMIT 32
|
|
74
|
+
FOR UPDATE SKIP LOCKED) stale
|
|
75
|
+
WHERE stale.id=w.id RETURNING w.id,w.org_id,w.generation`.execute(this.db.db);
|
|
76
|
+
for (const row of recovered.rows)
|
|
77
|
+
await enqueueRetention(this.outbox, row);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
__decorate([
|
|
81
|
+
LockedCron("*/5 * * * *", { name: "retention-sweep" })
|
|
82
|
+
], RetentionSweep.prototype, "sweep", null);
|
|
83
|
+
__decorate([
|
|
84
|
+
Transactional()
|
|
85
|
+
], RetentionSweep.prototype, "discover", null);
|
|
86
|
+
RetentionSweep = __decorate([
|
|
87
|
+
Injectable(),
|
|
88
|
+
__param(0, Inject(KernelDb)),
|
|
89
|
+
__param(1, Inject(TransactionHost)),
|
|
90
|
+
__param(2, Inject(OutboxService)),
|
|
91
|
+
__param(3, Inject(KernelConfigService)),
|
|
92
|
+
__param(4, Inject(LockService)),
|
|
93
|
+
__param(5, Inject(KERNEL_LOGGER))
|
|
94
|
+
], RetentionSweep);
|
|
95
|
+
export { RetentionSweep };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { ConversationsService } from "../conversations/conversations.service.js";
|
|
2
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
3
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
4
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
5
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
6
|
+
import { RetentionReportObligations } from "./report-obligations.js";
|
|
7
|
+
export declare class RetentionWorker {
|
|
8
|
+
private readonly db;
|
|
9
|
+
readonly txHost: TransactionHost;
|
|
10
|
+
private readonly outbox;
|
|
11
|
+
private readonly config;
|
|
12
|
+
private readonly conversations;
|
|
13
|
+
private readonly reports;
|
|
14
|
+
constructor(db: KernelDb, txHost: TransactionHost, outbox: OutboxService, config: KernelConfigService, conversations: ConversationsService, reports: RetentionReportObligations);
|
|
15
|
+
run(workId: string, jobId: string | undefined): Promise<void>;
|
|
16
|
+
private recordFailure;
|
|
17
|
+
private dispatch;
|
|
18
|
+
private row;
|
|
19
|
+
private claim;
|
|
20
|
+
private root;
|
|
21
|
+
private advance;
|
|
22
|
+
private purge;
|
|
23
|
+
private scan;
|
|
24
|
+
private scanBatch;
|
|
25
|
+
private platformAudit;
|
|
26
|
+
private auditBatch;
|
|
27
|
+
}
|
|
28
|
+
export declare class RetentionWorkerModule {
|
|
29
|
+
}
|