@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.
Files changed (204) hide show
  1. package/dist/admin/account-erasures.d.ts +37 -0
  2. package/dist/admin/account-erasures.js +119 -0
  3. package/dist/admin/admin.controller.d.ts +35 -2
  4. package/dist/admin/admin.controller.js +75 -18
  5. package/dist/admin/admin.module.js +10 -0
  6. package/dist/admin/admin.schemas.d.ts +51 -0
  7. package/dist/admin/admin.schemas.js +20 -0
  8. package/dist/admin/erasure-dispositions.d.ts +23 -0
  9. package/dist/admin/erasure-dispositions.js +76 -0
  10. package/dist/admin/health.service.d.ts +6 -0
  11. package/dist/admin/health.service.js +27 -1
  12. package/dist/admin/usage.service.d.ts +5 -0
  13. package/dist/admin/usage.service.js +21 -2
  14. package/dist/agents/agents.service.d.ts +1 -1
  15. package/dist/catalog/plugin-import.d.ts +3 -1
  16. package/dist/catalog/plugin-import.js +19 -15
  17. package/dist/channels/connections.service.d.ts +1 -1
  18. package/dist/client/client-reports.service.js +12 -0
  19. package/dist/config/schema.d.ts +9 -1
  20. package/dist/config/schema.js +51 -1
  21. package/dist/conversations/conversations.service.d.ts +9 -1
  22. package/dist/conversations/conversations.service.js +112 -15
  23. package/dist/conversations/event-log.d.ts +2 -0
  24. package/dist/conversations/event-log.js +77 -0
  25. package/dist/conversations/events.d.ts +11 -0
  26. package/dist/conversations/events.js +13 -1
  27. package/dist/conversations/prompt-suggestions.js +4 -0
  28. package/dist/conversations/titles.js +3 -2
  29. package/dist/ctx/create-ctx.d.ts +3 -2
  30. package/dist/ctx/create-ctx.js +10 -7
  31. package/dist/db/extension-db.d.ts +30 -0
  32. package/dist/db/extension-db.js +91 -0
  33. package/dist/db/extension-schema-transfer.d.ts +6 -0
  34. package/dist/db/extension-schema-transfer.js +141 -0
  35. package/dist/db/kernel-schema.d.ts +73 -12
  36. package/dist/db/migrator.d.ts +6 -0
  37. package/dist/db/migrator.js +39 -4
  38. package/dist/db/pool.d.ts +4 -0
  39. package/dist/db/pool.js +36 -1
  40. package/dist/devices/devices.service.d.ts +13 -1
  41. package/dist/devices/devices.service.js +122 -9
  42. package/dist/erasure/account-batches.d.ts +9 -0
  43. package/dist/erasure/account-batches.js +567 -0
  44. package/dist/erasure/account-files.d.ts +34 -0
  45. package/dist/erasure/account-files.js +217 -0
  46. package/dist/erasure/account-residual.d.ts +15 -0
  47. package/dist/erasure/account-residual.js +149 -0
  48. package/dist/erasure/account-worker.d.ts +32 -0
  49. package/dist/erasure/account-worker.js +392 -0
  50. package/dist/erasure/device-cleanup.d.ts +23 -0
  51. package/dist/erasure/device-cleanup.js +221 -0
  52. package/dist/erasure/erasure.module.d.ts +2 -0
  53. package/dist/{conversations/event-org-backfill.module.js → erasure/erasure.module.js} +6 -10
  54. package/dist/erasure/external-evidence.d.ts +4 -0
  55. package/dist/erasure/external-evidence.js +28 -0
  56. package/dist/erasure/jobs.d.ts +5 -0
  57. package/dist/erasure/jobs.js +20 -0
  58. package/dist/erasure/org-batches.d.ts +11 -0
  59. package/dist/erasure/org-batches.js +159 -0
  60. package/dist/erasure/org-catalog.d.ts +2 -0
  61. package/dist/erasure/org-catalog.js +34 -0
  62. package/dist/erasure/org-rules.d.ts +14 -0
  63. package/dist/erasure/org-rules.js +227 -0
  64. package/dist/erasure/org-worker.d.ts +38 -0
  65. package/dist/erasure/org-worker.js +501 -0
  66. package/dist/erasure/requests.d.ts +61 -0
  67. package/dist/erasure/requests.js +180 -0
  68. package/dist/erasure/sweep.job.d.ts +19 -0
  69. package/dist/erasure/sweep.job.js +130 -0
  70. package/dist/erasure/worker.d.ts +17 -0
  71. package/dist/erasure/worker.js +110 -0
  72. package/dist/errors.d.ts +4 -0
  73. package/dist/errors.js +4 -0
  74. package/dist/evals/judge.d.ts +5 -0
  75. package/dist/evals/judge.js +16 -1
  76. package/dist/evals/run-replay.js +12 -1
  77. package/dist/evals/step-replay.d.ts +5 -3
  78. package/dist/evals/step-replay.js +9 -5
  79. package/dist/evals/worker.d.ts +2 -0
  80. package/dist/evals/worker.js +60 -16
  81. package/dist/extensions/admin-ops.d.ts +3 -1
  82. package/dist/extensions/admin-ops.js +11 -7
  83. package/dist/extensions/extensions.module.js +3 -0
  84. package/dist/extensions/host.d.ts +4 -1
  85. package/dist/extensions/host.js +29 -6
  86. package/dist/extensions/instance.d.ts +3 -0
  87. package/dist/extensions/instance.js +3 -1
  88. package/dist/extensions/migrate-lock.d.ts +4 -1
  89. package/dist/extensions/migrate-lock.js +19 -2
  90. package/dist/files/blob-objects.d.ts +7 -3
  91. package/dist/files/blob-objects.js +39 -22
  92. package/dist/files/blob-sweep.job.d.ts +11 -0
  93. package/dist/files/blob-sweep.job.js +67 -6
  94. package/dist/http/api.module.js +5 -1
  95. package/dist/identity/accounts.js +3 -0
  96. package/dist/identity/api-tokens.js +5 -0
  97. package/dist/identity/auth.guard.d.ts +1 -0
  98. package/dist/identity/auth.guard.js +1 -0
  99. package/dist/identity/erasure-admission.d.ts +3 -0
  100. package/dist/identity/erasure-admission.js +14 -0
  101. package/dist/identity/external.js +5 -0
  102. package/dist/identity/sessions.js +5 -0
  103. package/dist/identity/settings.d.ts +86 -1
  104. package/dist/identity/settings.js +38 -4
  105. package/dist/infra/config/kernel-config.service.js +1 -0
  106. package/dist/infra/metrics/kernel-metrics.d.ts +18 -0
  107. package/dist/infra/metrics/kernel-metrics.js +54 -0
  108. package/dist/infra/metrics/operational-metrics.d.ts +31 -0
  109. package/dist/infra/metrics/operational-metrics.js +188 -0
  110. package/dist/infra/outbox/registry.d.ts +23 -14
  111. package/dist/infra/outbox/registry.js +12 -15
  112. package/dist/infra/throttler/credential-throttler.js +8 -1
  113. package/dist/infra/throttler/named-throttlers.d.ts +6 -0
  114. package/dist/infra/throttler/named-throttlers.js +6 -0
  115. package/dist/infra/throttler/principal-throttler.guard.d.ts +10 -0
  116. package/dist/infra/throttler/principal-throttler.guard.js +50 -0
  117. package/dist/infra/throttler/redis-throttler-storage.d.ts +1 -0
  118. package/dist/infra/throttler/redis-throttler-storage.js +27 -5
  119. package/dist/infra/throttler/throttler.guard.d.ts +2 -3
  120. package/dist/infra/throttler/throttler.guard.js +2 -3
  121. package/dist/infra/throttler/throttler.module.js +3 -2
  122. package/dist/kernel.js +4 -0
  123. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  124. package/dist/lifecycle/kernel-lifecycle.js +26 -21
  125. package/dist/models/budget-admission.d.ts +31 -0
  126. package/dist/models/budget-admission.js +149 -0
  127. package/dist/models/budget-counters.d.ts +28 -0
  128. package/dist/models/budget-counters.js +117 -0
  129. package/dist/models/budget-policy.d.ts +88 -0
  130. package/dist/models/budget-policy.js +78 -0
  131. package/dist/models/embeddings.js +13 -2
  132. package/dist/models/images.js +12 -2
  133. package/dist/models/purposes.d.ts +5 -2
  134. package/dist/models/purposes.js +9 -5
  135. package/dist/orgs/invitations.service.d.ts +1 -1
  136. package/dist/orgs/members.service.d.ts +28 -1
  137. package/dist/orgs/members.service.js +74 -11
  138. package/dist/orgs/offboarding.js +4 -6
  139. package/dist/orgs/org-owner.d.ts +2 -0
  140. package/dist/orgs/org-owner.js +21 -6
  141. package/dist/orgs/orgs.controller.d.ts +22 -0
  142. package/dist/orgs/orgs.controller.js +24 -0
  143. package/dist/orgs/orgs.module.js +4 -0
  144. package/dist/orgs/orgs.schemas.js +7 -0
  145. package/dist/orgs/orgs.service.d.ts +5 -1
  146. package/dist/orgs/orgs.service.js +28 -3
  147. package/dist/orgs/settings.controller.js +6 -1
  148. package/dist/orgs/settings.service.d.ts +58 -1
  149. package/dist/orgs/settings.service.js +74 -9
  150. package/dist/platform/exclusions.js +20 -1
  151. package/dist/platform/ops/accounts.ops.js +58 -1
  152. package/dist/platform/ops/admin.ops.js +13 -5
  153. package/dist/platform/ops/org-settings.ops.js +11 -4
  154. package/dist/platform/ops/orgs.ops.js +28 -0
  155. package/dist/platform/ops/retention.d.ts +16 -0
  156. package/dist/platform/ops/retention.js +21 -0
  157. package/dist/retention/jobs.d.ts +21 -0
  158. package/dist/retention/jobs.js +48 -0
  159. package/dist/retention/policy.d.ts +70 -0
  160. package/dist/retention/policy.js +103 -0
  161. package/dist/retention/purge-batch.d.ts +17 -0
  162. package/dist/retention/purge-batch.js +355 -0
  163. package/dist/retention/report-obligations.d.ts +12 -0
  164. package/dist/retention/report-obligations.js +71 -0
  165. package/dist/retention/sweep.job.d.ts +17 -0
  166. package/dist/retention/sweep.job.js +95 -0
  167. package/dist/retention/worker.d.ts +29 -0
  168. package/dist/retention/worker.js +306 -0
  169. package/dist/roles/worker.module.js +12 -8
  170. package/dist/runtime/maintenance.d.ts +5 -3
  171. package/dist/runtime/maintenance.js +19 -12
  172. package/dist/runtime/model-call.d.ts +3 -1
  173. package/dist/runtime/model-call.js +25 -3
  174. package/dist/runtime/providers.d.ts +7 -2
  175. package/dist/runtime/providers.js +76 -10
  176. package/dist/runtime/quota.d.ts +12 -12
  177. package/dist/runtime/quota.js +42 -37
  178. package/dist/runtime/run-finish.js +2 -0
  179. package/dist/runtime/run-principal.d.ts +9 -0
  180. package/dist/runtime/run-principal.js +18 -0
  181. package/dist/runtime/run-worker.js +48 -10
  182. package/dist/runtime/usage-report-jobs.d.ts +4 -1
  183. package/dist/runtime/usage-report-jobs.js +36 -13
  184. package/dist/runtime/usage-report.d.ts +5 -3
  185. package/dist/runtime/usage-report.js +37 -19
  186. package/dist/sandbox/review/classifier.d.ts +2 -2
  187. package/dist/sandbox/review/classifier.js +6 -2
  188. package/dist/sandbox/sandbox.service.js +18 -7
  189. package/dist/storage/purge.js +5 -1
  190. package/dist/storage/storage.service.d.ts +17 -1
  191. package/dist/storage/storage.service.js +75 -4
  192. package/dist/tools/builtins/vision/read-image.js +3 -0
  193. package/dist/tools/builtins/web/extract.js +3 -0
  194. package/dist/tools/pipeline.js +5 -1
  195. package/package.json +3 -1
  196. package/src/migrations/0216_model_budget_counters.sql +24 -0
  197. package/src/migrations/0217_retention.sql +44 -0
  198. package/src/migrations/0218_data_erasure.sql +41 -0
  199. package/src/migrations/0219_event_org_constraint_check.sql +29 -0
  200. package/src/migrations/0220_require_event_org.sql +18 -0
  201. package/src/migrations/0221_drop_connector_declaration_policy.sql +2 -0
  202. package/dist/conversations/event-org-backfill.d.ts +0 -111
  203. package/dist/conversations/event-org-backfill.js +0 -264
  204. package/dist/conversations/event-org-backfill.module.d.ts +0 -3
