@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/CHANGELOG.md ADDED
@@ -0,0 +1,104 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 - 2026-07-29
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.
8
+
9
+ ## 0.2.0 — 2026-07-24
10
+
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.
package/LICENSE ADDED
@@ -0,0 +1,75 @@
1
+ Classytic Source-Available License (Community & Commercial), Version 1.0
2
+
3
+ Copyright (c) 2026 Classytic LLC. All rights reserved.
4
+
5
+ This software is source-available, not open source. Please read this License
6
+ before using it.
7
+
8
+ 1. DEFINITIONS
9
+ "Software" means the contents of this package and any accompanying source
10
+ code, object code, or documentation, in any form.
11
+ "Licensor" means Classytic LLC, a limited liability company organized in the
12
+ United States.
13
+ "You" means the individual or legal entity exercising rights under this
14
+ License.
15
+ "Evaluation Use" means use for evaluation, development, testing,
16
+ experimentation, or internal non-commercial purposes only.
17
+ "Production Use" means any use of the Software that is live, commercial,
18
+ revenue-generating, or customer-facing, or any use other than Evaluation Use.
19
+ "Commercial License" means a separate written agreement executed with
20
+ Licensor that grants Production Use rights.
21
+
22
+ 2. OWNERSHIP
23
+ The Software is licensed, not sold. Licensor retains all right, title, and
24
+ interest in and to the Software, including all intellectual property rights.
25
+ All rights not expressly granted in this License are reserved by Licensor.
26
+
27
+ 3. EVALUATION GRANT
28
+ Subject to Your compliance with this License, Licensor grants You a
29
+ worldwide, royalty-free, non-exclusive, non-transferable, revocable license
30
+ to download, install, run, and modify the Software solely for Evaluation Use.
31
+
32
+ 4. PRODUCTION USE REQUIRES A COMMERCIAL LICENSE
33
+ Production Use of the Software is NOT permitted under this License and
34
+ requires a Commercial License from Licensor. A Commercial License may be
35
+ granted at Licensor's discretion, with or without a fee, and may confer
36
+ perpetual, irrevocable, and transferable Production Use rights as set out in
37
+ that agreement. Contact licensing@classytic.com to obtain one.
38
+
39
+ 5. RESTRICTIONS
40
+ You may not:
41
+ (a) make any Production Use of the Software without a Commercial License;
42
+ (b) redistribute, resell, rent, sublicense, or otherwise make the Software
43
+ (in whole or in part, original or modified) available to third parties as
44
+ a stand-alone product, framework, library, or hosted/managed service that
45
+ competes with the Software or with Licensor;
46
+ (c) remove, obscure, or alter any copyright, license, or attribution notice.
47
+
48
+ 6. FEEDBACK AND CONTRIBUTIONS
49
+ Any feedback, suggestions, or contributions You provide relating to the
50
+ Software may be used by Licensor for any purpose without obligation to You.
51
+
52
+ 7. TERMINATION
53
+ This License and the Evaluation Grant terminate automatically if You breach
54
+ any term. Upon termination You must cease all use of the Software and destroy
55
+ all copies in Your possession. Rights under a Commercial License are governed
56
+ by that agreement's own terms and survive termination of this License to the
57
+ extent stated there.
58
+
59
+ 8. DISCLAIMER OF WARRANTY
60
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
61
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
62
+ FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
63
+
64
+ 9. LIMITATION OF LIABILITY
65
+ TO THE MAXIMUM EXTENT PERMITTED BY LAW, IN NO EVENT SHALL LICENSOR BE LIABLE
66
+ FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
67
+ TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
68
+ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
69
+
70
+ 10. GOVERNING LAW
71
+ This License is governed by the laws of the State of Delaware, United States,
72
+ without regard to its conflict-of-laws principles. (Adjust to Your LLC's state
73
+ of formation.)
74
+
75
+ For commercial licensing, contact: licensing@classytic.com
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ # @classytic/facts
2
+
3
+ Generic **fact-projection kit** — the domain-agnostic machinery behind rebuildable
4
+ CQRS analytics projections (extracted from a production sales-analytics pipeline).
5
+
6
+ One factory call gives a domain everything except its own semantics:
7
+
8
+ | Machinery (this kernel owns) | Domain (the binding owns) |
9
+ |---|---|
10
+ | Generation **manifest** — `active → rebuilding → catching_up → verified → active` verified-cutover protocol, evidence stamps, cached reads, **dual-write targets** through every rebuild state, 3×TTL cutover time-guard | event → fact-row **mappers** (dedupe-key scheme, measures math, quality markers) |
11
+ | **`projectFacts`** — the idempotent "small projection transaction": dedupe pre-read → ONE transaction: insert only-new facts + per-grain rollup `$inc` upserts | event subscriptions / relay wiring |
12
+ | **Rollup engine** — `'(none)'` sentinel grain normalization, Decimal128 accumulators, deterministic `rebuildRollup` from facts in bounded civil-date chunks | the grain + measure list (declared in the spec) |
13
+ | **Backfill engine** — keyset `_id`-asc iteration, per-`(checkpointId, source)` resumable checkpoints pinned to one generation, validated batch/maxDocs/sleep bounds, insert-dup counting | `DocumentSource` bindings (collection + filter + `mapBatch`) |
14
+ | **Reconcile framework** — facts-side aggregation vs injected source-side aggregations, per-cell drift report | `ReconcileSource` aggregations |
15
+ | **Freshness** — outbox diagnostics + manifest → `{projectedThrough, lagMs, status}` | the dedicated outbox store instance (host-owned, rule 16) |
16
+ | Models + indexes (unique `{generation, dedupeKey}`, unique rollup grain), boot capability gate, `syncIndexes` | collection names, dimensions, secondaries (each with a rule-34 comment) |
17
+
18
+ ```ts
19
+ import { createFactProjection } from '@classytic/facts';
20
+
21
+ const sales = createFactProjection<SalesFact>({
22
+ name: 'sales', // manifest doc id + model namespace
23
+ connection: mongoose.connection,
24
+ collections: {
25
+ facts: 'sales_fact',
26
+ rollup: 'sales_daily',
27
+ manifest: 'sales_projection_manifest',
28
+ checkpoints: 'sales_projection_checkpoints',
29
+ },
30
+ civil: { // business-zone instant → civil labels
31
+ dateOf: businessDateStr, // e.g. Asia/Dhaka civil date
32
+ weekOf: businessWeekOf,
33
+ monthOf: businessMonthOf,
34
+ },
35
+ fact: {
36
+ dimensions: {
37
+ kind: { type: String, enum: ['ordered', 'fulfilled', 'returned', 'cancelled'], required: true },
38
+ organizationId: { type: String, required: true }, // a DIMENSION here, not a scope
39
+ skuRef: { type: String }, nodeRef: { type: String },
40
+ channel: { type: String }, currency: { type: String },
41
+ orderId: { type: String }, orderNumber: { type: String }, lineId: { type: String },
42
+ },
43
+ measures: [
44
+ { name: 'orderedQty', nonNegative: true },
45
+ { name: 'fulfilledQty', nonNegative: true },
46
+ 'grossRevenueMinor', 'discountMinor', 'taxMinor', 'netRevenueMinor', 'cogsMinor',
47
+ ],
48
+ markers: {
49
+ qtySource: { values: ['event', 'reconstructed'], default: 'event' },
50
+ costSource: { values: ['snapshot', 'missing'], default: 'missing' },
51
+ },
52
+ extraIndexes: [
53
+ { fields: { generation: 1, organizationId: 1, civilDate: 1, skuRef: 1 },
54
+ comment: 'branch dashboards / demand history: branch x day x SKU' },
55
+ ],
56
+ },
57
+ rollup: {
58
+ grain: ['organizationId', 'skuRef', 'nodeRef', 'channel', 'currency'],
59
+ measures: ['orderedQty', 'fulfilledQty', 'grossRevenueMinor', 'discountMinor',
60
+ 'taxMinor', 'netRevenueMinor', 'cogsMinor'],
61
+ },
62
+ autoIndex: process.env.NODE_ENV !== 'production', // rule 35
63
+ });
64
+
65
+ await sales.ensureReady(); // capability gate (transactions) + collection DDL
66
+ ```
67
+
68
+ ## The correctness core (what the moved machinery guarantees)
69
+
70
+ - **Idempotency** — dedupe keys are deterministic BUSINESS-occurrence keys, never
71
+ `eventId`; uniqueness is per `(generation, dedupeKey)`. At-least-once redelivery,
72
+ double envelope surfaces and backfill/live overlap all converge to one row.
73
+ - **Fact↔rollup atomicity** — `projectFacts` pre-reads existing dedupe keys
74
+ (redelivery drives *nothing*, so the rollup can never double-`$inc`), then commits
75
+ the only-new facts and their per-grain `$inc` upserts in ONE mongokit
76
+ `withTransaction`. Every failure **throws** — the relay's retry/backoff/DLQ
77
+ contract holds (a swallowed error would ack an unprojected row).
78
+ - **Lossless cutover** — the projector writes through
79
+ `manifest.getGenerationTargets()`: `[active]` normally, `[active, rebuild]`
80
+ in **all three** rebuild states, and `cutover()` refuses until the rebuild has
81
+ been visible ≥ 3 × cache TTL, so every pod dual-writes before the flip.
82
+ - **Deterministic rebuild** — `rebuildRollup` re-aggregates facts through the
83
+ repository `AggRequest` IR in bounded chunks; sentinel normalization + the civil
84
+ consistency contract keep rebuilt rows byte-equal to live rows.
85
+
86
+ ## New domain checklist (a binding lands in ~300 lines)
87
+
88
+ To stand up `purchases-analytics` (or POS-shift, inventory-movement, support…):
89
+
90
+ 1. **Spec** (~60 lines) — `createFactProjection({ name: 'purchases', ... })`:
91
+ collections, dimensions, integer measures (`nonNegative` for quantities),
92
+ marker vocabulary, rollup grain, secondaries (rule-34 comments mandatory).
93
+ 2. **Civil port** (~5 lines) — bind `dateOf/weekOf/monthOf` over the host's
94
+ business-date helpers. Contract: `weekOf(d) === isoWeekOfCivilDate(dateOf(d))`
95
+ and `monthOf(d) === dateOf(d).slice(0, 7)` (rebuild equivalence depends on it).
96
+ 3. **Event mappers** (~100 lines) — pure `event → FactRow[]` per event type:
97
+ build the dedupe key (`placed:{docNo}:{lineId}`-style), use
98
+ `engine.civilFields(occurredAt)` for the time block, `assertValidQty` /
99
+ `safeMulMinor` for every measure, stamp quality markers. The subscribing
100
+ handler resolves generations implicitly — just call
101
+ `engine.projectFacts(rows)` (dual-write is automatic).
102
+ 4. **`DocumentSource` bindings** (~80 lines) — per durable source collection:
103
+ `{ name, filter, read: (q, n) => coll.find(q).sort({_id:1}).limit(n).toArray(),
104
+ estimateTotal, mapBatch }`. `mapBatch` reuses the same dedupe/marker rules as
105
+ the live mappers so a backfilled generation is row-equivalent. Docs must have
106
+ ObjectId `_id`s (the checkpoint cursor type).
107
+ 5. **`ReconcileSource` aggregations** (~50 lines) — independent per-cell totals
108
+ from the source docs for the measures each source is authoritative for.
109
+ 6. **Host wiring** — dedicated outbox store + relay (durability is host-owned,
110
+ rule 16), a strict single-consumer transport lane, subscriptions, ops
111
+ resource calling `manifest.*`, `runBackfill`, `rebuildRollup`, `reconcile`,
112
+ `getFreshness(store)`.
113
+
114
+ Rebuild/cutover, checkpointed backfill, drift reports, freshness and all indexes
115
+ come for free.
116
+
117
+ ## Notes & sharp edges
118
+
119
+ - **No tenant plugin — deliberate.** These are analytical projections: an
120
+ org/branch id among the dimensions is a *queryable dimension*, not a scope.
121
+ Scope enforcement belongs to the query surface (lens semantic models /
122
+ resource permissions). A tenant plugin here would break projector system
123
+ writes (no request scope) and HQ rollup reads.
124
+ - **`allowNonTransactional`** is the standalone-Mongo dev fallback only. In
125
+ fallback mode a duplicate-only insert race rolls up exactly the subset that
126
+ inserted (`subtractFailedInserts`) — the invariant holds; production leaves it
127
+ `false` and `ensureReady()` fails closed without transactions.
128
+ - **Schema backstop is loud** — `insertMany` runs with
129
+ `throwOnValidationError: true`; a row failing the safe-integer/non-negative
130
+ validators aborts the transaction (or backfill batch) instead of being
131
+ silently skipped while the rollup counts it.
132
+ - **Mapper identity is fail-fast** — two rows with the same `dedupeKey` in one
133
+ input batch are rejected before a transaction starts; the kernel never
134
+ silently chooses between conflicting representations of one occurrence.
135
+ - **Rollup measures are Decimal128** — never serialize raw; use
136
+ `rollupMeasureToNumber` (throws on non-integer / unsafe magnitudes).
137
+ - **Freshness port ≠ primitives `OutboxStore`** — freshness needs two indexed
138
+ diagnostic reads (`oldestPendingAgeMs`, `newestDeliveredInstant`) the relay
139
+ contract deliberately does not carry; bind them over your store. Import
140
+ `OutboxStore` / `EventTransport` contracts directly from
141
+ `@classytic/primitives` subpaths (P4) — this package never re-exports them.
142
+ - **Model collisions throw** (rule 21) — two engines of one projection need two
143
+ connections, or `forceRecreate: true` in hot-reload/test fixtures.
144
+ - Peers: `@classytic/mongokit ≥3.25`, `@classytic/repo-core ≥0.14`,
145
+ `@classytic/primitives ≥0.14`, `mongoose ≥9.4.1`, `zod ≥4`.
146
+
147
+ ## Testing
148
+
149
+ ```bash
150
+ npm run test:unit # pure machinery (guards, rollup grouping, civil, spec)
151
+ npm run test:integration # MongoMemoryReplSet: manifest FSM, §4.3 txn, rebuild,
152
+ # backfill resume, reconcile, freshness
153
+ ```