@classytic/facts 0.1.0

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/index.mjs ADDED
@@ -0,0 +1,2361 @@
1
+ import { Repository, defineModels, isDuplicateKeyError, transactionResolutionOf, withTransaction } from "@classytic/mongokit";
2
+ import { addCivilDays, civilDate } from "@classytic/primitives/timezone";
3
+ import mongoose, { Schema, Types } from "mongoose";
4
+ import { and, eq, gte, lte } from "@classytic/repo-core/filter";
5
+ import { z } from "zod";
6
+ //#region src/civil/civil.ts
7
+ /**
8
+ * Civil-calendar seam of the fact projection.
9
+ *
10
+ * A fact row carries three CATEGORICAL time labels next to its `occurredAt`
11
+ * instant — `civilDate` (YYYY-MM-DD), `civilWeek` (YYYY-Www, ISO week) and
12
+ * `civilMonth` (YYYY-MM) — all derived from the BUSINESS zone's civil date of
13
+ * the instant, never from UTC or the server TZ. The zone itself is the host's
14
+ * business (Asia/Dhaka for BD deployments), so instant → label conversion is
15
+ * injected as {@link CivilCalendarPort}.
16
+ *
17
+ * String-level calendar math on an already-resolved civil DATE — the next
18
+ * civil day ({@link nextCivilDate}, rebuild chunk stepping) and the ISO week
19
+ * label ({@link isoWeekOfCivilDate}, rebuild `$setOnInsert` re-derivation) —
20
+ * is timezone-INDEPENDENT pure integer arithmetic and therefore lives in the
21
+ * kernel, so rebuild rows stay byte-equal to live-projected rows regardless
22
+ * of the host's zone binding.
23
+ */
24
+ const CIVIL_DATE_RE$4 = /^(\d{4})-(\d{2})-(\d{2})$/;
25
+ /** The next day after a civil-date string. "2024-01-15" → "2024-01-16". */
26
+ function nextCivilDate(dateStr) {
27
+ return addCivilDays(civilDate(dateStr), 1);
28
+ }
29
+ /**
30
+ * ISO-8601 week label (`'YYYY-Www'`) for a CIVIL date string, computed purely
31
+ * from the calendar PARTS — never by parsing `'YYYY-MM-DD'` through a Date
32
+ * zone. The `YYYY` here is the ISO **week-numbering year** (the calendar year
33
+ * of the week's Thursday), not the civil date's calendar year: Dec 29–31 can
34
+ * belong to next year's W01, and Jan 1–3 to the previous year's W52/W53.
35
+ */
36
+ function isoWeekOfCivilDate(dateStr) {
37
+ const m = CIVIL_DATE_RE$4.exec(dateStr);
38
+ if (!m) throw new Error(`isoWeekOfCivilDate: invalid civil date '${dateStr}' — expected 'YYYY-MM-DD'`);
39
+ const DAY_MS = 864e5;
40
+ const t = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
41
+ const isoDow = (new Date(t).getUTCDay() + 6) % 7 + 1;
42
+ const thursday = new Date(t + (4 - isoDow) * DAY_MS);
43
+ const weekYear = thursday.getUTCFullYear();
44
+ const week = Math.floor((thursday.getTime() - Date.UTC(weekYear, 0, 1)) / DAY_MS / 7) + 1;
45
+ return `${weekYear}-W${String(week).padStart(2, "0")}`;
46
+ }
47
+ /**
48
+ * Convenience for domain mappers: instant → the four system time fields of a
49
+ * fact row through the injected port.
50
+ */
51
+ function civilFieldsOf(civil, occurredAt) {
52
+ return {
53
+ occurredAt,
54
+ civilDate: civil.dateOf(occurredAt),
55
+ civilWeek: civil.weekOf(occurredAt),
56
+ civilMonth: civil.monthOf(occurredAt)
57
+ };
58
+ }
59
+ //#endregion
60
+ //#region src/errors.ts
61
+ /**
62
+ * Base domain error for the facts kernel. Implements repo-core's `HttpError`
63
+ * shape so an arc host serializes every facts error to a proper
64
+ * `ErrorContract` with a status code — hosts switch on `code`, never on
65
+ * `message`.
66
+ *
67
+ * Codes are hierarchical: `facts.<area>.<problem>`.
68
+ */
69
+ var FactsError = class extends Error {
70
+ status;
71
+ code;
72
+ meta;
73
+ constructor(input) {
74
+ super(input.message);
75
+ this.name = new.target.name;
76
+ this.status = input.status;
77
+ this.code = input.code;
78
+ if (input.meta !== void 0) this.meta = input.meta;
79
+ }
80
+ };
81
+ /**
82
+ * The projection shape failed Zod validation at describe time, or the civil
83
+ * source port was malformed at bind (fail-fast). A model-name collision is NOT
84
+ * one of these — that surfaces as mongokit's typed `ModelCollisionError`.
85
+ */
86
+ var FactsSpecError = class extends FactsError {
87
+ constructor(message, meta) {
88
+ super({
89
+ status: 500,
90
+ code: "facts.engine.invalid_spec",
91
+ message: `defineFactProjection: invalid shape — ${message}`,
92
+ ...meta !== void 0 ? { meta } : {}
93
+ });
94
+ }
95
+ };
96
+ /** The wired backend is missing runtime capabilities the projection requires. */
97
+ var FactsCapabilityError = class extends FactsError {
98
+ /**
99
+ * `true` when the backend never ANSWERED (bound before the connection
100
+ * opened, a driver exposing no topology) rather than answering "no". Both
101
+ * refuse — an unobserved outcome is never a positive one (AGENTS.md FAIL
102
+ * LOUD rule 3) — but the operator's fix differs, so the message must.
103
+ */
104
+ indeterminate;
105
+ constructor(missing, opts = {}) {
106
+ const indeterminate = opts.indeterminate === true;
107
+ super({
108
+ status: 500,
109
+ code: "facts.engine.missing_capabilities",
110
+ message: indeterminate ? `facts: could NOT determine whether the backend supports: ${missing.join(", ")}. An unconfirmed answer is treated as unsupported — the §4.3 projection write is transactional. Bind AFTER \`await mongoose.connect(...)\`, or call \`await probeMongoCapabilities(connection)\` first, or pass allowNonTransactional: true.` : `facts: backend missing required capabilities: ${missing.join(", ")}. The §4.3 projection transaction is transactional — MongoDB must run as a replica set (or pass allowNonTransactional: true for dev/standalone).`,
111
+ meta: {
112
+ missing: [...missing],
113
+ indeterminate
114
+ }
115
+ });
116
+ this.indeterminate = indeterminate;
117
+ }
118
+ };
119
+ //#endregion
120
+ //#region src/ensure-ready.ts
121
+ /**
122
+ * Boot helper — capability gate + collection materialisation.
123
+ *
124
+ * MongoDB refuses DDL inside transactions, so a projection's first write
125
+ * inside the §4.3 transaction would fail on a fresh database; materialise
126
+ * the four collections up-front. `skipIndexes: true` for production boots
127
+ * (rule 35) — run `engine.syncIndexes()` from the deploy script instead.
128
+ */
129
+ /**
130
+ * Runtime capabilities the projection requires at boot. `transactions` +
131
+ * `upsert` back the §4.3 projection transaction; `purgeByField` +
132
+ * `purgeByFilter` back the generation / occurrence / anonymize purge
133
+ * composition (fail loud at boot, not mid-purge, if the backend lacks them).
134
+ */
135
+ const REQUIRED_CAPABILITIES = [
136
+ "transactions",
137
+ "upsert",
138
+ "purgeByField",
139
+ "purgeByFilter"
140
+ ];
141
+ /**
142
+ * ## This gate could not fire until 2026-08-05
143
+ *
144
+ * `capabilities` resolved to mongokit's STATIC `MONGOKIT_CAPABILITIES`, whose
145
+ * `transactions` was hard-coded `true`, so the `transactions` half of this
146
+ * check was a tautology for every mongoose-backed repository and
147
+ * `allowNonTransactional` waived nothing (AGENTS.md FAIL LOUD rule 4).
148
+ * mongokit now OBSERVES the live SDAM topology per connection.
149
+ *
150
+ * Three answers, not two: an OBSERVED "no" (a standalone — fix the deployment)
151
+ * is distinguished from "could not determine" (bound before the connection
152
+ * opened, an unreadable driver). Both refuse, because an unobserved outcome is
153
+ * not a positive one (rule 3) — but the operator's fix differs, so the message
154
+ * does too. Only `transactions` is ever waivable; a backend without `upsert` /
155
+ * `purgeByField` / `purgeByFilter` is broken, not a deployment choice.
156
+ */
157
+ function assertFactsCapabilities(capabilities, allowNonTransactional) {
158
+ const caps = capabilities;
159
+ if (!caps) throw new FactsError({
160
+ status: 500,
161
+ code: "facts.engine.no_capabilities",
162
+ message: "facts: the wired backend declares no `capabilities` descriptor (repo-core 0.6 / mongokit 3.16+). Upgrade the kit."
163
+ });
164
+ const missing = (allowNonTransactional ? REQUIRED_CAPABILITIES.filter((flag) => flag !== "transactions") : REQUIRED_CAPABILITIES).filter((flag) => caps[flag] !== true);
165
+ if (missing.length === 0) return;
166
+ throw new FactsCapabilityError(missing, { indeterminate: missing.length === 1 && missing[0] === "transactions" && transactionResolutionOf(capabilities) === "unknown" });
167
+ }
168
+ async function ensureFactsReady(engine, options = {}) {
169
+ const models = [
170
+ engine.models.Fact,
171
+ engine.models.Rollup,
172
+ engine.models.Manifest,
173
+ engine.models.Checkpoint
174
+ ];
175
+ for (const model of models) await model.createCollection().catch((err) => {
176
+ if (err.code !== 48) throw err;
177
+ });
178
+ if (!options.skipIndexes) await engine.syncIndexes();
179
+ }
180
+ //#endregion
181
+ //#region src/models/manifest.model.ts
182
+ /**
183
+ * Projection generation MANIFEST model — a single tiny document
184
+ * (`_id: <projection name>`) that is the ONE switch saying which fact
185
+ * generation is live. The state machine + verbs live in
186
+ * `manifest/manifest.ts`; this module owns the schema and shared types.
187
+ */
188
+ /** The three in-flight rebuild states — dual-write is on in ALL of them. */
189
+ const REBUILD_STATES = [
190
+ "rebuilding",
191
+ "catching_up",
192
+ "verified"
193
+ ];
194
+ function buildManifestSchema(docId) {
195
+ return new Schema({
196
+ _id: {
197
+ type: String,
198
+ default: docId
199
+ },
200
+ activeGeneration: {
201
+ type: Number,
202
+ required: true,
203
+ default: 1
204
+ },
205
+ state: {
206
+ type: String,
207
+ enum: [
208
+ "active",
209
+ "rebuilding",
210
+ "catching_up",
211
+ "verified"
212
+ ],
213
+ required: true,
214
+ default: "active"
215
+ },
216
+ rebuildGeneration: { type: Number },
217
+ rebuildStartedAt: { type: Date },
218
+ backfillCompletedAt: { type: Date },
219
+ backfillCheckpointSummary: { type: Schema.Types.Mixed },
220
+ verifiedAt: { type: Date },
221
+ verification: { type: new Schema({
222
+ window: {
223
+ type: new Schema({
224
+ from: {
225
+ type: String,
226
+ required: true
227
+ },
228
+ to: {
229
+ type: String,
230
+ required: true
231
+ }
232
+ }, { _id: false }),
233
+ required: true
234
+ },
235
+ driftCount: {
236
+ type: Number,
237
+ required: true
238
+ },
239
+ factChecksum: { type: String }
240
+ }, { _id: false }) },
241
+ updatedAt: {
242
+ type: Date,
243
+ required: true,
244
+ default: () => /* @__PURE__ */ new Date()
245
+ }
246
+ }, {
247
+ timestamps: false,
248
+ versionKey: false
249
+ });
250
+ }
251
+ //#endregion
252
+ //#region src/manifest/manifest.ts
253
+ /** Default manifest read-cache TTL when the spec does not override it. */
254
+ const DEFAULT_GENERATION_CACHE_TTL_MS = 5e3;
255
+ /** Human instruction for the NEXT protocol step given the current state. */
256
+ function nextStepHint(state) {
257
+ switch (state) {
258
+ case "rebuilding": return "next step: finish the backfill with zero failed docs, then markBackfillComplete (ops: run the backfill script to completion)";
259
+ case "catching_up": return "next step: run a CLEAN reconciliation over the backfilled window, then markVerified";
260
+ case "verified": return "rebuild is verified — next step: cutover";
261
+ default: return "no rebuild in flight — next step: beginRebuild (ops: --rebuild)";
262
+ }
263
+ }
264
+ /**
265
+ * Instance-scoped manifest verbs + cached reads for ONE projection. Caches
266
+ * are per engine instance (per process pod), which is exactly the visibility
267
+ * unit the cutover time-guard reasons about.
268
+ */
269
+ var ProjectionManifest = class {
270
+ cacheTtlMs;
271
+ /**
272
+ * Minimum time the rebuild must have been visible before `cutover()` will
273
+ * proceed. 3 × the cache TTL guarantees every pod's cache (≤ TTL old at
274
+ * `beginRebuild`) expired and re-read a rebuild state — i.e. every live
275
+ * projector is already dual-writing — with margin. See the module docblock.
276
+ */
277
+ cutoverMinRebuildVisibleMs;
278
+ model;
279
+ docId;
280
+ label;
281
+ generationCache = null;
282
+ targetsCache = null;
283
+ constructor(model, options) {
284
+ this.model = model;
285
+ this.docId = options.name;
286
+ this.label = `${options.name}-projection manifest`;
287
+ this.cacheTtlMs = options.cacheTtlMs ?? 5e3;
288
+ this.cutoverMinRebuildVisibleMs = 3 * this.cacheTtlMs;
289
+ }
290
+ /** Drop the per-engine caches — called by every manifest mutation (and tests). */
291
+ invalidateCache() {
292
+ this.generationCache = null;
293
+ this.targetsCache = null;
294
+ }
295
+ /**
296
+ * The generation READERS resolve through. Default 1 when the manifest doc
297
+ * is absent (never-rebuilt deployments).
298
+ */
299
+ async getActiveGeneration() {
300
+ if (this.generationCache && Date.now() - this.generationCache.at < this.cacheTtlMs) return this.generationCache.value;
301
+ const value = (await this.model.findById(this.docId).lean().exec())?.activeGeneration ?? 1;
302
+ this.generationCache = {
303
+ value,
304
+ at: Date.now()
305
+ };
306
+ return value;
307
+ }
308
+ /**
309
+ * The generation set the live PROJECTOR must materialize every fact into:
310
+ * `[active]` normally, `[active, rebuildGeneration]` while a rebuild is in
311
+ * flight in ANY rebuild state (dual-write through the whole protocol — see
312
+ * module docblock for why this closes the cutover loss races). Same
313
+ * TTL/invalidation discipline as `getActiveGeneration`. Both inserts are
314
+ * idempotent because dedupe uniqueness is per `(generation, dedupeKey)`.
315
+ */
316
+ async getGenerationTargets() {
317
+ if (this.targetsCache && Date.now() - this.targetsCache.at < this.cacheTtlMs) return this.targetsCache.value;
318
+ const doc = await this.model.findById(this.docId).lean().exec();
319
+ const active = doc?.activeGeneration ?? 1;
320
+ const value = doc != null && REBUILD_STATES.includes(doc.state) && typeof doc.rebuildGeneration === "number" && doc.rebuildGeneration !== active ? [active, doc.rebuildGeneration] : [active];
321
+ this.targetsCache = {
322
+ value,
323
+ at: Date.now()
324
+ };
325
+ return value;
326
+ }
327
+ /** Current manifest snapshot (null when the doc was never created). */
328
+ async getManifest() {
329
+ return this.model.findById(this.docId).lean().exec();
330
+ }
331
+ /**
332
+ * Allocate (or resume) a shadow rebuild generation = active + 1.
333
+ *
334
+ * Resume semantics: while a rebuild is in flight (any rebuild state) the
335
+ * EXISTING rebuild generation is returned. Resuming from `catching_up` or
336
+ * `verified` DEMOTES the state back to `'rebuilding'` and clears the
337
+ * backfill/verification evidence — a new backfill run invalidates the
338
+ * earlier completion/clean-reconcile proof, so the protocol must be
339
+ * re-walked. The original `rebuildStartedAt` is kept (visibility began at
340
+ * the first flip).
341
+ */
342
+ async beginRebuild() {
343
+ const doc = await this.model.findOneAndUpdate({ _id: this.docId }, { $setOnInsert: {
344
+ activeGeneration: 1,
345
+ state: "active",
346
+ updatedAt: /* @__PURE__ */ new Date()
347
+ } }, {
348
+ upsert: true,
349
+ returnDocument: "after"
350
+ }).lean();
351
+ if (REBUILD_STATES.includes(doc.state) && typeof doc.rebuildGeneration === "number") {
352
+ if (doc.state !== "rebuilding") {
353
+ await this.model.updateOne({
354
+ _id: this.docId,
355
+ state: doc.state,
356
+ rebuildGeneration: doc.rebuildGeneration
357
+ }, {
358
+ $set: {
359
+ state: "rebuilding",
360
+ updatedAt: /* @__PURE__ */ new Date()
361
+ },
362
+ $unset: {
363
+ backfillCompletedAt: 1,
364
+ backfillCheckpointSummary: 1,
365
+ verifiedAt: 1,
366
+ verification: 1
367
+ }
368
+ });
369
+ this.invalidateCache();
370
+ }
371
+ return {
372
+ activeGeneration: doc.activeGeneration,
373
+ rebuildGeneration: doc.rebuildGeneration,
374
+ resumed: true
375
+ };
376
+ }
377
+ const rebuildGeneration = doc.activeGeneration + 1;
378
+ await this.model.updateOne({
379
+ _id: this.docId,
380
+ state: "active"
381
+ }, {
382
+ $set: {
383
+ state: "rebuilding",
384
+ rebuildGeneration,
385
+ rebuildStartedAt: /* @__PURE__ */ new Date(),
386
+ updatedAt: /* @__PURE__ */ new Date()
387
+ },
388
+ $unset: {
389
+ backfillCompletedAt: 1,
390
+ backfillCheckpointSummary: 1,
391
+ verifiedAt: 1,
392
+ verification: 1
393
+ }
394
+ });
395
+ this.invalidateCache();
396
+ return {
397
+ activeGeneration: doc.activeGeneration,
398
+ rebuildGeneration,
399
+ resumed: false
400
+ };
401
+ }
402
+ /**
403
+ * `rebuilding` → `catching_up`. Records that the document-driven backfill
404
+ * for the in-flight rebuild generation completed with zero failures.
405
+ * Guarded single update (`state:'rebuilding'` match) — REFUSES from any
406
+ * other state.
407
+ */
408
+ async markBackfillComplete(options) {
409
+ if (options.failed !== void 0 && options.failed > 0 && options.allowFailed !== true) throw new Error(`${this.label}: markBackfillComplete refused — backfill reported ${options.failed} mapper failure(s); the generation is MISSING those docs’ facts and would cut over incomplete. Fix the sources and re-run the backfill to zero failures, or pass allowFailed:true to override with intent.`);
410
+ const updated = await this.model.findOneAndUpdate({
411
+ _id: this.docId,
412
+ state: "rebuilding",
413
+ rebuildGeneration: { $gte: 1 }
414
+ }, {
415
+ $set: {
416
+ state: "catching_up",
417
+ backfillCompletedAt: /* @__PURE__ */ new Date(),
418
+ backfillCheckpointSummary: options.checkpointSummary ?? null,
419
+ updatedAt: /* @__PURE__ */ new Date()
420
+ },
421
+ $unset: {
422
+ verifiedAt: 1,
423
+ verification: 1
424
+ }
425
+ }, { returnDocument: "after" }).lean();
426
+ if (!updated) {
427
+ const current = await this.getManifest();
428
+ throw new Error(`${this.label}: markBackfillComplete refused — state is '${current?.state ?? "(none)"}' but must be 'rebuilding' with a rebuildGeneration; ${nextStepHint(current?.state)}`);
429
+ }
430
+ this.invalidateCache();
431
+ return updated;
432
+ }
433
+ /**
434
+ * `catching_up` → `verified`. Records the clean post-dual-write
435
+ * reconciliation evidence for the in-flight rebuild generation. REFUSES
436
+ * from any other state and REFUSES non-zero drift (a dirty reconcile is
437
+ * not verification).
438
+ */
439
+ async markVerified(options) {
440
+ if (options.driftCount !== 0) throw new Error(`${this.label}: markVerified refused — reconciliation reported ${options.driftCount} drift(s); verification evidence must be a CLEAN reconcile (driftCount 0). Fix the drift and reconcile again.`);
441
+ const verification = {
442
+ window: {
443
+ from: options.window.from,
444
+ to: options.window.to
445
+ },
446
+ driftCount: options.driftCount,
447
+ ...options.factChecksum !== void 0 ? { factChecksum: options.factChecksum } : {}
448
+ };
449
+ const updated = await this.model.findOneAndUpdate({
450
+ _id: this.docId,
451
+ state: "catching_up",
452
+ rebuildGeneration: { $gte: 1 }
453
+ }, { $set: {
454
+ state: "verified",
455
+ verifiedAt: /* @__PURE__ */ new Date(),
456
+ verification,
457
+ updatedAt: /* @__PURE__ */ new Date()
458
+ } }, { returnDocument: "after" }).lean();
459
+ if (!updated) {
460
+ const current = await this.getManifest();
461
+ throw new Error(`${this.label}: markVerified refused — state is '${current?.state ?? "(none)"}' but must be 'catching_up' (backfill marked complete, verification pending); ${nextStepHint(current?.state)}`);
462
+ }
463
+ this.invalidateCache();
464
+ return updated;
465
+ }
466
+ /**
467
+ * Atomic cutover: activeGeneration := rebuildGeneration, state := 'active',
468
+ * ALL rebuild/evidence fields cleared. Single guarded pipeline update — no
469
+ * read-modify-write window.
470
+ *
471
+ * STATE-GUARD: refuses unless `state === 'verified'` — the manifest itself
472
+ * proves backfill completion (`markBackfillComplete`) and a clean
473
+ * post-dual-write reconcile (`markVerified`) happened for THIS rebuild
474
+ * before any flip is possible; refusal messages name the missing step.
475
+ *
476
+ * TIME-GUARD (defense for the dual-write invariant — module docblock):
477
+ * refuses until the rebuild has been visible for at least
478
+ * `cutoverMinRebuildVisibleMs` (3 × cache TTL), so every pod's cached
479
+ * manifest read must have expired and observed a rebuild state (⇒ started
480
+ * dual-writing) before the flip can happen. Both guards are read-then-check
481
+ * (not atomic with the flip) — that is fine: they only ever REFUSE too
482
+ * early, and the actual flip stays guarded by the atomic `state:'verified'`
483
+ * match.
484
+ */
485
+ async cutover(options = {}) {
486
+ const current = await this.getManifest();
487
+ if (!current || !REBUILD_STATES.includes(current.state) || typeof current.rebuildGeneration !== "number") throw new Error(`${this.label}: cutover refused — no rebuild in flight (state=${current?.state ?? "(none)"}); ${nextStepHint(current?.state)}`);
488
+ if (current.state !== "verified") throw new Error(`${this.label}: cutover refused — rebuild generation ${current.rebuildGeneration} is '${current.state}', not 'verified'; ${nextStepHint(current.state)}`);
489
+ const startedAt = current.rebuildStartedAt;
490
+ if (!startedAt) throw new Error(`${this.label}: cutover refused — 'verified' manifest is missing rebuildStartedAt (corrupt state).`);
491
+ const visibleMs = (options.now ?? /* @__PURE__ */ new Date()).getTime() - new Date(startedAt).getTime();
492
+ if (visibleMs < this.cutoverMinRebuildVisibleMs) throw new Error(`${this.label}: cutover refused — rebuild has been visible for only ${visibleMs}ms (< ${this.cutoverMinRebuildVisibleMs}ms = 3 × generation-cache TTL). Every serving pod must have observed a rebuild state (and begun dual-writing) before cutover, or live facts landed between reconciliation and the flip would be lost from the new active generation. Retry after the window.`);
493
+ const updated = await this.model.findOneAndUpdate({
494
+ _id: this.docId,
495
+ state: "verified",
496
+ rebuildGeneration: { $gte: 1 }
497
+ }, [{ $set: {
498
+ activeGeneration: "$rebuildGeneration",
499
+ state: "active",
500
+ updatedAt: "$$NOW"
501
+ } }, { $unset: [
502
+ "rebuildGeneration",
503
+ "rebuildStartedAt",
504
+ "backfillCompletedAt",
505
+ "backfillCheckpointSummary",
506
+ "verifiedAt",
507
+ "verification"
508
+ ] }], {
509
+ returnDocument: "after",
510
+ updatePipeline: true
511
+ }).lean();
512
+ if (!updated) throw new Error(`${this.label}: cutover refused — manifest changed concurrently (state must be 'verified' with a rebuildGeneration)`);
513
+ this.invalidateCache();
514
+ return updated;
515
+ }
516
+ /**
517
+ * Abandon an in-flight rebuild from ANY rebuild state — activeGeneration
518
+ * untouched, all rebuild + evidence fields cleared. No-op when not rebuilding.
519
+ */
520
+ async abortRebuild() {
521
+ await this.model.updateOne({
522
+ _id: this.docId,
523
+ state: { $in: [...REBUILD_STATES] }
524
+ }, {
525
+ $set: {
526
+ state: "active",
527
+ updatedAt: /* @__PURE__ */ new Date()
528
+ },
529
+ $unset: {
530
+ rebuildGeneration: 1,
531
+ rebuildStartedAt: 1,
532
+ backfillCompletedAt: 1,
533
+ backfillCheckpointSummary: 1,
534
+ verifiedAt: 1,
535
+ verification: 1
536
+ }
537
+ });
538
+ this.invalidateCache();
539
+ }
540
+ };
541
+ //#endregion
542
+ //#region src/models/fact.model.ts
543
+ /**
544
+ * The atomic FACT model — one immutable row per business OCCURRENCE,
545
+ * projected asynchronously from a dedicated outbox stream. A rebuildable
546
+ * CQRS read model — NOT a source of truth for the domain's transactions,
547
+ * and it must never participate synchronously in domain writes.
548
+ *
549
+ * ## Idempotency — business-occurrence dedupe key (NOT eventId)
550
+ *
551
+ * Delivery is at-least-once, and the SAME business occurrence can surface
552
+ * under more than one envelope id. Dedupe therefore keys on a deterministic
553
+ * BUSINESS key built by the domain mapper, enforced by the unique
554
+ * `{generation, dedupeKey}` index. A duplicate-key on insert means "already
555
+ * projected" and is a silent no-op (idempotent redelivery). `eventId` /
556
+ * `eventType` stay on the row as PROVENANCE only (non-unique).
557
+ *
558
+ * ## Tenancy — organizationId (when declared) is a DIMENSION, not a scope
559
+ *
560
+ * NO org-scoping / multi-tenant plugin is attached here BY DESIGN: this is
561
+ * an analytical projection — the branch/tenant id the domain declares among
562
+ * its dimensions is stored as a queryable dimension so branch and HQ
563
+ * surfaces can slice it. Scope enforcement happens at the query surface
564
+ * (lens semantic models / resource permissions). Attaching a tenant plugin
565
+ * would break the projector (system writes carry no request scope) and the
566
+ * HQ rollup reads.
567
+ *
568
+ * ## Numeric types
569
+ *
570
+ * Per-row money/qty measures are plain integer JS `Number` (minor units /
571
+ * whole units) — BSON Decimal128 is for the ROLLUP accumulators, not for
572
+ * per-occurrence rows, which are bounded by single-occurrence magnitudes.
573
+ */
574
+ const safeIntegerMeasure = {
575
+ validator: Number.isSafeInteger,
576
+ message: (props) => `${props.value} is not a safe integer — measures are integer (minor units / whole units)`
577
+ };
578
+ const wholeNonNegativeMeasure = {
579
+ validator: (v) => Number.isSafeInteger(v) && v >= 0,
580
+ message: (props) => `${props.value} is not a whole non-negative quantity`
581
+ };
582
+ function buildFactSchema(input) {
583
+ const { fact, measures } = input;
584
+ const schemaVersion = fact.schemaVersion ?? 1;
585
+ const definition = {
586
+ generation: {
587
+ type: Number,
588
+ required: true
589
+ },
590
+ dedupeKey: {
591
+ type: String,
592
+ required: true
593
+ },
594
+ eventId: { type: String },
595
+ eventType: { type: String },
596
+ schemaVersion: {
597
+ type: Number,
598
+ default: schemaVersion
599
+ },
600
+ ...fact.dimensions,
601
+ occurredAt: {
602
+ type: Date,
603
+ required: true
604
+ },
605
+ recordedAt: {
606
+ type: Date,
607
+ required: true
608
+ },
609
+ civilDate: {
610
+ type: String,
611
+ required: true
612
+ },
613
+ civilWeek: {
614
+ type: String,
615
+ required: true
616
+ },
617
+ civilMonth: {
618
+ type: String,
619
+ required: true
620
+ }
621
+ };
622
+ for (const measure of measures) definition[measure.name] = {
623
+ type: Number,
624
+ default: 0,
625
+ validate: measure.nonNegative ? wholeNonNegativeMeasure : safeIntegerMeasure
626
+ };
627
+ for (const [name, marker] of Object.entries(fact.markers ?? {})) definition[name] = {
628
+ type: String,
629
+ enum: [...marker.values],
630
+ ...marker.default !== void 0 ? { default: marker.default } : {}
631
+ };
632
+ const schema = new Schema(definition, { timestamps: false });
633
+ schema.index({
634
+ generation: 1,
635
+ dedupeKey: 1
636
+ }, {
637
+ unique: true,
638
+ name: "gen_dedupeKey_unique"
639
+ });
640
+ for (const ix of fact.extraIndexes ?? []) schema.index(ix.fields, ix.options);
641
+ return schema;
642
+ }
643
+ //#endregion
644
+ //#region src/models/rollup.model.ts
645
+ /**
646
+ * The daily ROLLUP model — the serving aggregate of a fact projection.
647
+ *
648
+ * One document per GRAIN:
649
+ *
650
+ * generation × civilDate × ...spec.rollup.grain
651
+ *
652
+ * Grain dimension values that are absent on a fact are NULL-NORMALIZED to
653
+ * the stable sentinel `'(none)'` (see rollup/increments.ts) so the unique
654
+ * grain index has no null-vs-missing ambiguity and rollup rows group
655
+ * deterministically. Consumers slicing a dimension must treat the sentinel
656
+ * as "unattributed", never as a real value.
657
+ *
658
+ * ## Measures — additive totals ONLY (no distinct-order arrays)
659
+ *
660
+ * The measures mirror declared fact measures 1:1 plus `factCount` (facts
661
+ * rolled into the row). This projection deliberately carries NO
662
+ * distinct-count structures (an unbounded per-day id array cannot be
663
+ * maintained safely): exact distinct counts come from BOUNDED queries
664
+ * against the fact collection — the atomic projection remains the
665
+ * drill-down source of truth.
666
+ *
667
+ * ## Accumulator representation — BSON Decimal128 (deliberate)
668
+ *
669
+ * Decimal128 is the compliant multi-year-exact accumulator:
670
+ * - Mongoose has NO native Long schema type (Mixed would skip casting AND
671
+ * validation, and reads back inconsistently via `promoteLongs`).
672
+ * - MongoDB's query-time `$sum` over `long` SILENTLY promotes to `double`
673
+ * on int64 overflow; `$sum` over `decimal` stays `decimal` (34
674
+ * significant digits, never silently promoted).
675
+ * - `$inc` casting is lossless through the normal mongokit/mongoose update
676
+ * path (mongoose `castUpdate` → `Decimal128.fromString(String(n))` —
677
+ * exact for safe integers).
678
+ *
679
+ * SERIALIZATION RULE: a Decimal128 must NEVER cross a read boundary raw —
680
+ * convert through `rollupMeasureToNumber` (rollup/increments.ts), which
681
+ * asserts the value is a safe JS integer. Ratio measures are computed as
682
+ * ratio-of-sums by the reader; never stored here.
683
+ *
684
+ * ## Update discipline
685
+ *
686
+ * Live maintenance is the §4.3 small projection transaction owned by
687
+ * `projectFacts` (only-new facts insert + the matching `$inc` upserts commit
688
+ * atomically, per generation). Rebuild/repair is `rebuildRollup` —
689
+ * deterministic re-aggregation of the facts. Nothing else may write this
690
+ * collection.
691
+ *
692
+ * Tenancy: same as the fact model — NO tenant plugin; any org dimension in
693
+ * the grain is a queryable dimension, not a scope (see fact.model.ts header).
694
+ */
695
+ function buildRollupSchema(rollup) {
696
+ const schemaVersion = rollup.schemaVersion ?? 1;
697
+ const derivedWeek = rollup.derived?.civilWeek ?? true;
698
+ const derivedMonth = rollup.derived?.civilMonth ?? true;
699
+ const decimalMeasure = {
700
+ type: Schema.Types.Decimal128,
701
+ default: () => mongoose.Types.Decimal128.fromString("0")
702
+ };
703
+ const definition = {
704
+ generation: {
705
+ type: Number,
706
+ required: true
707
+ },
708
+ civilDate: {
709
+ type: String,
710
+ required: true
711
+ }
712
+ };
713
+ for (const dim of rollup.grain) definition[dim] = {
714
+ type: String,
715
+ required: true
716
+ };
717
+ if (derivedWeek) definition.civilWeek = {
718
+ type: String,
719
+ required: true
720
+ };
721
+ if (derivedMonth) definition.civilMonth = {
722
+ type: String,
723
+ required: true
724
+ };
725
+ definition.schemaVersion = {
726
+ type: Number,
727
+ default: schemaVersion
728
+ };
729
+ for (const measure of rollup.measures) definition[measure] = decimalMeasure;
730
+ definition.factCount = {
731
+ type: Number,
732
+ default: 0
733
+ };
734
+ definition.updatedAt = {
735
+ type: Date,
736
+ required: true,
737
+ default: () => /* @__PURE__ */ new Date()
738
+ };
739
+ const schema = new Schema(definition, {
740
+ timestamps: false,
741
+ versionKey: false
742
+ });
743
+ const grainIndex = {
744
+ generation: 1,
745
+ civilDate: 1
746
+ };
747
+ for (const dim of rollup.grain) grainIndex[dim] = 1;
748
+ schema.index(grainIndex, {
749
+ unique: true,
750
+ name: "daily_grain_unique"
751
+ });
752
+ for (const ix of rollup.extraIndexes ?? []) schema.index(ix.fields, ix.options);
753
+ return schema;
754
+ }
755
+ //#endregion
756
+ //#region src/models/checkpoint.model.ts
757
+ /**
758
+ * Backfill CHECKPOINT model — one document per (checkpointId, source).
759
+ * The target generation is persisted and immutable for that checkpoint
760
+ * identity; reusing the id for another generation is refused unless the
761
+ * operator explicitly restarts (which clears the old checkpoint).
762
+ * persisting the keyset cursor + counters of the resumable document-driven
763
+ * backfill (backfill/backfill.ts). Re-running with the same checkpointId
764
+ * resumes from `lastId`; `restart` clears the checkpoints first.
765
+ *
766
+ * `source` is the free-form source NAME from the host's `DocumentSource`
767
+ * bindings (not a closed enum — the engine is domain-agnostic).
768
+ */
769
+ function buildCheckpointSchema() {
770
+ const schema = new Schema({
771
+ checkpointId: {
772
+ type: String,
773
+ required: true
774
+ },
775
+ source: {
776
+ type: String,
777
+ required: true
778
+ },
779
+ generation: {
780
+ type: Number,
781
+ required: true,
782
+ min: 1
783
+ },
784
+ lastId: { type: Schema.Types.ObjectId },
785
+ processed: {
786
+ type: Number,
787
+ default: 0
788
+ },
789
+ inserted: {
790
+ type: Number,
791
+ default: 0
792
+ },
793
+ duplicates: {
794
+ type: Number,
795
+ default: 0
796
+ },
797
+ failed: {
798
+ type: Number,
799
+ default: 0
800
+ },
801
+ done: {
802
+ type: Boolean,
803
+ default: false
804
+ },
805
+ startedAt: {
806
+ type: Date,
807
+ required: true
808
+ },
809
+ updatedAt: {
810
+ type: Date,
811
+ required: true
812
+ }
813
+ }, {
814
+ timestamps: false,
815
+ versionKey: false
816
+ });
817
+ schema.index({
818
+ checkpointId: 1,
819
+ source: 1
820
+ }, {
821
+ unique: true,
822
+ name: "checkpoint_source_unique"
823
+ });
824
+ return schema;
825
+ }
826
+ //#endregion
827
+ //#region src/models/create-models.ts
828
+ /**
829
+ * Fact-projection model specification — the ONE authoritative place the four
830
+ * projection models (Fact, Rollup, Manifest, Checkpoint) are described.
831
+ *
832
+ * `defineFactProjectionModels(config)` returns a connection-free mongokit
833
+ * `ModelBlueprint`; `defineFactProjection` binds it during engine construction.
834
+ * Collision handling (rule 21), auto-index (rule 35) and explicit collection
835
+ * names (rule 20.1) live here once. A name collision surfaces as mongokit's
836
+ * typed `ModelCollisionError` — there is no kernel-specific collision error.
837
+ */
838
+ /** `'sales'` → `'Sales'` — the model-name namespace for one projection. */
839
+ function pascalName(name) {
840
+ return name.split(/[-_]/).filter((p) => p.length > 0).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
841
+ }
842
+ /**
843
+ * Model names for one projection — namespaced by the projection name so two
844
+ * different projections coexist on one connection.
845
+ */
846
+ function modelNames(name) {
847
+ const pascal = pascalName(name);
848
+ return {
849
+ Fact: `${pascal}Fact`,
850
+ Rollup: `${pascal}Rollup`,
851
+ Manifest: `${pascal}ProjectionManifest`,
852
+ Checkpoint: `${pascal}ProjectionCheckpoint`
853
+ };
854
+ }
855
+ /**
856
+ * Describe the four projection models as a connection-free blueprint. Pure —
857
+ * builds no schema and registers nothing until `.bind(connection)`. Each schema
858
+ * factory runs at most once, only when its model is actually registered.
859
+ */
860
+ function defineFactProjectionModels(config) {
861
+ const autoIndex = config.autoIndex ?? true;
862
+ const names = modelNames(config.name);
863
+ const existing = config.forceRecreate ? {
864
+ mode: "replace",
865
+ environment: "test"
866
+ } : { mode: "throw" };
867
+ const withAutoIndex = (build) => () => {
868
+ const schema = build();
869
+ schema.set("autoIndex", autoIndex);
870
+ return schema;
871
+ };
872
+ return defineModels({
873
+ models: [
874
+ {
875
+ name: names.Fact,
876
+ collection: config.collections.facts,
877
+ schema: withAutoIndex(() => buildFactSchema({
878
+ fact: config.fact,
879
+ measures: config.measures
880
+ })),
881
+ existing
882
+ },
883
+ {
884
+ name: names.Rollup,
885
+ collection: config.collections.rollup,
886
+ schema: withAutoIndex(() => buildRollupSchema(config.rollup)),
887
+ existing
888
+ },
889
+ {
890
+ name: names.Manifest,
891
+ collection: config.collections.manifest,
892
+ schema: withAutoIndex(() => buildManifestSchema(config.name)),
893
+ existing
894
+ },
895
+ {
896
+ name: names.Checkpoint,
897
+ collection: config.collections.checkpoints,
898
+ schema: withAutoIndex(() => buildCheckpointSchema()),
899
+ existing
900
+ }
901
+ ],
902
+ assemble: (models) => Object.freeze({
903
+ Fact: models.get(names.Fact),
904
+ Rollup: models.get(names.Rollup),
905
+ Manifest: models.get(names.Manifest),
906
+ Checkpoint: models.get(names.Checkpoint)
907
+ })
908
+ });
909
+ }
910
+ //#endregion
911
+ //#region src/projector/guards.ts
912
+ /**
913
+ * Numeric invariants + duplicate-key classification shared by the live
914
+ * projection path, the backfill engine and every domain mapper.
915
+ */
916
+ /**
917
+ * Assert a quantity is a whole, non-negative, safe integer. THROWS otherwise
918
+ * (relay retry/DLQ path for live events; loud abort for the backfill) — a
919
+ * negative or fractional quantity is corrupt input that must never be
920
+ * silently projected.
921
+ */
922
+ function assertValidQty(value, context) {
923
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`fact projector: invalid quantity ${value} (${context}) — must be a whole integer >= 0`);
924
+ return value;
925
+ }
926
+ /**
927
+ * Multiply a per-unit minor-unit amount by a quantity, THROWING when the
928
+ * product leaves the safe-integer range. Writing an unsafe float would
929
+ * silently corrupt money aggregates — the error must ride the retry/DLQ (or
930
+ * backfill-abort) path instead.
931
+ */
932
+ function safeMulMinor(unitMinor, quantity, context) {
933
+ const product = unitMinor * quantity;
934
+ if (!Number.isSafeInteger(product)) throw new Error(`fact projector: unsafe money product ${unitMinor} * ${quantity} (${context}) — exceeds Number.MAX_SAFE_INTEGER`);
935
+ return product;
936
+ }
937
+ /**
938
+ * True when an `insertMany` failure is ONLY duplicate-key (code 11000) —
939
+ * i.e. every failed write hit the unique `{generation, dedupeKey}` index.
940
+ * Any other error class (validation, network, mixed batches) returns false
941
+ * and MUST be rethrown by the caller. Scalar classification delegates to
942
+ * mongokit's `isDuplicateKeyError` (the authoritative 11000 classifier).
943
+ */
944
+ function isDuplicateKeyOnly(err) {
945
+ if (!err || typeof err !== "object") return false;
946
+ const writeErrors = err.writeErrors;
947
+ if (Array.isArray(writeErrors) && writeErrors.length > 0) return writeErrors.every((w) => {
948
+ const x = w;
949
+ return x.code === 11e3 || x.err != null && x.err.code === 11e3 || isDuplicateKeyError(w);
950
+ });
951
+ return isDuplicateKeyError(err);
952
+ }
953
+ /**
954
+ * Given a duplicate-key-only `insertMany({ordered:false})` failure, return
955
+ * the facts that DID insert (writeErrors carry the failed batch indexes).
956
+ * Pure; used only on the non-transactional fallback path.
957
+ */
958
+ function subtractFailedInserts(facts, err) {
959
+ const writeErrors = err.writeErrors;
960
+ if (!Array.isArray(writeErrors)) return facts.length === 1 ? [] : [...facts];
961
+ const failedIndexes = /* @__PURE__ */ new Set();
962
+ for (const w of writeErrors) {
963
+ const idx = w.index ?? w.err?.index;
964
+ if (typeof idx === "number") failedIndexes.add(idx);
965
+ }
966
+ return facts.filter((_, i) => !failedIndexes.has(i));
967
+ }
968
+ //#endregion
969
+ //#region src/backfill/backfill.ts
970
+ /**
971
+ * Resumable DOCUMENT-driven fact backfill — rebuilds (or seeds) a projection
972
+ * generation straight from the durable SOURCE documents, using the SAME
973
+ * business dedupe-key scheme and quality-marker rules as the live projector
974
+ * (both live in the domain's mappers), so a backfilled generation is
975
+ * row-equivalent to what live projection would have produced.
976
+ *
977
+ * ## Resumability & bounds
978
+ *
979
+ * - Stable `_id`-ascending KEYSET pagination (`_id > lastId`, limit N) —
980
+ * never `skip`. The engine composes the query ({@link buildKeysetQuery});
981
+ * the source supplies the minimal page reader.
982
+ * - One checkpoint doc per (checkpointId, source), pinned to its target
983
+ * generation. A resume against another generation fails loudly; `restart`
984
+ * explicitly clears and re-pins it. A cursor can never leak between
985
+ * rebuild generations.
986
+ * - `batchSize` + optional `maxDocs` budget + optional `sleepMs` rate limit.
987
+ * - NO Mongo transaction around batches (never large loops in a txn): the
988
+ * unique `{generation, dedupeKey}` index makes every insert idempotent, so
989
+ * a crash mid-batch simply re-inserts duplicates as no-ops.
990
+ *
991
+ * Idempotency: `insertMany({ordered:false})`, duplicate-key (11000) errors
992
+ * swallowed — a row already projected live (or by a resumed batch) is a
993
+ * no-op counted as `duplicates`. Every OTHER error aborts loudly.
994
+ *
995
+ * The domain's `mapBatch` mappers stay PURE-ish (doc + pre-resolved context
996
+ * → fact rows; async only for batch enrichment loads); all keyset reads,
997
+ * checkpoints, insert-dedupe and counting live HERE.
998
+ *
999
+ * Invoked by ops scripts and tests — NOT constructed at serving boot.
1000
+ * Backfill writes ONLY its explicit target generation (the live projector,
1001
+ * by contrast, dual-writes through the manifest's generation targets).
1002
+ */
1003
+ /**
1004
+ * Compose the next keyset query: base filter + `_id > lastId` when resuming.
1005
+ * Pure — the "resume from checkpoint" logic in one testable place.
1006
+ */
1007
+ function buildKeysetQuery(baseFilter, lastId) {
1008
+ return lastId ? {
1009
+ ...baseFilter,
1010
+ _id: { $gt: lastId }
1011
+ } : { ...baseFilter };
1012
+ }
1013
+ /**
1014
+ * Classify an `insertMany({ordered:false})` outcome into inserted/duplicates
1015
+ * counts. Call ONLY after `isDuplicateKeyOnly(err)` returned true — every
1016
+ * write error is then a duplicate-key no-op. Pure.
1017
+ */
1018
+ function countDuplicateWrites(err, totalFacts) {
1019
+ if (!err || typeof err !== "object") return 0;
1020
+ const writeErrors = err.writeErrors;
1021
+ if (Array.isArray(writeErrors)) return writeErrors.length;
1022
+ return Math.min(1, totalFacts);
1023
+ }
1024
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1025
+ /**
1026
+ * Resumable, bounded, idempotent backfill of the fact collection from source
1027
+ * documents. See module docblock. Returns per-source counters; callers
1028
+ * treat any `failed > 0` or `done: false` as a non-clean run.
1029
+ */
1030
+ async function runBackfill(deps, options) {
1031
+ const { sources, generation, checkpointId, batchSize = 500, maxDocs, sleepMs, restart = false, log = () => {} } = options;
1032
+ if (!Number.isInteger(generation) || generation < 1) throw new Error(`${deps.name} fact backfill: invalid generation ${generation}`);
1033
+ if (!checkpointId) throw new Error(`${deps.name} fact backfill: checkpointId is required`);
1034
+ if (sources.length === 0) throw new Error(`${deps.name} fact backfill: at least one source is required`);
1035
+ if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1e4) throw new Error(`${deps.name} fact backfill: batchSize must be a safe integer between 1 and 10000`);
1036
+ if (maxDocs !== void 0 && (!Number.isSafeInteger(maxDocs) || maxDocs < 1)) throw new Error(`${deps.name} fact backfill: maxDocs must be a positive safe integer`);
1037
+ if (sleepMs !== void 0 && (!Number.isSafeInteger(sleepMs) || sleepMs < 0)) throw new Error(`${deps.name} fact backfill: sleepMs must be a non-negative safe integer`);
1038
+ const sourceNames = sources.map((s) => s.name);
1039
+ if (new Set(sourceNames).size !== sourceNames.length) throw new Error(`${deps.name} fact backfill: source names must be unique`);
1040
+ if (restart) log(`[backfill] restart — cleared ${(await deps.checkpointModel.deleteMany({
1041
+ checkpointId,
1042
+ source: { $in: sourceNames }
1043
+ })).deletedCount} checkpoint(s) for '${checkpointId}'`);
1044
+ let budget = maxDocs ?? Number.POSITIVE_INFINITY;
1045
+ const results = [];
1046
+ for (const source of sources) {
1047
+ const now = /* @__PURE__ */ new Date();
1048
+ const checkpoint = await deps.checkpointModel.findOneAndUpdate({
1049
+ checkpointId,
1050
+ source: source.name
1051
+ }, { $setOnInsert: {
1052
+ startedAt: now,
1053
+ updatedAt: now,
1054
+ generation,
1055
+ processed: 0,
1056
+ inserted: 0,
1057
+ duplicates: 0,
1058
+ failed: 0,
1059
+ done: false
1060
+ } }, {
1061
+ upsert: true,
1062
+ returnDocument: "after"
1063
+ }).lean();
1064
+ if (checkpoint.generation !== generation) throw new Error(`${deps.name} fact backfill: checkpoint '${checkpointId}' source '${source.name}' belongs to generation ${String(checkpoint.generation)}, not ${generation}; use restart:true or a new checkpointId`);
1065
+ const counters = {
1066
+ source: source.name,
1067
+ processed: checkpoint.processed,
1068
+ inserted: checkpoint.inserted,
1069
+ duplicates: checkpoint.duplicates,
1070
+ failed: checkpoint.failed,
1071
+ done: checkpoint.done
1072
+ };
1073
+ if (checkpoint.done) {
1074
+ log(`[backfill:${source.name}] already done (${checkpoint.processed} docs) — skipping`);
1075
+ results.push(counters);
1076
+ continue;
1077
+ }
1078
+ if (budget <= 0) {
1079
+ log(`[backfill:${source.name}] doc budget exhausted — stopping before this source`);
1080
+ results.push(counters);
1081
+ continue;
1082
+ }
1083
+ const totalEstimate = source.estimateTotal ? await source.estimateTotal(source.filter) : null;
1084
+ let lastId = checkpoint.lastId ?? null;
1085
+ const runStartedAt = Date.now();
1086
+ let processedThisRun = 0;
1087
+ log(`[backfill:${source.name}] start gen=${generation} checkpoint='${checkpointId}' resumeFrom=${lastId ? String(lastId) : "(begin)"} estimate=${totalEstimate ?? "?"}`);
1088
+ while (budget > 0) {
1089
+ const limit = Math.min(batchSize, budget);
1090
+ const docs = await source.read(buildKeysetQuery(source.filter, lastId), limit);
1091
+ if (docs.length > limit) throw new Error(`${deps.name} fact backfill: source '${source.name}' returned ${docs.length} docs for limit ${limit}`);
1092
+ let previousId = lastId;
1093
+ for (const [index, doc] of docs.entries()) {
1094
+ const rawId = doc._id;
1095
+ if (!Types.ObjectId.isValid(rawId)) throw new Error(`${deps.name} fact backfill: source '${source.name}' returned a non-ObjectId _id at page index ${index}`);
1096
+ const id = rawId instanceof Types.ObjectId ? rawId : new Types.ObjectId(String(rawId));
1097
+ if (previousId && id.toHexString() <= previousId.toHexString()) throw new Error(`${deps.name} fact backfill: source '${source.name}' must return strictly ascending ObjectId pages`);
1098
+ previousId = id;
1099
+ }
1100
+ if (docs.length === 0) {
1101
+ counters.done = true;
1102
+ await deps.checkpointModel.updateOne({
1103
+ checkpointId,
1104
+ source: source.name
1105
+ }, { $set: {
1106
+ done: true,
1107
+ updatedAt: /* @__PURE__ */ new Date()
1108
+ } });
1109
+ log(`[backfill:${source.name}] done — processed=${counters.processed} inserted=${counters.inserted} duplicates=${counters.duplicates} failed=${counters.failed}`);
1110
+ break;
1111
+ }
1112
+ const ctx = {
1113
+ generation,
1114
+ recordedAt: /* @__PURE__ */ new Date()
1115
+ };
1116
+ const { facts, failures } = await source.mapBatch(docs, ctx);
1117
+ let inserted = 0;
1118
+ let duplicates = 0;
1119
+ if (facts.length > 0) try {
1120
+ inserted = (await deps.factModel.insertMany(facts, {
1121
+ ordered: false,
1122
+ throwOnValidationError: true
1123
+ })).length;
1124
+ } catch (err) {
1125
+ if (!isDuplicateKeyOnly(err)) throw err;
1126
+ duplicates = countDuplicateWrites(err, facts.length);
1127
+ inserted = facts.length - duplicates;
1128
+ }
1129
+ for (const failure of failures) log(`[backfill:${source.name}] FAILED doc ${failure.id}: ${failure.reason}`);
1130
+ const rawLastId = docs[docs.length - 1]._id;
1131
+ lastId = rawLastId instanceof Types.ObjectId ? rawLastId : new Types.ObjectId(String(rawLastId));
1132
+ counters.processed += docs.length;
1133
+ counters.inserted += inserted;
1134
+ counters.duplicates += duplicates;
1135
+ counters.failed += failures.length;
1136
+ processedThisRun += docs.length;
1137
+ budget -= docs.length;
1138
+ await deps.checkpointModel.updateOne({
1139
+ checkpointId,
1140
+ source: source.name
1141
+ }, {
1142
+ $set: {
1143
+ lastId,
1144
+ updatedAt: /* @__PURE__ */ new Date()
1145
+ },
1146
+ $inc: {
1147
+ processed: docs.length,
1148
+ inserted,
1149
+ duplicates,
1150
+ failed: failures.length
1151
+ }
1152
+ });
1153
+ const elapsedSec = Math.max((Date.now() - runStartedAt) / 1e3, .001);
1154
+ const rate = (processedThisRun / elapsedSec).toFixed(1);
1155
+ log(`[backfill:${source.name}] batch=${docs.length} progress=${counters.processed}/${totalEstimate ?? "?"} inserted=${inserted} duplicates=${duplicates} failed=${failures.length} rate=${rate}/s`);
1156
+ if (sleepMs && sleepMs > 0) await sleep(sleepMs);
1157
+ }
1158
+ if (!counters.done && budget <= 0) log(`[backfill:${source.name}] paused — maxDocs budget reached (checkpoint persisted at lastId=${String(lastId)})`);
1159
+ results.push(counters);
1160
+ }
1161
+ const complete = results.length === sources.length && results.every((r) => r.done);
1162
+ const failed = results.reduce((sum, r) => sum + r.failed, 0);
1163
+ return {
1164
+ generation,
1165
+ checkpointId,
1166
+ sources: results,
1167
+ complete,
1168
+ failed,
1169
+ clean: complete && failed === 0
1170
+ };
1171
+ }
1172
+ //#endregion
1173
+ //#region src/rollup/increments.ts
1174
+ /**
1175
+ * Null-normalization sentinel for absent grain dimensions. Stable — changing
1176
+ * it strands existing rows under the old sentinel.
1177
+ */
1178
+ const ROLLUP_DIM_NONE = "(none)";
1179
+ function normalizeDim(value) {
1180
+ return typeof value === "string" && value.length > 0 ? value : ROLLUP_DIM_NONE;
1181
+ }
1182
+ /** The rollup grain a fact rolls into — sentinel-normalized (see header). */
1183
+ function grainFromFact(rollup, fact) {
1184
+ const grain = {
1185
+ generation: fact.generation,
1186
+ civilDate: fact.civilDate
1187
+ };
1188
+ for (const dim of rollup.grain) grain[dim] = normalizeDim(fact[dim]);
1189
+ return grain;
1190
+ }
1191
+ function grainKey(rollup, grain) {
1192
+ return JSON.stringify([
1193
+ grain.generation,
1194
+ grain.civilDate,
1195
+ ...rollup.grain.map((dim) => grain[dim])
1196
+ ]);
1197
+ }
1198
+ /**
1199
+ * Group facts into per-grain `$inc` deltas — the pure core of the §4.3
1200
+ * projection transaction. Deterministic order (sorted by grain key) so
1201
+ * concurrent transactions touch rollup rows in a stable order.
1202
+ */
1203
+ function incrementsFromFacts(rollup, facts) {
1204
+ const map = /* @__PURE__ */ new Map();
1205
+ for (const fact of facts) {
1206
+ const grain = grainFromFact(rollup, fact);
1207
+ const key = grainKey(rollup, grain);
1208
+ let entry = map.get(key);
1209
+ if (!entry) {
1210
+ const inc = {};
1211
+ for (const measure of rollup.measures) inc[measure] = 0;
1212
+ inc.factCount = 0;
1213
+ entry = {
1214
+ grain,
1215
+ civilWeek: fact.civilWeek,
1216
+ civilMonth: fact.civilMonth,
1217
+ inc
1218
+ };
1219
+ map.set(key, entry);
1220
+ }
1221
+ for (const measure of rollup.measures) {
1222
+ const value = fact[measure];
1223
+ entry.inc[measure] = (entry.inc[measure] ?? 0) + (typeof value === "number" ? value : 0);
1224
+ }
1225
+ entry.inc.factCount = (entry.inc.factCount ?? 0) + 1;
1226
+ }
1227
+ return [...map.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, v]) => v);
1228
+ }
1229
+ /**
1230
+ * Serialize a Decimal128 (or driver-numeric) measure to a JS number at a
1231
+ * read boundary. THROWS on non-integer or unsafe magnitude — a lossy
1232
+ * conversion must never be silent (the exactness contract).
1233
+ */
1234
+ function rollupMeasureToNumber(value, context) {
1235
+ if (value == null) return 0;
1236
+ const str = typeof value === "number" ? String(value) : String(value.toString());
1237
+ const n = Number(str);
1238
+ if (!Number.isSafeInteger(n) || String(n) !== str.replace(/^(-?\d+)(\.0+)?$/, "$1")) throw new Error(`fact rollup: measure value "${str}" (${context}) is not a safe integer — refusing lossy serialization`);
1239
+ return n;
1240
+ }
1241
+ //#endregion
1242
+ //#region src/projector/project-facts.ts
1243
+ /**
1244
+ * The §4.3 SMALL PROJECTION TRANSACTION — the idempotent write runtime for
1245
+ * rows ALREADY MAPPED by the domain:
1246
+ *
1247
+ * 1. OUTSIDE the transaction: query which dedupeKeys already exist in this
1248
+ * generation. Already-projected occurrences drive NOTHING — this is what
1249
+ * makes at-least-once redelivery unable to double-`$inc` the rollup.
1250
+ * 2. In ONE mongokit `withTransaction`: insert ONLY the new facts (session)
1251
+ * + apply the per-grain rollup `$inc` upserts (session) derived from
1252
+ * those same new facts. Facts and rollup commit or abort TOGETHER — a
1253
+ * crash can never leave a fact counted (or uncounted) in the rollup.
1254
+ *
1255
+ * Scope stays SMALL by construction: one event's facts (a handful of rows)
1256
+ * and their few grain rows — never a loop over history.
1257
+ *
1258
+ * Concurrency: a racing duplicate delivery that slips past step 1 hits the
1259
+ * unique `{generation, dedupeKey}` index INSIDE the transaction; any write
1260
+ * error there aborts the whole txn and rethrows — the relay retries, and the
1261
+ * next attempt's step-1 read sees the winner's rows and no-ops. Same-grain
1262
+ * `$inc` write conflicts between concurrent transactions surface as
1263
+ * TransientTransactionError, which `session.withTransaction` auto-retries.
1264
+ *
1265
+ * Fallback (standalone Mongo — dev/unit tests only, via the engine's
1266
+ * `allowNonTransactional` flag, the codebase-wide `allowFallback`
1267
+ * convention): the callback re-runs once WITHOUT a transaction on the same
1268
+ * session. There a duplicate-only insert error does NOT abort anything, so
1269
+ * the rollup is applied for exactly the subset of facts that actually
1270
+ * inserted (writeErrors indexes) — the fact↔rollup invariant holds in both
1271
+ * modes. Production hosts leave the flag false: a deployment running a
1272
+ * projection must be transactional.
1273
+ *
1274
+ * Any failure THROWS — the relay retry/backoff/dead-letter contract is
1275
+ * unchanged (a swallowed error would ack an unprojected row — forbidden).
1276
+ */
1277
+ /**
1278
+ * Persist one batch's facts for ONE generation plus the matching rollup
1279
+ * `$inc` upserts — see module docblock. All rows MUST carry the same
1280
+ * `generation` (the engine's per-generation loop guarantees it).
1281
+ */
1282
+ async function projectFactsForGeneration(deps, facts) {
1283
+ if (facts.length === 0) return;
1284
+ const generation = facts[0].generation;
1285
+ const batchKeys = /* @__PURE__ */ new Set();
1286
+ for (const fact of facts) {
1287
+ if (batchKeys.has(fact.dedupeKey)) throw new Error(`${deps.name} fact projector: duplicate dedupeKey '${fact.dedupeKey}' within one input batch`);
1288
+ batchKeys.add(fact.dedupeKey);
1289
+ }
1290
+ const keys = facts.map((f) => f.dedupeKey);
1291
+ const existing = await deps.factModel.find({
1292
+ generation,
1293
+ dedupeKey: { $in: keys }
1294
+ }).select("dedupeKey").lean();
1295
+ const existingKeys = new Set(existing.map((r) => r.dedupeKey));
1296
+ const newFacts = facts.filter((f) => !existingKeys.has(f.dedupeKey));
1297
+ if (newFacts.length === 0) return;
1298
+ await withTransaction(deps.connection, async (session) => {
1299
+ const inTransaction = session.inTransaction();
1300
+ let rolledUp = newFacts;
1301
+ try {
1302
+ await deps.factModel.insertMany(newFacts, {
1303
+ ordered: false,
1304
+ session,
1305
+ throwOnValidationError: true
1306
+ });
1307
+ } catch (err) {
1308
+ if (inTransaction || !isDuplicateKeyOnly(err)) throw err;
1309
+ rolledUp = subtractFailedInserts(newFacts, err);
1310
+ }
1311
+ for (const { grain, civilWeek, civilMonth, inc } of incrementsFromFacts(deps.rollup, rolledUp)) await deps.rollupModel.findOneAndUpdate(grain, {
1312
+ $inc: inc,
1313
+ $set: { updatedAt: /* @__PURE__ */ new Date() },
1314
+ $setOnInsert: {
1315
+ schemaVersion: deps.rollupSchemaVersion,
1316
+ ...deps.derivedWeek ? { civilWeek } : {},
1317
+ ...deps.derivedMonth ? { civilMonth } : {}
1318
+ }
1319
+ }, {
1320
+ upsert: true,
1321
+ session
1322
+ });
1323
+ }, {
1324
+ allowFallback: deps.allowNonTransactional,
1325
+ onFallback: () => {
1326
+ if (deps.warnedNonTransactional.value) return;
1327
+ deps.warnedNonTransactional.value = true;
1328
+ deps.logger.warn({
1329
+ marker: "FACT_PROJECTION_NON_TRANSACTIONAL",
1330
+ projection: deps.name
1331
+ }, `fact projector [${deps.name}]: transactions unsupported (standalone Mongo) — projecting facts+rollup NON-ATOMICALLY (dev/test only; production fails closed). Drift, if any, heals via rollup rebuild.`);
1332
+ }
1333
+ });
1334
+ }
1335
+ //#endregion
1336
+ //#region src/reconcile/reconcile.ts
1337
+ const CIVIL_DATE_RE$3 = /^\d{4}-\d{2}-\d{2}$/;
1338
+ function cellKey(civilDate, dims, values) {
1339
+ return JSON.stringify([civilDate, ...dims.map((d) => values[d] ?? "")]);
1340
+ }
1341
+ function bump(map, key, measures, measure, amount) {
1342
+ if (amount === 0) return;
1343
+ let totals = map.get(key);
1344
+ if (!totals) {
1345
+ totals = {};
1346
+ for (const m of measures) totals[m] = 0;
1347
+ map.set(key, totals);
1348
+ }
1349
+ totals[measure] = (totals[measure] ?? 0) + amount;
1350
+ }
1351
+ /**
1352
+ * Compare fact totals vs source totals per (civilDate × dimensions ×
1353
+ * measure) over the inclusive civil-date window. Returns only non-zero
1354
+ * drifts plus a summary. Read-only — never writes.
1355
+ */
1356
+ async function reconcileFacts(deps, options) {
1357
+ const { generation, from, to, sources } = options;
1358
+ const dims = options.dimensions ?? [];
1359
+ if (!Number.isSafeInteger(generation) || generation < 1) throw new Error(`${deps.name} fact reconcile: invalid generation ${generation}`);
1360
+ if (!CIVIL_DATE_RE$3.test(from) || !CIVIL_DATE_RE$3.test(to)) throw new Error(`${deps.name} fact reconcile: invalid window '${from}'..'${to}' — expected YYYY-MM-DD`);
1361
+ if (from > to) throw new Error(`${deps.name} fact reconcile: from '${from}' is after to '${to}'`);
1362
+ if (sources.length === 0) throw new Error(`${deps.name} fact reconcile: at least one source is required`);
1363
+ const unknownDimension = dims.find((dimension) => !deps.factDimensionNames.includes(dimension));
1364
+ if (unknownDimension) throw new Error(`${deps.name} fact reconcile: unknown dimension '${unknownDimension}'`);
1365
+ if (new Set(dims).size !== dims.length) throw new Error(`${deps.name} fact reconcile: dimensions must be unique`);
1366
+ const sourceNames = sources.map((source) => source.name);
1367
+ if (new Set(sourceNames).size !== sourceNames.length) throw new Error(`${deps.name} fact reconcile: source names must be unique`);
1368
+ const measureSet = /* @__PURE__ */ new Set();
1369
+ for (const source of sources) {
1370
+ if (source.measures.length === 0) throw new Error(`${deps.name} fact reconcile: source '${source.name}' must declare at least one measure`);
1371
+ if (new Set(source.measures).size !== source.measures.length) throw new Error(`${deps.name} fact reconcile: source '${source.name}' measures must be unique`);
1372
+ for (const m of source.measures) {
1373
+ if (!deps.factMeasureNames.includes(m)) throw new Error(`${deps.name} fact reconcile: source '${source.name}' claims unknown measure '${m}'`);
1374
+ measureSet.add(m);
1375
+ }
1376
+ }
1377
+ const measures = [...measureSet];
1378
+ const aggMeasures = {};
1379
+ for (const m of measures) aggMeasures[m] = {
1380
+ op: "sum",
1381
+ field: m
1382
+ };
1383
+ const { rows } = await deps.factsRepository.aggregate({
1384
+ filter: {
1385
+ generation,
1386
+ civilDate: {
1387
+ $gte: from,
1388
+ $lte: to
1389
+ }
1390
+ },
1391
+ groupBy: ["civilDate", ...dims],
1392
+ measures: aggMeasures
1393
+ });
1394
+ const factTotals = /* @__PURE__ */ new Map();
1395
+ const cellDimValues = /* @__PURE__ */ new Map();
1396
+ for (const row of rows) {
1397
+ const civilDate = row.civilDate;
1398
+ if (typeof civilDate !== "string") continue;
1399
+ const values = {};
1400
+ for (const d of dims) values[d] = row[d] != null ? String(row[d]) : "";
1401
+ const key = cellKey(civilDate, dims, values);
1402
+ cellDimValues.set(key, values);
1403
+ for (const m of measures) {
1404
+ const v = row[m];
1405
+ bump(factTotals, key, measures, m, typeof v === "number" ? v : Number(v ?? 0));
1406
+ }
1407
+ }
1408
+ const sourceTotals = /* @__PURE__ */ new Map();
1409
+ for (const source of sources) {
1410
+ const sourceRows = await source.aggregate({
1411
+ from,
1412
+ to
1413
+ });
1414
+ for (const row of sourceRows) {
1415
+ if (!CIVIL_DATE_RE$3.test(row.civilDate)) throw new Error(`${deps.name} fact reconcile: source '${source.name}' returned invalid civilDate '${row.civilDate}'`);
1416
+ if (row.civilDate < from || row.civilDate > to) continue;
1417
+ const values = {};
1418
+ for (const d of dims) values[d] = row.dimensions?.[d] ?? "";
1419
+ const key = cellKey(row.civilDate, dims, values);
1420
+ if (!cellDimValues.has(key)) cellDimValues.set(key, values);
1421
+ for (const m of source.measures) {
1422
+ const total = row.totals[m] ?? 0;
1423
+ if (!Number.isSafeInteger(total)) throw new Error(`${deps.name} fact reconcile: source '${source.name}' returned non-safe-integer total for '${m}'`);
1424
+ bump(sourceTotals, key, measures, m, total);
1425
+ }
1426
+ }
1427
+ }
1428
+ const cells = /* @__PURE__ */ new Set([...factTotals.keys(), ...sourceTotals.keys()]);
1429
+ const drifts = [];
1430
+ let cellsCompared = 0;
1431
+ for (const key of [...cells].sort()) {
1432
+ const [civilDate] = JSON.parse(key);
1433
+ const dimensions = cellDimValues.get(key) ?? {};
1434
+ const fact = factTotals.get(key) ?? {};
1435
+ const source = sourceTotals.get(key) ?? {};
1436
+ for (const measure of measures) {
1437
+ cellsCompared += 1;
1438
+ const factTotal = fact[measure] ?? 0;
1439
+ const sourceTotal = source[measure] ?? 0;
1440
+ const drift = factTotal - sourceTotal;
1441
+ if (drift !== 0) drifts.push({
1442
+ civilDate,
1443
+ dimensions,
1444
+ measure,
1445
+ factTotal,
1446
+ sourceTotal,
1447
+ drift
1448
+ });
1449
+ }
1450
+ }
1451
+ return {
1452
+ drifts,
1453
+ summary: {
1454
+ generation,
1455
+ from,
1456
+ to,
1457
+ cellsCompared,
1458
+ driftCount: drifts.length,
1459
+ clean: drifts.length === 0
1460
+ }
1461
+ };
1462
+ }
1463
+ //#endregion
1464
+ //#region src/freshness/freshness.ts
1465
+ const DEFAULT_MAX_LAG_MS = 6e4;
1466
+ /** The freshness block — two indexed reads + the cached manifest. */
1467
+ async function getProjectionFreshness(manifest, source, options = {}) {
1468
+ const maxLagMs = options.maxLagMs ?? 6e4;
1469
+ const [oldestPendingAgeMs, manifestDoc, projectedThroughRaw] = await Promise.all([
1470
+ source.oldestPendingAgeMs(),
1471
+ manifest.getManifest(),
1472
+ source.newestDeliveredInstant ? source.newestDeliveredInstant() : Promise.resolve(null)
1473
+ ]);
1474
+ const lagMs = oldestPendingAgeMs ?? 0;
1475
+ const state = manifestDoc?.state ?? "active";
1476
+ return {
1477
+ projectedThrough: projectedThroughRaw != null && !Number.isNaN(projectedThroughRaw.getTime()) ? projectedThroughRaw : null,
1478
+ lagMs,
1479
+ status: state !== "active" ? "rebuilding" : lagMs > maxLagMs ? "delayed" : "fresh"
1480
+ };
1481
+ }
1482
+ //#endregion
1483
+ //#region src/rollup/rebuild.ts
1484
+ const CIVIL_DATE_RE$2 = /^\d{4}-\d{2}-\d{2}$/;
1485
+ /**
1486
+ * Merge raw per-(rawGrain) aggregate rows into sentinel-normalized rollup
1487
+ * rows, summing measures. Pure (exported for unit tests). Rows missing
1488
+ * `civilDate` are skipped defensively (it is a required fact field).
1489
+ */
1490
+ function mergeFactRowsByNormalizedGrain(rollup, generation, rows) {
1491
+ const map = /* @__PURE__ */ new Map();
1492
+ for (const row of rows) {
1493
+ const civilDate = row.civilDate;
1494
+ if (typeof civilDate !== "string" || civilDate.length === 0) continue;
1495
+ const grain = {
1496
+ generation,
1497
+ civilDate
1498
+ };
1499
+ const keyParts = [civilDate];
1500
+ for (const dim of rollup.grain) {
1501
+ const normalized = normalizeDim(row[dim]);
1502
+ grain[dim] = normalized;
1503
+ keyParts.push(normalized);
1504
+ }
1505
+ const key = JSON.stringify(keyParts);
1506
+ let entry = map.get(key);
1507
+ if (!entry) {
1508
+ const totals = {};
1509
+ for (const measure of rollup.measures) totals[measure] = 0;
1510
+ totals.factCount = 0;
1511
+ entry = {
1512
+ grain,
1513
+ totals
1514
+ };
1515
+ map.set(key, entry);
1516
+ }
1517
+ for (const measure of rollup.measures) {
1518
+ const context = `rebuild ${civilDate} ${keyParts.slice(1).join(" ")} ${measure}`;
1519
+ entry.totals[measure] = (entry.totals[measure] ?? 0) + rollupMeasureToNumber(row[measure], context);
1520
+ }
1521
+ entry.totals.factCount = (entry.totals.factCount ?? 0) + rollupMeasureToNumber(row.factCount, `rebuild factCount ${civilDate}`);
1522
+ }
1523
+ return [...map.values()];
1524
+ }
1525
+ /** Last civil date of the chunk starting at `from`, capped at `to`. */
1526
+ function chunkEnd(from, to, batchDays) {
1527
+ let end = from;
1528
+ for (let i = 1; i < batchDays; i += 1) {
1529
+ const next = nextCivilDate(end);
1530
+ if (next > to) break;
1531
+ end = next;
1532
+ }
1533
+ return end > to ? to : end;
1534
+ }
1535
+ /**
1536
+ * Re-aggregate facts → rollup for a generation over a bounded civil-date
1537
+ * window. See module docblock for semantics and the documented live-write
1538
+ * race.
1539
+ */
1540
+ async function rebuildRollupFromFacts(deps, options) {
1541
+ const { generation, batchDays = 7, log = () => {} } = options;
1542
+ if (!Number.isInteger(generation) || generation < 1) throw new Error(`${deps.name} rollup rebuild: invalid generation ${generation}`);
1543
+ for (const [name, value] of [["from", options.from], ["to", options.to]]) if (value !== void 0 && !CIVIL_DATE_RE$2.test(value)) throw new Error(`${deps.name} rollup rebuild: --${name} must be YYYY-MM-DD (got '${value}')`);
1544
+ let from = options.from ?? null;
1545
+ let to = options.to ?? null;
1546
+ if (!from || !to) {
1547
+ const { rows } = await deps.factsRepository.aggregate({
1548
+ filter: { generation },
1549
+ measures: {
1550
+ min: {
1551
+ op: "min",
1552
+ field: "civilDate"
1553
+ },
1554
+ max: {
1555
+ op: "max",
1556
+ field: "civilDate"
1557
+ }
1558
+ }
1559
+ });
1560
+ from = from ?? rows[0]?.min ?? null;
1561
+ to = to ?? rows[0]?.max ?? null;
1562
+ }
1563
+ if (!from || !to || from > to) {
1564
+ log(`[rollup-rebuild:${deps.name}] generation ${generation}: no facts in window — nothing to rebuild`);
1565
+ return {
1566
+ generation,
1567
+ from: null,
1568
+ to: null,
1569
+ days: 0,
1570
+ rows: 0,
1571
+ deleted: 0
1572
+ };
1573
+ }
1574
+ let totalRows = 0;
1575
+ let totalDeleted = 0;
1576
+ let days = 0;
1577
+ let cursor = from;
1578
+ for (;;) {
1579
+ const end = chunkEnd(cursor, to, batchDays);
1580
+ const measures = {};
1581
+ for (const measure of deps.rollup.measures) measures[measure] = {
1582
+ op: "sum",
1583
+ field: measure
1584
+ };
1585
+ measures.factCount = { op: "count" };
1586
+ const { rows } = await deps.factsRepository.aggregate({
1587
+ filter: {
1588
+ generation,
1589
+ civilDate: {
1590
+ $gte: cursor,
1591
+ $lte: end
1592
+ }
1593
+ },
1594
+ groupBy: ["civilDate", ...deps.rollup.grain],
1595
+ measures
1596
+ });
1597
+ const merged = mergeFactRowsByNormalizedGrain(deps.rollup, generation, rows);
1598
+ const deleted = await deps.rollupModel.deleteMany({
1599
+ generation,
1600
+ civilDate: {
1601
+ $gte: cursor,
1602
+ $lte: end
1603
+ }
1604
+ });
1605
+ totalDeleted += deleted.deletedCount ?? 0;
1606
+ if (merged.length > 0) {
1607
+ const now = /* @__PURE__ */ new Date();
1608
+ const ops = merged.map(({ grain, totals }) => ({ updateOne: {
1609
+ filter: { ...grain },
1610
+ update: {
1611
+ $set: {
1612
+ ...totals,
1613
+ updatedAt: now
1614
+ },
1615
+ $setOnInsert: {
1616
+ schemaVersion: deps.rollupSchemaVersion,
1617
+ ...deps.derivedWeek ? { civilWeek: isoWeekOfCivilDate(grain.civilDate) } : {},
1618
+ ...deps.derivedMonth ? { civilMonth: grain.civilDate.slice(0, 7) } : {}
1619
+ }
1620
+ },
1621
+ upsert: true
1622
+ } }));
1623
+ await deps.rollupModel.bulkWrite(ops, { ordered: false });
1624
+ totalRows += merged.length;
1625
+ }
1626
+ let d = cursor;
1627
+ let chunkDays = 1;
1628
+ while (d < end) {
1629
+ d = nextCivilDate(d);
1630
+ chunkDays += 1;
1631
+ }
1632
+ days += chunkDays;
1633
+ log(`[rollup-rebuild:${deps.name}] gen=${generation} ${cursor}..${end}: rows=${merged.length} deleted=${deleted.deletedCount ?? 0}`);
1634
+ if (end >= to) break;
1635
+ cursor = nextCivilDate(end);
1636
+ }
1637
+ return {
1638
+ generation,
1639
+ from,
1640
+ to,
1641
+ days,
1642
+ rows: totalRows,
1643
+ deleted: totalDeleted
1644
+ };
1645
+ }
1646
+ //#endregion
1647
+ //#region src/purge/purge.ts
1648
+ /**
1649
+ * Generation / occurrence / window PURGE composition — the retention +
1650
+ * right-to-be-forgotten surface built ENTIRELY on the repositories' native
1651
+ * compliance primitives (mongokit `purgeByField` equality + `purgeByFilter`
1652
+ * range/compound). NO hand-rolled `Model.deleteMany` / raw queries on the
1653
+ * fact + rollup collections: every purge routes through the repository so its
1654
+ * hook pipeline (audit, cache, capability gate) still fires, and the chunked
1655
+ * `runChunkedPurge` orchestrator bounds memory / lock contention.
1656
+ *
1657
+ * Three composed operations close three distinct leaks:
1658
+ *
1659
+ * 1. `purgeGeneration(gen)` — hard-drops a RETIRED (or aborted) generation's
1660
+ * facts + rollup + checkpoints. Closes the cutover LEAK: `cutover()`
1661
+ * retains the old generation for the rollback window but nothing deletes
1662
+ * it afterwards. GUARDED — refuses the live active/rebuild generation.
1663
+ * 2. `purgeOccurrence(dedupeKey)` — hard-deletes one business occurrence's
1664
+ * fact rows (source-doc erasure companion), optionally rebuilding the
1665
+ * affected civilDate rollup window so the aggregate stays consistent.
1666
+ * 3. `anonymizeFactWindow(...)` — REDACTS PII dimensions across a civilDate
1667
+ * RANGE while RETAINING the integer measures (GDPR / retention path),
1668
+ * via `purgeByFilter` with the repo-core Filter IR + `anonymize` strategy.
1669
+ *
1670
+ * ## Evidence (rule 5.5 — host owns durability)
1671
+ *
1672
+ * This module NEVER persists `PurgeEvidence`. Each result returns enough
1673
+ * (`scope`, `strategy`, `processed`, `measuresRetained`) for a host to build a
1674
+ * `@classytic/primitives/retention` `PurgeEvidence` record alongside the
1675
+ * mutation and persist it in its own audit store. facts stays a pure kernel.
1676
+ */
1677
+ const CIVIL_DATE_RE$1 = /^\d{4}-\d{2}-\d{2}$/;
1678
+ /** Chunking opts without tripping exactOptionalPropertyTypes on `undefined`. */
1679
+ function chunkOptions(batchSize) {
1680
+ return batchSize !== void 0 ? { batchSize } : {};
1681
+ }
1682
+ /**
1683
+ * A native purge NEVER throws for in-strategy errors — it wraps them into
1684
+ * `result.error` and returns `ok: false`. Fail LOUD instead of silently
1685
+ * reporting a partial count as success.
1686
+ */
1687
+ function assertPurgeOk(result, deps, op) {
1688
+ if (!result.ok) throw new FactsError({
1689
+ status: 500,
1690
+ code: "facts.purge.failed",
1691
+ message: `${deps.name} ${op}: purge did not complete — ${result.error?.message ?? "unknown error"} (chunkOffset ${result.error?.chunkOffset ?? "?"}, processed ${result.processed})`,
1692
+ meta: {
1693
+ op,
1694
+ processed: result.processed,
1695
+ error: result.error
1696
+ }
1697
+ });
1698
+ return result;
1699
+ }
1700
+ function assertCivilDate(deps, op, name, value) {
1701
+ if (!CIVIL_DATE_RE$1.test(value)) throw new FactsError({
1702
+ status: 400,
1703
+ code: "facts.purge.invalid_window",
1704
+ message: `${deps.name} ${op}: ${name} must be YYYY-MM-DD (got '${value}')`,
1705
+ meta: {
1706
+ op,
1707
+ [name]: value
1708
+ }
1709
+ });
1710
+ }
1711
+ /**
1712
+ * Hard-purge a RETIRED generation's facts + rollup + checkpoints.
1713
+ *
1714
+ * GUARD: reads the manifest and REFUSES if `gen` is the live
1715
+ * `activeGeneration` or an in-flight `rebuildGeneration` — a live generation
1716
+ * is never purgeable (readers resolve to active; the projector dual-writes to
1717
+ * the rebuild gen). Facts + rollup route through the native repository
1718
+ * `purgeByField('generation', gen, {type:'hard'})` (equality-bound chunked
1719
+ * purge); checkpoints are internal bookkeeping (no Repository) so the model's
1720
+ * `deleteMany` is the sanctioned path there.
1721
+ */
1722
+ async function purgeGeneration(deps, gen, options = {}) {
1723
+ if (!Number.isInteger(gen) || gen < 1) throw new FactsError({
1724
+ status: 400,
1725
+ code: "facts.purge.invalid_generation",
1726
+ message: `${deps.name} purgeGeneration: generation must be an integer ≥ 1 (got ${gen})`,
1727
+ meta: { generation: gen }
1728
+ });
1729
+ const manifest = await deps.getManifest();
1730
+ const active = manifest?.activeGeneration ?? 1;
1731
+ const rebuild = manifest?.rebuildGeneration;
1732
+ if (gen === active || gen === rebuild) throw new FactsError({
1733
+ status: 409,
1734
+ code: "facts.purge.live_generation",
1735
+ message: `${deps.name} purgeGeneration: refused — generation ${gen} is LIVE (active=${active}${typeof rebuild === "number" ? `, rebuild=${rebuild}` : ""}). Only a retired or aborted generation may be purged; cut over / abort first.`,
1736
+ meta: {
1737
+ generation: gen,
1738
+ active,
1739
+ ...typeof rebuild === "number" ? { rebuild } : {}
1740
+ }
1741
+ });
1742
+ const opts = chunkOptions(options.batchSize);
1743
+ const factsResult = assertPurgeOk(await deps.factsRepository.purgeByField("generation", gen, { type: "hard" }, opts), deps, "purgeGeneration.facts");
1744
+ const rollupResult = assertPurgeOk(await deps.rollupRepository.purgeByField("generation", gen, { type: "hard" }, opts), deps, "purgeGeneration.rollup");
1745
+ const checkpointsResult = await deps.checkpointModel.deleteMany({ generation: gen });
1746
+ return {
1747
+ facts: factsResult.processed,
1748
+ rollup: rollupResult.processed,
1749
+ checkpoints: checkpointsResult.deletedCount ?? 0,
1750
+ scope: `generation:${gen}`,
1751
+ strategy: "hard",
1752
+ measuresRetained: false
1753
+ };
1754
+ }
1755
+ /**
1756
+ * Hard-delete every fact row for one business occurrence (`dedupeKey`) — the
1757
+ * companion to source-document erasure. Optionally rebuilds the affected
1758
+ * civilDate rollup window(s) so the aggregate no longer counts the removed
1759
+ * occurrence. Routes through the native repository `purgeByField('dedupeKey',
1760
+ * …, {type:'hard'})`; the rebuild reuses the EXISTING deterministic
1761
+ * `rebuildRollup({generation, from, to})`.
1762
+ */
1763
+ async function purgeOccurrence(deps, dedupeKey, options = {}) {
1764
+ if (typeof dedupeKey !== "string" || dedupeKey.length === 0) throw new FactsError({
1765
+ status: 400,
1766
+ code: "facts.purge.invalid_dedupe_key",
1767
+ message: `${deps.name} purgeOccurrence: dedupeKey must be a non-empty string`
1768
+ });
1769
+ if (options.from !== void 0) assertCivilDate(deps, "purgeOccurrence", "from", options.from);
1770
+ if (options.to !== void 0) assertCivilDate(deps, "purgeOccurrence", "to", options.to);
1771
+ let windows = [];
1772
+ if (options.rebuild) {
1773
+ const affected = await deps.factModel.find({ dedupeKey }).select({
1774
+ generation: 1,
1775
+ civilDate: 1
1776
+ }).lean().exec();
1777
+ const byGen = /* @__PURE__ */ new Map();
1778
+ for (const row of affected) {
1779
+ if (typeof row.civilDate !== "string" || row.civilDate.length === 0) continue;
1780
+ const entry = byGen.get(row.generation);
1781
+ if (!entry) byGen.set(row.generation, {
1782
+ min: row.civilDate,
1783
+ max: row.civilDate
1784
+ });
1785
+ else {
1786
+ if (row.civilDate < entry.min) entry.min = row.civilDate;
1787
+ if (row.civilDate > entry.max) entry.max = row.civilDate;
1788
+ }
1789
+ }
1790
+ windows = [...byGen.entries()].map(([generation, { min, max }]) => ({
1791
+ generation,
1792
+ from: options.from ?? min,
1793
+ to: options.to ?? max
1794
+ }));
1795
+ }
1796
+ const result = assertPurgeOk(await deps.factsRepository.purgeByField("dedupeKey", dedupeKey, { type: "hard" }, {}), deps, "purgeOccurrence");
1797
+ let rebuilt = false;
1798
+ if (options.rebuild) {
1799
+ for (const window of windows) await deps.rebuildRollup(window);
1800
+ rebuilt = true;
1801
+ }
1802
+ return {
1803
+ facts: result.processed,
1804
+ ...options.rebuild ? { rebuilt } : {},
1805
+ scope: `occurrence:${dedupeKey}`,
1806
+ strategy: "hard",
1807
+ measuresRetained: false
1808
+ };
1809
+ }
1810
+ /**
1811
+ * Redact PII dimensions across a civilDate RANGE while RETAINING the integer
1812
+ * measures — the GDPR / retention "anonymize a slice, keep the aggregates"
1813
+ * path. Built on the native `purgeByFilter(filter, {type:'anonymize', fields})`
1814
+ * with the repo-core Filter IR: `and(eq(generation), gte(civilDate, from),
1815
+ * lte(civilDate, to))` plus optional extra dimension equality clauses. NO raw
1816
+ * query — the IR compiles through mongokit's `compileFilterToMongo` like every
1817
+ * other verb. `fields` is the `$set` redaction patch; measures are untouched.
1818
+ *
1819
+ * ## Grain-dimension guard (facts↔rollup consistency)
1820
+ *
1821
+ * Redacting a dimension that is part of `rollup.grain` shifts the matching
1822
+ * fact rows to the `'(none)'` sentinel while the rollup grain rows keep the old
1823
+ * value — a silent divergence the serving rollup would carry until someone
1824
+ * rebuilds. So a `fields` key intersecting the grain is REJECTED by default
1825
+ * (the safe outcome — a redaction must never quietly corrupt the aggregate).
1826
+ * `{ rebuild: true }` opts into re-deriving the affected civilDate window's
1827
+ * rollup from the redacted facts afterwards — the SAME `rebuildRollup` path
1828
+ * `purgeOccurrence` uses — so the aggregate reconverges instead.
1829
+ */
1830
+ async function anonymizeFactWindow(deps, options) {
1831
+ const { generation, from, to, fields, dimensions } = options;
1832
+ if (!Number.isInteger(generation) || generation < 1) throw new FactsError({
1833
+ status: 400,
1834
+ code: "facts.purge.invalid_generation",
1835
+ message: `${deps.name} anonymizeFactWindow: generation must be an integer ≥ 1 (got ${generation})`,
1836
+ meta: { generation }
1837
+ });
1838
+ assertCivilDate(deps, "anonymizeFactWindow", "from", from);
1839
+ assertCivilDate(deps, "anonymizeFactWindow", "to", to);
1840
+ if (from > to) throw new FactsError({
1841
+ status: 400,
1842
+ code: "facts.purge.invalid_window",
1843
+ message: `${deps.name} anonymizeFactWindow: from '${from}' is after to '${to}'`,
1844
+ meta: {
1845
+ from,
1846
+ to
1847
+ }
1848
+ });
1849
+ if (!fields || typeof fields !== "object" || Object.keys(fields).length === 0) throw new FactsError({
1850
+ status: 400,
1851
+ code: "facts.purge.empty_fields",
1852
+ message: `${deps.name} anonymizeFactWindow: fields must be a non-empty redaction patch (e.g. { customerId: null }) — an anonymize with no fields would mutate nothing.`
1853
+ });
1854
+ const grainRedacted = Object.keys(fields).filter((key) => deps.rollupGrain.includes(key));
1855
+ if (grainRedacted.length > 0 && !options.rebuild) throw new FactsError({
1856
+ status: 409,
1857
+ code: "facts.purge.grain_redaction",
1858
+ message: `${deps.name} anonymizeFactWindow: refused — field(s) [${grainRedacted.join(", ")}] are part of the rollup grain [${deps.rollupGrain.join(", ")}]. Redacting a grain dimension shifts facts to the '(none)' sentinel while the rollup keeps the old value (silent facts↔rollup divergence). Pass { rebuild: true } to re-derive the affected rollup window after redaction, or redact a non-grain field.`,
1859
+ meta: {
1860
+ grainRedacted,
1861
+ grain: [...deps.rollupGrain]
1862
+ }
1863
+ });
1864
+ const clauses = [
1865
+ eq("generation", generation),
1866
+ gte("civilDate", from),
1867
+ lte("civilDate", to)
1868
+ ];
1869
+ if (dimensions) for (const [key, value] of Object.entries(dimensions)) clauses.push(eq(key, value));
1870
+ const filter = and(...clauses);
1871
+ const result = assertPurgeOk(await deps.factsRepository.purgeByFilter(filter, {
1872
+ type: "anonymize",
1873
+ fields
1874
+ }, chunkOptions(options.batchSize)), deps, "anonymizeFactWindow");
1875
+ let rebuilt = false;
1876
+ if (grainRedacted.length > 0) {
1877
+ await deps.rebuildRollup({
1878
+ generation,
1879
+ from,
1880
+ to
1881
+ });
1882
+ rebuilt = true;
1883
+ }
1884
+ return {
1885
+ processed: result.processed,
1886
+ measuresRetained: true,
1887
+ strategy: "anonymize",
1888
+ scope: `generation:${generation}`,
1889
+ ...grainRedacted.length > 0 ? { rebuilt } : {}
1890
+ };
1891
+ }
1892
+ //#endregion
1893
+ //#region src/engine/spec-schema.ts
1894
+ /**
1895
+ * Zod-4 fail-fast validation of the {@link FactProjectionShape} plain-data
1896
+ * shape at describe time: name/collection hygiene, identifier syntax,
1897
+ * reserved-system-field collisions, measure/dimension/marker name collisions,
1898
+ * grain ⊆ dimensions, rollup measures ⊆ fact measures.
1899
+ *
1900
+ * The `civil` source port is a runtime (not data) collaborator and is checked
1901
+ * separately at `bind`.
1902
+ */
1903
+ /** Lowercase slug — manifest doc id + model-name namespace. */
1904
+ const NAME_RE = /^[a-z][a-z0-9_-]*$/;
1905
+ /** Field identifiers (dimensions, measures, markers). */
1906
+ const IDENT_RE = /^[A-Za-z][A-Za-z0-9_]*$/;
1907
+ /**
1908
+ * System field names owned by the engine — a domain dimension, measure or
1909
+ * marker may never shadow one.
1910
+ */
1911
+ const RESERVED_FACT_FIELDS = [
1912
+ "_id",
1913
+ "__v",
1914
+ "generation",
1915
+ "dedupeKey",
1916
+ "eventId",
1917
+ "eventType",
1918
+ "schemaVersion",
1919
+ "occurredAt",
1920
+ "recordedAt",
1921
+ "civilDate",
1922
+ "civilWeek",
1923
+ "civilMonth",
1924
+ "factCount",
1925
+ "updatedAt"
1926
+ ];
1927
+ const identifier = z.string().regex(IDENT_RE, "must be a bare identifier ([A-Za-z][A-Za-z0-9_]*)");
1928
+ const measureSchema = z.union([identifier, z.object({
1929
+ name: identifier,
1930
+ nonNegative: z.boolean().optional()
1931
+ })]);
1932
+ const indexSchema = z.object({
1933
+ fields: z.record(z.string().min(1), z.union([z.literal(1), z.literal(-1)])),
1934
+ comment: z.string().min(1, "rule 34 — every index names the query it supports"),
1935
+ options: z.record(z.string(), z.unknown()).optional()
1936
+ });
1937
+ const collectionName = z.string().min(1);
1938
+ const specDataSchema = z.object({
1939
+ name: z.string().regex(NAME_RE, "must be a lowercase slug (e.g. 'sales')"),
1940
+ collections: z.object({
1941
+ facts: collectionName,
1942
+ rollup: collectionName,
1943
+ manifest: collectionName,
1944
+ checkpoints: collectionName
1945
+ }),
1946
+ fact: z.object({
1947
+ dimensions: z.record(identifier, z.unknown()),
1948
+ measures: z.array(measureSchema).min(1),
1949
+ markers: z.record(identifier, z.object({
1950
+ values: z.array(z.string().min(1)).min(1),
1951
+ default: z.string().optional()
1952
+ })).optional(),
1953
+ extraIndexes: z.array(indexSchema).optional(),
1954
+ schemaVersion: z.number().int().min(1).optional()
1955
+ }),
1956
+ rollup: z.object({
1957
+ grain: z.array(identifier).min(1),
1958
+ measures: z.array(identifier).min(1),
1959
+ derived: z.object({
1960
+ civilWeek: z.boolean().optional(),
1961
+ civilMonth: z.boolean().optional()
1962
+ }).optional(),
1963
+ extraIndexes: z.array(indexSchema).optional(),
1964
+ schemaVersion: z.number().int().min(1).optional()
1965
+ }),
1966
+ cacheTtlMs: z.number().int().positive().optional(),
1967
+ autoIndex: z.boolean().optional(),
1968
+ forceRecreate: z.boolean().optional()
1969
+ });
1970
+ function measureName(m) {
1971
+ return typeof m === "string" ? m : m.name;
1972
+ }
1973
+ /**
1974
+ * Validate the spec's data shape and cross-field invariants; throws
1975
+ * {@link FactsSpecError} with every issue named. Returns the normalized
1976
+ * measure list (object form).
1977
+ */
1978
+ function validateSpec(spec) {
1979
+ const parsed = specDataSchema.safeParse(spec);
1980
+ if (!parsed.success) throw new FactsSpecError(parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; "));
1981
+ const problems = [];
1982
+ const data = parsed.data;
1983
+ const dimensionNames = Object.keys(data.fact.dimensions);
1984
+ const markerNames = Object.keys(data.fact.markers ?? {});
1985
+ const measures = data.fact.measures.map((m) => typeof m === "string" ? {
1986
+ name: m,
1987
+ nonNegative: false
1988
+ } : {
1989
+ name: m.name,
1990
+ nonNegative: m.nonNegative ?? false
1991
+ });
1992
+ const measureNames = measures.map((m) => m.name);
1993
+ for (const [family, names] of [
1994
+ ["fact.dimensions", dimensionNames],
1995
+ ["fact.measures", measureNames],
1996
+ ["fact.markers", markerNames]
1997
+ ]) for (const n of names) if (RESERVED_FACT_FIELDS.includes(n)) problems.push(`${family}: '${n}' is a reserved system field`);
1998
+ const seen = /* @__PURE__ */ new Map();
1999
+ for (const [family, names] of [
2000
+ ["dimension", dimensionNames],
2001
+ ["measure", measureNames],
2002
+ ["marker", markerNames]
2003
+ ]) for (const n of names) {
2004
+ const prior = seen.get(n);
2005
+ if (prior) problems.push(`'${n}' declared as both ${prior} and ${family}`);
2006
+ else seen.set(n, family);
2007
+ }
2008
+ const dupMeasures = measureNames.filter((n, i) => measureNames.indexOf(n) !== i);
2009
+ for (const n of new Set(dupMeasures)) problems.push(`fact.measures: '${n}' declared twice`);
2010
+ for (const g of data.rollup.grain) if (!dimensionNames.includes(g)) problems.push(`rollup.grain: '${g}' is not a declared fact dimension`);
2011
+ const dupGrain = data.rollup.grain.filter((n, i) => data.rollup.grain.indexOf(n) !== i);
2012
+ for (const n of new Set(dupGrain)) problems.push(`rollup.grain: '${n}' declared twice`);
2013
+ for (const m of data.rollup.measures) if (!measureNames.includes(m)) problems.push(`rollup.measures: '${m}' is not a declared fact measure`);
2014
+ const cols = Object.values(data.collections);
2015
+ if (new Set(cols).size !== cols.length) problems.push("collections: physical collection names must be distinct");
2016
+ if (problems.length > 0) throw new FactsSpecError(problems.join("; "), { problems });
2017
+ return measures;
2018
+ }
2019
+ //#endregion
2020
+ //#region src/engine/define-fact-projection.ts
2021
+ /**
2022
+ * `defineFactProjection(shape)` — the DESCRIBE/BIND blueprint for a fact
2023
+ * projection (STANDARDIZATION-PLAN §6). Splits construction into two phases:
2024
+ *
2025
+ * - **describe** (`defineFactProjection(shape)`): pure. Validates the shape
2026
+ * (Zod 4 + structural cross-field checks) and freezes the four model NAMES
2027
+ * via `defineFactProjectionModels()` (over mongokit `defineModels`). No
2028
+ * connection, no schema built, no I/O — safe at import / module-composition
2029
+ * time.
2030
+ * - **bind** (`blueprint.bind(connection, runtime)`): compiles the four
2031
+ * schemas on the supplied connection, registers the models, wires the
2032
+ * repositories + manifest + civil source port, and returns the frozen
2033
+ * {@link FactProjection}.
2034
+ *
2035
+ * The domain declares WHAT (collections, dimensions, integer measures, rollup
2036
+ * grain, marker vocabulary); the kernel owns HOW (generation manifest + dual-write
2037
+ * targets, the §4.3 idempotent projection transaction, rollup rebuild, keyset
2038
+ * backfill with checkpoints, the reconcile framework, freshness).
2039
+ *
2040
+ * This is the SOLE construction API — there is no `createFactProjection` wrapper.
2041
+ */
2042
+ const consoleLogger = {
2043
+ info: (obj, msg) => console.info(obj, msg),
2044
+ warn: (obj, msg) => console.warn(obj, msg),
2045
+ error: (obj, msg) => console.error(obj, msg)
2046
+ };
2047
+ /**
2048
+ * Describe a fact projection. Pure — validates the shape, freezes the four
2049
+ * model names, registers nothing and performs no I/O.
2050
+ */
2051
+ function defineFactProjection(shape) {
2052
+ const wshape = shape;
2053
+ const measures = validateSpec(wshape);
2054
+ const rollupSchemaVersion = shape.rollup.schemaVersion ?? 1;
2055
+ const derivedWeek = shape.rollup.derived?.civilWeek ?? true;
2056
+ const derivedMonth = shape.rollup.derived?.civilMonth ?? true;
2057
+ const modelBlueprint = defineFactProjectionModels({
2058
+ name: shape.name,
2059
+ collections: shape.collections,
2060
+ fact: wshape.fact,
2061
+ measures,
2062
+ rollup: wshape.rollup,
2063
+ ...shape.forceRecreate !== void 0 ? { forceRecreate: shape.forceRecreate } : {},
2064
+ ...shape.autoIndex !== void 0 ? { autoIndex: shape.autoIndex } : {}
2065
+ });
2066
+ return {
2067
+ id: shape.name,
2068
+ modelNames: modelBlueprint.modelNames,
2069
+ bind(connection, runtime) {
2070
+ if (!runtime.civil || typeof runtime.civil.dateOf !== "function" || typeof runtime.civil.weekOf !== "function" || typeof runtime.civil.monthOf !== "function") throw new FactsSpecError("civil must implement CivilCalendarPort { dateOf, weekOf, monthOf }");
2071
+ const civil = runtime.civil;
2072
+ const logger = runtime.logger ?? consoleLogger;
2073
+ const allowNonTransactional = runtime.allowNonTransactional ?? false;
2074
+ const models = modelBlueprint.bind(connection);
2075
+ const factsRepository = new Repository(models.Fact, [], {
2076
+ defaultLimit: 100,
2077
+ maxLimit: 1e3
2078
+ });
2079
+ const rollupRepository = new Repository(models.Rollup, [], {
2080
+ defaultLimit: 100,
2081
+ maxLimit: 1e3
2082
+ });
2083
+ const manifest = new ProjectionManifest(models.Manifest, {
2084
+ name: shape.name,
2085
+ ...shape.cacheTtlMs !== void 0 ? { cacheTtlMs: shape.cacheTtlMs } : {}
2086
+ });
2087
+ const factMeasureNames = shape.fact.measures.map(measureName);
2088
+ const factDimensionNames = Object.keys(shape.fact.dimensions);
2089
+ const projectDeps = {
2090
+ name: shape.name,
2091
+ connection,
2092
+ factModel: models.Fact,
2093
+ rollupModel: models.Rollup,
2094
+ rollup: shape.rollup,
2095
+ rollupSchemaVersion,
2096
+ derivedWeek,
2097
+ derivedMonth,
2098
+ allowNonTransactional,
2099
+ logger,
2100
+ warnedNonTransactional: { value: false }
2101
+ };
2102
+ const doRebuildRollup = (options) => rebuildRollupFromFacts({
2103
+ name: shape.name,
2104
+ factsRepository,
2105
+ rollupModel: models.Rollup,
2106
+ rollup: shape.rollup,
2107
+ rollupSchemaVersion,
2108
+ derivedWeek,
2109
+ derivedMonth
2110
+ }, options);
2111
+ const purgeDeps = {
2112
+ name: shape.name,
2113
+ factsRepository,
2114
+ rollupRepository,
2115
+ factModel: models.Fact,
2116
+ checkpointModel: models.Checkpoint,
2117
+ rollupGrain: shape.rollup.grain,
2118
+ getManifest: () => manifest.getManifest(),
2119
+ rebuildRollup: doRebuildRollup
2120
+ };
2121
+ const engine = {
2122
+ name: shape.name,
2123
+ models,
2124
+ repositories: {
2125
+ facts: factsRepository,
2126
+ rollup: rollupRepository
2127
+ },
2128
+ manifest,
2129
+ civilFields(occurredAt) {
2130
+ return civilFieldsOf(civil, occurredAt);
2131
+ },
2132
+ async projectFacts(facts, options) {
2133
+ if (facts.length === 0) return;
2134
+ const targets = [...new Set(options?.generations ?? await manifest.getGenerationTargets())];
2135
+ for (const generation of targets) {
2136
+ const rows = facts.map((f) => f.generation === generation ? f : {
2137
+ ...f,
2138
+ generation
2139
+ });
2140
+ await projectFactsForGeneration(projectDeps, rows);
2141
+ }
2142
+ },
2143
+ async rebuildRollup(options) {
2144
+ return doRebuildRollup(options);
2145
+ },
2146
+ async purgeGeneration(gen, options) {
2147
+ return purgeGeneration(purgeDeps, gen, options ?? {});
2148
+ },
2149
+ async purgeOccurrence(dedupeKey, options) {
2150
+ return purgeOccurrence(purgeDeps, dedupeKey, options ?? {});
2151
+ },
2152
+ async anonymizeFactWindow(options) {
2153
+ return anonymizeFactWindow(purgeDeps, options);
2154
+ },
2155
+ async runBackfill(options) {
2156
+ return runBackfill({
2157
+ name: shape.name,
2158
+ factModel: models.Fact,
2159
+ checkpointModel: models.Checkpoint
2160
+ }, options);
2161
+ },
2162
+ async reconcile(options) {
2163
+ return reconcileFacts({
2164
+ name: shape.name,
2165
+ factsRepository,
2166
+ factMeasureNames,
2167
+ factDimensionNames
2168
+ }, options);
2169
+ },
2170
+ async getFreshness(source, options) {
2171
+ return getProjectionFreshness(manifest, source, options ?? {});
2172
+ },
2173
+ async ensureReady(options) {
2174
+ assertFactsCapabilities(factsRepository.capabilities, allowNonTransactional);
2175
+ await ensureFactsReady(engine, options ?? {});
2176
+ },
2177
+ async syncIndexes() {
2178
+ await models.Fact.syncIndexes();
2179
+ await models.Rollup.syncIndexes();
2180
+ await models.Manifest.syncIndexes();
2181
+ await models.Checkpoint.syncIndexes();
2182
+ },
2183
+ async close() {
2184
+ manifest.invalidateCache();
2185
+ }
2186
+ };
2187
+ return engine;
2188
+ }
2189
+ };
2190
+ }
2191
+ //#endregion
2192
+ //#region src/cleanup/steps.ts
2193
+ const CIVIL_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
2194
+ /** Optional civil-date window read from operator parameters. */
2195
+ function windowOf(ctx, name) {
2196
+ const from = ctx.parameters?.from;
2197
+ const to = ctx.parameters?.to;
2198
+ for (const [label, value] of [["from", from], ["to", to]]) if (value !== void 0 && (typeof value !== "string" || !CIVIL_DATE_RE.test(value))) throw new FactsError({
2199
+ status: 400,
2200
+ code: "facts.cleanup.invalid_window",
2201
+ message: `${name}: parameter '${label}' must be YYYY-MM-DD (got '${String(value)}')`,
2202
+ meta: { [label]: value }
2203
+ });
2204
+ return {
2205
+ ...typeof from === "string" ? { from } : {},
2206
+ ...typeof to === "string" ? { to } : {}
2207
+ };
2208
+ }
2209
+ /** Per-generation fact-row counts (portable aggregate IR — no Model.aggregate). */
2210
+ async function factCountsByGeneration(projection) {
2211
+ const { rows } = await projection.repositories.facts.aggregate({
2212
+ groupBy: ["generation"],
2213
+ measures: { n: { op: "count" } }
2214
+ });
2215
+ return rows.map((r) => ({
2216
+ generation: Number(r.generation),
2217
+ n: Number(r.n ?? 0)
2218
+ })).filter((r) => Number.isInteger(r.generation) && r.generation >= 1);
2219
+ }
2220
+ /** Generations that are neither active nor an in-flight rebuild target. */
2221
+ async function retiredGenerations(projection) {
2222
+ const manifest = await projection.manifest.getManifest();
2223
+ const live = [manifest?.activeGeneration ?? 1];
2224
+ if (typeof manifest?.rebuildGeneration === "number") live.push(manifest.rebuildGeneration);
2225
+ return {
2226
+ retired: (await factCountsByGeneration(projection)).filter((c) => !live.includes(c.generation)),
2227
+ live
2228
+ };
2229
+ }
2230
+ function createProjectionCleanupSteps(projection) {
2231
+ const name = projection.name;
2232
+ return {
2233
+ rebuildRollup: {
2234
+ id: `${name}.rebuild-rollup`,
2235
+ resource: `${name} rollup`,
2236
+ destructive: false,
2237
+ rebuildActions: [`rebuild ${name} rollup from facts`],
2238
+ async estimate(ctx) {
2239
+ const window = windowOf(ctx, `${name} rebuild-rollup`);
2240
+ const filter = { generation: await projection.manifest.getActiveGeneration() };
2241
+ if (window.from || window.to) filter.civilDate = {
2242
+ ...window.from ? { $gte: window.from } : {},
2243
+ ...window.to ? { $lte: window.to } : {}
2244
+ };
2245
+ const { rows } = await projection.repositories.facts.aggregate({
2246
+ filter,
2247
+ measures: { n: { op: "count" } }
2248
+ });
2249
+ return {
2250
+ resource: `${name} rollup`,
2251
+ estimated: Number(rows[0]?.n ?? 0),
2252
+ retained: `${name} facts (rebuild source) untouched`
2253
+ };
2254
+ },
2255
+ async execute(ctx) {
2256
+ const window = windowOf(ctx, `${name} rebuild-rollup`);
2257
+ await ctx.throwIfCancelled?.();
2258
+ const generation = await projection.manifest.getActiveGeneration();
2259
+ const result = await projection.rebuildRollup({
2260
+ generation,
2261
+ ...window.from ? { from: window.from } : {},
2262
+ ...window.to ? { to: window.to } : {}
2263
+ });
2264
+ await ctx.onProgress?.({
2265
+ resource: `${name} rollup`,
2266
+ processed: result.rows,
2267
+ ...result.to ? { cursor: `civilDate:${result.to}` } : {}
2268
+ });
2269
+ return {
2270
+ resource: `${name} rollup`,
2271
+ processed: result.rows,
2272
+ ok: true
2273
+ };
2274
+ },
2275
+ async verify(ctx) {
2276
+ windowOf(ctx, `${name} rebuild-rollup`);
2277
+ const generation = await projection.manifest.getActiveGeneration();
2278
+ const extent = async (repo) => {
2279
+ const { rows } = await projection.repositories[repo].aggregate({
2280
+ filter: { generation },
2281
+ measures: {
2282
+ min: {
2283
+ op: "min",
2284
+ field: "civilDate"
2285
+ },
2286
+ max: {
2287
+ op: "max",
2288
+ field: "civilDate"
2289
+ },
2290
+ n: { op: "count" }
2291
+ }
2292
+ });
2293
+ return {
2294
+ min: rows[0]?.min ?? null,
2295
+ max: rows[0]?.max ?? null,
2296
+ n: Number(rows[0]?.n ?? 0)
2297
+ };
2298
+ };
2299
+ const [facts, rollup] = await Promise.all([extent("facts"), extent("rollup")]);
2300
+ const emptinessAgrees = facts.n === 0 === (rollup.n === 0);
2301
+ const extentMatches = facts.n === 0 || facts.min === rollup.min && facts.max === rollup.max;
2302
+ return [{
2303
+ name: `${name}.rollup.nonempty-agrees-with-facts`,
2304
+ ok: emptinessAgrees,
2305
+ detail: `facts=${facts.n} rollupRows=${rollup.n} (generation ${generation})`
2306
+ }, {
2307
+ name: `${name}.rollup.civil-extent-matches-facts`,
2308
+ ok: extentMatches,
2309
+ detail: `facts ${facts.min}..${facts.max} vs rollup ${rollup.min}..${rollup.max}`
2310
+ }];
2311
+ }
2312
+ },
2313
+ purgeRetiredGenerations: {
2314
+ id: `${name}.purge-retired-generations`,
2315
+ resource: `${name} retired generations`,
2316
+ destructive: true,
2317
+ async estimate() {
2318
+ const { retired, live } = await retiredGenerations(projection);
2319
+ const rebuildInFlight = typeof (await projection.manifest.getManifest())?.rebuildGeneration === "number";
2320
+ return {
2321
+ resource: `${name} retired generations`,
2322
+ estimated: retired.reduce((sum, r) => sum + r.n, 0),
2323
+ retained: `live generation${live.length > 1 ? "s" : ""} ${live.join(", ")} untouched`,
2324
+ ...rebuildInFlight ? { warnings: [`${name}: a rebuild is in flight — the previous generation stays live until cutover and is NOT purged`] } : {}
2325
+ };
2326
+ },
2327
+ async execute(ctx) {
2328
+ const { retired } = await retiredGenerations(projection);
2329
+ let processed = 0;
2330
+ let lastGen;
2331
+ for (const { generation } of retired) {
2332
+ await ctx.throwIfCancelled?.();
2333
+ const result = await projection.purgeGeneration(generation);
2334
+ processed += result.facts + result.rollup + result.checkpoints;
2335
+ lastGen = generation;
2336
+ await ctx.onProgress?.({
2337
+ resource: `${name} retired generations`,
2338
+ processed,
2339
+ cursor: `generation:${generation}`
2340
+ });
2341
+ }
2342
+ return {
2343
+ resource: `${name} retired generations`,
2344
+ processed,
2345
+ ok: true,
2346
+ ...lastGen !== void 0 ? { cursor: `generation:${lastGen}` } : {}
2347
+ };
2348
+ },
2349
+ async verify() {
2350
+ const { retired, live } = await retiredGenerations(projection);
2351
+ return [{
2352
+ name: `${name}.no-retired-generations-remain`,
2353
+ ok: retired.length === 0,
2354
+ detail: retired.length === 0 ? `only live generation(s) ${live.join(", ")} present` : `retired generation(s) still present: ${retired.map((r) => r.generation).join(", ")}`
2355
+ }];
2356
+ }
2357
+ }
2358
+ };
2359
+ }
2360
+ //#endregion
2361
+ export { DEFAULT_GENERATION_CACHE_TTL_MS, DEFAULT_MAX_LAG_MS, FactsCapabilityError, FactsError, FactsSpecError, REBUILD_STATES, RESERVED_FACT_FIELDS, ROLLUP_DIM_NONE, assertFactsCapabilities, assertValidQty, buildKeysetQuery, civilFieldsOf, countDuplicateWrites, createProjectionCleanupSteps, defineFactProjection, defineFactProjectionModels, ensureFactsReady, grainFromFact, incrementsFromFacts, isDuplicateKeyOnly, isoWeekOfCivilDate, mergeFactRowsByNormalizedGrain, nextCivilDate, normalizeDim, rollupMeasureToNumber, safeMulMinor, subtractFailedInserts };