@loomwork/event-runtime 0.0.0-stage → 0.1.1

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 (153) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +95 -2
  4. package/dist/BranchRegistry.d.ts +140 -0
  5. package/dist/BranchRegistry.d.ts.map +1 -0
  6. package/dist/BranchRegistry.js +66 -0
  7. package/dist/BranchRegistry.js.map +1 -0
  8. package/dist/CoalescingEventStore.d.ts +97 -0
  9. package/dist/CoalescingEventStore.d.ts.map +1 -0
  10. package/dist/CoalescingEventStore.js +180 -0
  11. package/dist/CoalescingEventStore.js.map +1 -0
  12. package/dist/InMemoryArchiveStore.d.ts +19 -0
  13. package/dist/InMemoryArchiveStore.d.ts.map +1 -0
  14. package/dist/InMemoryArchiveStore.js +49 -0
  15. package/dist/InMemoryArchiveStore.js.map +1 -0
  16. package/dist/InMemoryAsyncEventStore.d.ts +111 -0
  17. package/dist/InMemoryAsyncEventStore.d.ts.map +1 -0
  18. package/dist/InMemoryAsyncEventStore.js +374 -0
  19. package/dist/InMemoryAsyncEventStore.js.map +1 -0
  20. package/dist/InMemoryBranchRegistry.d.ts +31 -0
  21. package/dist/InMemoryBranchRegistry.d.ts.map +1 -0
  22. package/dist/InMemoryBranchRegistry.js +167 -0
  23. package/dist/InMemoryBranchRegistry.js.map +1 -0
  24. package/dist/ProfilingEventStore.d.ts +75 -0
  25. package/dist/ProfilingEventStore.d.ts.map +1 -0
  26. package/dist/ProfilingEventStore.js +133 -0
  27. package/dist/ProfilingEventStore.js.map +1 -0
  28. package/dist/ShardPlan.d.ts +87 -0
  29. package/dist/ShardPlan.d.ts.map +1 -0
  30. package/dist/ShardPlan.js +193 -0
  31. package/dist/ShardPlan.js.map +1 -0
  32. package/dist/ShardedEventStore.d.ts +149 -0
  33. package/dist/ShardedEventStore.d.ts.map +1 -0
  34. package/dist/ShardedEventStore.js +468 -0
  35. package/dist/ShardedEventStore.js.map +1 -0
  36. package/dist/SubscriberRegistry.d.ts +59 -0
  37. package/dist/SubscriberRegistry.d.ts.map +1 -0
  38. package/dist/SubscriberRegistry.js +113 -0
  39. package/dist/SubscriberRegistry.js.map +1 -0
  40. package/dist/TenantScopedArchiveStore.d.ts +36 -0
  41. package/dist/TenantScopedArchiveStore.d.ts.map +1 -0
  42. package/dist/TenantScopedArchiveStore.js +96 -0
  43. package/dist/TenantScopedArchiveStore.js.map +1 -0
  44. package/dist/TenantScopedEventStore.d.ts +59 -0
  45. package/dist/TenantScopedEventStore.d.ts.map +1 -0
  46. package/dist/TenantScopedEventStore.js +227 -0
  47. package/dist/TenantScopedEventStore.js.map +1 -0
  48. package/dist/archive.d.ts +68 -0
  49. package/dist/archive.d.ts.map +1 -0
  50. package/dist/archive.js +207 -0
  51. package/dist/archive.js.map +1 -0
  52. package/dist/archiveSpi.d.ts +165 -0
  53. package/dist/archiveSpi.d.ts.map +1 -0
  54. package/dist/archiveSpi.js +184 -0
  55. package/dist/archiveSpi.js.map +1 -0
  56. package/dist/creationMarker.d.ts +13 -0
  57. package/dist/creationMarker.d.ts.map +1 -0
  58. package/dist/creationMarker.js +17 -0
  59. package/dist/creationMarker.js.map +1 -0
  60. package/dist/decoratorPlan.typecheck.d.ts +2 -0
  61. package/dist/decoratorPlan.typecheck.d.ts.map +1 -0
  62. package/dist/decoratorPlan.typecheck.js +41 -0
  63. package/dist/decoratorPlan.typecheck.js.map +1 -0
  64. package/dist/eventKindClass.d.ts +40 -0
  65. package/dist/eventKindClass.d.ts.map +1 -0
  66. package/dist/eventKindClass.js +99 -0
  67. package/dist/eventKindClass.js.map +1 -0
  68. package/dist/executionIdOrder.d.ts +21 -0
  69. package/dist/executionIdOrder.d.ts.map +1 -0
  70. package/dist/executionIdOrder.js +43 -0
  71. package/dist/executionIdOrder.js.map +1 -0
  72. package/dist/fencing.d.ts +21 -0
  73. package/dist/fencing.d.ts.map +1 -0
  74. package/dist/fencing.js +36 -0
  75. package/dist/fencing.js.map +1 -0
  76. package/dist/index.d.ts +39 -0
  77. package/dist/index.d.ts.map +1 -0
  78. package/dist/index.js +126 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/installOptional.d.ts +52 -0
  81. package/dist/installOptional.d.ts.map +1 -0
  82. package/dist/installOptional.js +112 -0
  83. package/dist/installOptional.js.map +1 -0
  84. package/dist/keyUnavailable.d.ts +67 -0
  85. package/dist/keyUnavailable.d.ts.map +1 -0
  86. package/dist/keyUnavailable.js +87 -0
  87. package/dist/keyUnavailable.js.map +1 -0
  88. package/dist/leases.d.ts +177 -0
  89. package/dist/leases.d.ts.map +1 -0
  90. package/dist/leases.js +142 -0
  91. package/dist/leases.js.map +1 -0
  92. package/dist/payloadShredded.d.ts +30 -0
  93. package/dist/payloadShredded.d.ts.map +1 -0
  94. package/dist/payloadShredded.js +67 -0
  95. package/dist/payloadShredded.js.map +1 -0
  96. package/dist/scaleDecorators.bench.d.ts +2 -0
  97. package/dist/scaleDecorators.bench.d.ts.map +1 -0
  98. package/dist/scaleDecorators.bench.js +93 -0
  99. package/dist/scaleDecorators.bench.js.map +1 -0
  100. package/dist/sequenceRange.bench.d.ts +2 -0
  101. package/dist/sequenceRange.bench.d.ts.map +1 -0
  102. package/dist/sequenceRange.bench.js +46 -0
  103. package/dist/sequenceRange.bench.js.map +1 -0
  104. package/dist/sequenceRange.d.ts +10 -0
  105. package/dist/sequenceRange.d.ts.map +1 -0
  106. package/dist/sequenceRange.js +35 -0
  107. package/dist/sequenceRange.js.map +1 -0
  108. package/dist/timers.d.ts +87 -0
  109. package/dist/timers.d.ts.map +1 -0
  110. package/dist/timers.js +68 -0
  111. package/dist/timers.js.map +1 -0
  112. package/dist/types.d.ts +634 -0
  113. package/dist/types.d.ts.map +1 -0
  114. package/dist/types.js +429 -0
  115. package/dist/types.js.map +1 -0
  116. package/dist/writeConflicts.d.ts +46 -0
  117. package/dist/writeConflicts.d.ts.map +1 -0
  118. package/dist/writeConflicts.js +63 -0
  119. package/dist/writeConflicts.js.map +1 -0
  120. package/memory.d.ts +4 -0
  121. package/memory.js +13 -0
  122. package/package.json +67 -3
  123. package/sequence.d.ts +1 -0
  124. package/sequence.js +5 -0
  125. package/src/BranchRegistry.ts +161 -0
  126. package/src/CoalescingEventStore.ts +214 -0
  127. package/src/InMemoryArchiveStore.ts +69 -0
  128. package/src/InMemoryAsyncEventStore.ts +425 -0
  129. package/src/InMemoryBranchRegistry.ts +178 -0
  130. package/src/ProfilingEventStore.ts +153 -0
  131. package/src/ShardPlan.ts +235 -0
  132. package/src/ShardedEventStore.ts +557 -0
  133. package/src/SubscriberRegistry.ts +115 -0
  134. package/src/TenantScopedArchiveStore.ts +114 -0
  135. package/src/TenantScopedEventStore.ts +266 -0
  136. package/src/archive.ts +248 -0
  137. package/src/archiveSpi.ts +308 -0
  138. package/src/creationMarker.ts +15 -0
  139. package/src/decoratorPlan.typecheck.ts +52 -0
  140. package/src/eventKindClass.ts +127 -0
  141. package/src/executionIdOrder.ts +38 -0
  142. package/src/fencing.ts +31 -0
  143. package/src/index.ts +151 -0
  144. package/src/installOptional.ts +136 -0
  145. package/src/keyUnavailable.ts +98 -0
  146. package/src/leases.ts +319 -0
  147. package/src/payloadShredded.ts +63 -0
  148. package/src/scaleDecorators.bench.ts +107 -0
  149. package/src/sequenceRange.bench.ts +51 -0
  150. package/src/sequenceRange.ts +35 -0
  151. package/src/timers.ts +150 -0
  152. package/src/types.ts +857 -0
  153. package/src/writeConflicts.ts +56 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/NOTICE ADDED
