dexbot 1.6.18 → 1.7.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.
- package/CHANGELOG.md +68 -0
- package/README.md +24 -18
- package/analysis/README.md +117 -5
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.js +5 -6
- package/dist/analysis/analyze_dynamic_weight.js +2 -1
- package/dist/analysis/analyze_kalman.js +3 -2
- package/dist/analysis/analyze_liquidity.d.ts +17 -0
- package/dist/analysis/analyze_liquidity.js +336 -0
- package/dist/analysis/analyze_regime.js +3 -2
- package/dist/analysis/analyze_regime_windows.js +3 -2
- package/dist/analysis/analyze_volatility.js +3 -2
- package/dist/analysis/bot_key_utils.d.ts +44 -1
- package/dist/analysis/bot_key_utils.js +76 -7
- package/dist/analysis/fills_cache.js +2 -1
- package/dist/analysis/grid_correction_check.d.ts +1 -19
- package/dist/analysis/grid_correction_check.js +12 -30
- package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
- package/dist/analysis/liquidity/liquidity_chain.js +178 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
- package/dist/analysis/liquidity/liquidity_chart_generator.js +693 -0
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +166 -0
- package/dist/analysis/liquidity/liquidity_depth_model.js +258 -0
- package/dist/analysis/liquidity/liquidity_view.d.ts +53 -0
- package/dist/analysis/liquidity/liquidity_view.js +66 -0
- package/dist/analysis/resolve_bot_accounts.js +7 -6
- package/dist/analysis/trade_profitability.js +4 -2
- package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
- package/dist/credential-daemon.js +13 -2
- package/dist/dexbot.js +77 -172
- package/dist/modules/account_bots.d.ts +11 -1
- package/dist/modules/account_orders.d.ts +12 -0
- package/dist/modules/account_orders.js +30 -0
- package/dist/modules/asset_lookup.d.ts +25 -0
- package/dist/modules/asset_lookup.js +75 -0
- package/dist/modules/bitshares-native/transport.js +24 -6
- package/dist/modules/bitshares_client.d.ts +24 -6
- package/dist/modules/bitshares_client.js +44 -7
- package/dist/modules/bot_settings.d.ts +2 -0
- package/dist/modules/chain_scan.d.ts +64 -0
- package/dist/modules/chain_scan.js +80 -0
- package/dist/modules/cli_colors.d.ts +5 -0
- package/dist/modules/cli_colors.js +7 -0
- package/dist/modules/cli_progress.d.ts +51 -0
- package/dist/modules/cli_progress.js +113 -0
- package/dist/modules/constants.d.ts +26 -3
- package/dist/modules/constants.js +63 -8
- package/dist/modules/dexbot_class.d.ts +1 -6
- package/dist/modules/dexbot_class.js +14 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
- package/dist/modules/dexbot_cow_runtime.js +634 -136
- package/dist/modules/dexbot_fill_runtime.js +132 -23
- package/dist/modules/dexbot_maintenance_runtime.js +242 -74
- package/dist/modules/dexbot_startup_runtime.js +32 -20
- package/dist/modules/dexbot_state_recovery.d.ts +33 -1
- package/dist/modules/dexbot_state_recovery.js +167 -5
- package/dist/modules/launcher/runtime_entry.d.ts +21 -1
- package/dist/modules/launcher/runtime_entry.js +36 -1
- package/dist/modules/liquidity_pool_ref.d.ts +32 -0
- package/dist/modules/liquidity_pool_ref.js +116 -0
- package/dist/modules/node_connect_policy.d.ts +8 -1
- package/dist/modules/node_connect_policy.js +18 -2
- package/dist/modules/node_flap_score.d.ts +87 -0
- package/dist/modules/node_flap_score.js +124 -0
- package/dist/modules/node_health_cache.d.ts +40 -3
- package/dist/modules/node_health_cache.js +66 -20
- package/dist/modules/node_manager.d.ts +101 -19
- package/dist/modules/node_manager.js +255 -65
- package/dist/modules/order/accounting.js +56 -7
- package/dist/modules/order/format.d.ts +24 -10
- package/dist/modules/order/format.js +30 -10
- package/dist/modules/order/grid.js +91 -13
- package/dist/modules/order/grid_reconcile.d.ts +5 -1
- package/dist/modules/order/grid_reconcile.js +333 -189
- package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
- package/dist/modules/order/grid_reconcile_internal.js +298 -100
- package/dist/modules/order/index.d.ts +19 -1
- package/dist/modules/order/lifecycle.d.ts +353 -0
- package/dist/modules/order/lifecycle.js +1109 -0
- package/dist/modules/order/manager.d.ts +273 -5
- package/dist/modules/order/manager.js +654 -48
- package/dist/modules/order/placement_lock.d.ts +102 -0
- package/dist/modules/order/placement_lock.js +222 -0
- package/dist/modules/order/strategy.js +13 -1
- package/dist/modules/order/sync_engine.d.ts +33 -1
- package/dist/modules/order/sync_engine.js +241 -73
- package/dist/modules/order/utils/math.d.ts +39 -1
- package/dist/modules/order/utils/math.js +83 -1
- package/dist/modules/order/utils/order.d.ts +181 -5
- package/dist/modules/order/utils/order.js +455 -9
- package/dist/modules/order/utils/system.d.ts +81 -1
- package/dist/modules/order/utils/system.js +331 -44
- package/dist/modules/order/utils/validate.d.ts +7 -1
- package/dist/modules/order/utils/validate.js +80 -3
- package/dist/modules/outcome.d.ts +54 -0
- package/dist/modules/outcome.js +51 -0
- package/dist/modules/settings_merge.d.ts +4 -0
- package/dist/modules/settings_merge.js +9 -0
- package/dist/modules/timing_policy.d.ts +82 -0
- package/dist/modules/timing_policy.js +244 -0
- package/dist/modules/types.d.ts +137 -0
- package/dist/modules/utils/asset_symbols.d.ts +13 -2
- package/dist/modules/utils/asset_symbols.js +21 -2
- package/dist/scripts/analysis_runner.d.ts +10 -0
- package/dist/scripts/analysis_runner.js +33 -0
- package/dist/scripts/analyze-credit.js +54 -17
- package/dist/scripts/analyze-orders.d.ts +4 -2
- package/dist/scripts/analyze-orders.js +115 -35
- package/dist/scripts/asset.d.ts +26 -0
- package/dist/scripts/asset.js +165 -0
- package/dist/scripts/bts_distribution.d.ts +1 -0
- package/dist/scripts/bts_distribution.js +194 -142
- package/dist/scripts/chart_command.d.ts +1 -1
- package/dist/scripts/chart_command.js +60 -86
- package/dist/scripts/chart_targets.d.ts +18 -0
- package/dist/scripts/chart_targets.js +48 -0
- package/dist/scripts/dw.js +1 -1
- package/dist/scripts/liquid.d.ts +24 -0
- package/dist/scripts/liquid.js +134 -0
- package/dist/scripts/rich_list.js +12 -16
- package/dist/scripts/test-credit-renewal.js +12 -5
- package/dist/scripts/token_distribution.d.ts +2 -0
- package/dist/scripts/token_distribution.js +132 -108
- package/dist/scripts/tv.js +1 -1
- package/dist/scripts/verify-browser-bundle.js +18 -0
- package/docs/COW_INVARIANTS.md +69 -10
- package/docs/DEXBOT_COMPARISON.md +6 -6
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_PRICE_INVARIANT.md +5 -2
- package/docs/GRID_RECONCILE.md +36 -11
- package/docs/LOGGING.md +50 -4
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +177 -27
- package/docs/README.md +23 -2
- package/docs/WORKFLOW.md +12 -4
- package/docs/architecture.md +42 -5
- package/docs/developer_guide.md +25 -8
- package/modules/README.md +8 -1
- package/package.json +3 -1
- package/scripts/README.md +39 -7
- package/scripts/pdev.sh +14 -1
- package/scripts/pmain.sh +23 -8
- package/scripts/ptest.sh +7 -0
- package/tests/README.md +30 -1
|
@@ -0,0 +1,1109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* modules/order/lifecycle.ts - Order Lifecycle Registry
|
|
3
|
+
*
|
|
4
|
+
* ONE owner for "does this order exist on chain, and how sure are we?".
|
|
5
|
+
*
|
|
6
|
+
* The engine used to answer that question from seven independent structures,
|
|
7
|
+
* each with its own clock:
|
|
8
|
+
*
|
|
9
|
+
* - `_pendingBroadcasts` (fingerprint -> entry, PENDING_BROADCAST_TTL_MS)
|
|
10
|
+
* - `createUncertain` (slot flag, persisted, no clock)
|
|
11
|
+
* - `_committedOrderIds` (Set + built-at stamp, SYNC_LOCK_TIMEOUT_MS)
|
|
12
|
+
* - `_orderIdAssignedAt` (orderId -> ts, no clock)
|
|
13
|
+
* - `_placedAt` (orderId -> ts, SURPLUS_CANCEL_GRACE_MS)
|
|
14
|
+
* - `_chainSizeAppliedFills` (orderId -> marker, CHAIN_SIZE_APPLIED_MARKER_TTL_MS)
|
|
15
|
+
* - `_lastUnmatchedChainOrders` (array, no clock)
|
|
16
|
+
*
|
|
17
|
+
* Four read sites consulted four different subsets and could therefore give
|
|
18
|
+
* four different answers for the same order. That disagreement is the bug
|
|
19
|
+
* class this module removes.
|
|
20
|
+
*
|
|
21
|
+
* MODEL
|
|
22
|
+
* -----
|
|
23
|
+
* A record is keyed by **slot** when the slot is known (a slot is the stable
|
|
24
|
+
* identity across its order incarnations: intent -> chain id -> partial ->
|
|
25
|
+
* gone), by **orderId** when only the chain id is known, and by **fingerprint**
|
|
26
|
+
* when a CREATE has neither yet. `LifecycleView` is the single read surface:
|
|
27
|
+
* every consumer asks the same questions of the same record.
|
|
28
|
+
*
|
|
29
|
+
* The legacy structures are preserved as *facade views* (`_placedAt`, ...)
|
|
30
|
+
* backed by this registry, so existing call sites keep working while the
|
|
31
|
+
* truth lives in one place. See `LifecycleRegistry` accessors below.
|
|
32
|
+
*/
|
|
33
|
+
import { TIMING } from '../constants.js';
|
|
34
|
+
/**
|
|
35
|
+
* How much a piece of evidence proves, weakest first.
|
|
36
|
+
*
|
|
37
|
+
* Evidence is MONOTONIC within a phase: a local re-assertion of the same phase
|
|
38
|
+
* (the write funnel runs after a sync pass already recorded what the chain said)
|
|
39
|
+
* must not overwrite `chain-snapshot` with `local`. The rank makes that rule
|
|
40
|
+
* mechanical instead of a convention every writer has to remember.
|
|
41
|
+
*/
|
|
42
|
+
const EVIDENCE_RANK = {
|
|
43
|
+
none: 0,
|
|
44
|
+
local: 1,
|
|
45
|
+
'broadcast-receipt': 2,
|
|
46
|
+
adoption: 3,
|
|
47
|
+
'chain-snapshot': 4,
|
|
48
|
+
'fill-history': 5,
|
|
49
|
+
};
|
|
50
|
+
/** True for the phases where the engine has evidence of a problem, not an answer. */
|
|
51
|
+
function isUnresolvedPhase(phase) {
|
|
52
|
+
return phase === 'unknown' || phase === 'broadcasting';
|
|
53
|
+
}
|
|
54
|
+
/** True when the evidence came from outside the process. */
|
|
55
|
+
function isChainBacked(evidence) {
|
|
56
|
+
return evidence === 'chain-snapshot' || evidence === 'fill-history' || evidence === 'adoption';
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* When the current uncertainty was recorded (0 = no clock).
|
|
60
|
+
*
|
|
61
|
+
* The newer of the two clocks: a chain answer that already told us "unreadable"
|
|
62
|
+
* is the latest thing we know, and the local re-recording that followed it must
|
|
63
|
+
* not restart the bound. Every consumer of the unresolved bound (isInFlight,
|
|
64
|
+
* markIntentIfResolved, pruning) measures from here, so they cannot drift.
|
|
65
|
+
*/
|
|
66
|
+
function unresolvedAnchor(record) {
|
|
67
|
+
const recorded = Number(record?.recordedAt) || 0;
|
|
68
|
+
const observed = Number(record?.observedAt) || 0;
|
|
69
|
+
return Math.max(recorded, observed);
|
|
70
|
+
}
|
|
71
|
+
// ===============================================================================
|
|
72
|
+
// SECTION 2: WINDOWS
|
|
73
|
+
// ===============================================================================
|
|
74
|
+
//
|
|
75
|
+
// Every window the registry consults is read here, once, through
|
|
76
|
+
// `timingWindowMs`. The old shape — `Number(TIMING.X) > 0 ? Number(TIMING.X) :
|
|
77
|
+
// <literal>` copy-pasted per site — is how a window's value and its fallback
|
|
78
|
+
// drift apart from the constant they claim to describe.
|
|
79
|
+
/**
|
|
80
|
+
* Read a timing window in milliseconds with a fallback for a missing constant.
|
|
81
|
+
*
|
|
82
|
+
* The fallback exists for fixtures that stub `TIMING` with a partial object. It
|
|
83
|
+
* must never be a SECOND definition of the window: it is the value the constant
|
|
84
|
+
* already carries (see modules/constants.ts), applied only when the constant is
|
|
85
|
+
* absent or unusable.
|
|
86
|
+
*
|
|
87
|
+
* @param key - TIMING key
|
|
88
|
+
* @param fallback - Value to use when the constant is missing/unusable
|
|
89
|
+
* @returns {number} Positive window length in milliseconds
|
|
90
|
+
*/
|
|
91
|
+
export function timingWindowMs(key, fallback) {
|
|
92
|
+
const raw = Number(TIMING[key]);
|
|
93
|
+
return Number.isFinite(raw) && raw > 0 ? raw : fallback;
|
|
94
|
+
}
|
|
95
|
+
/** Fresh-placement grace (surplus-cancel protection). */
|
|
96
|
+
function surplusCancelGraceMs() {
|
|
97
|
+
return timingWindowMs('SURPLUS_CANCEL_GRACE_MS', 15 * 60 * 1000);
|
|
98
|
+
}
|
|
99
|
+
/** Post-commit protection window (a lagging snapshot must not virtualize). */
|
|
100
|
+
function commitProtectionWindowMs() {
|
|
101
|
+
return timingWindowMs('SYNC_LOCK_TIMEOUT_MS', 20_000);
|
|
102
|
+
}
|
|
103
|
+
/** Retention of an unresolved pending-CREATE entry. */
|
|
104
|
+
export function pendingBroadcastTtlMs() {
|
|
105
|
+
return timingWindowMs('PENDING_BROADCAST_TTL_MS', 30 * 60 * 1000);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* How long an unresolved (`unknown` / `broadcasting`) record may suppress an
|
|
109
|
+
* absence decision.
|
|
110
|
+
*
|
|
111
|
+
* The old per-site guards each carried a time escape hatch — "a permanently
|
|
112
|
+
* lagging node must not park CREATEs forever". Unifying the sources must not
|
|
113
|
+
* drop that hatch, so the same bound (2× the pending-broadcast TTL, which is
|
|
114
|
+
* the longest existing unblock window) applies to every unresolved phase.
|
|
115
|
+
* Past it the order is presumed gone and normal cleanup proceeds.
|
|
116
|
+
*
|
|
117
|
+
* The bound is only honest if it is measured from when the uncertainty was
|
|
118
|
+
* RECORDED: a caller re-asserting `unknown` without new evidence must not push
|
|
119
|
+
* the deadline out (see `observe`).
|
|
120
|
+
*/
|
|
121
|
+
function unresolvedBoundMs() {
|
|
122
|
+
return pendingBroadcastTtlMs() * 2;
|
|
123
|
+
}
|
|
124
|
+
// ===============================================================================
|
|
125
|
+
// SECTION 3: KEY HELPERS
|
|
126
|
+
// ===============================================================================
|
|
127
|
+
const SLOT_PREFIX = 'slot:';
|
|
128
|
+
const ORDER_PREFIX = 'order:';
|
|
129
|
+
function asKey(value) {
|
|
130
|
+
if (value == null)
|
|
131
|
+
return null;
|
|
132
|
+
const text = String(value);
|
|
133
|
+
return text.length > 0 ? text : null;
|
|
134
|
+
}
|
|
135
|
+
// ===============================================================================
|
|
136
|
+
// SECTION 4: LIFECYCLE VIEW
|
|
137
|
+
// ===============================================================================
|
|
138
|
+
class LifecycleViewImpl {
|
|
139
|
+
record;
|
|
140
|
+
now;
|
|
141
|
+
constructor(record, now) {
|
|
142
|
+
this.record = record;
|
|
143
|
+
this.now = now;
|
|
144
|
+
}
|
|
145
|
+
get slotId() { return this.record?.slotId ?? null; }
|
|
146
|
+
get orderId() { return this.record?.orderId ?? null; }
|
|
147
|
+
get phase() { return this.record?.phase ?? 'intent'; }
|
|
148
|
+
get evidence() { return this.record?.evidence ?? 'none'; }
|
|
149
|
+
get recordedAt() { return this.record?.recordedAt ?? 0; }
|
|
150
|
+
get observedAt() { return this.record?.observedAt ?? 0; }
|
|
151
|
+
get assignedAt() { return this.record?.assignedAt ?? 0; }
|
|
152
|
+
get placedAt() { return this.record?.placedAt ?? 0; }
|
|
153
|
+
get committedAt() { return this.record?.committedAt ?? 0; }
|
|
154
|
+
get pending() { return this.record?.pending ?? null; }
|
|
155
|
+
get isUnknown() { return this.phase === 'unknown'; }
|
|
156
|
+
get isUnresolved() { return isUnresolvedPhase(this.phase); }
|
|
157
|
+
get isConfirmedGone() { return this.phase === 'gone'; }
|
|
158
|
+
get isIntentOnly() { return this.phase === 'intent'; }
|
|
159
|
+
get isOnChain() { return this.phase === 'landed' || this.phase === 'filling'; }
|
|
160
|
+
get mayExistOnChain() {
|
|
161
|
+
// `intent` and `gone` are the only phases where nothing can be resting
|
|
162
|
+
// on chain. `unknown` MUST count as "may exist" — guessing "absent" is
|
|
163
|
+
// the exact failure this whole module exists to prevent.
|
|
164
|
+
return this.phase === 'broadcasting' || this.isOnChain || this.isUnknown;
|
|
165
|
+
}
|
|
166
|
+
isFreshlyPlaced(graceMs, now) {
|
|
167
|
+
const placedAt = this.placedAt;
|
|
168
|
+
if (!Number.isFinite(placedAt) || placedAt <= 0)
|
|
169
|
+
return false;
|
|
170
|
+
const window = Number.isFinite(Number(graceMs)) && Number(graceMs) > 0
|
|
171
|
+
? Number(graceMs)
|
|
172
|
+
: surplusCancelGraceMs();
|
|
173
|
+
const clock = Number.isFinite(Number(now)) ? Number(now) : this.now();
|
|
174
|
+
return clock - placedAt < window;
|
|
175
|
+
}
|
|
176
|
+
isRecentlyCommitted(windowMs, now) {
|
|
177
|
+
if (!this.record)
|
|
178
|
+
return false;
|
|
179
|
+
const committedAt = this.record.committedSnapshotAt > 0
|
|
180
|
+
? this.record.committedSnapshotAt
|
|
181
|
+
: this.committedAt;
|
|
182
|
+
if (!Number.isFinite(committedAt) || committedAt <= 0)
|
|
183
|
+
return false;
|
|
184
|
+
const window = Number.isFinite(Number(windowMs)) && Number(windowMs) > 0
|
|
185
|
+
? Number(windowMs)
|
|
186
|
+
: commitProtectionWindowMs();
|
|
187
|
+
const clock = Number.isFinite(Number(now)) ? Number(now) : this.now();
|
|
188
|
+
return clock - committedAt < window;
|
|
189
|
+
}
|
|
190
|
+
isRecentlyAssigned(windowMs, now) {
|
|
191
|
+
const assignedAt = this.assignedAt;
|
|
192
|
+
if (!Number.isFinite(assignedAt) || assignedAt <= 0)
|
|
193
|
+
return false;
|
|
194
|
+
const window = Number.isFinite(Number(windowMs)) && Number(windowMs) > 0
|
|
195
|
+
? Number(windowMs)
|
|
196
|
+
: commitProtectionWindowMs();
|
|
197
|
+
const clock = Number.isFinite(Number(now)) ? Number(now) : this.now();
|
|
198
|
+
return clock - assignedAt < window;
|
|
199
|
+
}
|
|
200
|
+
isInFlight(windowMs, now) {
|
|
201
|
+
if (this.isRecentlyAssigned(windowMs, now) || this.isRecentlyCommitted(windowMs, now))
|
|
202
|
+
return true;
|
|
203
|
+
if (this.isUnknown || this.phase === 'broadcasting')
|
|
204
|
+
return this.isUnresolvedFresh(now);
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
isUnresolvedFresh(now) {
|
|
208
|
+
const clock = Number.isFinite(Number(now)) ? Number(now) : this.now();
|
|
209
|
+
const from = unresolvedAnchor(this.record);
|
|
210
|
+
if (!(from > 0))
|
|
211
|
+
return false;
|
|
212
|
+
return clock - from < unresolvedBoundMs();
|
|
213
|
+
}
|
|
214
|
+
isChainBacked() {
|
|
215
|
+
return isChainBacked(this.evidence);
|
|
216
|
+
}
|
|
217
|
+
appliedFillMatches(filledInt) {
|
|
218
|
+
if (!this.record)
|
|
219
|
+
return false;
|
|
220
|
+
const applied = this.record.appliedFillInt;
|
|
221
|
+
if (applied == null)
|
|
222
|
+
return false;
|
|
223
|
+
return Number(applied) === Number(filledInt);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
class LifecycleMapView extends Map {
|
|
227
|
+
source;
|
|
228
|
+
constructor(source) {
|
|
229
|
+
super();
|
|
230
|
+
this.source = source;
|
|
231
|
+
}
|
|
232
|
+
get size() {
|
|
233
|
+
let count = 0;
|
|
234
|
+
for (const _ of this.source.entries())
|
|
235
|
+
count += 1;
|
|
236
|
+
return count;
|
|
237
|
+
}
|
|
238
|
+
get(key) { return this.source.get(String(key)); }
|
|
239
|
+
has(key) { return this.source.get(String(key)) !== undefined; }
|
|
240
|
+
set(key, value) {
|
|
241
|
+
this.source.set(String(key), value);
|
|
242
|
+
return this;
|
|
243
|
+
}
|
|
244
|
+
delete(key) {
|
|
245
|
+
if (this.source.get(String(key)) === undefined)
|
|
246
|
+
return false;
|
|
247
|
+
this.source.delete(String(key));
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
clear() { this.source.clear(); }
|
|
251
|
+
*keys() {
|
|
252
|
+
for (const [key] of this.source.entries())
|
|
253
|
+
yield key;
|
|
254
|
+
}
|
|
255
|
+
*values() {
|
|
256
|
+
for (const [, value] of this.source.entries())
|
|
257
|
+
yield value;
|
|
258
|
+
}
|
|
259
|
+
*entries() {
|
|
260
|
+
for (const pair of this.source.entries())
|
|
261
|
+
yield pair;
|
|
262
|
+
}
|
|
263
|
+
forEach(callback, thisArg) {
|
|
264
|
+
for (const [key, value] of this.source.entries())
|
|
265
|
+
callback.call(thisArg, value, key, this);
|
|
266
|
+
}
|
|
267
|
+
[Symbol.iterator]() { return this.entries(); }
|
|
268
|
+
}
|
|
269
|
+
class LifecycleSetView extends Set {
|
|
270
|
+
source;
|
|
271
|
+
constructor(source) {
|
|
272
|
+
super();
|
|
273
|
+
this.source = source;
|
|
274
|
+
}
|
|
275
|
+
get size() {
|
|
276
|
+
let count = 0;
|
|
277
|
+
for (const _ of this.source.values())
|
|
278
|
+
count += 1;
|
|
279
|
+
return count;
|
|
280
|
+
}
|
|
281
|
+
has(value) { return this.source.has(String(value)); }
|
|
282
|
+
add(value) {
|
|
283
|
+
this.source.add(String(value));
|
|
284
|
+
return this;
|
|
285
|
+
}
|
|
286
|
+
delete(value) {
|
|
287
|
+
if (!this.source.has(String(value)))
|
|
288
|
+
return false;
|
|
289
|
+
this.source.delete(String(value));
|
|
290
|
+
return true;
|
|
291
|
+
}
|
|
292
|
+
clear() { this.source.clear(); }
|
|
293
|
+
*values() {
|
|
294
|
+
for (const value of this.source.values())
|
|
295
|
+
yield value;
|
|
296
|
+
}
|
|
297
|
+
*keys() {
|
|
298
|
+
for (const value of this.source.values())
|
|
299
|
+
yield value;
|
|
300
|
+
}
|
|
301
|
+
*entries() {
|
|
302
|
+
for (const value of this.source.values())
|
|
303
|
+
yield [value, value];
|
|
304
|
+
}
|
|
305
|
+
forEach(callback, thisArg) {
|
|
306
|
+
for (const value of this.source.values())
|
|
307
|
+
callback.call(thisArg, value, value, this);
|
|
308
|
+
}
|
|
309
|
+
[Symbol.iterator]() { return this.values(); }
|
|
310
|
+
}
|
|
311
|
+
export class LifecycleRegistry {
|
|
312
|
+
records = new Map();
|
|
313
|
+
byOrderId = new Map();
|
|
314
|
+
bySlotId = new Map();
|
|
315
|
+
byFingerprint = new Map();
|
|
316
|
+
now;
|
|
317
|
+
maxRecords;
|
|
318
|
+
/**
|
|
319
|
+
* The single "last committed snapshot" stamp. The COW engine publishes a
|
|
320
|
+
* whole Set of committed ids at once, and the protection window is measured
|
|
321
|
+
* from that publish, not from each id. Kept here so the stamp cannot drift
|
|
322
|
+
* away from the ids it describes.
|
|
323
|
+
*/
|
|
324
|
+
committedSnapshotAt = 0;
|
|
325
|
+
/** Facade for `manager._placedAt`. */
|
|
326
|
+
placedAt;
|
|
327
|
+
/** Facade for `manager._orderIdAssignedAt`. */
|
|
328
|
+
assignedAt;
|
|
329
|
+
/** Facade for `manager._committedOrderIds`. */
|
|
330
|
+
committedIds;
|
|
331
|
+
/** Facade for `manager._pendingBroadcasts` (keyed by fingerprint). */
|
|
332
|
+
pendingBroadcasts;
|
|
333
|
+
/** Facade for `manager._chainSizeAppliedFills`. */
|
|
334
|
+
appliedFills;
|
|
335
|
+
constructor(options = {}) {
|
|
336
|
+
this.now = typeof options.now === 'function' ? options.now : () => Date.now();
|
|
337
|
+
this.maxRecords = Number.isFinite(Number(options.maxRecords)) && Number(options.maxRecords) > 0
|
|
338
|
+
? Number(options.maxRecords)
|
|
339
|
+
: 5000;
|
|
340
|
+
this.placedAt = new LifecycleMapView({
|
|
341
|
+
entries: () => this.placedEntries(),
|
|
342
|
+
get: (key) => {
|
|
343
|
+
const record = this.findByIdentity(key);
|
|
344
|
+
return record && record.placedAt > 0 ? record.placedAt : undefined;
|
|
345
|
+
},
|
|
346
|
+
set: (key, value) => this.writePlacedAt(key, value),
|
|
347
|
+
delete: (key) => this.writePlacedAt(key, 0),
|
|
348
|
+
clear: () => this.clearPlacedAt(),
|
|
349
|
+
});
|
|
350
|
+
this.assignedAt = new LifecycleMapView({
|
|
351
|
+
entries: () => this.assignedEntries(),
|
|
352
|
+
get: (key) => {
|
|
353
|
+
const record = this.findByIdentity(key);
|
|
354
|
+
return record && record.assignedAt > 0 ? record.assignedAt : undefined;
|
|
355
|
+
},
|
|
356
|
+
set: (key, value) => this.writeAssignedAt(key, value),
|
|
357
|
+
delete: (key) => this.writeAssignedAt(key, 0),
|
|
358
|
+
clear: () => this.clearAssignedAt(),
|
|
359
|
+
});
|
|
360
|
+
this.committedIds = new LifecycleSetView({
|
|
361
|
+
values: () => this.committedValues(),
|
|
362
|
+
has: (id) => {
|
|
363
|
+
const record = this.findByIdentity(id);
|
|
364
|
+
return !!record && record.committedAt > 0;
|
|
365
|
+
},
|
|
366
|
+
add: (id) => this.writeCommitted(id, this.now()),
|
|
367
|
+
delete: (id) => this.writeCommitted(id, 0),
|
|
368
|
+
clear: () => this.clearCommitted(),
|
|
369
|
+
});
|
|
370
|
+
this.pendingBroadcasts = new LifecycleMapView({
|
|
371
|
+
entries: () => this.pendingEntries(),
|
|
372
|
+
get: (fingerprint) => this.getPending(fingerprint),
|
|
373
|
+
set: (fingerprint, entry) => { this.setPending(fingerprint, entry); },
|
|
374
|
+
delete: (fingerprint) => { this.deletePending(fingerprint); },
|
|
375
|
+
clear: () => { this.clearPending(); },
|
|
376
|
+
});
|
|
377
|
+
this.appliedFills = new LifecycleMapView({
|
|
378
|
+
entries: () => this.appliedEntries(),
|
|
379
|
+
get: (id) => {
|
|
380
|
+
const record = this.findByIdentity(id);
|
|
381
|
+
if (!record || record.appliedFillInt == null)
|
|
382
|
+
return undefined;
|
|
383
|
+
return { filledInt: Number(record.appliedFillInt), at: Number(record.appliedFillAt) || 0 };
|
|
384
|
+
},
|
|
385
|
+
set: (id, value) => this.writeAppliedFill(id, value),
|
|
386
|
+
delete: (id) => this.writeAppliedFill(id, null),
|
|
387
|
+
clear: () => this.clearAppliedFills(),
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
// ---------------------------------------------------------------------------
|
|
391
|
+
// Record plumbing
|
|
392
|
+
// ---------------------------------------------------------------------------
|
|
393
|
+
createRecord(key) {
|
|
394
|
+
const record = {
|
|
395
|
+
key,
|
|
396
|
+
slotId: null,
|
|
397
|
+
orderId: null,
|
|
398
|
+
fingerprint: null,
|
|
399
|
+
phase: 'intent',
|
|
400
|
+
evidence: 'none',
|
|
401
|
+
recordedAt: this.now(),
|
|
402
|
+
observedAt: 0,
|
|
403
|
+
assignedAt: 0,
|
|
404
|
+
placedAt: 0,
|
|
405
|
+
committedAt: 0,
|
|
406
|
+
appliedFillInt: null,
|
|
407
|
+
appliedFillAt: null,
|
|
408
|
+
committedSnapshotAt: 0,
|
|
409
|
+
pending: null,
|
|
410
|
+
revision: 1,
|
|
411
|
+
};
|
|
412
|
+
this.records.set(key, record);
|
|
413
|
+
this.prune(key);
|
|
414
|
+
return record;
|
|
415
|
+
}
|
|
416
|
+
keyForSlot(slotId) { return `${SLOT_PREFIX}${slotId}`; }
|
|
417
|
+
keyForOrder(orderId) { return `${ORDER_PREFIX}${orderId}`; }
|
|
418
|
+
/**
|
|
419
|
+
* Find (or create) the record that owns this slot, claiming any order-only
|
|
420
|
+
* record for `orderId` on the way so a slot's life never forks in two.
|
|
421
|
+
*/
|
|
422
|
+
recordForSlot(slotId, orderId) {
|
|
423
|
+
if (slotId) {
|
|
424
|
+
const existingKey = this.bySlotId.get(slotId);
|
|
425
|
+
if (existingKey) {
|
|
426
|
+
const existing = this.records.get(existingKey);
|
|
427
|
+
if (existing) {
|
|
428
|
+
if (orderId)
|
|
429
|
+
this.linkOrderId(existing, orderId);
|
|
430
|
+
return existing;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
// Claim an order-only record so the slot becomes the single owner.
|
|
434
|
+
const orderKey = orderId ? this.byOrderId.get(orderId) : undefined;
|
|
435
|
+
if (orderKey && orderKey !== this.keyForSlot(slotId)) {
|
|
436
|
+
const claimed = this.records.get(orderKey);
|
|
437
|
+
if (claimed && claimed.slotId == null) {
|
|
438
|
+
this.records.delete(orderKey);
|
|
439
|
+
claimed.key = this.keyForSlot(slotId);
|
|
440
|
+
claimed.slotId = slotId;
|
|
441
|
+
this.records.set(claimed.key, claimed);
|
|
442
|
+
this.bySlotId.set(slotId, claimed.key);
|
|
443
|
+
// The order index still points at the retired key; re-point it
|
|
444
|
+
// or every lookup by chain id would miss this record.
|
|
445
|
+
if (claimed.orderId)
|
|
446
|
+
this.byOrderId.set(claimed.orderId, claimed.key);
|
|
447
|
+
claimed.revision += 1;
|
|
448
|
+
return claimed;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const created = this.createRecord(this.keyForSlot(slotId));
|
|
452
|
+
created.slotId = slotId;
|
|
453
|
+
this.bySlotId.set(slotId, created.key);
|
|
454
|
+
if (orderId)
|
|
455
|
+
this.linkOrderId(created, orderId);
|
|
456
|
+
return created;
|
|
457
|
+
}
|
|
458
|
+
if (orderId) {
|
|
459
|
+
const existingKey = this.byOrderId.get(orderId);
|
|
460
|
+
const existing = existingKey ? this.records.get(existingKey) : undefined;
|
|
461
|
+
if (existing)
|
|
462
|
+
return existing;
|
|
463
|
+
const created = this.createRecord(this.keyForOrder(orderId));
|
|
464
|
+
created.orderId = orderId;
|
|
465
|
+
this.byOrderId.set(orderId, created.key);
|
|
466
|
+
return created;
|
|
467
|
+
}
|
|
468
|
+
throw new Error('LifecycleRegistry: need a slotId, orderId or fingerprint');
|
|
469
|
+
}
|
|
470
|
+
linkOrderId(record, orderId) {
|
|
471
|
+
if (!orderId)
|
|
472
|
+
return;
|
|
473
|
+
if (record.orderId === orderId) {
|
|
474
|
+
this.byOrderId.set(orderId, record.key);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
// If an order-only record already claimed this chain id (a stamp written
|
|
478
|
+
// before the slot was known), fold its facts in and drop it. Without this
|
|
479
|
+
// merge, every placement would leak one unreachable order-keyed record
|
|
480
|
+
// and its `placedAt`/`committedAt` stamps would be stranded on it —
|
|
481
|
+
// making the slot look never-freshly-placed.
|
|
482
|
+
const previousKey = this.byOrderId.get(orderId);
|
|
483
|
+
if (previousKey && previousKey !== record.key) {
|
|
484
|
+
const orphan = this.records.get(previousKey);
|
|
485
|
+
if (orphan && !orphan.slotId && !orphan.pending) {
|
|
486
|
+
record.placedAt = Math.max(record.placedAt, orphan.placedAt);
|
|
487
|
+
record.assignedAt = Math.max(record.assignedAt, orphan.assignedAt);
|
|
488
|
+
record.committedAt = Math.max(record.committedAt, orphan.committedAt);
|
|
489
|
+
record.observedAt = Math.max(record.observedAt, orphan.observedAt);
|
|
490
|
+
if (record.appliedFillInt == null && orphan.appliedFillInt != null) {
|
|
491
|
+
record.appliedFillInt = orphan.appliedFillInt;
|
|
492
|
+
record.appliedFillAt = orphan.appliedFillAt;
|
|
493
|
+
}
|
|
494
|
+
// dropRecord (not a bare delete) so no stale index entry is left
|
|
495
|
+
// pointing at a key that no longer exists.
|
|
496
|
+
this.dropRecord(orphan);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
if (record.orderId)
|
|
500
|
+
this.byOrderId.delete(record.orderId);
|
|
501
|
+
record.orderId = orderId;
|
|
502
|
+
this.byOrderId.set(orderId, record.key);
|
|
503
|
+
record.revision += 1;
|
|
504
|
+
}
|
|
505
|
+
/** Record for a fingerprint whose CREATE has no slot id yet. */
|
|
506
|
+
recordForFingerprint(fingerprint) {
|
|
507
|
+
const existingKey = this.byFingerprint.get(fingerprint);
|
|
508
|
+
const existing = existingKey ? this.records.get(existingKey) : undefined;
|
|
509
|
+
if (existing)
|
|
510
|
+
return existing;
|
|
511
|
+
const created = this.createRecord(`fp:${fingerprint}`);
|
|
512
|
+
created.fingerprint = fingerprint;
|
|
513
|
+
this.byFingerprint.set(fingerprint, created.key);
|
|
514
|
+
return created;
|
|
515
|
+
}
|
|
516
|
+
/** Resolve a record from any of the three identities. */
|
|
517
|
+
findByIdentity(id) {
|
|
518
|
+
const key = asKey(id);
|
|
519
|
+
if (!key)
|
|
520
|
+
return undefined;
|
|
521
|
+
const bySlot = this.bySlotId.get(key);
|
|
522
|
+
if (bySlot)
|
|
523
|
+
return this.records.get(bySlot);
|
|
524
|
+
const byOrder = this.byOrderId.get(key);
|
|
525
|
+
if (byOrder)
|
|
526
|
+
return this.records.get(byOrder);
|
|
527
|
+
const byFp = this.byFingerprint.get(key);
|
|
528
|
+
if (byFp)
|
|
529
|
+
return this.records.get(byFp);
|
|
530
|
+
// A raw registry key (tests / diagnostics).
|
|
531
|
+
return this.records.get(key);
|
|
532
|
+
}
|
|
533
|
+
prune(exceptKey) {
|
|
534
|
+
if (this.records.size <= this.maxRecords)
|
|
535
|
+
return;
|
|
536
|
+
// Evict settled records oldest-first. `unknown`/`broadcasting` records
|
|
537
|
+
// are never evicted while their uncertainty is live: they are the ones
|
|
538
|
+
// that must not be forgotten. Past the unresolved bound they are no
|
|
539
|
+
// longer consulted by any decision (isInFlight() released them), so they
|
|
540
|
+
// become evictable like any other settled record — otherwise a bot that
|
|
541
|
+
// keeps losing CREATE receipts grows this registry without a ceiling.
|
|
542
|
+
// `exceptKey` is the record just created — it must survive its own
|
|
543
|
+
// insertion even when it shares a millisecond with older records.
|
|
544
|
+
const clock = this.now();
|
|
545
|
+
const evictable = [];
|
|
546
|
+
for (const record of this.records.values()) {
|
|
547
|
+
if (record.key === exceptKey)
|
|
548
|
+
continue;
|
|
549
|
+
if (!this.isEvictable(record, clock))
|
|
550
|
+
continue;
|
|
551
|
+
evictable.push(record);
|
|
552
|
+
}
|
|
553
|
+
evictable.sort((a, b) => a.recordedAt - b.recordedAt);
|
|
554
|
+
const overflow = this.records.size - this.maxRecords;
|
|
555
|
+
for (let i = 0; i < overflow && i < evictable.length; i += 1) {
|
|
556
|
+
this.dropRecord(evictable[i]);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
/** True when a record carries no live uncertainty and may be evicted. */
|
|
560
|
+
isEvictable(record, clock) {
|
|
561
|
+
if (!isUnresolvedPhase(record.phase))
|
|
562
|
+
return true;
|
|
563
|
+
const since = unresolvedAnchor(record);
|
|
564
|
+
if (!(since > 0))
|
|
565
|
+
return true;
|
|
566
|
+
return clock - since >= unresolvedBoundMs();
|
|
567
|
+
}
|
|
568
|
+
dropRecord(record) {
|
|
569
|
+
this.records.delete(record.key);
|
|
570
|
+
if (record.orderId)
|
|
571
|
+
this.byOrderId.delete(record.orderId);
|
|
572
|
+
if (record.slotId)
|
|
573
|
+
this.bySlotId.delete(record.slotId);
|
|
574
|
+
if (record.fingerprint)
|
|
575
|
+
this.byFingerprint.delete(record.fingerprint);
|
|
576
|
+
}
|
|
577
|
+
// ---------------------------------------------------------------------------
|
|
578
|
+
// Public reads
|
|
579
|
+
// ---------------------------------------------------------------------------
|
|
580
|
+
/** Resolve a read surface for any identity (slot / orderId / fingerprint). */
|
|
581
|
+
view(id) {
|
|
582
|
+
return new LifecycleViewImpl(this.findByIdentity(id) ?? null, this.now);
|
|
583
|
+
}
|
|
584
|
+
/** Raw record (diagnostics / tests). Returns a frozen copy. */
|
|
585
|
+
snapshot(id) {
|
|
586
|
+
const record = this.findByIdentity(id);
|
|
587
|
+
return record ? Object.freeze({ ...record }) : null;
|
|
588
|
+
}
|
|
589
|
+
size() { return this.records.size; }
|
|
590
|
+
/**
|
|
591
|
+
* A read-only view with one phase overridden, without touching the record.
|
|
592
|
+
*
|
|
593
|
+
* Used where a caller holds extra evidence the registry does not (a
|
|
594
|
+
* persisted per-slot flag): the read must reflect it, but a read must not
|
|
595
|
+
* write. Mutating here would also refresh `recordedAt` on every call and
|
|
596
|
+
* keep `isUnresolvedFresh` eternally true.
|
|
597
|
+
*
|
|
598
|
+
* @param identity - Slot id, chain order id or fingerprint
|
|
599
|
+
* @param phase - Phase to report
|
|
600
|
+
* @param evidence - Evidence backing the overridden phase
|
|
601
|
+
* @returns {LifecycleView} Read surface over a copy
|
|
602
|
+
*/
|
|
603
|
+
withPhase(identity, phase, evidence) {
|
|
604
|
+
const record = this.findByIdentity(identity);
|
|
605
|
+
const base = record
|
|
606
|
+
? { ...record }
|
|
607
|
+
: {
|
|
608
|
+
key: `transient:${String(identity)}`,
|
|
609
|
+
slotId: null,
|
|
610
|
+
orderId: asKey(identity),
|
|
611
|
+
fingerprint: null,
|
|
612
|
+
phase,
|
|
613
|
+
evidence,
|
|
614
|
+
// No recorded clock: a synthesized record has no evidence time,
|
|
615
|
+
// and stamping `now` here would make an aged marker look fresh on
|
|
616
|
+
// every read (the suppression bound would never expire).
|
|
617
|
+
recordedAt: 0,
|
|
618
|
+
observedAt: 0,
|
|
619
|
+
assignedAt: 0,
|
|
620
|
+
placedAt: 0,
|
|
621
|
+
committedAt: 0,
|
|
622
|
+
appliedFillInt: null,
|
|
623
|
+
appliedFillAt: null,
|
|
624
|
+
committedSnapshotAt: 0,
|
|
625
|
+
pending: null,
|
|
626
|
+
revision: 1,
|
|
627
|
+
};
|
|
628
|
+
base.phase = phase;
|
|
629
|
+
base.evidence = evidence;
|
|
630
|
+
if (phase === 'unknown')
|
|
631
|
+
base.pending = null;
|
|
632
|
+
return new LifecycleViewImpl(base, this.now);
|
|
633
|
+
}
|
|
634
|
+
// ---------------------------------------------------------------------------
|
|
635
|
+
// Public writes
|
|
636
|
+
// ---------------------------------------------------------------------------
|
|
637
|
+
/** Record a planned-only order (nothing broadcast). */
|
|
638
|
+
markIntent(identity, at) {
|
|
639
|
+
const record = this.recordForSlot(identity.slotId ?? null, identity.orderId ?? null);
|
|
640
|
+
record.phase = 'intent';
|
|
641
|
+
record.evidence = 'local';
|
|
642
|
+
record.recordedAt = this.clock(at);
|
|
643
|
+
// Explicit resolution: drop the pending payload AND its index entry, so
|
|
644
|
+
// the facade the engine reads and `pendingSize()` cannot disagree.
|
|
645
|
+
this.dropPending(record);
|
|
646
|
+
record.revision += 1;
|
|
647
|
+
return this.view(identity.slotId ?? identity.orderId ?? null);
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Mark a slot as holding no chain order, but only when nothing unresolved is
|
|
651
|
+
* on record.
|
|
652
|
+
*
|
|
653
|
+
* "Nothing is out there" is a claim that requires evidence. If the record is
|
|
654
|
+
* still `unknown` or `broadcasting`, an unrelated slot mutation (a size tweak,
|
|
655
|
+
* a re-plan) must not silently erase that: the only ways out are an explicit
|
|
656
|
+
* decision by the caller (`markIntent`) or the chain answering.
|
|
657
|
+
*
|
|
658
|
+
* @param slotId - Slot id
|
|
659
|
+
* @param at - Clock override (tests)
|
|
660
|
+
* @returns {LifecycleView}
|
|
661
|
+
*/
|
|
662
|
+
markIntentIfResolved(slotId, at) {
|
|
663
|
+
const identity = asKey(slotId);
|
|
664
|
+
if (!identity)
|
|
665
|
+
return this.view(null);
|
|
666
|
+
const existing = this.findByIdentity(identity);
|
|
667
|
+
if (existing && isUnresolvedPhase(existing.phase)) {
|
|
668
|
+
// Inside the bound the uncertainty still speaks. Past it the bound has
|
|
669
|
+
// already released every absence decision (isInFlight()), so leaving
|
|
670
|
+
// the phase at `unknown` would persist a suppression the engine no
|
|
671
|
+
// longer honours — `mayExistOnChain` true forever, and the record
|
|
672
|
+
// un-evictable. Resolve it here, where the caller is explicitly
|
|
673
|
+
// re-declaring the slot as a clean intent.
|
|
674
|
+
const clock = this.clock(at);
|
|
675
|
+
const since = unresolvedAnchor(existing);
|
|
676
|
+
const expired = !(since > 0) || clock - since >= unresolvedBoundMs();
|
|
677
|
+
if (!expired)
|
|
678
|
+
return new LifecycleViewImpl(existing, this.now);
|
|
679
|
+
}
|
|
680
|
+
return this.markIntent({ slotId: identity }, at);
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Record a state transition observed from an external source.
|
|
684
|
+
*
|
|
685
|
+
* Two rules make the clocks trustworthy:
|
|
686
|
+
*
|
|
687
|
+
* - `observedAt` only advances for chain-backed evidence, so "when did we
|
|
688
|
+
* last hear the truth" cannot be advanced by local bookkeeping.
|
|
689
|
+
* - `recordedAt` (the anchor of the unresolved bound) only advances when the
|
|
690
|
+
* phase actually changes or chain-backed evidence arrives. Re-asserting the
|
|
691
|
+
* same unresolved phase is not new information; refreshing the clock for it
|
|
692
|
+
* would keep `isInFlight()` true forever, which is the opposite of the
|
|
693
|
+
* documented 2× TTL escape hatch.
|
|
694
|
+
*
|
|
695
|
+
* Evidence is monotonic within a phase (see EVIDENCE_RANK): a local write
|
|
696
|
+
* that follows a chain observation keeps the stronger evidence.
|
|
697
|
+
*/
|
|
698
|
+
observe(orderId, input = {}) {
|
|
699
|
+
const slotId = input.slotId ?? null;
|
|
700
|
+
const id = asKey(orderId) ?? slotId;
|
|
701
|
+
if (!id)
|
|
702
|
+
return this.view(null);
|
|
703
|
+
const record = this.recordForSlot(slotId, orderId ?? null);
|
|
704
|
+
const at = this.clock(input.at);
|
|
705
|
+
const phaseChanged = input.phase != null && input.phase !== record.phase;
|
|
706
|
+
const nextEvidence = input.evidence;
|
|
707
|
+
const chainBacked = nextEvidence != null && isChainBacked(nextEvidence);
|
|
708
|
+
const keepsStrongerEvidence = nextEvidence != null
|
|
709
|
+
&& !phaseChanged
|
|
710
|
+
&& EVIDENCE_RANK[nextEvidence] < EVIDENCE_RANK[record.evidence];
|
|
711
|
+
if (input.phase)
|
|
712
|
+
record.phase = input.phase;
|
|
713
|
+
if (nextEvidence && !keepsStrongerEvidence)
|
|
714
|
+
record.evidence = nextEvidence;
|
|
715
|
+
// `recordedAt` doubles as the retention ordering used by `prune`, so a
|
|
716
|
+
// settled record may refresh it freely. The one case that must NOT is a
|
|
717
|
+
// repeated re-assertion of an unresolved phase: that clock is also the
|
|
718
|
+
// anchor of the suppression bound, and refreshing it would make the
|
|
719
|
+
// bound infinite.
|
|
720
|
+
const reassertsUnresolved = !phaseChanged && isUnresolvedPhase(record.phase);
|
|
721
|
+
if (!reassertsUnresolved || chainBacked)
|
|
722
|
+
record.recordedAt = at;
|
|
723
|
+
if (chainBacked) {
|
|
724
|
+
const observed = Number(input.observedAt);
|
|
725
|
+
record.observedAt = Number.isFinite(observed) && observed > 0 ? observed : at;
|
|
726
|
+
}
|
|
727
|
+
if (input.phase !== 'broadcasting' && input.phase !== 'unknown') {
|
|
728
|
+
// The pending CREATE resolved (or was superseded): drop the entry AND
|
|
729
|
+
// its index, so `pendingSize()`/`getPending()` cannot disagree with
|
|
730
|
+
// the facade the rest of the engine reads.
|
|
731
|
+
if (record.pending)
|
|
732
|
+
this.dropPending(record);
|
|
733
|
+
}
|
|
734
|
+
record.revision += 1;
|
|
735
|
+
return this.view(record.slotId ?? record.orderId);
|
|
736
|
+
}
|
|
737
|
+
/** The chain confirmed an open order (full or partial). */
|
|
738
|
+
markLanded(orderId, input = {}) {
|
|
739
|
+
return this.observe(orderId, { ...input, phase: input.phase ?? 'landed', evidence: input.evidence ?? 'chain-snapshot' });
|
|
740
|
+
}
|
|
741
|
+
/** A receipt was lost / a read was ambiguous: the order may exist. */
|
|
742
|
+
markUnknown(orderId, input = {}) {
|
|
743
|
+
return this.observe(orderId, { ...input, phase: 'unknown', evidence: input.evidence ?? 'local' });
|
|
744
|
+
}
|
|
745
|
+
/** Record the chain id assigned to a slot. */
|
|
746
|
+
markAssigned(slotId, orderId, at) {
|
|
747
|
+
const record = this.recordForSlot(slotId ?? null, orderId ?? null);
|
|
748
|
+
if (orderId)
|
|
749
|
+
this.linkOrderId(record, orderId);
|
|
750
|
+
record.assignedAt = this.clock(at);
|
|
751
|
+
record.revision += 1;
|
|
752
|
+
return this.view(slotId ?? orderId);
|
|
753
|
+
}
|
|
754
|
+
/** Record a fresh on-chain placement (surplus-cancel grace anchor). */
|
|
755
|
+
markPlaced(orderId, at, slotId) {
|
|
756
|
+
const id = asKey(orderId);
|
|
757
|
+
if (!id)
|
|
758
|
+
return this.view(null);
|
|
759
|
+
const record = this.recordForSlot(slotId ?? null, id);
|
|
760
|
+
this.linkOrderId(record, id);
|
|
761
|
+
record.placedAt = this.clock(at);
|
|
762
|
+
record.revision += 1;
|
|
763
|
+
return this.view(record.slotId ?? id);
|
|
764
|
+
}
|
|
765
|
+
/**
|
|
766
|
+
* Publish a whole committed-id snapshot atomically (COW commit path).
|
|
767
|
+
* This is the only writer that moves the snapshot stamp.
|
|
768
|
+
*/
|
|
769
|
+
markCommittedSnapshot(orderIds, at) {
|
|
770
|
+
const stamp = this.clock(at);
|
|
771
|
+
const next = new Set();
|
|
772
|
+
for (const id of orderIds) {
|
|
773
|
+
const text = asKey(id);
|
|
774
|
+
if (text)
|
|
775
|
+
next.add(text);
|
|
776
|
+
}
|
|
777
|
+
for (const record of this.records.values()) {
|
|
778
|
+
if (record.orderId && next.has(record.orderId)) {
|
|
779
|
+
record.committedAt = stamp;
|
|
780
|
+
record.committedSnapshotAt = stamp;
|
|
781
|
+
record.revision += 1;
|
|
782
|
+
}
|
|
783
|
+
else if (record.committedAt > 0) {
|
|
784
|
+
// Leaving the committed set means leaving it for the protection
|
|
785
|
+
// window too. Keeping a per-id stamp here would keep an order
|
|
786
|
+
// protected that the engine deliberately dropped (a filled or
|
|
787
|
+
// virtualized order drops out of the next commit's finalMap).
|
|
788
|
+
record.committedAt = 0;
|
|
789
|
+
record.committedSnapshotAt = 0;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
for (const id of next) {
|
|
793
|
+
const record = this.recordForSlot(null, id);
|
|
794
|
+
record.committedAt = stamp;
|
|
795
|
+
record.committedSnapshotAt = stamp;
|
|
796
|
+
record.revision += 1;
|
|
797
|
+
}
|
|
798
|
+
this.committedSnapshotAt = stamp;
|
|
799
|
+
}
|
|
800
|
+
/** The stamp of the last published committed-id snapshot (0 = none). */
|
|
801
|
+
get committedBuiltAt() { return this.committedSnapshotAt; }
|
|
802
|
+
set committedBuiltAt(value) {
|
|
803
|
+
const stamp = Number(value) > 0 ? Number(value) : 0;
|
|
804
|
+
this.committedSnapshotAt = stamp;
|
|
805
|
+
for (const record of this.records.values()) {
|
|
806
|
+
if (record.committedAt > 0)
|
|
807
|
+
record.committedSnapshotAt = stamp;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
/** Record that sync pass 1 already absorbed this chain filled amount. */
|
|
811
|
+
markAppliedFill(orderId, filledInt, at) {
|
|
812
|
+
const id = asKey(orderId);
|
|
813
|
+
if (!id)
|
|
814
|
+
return;
|
|
815
|
+
const record = this.recordForSlot(null, id);
|
|
816
|
+
record.appliedFillInt = Number(filledInt);
|
|
817
|
+
record.appliedFillAt = this.clock(at);
|
|
818
|
+
record.revision += 1;
|
|
819
|
+
}
|
|
820
|
+
/** Forget everything about an identity (cancel confirmed, slot cleared). */
|
|
821
|
+
forget(id) {
|
|
822
|
+
const record = this.findByIdentity(id);
|
|
823
|
+
if (!record)
|
|
824
|
+
return;
|
|
825
|
+
this.dropPending(record);
|
|
826
|
+
this.dropRecord(record);
|
|
827
|
+
}
|
|
828
|
+
// ---------------------------------------------------------------------------
|
|
829
|
+
// Pending CREATE broadcasts (keyed by fingerprint)
|
|
830
|
+
// ---------------------------------------------------------------------------
|
|
831
|
+
setPending(fingerprint, entry) {
|
|
832
|
+
const fp = asKey(fingerprint);
|
|
833
|
+
if (!fp)
|
|
834
|
+
return;
|
|
835
|
+
if (entry == null) {
|
|
836
|
+
this.deletePending(fp);
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
const slotId = entry.slotId != null && String(entry.slotId).length > 0 ? String(entry.slotId) : null;
|
|
840
|
+
const existingKey = this.byFingerprint.get(fp);
|
|
841
|
+
// A pending entry may carry no slot id yet (the CREATE's target was not
|
|
842
|
+
// resolved). It still needs a record, keyed by fingerprint.
|
|
843
|
+
const record = existingKey
|
|
844
|
+
? this.records.get(existingKey)
|
|
845
|
+
: (slotId ? this.recordForSlot(slotId, null) : this.recordForFingerprint(fp));
|
|
846
|
+
if (!record)
|
|
847
|
+
return;
|
|
848
|
+
// A record owns at most ONE fingerprint. Re-recording under a new one
|
|
849
|
+
// (a rebuilt CREATE for the same slot) must retire the previous index
|
|
850
|
+
// entry, or the stale key keeps yielding this record's pending payload.
|
|
851
|
+
if (record.fingerprint && record.fingerprint !== fp) {
|
|
852
|
+
this.byFingerprint.delete(record.fingerprint);
|
|
853
|
+
}
|
|
854
|
+
record.fingerprint = fp;
|
|
855
|
+
record.pending = entry;
|
|
856
|
+
record.phase = 'broadcasting';
|
|
857
|
+
record.evidence = 'local';
|
|
858
|
+
record.recordedAt = this.clock(undefined);
|
|
859
|
+
record.revision += 1;
|
|
860
|
+
this.byFingerprint.set(fp, record.key);
|
|
861
|
+
if (slotId)
|
|
862
|
+
this.bySlotId.set(slotId, record.key);
|
|
863
|
+
}
|
|
864
|
+
getPending(fingerprint) {
|
|
865
|
+
const fp = asKey(fingerprint);
|
|
866
|
+
if (!fp)
|
|
867
|
+
return undefined;
|
|
868
|
+
const key = this.byFingerprint.get(fp);
|
|
869
|
+
const record = key ? this.records.get(key) : undefined;
|
|
870
|
+
return record?.pending ?? undefined;
|
|
871
|
+
}
|
|
872
|
+
deletePending(fingerprint) {
|
|
873
|
+
const fp = asKey(fingerprint);
|
|
874
|
+
if (!fp)
|
|
875
|
+
return;
|
|
876
|
+
const key = this.byFingerprint.get(fp);
|
|
877
|
+
if (!key)
|
|
878
|
+
return;
|
|
879
|
+
const record = this.records.get(key);
|
|
880
|
+
this.byFingerprint.delete(fp);
|
|
881
|
+
if (!record)
|
|
882
|
+
return;
|
|
883
|
+
this.dropPending(record);
|
|
884
|
+
record.revision += 1;
|
|
885
|
+
// Dropping a pending entry means the CREATE resolved. If the record
|
|
886
|
+
// still reads `broadcasting`, nothing was observed afterwards, so the
|
|
887
|
+
// slot is a clean intent again. (An ABANDONED entry goes through
|
|
888
|
+
// `expirePending`, which leaves `unknown` instead — the two cases must
|
|
889
|
+
// not collapse into one.)
|
|
890
|
+
if (record.phase === 'broadcasting')
|
|
891
|
+
record.phase = 'intent';
|
|
892
|
+
if (!record.orderId && !record.slotId)
|
|
893
|
+
this.dropRecord(record);
|
|
894
|
+
}
|
|
895
|
+
/** Drop a record's pending-CREATE payload and its fingerprint index entry. */
|
|
896
|
+
dropPending(record) {
|
|
897
|
+
if (record.fingerprint)
|
|
898
|
+
this.byFingerprint.delete(record.fingerprint);
|
|
899
|
+
record.pending = null;
|
|
900
|
+
record.fingerprint = null;
|
|
901
|
+
}
|
|
902
|
+
clearPending() {
|
|
903
|
+
for (const fingerprint of [...this.byFingerprint.keys()])
|
|
904
|
+
this.deletePending(fingerprint);
|
|
905
|
+
}
|
|
906
|
+
pendingSize() {
|
|
907
|
+
return this.byFingerprint.size;
|
|
908
|
+
}
|
|
909
|
+
*pendingEntries() {
|
|
910
|
+
for (const [fingerprint, key] of [...this.byFingerprint]) {
|
|
911
|
+
const record = this.records.get(key);
|
|
912
|
+
if (record?.pending)
|
|
913
|
+
yield [fingerprint, record.pending];
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
// ---------------------------------------------------------------------------
|
|
917
|
+
// Facade write paths
|
|
918
|
+
// ---------------------------------------------------------------------------
|
|
919
|
+
clock(at) {
|
|
920
|
+
return Number.isFinite(Number(at)) ? Number(at) : this.now();
|
|
921
|
+
}
|
|
922
|
+
writePlacedAt(key, value) {
|
|
923
|
+
const id = asKey(key);
|
|
924
|
+
if (!id)
|
|
925
|
+
return;
|
|
926
|
+
const record = this.recordForSlot(null, id);
|
|
927
|
+
this.linkOrderId(record, id);
|
|
928
|
+
record.placedAt = Number(value) > 0 ? Number(value) : 0;
|
|
929
|
+
record.revision += 1;
|
|
930
|
+
}
|
|
931
|
+
writeAssignedAt(key, value) {
|
|
932
|
+
const id = asKey(key);
|
|
933
|
+
if (!id)
|
|
934
|
+
return;
|
|
935
|
+
const record = this.recordForSlot(null, id);
|
|
936
|
+
this.linkOrderId(record, id);
|
|
937
|
+
record.assignedAt = Number(value) > 0 ? Number(value) : 0;
|
|
938
|
+
record.revision += 1;
|
|
939
|
+
}
|
|
940
|
+
writeCommitted(key, value) {
|
|
941
|
+
const id = asKey(key);
|
|
942
|
+
if (!id)
|
|
943
|
+
return;
|
|
944
|
+
const record = this.recordForSlot(null, id);
|
|
945
|
+
this.linkOrderId(record, id);
|
|
946
|
+
record.committedAt = Number(value) > 0 ? Number(value) : 0;
|
|
947
|
+
// A per-id write supersedes the published snapshot for this record, in
|
|
948
|
+
// both directions: a re-add stamps fresh, a delete clears protection
|
|
949
|
+
// even if a snapshot had been published earlier.
|
|
950
|
+
record.committedSnapshotAt = 0;
|
|
951
|
+
record.revision += 1;
|
|
952
|
+
}
|
|
953
|
+
writeAppliedFill(key, value) {
|
|
954
|
+
const id = asKey(key);
|
|
955
|
+
if (!id)
|
|
956
|
+
return;
|
|
957
|
+
const record = this.recordForSlot(null, id);
|
|
958
|
+
this.linkOrderId(record, id);
|
|
959
|
+
if (value == null) {
|
|
960
|
+
record.appliedFillInt = null;
|
|
961
|
+
record.appliedFillAt = null;
|
|
962
|
+
}
|
|
963
|
+
else {
|
|
964
|
+
record.appliedFillInt = Number(value.filledInt);
|
|
965
|
+
record.appliedFillAt = Number(value.at) || 0;
|
|
966
|
+
}
|
|
967
|
+
record.revision += 1;
|
|
968
|
+
}
|
|
969
|
+
*placedEntries() {
|
|
970
|
+
for (const record of [...this.records.values()]) {
|
|
971
|
+
if (record.orderId && record.placedAt > 0)
|
|
972
|
+
yield [record.orderId, record.placedAt];
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
*assignedEntries() {
|
|
976
|
+
for (const record of [...this.records.values()]) {
|
|
977
|
+
if (record.orderId && record.assignedAt > 0)
|
|
978
|
+
yield [record.orderId, record.assignedAt];
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
*appliedEntries() {
|
|
982
|
+
for (const record of [...this.records.values()]) {
|
|
983
|
+
if (record.orderId && record.appliedFillInt != null) {
|
|
984
|
+
yield [record.orderId, { filledInt: Number(record.appliedFillInt), at: Number(record.appliedFillAt) || 0 }];
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
*committedValues() {
|
|
989
|
+
for (const record of [...this.records.values()]) {
|
|
990
|
+
if (record.orderId && record.committedAt > 0)
|
|
991
|
+
yield record.orderId;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
clearPlacedAt() {
|
|
995
|
+
for (const record of this.records.values())
|
|
996
|
+
record.placedAt = 0;
|
|
997
|
+
}
|
|
998
|
+
clearAssignedAt() {
|
|
999
|
+
for (const record of this.records.values())
|
|
1000
|
+
record.assignedAt = 0;
|
|
1001
|
+
}
|
|
1002
|
+
clearCommitted() {
|
|
1003
|
+
for (const record of this.records.values()) {
|
|
1004
|
+
record.committedAt = 0;
|
|
1005
|
+
record.committedSnapshotAt = 0;
|
|
1006
|
+
}
|
|
1007
|
+
this.committedSnapshotAt = 0;
|
|
1008
|
+
}
|
|
1009
|
+
clearAppliedFills() {
|
|
1010
|
+
for (const record of this.records.values()) {
|
|
1011
|
+
record.appliedFillInt = null;
|
|
1012
|
+
record.appliedFillAt = null;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
// ===============================================================================
|
|
1017
|
+
// SECTION 7: PHASE PREDICATES
|
|
1018
|
+
// ===============================================================================
|
|
1019
|
+
/**
|
|
1020
|
+
* True when a slot carries a persisted "the CREATE result was lost" marker.
|
|
1021
|
+
*
|
|
1022
|
+
* This is the single definition; the registry phase and the slot flag must
|
|
1023
|
+
* never disagree, so every site that used to read `slot.createUncertain`
|
|
1024
|
+
* directly goes through here.
|
|
1025
|
+
*/
|
|
1026
|
+
export function isSlotCreateUncertain(slot) {
|
|
1027
|
+
if (!slot || typeof slot !== 'object')
|
|
1028
|
+
return false;
|
|
1029
|
+
return slot.createUncertain === true;
|
|
1030
|
+
}
|
|
1031
|
+
// ===============================================================================
|
|
1032
|
+
// SECTION 8: MANAGER-AGNOSTIC READ
|
|
1033
|
+
// ===============================================================================
|
|
1034
|
+
/**
|
|
1035
|
+
* Read an order's lifecycle from any manager-shaped object.
|
|
1036
|
+
*
|
|
1037
|
+
* Production managers expose `getLifecycle`; partial test doubles and legacy
|
|
1038
|
+
* call sites that only carry the raw maps still work, because the fallback
|
|
1039
|
+
* synthesizes a record from exactly those maps. That keeps the *vocabulary*
|
|
1040
|
+
* unified (callers ask one question) without requiring every fixture to grow a
|
|
1041
|
+
* registry.
|
|
1042
|
+
*
|
|
1043
|
+
* @param manager - OrderManager, its interface, or a partial test double
|
|
1044
|
+
* @param identity - Slot id, chain order id, or pending-broadcast fingerprint
|
|
1045
|
+
* @returns {LifecycleView} Unified read surface (never null)
|
|
1046
|
+
*/
|
|
1047
|
+
export function readLifecycle(manager, identity) {
|
|
1048
|
+
const candidate = manager;
|
|
1049
|
+
if (candidate && typeof candidate.getLifecycle === 'function') {
|
|
1050
|
+
return candidate.getLifecycle(identity);
|
|
1051
|
+
}
|
|
1052
|
+
const key = asKey(identity);
|
|
1053
|
+
if (!key || !candidate)
|
|
1054
|
+
return new LifecycleViewImpl(null, () => Date.now());
|
|
1055
|
+
const placedAt = Number(candidate._placedAt instanceof Map ? candidate._placedAt.get(key) : 0) || 0;
|
|
1056
|
+
const assignedAt = Number(candidate._orderIdAssignedAt instanceof Map ? candidate._orderIdAssignedAt.get(key) : 0) || 0;
|
|
1057
|
+
const committed = !!candidate._committedOrderIds?.has?.(key);
|
|
1058
|
+
// Mirror the registry: the protection window is measured from the PUBLISHED
|
|
1059
|
+
// stamp, and a missing stamp is not a fresh one. Substituting `Date.now()`
|
|
1060
|
+
// here would invent a commit window production never had.
|
|
1061
|
+
const committedAt = committed ? (Number(candidate._committedOrderIdsBuiltAt) || 0) : 0;
|
|
1062
|
+
const synthesized = {
|
|
1063
|
+
key: `legacy:${key}`,
|
|
1064
|
+
slotId: null,
|
|
1065
|
+
orderId: key,
|
|
1066
|
+
fingerprint: null,
|
|
1067
|
+
// A partial double cannot know the phase. `landed` is chosen so the WINDOW
|
|
1068
|
+
// predicates (isInFlight / isRecentlyAssigned / isRecentlyCommitted)
|
|
1069
|
+
// behave exactly as they did before the registry existed; only those are
|
|
1070
|
+
// meaningful on a synthesized record.
|
|
1071
|
+
phase: committed || assignedAt > 0 || placedAt > 0 ? 'landed' : 'intent',
|
|
1072
|
+
evidence: committed || assignedAt > 0 || placedAt > 0 ? 'chain-snapshot' : 'none',
|
|
1073
|
+
recordedAt: Math.max(placedAt, assignedAt, committedAt),
|
|
1074
|
+
observedAt: committed || assignedAt > 0 ? Math.max(assignedAt, committedAt) : 0,
|
|
1075
|
+
assignedAt,
|
|
1076
|
+
placedAt,
|
|
1077
|
+
committedAt,
|
|
1078
|
+
appliedFillInt: null,
|
|
1079
|
+
appliedFillAt: null,
|
|
1080
|
+
committedSnapshotAt: committedAt,
|
|
1081
|
+
pending: null,
|
|
1082
|
+
revision: 1,
|
|
1083
|
+
};
|
|
1084
|
+
return new LifecycleViewImpl(synthesized, () => Date.now());
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* Read an order's lifecycle from a SLOT (preferred over an identity lookup).
|
|
1088
|
+
*
|
|
1089
|
+
* A slot is the stable identity (intent → chain id → partial → gone) and can
|
|
1090
|
+
* carry evidence the registry does not: the persisted `createUncertain` marker,
|
|
1091
|
+
* which must report `unknown` (may exist on chain) rather than a clean intent.
|
|
1092
|
+
* Every absence decision that has the slot object in hand must go through this
|
|
1093
|
+
* helper, not `readLifecycle(manager, slot.orderId)` — an orderId-keyed read
|
|
1094
|
+
* silently ignores the marker and can virtualize an order whose CREATE landed.
|
|
1095
|
+
*
|
|
1096
|
+
* Falls back to the identity read for partial test doubles.
|
|
1097
|
+
*
|
|
1098
|
+
* @param manager - OrderManager, its interface, or a partial test double
|
|
1099
|
+
* @param slot - Grid slot the decision is about
|
|
1100
|
+
* @returns {LifecycleView} Unified read surface (never null)
|
|
1101
|
+
*/
|
|
1102
|
+
export function readSlotLifecycle(manager, slot) {
|
|
1103
|
+
const candidate = manager;
|
|
1104
|
+
if (candidate && typeof candidate.getSlotLifecycle === 'function') {
|
|
1105
|
+
return candidate.getSlotLifecycle(slot);
|
|
1106
|
+
}
|
|
1107
|
+
return readLifecycle(manager, slot?.orderId ?? slot?.id ?? null);
|
|
1108
|
+
}
|
|
1109
|
+
//# sourceMappingURL=lifecycle.js.map
|