dexbot 1.7.1 → 1.7.3
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 +52 -0
- 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/grid_correction_check.d.ts +60 -1
- package/dist/analysis/grid_correction_check.js +268 -18
- package/dist/analysis/pivot_timeline.d.ts +78 -0
- package/dist/analysis/pivot_timeline.js +360 -0
- package/dist/market_adapter/utils/file_lock.js +16 -4
- package/dist/modules/account_bots.d.ts +7 -0
- package/dist/modules/account_bots.js +7 -5
- package/dist/modules/bot_defaults.js +6 -1
- package/dist/modules/constants.d.ts +14 -0
- package/dist/modules/constants.js +82 -2
- package/dist/modules/dexbot_class.d.ts +39 -0
- package/dist/modules/dexbot_class.js +86 -1
- package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
- package/dist/modules/dexbot_cow_runtime.js +299 -75
- package/dist/modules/dexbot_maintenance_runtime.d.ts +32 -2
- package/dist/modules/dexbot_maintenance_runtime.js +196 -16
- package/dist/modules/dexbot_state_recovery.js +15 -1
- package/dist/modules/launcher/instance_lock.d.ts +27 -0
- package/dist/modules/launcher/instance_lock.js +131 -0
- package/dist/modules/node_flap_score.d.ts +6 -6
- package/dist/modules/node_flap_score.js +6 -6
- package/dist/modules/order/accounting.d.ts +9 -4
- package/dist/modules/order/accounting.js +89 -26
- package/dist/modules/order/async_lock.d.ts +7 -1
- package/dist/modules/order/async_lock.js +7 -1
- package/dist/modules/order/export.js +25 -18
- package/dist/modules/order/fill_ledger.d.ts +99 -0
- package/dist/modules/order/fill_ledger.js +103 -0
- package/dist/modules/order/grid.d.ts +94 -18
- package/dist/modules/order/grid.js +247 -75
- package/dist/modules/order/grid_reconcile_internal.js +16 -4
- package/dist/modules/order/index.d.ts +29 -6
- package/dist/modules/order/index.js +5 -5
- package/dist/modules/order/lifecycle.js +3 -3
- package/dist/modules/order/manager.d.ts +36 -24
- package/dist/modules/order/manager.js +159 -39
- package/dist/modules/order/placement_lock.d.ts +30 -0
- package/dist/modules/order/placement_lock.js +48 -0
- package/dist/modules/order/sync_engine.d.ts +66 -118
- package/dist/modules/order/sync_engine.js +118 -162
- package/dist/modules/order/utils/math.d.ts +7 -3
- package/dist/modules/order/utils/math.js +7 -3
- package/dist/modules/order/utils/order.d.ts +79 -42
- package/dist/modules/order/utils/order.js +183 -86
- package/dist/modules/order/utils/system.d.ts +192 -8
- package/dist/modules/order/utils/system.js +534 -34
- package/dist/modules/paths.d.ts +1 -0
- package/dist/modules/paths.js +1 -0
- package/dist/modules/timing_policy.js +4 -2
- package/dist/modules/types.d.ts +49 -27
- package/dist/pm2.js +126 -0
- package/dist/unlock.js +26 -1
- package/docs/COW_INVARIANTS.md +5 -1
- package/docs/DEXBOT_COMPARISON.md +5 -5
- package/docs/EVOLUTION.md +10 -8
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_RECONCILE.md +3 -3
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +192 -31
- package/docs/README.md +1 -1
- package/docs/architecture.md +26 -8
- package/modules/README.md +4 -0
- package/package.json +4 -3
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
* ===============================================================================
|
|
10
10
|
*
|
|
11
11
|
* SECTION 1: EXTERNAL DEPENDENCIES
|
|
12
|
-
* SECTION 2: COW REBALANCE ENGINE
|
|
13
|
-
* SECTION 3: ORDER MANAGER CLASS
|
|
12
|
+
* SECTION 2: COW REBALANCE ENGINE - COWRebalanceEngine class (exported)
|
|
13
|
+
* SECTION 3: ORDER MANAGER CLASS - OrderManager class (exported)
|
|
14
14
|
* ===============================================================================
|
|
15
15
|
*/
|
|
16
16
|
// ===============================================================================
|
|
@@ -33,7 +33,7 @@ import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolve
|
|
|
33
33
|
import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
|
|
34
34
|
import { resolveSpreadOrderSide, resolveLiveOrderLadderPosition, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, isFreshlyPlacedOrder, collectEdgePinnedFillIds, isStructuralRebuildStaleReason } from './utils/order.js';
|
|
35
35
|
import { parseSlotIndex } from './utils/slot.js';
|
|
36
|
-
import PlacementLock, { withPlacement as runWithPlacement } from './placement_lock.js';
|
|
36
|
+
import PlacementLock, { withPlacement as runWithPlacement, attachPlanLease } from './placement_lock.js';
|
|
37
37
|
import { getErrorMessage, getErrorCode } from '../utils/errors.js';
|
|
38
38
|
const { toFiniteNumber } = Format;
|
|
39
39
|
function stalePlacementDropReason(action, planBoundary) {
|
|
@@ -163,10 +163,29 @@ class COWRebalanceEngine {
|
|
|
163
163
|
// the whole slot's action group (a type-mismatch CANCEL is paired with
|
|
164
164
|
// a CREATE on the same id) for the grace window. The surplus is
|
|
165
165
|
// re-derived next cycle once the order has had time to prove itself.
|
|
166
|
+
//
|
|
167
|
+
// EXEMPT: a chain-observed wrong-side order. Only the correction
|
|
168
|
+
// queue's `typeMismatch` entry proves the CHAIN side is wrong; a
|
|
169
|
+
// plan-shaped CANCEL with reason 'type-mismatch' only proves
|
|
170
|
+
// master !== target, which is exactly the stale-target lag this
|
|
171
|
+
// grace exists for and must keep waiting. The pre-batch drain
|
|
172
|
+
// (correctAllPriceMismatches) normally cancels the mismatch first;
|
|
173
|
+
// when it deferred (active region) or failed, the entry is still
|
|
174
|
+
// queued — parking this action would add a second, 15-minute wait.
|
|
175
|
+
const knownWrongSide = new Set();
|
|
176
|
+
if (manager && Array.isArray(manager.ordersNeedingPriceCorrection)) {
|
|
177
|
+
for (const correction of manager.ordersNeedingPriceCorrection) {
|
|
178
|
+
if (correction?.typeMismatch === true && correction.chainOrderId) {
|
|
179
|
+
knownWrongSide.add(String(correction.chainOrderId));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
166
183
|
const deferredFreshCancelSlots = new Set();
|
|
167
184
|
for (const action of reconcileResult.actions) {
|
|
168
185
|
if (action.type !== COW_ACTIONS.CANCEL || !action.orderId)
|
|
169
186
|
continue;
|
|
187
|
+
if (knownWrongSide.has(String(action.orderId)))
|
|
188
|
+
continue;
|
|
170
189
|
if (!manager || !isFreshlyPlacedOrder(manager, action.orderId))
|
|
171
190
|
continue;
|
|
172
191
|
const slotId = String(action.id);
|
|
@@ -420,6 +439,11 @@ class OrderManager {
|
|
|
420
439
|
_pauseFundRecalc;
|
|
421
440
|
_pauseFundRecalcWatchdog;
|
|
422
441
|
_fillBatchInFlight;
|
|
442
|
+
// Consecutive blocked-cycle counter for the grid-update gate
|
|
443
|
+
// (`noteGridUpdateBlockers` in order/utils/system.ts is its only writer and
|
|
444
|
+
// reader). Cleared when the gate is evaluated healthy or not evaluated at
|
|
445
|
+
// all; a cycle count, never a timing window.
|
|
446
|
+
_gridUpdateBlockedCycles;
|
|
423
447
|
_pauseRecalcLogging;
|
|
424
448
|
_pauseRecalcLoggingWatchdog;
|
|
425
449
|
_throwOnIllegalState;
|
|
@@ -496,6 +520,12 @@ class OrderManager {
|
|
|
496
520
|
_lastFilledPrice;
|
|
497
521
|
_lastFilledType;
|
|
498
522
|
_lastFilledAt;
|
|
523
|
+
// Refused (off-market) fill level: the pivot-arming refusal (§9.12/P1)
|
|
524
|
+
// still marks its level as a same-level re-fill block (§9.12/P2 amended).
|
|
525
|
+
// In-memory only — never persisted, cleared by resetLastFillPivot.
|
|
526
|
+
_lastRefusedFillPrice;
|
|
527
|
+
_lastRefusedFillType;
|
|
528
|
+
_lastRefusedFillAt;
|
|
499
529
|
/** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
|
|
500
530
|
_lastFillPivotExpiryLoggedAt;
|
|
501
531
|
lastFillPivotSource;
|
|
@@ -631,6 +661,7 @@ class OrderManager {
|
|
|
631
661
|
// window would report a spurious Total != Free + Committed by exactly the
|
|
632
662
|
// fills' size. The check runs once the batch settles instead.
|
|
633
663
|
this._fillBatchInFlight = 0;
|
|
664
|
+
this._gridUpdateBlockedCycles = 0;
|
|
634
665
|
this._pauseRecalcLogging = false;
|
|
635
666
|
this._pauseRecalcLoggingWatchdog = null;
|
|
636
667
|
this._throwOnIllegalState = false;
|
|
@@ -644,7 +675,7 @@ class OrderManager {
|
|
|
644
675
|
this._committedOrderIdsBuiltAt = 0;
|
|
645
676
|
this._orderIdAssignedAt = new Map();
|
|
646
677
|
// Fresh-placement timestamps (chainOrderId -> Date.now) for the
|
|
647
|
-
// surplus-cancel grace window.
|
|
678
|
+
// surplus-cancel grace window. Written by this lifecycle funnel only.
|
|
648
679
|
this._placedAt = new Map();
|
|
649
680
|
this._gapSlots = 0;
|
|
650
681
|
// Genesis (price-ladder) state. `_genesis` is established by
|
|
@@ -668,6 +699,9 @@ class OrderManager {
|
|
|
668
699
|
this._lastFilledPrice = null;
|
|
669
700
|
this._lastFilledType = null;
|
|
670
701
|
this._lastFilledAt = 0;
|
|
702
|
+
this._lastRefusedFillPrice = null;
|
|
703
|
+
this._lastRefusedFillType = null;
|
|
704
|
+
this._lastRefusedFillAt = 0;
|
|
671
705
|
this._lastFillPivotExpiryLoggedAt = 0;
|
|
672
706
|
// Pivot provenance for the LAST-FILL-GUARD persist/restore contract:
|
|
673
707
|
// 'fill' = armed by a real fill (persist-eligible), 'book' = armed by
|
|
@@ -842,7 +876,8 @@ class OrderManager {
|
|
|
842
876
|
* `isPlacementLeaseCurrent()` before mutating.
|
|
843
877
|
*
|
|
844
878
|
* Lock hierarchy: acquire placement BEFORE `_gridLock`; never acquire it
|
|
845
|
-
* while holding `_gridLock` (Level 0.5 — see
|
|
879
|
+
* while holding `_gridLock` (Level 0.5 — see the constructor's canonical
|
|
880
|
+
* lock-hierarchy block in this file).
|
|
846
881
|
*
|
|
847
882
|
* @returns `null` when the region could not be acquired; the caller must
|
|
848
883
|
* defer/abort its broadcast.
|
|
@@ -993,16 +1028,6 @@ class OrderManager {
|
|
|
993
1028
|
}
|
|
994
1029
|
return applied;
|
|
995
1030
|
}
|
|
996
|
-
/**
|
|
997
|
-
* Boolean compatibility wrapper for {@link consumeChainSizeAppliedFillAmount}.
|
|
998
|
-
* @param {string} orderId - Chain order id
|
|
999
|
-
* @param {number} filledInt - Base-amount delta in chain integer units
|
|
1000
|
-
* @param {number} [maxAgeMs] - Marker freshness bound
|
|
1001
|
-
* @returns {boolean} true when any part of the fill was already applied
|
|
1002
|
-
*/
|
|
1003
|
-
consumeChainSizeAppliedFill(orderId, filledInt, maxAgeMs = TIMING.CHAIN_SIZE_APPLIED_MARKER_TTL_MS) {
|
|
1004
|
-
return this.consumeChainSizeAppliedFillAmount(orderId, filledInt, maxAgeMs) > 0;
|
|
1005
|
-
}
|
|
1006
1031
|
/**
|
|
1007
1032
|
* Merge persisted pass-1 markers into the in-memory set (recovery reload).
|
|
1008
1033
|
* Live markers win on conflict: they may already be partially consumed,
|
|
@@ -1608,7 +1633,7 @@ class OrderManager {
|
|
|
1608
1633
|
}
|
|
1609
1634
|
}
|
|
1610
1635
|
/**
|
|
1611
|
-
* @param {Array<import('
|
|
1636
|
+
* @param {Array<import('../types.js').Order>} orders
|
|
1612
1637
|
* @param {Object} info
|
|
1613
1638
|
* @returns {Promise<any>}
|
|
1614
1639
|
*/
|
|
@@ -1876,11 +1901,22 @@ class OrderManager {
|
|
|
1876
1901
|
return;
|
|
1877
1902
|
}
|
|
1878
1903
|
if (nextId !== prevId) {
|
|
1904
|
+
const isLoadContext = context === 'grid-load' || context === 'grid-init';
|
|
1879
1905
|
// A freshly assigned chain id (create/adopt broadcast in flight, or
|
|
1880
1906
|
// not yet visible to a lagging read) must not read as "absent from
|
|
1881
1907
|
// chain": absence decisions defer while it is younger than
|
|
1882
1908
|
// SYNC_LOCK_TIMEOUT_MS (isRecentlyAssigned).
|
|
1883
|
-
|
|
1909
|
+
//
|
|
1910
|
+
// Snapshot/grid load paths are excluded for ids this process
|
|
1911
|
+
// already knows: a reload re-adopts OLD ids, so re-stamping them
|
|
1912
|
+
// would hand the same (possibly dead) order a brand-new defer
|
|
1913
|
+
// window on every reload. The reload that follows a refused
|
|
1914
|
+
// UPDATE re-armed it indefinitely, so a genuinely absent orderId
|
|
1915
|
+
// could never be cleaned up and kept blocking the gap band. First
|
|
1916
|
+
// sight of an id (fresh process) still gets the grace.
|
|
1917
|
+
const isKnownId = this._lifecycle.assignedAt.has(nextId);
|
|
1918
|
+
if (!isLoadContext || !isKnownId)
|
|
1919
|
+
this._lifecycle.markAssigned(slotId, nextId);
|
|
1884
1920
|
// Fresh-placement timestamp for the surplus-cancel grace window: a
|
|
1885
1921
|
// slot gaining an orderId it did not have is a new placement
|
|
1886
1922
|
// (create, adopt, rotation target), and surplus sweeps must not
|
|
@@ -1889,7 +1925,6 @@ class OrderManager {
|
|
|
1889
1925
|
// Snapshot/grid load paths are excluded: reloaded orders are old by
|
|
1890
1926
|
// definition, and stamping them would neuter surplus sweeps for 15
|
|
1891
1927
|
// minutes after every restart.
|
|
1892
|
-
const isLoadContext = context === 'grid-load' || context === 'grid-init';
|
|
1893
1928
|
if (!isLoadContext)
|
|
1894
1929
|
this._lifecycle.markPlaced(nextId, undefined, slotId);
|
|
1895
1930
|
}
|
|
@@ -1956,7 +1991,7 @@ class OrderManager {
|
|
|
1956
1991
|
}
|
|
1957
1992
|
}
|
|
1958
1993
|
/**
|
|
1959
|
-
* @param {Array<import('
|
|
1994
|
+
* @param {Array<import('../types.js').Order>} updates - Order updates to apply
|
|
1960
1995
|
* @param {string} [context] - Update context label
|
|
1961
1996
|
* @param {unknown} [options]
|
|
1962
1997
|
* @returns {Promise<boolean>}
|
|
@@ -2045,7 +2080,7 @@ class OrderManager {
|
|
|
2045
2080
|
return result || { isValid: true };
|
|
2046
2081
|
}
|
|
2047
2082
|
/**
|
|
2048
|
-
* @param {Array<import('
|
|
2083
|
+
* @param {Array<import('../types.js').Order>} orders - Filled orders
|
|
2049
2084
|
* @param {Set<string>} [excl] - Order IDs to exclude
|
|
2050
2085
|
* @param {Object} [options]
|
|
2051
2086
|
* @returns {Promise<any>}
|
|
@@ -2072,7 +2107,10 @@ class OrderManager {
|
|
|
2072
2107
|
const reanchorBudgetBefore = Number(this._boundaryReanchorBudget);
|
|
2073
2108
|
const rebalanceResult = await this.performSafeRebalance(orders, excl, {
|
|
2074
2109
|
...(options || {}),
|
|
2075
|
-
deferIfBroadcasting: true
|
|
2110
|
+
deferIfBroadcasting: true,
|
|
2111
|
+
// This result is always fed to the executor by
|
|
2112
|
+
// _processFillsWithBatching, so the region can span plan→commit.
|
|
2113
|
+
holdPlanRegion: true
|
|
2076
2114
|
});
|
|
2077
2115
|
// Carry the fill set + exclusions on the result so the COW batch
|
|
2078
2116
|
// executor can re-plan once from fresh master if the plan goes
|
|
@@ -2094,7 +2132,7 @@ class OrderManager {
|
|
|
2094
2132
|
};
|
|
2095
2133
|
}
|
|
2096
2134
|
/**
|
|
2097
|
-
* @returns {Array<import('
|
|
2135
|
+
* @returns {Array<import('../types.js').Order>}
|
|
2098
2136
|
*/
|
|
2099
2137
|
getInitialOrdersToActivate() {
|
|
2100
2138
|
// Apply coreOrders limit from config
|
|
@@ -2247,19 +2285,16 @@ class OrderManager {
|
|
|
2247
2285
|
* Also used when the boundary is (re)anchored outside the fill path (grid
|
|
2248
2286
|
* reset / recenter / rejected-snapshot rebuild): those records belong to
|
|
2249
2287
|
* the previous generation, and applying their relative deltas onto a fresh
|
|
2250
|
-
* anchor would double-count movement the anchor already contains.
|
|
2288
|
+
* anchor would double-count movement the anchor already contains. That is
|
|
2289
|
+
* the explicit allowed-loss path: the grid generation is being discarded
|
|
2290
|
+
* (rebuild, rejected snapshot, restart replay), so the relative deltas no
|
|
2291
|
+
* longer have a geometry to apply onto.
|
|
2251
2292
|
*
|
|
2252
2293
|
* Marks the grid dirty so the cleared array reaches disk even on paths
|
|
2253
2294
|
* that do not otherwise persist.
|
|
2254
2295
|
*
|
|
2255
2296
|
* @param {string} reason - Log/debug label for the drop
|
|
2256
|
-
|
|
2257
|
-
/**
|
|
2258
|
-
* Drop ALL owed fill-crawl records.
|
|
2259
|
-
*
|
|
2260
|
-
* This is the explicit allowed-loss path: the grid generation is being
|
|
2261
|
-
* discarded (rebuild, rejected snapshot, restart replay), so the relative
|
|
2262
|
-
* deltas no longer have a geometry to apply onto.
|
|
2297
|
+
* @param {string} detail - Extra context appended to the drop log line
|
|
2263
2298
|
*/
|
|
2264
2299
|
_clearPendingFillCrawls(reason = 'unspecified', detail = '') {
|
|
2265
2300
|
if (!Array.isArray(this._pendingFillCrawls) || this._pendingFillCrawls.length === 0)
|
|
@@ -2463,6 +2498,17 @@ class OrderManager {
|
|
|
2463
2498
|
* edge. Skipping keeps the reference on the last WINDOW trade, matching
|
|
2464
2499
|
* the crawl's classification (collectEdgePinnedFillIds is the shared
|
|
2465
2500
|
* definition).
|
|
2501
|
+
*
|
|
2502
|
+
* IN-BAND FILLS ARE SKIPPED TOO (same rule, completed). A slot the CURRENT
|
|
2503
|
+
* geometry classifies as gap-band holds a stranded residual — an order the
|
|
2504
|
+
* engine has already declared out of place ("placed_order_in_band") — not a
|
|
2505
|
+
* window trade. Live: a sweep crawled the boundary over a resting sell,
|
|
2506
|
+
* that stranded sell then partially filled 11s later, and the fill armed the
|
|
2507
|
+
* pivot at the top of the band the geometry had just derived. Every SELL in
|
|
2508
|
+
* the band was then `<= pivot`, so the counter-orders the sweep owed could
|
|
2509
|
+
* never be placed. The eligibility rule (§9.6 "Only a window trade may
|
|
2510
|
+
* become the pivot") is applied at this single writer: edge-pinned here,
|
|
2511
|
+
* in-band here, off-market distance in setLastFillPivot.
|
|
2466
2512
|
* @param {Array} fills
|
|
2467
2513
|
*/
|
|
2468
2514
|
recordLastFilledPrices(fills) {
|
|
@@ -2471,6 +2517,7 @@ class OrderManager {
|
|
|
2471
2517
|
const edgeFillIds = collectEdgePinnedFillIds(this, fills);
|
|
2472
2518
|
let recorded = 0;
|
|
2473
2519
|
let skippedEdge = 0;
|
|
2520
|
+
let skippedInBand = 0;
|
|
2474
2521
|
let lastKind = 'unknown';
|
|
2475
2522
|
let lastPriceSrc = 'direct';
|
|
2476
2523
|
for (const f of fills) {
|
|
@@ -2480,6 +2527,20 @@ class OrderManager {
|
|
|
2480
2527
|
skippedEdge++;
|
|
2481
2528
|
continue;
|
|
2482
2529
|
}
|
|
2530
|
+
// Geometry eligibility: an in-band slot is not a window trade. Fails
|
|
2531
|
+
// OPEN when the geometry is unreadable (no boundary/gap yet), because
|
|
2532
|
+
// a cold grid must still arm on its first real fill.
|
|
2533
|
+
if (f.id != null) {
|
|
2534
|
+
try {
|
|
2535
|
+
const idx = parseSlotIndex(String(f.id));
|
|
2536
|
+
const geom = geometryTypeForSlotIndex(idx, this.boundaryIdx, this._gapSlots);
|
|
2537
|
+
if (geom === ORDER_TYPES.SPREAD) {
|
|
2538
|
+
skippedInBand++;
|
|
2539
|
+
continue;
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
catch { /* unreadable geometry — treat as eligible */ }
|
|
2543
|
+
}
|
|
2483
2544
|
let price = Number(f.price ?? f.order?.price);
|
|
2484
2545
|
let priceSrc = 'direct';
|
|
2485
2546
|
if (!Number.isFinite(price) || price <= 0) {
|
|
@@ -2510,13 +2571,19 @@ class OrderManager {
|
|
|
2510
2571
|
this.logger?.log?.(`[FILL-PIVOT] pivot=${fmt(this._lastFilledPrice)}(${this._lastFilledType}) ` +
|
|
2511
2572
|
`buy=${fmt(this._lastFilledBuyPrice)} sell=${fmt(this._lastFilledSellPrice)} ` +
|
|
2512
2573
|
`n=${recorded} src=${lastKind}/${lastPriceSrc}` +
|
|
2513
|
-
`${skippedEdge > 0 ? ` edge-skipped=${skippedEdge}` : ''}
|
|
2574
|
+
`${skippedEdge > 0 ? ` edge-skipped=${skippedEdge}` : ''}` +
|
|
2575
|
+
`${skippedInBand > 0 ? ` band-skipped=${skippedInBand}` : ''}`, 'info');
|
|
2514
2576
|
}
|
|
2515
2577
|
catch { /* logging is best-effort */ }
|
|
2516
2578
|
}
|
|
2517
|
-
else if (skippedEdge > 0) {
|
|
2579
|
+
else if (skippedEdge > 0 || skippedInBand > 0) {
|
|
2518
2580
|
try {
|
|
2519
|
-
|
|
2581
|
+
const parts = [];
|
|
2582
|
+
if (skippedEdge > 0)
|
|
2583
|
+
parts.push(`${skippedEdge} edge-pinned`);
|
|
2584
|
+
if (skippedInBand > 0)
|
|
2585
|
+
parts.push(`${skippedInBand} gap-band (stranded residual)`);
|
|
2586
|
+
this.logger?.log?.(`[FILL-PIVOT] ${parts.join(' + ')} fill(s) ignored — the guard pivot and the boundary anchor stay on the last window trade`, 'info');
|
|
2520
2587
|
}
|
|
2521
2588
|
catch { /* logging is best-effort */ }
|
|
2522
2589
|
}
|
|
@@ -2710,7 +2777,7 @@ class OrderManager {
|
|
|
2710
2777
|
return true;
|
|
2711
2778
|
}
|
|
2712
2779
|
/**
|
|
2713
|
-
* @param {Map<string, import('
|
|
2780
|
+
* @param {Map<string, import('../types.js').Order>} targetGrid
|
|
2714
2781
|
* @param {number} targetBoundary
|
|
2715
2782
|
* @returns {Object}
|
|
2716
2783
|
*/
|
|
@@ -2867,6 +2934,11 @@ class OrderManager {
|
|
|
2867
2934
|
* @param {boolean} [options.skipBroadcastWait] - Set by the COW re-plan path,
|
|
2868
2935
|
* which runs INSIDE its own startBroadcasting() region and must not wait
|
|
2869
2936
|
* on the flag it holds itself.
|
|
2937
|
+
* @param {boolean} [options.holdPlanRegion] - Claim the exclusive placement
|
|
2938
|
+
* region before planning and ride it on the result, so the plan→broadcast
|
|
2939
|
+
* window is serialized against other planners. Set by the callers that are
|
|
2940
|
+
* guaranteed to execute the result (fill path, post-recovery rebalance).
|
|
2941
|
+
* Planner-only callers (unit fixtures) leave it off and stay lease-free.
|
|
2870
2942
|
* @returns {Promise<any>}
|
|
2871
2943
|
*/
|
|
2872
2944
|
async performSafeRebalance(fills = [], excludeIds = new Set(), options = {}) {
|
|
@@ -2958,9 +3030,57 @@ class OrderManager {
|
|
|
2958
3030
|
}
|
|
2959
3031
|
}
|
|
2960
3032
|
}
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
3033
|
+
// PLAN REGION (plan → broadcast → commit), opted in by holdPlanRegion.
|
|
3034
|
+
// For the callers that are guaranteed to execute the result (the fill
|
|
3035
|
+
// path and the post-recovery rebalance), the region is claimed BEFORE
|
|
3036
|
+
// planning, not by the executor afterwards. The old split left a window
|
|
3037
|
+
// between "plan finished" and "executor claimed placement" in which a
|
|
3038
|
+
// second planner passed every pre-check (`isPlacementActive()` was still
|
|
3039
|
+
// false), built from the same master, and both batches broadcast — the
|
|
3040
|
+
// duplicate-order window (two plans 595 ms apart, observed 2026-11-13).
|
|
3041
|
+
// Holding the lease across the plan makes the next planner defer on the
|
|
3042
|
+
// existing `isPlacementActive()` check; the lease rides on the result
|
|
3043
|
+
// and the executor adopts it (placement_lock.ts PLAN_LEASE_RESULT_KEY).
|
|
3044
|
+
// Planner-only callers leave the flag off: they never execute, so a
|
|
3045
|
+
// lease would only strand the region.
|
|
3046
|
+
//
|
|
3047
|
+
// `skipBroadcastWait` is the COW re-plan recursion: this frame is
|
|
3048
|
+
// already inside the executor's region and hands its own lease to the
|
|
3049
|
+
// inline re-broadcast, so acquiring again would self-deadlock (the
|
|
3050
|
+
// lock is not reentrant).
|
|
3051
|
+
let planLease = null;
|
|
3052
|
+
if (options?.holdPlanRegion === true && !options?.skipBroadcastWait
|
|
3053
|
+
&& typeof this.tryAcquirePlacement === 'function') {
|
|
3054
|
+
// Non-blocking by design: a planner that cannot get the region
|
|
3055
|
+
// DEFERS (the same level-triggered contract as the
|
|
3056
|
+
// isPlacementActive() pre-check just above) instead of parking the
|
|
3057
|
+
// fill lock for a full acquisition timeout. The pre-check makes
|
|
3058
|
+
// this a narrow race, not the normal path.
|
|
3059
|
+
planLease = this.tryAcquirePlacement('cow-plan');
|
|
3060
|
+
if (!planLease) {
|
|
3061
|
+
this.logger.log('[SAFE-REBALANCE] Deferred: exclusive placement region became unavailable; rebalance retries after it ends', 'info');
|
|
3062
|
+
this._deferredRebalanceAt = Date.now();
|
|
3063
|
+
return { ...buildAbortedResult('placement-active-deferred'), deferred: true };
|
|
3064
|
+
}
|
|
3065
|
+
}
|
|
3066
|
+
let result;
|
|
3067
|
+
try {
|
|
3068
|
+
result = await this._gridLock.acquire(async () => {
|
|
3069
|
+
return await this._applySafeRebalanceCOW(fills, excludeIds);
|
|
3070
|
+
});
|
|
3071
|
+
}
|
|
3072
|
+
catch (err) {
|
|
3073
|
+
// A plan that throws must not park the region (the COW body's own
|
|
3074
|
+
// claim path has the same contract).
|
|
3075
|
+
planLease?.release();
|
|
3076
|
+
throw err;
|
|
3077
|
+
}
|
|
3078
|
+
if (!result || result.aborted) {
|
|
3079
|
+
planLease?.release();
|
|
3080
|
+
return result;
|
|
3081
|
+
}
|
|
3082
|
+
attachPlanLease(result, planLease);
|
|
3083
|
+
return result;
|
|
2964
3084
|
}
|
|
2965
3085
|
async _applySafeRebalanceCOW(fills = [], excludeIds = new Set()) {
|
|
2966
3086
|
const cowEngine = this._getCOWEngine();
|
|
@@ -3083,7 +3203,7 @@ class OrderManager {
|
|
|
3083
3203
|
comparePrecisions
|
|
3084
3204
|
});
|
|
3085
3205
|
if (!preCommitGuard.canCommit) {
|
|
3086
|
-
this.logger.log(`[COW] ${preCommitGuard.reason}`, preCommitGuard
|
|
3206
|
+
this.logger.log(`[COW] ${preCommitGuard.reason}`, preCommitGuard?.level || 'warn');
|
|
3087
3207
|
releaseStackEntry();
|
|
3088
3208
|
return false;
|
|
3089
3209
|
}
|
|
@@ -3095,7 +3215,7 @@ class OrderManager {
|
|
|
3095
3215
|
comparePrecisions
|
|
3096
3216
|
});
|
|
3097
3217
|
if (!lockCommitGuard.canCommit) {
|
|
3098
|
-
this.logger.log(`[COW] ${lockCommitGuard.reason}`, lockCommitGuard
|
|
3218
|
+
this.logger.log(`[COW] ${lockCommitGuard.reason}`, lockCommitGuard?.level || 'warn');
|
|
3099
3219
|
// Working grid ref is cleared exactly once below via the
|
|
3100
3220
|
// !committed path (the callback returns without committing).
|
|
3101
3221
|
return;
|
|
@@ -44,6 +44,36 @@ export interface PlacementCapableManager {
|
|
|
44
44
|
isPlacementLeaseCurrent?(lease: PlacementLease | null | undefined): boolean;
|
|
45
45
|
placementKind?(): string | null;
|
|
46
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Result-carried plan lease (the plan → broadcast → commit region).
|
|
49
|
+
*
|
|
50
|
+
* `performSafeRebalance` acquires the placement region BEFORE it plans, so a
|
|
51
|
+
* second planner cannot build from the master this plan is about to mutate
|
|
52
|
+
* (the gap between "plan finished" and "executor claimed placement" was the
|
|
53
|
+
* duplicate-order window: two plans 595 ms apart both passed the
|
|
54
|
+
* `isPlacementActive()` pre-check, then both broadcast). The lease rides on
|
|
55
|
+
* the rebalance result until the executor adopts it; every consumer either
|
|
56
|
+
* takes it (the COW body, which releases it in its own finally) or releases
|
|
57
|
+
* it (no-action / discarded results).
|
|
58
|
+
*
|
|
59
|
+
* Keep the property name in one place: producer (manager), consumer
|
|
60
|
+
* (dexbot_class / dexbot_cow_runtime / dexbot_state_recovery) and tests must
|
|
61
|
+
* agree on it.
|
|
62
|
+
*/
|
|
63
|
+
export declare const PLAN_LEASE_RESULT_KEY = "_planPlacementLease";
|
|
64
|
+
export declare function attachPlanLease(result: unknown, lease: PlacementLease | null | undefined): void;
|
|
65
|
+
/**
|
|
66
|
+
* Remove and return the plan lease carried by a rebalance result.
|
|
67
|
+
* The caller becomes the owner and MUST release it (directly or through the
|
|
68
|
+
* COW body's finally). Taking is idempotent: a second call returns null.
|
|
69
|
+
*/
|
|
70
|
+
export declare function takePlanLease(result: unknown): PlacementLease | null;
|
|
71
|
+
/**
|
|
72
|
+
* Release (and drop) a plan lease a caller will not execute. Safe on results
|
|
73
|
+
* that never carried one, and safe to call twice (lease release is
|
|
74
|
+
* token-guarded/idempotent).
|
|
75
|
+
*/
|
|
76
|
+
export declare function releasePlanLease(result: unknown): void;
|
|
47
77
|
/**
|
|
48
78
|
* Run `fn` inside the exclusive placement region.
|
|
49
79
|
*
|
|
@@ -34,6 +34,54 @@
|
|
|
34
34
|
* still the lease that owns the region?".
|
|
35
35
|
*/
|
|
36
36
|
const leaseTokens = new WeakMap();
|
|
37
|
+
/**
|
|
38
|
+
* Result-carried plan lease (the plan → broadcast → commit region).
|
|
39
|
+
*
|
|
40
|
+
* `performSafeRebalance` acquires the placement region BEFORE it plans, so a
|
|
41
|
+
* second planner cannot build from the master this plan is about to mutate
|
|
42
|
+
* (the gap between "plan finished" and "executor claimed placement" was the
|
|
43
|
+
* duplicate-order window: two plans 595 ms apart both passed the
|
|
44
|
+
* `isPlacementActive()` pre-check, then both broadcast). The lease rides on
|
|
45
|
+
* the rebalance result until the executor adopts it; every consumer either
|
|
46
|
+
* takes it (the COW body, which releases it in its own finally) or releases
|
|
47
|
+
* it (no-action / discarded results).
|
|
48
|
+
*
|
|
49
|
+
* Keep the property name in one place: producer (manager), consumer
|
|
50
|
+
* (dexbot_class / dexbot_cow_runtime / dexbot_state_recovery) and tests must
|
|
51
|
+
* agree on it.
|
|
52
|
+
*/
|
|
53
|
+
export const PLAN_LEASE_RESULT_KEY = '_planPlacementLease';
|
|
54
|
+
export function attachPlanLease(result, lease) {
|
|
55
|
+
if (!result || typeof result !== 'object' || !lease)
|
|
56
|
+
return;
|
|
57
|
+
result[PLAN_LEASE_RESULT_KEY] = lease;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Remove and return the plan lease carried by a rebalance result.
|
|
61
|
+
* The caller becomes the owner and MUST release it (directly or through the
|
|
62
|
+
* COW body's finally). Taking is idempotent: a second call returns null.
|
|
63
|
+
*/
|
|
64
|
+
export function takePlanLease(result) {
|
|
65
|
+
if (!result || typeof result !== 'object')
|
|
66
|
+
return null;
|
|
67
|
+
const carrier = result;
|
|
68
|
+
const lease = carrier[PLAN_LEASE_RESULT_KEY] ?? null;
|
|
69
|
+
if (lease)
|
|
70
|
+
delete carrier[PLAN_LEASE_RESULT_KEY];
|
|
71
|
+
return lease;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Release (and drop) a plan lease a caller will not execute. Safe on results
|
|
75
|
+
* that never carried one, and safe to call twice (lease release is
|
|
76
|
+
* token-guarded/idempotent).
|
|
77
|
+
*/
|
|
78
|
+
export function releasePlanLease(result) {
|
|
79
|
+
const lease = takePlanLease(result);
|
|
80
|
+
try {
|
|
81
|
+
lease?.release();
|
|
82
|
+
}
|
|
83
|
+
catch { /* a release must never escape into the settle path */ }
|
|
84
|
+
}
|
|
37
85
|
/** Used when the caller has no lock (dry-run mocks / browser shims). */
|
|
38
86
|
const NOOP_PLACEMENT_LEASE = { kind: 'noop', release: () => { } };
|
|
39
87
|
/**
|