@@ -0,0 +1,8 @@
1
+ Loom
2
+ Copyright 2026 Sushil Chhetri
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this project except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
package/README.md CHANGED
@@ -1,3 +1,96 @@
1
- # Temporary Holding Version
1
+ # @loomwork/event-runtime
2
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.
3
+ The durable log's contract (`EventStore`, SPI 2.6.0), an in-memory implementation, and the decorators
4
+ that scale or scope any backend. The kernel appends every fact to an `EventStore` and rebuilds state by
5
+ folding it, so this is the interface a storage backend implements. You use the package directly to
6
+ compose stores for `defineConfig`, to write your own backend, or to write a decorator. The durable
7
+ backends live in `@loomwork/plugin-sqlite` and `@loomwork/plugin-postgres`.
8
+
9
+ ```ts
10
+ import { defineConfig } from "@loomwork/app";
11
+ import {
12
+ CoalescingEventStore,
13
+ InMemoryAsyncEventStore,
14
+ ShardedEventStore,
15
+ TenantScopedEventStore,
16
+ appendBatchOf,
17
+ headOf,
18
+ } from "@loomwork/event-runtime";
19
+
20
+ // Order from ADR 0074: sharding outermost, then coalescing, then tenant scoping, then the backend.
21
+ const shard = () =>
22
+ new CoalescingEventStore(new TenantScopedEventStore(new InMemoryAsyncEventStore(), "acme"), {
23
+ maxBatch: 32,
24
+ });
25
+ const events = new ShardedEventStore([shard(), shard()]);
26
+
27
+ const app = defineConfig({ storage: { kind: "custom", eventStore: events } });
28
+
29
+ // Optional methods may be absent on a backend: call them through the helpers, which fall back.
30
+ export async function tipOf(executionId: string) {
31
+ await appendBatchOf(events, []); // empty input is a no-op
32
+ return headOf(events, executionId); // null when the execution has no events
33
+ }
34
+ ```
35
+
36
+ ## Surface
37
+
38
+ - **The SPI.** Required: `append`, `read`, `readFrom`, `subscribe`, `close`. Optional, each added in a
39
+ MINOR version: `appendBatch`, `readRange`, `head`, `acquireFence` / `acquireFenceIf`,
40
+ `appendIfUnchanged`, `storeNow`, `copyPrefix`, `deleteExecution`, `deleteThrough`, `truncatePrefix` /
41
+ `truncatePrefixKeeping`, `listExecutions` / `listExecutionsPage`, plus the sealing methods
42
+ `sealingCapability` and `readAtRest`. Callers use `appendBatchOf`, `readRangeOf`, `headOf` and
43
+ `iterateExecutionIds`, which fall back when a method is missing.
44
+ - **Stores.** `InMemoryAsyncEventStore` (also importable from `@loomwork/event-runtime/memory`, which pulls
45
+ in no native modules) and `InMemoryArchiveStore`, `InMemoryLeaseStore`, `InMemoryBranchRegistry`,
46
+ `InMemoryTimerStore`. All are process-local and lose everything on exit.
47
+ - **Decorators.** `CoalescingEventStore` (many concurrent appends, one `appendBatch`),
48
+ `ShardedEventStore` + `ShardPlan` (route an execution to one of N stores, rebalance with
49
+ `migrateExecution`), `TenantScopedEventStore` (prefix every id with a tenant), and
50
+ `ProfilingEventStore` (write-side timing, `writeProfile()`).
51
+ - **Writing a decorator.** `installOptional` and `DecoratorPlan` make you forward, override or refuse
52
+ every optional method; a plan that omits one does not compile.
53
+ - **Errors and reserved ids.** `StaleFenceError`, `DuplicateSequenceError`, `DuplicateEnvelopeIdError`;
54
+ `isReservedStream` and the `__loom_*` stream prefixes.
55
+
56
+ ## Behaviour that surprises people
57
+
58
+ - **Two uniqueness rules.** A backend must reject a repeated `(executionId, sequence)` with
59
+ `DuplicateSequenceError` and a repeated envelope `id` within an execution with
60
+ `DuplicateEnvelopeIdError`. Neither may be reported as the other, and neither overwrites.
61
+ - **`subscribe` can lose a cross-node wake-up.** A local append is delivered synchronously, but a
62
+ wake-up from another node (a dropped listener, a full Postgres NOTIFY queue) is not re-sent. The log
63
+ stays complete. A subscriber that must see a final event re-reads the log on its own timer, as
64
+ `@loomwork/live-query` does.
65
+ - **Batching is atomic per execution, not across executions.** `appendBatch` is equivalent to `append`
66
+ in array order. If a backend omits it, `appendBatchOf` falls back to a sequential loop that is not
67
+ atomic. `CoalescingEventStore` resolves an append only after its batch commits, and one rejected
68
+ envelope (a stale fence, for example) rejects every writer in that batch. It also needs
69
+ `appendBatch` on every layer below it to get the atomicity.
70
+ - **Composition order matters.** A decorator that drops an optional method silently takes that
71
+ capability away from everything above it (the original `Coalescing(TenantScoped(...))` batched
72
+ nothing). `runEventStoreDecoratorConformance` in `@loomwork/conformance` checks yours.
73
+ - **Tenant scoping is by key prefix.** `TenantScopedEventStore` throws `TypeError` for an empty tenant
74
+ or one containing `:`. It scopes ids the store sees; it is not encryption.
75
+ - **`ShardedEventStore` needs a stable `shardOf`** (the default is a fixed hash), and it advertises an
76
+ optional method only if every shard has it. It throws `ShardSealingMismatchError` when shards
77
+ disagree about sealing. Changing the shard count without a `ShardPlan` re-routes executions.
78
+ - **Listing order is part of the SPI.** `listExecutionsPage` pages in Unicode code point order with an
79
+ executionId as the cursor (SPI 2.0.0, ADR 0108).
80
+ - **Erasure is signalled by a branded error.** A store that crypto-shreds must throw an error
81
+ recognised by `isPayloadShredded`; any other failure is treated as retryable, not as proof of erasure.
82
+
83
+ ## See also
84
+
85
+ - API reference: section "`@loomwork/event-runtime` — the durable log" in
86
+ [docs/api-reference.org](../../docs/api-reference.org).
87
+ - Guides: [log and read models](../../docs/user-guide/log-and-read-models.md),
88
+ [scaling](../../docs/scaling.md).
89
+ - ADRs: [0033 SPI conformance](../../docs/adr/0033-spi-conformance-contracts.md),
90
+ [0074 scale-out decorators](../../docs/adr/0074-storage-scale-out-decorators.md),
91
+ [0075 shard rebalancing](../../docs/adr/0075-shard-rebalancing.md),
92
+ [0108 execution-id order](../../docs/adr/0108-execution-id-order-and-fail-soft-migrations.md).
93
+
94
+ ## Install
95
+
96
+ Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override (see [AGENTS.md](../../AGENTS.md)).
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Git-style branching for event-sourced executions — branch only, no merge.
3
+ *
4
+ * A {@link BranchRef} is a movable pointer (like a git branch) naming the head
5
+ * execution of a line of work. A {@link LineageRecord} is an immutable edge in
6
+ * the fork DAG (child → parent at a sequence). Together they let speculative
7
+ * agent executions fork from any point, run independently, and be selected with
8
+ * `promote()` ("pick-a-winner"). There is deliberately no merge/rebase: two
9
+ * divergent ExecutionStates have no principled join, so we don't fake one.
10
+ */
11
+ /**
12
+ * SPI version for the {@link BranchRegistry} contract (ADR 0033). Pinned by
13
+ * `runBranchRegistryConformance` in `@loomwork/testing`.
14
+ *
15
+ * **2.0.0 (L21, ADR 0108 addendum, MAJOR):** `listRefs` orders names in Unicode **code
16
+ * point** order — the same order `EventStore.listExecutionsPage` pins (ADR 0108, SPI
17
+ * 2.0.0): UTF-8 byte order, SQL `COLLATE "C"`, SQLite BINARY, and `compareExecutionIds`
18
+ * (`@loomwork/event-runtime`) as the reference comparator. Not a database's default collation,
19
+ * and not `String.prototype.localeCompare` — both can disagree with code point order, and
20
+ * `localeCompare` can return 0 for two DISTINCT, canonically-equivalent names (an NFC "é"
21
+ * and its NFD decomposition). `after` may be **any string**, not only a name a previous
22
+ * `listRefs` call returned, and the page holds the names strictly after it. Before this, the
23
+ * three backends ordered `listRefs` three different ways (Postgres: database collation;
24
+ * SQLite: BINARY, already conforming; in-memory: `localeCompare`), so a cursor produced by
25
+ * one order and consumed by another skipped or repeated refs at a page boundary — the same
26
+ * failure mode ADR 0108 fixed for execution ids. MAJOR because a store conforming to 1.x
27
+ * (any order, an opaque cursor) can fail the new conformance case (the ADR 0091 rule); no
28
+ * method was added or removed.
29
+ */
30
+ export declare const BRANCH_REGISTRY_SPI_VERSION = "2.0.0";
31
+ /** A named, movable pointer to an execution head. */
32
+ export interface BranchRef {
33
+ /** Branch name, e.g. "main" or "spec/scale-replicas". Unique. */
34
+ name: string;
35
+ /** The execution this ref currently points at. */
36
+ executionId: string;
37
+ /** Latest known sequence on that execution (advanced via `moveTip`). */
38
+ tip: number;
39
+ /** If this branch was created by a fork, the execution it forked from. */
40
+ parentExecutionId?: string;
41
+ /** If this branch was created by a fork, the sequence it forked at. */
42
+ forkSequence?: number;
43
+ createdAt: number;
44
+ updatedAt: number;
45
+ }
46
+ /** An immutable edge in the fork DAG: `executionId` forked from `parentExecutionId` at `forkSequence`. */
47
+ export interface LineageRecord {
48
+ executionId: string;
49
+ parentExecutionId: string;
50
+ forkSequence: number;
51
+ createdAt: number;
52
+ }
53
+ /** Paging for {@link BranchRegistry.listRefs}. Keyset, because refs are unique and name-ordered. */
54
+ export interface ListRefsOptions {
55
+ /** Max rows to return. Must be a positive integer — an unbounded page is not a default. */
56
+ limit?: number;
57
+ /**
58
+ * Return refs whose name sorts strictly AFTER this one, in Unicode CODE POINT order
59
+ * (SPI 2.0.0, ADR 0108 addendum / L21 — {@link BRANCH_REGISTRY_SPI_VERSION}). May be ANY
60
+ * string, not only a name a previous `listRefs` call returned — pass the last name of the
61
+ * previous page.
62
+ */
63
+ after?: string;
64
+ }
65
+ /** Options for {@link BranchRegistry.promote}. */
66
+ export interface PromoteOptions {
67
+ /**
68
+ * Compare-and-set. The executionId `toName` is expected to name right now, or `null` for
69
+ * "must not exist yet". The repoint happens only if the expectation holds; otherwise it
70
+ * throws {@link BranchPromotionConflictError} and **nothing moves**.
71
+ *
72
+ * Without it, `promote` is last-write-wins: two nodes promoting different winners onto
73
+ * `main` both succeed and the loser silently wins. That is the 1.0.0 behaviour, preserved
74
+ * byte-identically when `expect` is omitted.
75
+ */
76
+ expect?: string | null;
77
+ }
78
+ /**
79
+ * A compare-and-set {@link BranchRegistry.promote} lost: `toName` does not name what the
80
+ * caller expected, so the promotion was refused. The registry is untouched — re-read the ref
81
+ * and decide, rather than retrying blind.
82
+ */
83
+ export declare class BranchPromotionConflictError extends Error {
84
+ readonly toName: string;
85
+ readonly expected: string | null;
86
+ readonly actual: string | null;
87
+ constructor(toName: string, expected: string | null, actual: string | null);
88
+ }
89
+ /**
90
+ * Refuse a nonsense page size before it reaches a backend. SQLite treats `LIMIT -1` as "no
91
+ * limit", so an unvalidated negative silently returns the whole table — the opposite of what
92
+ * a caller asking for a page wants.
93
+ */
94
+ export declare function assertListRefsLimit(limit: number | undefined): void;
95
+ export interface BranchRegistry {
96
+ /** Create or move a ref (upsert by name). */
97
+ putRef(ref: BranchRef): Promise<void>;
98
+ getRef(name: string): Promise<BranchRef | null>;
99
+ /**
100
+ * Refs in name order — Unicode CODE POINT order (SPI 2.0.0, see
101
+ * {@link BRANCH_REGISTRY_SPI_VERSION}), never a database collation or
102
+ * `String.prototype.localeCompare`. Unpaged by default; pass `limit`/`after` to walk a
103
+ * registry that has grown — forking is cheap, so the ref table is unbounded by design.
104
+ */
105
+ listRefs(options?: ListRefsOptions): Promise<BranchRef[]>;
106
+ /** Advance a ref's tip as its execution grows. No-op if the ref is absent. */
107
+ moveTip(name: string, tip: number): Promise<void>;
108
+ /**
109
+ * Pick-a-winner: repoint `toName` onto the execution `fromName` currently
110
+ * names, adopting its (executionId, tip). This is the entire "merge"
111
+ * replacement — a pointer move, no history rewrite, no state reconciliation.
112
+ * The losing execution remains immutable and independently resumable.
113
+ * Throws if `fromName` does not exist. Pass `options.expect` to make it a compare-and-set
114
+ * (see {@link PromoteOptions}) — without it, a concurrent promotion is a silent overwrite.
115
+ */
116
+ promote(fromName: string, toName: string, options?: PromoteOptions): Promise<void>;
117
+ deleteRef(name: string): Promise<void>;
118
+ /** Record a fork edge in the DAG. */
119
+ recordLineage(rec: Omit<LineageRecord, "createdAt">): Promise<void>;
120
+ getLineage(executionId: string): Promise<LineageRecord | null>;
121
+ /**
122
+ * OPTIONAL: forget one fork edge — the child's edge to its parent.
123
+ *
124
+ * Lineage is the alternatives-considered audit trail and must outlive a branch's own
125
+ * life. It must NOT outlive the executions it describes: once retention has reclaimed a
126
+ * branch, its edge points at data that no longer exists, and keeping a permanent index of
127
+ * deleted executions contradicts the retention policy that deleted them. It also costs —
128
+ * `LogLifecycle` walks `children()` on every sweep, so dead edges make retention slower
129
+ * forever, in proportion to every fork ever taken.
130
+ *
131
+ * Called by `LogLifecycle` at the moment an execution is deleted, which is the only point
132
+ * where the id is known and the data is provably gone. A store that omits it simply keeps
133
+ * its edges (today's behaviour, byte-identically).
134
+ */
135
+ removeLineage?(executionId: string): Promise<void>;
136
+ /** Direct children forked from `executionId`. */
137
+ children(executionId: string): Promise<LineageRecord[]>;
138
+ close(): Promise<void>;
139
+ }
140
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@ -0,0 +1,66 @@
1
+ "use strict";
2
+ /**
3
+ * Git-style branching for event-sourced executions — branch only, no merge.
4
+ *
5
+ * A {@link BranchRef} is a movable pointer (like a git branch) naming the head
6
+ * execution of a line of work. A {@link LineageRecord} is an immutable edge in
7
+ * the fork DAG (child → parent at a sequence). Together they let speculative
8
+ * agent executions fork from any point, run independently, and be selected with
9
+ * `promote()` ("pick-a-winner"). There is deliberately no merge/rebase: two
10
+ * divergent ExecutionStates have no principled join, so we don't fake one.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.BranchPromotionConflictError = exports.BRANCH_REGISTRY_SPI_VERSION = void 0;
14
+ exports.assertListRefsLimit = assertListRefsLimit;
15
+ /**
16
+ * SPI version for the {@link BranchRegistry} contract (ADR 0033). Pinned by
17
+ * `runBranchRegistryConformance` in `@loomwork/testing`.
18
+ *
19
+ * **2.0.0 (L21, ADR 0108 addendum, MAJOR):** `listRefs` orders names in Unicode **code
20
+ * point** order — the same order `EventStore.listExecutionsPage` pins (ADR 0108, SPI
21
+ * 2.0.0): UTF-8 byte order, SQL `COLLATE "C"`, SQLite BINARY, and `compareExecutionIds`
22
+ * (`@loomwork/event-runtime`) as the reference comparator. Not a database's default collation,
23
+ * and not `String.prototype.localeCompare` — both can disagree with code point order, and
24
+ * `localeCompare` can return 0 for two DISTINCT, canonically-equivalent names (an NFC "é"
25
+ * and its NFD decomposition). `after` may be **any string**, not only a name a previous
26
+ * `listRefs` call returned, and the page holds the names strictly after it. Before this, the
27
+ * three backends ordered `listRefs` three different ways (Postgres: database collation;
28
+ * SQLite: BINARY, already conforming; in-memory: `localeCompare`), so a cursor produced by
29
+ * one order and consumed by another skipped or repeated refs at a page boundary — the same
30
+ * failure mode ADR 0108 fixed for execution ids. MAJOR because a store conforming to 1.x
31
+ * (any order, an opaque cursor) can fail the new conformance case (the ADR 0091 rule); no
32
+ * method was added or removed.
33
+ */
34
+ exports.BRANCH_REGISTRY_SPI_VERSION = "2.0.0";
35
+ /**
36
+ * A compare-and-set {@link BranchRegistry.promote} lost: `toName` does not name what the
37
+ * caller expected, so the promotion was refused. The registry is untouched — re-read the ref
38
+ * and decide, rather than retrying blind.
39
+ */
40
+ class BranchPromotionConflictError extends Error {
41
+ toName;
42
+ expected;
43
+ actual;
44
+ constructor(toName, expected, actual) {
45
+ super(`promote onto "${toName}" refused: expected it to name ${expected === null ? "nothing" : `"${expected}"`}, but it names ${actual === null ? "nothing" : `"${actual}"`}`);
46
+ this.toName = toName;
47
+ this.expected = expected;
48
+ this.actual = actual;
49
+ this.name = "BranchPromotionConflictError";
50
+ Object.setPrototypeOf(this, BranchPromotionConflictError.prototype);
51
+ }
52
+ }
53
+ exports.BranchPromotionConflictError = BranchPromotionConflictError;
54
+ /**
55
+ * Refuse a nonsense page size before it reaches a backend. SQLite treats `LIMIT -1` as "no
56
+ * limit", so an unvalidated negative silently returns the whole table — the opposite of what
57
+ * a caller asking for a page wants.
58
+ */
59
+ function assertListRefsLimit(limit) {
60
+ if (limit === undefined)
61
+ return;
62
+ if (!Number.isInteger(limit) || limit <= 0) {
63
+ throw new RangeError(`listRefs: limit must be a positive integer, got ${limit}`);
64
+ }
65
+ }
66
+ //# sourceMappingURL=BranchRegistry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BranchRegistry.js","sourceRoot":"","sources":["../src/BranchRegistry.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;AAkGH,kDAKC;AArGD;;;;;;;;;;;;;;;;;;GAkBG;AACU,QAAA,2BAA2B,GAAG,OAAO,CAAC;AAqDnD;;;;GAIG;AACH,MAAa,4BAA6B,SAAQ,KAAK;IAE1C;IACA;IACA;IAHX,YACW,MAAc,EACd,QAAuB,EACvB,MAAqB;QAE9B,KAAK,CACH,iBAAiB,MAAM,kCAAkC,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,QAAQ,GAAG,kBAAkB,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,MAAM,GAAG,EAAE,CACxK,CAAC;QANO,WAAM,GAAN,MAAM,CAAQ;QACd,aAAQ,GAAR,QAAQ,CAAe;QACvB,WAAM,GAAN,MAAM,CAAe;QAK9B,IAAI,CAAC,IAAI,GAAG,8BAA8B,CAAC;QAC3C,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,4BAA4B,CAAC,SAAS,CAAC,CAAC;IACtE,CAAC;CACF;AAZD,oEAYC;AAED;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,KAAyB;IAC3D,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO;IAChC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,UAAU,CAAC,mDAAmD,KAAK,EAAE,CAAC,CAAC;IACnF,CAAC;AACH,CAAC"}
@@ -0,0 +1,97 @@
1
+ import type { EventEnvelope } from "@loomwork/core";
2
+ import { type EventStore } from "./types";
3
+ export interface CoalescingEventStoreOptions {
4
+ /**
5
+ * Flush once this many envelopes are queued. The measured knee is ~16; past ~64 both
6
+ * throughput and tail latency regress. Default 16.
7
+ */
8
+ maxBatch?: number;
9
+ /**
10
+ * Upper bound in milliseconds on how long the FIRST envelope of a batch waits for
11
+ * company. Default 0 — flush on the next microtask, which under concurrency already
12
+ * collects everything enqueued in the same turn without adding measurable latency.
13
+ * Raise it only if you are deliberately trading latency for batch size.
14
+ */
15
+ maxLingerMs?: number;
16
+ }
17
+ /**
18
+ * Merges concurrent appends **across executions** into one `appendBatch` (ADR 0074 D2).
19
+ *
20
+ * Why a decorator and not the journal: `ExecutionJournal` is per-execution, so a
21
+ * journal-side batcher can only ever hold one execution's envelopes — a 1-step flow emits
22
+ * four, and with a realistic slow effect the serial tail drains between `STEP_STARTED` and
23
+ * `STEP_COMPLETED`, so it collects one. Measured; it is ADR 0065's own gate-2 case. A store
24
+ * decorator sees every live execution at once and can actually fill a batch.
25
+ *
26
+ * **Ordering.** Each `ExecutionJournal` still serializes its own execution (D3 unchanged) —
27
+ * it awaits each `append` before issuing the next, so this store never holds two envelopes
28
+ * of one execution concurrently through the normal path. Should it anyway (a second writer,
29
+ * a caller not using the journal), the queue is FIFO and `appendBatch` is specified to
30
+ * apply in array order, so arrival order is preserved regardless.
31
+ *
32
+ * **Durability.** An `append` promise resolves only once its batch has committed. Nothing
33
+ * resolves early, so every `drain()` barrier keeps exactly the meaning it has today. This
34
+ * is the property that distinguishes coalescing from the durability classes ADR 0065
35
+ * rejected on invariants.
36
+ *
37
+ * **Failure.** A batch rejection rejects every caller in that batch, so a partial write can
38
+ * never look like success. Combined with `appendBatch`'s all-or-nothing contract, a failed
39
+ * flush leaves the log untouched and every writer informed — **but only when the inner store
40
+ * implements `appendBatch`**. Over a store without it, `appendBatchOf` falls back to a
41
+ * sequential `append` loop, which is not atomic: envelopes ahead of the failing one are
42
+ * already durable while their writers are told the batch failed. Every decorator between
43
+ * this one and the backend must therefore carry `appendBatch` down (ADR 0074 Amendment —
44
+ * `runEventStoreDecoratorConformance` checks it).
45
+ *
46
+ * **Blast radius.** One stale-fence zombie in a batch rejects the whole batch, so every
47
+ * healthy writer coalesced with it is told "failed" too (nothing of theirs lands; they abort
48
+ * and recovery re-drives them from the log). Coalescing widens a fencing rejection from one
49
+ * execution to up to `maxBatch` of them — a price worth paying while fencing is rare.
50
+ *
51
+ * Inert unless wired: compose it explicitly in `storage`, outermost-but-one (sharding
52
+ * outside it, since routing must pick a shard before a batch is formed for that shard).
53
+ */
54
+ export declare class CoalescingEventStore implements EventStore {
55
+ private readonly inner;
56
+ readonly head?: NonNullable<EventStore["head"]>;
57
+ readonly readRange?: NonNullable<EventStore["readRange"]>;
58
+ readonly acquireFence?: NonNullable<EventStore["acquireFence"]>;
59
+ readonly acquireFenceIf?: NonNullable<EventStore["acquireFenceIf"]>;
60
+ readonly appendIfUnchanged?: NonNullable<EventStore["appendIfUnchanged"]>;
61
+ readonly storeNow?: NonNullable<EventStore["storeNow"]>;
62
+ readonly sealingCapability?: NonNullable<EventStore["sealingCapability"]>;
63
+ readonly readAtRest?: NonNullable<EventStore["readAtRest"]>;
64
+ readonly copyPrefix?: NonNullable<EventStore["copyPrefix"]>;
65
+ readonly deleteExecution?: NonNullable<EventStore["deleteExecution"]>;
66
+ readonly deleteThrough?: NonNullable<EventStore["deleteThrough"]>;
67
+ readonly truncatePrefix?: NonNullable<EventStore["truncatePrefix"]>;
68
+ readonly truncatePrefixKeeping?: NonNullable<EventStore["truncatePrefixKeeping"]>;
69
+ readonly listExecutions?: NonNullable<EventStore["listExecutions"]>;
70
+ readonly listExecutionsPage?: NonNullable<EventStore["listExecutionsPage"]>;
71
+ private readonly maxBatch;
72
+ private readonly maxLingerMs;
73
+ private queue;
74
+ private flushScheduled;
75
+ private timer;
76
+ /** Serializes flushes so two batches can never be in flight against the inner store. */
77
+ private tail;
78
+ private closed;
79
+ constructor(inner: EventStore, options?: CoalescingEventStoreOptions);
80
+ append(envelope: EventEnvelope): Promise<void>;
81
+ /**
82
+ * A caller that already has a batch skips the queue entirely — it is by definition
83
+ * already coalesced, and threading it through the queue would only risk splitting it.
84
+ */
85
+ appendBatch(envelopes: readonly EventEnvelope[]): Promise<void>;
86
+ private scheduleFlush;
87
+ private flushNow;
88
+ /** Chain onto the serial tail so batches commit one at a time, in enqueue order. */
89
+ private enqueueFlush;
90
+ read(executionId: string): Promise<EventEnvelope[]>;
91
+ readFrom(executionId: string, fromSequence: number): Promise<EventEnvelope[]>;
92
+ subscribe(executionId: string, handler: (event: EventEnvelope) => void): Promise<() => void>;
93
+ /** Flush anything queued and wait for in-flight batches. Safe to call repeatedly. */
94
+ drain(): Promise<void>;
95
+ close(): Promise<void>;
96
+ }
97
+ //# sourceMappingURL=CoalescingEventStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"CoalescingEventStore.d.ts","sourceRoot":"","sources":["../src/Coal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