@classytic/facts 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,104 +1,9 @@
1
1
  # Changelog
2
2
 
3
- ## 1.0.0 - 2026-07-29
3
+ ## Unreleased
4
4
 
5
- ### Changed
6
- - **License:** relicensed from MIT to the **Classytic Source-Available License** (Community & Commercial). Evaluation/development use remains free; production use now requires a commercial license from Classytic LLC. See `LICENSE`.
7
- - Major bump marks the license change; versions published before 1.0.0 remain under their original MIT terms.
5
+ ## 0.2.0 — 2026-11-28
8
6
 
9
- ## 0.2.0 — 2026-07-24
7
+ Peers raised to the latest published: `@classytic/mongokit >=3.47.0`, `@classytic/primitives >=0.39.0`, `@classytic/repo-core >=0.39.0`, `mongoose >=9.13.1`.
10
8
 
11
- Generation / occurrence / anonymize **purge composition** — the retention +
12
- right-to-be-forgotten surface, built ENTIRELY on the repositories' native
13
- compliance primitives (mongokit `purgeByField` equality + `purgeByFilter`
14
- range/compound via the repo-core Filter IR). No hand-rolled `deleteMany` / raw
15
- queries on facts + rollup — every purge routes through the repository so its
16
- hook pipeline (audit, cache, capability gate) fires and the chunked
17
- `runChunkedPurge` orchestrator bounds memory / lock contention.
18
-
19
- - **`purgeGeneration(gen, { batchSize? })`** → `{ facts, rollup, checkpoints, scope,
20
- strategy, measuresRetained }`. GUARDED — refuses the live `activeGeneration`
21
- or an in-flight `rebuildGeneration` (409 `facts.purge.live_generation`). Hard-
22
- drops a retired/aborted generation's facts + rollup (`purgeByField('generation',
23
- gen, {type:'hard'})`) + checkpoints (model `deleteMany` — internal bookkeeping,
24
- no Repository). Closes the retired-generation cleanup LEAK left by `cutover()`.
25
- - **`purgeOccurrence(dedupeKey, { rebuild?, from?, to? })`** → `{ facts, rebuilt?,
26
- scope, strategy, measuresRetained }`. Hard-deletes one business occurrence's
27
- fact rows (`purgeByField('dedupeKey', …, {type:'hard'})`); with `rebuild`,
28
- reads the affected `{generation, civilDate}` extent FIRST then re-derives each
29
- affected civilDate window via the existing deterministic `rebuildRollup`. The
30
- source-document-erasure companion.
31
- - **`anonymizeFactWindow({ generation, from, to, fields, dimensions? })`** →
32
- `{ processed, measuresRetained: true, strategy, scope }`. Redacts PII
33
- dimensions across a civilDate RANGE while RETAINING integer measures — the
34
- GDPR / retention path — via `purgeByFilter(and(eq(generation), gte(civilDate,
35
- from), lte(civilDate, to), …), {type:'anonymize', fields})`.
36
- - **Boot capability gate** (`ensure-ready.ts`): `purgeByField` + `purgeByFilter`
37
- added to the required-capabilities list — fail loud at boot (not mid-purge) if
38
- the backend lacks them.
39
- - Results carry `scope` / `strategy` / `processed` / `measuresRetained` so hosts
40
- can build a `@classytic/primitives/retention` `PurgeEvidence` record; facts
41
- never persists evidence (rule 5.5 — host owns durability).
42
-
43
- ### FIX 6 — generic spec typing
44
-
45
- `FactSpec` / `RollupSpec` / `FactProjectionSpec` are now generic over the
46
- declared dimension (`TDim`) + measure (`TMeasure`) name unions (both default to
47
- `string`). `createFactProjection` infers them from `fact.dimensions` /
48
- `fact.measures`; `RollupSpec.grain` + `RollupSpec.measures` use `NoInfer<…>` so
49
- they are CHECK-only positions — the compiler now verifies `grain ⊆ dimensions`
50
- and `rollup.measures ⊆ fact.measures` at un-cast call sites (runtime
51
- `validateSpec` remains the backstop; a cast / annotated `string` spec behaves
52
- exactly as before, so existing call sites are unaffected).
53
-
54
- ## 0.1.0 — 2026-07-24
55
-
56
- Initial release — the generic, domain-agnostic fact-projection kit extracted
57
- (MOVED + parameterized, not rewritten) from be-prod's sales-analytics
58
- projection machinery (erp-plan §17, phase X2).
59
-
60
- - `createFactProjection(spec)` factory (rule 19): spec declares name,
61
- connection, explicit collection names (rule 20.1), civil-calendar port,
62
- fact dimensions / integer measures / quality markers / secondaries, rollup
63
- grain + Decimal128 measures. Zod-4 fail-fast spec validation (reserved
64
- system fields, cross-family collisions, grain/measure subset rules).
65
- - Generation **manifest** (verified-cutover protocol): `beginRebuild` (with
66
- idempotent resume + demote), `markBackfillComplete`, `markVerified`
67
- (refuses non-zero drift), `cutover` (state guard + 3×TTL visibility
68
- time-guard, atomic pipeline promote), `abortRebuild`; cached
69
- `getActiveGeneration` / `getGenerationTargets` (dual-write across ALL
70
- rebuild states). Caches are engine-instance-scoped.
71
- - **`projectFacts`** — the §4.3 small projection transaction: dedupe
72
- pre-read → one mongokit `withTransaction`: only-new fact inserts +
73
- per-grain rollup `$inc` upserts; duplicate-key-only swallowing; explicit
74
- `allowNonTransactional` fallback with `subtractFailedInserts`; per-call
75
- generation targets default to the manifest (dual-write).
76
- - **Rollup engine**: `'(none)'` sentinel grain normalization, Decimal128
77
- accumulator schema, `rollupMeasureToNumber` serialization guard,
78
- `rebuildRollup` (bounded civil-date chunks via repository `AggRequest`).
79
- - **Backfill engine**: `runBackfill` over host `DocumentSource`s — keyset
80
- `_id`-asc iteration (`buildKeysetQuery`), resumable per-(checkpointId,
81
- source) checkpoints pinned to one generation, validated source ordering and
82
- batch/maxDocs/sleep bounds, insert-dup counting
83
- (`countDuplicateWrites`).
84
- - **Reconcile framework**: facts-side repository aggregation vs injected
85
- `ReconcileSource` aggregations → per-cell drift report.
86
- - **Freshness**: outbox diagnostics port + manifest →
87
- `{projectedThrough, lagMs, status}`.
88
- - Shared guards for domain mappers: `assertValidQty`, `safeMulMinor`,
89
- `isDuplicateKeyOnly` (scalar classification via mongokit's
90
- `isDuplicateKeyError`).
91
- - Same-batch duplicate dedupe keys now fail before the projection transaction;
92
- rollup/reconcile internal grouping uses collision-safe tuple encoding; and
93
- reconcile validates generations, dimensions, sources, dates and safe-integer
94
- source totals before accepting verification evidence.
95
- - Pure civil helpers: `isoWeekOfCivilDate`, `nextCivilDate`,
96
- `civilFieldsOf` + the `CivilCalendarPort` consistency contract.
97
- - `ensureReady()` boot gate (transactions/upsert capabilities + collection
98
- materialisation), `syncIndexes()` (rule 35), model-collision throw +
99
- `forceRecreate` (rule 21). No tenant plugin on projection models by
100
- design (org id is a dimension, not a scope).
101
- - Deviation from the be-prod copy (deliberate hardening): `insertMany` runs
102
- with `throwOnValidationError: true` so the schema backstop is loud —
103
- mongoose's `ordered:false` default silently skips invalid rows, which
104
- would let the rollup `$inc` count a fact that never inserted.
9
+ - `FACT_QUANTITY_SCALE`, `toQuantityMicro`, `fromQuantityMicro`, `extendMinorByQuantity`: quantities on the primitives 6-decimal grid; an off-grid or negative quantity throws. Peer `@classytic/primitives >=0.31.0`. Consumers: none to change.
package/dist/index.d.mts CHANGED
@@ -865,6 +865,24 @@ declare function isDuplicateKeyOnly(err: unknown): boolean;
865
865
  */
866
866
  declare function subtractFailedInserts<TFact extends BaseFactRow>(facts: readonly TFact[], err: unknown): TFact[];
867
867
  //#endregion
868
+ //#region src/projector/quantity.d.ts
869
+ /** Micro-units per quantity unit — the primitives grid, declared once. */
870
+ declare const FACT_QUANTITY_SCALE: number;
871
+ /**
872
+ * A non-negative quantity ON the 6-dp grid → its integer micro-unit count. THROWS on a negative,
873
+ * non-finite, off-grid (a 7th decimal) or out-of-range value — corrupt input rides the retry/DLQ
874
+ * (live) or abort (backfill) path, never a rounded fact.
875
+ */
876
+ declare function toQuantityMicro(value: number, context: string): number;
877
+ /** An integer micro-unit count → the quantity it encodes (`6_450_000` → `6.45`). THROWS on a non-integer. */
878
+ declare function fromQuantityMicro(micro: number, context: string): number;
879
+ /**
880
+ * `unitMinor × quantity` in minor units, rounded ONCE half-even (sign-symmetric) — the order
881
+ * kernel's line-total rounding (`resolvePriceBasisTotal`). Exact for a whole quantity, so it
882
+ * agrees with {@link safeMulMinor} wherever both apply. THROWS on an unsafe input or total.
883
+ */
884
+ declare function extendMinorByQuantity(unitMinor: number, quantity: number, context: string): number;
885
+ //#endregion
868
886
  //#region src/cleanup/steps.d.ts
869
887
  /** The projection surface the steps drive — everything `defineFactProjection().bind()` returns. */
870
888
  type ProjectionCleanupSource = Pick<FactProjection, 'name' | 'repositories' | 'manifest' | 'rebuildRollup' | 'purgeGeneration'>;
@@ -941,4 +959,4 @@ declare class FactsCapabilityError extends FactsError {
941
959
  });
942
960
  }
943
961
  //#endregion
944
- export { type AnonymizeFactWindowOptions, type AnonymizeFactWindowResult, type BackfillLogger, type BackfillMapContext, type BackfillMapFailure, type BackfillMapResult, type BackfillOptions, type BackfillResult, type BaseFactRow, type BaseRollupRow, type BeginRebuildResult, type CivilCalendarPort, type CivilFields, type CutoverOptions, DEFAULT_GENERATION_CACHE_TTL_MS, DEFAULT_MAX_LAG_MS, type DefineFactProjectionModelsConfig, type DocumentSource, type DriftRow, type FactDocument, type FactIndexSpec, type FactMarkerSpec, type FactMeasureSpec, type FactProjection, type FactProjectionBlueprint, type FactProjectionCollections, type FactProjectionLogger, type FactProjectionManifest, type FactProjectionModels, type FactProjectionRepositories, type FactProjectionRuntime, type FactProjectionShape, type FactSpec, FactsCapabilityError, FactsError, FactsSpecError, type FreshnessSource, type GetFreshnessOptions, type MarkBackfillCompleteOptions, type MarkVerifiedOptions, type ProjectFactsOptions, type ProjectionCheckpoint, type ProjectionCleanupSource, type ProjectionCleanupSteps, type ProjectionFreshness, type ProjectionManifestData, type ProjectionManifestState, type PurgeGenerationOptions, type PurgeGenerationResult, type PurgeOccurrenceOptions, type PurgeOccurrenceResult, REBUILD_STATES, RESERVED_FACT_FIELDS, ROLLUP_DIM_NONE, type RebuildRollupOptions, type RebuildRollupResult, type RebuildVerification, type ReconcileOptions, type ReconcileReport, type ReconcileSource, type ReconcileSourceRow, type ReconcileSummary, type ReconcileWindow, type RollupDocument, type RollupGrain, type RollupIncrement, type RollupSpec, type SourceBackfillResult, assertFactsCapabilities, assertValidQty, buildKeysetQuery, civilFieldsOf, countDuplicateWrites, createProjectionCleanupSteps, defineFactProjection, defineFactProjectionModels, ensureFactsReady, grainFromFact, incrementsFromFacts, isDuplicateKeyOnly, isoWeekOfCivilDate, mergeFactRowsByNormalizedGrain, nextCivilDate, normalizeDim, rollupMeasureToNumber, safeMulMinor, subtractFailedInserts };
962
+ export { type AnonymizeFactWindowOptions, type AnonymizeFactWindowResult, type BackfillLogger, type BackfillMapContext, type BackfillMapFailure, type BackfillMapResult, type BackfillOptions, type BackfillResult, type BaseFactRow, type BaseRollupRow, type BeginRebuildResult, type CivilCalendarPort, type CivilFields, type CutoverOptions, DEFAULT_GENERATION_CACHE_TTL_MS, DEFAULT_MAX_LAG_MS, type DefineFactProjectionModelsConfig, type DocumentSource, type DriftRow, FACT_QUANTITY_SCALE, type FactDocument, type FactIndexSpec, type FactMarkerSpec, type FactMeasureSpec, type FactProjection, type FactProjectionBlueprint, type FactProjectionCollections, type FactProjectionLogger, type FactProjectionManifest, type FactProjectionModels, type FactProjectionRepositories, type FactProjectionRuntime, type FactProjectionShape, type FactSpec, FactsCapabilityError, FactsError, FactsSpecError, type FreshnessSource, type GetFreshnessOptions, type MarkBackfillCompleteOptions, type MarkVerifiedOptions, type ProjectFactsOptions, type ProjectionCheckpoint, type ProjectionCleanupSource, type ProjectionCleanupSteps, type ProjectionFreshness, type ProjectionManifestData, type ProjectionManifestState, type PurgeGenerationOptions, type PurgeGenerationResult, type PurgeOccurrenceOptions, type PurgeOccurrenceResult, REBUILD_STATES, RESERVED_FACT_FIELDS, ROLLUP_DIM_NONE, type RebuildRollupOptions, type RebuildRollupResult, type RebuildVerification, type ReconcileOptions, type ReconcileReport, type ReconcileSource, type ReconcileSourceRow, type ReconcileSummary, type ReconcileWindow, type RollupDocument, type RollupGrain, type RollupIncrement, type RollupSpec, type SourceBackfillResult, assertFactsCapabilities, assertValidQty, buildKeysetQuery, civilFieldsOf, countDuplicateWrites, createProjectionCleanupSteps, defineFactProjection, defineFactProjectionModels, ensureFactsReady, extendMinorByQuantity, fromQuantityMicro, grainFromFact, incrementsFromFacts, isDuplicateKeyOnly, isoWeekOfCivilDate, mergeFactRowsByNormalizedGrain, nextCivilDate, normalizeDim, rollupMeasureToNumber, safeMulMinor, subtractFailedInserts, toQuantityMicro };
package/dist/index.mjs CHANGED
@@ -3,6 +3,8 @@ import { addCivilDays, civilDate } from "@classytic/primitives/timezone";
3
3
  import mongoose, { Schema, Types } from "mongoose";
4
4
  import { and, eq, gte, lte } from "@classytic/repo-core/filter";
5
5
  import { z } from "zod";
6
+ import { resolvePriceBasisTotal } from "@classytic/primitives/price-basis";
7
+ import { QUANTITY_SCALE, isOnQuantityGrid, quantityToGrid } from "@classytic/primitives/quantity";
6
8
  //#region src/civil/civil.ts
7
9
  /**
8
10
  * Civil-calendar seam of the fact projection.
@@ -568,8 +570,9 @@ var ProjectionManifest = class {
568
570
  * ## Numeric types
569
571
  *
570
572
  * 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
+ * whole units, or quantity micro-units — `projector/quantity.ts` — for a
574
+ * fractional quantity) — BSON Decimal128 is for the ROLLUP accumulators, not
575
+ * for per-occurrence rows, which are bounded by single-occurrence magnitudes.
573
576
  */
574
577
  const safeIntegerMeasure = {
575
578
  validator: Number.isSafeInteger,
@@ -2189,6 +2192,49 @@ function defineFactProjection(shape) {
2189
2192
  };
2190
2193
  }
2191
2194
  //#endregion
2195
+ //#region src/projector/quantity.ts
2196
+ /**
2197
+ * Fractional quantities as fact measures: an integer count of MICRO-units on the
2198
+ * `@classytic/primitives/quantity` grid ({@link FACT_QUANTITY_SCALE} = `QUANTITY_SCALE`, 6 dp),
2199
+ * so every sum the kit runs — the projection `$inc`, the rollup rebuild, the reconcile — stays an
2200
+ * exact integer. Convert at the edges only: {@link toQuantityMicro} in a mapper,
2201
+ * {@link fromQuantityMicro} at a read.
2202
+ */
2203
+ /** Micro-units per quantity unit — the primitives grid, declared once. */
2204
+ const FACT_QUANTITY_SCALE = QUANTITY_SCALE;
2205
+ /**
2206
+ * A non-negative quantity ON the 6-dp grid → its integer micro-unit count. THROWS on a negative,
2207
+ * non-finite, off-grid (a 7th decimal) or out-of-range value — corrupt input rides the retry/DLQ
2208
+ * (live) or abort (backfill) path, never a rounded fact.
2209
+ */
2210
+ function toQuantityMicro(value, context) {
2211
+ if (typeof value !== "number" || !(value >= 0) || !isOnQuantityGrid(value)) throw new Error(`fact projector: invalid quantity ${String(value)} (${context}) — must be >= 0 with at most 6 decimal places`);
2212
+ const micro = Number(quantityToGrid(value));
2213
+ if (!Number.isSafeInteger(micro)) throw new Error(`fact projector: quantity ${value} (${context}) exceeds the safe micro-unit range`);
2214
+ return micro;
2215
+ }
2216
+ /** An integer micro-unit count → the quantity it encodes (`6_450_000` → `6.45`). THROWS on a non-integer. */
2217
+ function fromQuantityMicro(micro, context) {
2218
+ if (!Number.isSafeInteger(micro)) throw new Error(`fact quantity: micro-unit value ${String(micro)} (${context}) is not a safe integer`);
2219
+ const value = micro / FACT_QUANTITY_SCALE;
2220
+ return value === 0 ? 0 : value;
2221
+ }
2222
+ /**
2223
+ * `unitMinor × quantity` in minor units, rounded ONCE half-even (sign-symmetric) — the order
2224
+ * kernel's line-total rounding (`resolvePriceBasisTotal`). Exact for a whole quantity, so it
2225
+ * agrees with {@link safeMulMinor} wherever both apply. THROWS on an unsafe input or total.
2226
+ */
2227
+ function extendMinorByQuantity(unitMinor, quantity, context) {
2228
+ if (!Number.isSafeInteger(unitMinor)) throw new Error(`fact projector: unit amount ${String(unitMinor)} (${context}) is not a safe integer`);
2229
+ try {
2230
+ const magnitude = resolvePriceBasisTotal(Math.abs(unitMinor), quantity);
2231
+ return unitMinor < 0 && magnitude !== 0 ? -magnitude : magnitude;
2232
+ } catch (err) {
2233
+ const unsafe = err.code === "UNSAFE_TOTAL";
2234
+ throw new Error(unsafe ? `fact projector: unsafe money product ${unitMinor} * ${quantity} (${context}) — exceeds Number.MAX_SAFE_INTEGER` : `fact projector: cannot extend ${unitMinor} by quantity ${quantity} (${context}) — ${err.message}`);
2235
+ }
2236
+ }
2237
+ //#endregion
2192
2238
  //#region src/cleanup/steps.ts
2193
2239
  const CIVIL_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
2194
2240
  /** Optional civil-date window read from operator parameters. */
@@ -2358,4 +2404,4 @@ function createProjectionCleanupSteps(projection) {
2358
2404
  };
2359
2405
  }
2360
2406
  //#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 };
2407
+ export { DEFAULT_GENERATION_CACHE_TTL_MS, DEFAULT_MAX_LAG_MS, FACT_QUANTITY_SCALE, FactsCapabilityError, FactsError, FactsSpecError, REBUILD_STATES, RESERVED_FACT_FIELDS, ROLLUP_DIM_NONE, assertFactsCapabilities, assertValidQty, buildKeysetQuery, civilFieldsOf, countDuplicateWrites, createProjectionCleanupSteps, defineFactProjection, defineFactProjectionModels, ensureFactsReady, extendMinorByQuantity, fromQuantityMicro, grainFromFact, incrementsFromFacts, isDuplicateKeyOnly, isoWeekOfCivilDate, mergeFactRowsByNormalizedGrain, nextCivilDate, normalizeDim, rollupMeasureToNumber, safeMulMinor, subtractFailedInserts, toQuantityMicro };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classytic/facts",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Generic fact-projection kit — the domain-agnostic machinery behind rebuildable CQRS analytics projections. `defineFactProjection(spec)` declares collections, dimensions, integer fact measures, a Decimal128 daily rollup grain and quality-marker vocabulary, and returns: the generation manifest (verified-cutover state machine with dual-write targets), the idempotent §4.3 small-projection transaction (dedupe pre-read → one transaction: only-new fact inserts + per-grain rollup $inc upserts), a deterministic rollup rebuild from facts, a resumable keyset document backfill with per-source checkpoints, a facts-vs-source drift reconcile framework, and outbox-derived freshness. Domain bindings supply only mappers, document sources and reconcile aggregations.",
5
5
  "author": "Classytic",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -22,6 +22,7 @@
22
22
  },
23
23
  "exports": {
24
24
  ".": {
25
+ "@classytic/source": "./src/index.ts",
25
26
  "types": "./dist/index.d.mts",
26
27
  "default": "./dist/index.mjs"
27
28
  }
@@ -45,20 +46,20 @@
45
46
  "push": "classytic-push"
46
47
  },
47
48
  "peerDependencies": {
48
- "@classytic/mongokit": ">=3.32.0",
49
- "@classytic/primitives": ">=0.14.0",
50
- "@classytic/repo-core": ">=0.17.0",
51
- "mongoose": ">=9.4.1",
49
+ "@classytic/mongokit": ">=3.47.0",
50
+ "@classytic/primitives": ">=0.39.0",
51
+ "@classytic/repo-core": ">=0.39.0",
52
+ "mongoose": ">=9.13.1",
52
53
  "zod": ">=4.0.0"
53
54
  },
54
55
  "devDependencies": {
55
56
  "@classytic/dev-tools": "^0.2.0",
56
- "@classytic/mongokit": ">=3.25.0",
57
- "@classytic/primitives": ">=0.20.0",
58
- "@classytic/repo-core": ">=0.20.0",
57
+ "@classytic/mongokit": ">=3.47.0",
58
+ "@classytic/primitives": ">=0.39.0",
59
+ "@classytic/repo-core": ">=0.39.0",
59
60
  "@types/node": "^25.5.0",
60
- "mongodb-memory-server": "^10.2.3",
61
- "mongoose": "^9.7.4",
61
+ "mongodb-memory-server": "^11.4.0",
62
+ "mongoose": "^9.13.1",
62
63
  "publint": "^0.3.23",
63
64
  "tsdown": "^0.22.14",
64
65
  "typescript": "^7.0.2",