@@ -0,0 +1,41 @@
1
+ ALTER TABLE accounts ADD COLUMN IF NOT EXISTS erasure_requested boolean NOT NULL DEFAULT false;
2
+
3
+ -- Operation receipts survive the removal of their targets. A completed receipt has no target.
4
+ CREATE TABLE IF NOT EXISTS data_erasure_requests (
5
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
6
+ kind text NOT NULL CHECK (kind IN ('org', 'account')),
7
+ org_id text,
8
+ target_id text,
9
+ generation integer NOT NULL DEFAULT 0 CHECK (generation >= 0),
10
+ stage text NOT NULL DEFAULT 'pending' CHECK (stage IN ('pending', 'blocked', 'roots', 'objects', 'rows', 'prefix', 'late', 'account-orgs', 'account-external', 'account-final', 'done')),
11
+ blocked_reason text,
12
+ scope_boundaries text[] NOT NULL DEFAULT ARRAY[]::text[],
13
+ progress jsonb CHECK (jsonb_typeof(progress) = 'object'),
14
+ due_at timestamptz NOT NULL DEFAULT now(),
15
+ completed_at timestamptz,
16
+ UNIQUE (kind, target_id),
17
+ CHECK (scope_boundaries <@ ARRAY['third-party-conversation-content']::text[]),
18
+ CHECK (kind = 'account' OR cardinality(scope_boundaries) = 0),
19
+ CHECK ((stage = 'done') = (target_id IS NULL)),
20
+ CHECK ((stage = 'done') = (completed_at IS NOT NULL)),
21
+ CHECK (stage <> 'done' OR (blocked_reason IS NULL AND progress IS NULL)),
22
+ CHECK ((kind = 'account' AND org_id IS NULL) OR
23
+ (kind = 'org' AND org_id IS NOT DISTINCT FROM target_id))
24
+ );
25
+ DROP POLICY IF EXISTS org_scope ON data_erasure_requests;
26
+ CREATE POLICY org_scope ON data_erasure_requests USING (rls_admits(org_id)) WITH CHECK (rls_admits(org_id));
27
+ CREATE INDEX IF NOT EXISTS data_erasure_due ON data_erasure_requests (due_at, id) WHERE stage <> 'done';
28
+ CREATE INDEX IF NOT EXISTS data_erasure_completed ON data_erasure_requests (completed_at, id) WHERE stage = 'done';
29
+
30
+ -- Preserve shared records when an erased account was their historical author.
31
+ ALTER TABLE agent_versions ALTER COLUMN created_by DROP NOT NULL;
32
+ ALTER TABLE api_tokens ALTER COLUMN created_by DROP NOT NULL;
33
+ ALTER TABLE channel_connections ALTER COLUMN created_by DROP NOT NULL;
34
+ ALTER TABLE invitations ALTER COLUMN created_by DROP NOT NULL;
35
+ ALTER TABLE eval_runs ALTER COLUMN created_by DROP NOT NULL;
36
+ ALTER TABLE eval_sets ALTER COLUMN created_by DROP NOT NULL;
37
+ ALTER TABLE eval_cases ALTER COLUMN added_by DROP NOT NULL;
38
+ ALTER TABLE device_projects ALTER COLUMN created_by DROP NOT NULL;
39
+
40
+ -- Written only after the bound provider acknowledged both instance and file destruction.
41
+ ALTER TABLE devices ADD COLUMN IF NOT EXISTS files_destroyed_at timestamptz;
@@ -0,0 +1,29 @@
1
+ -- Run after the 0215 writers have fully rolled out and the event backfill has finished.
2
+ -- capybara:allow-destructive report a pending backfill and add the temporary check once; no data is changed
3
+ DO $$
4
+ BEGIN
5
+ IF EXISTS (SELECT 1 FROM conversation_events WHERE org_id IS NULL) THEN
6
+ RAISE EXCEPTION 'conversation_events still contains NULL org_id values. Wait for EventOrgBackfillJob to finish on the previous release before rerunning the migration.';
7
+ END IF;
8
+ END
9
+ $$;
10
+
11
+ -- Validate under SHARE UPDATE EXCLUSIVE before adding the check takes ACCESS EXCLUSIVE.
12
+ ALTER TABLE conversation_events VALIDATE CONSTRAINT conversation_events_conversation_org_fkey;
13
+
14
+ -- capybara:allow-destructive add the temporary check idempotently after validating the foreign key
15
+ DO $$
16
+ BEGIN
17
+ IF NOT EXISTS (
18
+ SELECT 1 FROM pg_attribute
19
+ WHERE attrelid = 'conversation_events'::regclass AND attname = 'org_id' AND attnotnull
20
+ ) AND NOT EXISTS (
21
+ SELECT 1 FROM pg_constraint
22
+ WHERE conrelid = 'conversation_events'::regclass
23
+ AND conname = 'conversation_events_org_id_present'
24
+ ) THEN
25
+ ALTER TABLE conversation_events
26
+ ADD CONSTRAINT conversation_events_org_id_present CHECK (org_id IS NOT NULL) NOT VALID;
27
+ END IF;
28
+ END
29
+ $$;
@@ -0,0 +1,18 @@
1
+ -- Migration 0219 committed the temporary CHECK. Validate it under SHARE UPDATE EXCLUSIVE
2
+ -- so the scan permits ordinary reads and writes.
3
+ -- capybara:allow-destructive skip check validation on reapplication after the temporary check was removed
4
+ DO $$
5
+ BEGIN
6
+ IF NOT EXISTS (
7
+ SELECT 1 FROM pg_attribute
8
+ WHERE attrelid = 'conversation_events'::regclass AND attname = 'org_id' AND attnotnull
9
+ ) THEN
10
+ ALTER TABLE conversation_events VALIDATE CONSTRAINT conversation_events_org_id_present;
11
+ END IF;
12
+ END
13
+ $$;
14
+
15
+ -- The validated CHECK proves there are no NULLs, so SET NOT NULL takes ACCESS EXCLUSIVE
16
+ -- without scanning the table. Drop the check in a separate statement to preserve that proof.
17
+ ALTER TABLE conversation_events ALTER COLUMN org_id SET NOT NULL;
18
+ ALTER TABLE conversation_events DROP CONSTRAINT IF EXISTS conversation_events_org_id_present;
@@ -0,0 +1,2 @@
1
+ -- capybara:allow-destructive migration 0213 moved connector defaults into default_policy; replicas that read declaration_policy have drained (#1246)
2
+ ALTER TABLE connector_tools DROP COLUMN IF EXISTS declaration_policy;
@@ -1,111 +0,0 @@
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
- /** The maintenance job name for one batched backfill step (no `:`). */
8
- export declare const EVENT_ORG_BACKFILL_JOB = "conversation-events-org-backfill";
9
- /** The periodic kickoff's name (scheduler key and lock; no `:`). */
10
- export declare const EVENT_ORG_BACKFILL_KICKOFF_JOB = "conversation-events-org-backfill-kickoff";
11
- /** How often the worker kickoff checks for remaining NULL `org_id` rows during rolling deploys. */
12
- export declare const EVENT_ORG_BACKFILL_KICKOFF_PERIOD_MS: number;
13
- /** Rows committed per short backfill transaction. */
14
- export declare const EVENT_ORG_BACKFILL_BATCH = 5000;
15
- /** Keyset cursor in primary-key `(conversation_id, seq)` order. */
16
- export interface EventOrgBackfillCursor {
17
- conversationId: string;
18
- /** `bigint` serialized as decimal string to stay lossless in JSON job payloads. */
19
- seq: string;
20
- }
21
- /** Payload of one {@link EVENT_ORG_BACKFILL_JOB} batch. */
22
- export interface EventOrgBackfillData {
23
- /** Exclusive keyset cursor; `null` starts from the beginning of `(conversation_id, seq)`. */
24
- after: EventOrgBackfillCursor | null;
25
- /** Optional batch size override (clamped to `1..EVENT_ORG_BACKFILL_BATCH`); tests use small values. */
26
- batchSize?: number;
27
- }
28
- /** Counts produced by the post-backfill parent and ownership integrity check. */
29
- export interface EventOrgIntegrity {
30
- /** Events whose `conversation_id` has no matching row in `conversations`. */
31
- missingParents: number;
32
- /** Events whose non-null `org_id` disagrees with their parent conversation's `org_id`. */
33
- mismatchedOrgs: number;
34
- /** Events whose `org_id` is still `NULL`. */
35
- remainingNulls: number;
36
- }
37
- /** Outcome of one committed backfill batch. */
38
- export interface EventOrgBackfillBatchResult {
39
- /** Rows whose `org_id` was filled in this transaction. */
40
- updated: number;
41
- /** Last `(conversation_id, seq)` key locked in this batch, or `null` if none matched. */
42
- last: EventOrgBackfillCursor | null;
43
- /** Cursor of the next batch owed via the outbox, or `null` when this pass reached the end. */
44
- next: EventOrgBackfillCursor | null;
45
- /** True when the pass reached the end and verified zero remaining `NULL` rows. */
46
- done: boolean;
47
- /** Populated when the pass finished with no remaining `NULL` rows. */
48
- integrity?: EventOrgIntegrity;
49
- }
50
- /**
51
- * Deterministic BullMQ / outbox job id for a backfill batch cursor (no `:`).
52
- * The first batch uses a fixed id so repeated kickoffs deduplicate cleanly; subsequent batches
53
- * hash the `(conversationId, seq)` key so arbitrary conversation ids never introduce `:`.
54
- */
55
- export declare function eventOrgBackfillJobId(after: EventOrgBackfillCursor | null): string;
56
- /**
57
- * Worker-only batched backfill of `conversation_events.org_id` from `conversations` (issue #1175):
58
- *
59
- * - Migration 0215 adds the nullable `org_id` column and `NOT VALID` composite FK with short locks
60
- * only; this job fills existing and rolling-window NULL rows outside migration transactions.
61
- * - Each invocation commits one short `@Transactional()` batch of up to
62
- * {@link EVENT_ORG_BACKFILL_BATCH} (5,000) rows ordered by `(conversation_id, seq)` using
63
- * `FOR UPDATE OF e SKIP LOCKED`, so concurrent appends and two concurrent workers never block or
64
- * deadlock on each other.
65
- * - When a full batch is processed, the next resumable cursor job is owed atomically in the same
66
- * transaction through `OutboxService.add` under a deterministic job id without `:`.
67
- * - When no `NULL` rows remain, the job verifies that zero events lack a parent conversation and
68
- * zero events carry a mismatched `org_id`, then stops.
69
- */
70
- export declare class EventOrgBackfillJob {
71
- private readonly db;
72
- readonly txHost: TransactionHost;
73
- private readonly outbox;
74
- private readonly log;
75
- constructor(db: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "info" | "warn">);
76
- /** Whether any `conversation_events` row still has `org_id IS NULL`. */
77
- anyNullOrg(): Promise<boolean>;
78
- /**
79
- * Deployment-wide ownership check: counts orphan events (no parent in `conversations`),
80
- * mismatched non-null `org_id` rows, and remaining `NULL` rows.
81
- */
82
- verifyIntegrity(): Promise<EventOrgIntegrity>;
83
- /** Owes the first backfill batch via the transactional outbox (deduplicated by fixed job id). */
84
- oweFirst(opts?: {
85
- batchSize?: number;
86
- }): Promise<boolean>;
87
- /**
88
- * Executes one committed batch starting strictly after `data.after`, owes the next batch if the
89
- * batch was full, and verifies integrity once no `NULL` rows remain.
90
- */
91
- runBatch(data?: EventOrgBackfillData): Promise<EventOrgBackfillBatchResult>;
92
- private commitBatch;
93
- }
94
- /**
95
- * Periodic worker-only kickoff for {@link EventOrgBackfillJob} (`@LockedInterval`, once per tick
96
- * across replicas and once on worker start; provided only under `WorkerModule`). While any
97
- * `conversation_events` row has `org_id IS NULL`, it owes the first batch under its deterministic
98
- * job id; once zero `NULL` rows remain, it is a no-op.
99
- */
100
- export declare class EventOrgBackfillKickoffJob {
101
- private readonly backfill;
102
- readonly config: KernelConfigService;
103
- readonly lockService: LockService;
104
- readonly log: KernelLogger;
105
- constructor(backfill: Pick<EventOrgBackfillJob, "anyNullOrg" | "oweFirst">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
106
- tick(): Promise<void>;
107
- /** One kickoff check without the tick lock (the interval body; tests call it directly). */
108
- runOnce(opts?: {
109
- batchSize?: number;
110
- }): Promise<boolean>;
111
- }
@@ -1,264 +0,0 @@
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 { createHash } from "node:crypto";
11
- import { Inject, Injectable } from "@nestjs/common";
12
- import { sql } from "kysely";
13
- import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
- import { KernelDb } from "../infra/database/kernel-db.js";
15
- import { asPlatform } from "../infra/database/org-scope.js";
16
- import { TransactionHost } from "../infra/database/transaction-host.js";
17
- import { Transactional } from "../infra/database/transactional.decorator.js";
18
- import { LockService } from "../infra/lock/lock.service.js";
19
- import { OutboxService } from "../infra/outbox/outbox.service.js";
20
- import { LockedInterval } from "../infra/schedule/locked-interval.js";
21
- import { KERNEL_LOGGER } from "../infra/tokens.js";
22
- import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
23
- /** The maintenance job name for one batched backfill step (no `:`). */
24
- export const EVENT_ORG_BACKFILL_JOB = "conversation-events-org-backfill";
25
- /** The periodic kickoff's name (scheduler key and lock; no `:`). */
26
- export const EVENT_ORG_BACKFILL_KICKOFF_JOB = "conversation-events-org-backfill-kickoff";
27
- /** How often the worker kickoff checks for remaining NULL `org_id` rows during rolling deploys. */
28
- export const EVENT_ORG_BACKFILL_KICKOFF_PERIOD_MS = 15 * 60_000;
29
- /** Rows committed per short backfill transaction. */
30
- export const EVENT_ORG_BACKFILL_BATCH = 5_000;
31
- /**
32
- * Deterministic BullMQ / outbox job id for a backfill batch cursor (no `:`).
33
- * The first batch uses a fixed id so repeated kickoffs deduplicate cleanly; subsequent batches
34
- * hash the `(conversationId, seq)` key so arbitrary conversation ids never introduce `:`.
35
- */
36
- export function eventOrgBackfillJobId(after) {
37
- if (after === null)
38
- return `${EVENT_ORG_BACKFILL_JOB}-first`;
39
- const digest = createHash("sha256")
40
- .update(`${after.conversationId}\0${after.seq}`)
41
- .digest("hex")
42
- .slice(0, 16);
43
- return `${EVENT_ORG_BACKFILL_JOB}-${digest}`;
44
- }
45
- /**
46
- * Worker-only batched backfill of `conversation_events.org_id` from `conversations` (issue #1175):
47
- *
48
- * - Migration 0215 adds the nullable `org_id` column and `NOT VALID` composite FK with short locks
49
- * only; this job fills existing and rolling-window NULL rows outside migration transactions.
50
- * - Each invocation commits one short `@Transactional()` batch of up to
51
- * {@link EVENT_ORG_BACKFILL_BATCH} (5,000) rows ordered by `(conversation_id, seq)` using
52
- * `FOR UPDATE OF e SKIP LOCKED`, so concurrent appends and two concurrent workers never block or
53
- * deadlock on each other.
54
- * - When a full batch is processed, the next resumable cursor job is owed atomically in the same
55
- * transaction through `OutboxService.add` under a deterministic job id without `:`.
56
- * - When no `NULL` rows remain, the job verifies that zero events lack a parent conversation and
57
- * zero events carry a mismatched `org_id`, then stops.
58
- */
59
- let EventOrgBackfillJob = class EventOrgBackfillJob {
60
- db;
61
- txHost;
62
- outbox;
63
- log;
64
- constructor(db, txHost, outbox, log) {
65
- this.db = db;
66
- this.txHost = txHost;
67
- this.outbox = outbox;
68
- this.log = log;
69
- }
70
- /** Whether any `conversation_events` row still has `org_id IS NULL`. */
71
- anyNullOrg() {
72
- // org-filter: deployment-wide existence check for unbackfilled conversation_events rows
73
- return asPlatform("conversation_events org_id backfill: check for remaining NULL rows", async () => {
74
- const row = await this.db
75
- .selectFrom("conversation_events")
76
- .select("conversation_id")
77
- .where("org_id", "is", null)
78
- .limit(1)
79
- .executeTakeFirst();
80
- return row !== undefined;
81
- });
82
- }
83
- /**
84
- * Deployment-wide ownership check: counts orphan events (no parent in `conversations`),
85
- * mismatched non-null `org_id` rows, and remaining `NULL` rows.
86
- */
87
- verifyIntegrity() {
88
- // org-filter: deployment-wide integrity check across all conversation_events and conversations
89
- return asPlatform("conversation_events org_id backfill: verify parent and org ownership integrity", async () => {
90
- const res = await sql `
91
- SELECT
92
- count(*) FILTER (WHERE c.id IS NULL)::int AS missing_parents,
93
- count(*) FILTER (
94
- WHERE c.id IS NOT NULL AND e.org_id IS NOT NULL AND e.org_id <> c.org_id
95
- )::int AS mismatched_orgs,
96
- count(*) FILTER (WHERE e.org_id IS NULL)::int AS remaining_nulls
97
- FROM capybara.conversation_events e
98
- LEFT JOIN capybara.conversations c ON c.id = e.conversation_id
99
- `.execute(this.db.db);
100
- const row = res.rows[0];
101
- return {
102
- missingParents: row?.missing_parents ?? 0,
103
- mismatchedOrgs: row?.mismatched_orgs ?? 0,
104
- remainingNulls: row?.remaining_nulls ?? 0,
105
- };
106
- });
107
- }
108
- /** Owes the first backfill batch via the transactional outbox (deduplicated by fixed job id). */
109
- async oweFirst(opts = {}) {
110
- const data = opts.batchSize === undefined ? { after: null } : { after: null, batchSize: opts.batchSize };
111
- return this.outbox.add({
112
- queue: MAINTENANCE_QUEUE_NAME,
113
- name: EVENT_ORG_BACKFILL_JOB,
114
- jobId: eventOrgBackfillJobId(null),
115
- data,
116
- });
117
- }
118
- /**
119
- * Executes one committed batch starting strictly after `data.after`, owes the next batch if the
120
- * batch was full, and verifies integrity once no `NULL` rows remain.
121
- */
122
- async runBatch(data = { after: null }) {
123
- const rawSize = data.batchSize ?? EVENT_ORG_BACKFILL_BATCH;
124
- const batchSize = Math.max(1, Math.min(EVENT_ORG_BACKFILL_BATCH, Math.floor(rawSize)));
125
- // org-filter: deployment-wide batched backfill of conversation_events.org_id from conversations
126
- const batch = await asPlatform("conversation_events org_id backfill batch", () => this.commitBatch(data.after ?? null, batchSize, data.batchSize));
127
- if (batch.next !== null) {
128
- return { ...batch, done: false };
129
- }
130
- if (await this.anyNullOrg()) {
131
- // Either a concurrent worker still holds uncommitted NULL rows or an old replica inserted a
132
- // NULL row behind our cursor; the next kickoff or sibling worker finishes it.
133
- return { ...batch, done: false };
134
- }
135
- const integrity = await this.verifyIntegrity();
136
- if (integrity.missingParents > 0 || integrity.mismatchedOrgs > 0) {
137
- throw new Error(`conversation_events org_id integrity check failed: missingParents=${integrity.missingParents}, mismatchedOrgs=${integrity.mismatchedOrgs}`);
138
- }
139
- if (batch.updated > 0) {
140
- this.log.info("conversation_events org_id backfill pass finished", { ...integrity });
141
- }
142
- return {
143
- ...batch,
144
- done: integrity.remainingNulls === 0,
145
- integrity,
146
- };
147
- }
148
- async commitBatch(after, batchSize, explicitBatchSize) {
149
- // Split the cursor branch so Postgres uses a pure index range scan on conversation_events_pkey
150
- // when resuming after a cursor instead of falling back to an OR scan from the start.
151
- const cursorClause = after === null
152
- ? sql ``
153
- : sql `AND (e.conversation_id, e.seq) > (${after.conversationId}, ${after.seq}::bigint)`;
154
- const res = await sql `
155
- WITH batch AS (
156
- SELECT e.conversation_id, e.seq, c.id AS parent_id, c.org_id
157
- FROM capybara.conversation_events e
158
- LEFT JOIN capybara.conversations c ON c.id = e.conversation_id
159
- WHERE e.org_id IS NULL
160
- ${cursorClause}
161
- ORDER BY e.conversation_id, e.seq
162
- LIMIT ${batchSize}
163
- FOR UPDATE OF e SKIP LOCKED
164
- ),
165
- updated AS (
166
- UPDATE capybara.conversation_events e
167
- SET org_id = batch.org_id
168
- FROM batch
169
- WHERE batch.parent_id IS NOT NULL
170
- AND e.conversation_id = batch.conversation_id
171
- AND e.seq = batch.seq
172
- AND e.org_id IS NULL
173
- RETURNING e.conversation_id, e.seq
174
- )
175
- SELECT
176
- (SELECT count(*)::int FROM batch) AS fetched_count,
177
- (SELECT count(*)::int FROM batch WHERE parent_id IS NULL) AS missing_parents,
178
- (SELECT count(*)::int FROM updated) AS updated_count,
179
- (SELECT conversation_id FROM batch ORDER BY conversation_id DESC, seq DESC LIMIT 1) AS last_conv,
180
- (SELECT seq::text FROM batch ORDER BY conversation_id DESC, seq DESC LIMIT 1) AS last_seq
181
- `.execute(this.db.db);
182
- const row = res.rows[0];
183
- const fetched = row?.fetched_count ?? 0;
184
- const missingParents = row?.missing_parents ?? 0;
185
- if (missingParents > 0) {
186
- throw new Error(`conversation_events org_id backfill found ${missingParents} event(s) without a parent conversation`);
187
- }
188
- const updated = row?.updated_count ?? 0;
189
- const last = row?.last_conv !== null &&
190
- row?.last_conv !== undefined &&
191
- row?.last_seq !== null &&
192
- row?.last_seq !== undefined
193
- ? { conversationId: row.last_conv, seq: row.last_seq }
194
- : null;
195
- const next = fetched >= batchSize && last !== null ? last : null;
196
- if (next !== null) {
197
- const nextData = explicitBatchSize === undefined
198
- ? { after: next }
199
- : { after: next, batchSize: explicitBatchSize };
200
- await this.outbox.add({
201
- queue: MAINTENANCE_QUEUE_NAME,
202
- name: EVENT_ORG_BACKFILL_JOB,
203
- jobId: eventOrgBackfillJobId(next),
204
- data: nextData,
205
- });
206
- }
207
- return { updated, last, next };
208
- }
209
- };
210
- __decorate([
211
- Transactional()
212
- ], EventOrgBackfillJob.prototype, "oweFirst", null);
213
- __decorate([
214
- Transactional()
215
- ], EventOrgBackfillJob.prototype, "commitBatch", null);
216
- EventOrgBackfillJob = __decorate([
217
- Injectable(),
218
- __param(0, Inject(KernelDb)),
219
- __param(1, Inject(TransactionHost)),
220
- __param(2, Inject(OutboxService)),
221
- __param(3, Inject(KERNEL_LOGGER))
222
- ], EventOrgBackfillJob);
223
- export { EventOrgBackfillJob };
224
- /**
225
- * Periodic worker-only kickoff for {@link EventOrgBackfillJob} (`@LockedInterval`, once per tick
226
- * across replicas and once on worker start; provided only under `WorkerModule`). While any
227
- * `conversation_events` row has `org_id IS NULL`, it owes the first batch under its deterministic
228
- * job id; once zero `NULL` rows remain, it is a no-op.
229
- */
230
- let EventOrgBackfillKickoffJob = class EventOrgBackfillKickoffJob {
231
- backfill;
232
- config;
233
- lockService;
234
- log;
235
- constructor(backfill, config, lockService, log) {
236
- this.backfill = backfill;
237
- this.config = config;
238
- this.lockService = lockService;
239
- this.log = log;
240
- }
241
- async tick() {
242
- if (await this.runOnce())
243
- this.log.info("conversation_events org_id backfill owed");
244
- }
245
- /** One kickoff check without the tick lock (the interval body; tests call it directly). */
246
- async runOnce(opts) {
247
- if (!(await this.backfill.anyNullOrg()))
248
- return false;
249
- return this.backfill.oweFirst(opts);
250
- }
251
- };
252
- __decorate([
253
- LockedInterval(EVENT_ORG_BACKFILL_KICKOFF_JOB, () => EVENT_ORG_BACKFILL_KICKOFF_PERIOD_MS, {
254
- runOnStart: true,
255
- })
256
- ], EventOrgBackfillKickoffJob.prototype, "tick", null);
257
- EventOrgBackfillKickoffJob = __decorate([
258
- Injectable(),
259
- __param(0, Inject(EventOrgBackfillJob)),
260
- __param(1, Inject(KernelConfigService)),
261
- __param(2, Inject(LockService)),
262
- __param(3, Inject(KERNEL_LOGGER))
263
- ], EventOrgBackfillKickoffJob);
264
- export { EventOrgBackfillKickoffJob };
@@ -1,3 +0,0 @@
1
- /** Batched `conversation_events.org_id` backfill ({@link EventOrgBackfillJob}), worker-only. */
2
- export declare class EventOrgBackfillModule {
3
- }