@capybara-hq/kernel 0.1.0-rc.131 → 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/catalog/plugin-import.d.ts +3 -1
- package/dist/catalog/plugin-import.js +19 -15
- package/dist/config/schema.d.ts +1 -0
- package/dist/config/schema.js +8 -0
- 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 +2 -4
- 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/erasure/org-catalog.js +2 -2
- 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/infra/outbox/registry.d.ts +0 -14
- package/dist/infra/outbox/registry.js +0 -15
- 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/roles/worker.module.js +0 -6
- package/dist/runtime/maintenance.d.ts +1 -3
- package/dist/runtime/maintenance.js +3 -14
- package/package.json +1 -1
- 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
- package/dist/conversations/event-org-backfill.module.js +0 -18
|
@@ -3,7 +3,6 @@ import type { Job, Worker } from "bullmq";
|
|
|
3
3
|
import { EventCoalescer } from "../automations/events/coalesce.js";
|
|
4
4
|
import { TriggerDispatcher } from "../automations/events/dispatcher.js";
|
|
5
5
|
import { AutomationFirer } from "../automations/fire.js";
|
|
6
|
-
import { EventOrgBackfillJob } from "../conversations/event-org-backfill.js";
|
|
7
6
|
import { ConversationNoticeDelivery } from "../device-access/conversation-notice-delivery.js";
|
|
8
7
|
import { ErasureWorker } from "../erasure/worker.js";
|
|
9
8
|
import { BlobObjects } from "../files/blob-objects.js";
|
|
@@ -65,10 +64,9 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
|
|
|
65
64
|
private readonly idleCompaction;
|
|
66
65
|
private readonly db;
|
|
67
66
|
private readonly loopback;
|
|
68
|
-
private readonly eventOrgBackfill;
|
|
69
67
|
private readonly retention;
|
|
70
68
|
private readonly erasure;
|
|
71
|
-
constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke" | "settleResumeProof">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, db: KernelDb, loopback: Pick<LoopbackGrants, "refresh">,
|
|
69
|
+
constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, automations: Pick<AutomationFirer, "fire" | "settle">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke" | "settleResumeProof">, blobObjects: Pick<BlobObjects, "deleteBlob" | "deleteStaging" | "releaseFile">, hashing: Pick<FileLibraryHashJob, "dispatch" | "runOrgBatch">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, notices: Pick<ConversationNoticeDelivery, "attempt">, triggers: Pick<TriggerDispatcher, "dispatch">, coalescer: Pick<EventCoalescer, "flush">, idleCompaction: Pick<IdleCompactionJob, "fire">, db: KernelDb, loopback: Pick<LoopbackGrants, "refresh">, retention: Pick<RetentionWorker, "run">, erasure: Pick<ErasureWorker, "run">);
|
|
72
70
|
process(job: Job, token?: string): Promise<void>;
|
|
73
71
|
/** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
|
|
74
72
|
start(): void;
|
|
@@ -16,8 +16,6 @@ import { AUTOMATION_COALESCE_JOB, AUTOMATION_FIRE_JOB, AUTOMATION_SETTLE_JOB, TR
|
|
|
16
16
|
import { BackgroundModule } from "../background/background.module.js";
|
|
17
17
|
import { BG_WAKE_JOB } from "../background/wake-rules.js";
|
|
18
18
|
import { EventLogModule } from "../conversations/event-log.js";
|
|
19
|
-
import { EVENT_ORG_BACKFILL_JOB, EventOrgBackfillJob, } from "../conversations/event-org-backfill.js";
|
|
20
|
-
import { EventOrgBackfillModule } from "../conversations/event-org-backfill.module.js";
|
|
21
19
|
import { resolveConversationOrg, resolveRunOrg } from "../conversations/job-org.js";
|
|
22
20
|
import { ConversationNoticeDelivery, ConversationNoticesModule, NOTICE_PROMPT_TIMEOUT_MS, } from "../device-access/conversation-notice-delivery.js";
|
|
23
21
|
import { CONVERSATION_NOTICE_JOB, } from "../device-access/conversation-notices.js";
|
|
@@ -101,10 +99,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
101
99
|
idleCompaction;
|
|
102
100
|
db;
|
|
103
101
|
loopback;
|
|
104
|
-
eventOrgBackfill;
|
|
105
102
|
retention;
|
|
106
103
|
erasure;
|
|
107
|
-
constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback,
|
|
104
|
+
constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, automations, scheduled, log, operations, blobObjects, hashing, platformIcons, notices, triggers, coalescer, idleCompaction, db, loopback, retention, erasure) {
|
|
108
105
|
super();
|
|
109
106
|
this.permissionApprovals = permissionApprovals;
|
|
110
107
|
this.waits = waits;
|
|
@@ -127,7 +124,6 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
127
124
|
this.idleCompaction = idleCompaction;
|
|
128
125
|
this.db = db;
|
|
129
126
|
this.loopback = loopback;
|
|
130
|
-
this.eventOrgBackfill = eventOrgBackfill;
|
|
131
127
|
this.retention = retention;
|
|
132
128
|
this.erasure = erasure;
|
|
133
129
|
}
|
|
@@ -315,10 +311,6 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
|
|
|
315
311
|
await this.inOwnerScope(job, resolveRunOrg(this.db.db, data.runId, data.conversationId), (orgId) => this.idleCompaction.fire({ ...data, orgId }));
|
|
316
312
|
return;
|
|
317
313
|
}
|
|
318
|
-
// batched backfill of conversation_events.org_id from conversations (issue #1175)
|
|
319
|
-
case EVENT_ORG_BACKFILL_JOB:
|
|
320
|
-
await this.eventOrgBackfill.runBatch((job.data ?? { after: null }));
|
|
321
|
-
return;
|
|
322
314
|
default:
|
|
323
315
|
if (await this.scheduled.runNow(job.name))
|
|
324
316
|
return;
|
|
@@ -364,9 +356,8 @@ MaintenanceProcessor = __decorate([
|
|
|
364
356
|
__param(18, Inject(IdleCompactionJob)),
|
|
365
357
|
__param(19, Inject(KernelDb)),
|
|
366
358
|
__param(20, Inject(LoopbackGrants)),
|
|
367
|
-
__param(21, Inject(
|
|
368
|
-
__param(22, Inject(
|
|
369
|
-
__param(23, Inject(ErasureWorker))
|
|
359
|
+
__param(21, Inject(RetentionWorker)),
|
|
360
|
+
__param(22, Inject(ErasureWorker))
|
|
370
361
|
], MaintenanceProcessor);
|
|
371
362
|
export { MaintenanceProcessor };
|
|
372
363
|
/**
|
|
@@ -397,8 +388,6 @@ MaintenanceModule = __decorate([
|
|
|
397
388
|
BlobObjectsModule,
|
|
398
389
|
// the file library's hashing
|
|
399
390
|
FileLibraryJobsModule,
|
|
400
|
-
// batched conversation_events.org_id backfill
|
|
401
|
-
EventOrgBackfillModule,
|
|
402
391
|
RetentionWorkerModule,
|
|
403
392
|
ErasureWorkerModule,
|
|
404
393
|
// the platform icon object deletion
|
package/package.json
CHANGED
|
@@ -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;
|
|
@@ -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,18 +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
|
-
import { Module } from "@nestjs/common";
|
|
8
|
-
import { EventOrgBackfillJob } from "./event-org-backfill.js";
|
|
9
|
-
/** Batched `conversation_events.org_id` backfill ({@link EventOrgBackfillJob}), worker-only. */
|
|
10
|
-
let EventOrgBackfillModule = class EventOrgBackfillModule {
|
|
11
|
-
};
|
|
12
|
-
EventOrgBackfillModule = __decorate([
|
|
13
|
-
Module({
|
|
14
|
-
providers: [EventOrgBackfillJob],
|
|
15
|
-
exports: [EventOrgBackfillJob],
|
|
16
|
-
})
|
|
17
|
-
], EventOrgBackfillModule);
|
|
18
|
-
export { EventOrgBackfillModule };
|