@cobol-ts/cursor-loader-indexed-graph-state 0.0.0-stage → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +452 -3
  2. package/dist/index.d.ts +6 -0
  3. package/dist/index.js +23 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/src/indexed.state.codec.d.ts +16 -0
  6. package/dist/src/indexed.state.codec.js +427 -0
  7. package/dist/src/indexed.state.codec.js.map +1 -0
  8. package/dist/src/indexed.state.configuration.d.ts +12 -0
  9. package/dist/src/indexed.state.configuration.js +45 -0
  10. package/dist/src/indexed.state.configuration.js.map +1 -0
  11. package/dist/src/indexed.state.exports.spec.d.ts +1 -0
  12. package/dist/src/indexed.state.exports.spec.js +23 -0
  13. package/dist/src/indexed.state.exports.spec.js.map +1 -0
  14. package/dist/src/indexed.state.file.d.ts +20 -0
  15. package/dist/src/indexed.state.file.js +147 -0
  16. package/dist/src/indexed.state.file.js.map +1 -0
  17. package/dist/src/indexed.state.file.spec.d.ts +1 -0
  18. package/dist/src/indexed.state.file.spec.js +345 -0
  19. package/dist/src/indexed.state.file.spec.js.map +1 -0
  20. package/dist/src/indexed.state.join.d.ts +36 -0
  21. package/dist/src/indexed.state.join.js +222 -0
  22. package/dist/src/indexed.state.join.js.map +1 -0
  23. package/dist/src/indexed.state.join.spec.d.ts +1 -0
  24. package/dist/src/indexed.state.join.spec.js +270 -0
  25. package/dist/src/indexed.state.join.spec.js.map +1 -0
  26. package/dist/src/indexed.state.number.spec.d.ts +1 -0
  27. package/dist/src/indexed.state.number.spec.js +102 -0
  28. package/dist/src/indexed.state.number.spec.js.map +1 -0
  29. package/dist/src/indexed.state.optional.spec.d.ts +1 -0
  30. package/dist/src/indexed.state.optional.spec.js +63 -0
  31. package/dist/src/indexed.state.optional.spec.js.map +1 -0
  32. package/dist/src/indexed.state.parser.d.ts +34 -0
  33. package/dist/src/indexed.state.parser.js +237 -0
  34. package/dist/src/indexed.state.parser.js.map +1 -0
  35. package/dist/src/indexed.state.rolling.spec.d.ts +1 -0
  36. package/dist/src/indexed.state.rolling.spec.js +176 -0
  37. package/dist/src/indexed.state.rolling.spec.js.map +1 -0
  38. package/dist/src/indexed.state.schema.d.ts +48 -0
  39. package/dist/src/indexed.state.schema.js +118 -0
  40. package/dist/src/indexed.state.schema.js.map +1 -0
  41. package/package.json +64 -3
package/README.md CHANGED
@@ -1,3 +1,452 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @cobol-ts/cursor-loader-indexed-graph-state
2
+
3
+ A schema-first, indexed binary file reader and writer for graph state.
4
+
5
+ Indexed Graph State stores one scalar value per graph node, using numeric
6
+ array positions rather than string-keyed object properties. It uses the
7
+ same pooled physical cursor infrastructure as the COBOL, CSV, JSONL and
8
+ Protobuf loaders.
9
+
10
+ The format supports both ordinary file input and persisted accumulator
11
+ state. It does not require a Protobuf message representation.
12
+
13
+ ## Quick orientation
14
+
15
+ **In this README:** [Design](#design) · [File format](#file-format) · [Creating a schema](#creating-a-schema) · [Writing a file](#writing-a-file) · [Reading a file](#reading-a-file) · [Schema evolution](#schema-evolution) · [Pooled state without historical data](#pooled-state-without-historical-data) · [Indexed updates and material changes](#indexed-updates-and-material-changes) · [Integration with the file catalogue](#integration-with-the-file-catalogue) · [Public API](#public-api) · …
16
+
17
+ **Responsibility.** Encode, decode and scan persisted indexed graph accumulator records with a self-describing schema.
18
+
19
+ **Boundary.** A prepared accumulator scanner reuses schema/codec/pool state across runs; each scan retains fresh pass-local record ownership.
20
+
21
+ **Public modules.** [indexed.state.schema.ts](./src/indexed.state.schema.ts), [indexed.state.codec.ts](./src/indexed.state.codec.ts), [indexed.state.parser.ts](./src/indexed.state.parser.ts), [indexed.state.file.ts](./src/indexed.state.file.ts), [indexed.state.join.ts](./src/indexed.state.join.ts) (and 1 more exports in [`index.ts`](index.ts)).
22
+
23
+ **Tests.** [indexed.state.exports.spec.ts](src/indexed.state.exports.spec.ts), [indexed.state.file.spec.ts](src/indexed.state.file.spec.ts), [indexed.state.join.spec.ts](src/indexed.state.join.spec.ts) (+1 more)
24
+
25
+ **Related packages.** [@cobol-ts/cel-graph-runtime](../../cel/graph-runtime/README.md) · [@cobol-ts/cursor-composition](../cursor-composition/README.md).
26
+
27
+ ## Design
28
+
29
+ A prepared dependency graph assigns each node a numeric index. The
30
+ Indexed Graph State representation uses those indices directly:
31
+
32
+ ```typescript
33
+ const value = record.values[node.index];
34
+ const changed = record.update(node.index, candidate);
35
+ ```
36
+
37
+ Node names are resolved during preparation, not during record evaluation.
38
+
39
+ There are three distinct concepts:
40
+
41
+ - **Node name:** stable logical identity, used for schema compatibility.
42
+ - **Graph index:** numeric position assigned by the current prepared graph.
43
+ - **Stored position:** numeric position of the field in the persisted schema.
44
+
45
+ The stored position and graph index need not be identical.
46
+
47
+ When a file is opened, the stored schema is compared with the active
48
+ schema and a mapping is prepared. Subsequent records use that mapping
49
+ without resolving node names.
50
+
51
+ ## File format
52
+
53
+ Files use the existing four-byte Record Descriptor Word (RDW) framing.
54
+
55
+ The first record contains the schema. Subsequent records contain entity
56
+ keys and scalar values.
57
+
58
+ ```text
59
+ File
60
+ RDW + Schema
61
+ RDW + Entity 1
62
+ RDW + Entity 2
63
+ RDW + Entity 3
64
+ ...
65
+ ```
66
+
67
+ ### Schema record
68
+
69
+ The schema payload begins with a four-byte ASCII magic followed by UTF-8 JSON:
70
+ `IGS1` for version 1 (existing required scalars), and `IGS2` for version 2
71
+ (schemas containing optional scalar fields). The writer selects version 2 when
72
+ any scalar is declared `optional: true`. Existing version-1 files and scalar
73
+ record layouts are unchanged.
74
+
75
+ For example:
76
+
77
+ ```json
78
+ {
79
+ "format": "indexed-graph-state",
80
+ "version": 1,
81
+ "nodes": [
82
+ {"name": "balance", "type": "int"},
83
+ {"name": "exposure", "type": "double"},
84
+ {"name": "active", "type": "bool"}
85
+ ]
86
+ }
87
+ ```
88
+
89
+ The schema defines the physical order and types of the stored values.
90
+ Graph execution indices are not persisted.
91
+
92
+ ### Entity records
93
+
94
+ Each entity record contains:
95
+
96
+ 1. A signed 64-bit entity key (`customerId`).
97
+ 2. One scalar or rolling-window value for every field in the stored schema.
98
+
99
+ Values use the following encodings:
100
+
101
+ | Type | TypeScript | Binary representation |
102
+ |---|---|---|
103
+ | `int` | `bigint` | Signed int64, little-endian |
104
+ | `uint` | `bigint` | Unsigned uint64, little-endian |
105
+ | `double` | `number` | IEEE 754 float64, little-endian |
106
+ | `bool` | `boolean` | One byte, 0 or 1 |
107
+ | `string` | `string` | uint32 byte length followed by UTF-8 |
108
+ | `rolling-window` | `RingBuffer<T>` | uint32 count, uint32 excluded position, one expiration flag, then `size + 1` slots with presence bytes and typed values |
109
+
110
+ Version 1 supports both scalar and rolling-window graph values. A window
111
+ declaration stores `element`, `periodicity` and `size` in the schema; it has
112
+ `size + 1` physical slots. Integer fields and integer window elements may
113
+ select `javascriptType: number` (safe integers) or `bigint` while retaining
114
+ the same int64/uint64 storage. The JavaScript representation is not persisted
115
+ in the schema record.
116
+
117
+ Both the schema record and each entity record must fit within the
118
+ existing RDW limit of 65,535 bytes, including the RDW itself.
119
+
120
+ An empty physical file is invalid. A file containing a schema but no
121
+ entity records is valid.
122
+
123
+ Entity records must be sorted by strictly increasing `customerId`. The wire
124
+ key remains signed int64. The decoder defaults to BigInt IDs, or accepts
125
+ `customerIdType: "number"` to read them directly as safe JavaScript integers.
126
+ Numbers outside `Number.MIN_SAFE_INTEGER..Number.MAX_SAFE_INTEGER` are rejected
127
+ without rounding. The writer accepts correctly ranged numeric or BigInt keys.
128
+
129
+ ## Creating a schema
130
+
131
+ Schemas are constructed using `indexedGraphSchema`. The graph executor can
132
+ also construct them from canonical value metadata using
133
+ `indexedGraphSchemaFromValueTypes()`. A rolling-window field declares its
134
+ element type, logical capacity and advancement periodicity; for example:
135
+
136
+ ```typescript
137
+ const history = indexedGraphSchema([
138
+ {name: 'monthlyAmounts', type: 'rolling-window', element: 'int',
139
+ javascriptType: 'number', periodicity: 'monthly', size: 6}
140
+ ]);
141
+ ```
142
+
143
+ The wire schema persists the field layout, not `javascriptType`.
144
+
145
+ ```typescript
146
+ import {
147
+ indexedGraphSchema
148
+ } from '@cobol-ts/cursor-loader-indexed-graph-state';
149
+
150
+ const schema = indexedGraphSchema([
151
+ {name: 'balance', type: 'int'},
152
+ {name: 'exposure', type: 'double'},
153
+ {name: 'active', type: 'bool'}
154
+ ]);
155
+ ```
156
+
157
+ Schema validation rejects duplicate names, invalid names, unsupported
158
+ types and use of the reserved field name `customerId`.
159
+
160
+ ## Writing a file
161
+
162
+ `writeIndexedGraphStateFile` writes the schema followed by sorted
163
+ entity records.
164
+
165
+ ```typescript
166
+ import {
167
+ createIndexedGraphRecord,
168
+ indexedGraphSchema,
169
+ writeIndexedGraphStateFile
170
+ } from '@cobol-ts/cursor-loader-indexed-graph-state';
171
+
172
+ const schema = indexedGraphSchema([
173
+ {name: 'balance', type: 'int'},
174
+ {name: 'exposure', type: 'double'}
175
+ ]);
176
+
177
+ const first = createIndexedGraphRecord(2);
178
+ first.customerId = 100n;
179
+ first.values[0] = 1250n;
180
+ first.values[1] = 0.25;
181
+
182
+ const second = createIndexedGraphRecord(2);
183
+ second.customerId = 200n;
184
+ second.values[0] = 2400n;
185
+ second.values[1] = 0.75;
186
+
187
+ await writeIndexedGraphStateFile(
188
+ 'state.igs',
189
+ schema,
190
+ [first, second]
191
+ );
192
+ ```
193
+
194
+ The writer uses a reusable output buffer and encodes records directly
195
+ into it. It does not construct an intermediate Protobuf message.
196
+
197
+ All required scalar fields must have defined values before serialisation.
198
+ An `undefined` value is allowed only for scalars declared `optional: true`;
199
+ it is encoded as absent, which is distinct from a numeric zero. An ordinary
200
+ missing field remains an error.
201
+
202
+ The writer validates scalar types, integer ranges, record sizes and
203
+ entity-key ordering.
204
+
205
+ ## Reading a file
206
+
207
+ `readIndexedGraphStateFile` exposes records through the shared prepared
208
+ physical cursor infrastructure. It is the asynchronous iteration API. The
209
+ production indexed join instead uses `openIndexedGraphStateFileCursor()`: setup
210
+ and close are asynchronous, while `take()` and physical refills are synchronous.
211
+ The pooled parser decodes directly from an existing buffer plus offset/length,
212
+ reusing a per-buffer `DataView`; no `subarray()` or `DataView` is required for
213
+ each numeric record.
214
+
215
+ ```typescript
216
+ import {
217
+ readIndexedGraphStateFile
218
+ } from '@cobol-ts/cursor-loader-indexed-graph-state';
219
+
220
+ for await (const lease of readIndexedGraphStateFile('state.igs')) {
221
+ try {
222
+ const record = lease.representation;
223
+
224
+ const customerId = record.customerId;
225
+ const balance = record.values[0];
226
+ const exposure = record.values[1];
227
+
228
+ // Process the values.
229
+ } finally {
230
+ lease.close();
231
+ }
232
+ }
233
+ ```
234
+
235
+ Each returned lease owns its record representation until it is closed.
236
+
237
+ Records are pooled and may be reused after their leases are released.
238
+ A caller must not retain a borrowed representation after closing its
239
+ lease.
240
+
241
+ Multiple simultaneously live leases must retain independent record
242
+ state.
243
+
244
+ ## Schema evolution
245
+
246
+ The schema stored in a file may differ from the schema of the current
247
+ graph. The reader accepts both IGS1 and IGS2, mapping by logical node name.
248
+ This supports loading an IGS1 rolling window and initialising newly added
249
+ aggregate fields under an IGS2 active schema. Moving from an existing
250
+ optional scalar to a required scalar under the same name is rejected.
251
+
252
+ For example, a historical file might contain:
253
+
254
+ ```text
255
+ Stored schema
256
+ 0: balance
257
+ 1: exposure
258
+ ```
259
+
260
+ The current graph might use:
261
+
262
+ ```text
263
+ Active schema
264
+ 0: exposure
265
+ 1: balance
266
+ 2: risk
267
+ ```
268
+
269
+ Preparation resolves the names once:
270
+
271
+ ```text
272
+ Stored 0 -> Active 1
273
+ Stored 1 -> Active 0
274
+ ```
275
+
276
+ The decoder writes directly into the active graph's array positions.
277
+
278
+ The newly introduced `risk` field has no historical value and remains
279
+ `undefined`.
280
+
281
+ A missing historical value is different from a stored default such as
282
+ `0n`, `0`, `false` or an empty string. This distinction is important
283
+ for the graph Planner's first-update activation rules.
284
+
285
+ ### Compatibility rules
286
+
287
+ - Reordered fields are supported.
288
+ - Newly introduced fields are initially undefined.
289
+ - Removed fields are rejected by default.
290
+ - Removed fields may be ignored using the explicit `removed: 'ignore'`
291
+ policy.
292
+ - Changes to a field's scalar type are rejected.
293
+ - Renaming a field changes its persisted identity.
294
+
295
+ No implicit type conversion or node-rename migration is performed.
296
+
297
+ To read an older file into the current layout:
298
+
299
+ ```typescript
300
+ for await (const lease of readIndexedGraphStateFile(
301
+ 'previous.igs',
302
+ {activeSchema: currentSchema}
303
+ )) {
304
+ try {
305
+ const record = lease.representation;
306
+
307
+ // Values use currentSchema's field order.
308
+ } finally {
309
+ lease.close();
310
+ }
311
+ }
312
+ ```
313
+
314
+ ## Pooled state without historical data
315
+
316
+ An entity may have no persisted accumulator.
317
+
318
+ `createIndexedGraphStatePool` supplies reusable, initially missing
319
+ state for such entities.
320
+
321
+ ```typescript
322
+ import {
323
+ createIndexedGraphStatePool
324
+ } from '@cobol-ts/cursor-loader-indexed-graph-state';
325
+
326
+ const pool = createIndexedGraphStatePool(schema);
327
+
328
+ const record = pool.acquireEmpty(100n);
329
+
330
+ try {
331
+ // All values are initially undefined.
332
+ record.update(0, 1250n);
333
+ record.update(1, 0.25);
334
+ } finally {
335
+ pool.release(record);
336
+ }
337
+ ```
338
+
339
+ Acquiring a pooled record resets its entity key and values.
340
+
341
+ The pool rejects duplicate releases and records it does not own.
342
+ A record must be released exactly once.
343
+
344
+ ## Indexed updates and material changes
345
+
346
+ `IndexedGraphRecord.update()` accepts a graph index and candidate value.
347
+
348
+ ```typescript
349
+ record.update(0, 1250n); // true when previously missing
350
+ record.update(0, 1250n); // false
351
+ record.update(0, 1300n); // true
352
+ ```
353
+
354
+ The current implementation uses `Object.is` for defined scalar values and
355
+ treats the first update of an undefined slot as a change. Rolling windows
356
+ are represented by pooled `RingBuffer` values; their period advancement and
357
+ daily/monthly reset semantics are implemented by the graph executor, not by
358
+ `IndexedGraphRecord.update()` itself. The returned boolean feeds downstream
359
+ change-driven planning. Specialised incremental aggregates remain future work.
360
+
361
+ ## Integration with the file catalogue
362
+
363
+ The file catalogue recognises the type:
364
+
365
+ ```yaml
366
+ files:
367
+ previousState:
368
+ type: indexed-graph-state
369
+ ```
370
+
371
+ The shared prepared-source infrastructure can open Indexed Graph State
372
+ as an ordinary physical input source.
373
+
374
+ The parser provides compiled named-field access through the existing
375
+ cursor projection contract, including the special entity key
376
+ `customerId`.
377
+
378
+ For accumulator execution, the intended access path is different:
379
+ CEL field names will be resolved to graph indices at compilation time
380
+ and the executor will access the indexed values directly.
381
+
382
+ These are separate responsibilities.
383
+
384
+ ## Public API
385
+
386
+ ### Schema and representation
387
+
388
+ - `indexedGraphSchema`
389
+ - `validateIndexedGraphSchema`
390
+ - `createIndexedGraphRecord`
391
+ - `IndexedGraphSchema`
392
+ - `IndexedGraphRecord`
393
+ - `IndexedScalar`
394
+ - `IndexedScalarKind`
395
+ - `IndexedCustomerId` (`number | bigint`)
396
+ - `IndexedValue` (scalar or rolling window)
397
+ - `indexedGraphSchemaFromValueTypes`
398
+
399
+ ### Encoding and schema mapping
400
+
401
+ - `encodeIndexedGraphSchema`
402
+ - `decodeIndexedGraphSchema`
403
+ - `prepareIndexedGraphCodec`
404
+ - `PreparedIndexedGraphCodec`
405
+ - `RemovedNodePolicy`
406
+
407
+ ### Physical cursor
408
+
409
+ - `indexedGraphParser`
410
+ - `createIndexedGraphParserRegistry`
411
+ - `createIndexedGraphRecordState`
412
+ - `readIndexedGraphStateFile`
413
+ - `openIndexedGraphStateFileCursor` (synchronous pull after async setup)
414
+ - `readIndexedGraphStateFileSchema`
415
+ - `writeIndexedGraphStateFile`
416
+ - `createIndexedGraphStatePool`
417
+
418
+ ## Tests
419
+
420
+ `src/indexed.state.file.spec.ts` covers:
421
+
422
+ - Schema-first file writing and reading.
423
+ - Fragmented RDW input buffers.
424
+ - Multiple entity records.
425
+ - Overlapping live leases.
426
+ - Reordered stored and active schemas.
427
+ - Newly added fields with missing historical values.
428
+ - Indexed updates and material-change detection.
429
+ - Pool reuse and reset behaviour.
430
+ - Rolling-window wire round trips and schema compatibility.
431
+ - Direct numeric customer-ID decoding with safe-integer bounds.
432
+ - Synchronous buffered history reads, including split records.
433
+ - Type-incompatible schema changes.
434
+ - Invalid or missing schema records.
435
+ - Unsorted entity records.
436
+ - Schema-only files.
437
+ - Compiled access to the entity key.
438
+
439
+ The test suite should be run with the repository's normal Yarn/Jest
440
+ workflow after Laoban has generated the package configuration.
441
+
442
+ ## Current scope
443
+
444
+ This module implements the Indexed Graph State physical format, schema
445
+ mapping, rolling-window encoding, decoding and pooled record representation.
446
+ The indexed production executor uses these numeric slots directly and joins
447
+ current input against sorted historical state. It can select safe-integer
448
+ customer IDs without changing the signed int64 wire format.
449
+
450
+ The legacy object accumulator strategy remains separately selectable.
451
+ Neither `benchmark run` nor `cel execute` commits a new indexed checkpoint;
452
+ checkpoint promotion and exactly-once period identity are separate work.
@@ -0,0 +1,6 @@
1
+ export * from './src/indexed.state.schema';
2
+ export * from './src/indexed.state.codec';
3
+ export * from './src/indexed.state.parser';
4
+ export * from './src/indexed.state.file';
5
+ export * from './src/indexed.state.join';
6
+ export * from './src/indexed.state.configuration';
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./src/indexed.state.schema"), exports);
18
+ __exportStar(require("./src/indexed.state.codec"), exports);
19
+ __exportStar(require("./src/indexed.state.parser"), exports);
20
+ __exportStar(require("./src/indexed.state.file"), exports);
21
+ __exportStar(require("./src/indexed.state.join"), exports);
22
+ __exportStar(require("./src/indexed.state.configuration"), exports);
23
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6DAA2C;AAC3C,4DAA0C;AAC1C,6DAA2C;AAC3C,2DAAyC;AAEzC,2DAAyC;AACzC,oEAAkD"}
@@ -0,0 +1,16 @@
1
+ import { type IndexedGraphRecord, type IndexedGraphSchema, type IndexedCustomerId } from './indexed.state.schema';
2
+ /** Persist physical field type and temporal layout, but not working JS representation. */
3
+ export declare function encodeIndexedGraphSchema(schema: IndexedGraphSchema): Uint8Array;
4
+ export declare function decodeIndexedGraphSchema(bytes: Uint8Array): IndexedGraphSchema;
5
+ export type RemovedNodePolicy = 'reject' | 'ignore';
6
+ export interface PreparedIndexedGraphCodec {
7
+ readonly storedSchema: IndexedGraphSchema;
8
+ readonly activeSchema: IndexedGraphSchema;
9
+ readonly storedToCurrent: readonly number[];
10
+ initializeMissing(target: IndexedGraphRecord, customerId: IndexedCustomerId): void;
11
+ decodeInto(payload: Uint8Array, target: IndexedGraphRecord, offset?: number, length?: number): void;
12
+ encodedLength(record: IndexedGraphRecord): number;
13
+ encodeInto(record: IndexedGraphRecord, out: Uint8Array, offset: number): number;
14
+ }
15
+ /** Bind field positions once, reuse ring data on decode, and keep scalar record bytes unchanged. */
16
+ export declare function prepareIndexedGraphCodec(stored: IndexedGraphSchema, active?: IndexedGraphSchema, removed?: RemovedNodePolicy, customerIdType?: 'number' | 'bigint'): PreparedIndexedGraphCodec;