dexbot 1.7.0 → 1.7.2
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 +70 -0
- package/README.md +3 -3
- package/analysis/README.md +33 -13
- 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_liquidity.js +15 -4
- 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_chart_generator.js +190 -20
- package/dist/analysis/liquidity/liquidity_depth_model.d.ts +41 -16
- package/dist/analysis/liquidity/liquidity_depth_model.js +49 -21
- package/dist/analysis/liquidity/liquidity_view.d.ts +15 -0
- package/dist/analysis/liquidity/liquidity_view.js +11 -0
- package/dist/analysis/resolve_bot_accounts.js +7 -6
- package/dist/analysis/trade_profitability.js +2 -1
- package/dist/credential-daemon.js +13 -2
- package/dist/dexbot.js +4 -4
- package/dist/modules/account_bots.d.ts +12 -1
- package/dist/modules/account_bots.js +7 -5
- package/dist/modules/account_orders.d.ts +12 -0
- package/dist/modules/account_orders.js +30 -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/constants.d.ts +28 -3
- package/dist/modules/constants.js +79 -10
- package/dist/modules/dexbot_class.d.ts +23 -6
- package/dist/modules/dexbot_class.js +44 -0
- package/dist/modules/dexbot_cow_runtime.d.ts +128 -8
- package/dist/modules/dexbot_cow_runtime.js +688 -188
- package/dist/modules/dexbot_fill_runtime.js +124 -35
- package/dist/modules/dexbot_maintenance_runtime.d.ts +1 -1
- package/dist/modules/dexbot_maintenance_runtime.js +259 -79
- 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/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.d.ts +9 -4
- package/dist/modules/order/accounting.js +131 -19
- 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/format.d.ts +24 -10
- package/dist/modules/order/format.js +30 -10
- package/dist/modules/order/grid.d.ts +75 -18
- package/dist/modules/order/grid.js +289 -72
- package/dist/modules/order/grid_reconcile.d.ts +5 -1
- package/dist/modules/order/grid_reconcile.js +333 -210
- package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
- package/dist/modules/order/grid_reconcile_internal.js +223 -91
- package/dist/modules/order/index.d.ts +18 -5
- package/dist/modules/order/index.js +5 -5
- package/dist/modules/order/lifecycle.d.ts +353 -0
- package/dist/modules/order/lifecycle.js +1109 -0
- package/dist/modules/order/manager.d.ts +277 -20
- package/dist/modules/order/manager.js +680 -64
- 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 +74 -114
- package/dist/modules/order/sync_engine.js +254 -198
- package/dist/modules/order/utils/math.d.ts +29 -4
- package/dist/modules/order/utils/math.js +61 -4
- package/dist/modules/order/utils/order.d.ts +106 -37
- package/dist/modules/order/utils/order.js +256 -81
- package/dist/modules/order/utils/system.d.ts +99 -6
- package/dist/modules/order/utils/system.js +249 -35
- package/dist/modules/order/utils/validate.d.ts +7 -1
- package/dist/modules/order/utils/validate.js +48 -2
- 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 +149 -22
- package/dist/scripts/analyze-credit.js +54 -17
- package/dist/scripts/analyze-orders.d.ts +4 -2
- package/dist/scripts/analyze-orders.js +113 -34
- package/dist/scripts/chart_targets.js +11 -15
- package/dist/scripts/test-credit-renewal.js +12 -5
- package/docs/COW_INVARIANTS.md +71 -8
- 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 +1 -1
- package/docs/GRID_RECONCILE.md +18 -13
- package/docs/LOGGING.md +25 -1
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +183 -26
- package/docs/README.md +23 -2
- package/docs/WORKFLOW.md +9 -3
- package/docs/architecture.md +68 -13
- package/docs/developer_guide.md +25 -8
- package/modules/README.md +6 -0
- package/package.json +3 -3
- package/scripts/README.md +16 -0
- package/scripts/pdev.sh +14 -1
- package/scripts/pmain.sh +23 -8
- package/scripts/ptest.sh +7 -0
- package/tests/README.md +30 -1
|
@@ -10,9 +10,10 @@ const chainOrders = require('../modules/chain_orders');
|
|
|
10
10
|
const { PATHS } = require('../modules/paths');
|
|
11
11
|
const { getErrorMessage, getErrorName } = require('../modules/utils/errors');
|
|
12
12
|
const { loadSettingsFile, normalizeBotEntries, resolveRawBotEntries } = require('../modules/bot_settings');
|
|
13
|
-
const { getStoredBotAccountId, persistBotAccountId } = require('../analysis/bot_key_utils');
|
|
14
|
-
const { isSameBotName } = require('../modules/utils/sanitize_key');
|
|
15
13
|
const { blockchainToFloat } = require('../modules/order/utils/math');
|
|
14
|
+
// Typed ESM import (not `require`) so target matching and the accountId helpers
|
|
15
|
+
// stay checked here instead of degrading to `any`.
|
|
16
|
+
import { getStoredBotAccountId, matchBotTargetIn, persistBotAccountId } from '../analysis/bot_key_utils.js';
|
|
16
17
|
const DEFAULT_BOT_NAME = 'AAA-BBB';
|
|
17
18
|
const DEFAULT_THRESHOLD_HOURS = 24;
|
|
18
19
|
const DEFAULT_MAX_FEE_RATE_PER_DAY = 0.05;
|
|
@@ -101,11 +102,14 @@ function loadBot(botName) {
|
|
|
101
102
|
const botsPath = PATHS.PROFILES.BOTS_JSON;
|
|
102
103
|
const { config } = loadSettingsFile(botsPath, { silent: false, exitOnError: false });
|
|
103
104
|
const entries = normalizeBotEntries(resolveRawBotEntries(config));
|
|
104
|
-
|
|
105
|
-
|
|
105
|
+
// Shared `<bot>` rule set (analysis/bot_key_utils): display name or bot key,
|
|
106
|
+
// case/separator-insensitive. Account spellings are rejected here — this
|
|
107
|
+
// flag selects a bot profile, not a chain account.
|
|
108
|
+
const match = matchBotTargetIn(entries, botName).find((m) => m.matchedBy !== 'account');
|
|
109
|
+
if (!match) {
|
|
106
110
|
throw new Error(`Bot profile "${botName}" not found in ${botsPath}`);
|
|
107
111
|
}
|
|
108
|
-
return
|
|
112
|
+
return match.meta;
|
|
109
113
|
}
|
|
110
114
|
function amountToFloat(amount, asset) {
|
|
111
115
|
const value = Number(amount);
|
|
@@ -218,6 +222,9 @@ async function main() {
|
|
|
218
222
|
maxFeeRatePerDay: args.maxFeeRatePerDay,
|
|
219
223
|
autoReborrow: true,
|
|
220
224
|
autoRepay: args.autoRepay,
|
|
225
|
+
// Widened on purpose: the block below adds fields to this item
|
|
226
|
+
// (`maxCollateralAmount`, `allowedOfferIds`) that this literal does not
|
|
227
|
+
// declare — without the annotation the assignment trips TS2561.
|
|
221
228
|
},
|
|
222
229
|
],
|
|
223
230
|
},
|
package/docs/COW_INVARIANTS.md
CHANGED
|
@@ -20,6 +20,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
20
20
|
| `INV-COW` | COW pipeline |
|
|
21
21
|
| `INV-PROJ` | Projection |
|
|
22
22
|
| `INV-ID` | Order identity |
|
|
23
|
+
| `INV-LIFE` | Order lifecycle (chain existence) |
|
|
23
24
|
| `INV-ACC` | Accounting / fund tracking |
|
|
24
25
|
| `INV-SYNC` | Sync engine |
|
|
25
26
|
| `INV-MAINT` | Maintenance runtime |
|
|
@@ -30,6 +31,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
30
31
|
| `INV-REG` | Fund registry |
|
|
31
32
|
| `INV-SUB` | Subscriptions |
|
|
32
33
|
| `INV-BROADCAST` | Broadcast |
|
|
34
|
+
| `INV-TIME` | Timing windows |
|
|
33
35
|
|
|
34
36
|
---
|
|
35
37
|
|
|
@@ -57,12 +59,12 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
57
59
|
- `_clearOrderCachesLogic` must bump `_gridVersion` so an in-flight COW plan (baseVersion from the pre-swap grid) is refused at commit instead of committing over a regenerated zero-slot grid.
|
|
58
60
|
|
|
59
61
|
- `INV-COW-006` Boundary moves only on fills and same-batch spread promotion
|
|
60
|
-
- Fund changes never move the boundary. Only boundary crawl (`deriveTargetBoundary`, `order/utils/order.ts`), spread promotion, and the fill-driven rail clamp move it
|
|
62
|
+
- Fund changes never move the boundary. Only boundary crawl (`deriveTargetBoundary`, `order/utils/order.ts`), spread promotion, and the fill-driven rail clamp move it. Promotion shifts it onto orders placed in the same atomic batch **and may absorb a same-side order already placed inside the band** (that order is rail-typed by construction — a placed SPREAD slot is `ILLEGAL_SPREAD_STATE` in `validateOrder`, so "same-side" needs no extra resolution); it becomes a legal rail member once the boundary slides past it. Only the empty band slot is a CREATE target, and the absorption still counts against the reserve/stranding depth caps.
|
|
61
63
|
- Funds drive order sizing/budget allocation only; `syncBoundaryToFunds`/`calculateFundDrivenBoundary` are deleted (1.5.3).
|
|
62
|
-
- `deriveRailBoundary` (`dexbot_cow_runtime.ts`, pre-broadcast) clamps the committed boundary to the batch's resulting rails: `maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1`. A fill's counter order is the rail fact, so it decides the boundary; an empty refill hole never outvotes it. Rail membership = the batch's own op destinations + master rail orders on their own side of the planned boundary (BUY at/below, SELL at/above the implied sellStart); a master order parked on the wrong side is a STRAY (refused-commit adoption, SPREAD-GUARD straggler, stranded hold) and is skipped, because clamping onto it would self-legalize the corrupt state (live: one stray sell clamped 138 → 115). Rail indices are the orders' LIVE chain price (`resolveLiveOrderLadderPosition`), not stale slot ids. A crossed/over-ceiling rail fails closed (`rail-crossed` / `rail-exceeds-grid`) and keeps the previous value instead of legalizing it; the result then passes the shared `validatePersistedBoundary` gate (with cancel/rotation sources allow-listed), so the rail clamp and the fill re-anchor end in one validator.
|
|
64
|
+
- `deriveRailBoundary` (`dexbot_cow_runtime.ts`, pre-broadcast) clamps the committed boundary to the batch's resulting rails: `maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1`. A fill's counter order is the rail fact, so it decides the boundary; an empty refill hole never outvotes it. Rail membership = the batch's own op destinations + master rail orders on their own side of the planned boundary (BUY at/below, SELL at/above the implied sellStart); a master order parked on the wrong side is a STRAY (refused-commit adoption, SPREAD-GUARD straggler, stranded hold) and is skipped, because clamping onto it would self-legalize the corrupt state (live: one stray sell clamped 138 → 115). Rail indices are the orders' LIVE chain price (`resolveLiveOrderLadderPosition`), not stale slot ids. A crossed/over-ceiling rail fails closed (`rail-crossed` / `rail-exceeds-grid`) and keeps the previous value instead of legalizing it; the result then passes the shared `validatePersistedBoundary` gate (with cancel/rotation sources allow-listed), so the rail clamp and the fill re-anchor end in one validator. The gate accepts a **violation-reducing repair**: a candidate that strands strictly fewer placed orders than the committed boundary is allowed (the fill-driven retreat case), while an equal count stays refused. The comparison uses the validator's own in-band count (`countInBandPlacements` / `boundaryMoveReducesStrands`), never a second stranding predicate.
|
|
63
65
|
|
|
64
66
|
- `INV-COW-007` Boundary hold on guard-skipped refills
|
|
65
|
-
- When a slot on the plan's refill wire (`collectRefillSlotIds`: the plan's CREATE ids minus edge-ladder edge ids) was guard-skipped at broadcast (`skippedUpdateSlotIds` ∪ `clampedUpdateSlotIds` ∪ `skippedCreateSlotIds`), `resolveRefillBoundaryHold` keeps the COMMITTED boundary instead of committing the plan's shifted one over the stranded rail hole; the grid still commits.
|
|
67
|
+
- When a slot on the plan's refill wire (`collectRefillSlotIds`: the plan's CREATE ids minus edge-ladder edge ids) was guard-skipped at broadcast (`skippedUpdateSlotIds` ∪ `clampedUpdateSlotIds` ∪ `skippedCreateSlotIds`), `resolveRefillBoundaryHold` keeps the COMMITTED boundary instead of committing the plan's shifted one over the stranded rail hole; the grid still commits. The hold is scoped to the **promotion direction** (the move advances toward the band holes): a fill-driven retreat moves away from them, so its skipped refills must not pin the old boundary. `resolveRefillSide` supplies the plan's rail side; an unknown side keeps the legacy hold (fail safe).
|
|
66
68
|
- Edge-ladder CREATEs are excluded because reserves are static edge insurance whose fills never crawl — a skipped reserve must not pin geometry.
|
|
67
69
|
- The hold is intersected with `deriveRailBoundary`: when the batch actually placed a counter order above the committed boundary, the rail clamp advances the boundary (the hold becomes a no-op and the counter stays live). The hold still applies when nothing was placed on the promoted rail. `boundaryHeld` is `effectiveBoundary !== workingBoundary`, so crawl consumption follows the value actually committed.
|
|
68
70
|
- The hold rides to the commit as `options.boundaryHeld`, which suppresses the pending-crawl clear.
|
|
@@ -73,7 +75,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
73
75
|
- `INV-COW-008` Owed fill crawls survive unapplied commits
|
|
74
76
|
- `order/strategy.ts` records a crawl per shift-eligible fill at intake (slot-level dedupe, capped at 500); `deriveTargetBoundary` folds still-owed `_pendingFillCrawls` into the next derivation, excluding the current batch's slots, edge slots, and window members — a window that reaches the grid edge is not an edge order, using the same window exclusion every placement picker and `countLiveEdgeOrders` apply.
|
|
75
77
|
- `_commitWorkingGrid` clears them only when the plan's boundary was actually applied — a held boundary (`boundaryHeld`), a gate-rejected boundary, and a null boundary all leave them owed.
|
|
76
|
-
- A window that lands BEHIND the newest real fill is repaired by `reanchorBoundaryFromLastFill` (called from `calculateTargetGrid` right after the derivation): the fill anchors the geometry — `SELL fill at f => boundary ≥ f − gapSlots`, `BUY fill at f => boundary ≤ f − 1` — because a ±1 crawl can never catch up. The anchor index is the current fill batch's EXTREMUM for the fill side (max slot for SELL, min slot for BUY), not the mutable last-processed pivot: a sweep processed in chunks overwrites the pivot per chunk (live: 1366 → 1349 → 1361), and anchoring on a non-extremum leaves the furthest fill's counter order in-band. Prices come from the fill record (the real execution price, `INV-COW-011`) with the slot id as a legacy fallback. Fail-closed preconditions: a pivot whose `lastFillPivotSource` is `fill` (a book seed never anchors; the bot-scoped last-market-fill row is the fallback), on-ladder price within one increment, a post-clamp target that actually puts the fill outside the window, and `validatePersistedBoundary`
|
|
78
|
+
- A window that lands BEHIND the newest real fill is repaired by `reanchorBoundaryFromLastFill` (called from `calculateTargetGrid` right after the derivation): the fill anchors the geometry — `SELL fill at f => boundary ≥ f − gapSlots`, `BUY fill at f => boundary ≤ f − 1` — because a ±1 crawl can never catch up. The anchor index is the current fill batch's EXTREMUM for the fill side (max slot for SELL, min slot for BUY), not the mutable last-processed pivot: a sweep processed in chunks overwrites the pivot per chunk (live: 1366 → 1349 → 1361), and anchoring on a non-extremum leaves the furthest fill's counter order in-band. Prices come from the fill record (the real execution price, `INV-COW-011`) with the slot id as a legacy fallback. Fail-closed preconditions: a pivot whose `lastFillPivotSource` is `fill` (a book seed never anchors; the bot-scoped last-market-fill row is the fallback), on-ladder price within one increment, a post-clamp target that actually puts the fill outside the window, and `validatePersistedBoundary` — a strand refuses the re-anchor unless the candidate strands **strictly fewer** placed orders than the committed boundary (the violation-reducing repair, measured with the validator's own count; an equal count still refuses). ELIGIBILITY matches the crawl: EDGE-pinned insurance fills never arm the pivot (`recordLastFilledPrices` skips them, shared classifier `collectEdgePinnedFillIds`) and so can never anchor — an edge order is static insurance, not market movement, and an absolute anchor at a rail-edge price would teleport the window there; PARTIAL fills still anchor (real trade) because the fill's OWN PARTIAL residual at the anchor slot is explicitly allow-listed (it is inside the band by construction). Startup/recovery load paths tolerate that pure in-band state (`tolerateTransientStranding`) so a restart does not rebuild the boundary before GAP-EVAC clears the residual. A successful re-anchor is absolute: it consumes the whole pending-crawl snapshot taken at plan time, so no older delta can be applied on top.
|
|
77
79
|
- Consumption is SCOPED to what the derivation applied: `deriveTargetBoundary` returns `consumedCrawlIds` (the owed records whose shift it folded, plus the records it deliberately never counts — current-batch slots, edge-classified slots, malformed records), the plan carries it (`buildSuccessResult` → `CowResult` → `_commitWorkingGrid` options), and `_consumePendingFillCrawls` drops exactly those, logging `Dropped N … kept=M`. A capped fold consumes only the entries it actually applied (same-side prefix up to the applied magnitude), so the remainder stays owed exactly once. `_clearPendingFillCrawls` remains the explicit allowed-loss path (rebuild, rejected snapshot, restart replay) and drops everything.
|
|
78
80
|
- A commit **without** the wire consumes nothing (a create-only plan never derived a boundary): clearing it would be the old silent-loss bug (2026-10-25: 7 slots 147–153 swept, every record dropped, boundary ending 7 levels behind).
|
|
79
81
|
- `consumePendingFillCrawls` applies them onto a restored finite boundary; `applyPersistedPendingCrawls` is the shared startup/recovery wrapper used before sync/reconcile; `_clearPendingFillCrawls` drops them when the boundary is re-anchored (grid rebuild via `initializeGrid`, rejected snapshot via `rejectCorruptedGridSnapshot`, persisted snapshot wipe via `AccountOrders.clearGrid`).
|
|
@@ -101,6 +103,8 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
101
103
|
- A fill record carries the chain execution price (`sync_engine._computeFillTransitionResult` / pass-1 full-fill / pass-2 adoption), computed from paid/received amounts when only the history is available; the slot's generation price is a fallback, never the first choice. The queued-fill pivot refresh (`refreshLastFillPivotFromQueue`) likewise prefers fill economics over the slot price. The slot's identity price is NOT rewritten (`GRID-PRICE-INVARIANT`); only the transient fill/pivot fact uses the chain price.
|
|
102
104
|
- Gap-evacuation geometry maps an on-chain order's LIVE price onto the genesis ladder (`resolveLiveOrderLadderPosition`) before falling back to `parseSlotIndex(slot.id)`. Detection (`detectGapEvacuationCandidates`), the drain-time validation (`_validatePriceCorrectionEntry`), and the teeth (`_processGapEvacuationTeeth`) all use it, so a refused-commit adoption that leaves an order keyed at an in-rail slot cannot hide an in-band order.
|
|
103
105
|
- A price mismatch whose live chain price maps inside the gap band queues a cancel-only `gapEvacuation` correction and drops any opposite-kind (plain re-price) entry for the same chain order. Evacuation takes precedence over correcting the order back to a stale slot price.
|
|
106
|
+
- **Stale-stamp refusal vs. forced retreat.** A gap-evacuation rotation is B-stamped with its plan-build boundary/gap and re-proven against the LIVE geometry at execution (`isEvacuationStampStillValid`): a boundary commit landing mid-batch must not grant a bypass for a move that no longer makes grid sense (the 2026-10-30 bid-edge incident). That refusal assumes the live boundary survives the commit. When the live rails ALREADY conflict — `maxBuy > minSell − gap − 1`, i.e. no boundary can host both rails with the band (`liveRailsConflictWithGap`, reached through the single decision point `forcedRetreatJustifiesEvacuation`, which also refuses to override a stamp whose source/dest ids are unparseable — an unprovable stamp is never overridden) — the batch's retreat is forced, the plan's boundary is the only consistent geometry, and refusing the evacuation is what permanently strands the order inside the band (spread collapse: 4-slot band, real spread 1.21% vs 2.0% target). Both the build loop and the final pivot gate therefore keep the evacuation in that case.
|
|
107
|
+
- **Committed-geometry sweep.** Because the in-batch refusal is fail-closed by design, the writer of the stranding must repair it: after a commit, and on every maintenance tick, `scheduleGapEvacRepair` re-derives the in-band set against the COMMITTED geometry (pruning resolved ledger entries WITHOUT counting a new observation — `reconcileGrid` is the cycle's single tick, and counting twice armed the cancel-only teeth in the very cycle whose rotation evacuated the order), queues the cancel-only teeth past the threshold, and schedules a fill-less COW re-plan (rate-limited 60s per bot). A queued cancel-only evacuation whose chain order the SAME batch rotates is held out of the pre-batch correction drain (`splitEvacuationCancelsSupersededByRotations`): the rotation IS the evacuation, and cancelling first destroyed the batch's own source (live: `2 target(s) missing on chain` → structural resync + full grid reload instead of two in-place price updates). Plans are fill-driven, so without this a quiet market never heals a collapsed spread.
|
|
104
108
|
- The crossing guard's candidate set (`buildCrossingCheckCandidates`) uses the live chain price for master and pending orders, so an emission cannot print onto a live opposite-side order that was adopted at a stale slot price.
|
|
105
109
|
|
|
106
110
|
- `INV-PROJ-001` New projected orders remain virtual
|
|
@@ -136,6 +140,46 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
136
140
|
|
|
137
141
|
---
|
|
138
142
|
|
|
143
|
+
## Order Lifecycle ([ORDER_LIFECYCLE.md](ORDER_LIFECYCLE.md))
|
|
144
|
+
|
|
145
|
+
Chain existence is answered by ONE record per slot (`modules/order/lifecycle.ts`),
|
|
146
|
+
not by the seven per-site structures that used to disagree
|
|
147
|
+
(`_pendingBroadcasts`, `createUncertain`, `_committedOrderIds`,
|
|
148
|
+
`_orderIdAssignedAt`, `_placedAt`, `_chainSizeAppliedFills`,
|
|
149
|
+
`_lastUnmatchedChainOrders`). Those now exist only as live views onto the record.
|
|
150
|
+
|
|
151
|
+
- `INV-LIFE-001` Unknown is never gone
|
|
152
|
+
- `phase === 'unknown'` (lost receipt, ambiguous read, unparseable chain entry) implies `mayExistOnChain === true` and `isConfirmedGone === false`.
|
|
153
|
+
- Only a chain-observed absence sets `phase === 'gone'`. A consumer must never coerce `unknown` into "absent" via a default.
|
|
154
|
+
|
|
155
|
+
- `INV-LIFE-002` One record per slot
|
|
156
|
+
- A slot is the identity across its order incarnations. A chain-id change (rotation, re-place, adoption) updates the existing record; it must not start a parallel one.
|
|
157
|
+
- Writers funnel through `_applyOrderUpdate` → `_syncLifecycleFromMutation`; no call site maintains its own chain-existence bookkeeping (that includes the stamps: `assignedAt`/`placedAt` are written by the funnel only).
|
|
158
|
+
- The one mutation that does not call `_applyOrderUpdate` is the COW whole-map commit (`_commitWorkingGrid`): it projects every slot of the committed map through the same funnel before swapping, so the primary placement path stamps `placedAt`/`assignedAt` too. Without it the surplus-cancel grace is inert for every COW-created order.
|
|
159
|
+
|
|
160
|
+
- `INV-LIFE-003` One definition per guard
|
|
161
|
+
- Absence decisions ("is this order's absence trustworthy yet?") use `isInFlight()`, read through the slot (`readSlotLifecycle`) so a persisted `createUncertain` marker participates.
|
|
162
|
+
- The committed-but-missing guard uses `isRecentlyCommitted()`.
|
|
163
|
+
- The fresh-id guard uses `isRecentlyAssigned()`.
|
|
164
|
+
- A read site must not re-derive a window from a raw map, and must not consult a subset of `isInFlight()`: that is how four sites ended up with four answers.
|
|
165
|
+
|
|
166
|
+
- `INV-LIFE-004` A LIVE unresolved record is never evicted or downgraded
|
|
167
|
+
- Registry pruning skips `unknown` and `broadcasting` while their uncertainty is inside the bound; past it no decision consults them, so they become evictable (the registry keeps a ceiling).
|
|
168
|
+
- `markIntentIfResolved` likewise refuses to downgrade a live uncertainty, and resolves one whose bound has expired instead of leaving an un-honoured suppression behind.
|
|
169
|
+
- A pending CREATE has two distinct exits: *resolved* (`deletePending` → `intent`) and *abandoned* (`_expirePendingBroadcast` → `unknown`). Collapsing them turns a lost receipt into a clean hole that gets re-CREATEd.
|
|
170
|
+
|
|
171
|
+
- `INV-LIFE-005` Unparseable chain entries make absence unknown, not absent
|
|
172
|
+
- A chain order that was returned but could not be decoded puts its slot's absence in the UNKNOWN bucket (`sync_engine` pass-1 guard 0, mirroring the accounting recovery sweep's `malformedOrderIds`); the slot is not virtualized.
|
|
173
|
+
|
|
174
|
+
- `INV-LIFE-006` Evidence is monotonic; clocks cannot be refreshed for free
|
|
175
|
+
- Within a phase the evidence rank may only rise (`local` < `broadcast-receipt` < `adoption` < `chain-snapshot` < `fill-history`), so a local write cannot overwrite what the chain said.
|
|
176
|
+
- `observedAt` advances only for chain-backed evidence.
|
|
177
|
+
- `recordedAt` (the anchor of the unresolved bound) advances only on a phase change or chain-backed evidence: re-asserting `unknown` is not new information.
|
|
178
|
+
|
|
179
|
+
- `INV-LIFE-007` The unresolved bound is measured from when the uncertainty was RECORDED
|
|
180
|
+
- `isInFlight()` is bounded (2× `PENDING_BROADCAST_TTL_MS`) from `recordedAt`, so a lagging node cannot park the grid and a bot that re-asserts `unknown` every cycle cannot extend its own suppression.
|
|
181
|
+
- An explicit decision (`markIntent`) or chain evidence resolves the phase sooner; age alone never extends it.
|
|
182
|
+
|
|
139
183
|
## Sync Engine
|
|
140
184
|
|
|
141
185
|
- `INV-SYNC-001` Drift-refetch for partial fill correctness
|
|
@@ -153,8 +197,9 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
153
197
|
- The sync engine must treat this as a chain-confirmed empty, not a connection failure.
|
|
154
198
|
|
|
155
199
|
- `INV-SYNC-004` Orphan adoption rejects duplicate price levels
|
|
156
|
-
- Pass-2
|
|
157
|
-
-
|
|
200
|
+
- Pass-2 adoption must check whether an active grid order of the same type already maps to the same ladder level (`chainPriceOnSameLevel` → `pricesOnSameLevel`: the chain price and the grid level resolve to one slot, so equality is by level, not by a tuned band).
|
|
201
|
+
- `calculatePriceTolerance` is NOT the duplicate rule; it survives only inside helpers that need a representable-price tolerance, and the old `findMatchingGridOrderByOpenOrder` matcher is gone (see [GRID_PRICE_INVARIANT.md](GRID_PRICE_INVARIANT.md#the-tolerance-matcher-is-gone)).
|
|
202
|
+
- If a duplicate exists, the orphan is NOT adopted; it is pushed to `unmatchedChainOrders` as `duplicate-price-level` for chain cancel.
|
|
158
203
|
- Size is irrelevant — any duplicate violates the one-order-per-price-level invariant.
|
|
159
204
|
|
|
160
205
|
- `INV-SYNC-005` Fill queue back-pressure
|
|
@@ -176,6 +221,8 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
176
221
|
- `INV-SYNC-008` SPREAD-typed fills resolve the real side
|
|
177
222
|
- A SPREAD slot can carry an on-chain order (spread-correction activation). Fill processing must resolve the real BUY/SELL side (chain order type, pays asset, or price-vs-startPrice convention) before pushing the fill or computing the transition.
|
|
178
223
|
- A SPREAD-typed fill would silently drop the `deriveTargetBoundary` shift and produce an illegal SPREAD+on-chain state rejected by `validateOrder`.
|
|
224
|
+
- The pays-asset mapping has ONE implementation (`order/fill_ledger.ts` `resolveTradedSide`, used by `_computeFillContext`, the unmatched-fill attribution and the queued pivot refresh). The SPREAD price fallback stays with the caller that owns the ladder (`resolveSpreadOrderSide`).
|
|
225
|
+
- `slot.type` is the ACCOUNTING side and is retagged to the traded side by a partial-fill transition (so `size` stays dimensionally consistent for `recalculateFunds`). It is NOT rail identity: a repair proof must also read the level's geometry (`geometryTypeForSlotIndex`), and a fill-retagged slot on the opposite rail is still wrong-side. See `docs/FILL_PIPELINE.md` INV-FILL-002/INV-FILL-006.
|
|
179
226
|
|
|
180
227
|
---
|
|
181
228
|
|
|
@@ -183,7 +230,7 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
183
230
|
|
|
184
231
|
- `INV-MAINT-001` Pipeline in-flight defers maintenance
|
|
185
232
|
- When `isPipelineEmpty` returns `isEmpty=false` (batch in-flight, recovery-in-flight, or broadcasting active), `checkSpreadCondition` and divergence corrections must be skipped.
|
|
186
|
-
- Dust cancels
|
|
233
|
+
- Dust cancels mutate the chain, so they take the **exclusive placement region** (`withPlacement('dust-cancel')`) and defer to the next cycle when it is busy or the bot is shutting down — they are NOT "safe regardless of pipeline state". The rotation batch that follows the cancels runs after the region is released and acquires its own lease.
|
|
187
234
|
- Pipeline signals (`batchInFlight`, `recoveryInFlight`, `broadcasting`) must be passed to `isPipelineEmpty`.
|
|
188
235
|
|
|
189
236
|
- `INV-MAINT-002` Illegal state abort
|
|
@@ -262,7 +309,9 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
262
309
|
- SELL placements must use nearest available free slots first (ascending price).
|
|
263
310
|
|
|
264
311
|
- `INV-RECON-006` Fresh-placement cancels are deferred for a grace window
|
|
265
|
-
- A CANCEL action targeting an `orderId` placed within `TIMING.SURPLUS_CANCEL_GRACE_MS` (15 min) is deferred. The timestamp is written by
|
|
312
|
+
- A CANCEL action targeting an `orderId` placed within `TIMING.SURPLUS_CANCEL_GRACE_MS` (15 min) is deferred. The timestamp is written only by the lifecycle write funnel into `manager._placedAt`, and tested by `isFreshlyPlacedOrder`.
|
|
313
|
+
- **Exemption (chain-observed wrong side).** A CANCEL for an order the correction queue holds as a chain-observed `typeMismatch` (`entry.typeMismatch === true` with a `chainOrderId`) is exempt: the chain already proved the side is wrong, so parking it adds a second 15-minute wait after the pre-batch drain deferred (active region) or failed. A plan-shaped CANCEL whose reason is `type-mismatch` is NOT exempt — it only proves master ≠ target, which is the stale-target lag this grace exists for. The exemption is a queue-provenance fact, not a grid blocker: see `docs/FILL_PIPELINE.md` INV-FILL-004.
|
|
314
|
+
- A queued `typeMismatch` entry stays valid while the level's stored type OR its rail geometry still disagrees with the chain side; a retagged `slot.type` alone is not a repair (INV-SYNC-008 / `docs/FILL_PIPELINE.md` INV-FILL-006).
|
|
266
315
|
- `COWRebalanceEngine.execute` drops the whole slot's action group for a deferred cancel (dropping only the CANCEL would let a paired CREATE fold back into an UPDATE and re-materialize the placement), then re-syncs the deferred slots from master via `workingGrid.syncFromMaster` so the commit does not virtualize a still-live order.
|
|
267
316
|
- Divergence correction (`applyGridDivergenceCorrections`) applies the same guard after dropping any queued committed-size UPDATE for the not-desired/size-0 slot.
|
|
268
317
|
- `grid-load`/`grid-init` load contexts are excluded so restarts do not suppress the sweep.
|
|
@@ -363,6 +412,20 @@ This document defines the non-negotiable behavioral invariants for the DEXBot2 s
|
|
|
363
412
|
- A `get_full_accounts` window capped at the order limit omits the freshest orders (by_account index = seller,id ascending — fresh creates sort last), so absence on a truncated/empty read can never free slots/capital, confirm a cancel, discard a batch, or clear pending-broadcast protection.
|
|
364
413
|
- All absence decisions use `readOpenOrdersWithMeta`; truncated/empty snapshots defer (keep protection + request structural resync) instead of acting.
|
|
365
414
|
|
|
415
|
+
- `INV-BROADCAST-005` One exclusive placement region; one lease-liveness predicate
|
|
416
|
+
- Every chain-mutating path (COW broadcast, reconcile Phase 1+2, correction drain, dust/residual cancel, pool swap) runs inside the exclusive placement region (`modules/order/placement_lock.ts`). The broadcast refcount only defers fills; it is not mutual exclusion.
|
|
417
|
+
- The region is NOT reentrant. Nested work receives the holder's lease and verifies it with `manager.isPlacementLeaseCurrent(lease)` — `isPlacementActive()` is true for ANY holder and must never stand in for ownership.
|
|
418
|
+
- Non-token holders must use `manager.withPlacement()` (single acquire/release contract, bounded wait, shutdown probe). `correctAllPriceMismatches` is the only nested consumer and takes the inherited lease explicitly.
|
|
419
|
+
- Pending-broadcast liveness has ONE policy (`getLivePendingBroadcasts`): TTL, or TTL + a sync completed after the record, or 2× TTL hard cap. Every reader (COW guard, reconcile CREATE, reconcile surplus sweep, crossing candidates, maintenance lightweight-sync gate) uses it.
|
|
420
|
+
- A PLACEMENT-BACKED hung region is torn down by ONE authority: `_clearStalePlacementRegion()` after `PLACEMENT_STALE_CLEAR_MS`, and it also clears that region's stale broadcast refcount atomically. The teardown's refcount clear is sound only because a refcount raised by a placement holder belongs to that same region; a refcount raised OUTSIDE any placement region (the spread-correction pre-broadcast hold in `order/grid.ts`) is not touched by it and is still cleared by its own watchdog. The broadcast watchdog refuses to act while a placement lease is held (so it only clears a refcount leaked without a lease), and the placement watchdog refuses a teardown while a bot-level pipeline counter younger than the bound proves progress.
|
|
421
|
+
- The owner of a region must re-verify its own lease (`isPlacementLeaseCurrent`) before it BROADCASTS a CREATE/UPDATE batch: a watchdog teardown turns the lease into a stale token, and a resumed holder must abort instead of broadcasting unprotected (COW body: `PLACEMENT_LEASE_LOST`; reconcile Phase 1+2: the plan is discarded and the cycle defers). Pure cancel paths are exempt — a cancel carries its own order id and cannot duplicate a CREATE.
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
- `INV-TIME-001` Every timing window is classified, and self-healing windows are removal targets
|
|
425
|
+
- `modules/timing_policy.ts` classifies every `TIMING` window as `external`, `bound`, `policy` or `self-healing`, each with a rationale; a `self-healing` window must also name the evidence that replaces it.
|
|
426
|
+
- `tests/test_timing_policy.ts` fails on an unclassified window, so the inventory can only shrink by decision.
|
|
427
|
+
- A wait that compensates for our own lost state is a bug with a timer attached; the fix is a lifecycle phase, not patience. See [TIMING_INVENTORY.md](TIMING_INVENTORY.md).
|
|
428
|
+
|
|
366
429
|
## Change Policy
|
|
367
430
|
|
|
368
431
|
- Any intentional invariant change must:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# DEXBot vs DEXBot2 — Detailed Comparison Report
|
|
2
2
|
|
|
3
3
|
> **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
|
|
4
|
-
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.7.
|
|
4
|
+
> **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.7.2).
|
|
5
5
|
> **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
|
|
6
6
|
|
|
7
7
|
---
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
| Attribute | DEXBot (original) | DEXBot2 |
|
|
38
38
|
|---|---|---|
|
|
39
|
-
| **Release Track** | 1.0.0 | v1.7.
|
|
39
|
+
| **Release Track** | 1.0.0 | v1.7.2 |
|
|
40
40
|
| **Language** | Python 3.6+ | TypeScript 5.x |
|
|
41
41
|
| **Status** | Released 1.0.0, unmaintained | Active development |
|
|
42
42
|
| **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
|
|
@@ -776,13 +776,13 @@ Where:
|
|
|
776
776
|
|
|
777
777
|
| Metric | DEXBot | DEXBot2 |
|
|
778
778
|
|---|---|---|
|
|
779
|
-
| **Release Track** | 1.0.0 | v1.7.
|
|
779
|
+
| **Release Track** | 1.0.0 | v1.7.2 |
|
|
780
780
|
| **Active Since** | ~2018 | December 2025 |
|
|
781
|
-
| **Last Commit** | May 23, 2020 | 2026-11-
|
|
782
|
-
| **Total Commits** | 2281 | 2,
|
|
781
|
+
| **Last Commit** | May 23, 2020 | 2026-11-04 |
|
|
782
|
+
| **Total Commits** | 2281 | 2,506 (current HEAD, v1.7.2 line) |
|
|
783
783
|
| **Lines of Code** | ~10,846 Python LOC in `dexbot/` | Large TypeScript runtime + adapter + Claw + analysis + tests |
|
|
784
784
|
| **Source Files** | 72 Python files in `dexbot/` | ~656 TS files across the repo |
|
|
785
|
-
| **Test Files** | 16 Python test files |
|
|
785
|
+
| **Test Files** | 16 Python test files | 367 `test_*.ts` files (350 `tests/` + 17 `claw/tests/`, auto-discovered via `globSync`) |
|
|
786
786
|
| **Documentation** | Sphinx docs + README | 60+ Markdown docs plus Claw skills/references |
|
|
787
787
|
| **Strategies** | 3 + plugins | 1 |
|
|
788
788
|
| **Max Concurrent Bots** | Many (one process) | Many (one monolithic process by default; per-bot via `--isolated`/PM2) |
|
package/docs/EVOLUTION.md
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
## Executive Summary
|
|
4
4
|
|
|
5
|
-
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.7.
|
|
5
|
+
DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.7.2 stable release.
|
|
6
6
|
|
|
7
7
|
### Key Milestones
|
|
8
8
|
- **Project Inception**: December 2, 2025
|
|
9
|
-
- **Growth Phase**: 2,
|
|
9
|
+
- **Growth Phase**: 2,506 commits over ~9 active months
|
|
10
10
|
- **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
|
|
11
|
-
- **Stability**: Progression from manual testing to a suite of
|
|
12
|
-
- **Releases**:
|
|
11
|
+
- **Stability**: Progression from manual testing to a suite of 358 automated test files (live tests included in `test:live`)
|
|
12
|
+
- **Releases**: 153 changelog entries (v0.1.0 to v1.7.2)
|
|
13
13
|
|
|
14
14
|
> **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
|
|
15
15
|
> bug families, and lessons — lives in
|
|
@@ -149,7 +149,7 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
|
|
|
149
149
|
|
|
150
150
|
## Version History
|
|
151
151
|
|
|
152
|
-
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-11-
|
|
152
|
+
Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-11-04). The 107 commits up to and including the `v0.1.0` tag are not attributed to an era, so the current totals are 2,385 (`v0.1.0..HEAD`) and 2,492 (`HEAD`); the `v1.4.x` era rows overlap slightly because `v1.4.13` is not an ancestor of `v1.4.25` in the current history. Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
|
|
153
153
|
|
|
154
154
|
| Era | Commits | Theme |
|
|
155
155
|
|-----|--------:|-------|
|
|
@@ -177,11 +177,13 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
|
|
|
177
177
|
| v1.6.16 → v1.6.17 | 11 | Last-fill direction guard, placeable-slot spread planning with named stalls, chain-truth funding + fill-anchored boundary re-anchor, owed-crawl consumption, restart auth-before-stop with cleared vault secret, pool-priced LP-share collateral, AMA slowPeriod/slope retune, BTS & per-token supply distribution analyzers |
|
|
178
178
|
| v1.6.17 → v1.6.18 | 19 | Partial-fill re-anchor recovery (stale-evac skip, residual allow-list, crawl subsumption, rotation-only repair), rail-derived boundary + live fill/chain prices, edge-fill pivot exclusion, guard arity pinning with explicit re-arm, per-slot last-fill exclusion count, CLI `--flag=value` walker, `__test` seam guard, export-surface cleanup |
|
|
179
179
|
| v1.6.18 → v1.7.0 | 11 | Liquidity depth chart + `dexbot liquid`/`liq`/`liqu`, `dexbot asset` supply distribution shortcut, pool id/pool-token chart targets + shared spawn runner, case-insensitive asset lookup, asset-report chain-request cuts, shared CLI terminal output, orphan-fill attribution + dark-level revive, stale-grid re-buy discipline, pivot clock provenance & read-time TTL |
|
|
180
|
+
| v1.7.1 → v1.7.2 | 13 | One fill contract + fill-pipeline ratchet, fail-closed grid-update blockers with bounded escalation, single fill identity (`fill_ledger`), credit-time fill-key claim with all-or-nothing balance credits, single-winner concurrent claim, removal of the duplicate applied-amount channel and the second grace-stamp writer, COW broadcast-region leak repair, chain-observed wrong-side cancel exemptions, fill side derived from the paid asset + rail-geometry repair check, fill-anchored rebuild/load boundary, spread rotation into orphaned rail slots, consecutive grid-blocked escalation counter, live-suite env fix |
|
|
181
|
+
| v1.7.0 → v1.7.1 | 22 | One existence record per slot (life-cycle registry, unknown-is-never-gone), typed three-valued broadcast outcome, timing-window policy inventory, reconciliation interleaving fuzzer, one writer per life-cycle clock, serialized placement region with lease re-verification, fill-marker idempotency, forced-retreat gap evacuation + committed-geometry sweep, unknown-gap-geometry fix, replay-safe stranded-boundary repair, stability-ranked node selection + flap scoring, chain-account `<bot>` targets for `credit`/`order`, fee-adjusted pool depth chart with both spreads, atomic branch promotion preflight |
|
|
180
182
|
|
|
181
183
|
---
|
|
182
184
|
|
|
183
185
|
**Report Originally Generated**: February 19, 2026
|
|
184
|
-
**Last Updated**: November
|
|
185
|
-
**Total Commits**: 2,
|
|
186
|
-
**Date Range**: December 2, 2025 – November
|
|
186
|
+
**Last Updated**: November 4, 2026
|
|
187
|
+
**Total Commits**: 2,506
|
|
188
|
+
**Date Range**: December 2, 2025 – November 4, 2026
|
|
187
189
|
**Repository**: DEXBot2 (BitShares DEX Trading Bot)
|
|
@@ -805,4 +805,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
|
|
|
805
805
|
**TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
|
|
806
806
|
|
|
807
807
|
---
|
|
808
|
-
*Technical Reference for DEXBot2 v1.7.
|
|
808
|
+
*Technical Reference for DEXBot2 v1.7.2 release*
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# The Grid-Price Invariant
|
|
2
2
|
|
|
3
3
|
Status: **implemented; the emission check is BLOCKING**
|
|
4
|
-
Last code-reviewed against the v1.
|
|
4
|
+
Last code-reviewed against the v1.7.0 release baseline `5644aa3a` (2026-11-02).
|
|
5
5
|
|
|
6
6
|
## The invariant
|
|
7
7
|
|
package/docs/GRID_RECONCILE.md
CHANGED
|
@@ -22,7 +22,9 @@ Reconciliation aligns the bot's model with on-chain reality. It runs at startup
|
|
|
22
22
|
|
|
23
23
|
The reconcile runs from [`recalculateGrid`](../modules/order/grid.ts) during startup full-resync. **There is no per-attempt wall-clock race around the reconcile itself** — an outer timeout would fire mid-batch and orphan in-flight broadcasts (the duplicate-accumulation death spiral). The reconcile is bounded only by the 10-minute total resync safety net, and every internal chain read follows the shared guarded-read standard.
|
|
24
24
|
|
|
25
|
-
Phase 1 does all reasoning in memory under `_gridLock` (fast); Phases 2 and 3 execute outside that planning lock — holding it across RPC calls would block fills, sync, and divergence checks. Phase 2 holds the broadcasting single-flight marker, while the sync/apply paths it invokes follow the canonical lock hierarchy. No planning-phase grid lock spans a network operation.
|
|
25
|
+
Phase 1 does all reasoning in memory under `_gridLock` (fast); Phases 2 and 3 execute outside that planning lock — holding it across RPC calls would block fills, sync, and divergence checks. **Both phases run inside the exclusive placement region** (`manager.acquirePlacement('startup-reconcile')`, acquired before the chain snapshot is trusted and released after `stopBroadcasting`), so no other chain-mutating path can broadcast between Phase 1's plan and Phase 2's execution. Phase 2 additionally holds the broadcasting single-flight marker (which only defers fills), while the sync/apply paths it invokes follow the canonical lock hierarchy. No planning-phase grid lock spans a network operation.
|
|
26
|
+
|
|
27
|
+
The reconcile is not purely time-unbounded: besides the 10-minute total resync safety net it also waits up to 120 s for the placement region and re-reads the open-orders snapshot after acquiring it (planning from a snapshot older than the region is exactly the duplicate class). A reconcile that cannot get the region returns `null` and defers to the next sync cycle.
|
|
26
28
|
|
|
27
29
|
Phase 2 and 3 both respect the `dryRun` flag: when true, no on-chain mutations are attempted — plans are logged but not executed.
|
|
28
30
|
|
|
@@ -80,8 +82,8 @@ Phase 2 and 3 both respect the `dryRun` flag: when true, no on-chain mutations a
|
|
|
80
82
|
|
|
81
83
|
**Source:** `reconcileGridOrders()` Phase 1 in `grid_reconcile.ts`.
|
|
82
84
|
|
|
83
|
-
1. **Phantom order sanitization** (the `isOrderPlaced()` absence pass in `reconcileGridOrders()`): For each `isOrderPlaced()` order whose `orderId` is not in the chain snapshot, reset it to VIRTUAL with `skipAccounting` to prevent fund inflation.
|
|
84
|
-
- **
|
|
85
|
+
1. **Phantom order sanitization** (the `isOrderPlaced()` absence pass in `reconcileGridOrders()`): For each `isOrderPlaced()` order whose `orderId` is not in the chain snapshot, reset it to VIRTUAL with `skipAccounting` to prevent fund inflation. One absence-decision guard makes this safe:
|
|
86
|
+
- **In-flight deferral** (`LifecycleView.isInFlight()`, read through the slot with `readSlotLifecycle`): an order whose chain id was assigned/committed within the guard window, or whose lifecycle phase is still unresolved (`unknown`/`broadcasting` — a lost CREATE receipt, an ambiguous or unparseable read), may be live and merely missing from a lagging/truncated read — virtualizing it and re-creating would duplicate a real live order (the reconcile-timeout death-spiral root cause). It is skipped (deferred) rather than virtualized. The same predicate is the only absence guard in the sync pass-1 phantom cleanup and the fund recalibration sweep; asking a per-site subset is the bug class [ORDER_LIFECYCLE.md](ORDER_LIFECYCLE.md) exists to remove.
|
|
85
87
|
- **Ghost heuristic** (same absence pass): an order with `size <= 0` && `PARTIAL` (a known filled ghost) still passes through so known fills get cleaned up.
|
|
86
88
|
- Virtualization always uses `{ skipAccounting: true }` so startup cleanup never inflates `ChainFree`.
|
|
87
89
|
|
|
@@ -93,7 +95,7 @@ Phase 2 and 3 both respect the `dryRun` flag: when true, no on-chain mutations a
|
|
|
93
95
|
- Match sorted unmatched chain orders to virtual slots → `plannedUpdates`
|
|
94
96
|
- Detect grid-edge lock and plan a largest-order cancel
|
|
95
97
|
- Plan creates for remaining slots
|
|
96
|
-
- Plan excess cancellations (guarded by `matchedOnGrid > 0`): orphans first, then **matched surplus** (`chainCount - targetCount`, edge slots last) —
|
|
98
|
+
- Plan excess cancellations (guarded by `matchedOnGrid > 0`): orphans first, then **matched surplus** (`chainCount - targetCount`, edge slots last) — ONE selection feeds both the planOnly and the inline sink (the `excessPlans` list), so planning can never drift from execution; matched slots omit `releaseUntrackedFunds` (their funds are tracked on the grid slot). Every plan stamps the gap geometry from `resolveGapSlots` (never the raw `_gapSlots` field), which is also what the Phase-2 plan validator compares against
|
|
97
99
|
- Fork-kept **shelf orders** (live non-slot-N ids below the rail, e.g. `deep-*`) are never cancel candidates or reserve members — see [Shelf Orders](#shelf-orders-fork-kept-manual-orders)
|
|
98
100
|
- **Vacated-rail refill**: each PROCEEDING update whose vacated price exactly matches (`priceSlotEqual`) an empty, sized, in-rail slot of the same side queues a refill CREATE in the same plan (`source startupVacatedRailRefill`) — skipped updates, ghost prices (lattice moved), in-band slots, and already-desired slots never refill; refill targets require VIRTUAL state with no `orderId`
|
|
99
101
|
|
|
@@ -115,7 +117,9 @@ snapshots. For every plan, `_startupCancelPlanStillCurrent()` requires:
|
|
|
115
117
|
|
|
116
118
|
- the target chain order still exists with its exact Phase-1 signature;
|
|
117
119
|
- a matched plan still owns the same chain order in the same live grid slot;
|
|
118
|
-
- planned type, slot price, boundary, and gap geometry still match
|
|
120
|
+
- planned type, slot price, boundary, and gap geometry still match (both sides
|
|
121
|
+
read the geometry through `resolveGapSlots`, so an unpublished `_gapSlots`
|
|
122
|
+
field cannot make every plan look stale); and
|
|
119
123
|
- an originally unmatched surplus is still not owned by any live slot.
|
|
120
124
|
|
|
121
125
|
Validation is per-plan: an earlier cancellation or unrelated order change does
|
|
@@ -127,8 +131,9 @@ remain unchanged.
|
|
|
127
131
|
|
|
128
132
|
**Fresh-placement grace (`TIMING.SURPLUS_CANCEL_GRACE_MS`, 15 min):** surplus
|
|
129
133
|
and cancel-only cancellations also skip any order whose `orderId` was placed
|
|
130
|
-
inside the grace window. The timestamp is written by
|
|
131
|
-
`
|
|
134
|
+
inside the grace window. The timestamp is written only by the lifecycle write
|
|
135
|
+
funnel (`_syncLifecycleFromMutation` -> `markPlaced`) into `manager._placedAt`
|
|
136
|
+
and tested with `isFreshlyPlacedOrder`; the reconciler's CANCEL
|
|
132
137
|
actions are filtered by `COWRebalanceEngine.execute`, which drops the whole slot's
|
|
133
138
|
action group (a paired CANCEL+CREATE must not lose only its CANCEL, or the CREATE
|
|
134
139
|
folds back into an UPDATE and re-materializes the placement) and re-syncs the
|
|
@@ -207,7 +212,7 @@ Up to 3 batch attempts (`maxBatchAttempts = 3`). Each failure triggers a recover
|
|
|
207
212
|
|
|
208
213
|
### Phantom Orders via Reconcile
|
|
209
214
|
|
|
210
|
-
Reconcile's role in the defense-in-depth: during Phase 1, any ACTIVE/PARTIAL order whose `orderId` is not found on-chain is reset to VIRTUAL with `skipAccounting`. The
|
|
215
|
+
Reconcile's role in the defense-in-depth: during Phase 1, any ACTIVE/PARTIAL order whose `orderId` is not found on-chain is reset to VIRTUAL with `skipAccounting`. The in-flight deferral (`LifecycleView.isInFlight()`) protects in-flight broadcasts and unresolved receipts, and the ghost heuristic lets known fills pass. See [`developer_guide.md`](developer_guide.md#phantom-orders-prevention-defense-in-depth) for the full 3-layer defense.
|
|
211
216
|
|
|
212
217
|
### Shelf Orders (Fork-Kept Manual Orders)
|
|
213
218
|
|
|
@@ -232,7 +237,7 @@ Reconcile derives its window from the **master grid**, which is only as fresh as
|
|
|
232
237
|
- **Unsettled-fill gate** (`hasUnsettledFills`, `utils/system.ts`): while fills are queued (`_incomingFillQueue`), draining (`_deferredFillsPending`), in flight (`_fillBatchInFlight`) or owed a crawl (`_pendingFillCrawls`), `maybeRunTargetedDriftReconciliation` defers the targeted reconcile entirely and `_reconcileStartupSide` defers only the **window top-up** creates (1:1 repairs — cancelled-slot replacement, vacated-rail refill — still run). The master still counts filled slots as ACTIVE in that window, so a top-up would restore the expensive end of the rail.
|
|
233
238
|
- **Last-fill placement guard** (`isLastFillPlacementBlocked`, `utils/system.ts`): every reconcile placement (create in `_createOrderFromGrid` and the batch create path, plus the re-pricing relocation in `_prepareStartupUpdatePlan`) is refused when it sits on the wrong side of the last fill **or on the same grid level** (within half an increment — a slot level and its execution price differ by rounding). A same-price relocation is an adoption, not a placement, and is exempt. `_pickVirtualSlotsToActivate` applies the same predicate so the pick budget rolls to the next level down/up instead of being spent on a level the create would refuse — the filled level is never re-stamped same-side (the "rotate to bottom BUY / counter SELL" behaviour).
|
|
234
239
|
|
|
235
|
-
A fill whose order id no longer sits on an ACTIVE/PARTIAL slot is no longer dropped: `attributeUnmatchedFillToGrid` (shared by `SyncEngine._absorbUnmatchedFill` and the orphan-credit sweep in `dexbot_fill_runtime.ts`) records the **pivot + owed crawl from the real execution price**. It resolves the slot two ways — the chain id when a virtualised slot still owns it, otherwise the **genesis ladder level of the execution price** (the common case, because `virtualizeOrder` NULLS `orderId`; this is what the incident actually hit). A crawl is only owed by a HOLE, and a price outside the frozen rail is refused so a shelf order cannot arm the pivot. Without this the pivot stays on a stale, higher fill and the direction rule then permits re-buys above the market.
|
|
240
|
+
A fill whose order id no longer sits on an ACTIVE/PARTIAL slot is no longer dropped: `attributeUnmatchedFillToGrid` (shared by `SyncEngine._absorbUnmatchedFill` and the orphan-credit sweep in `dexbot_fill_runtime.ts`) records the **pivot + owed crawl from the real execution price**. It resolves the slot two ways — the chain id when a virtualised slot still owns it, otherwise the **genesis ladder level of the execution price** (the common case, because `virtualizeOrder` NULLS `orderId`; this is what the incident actually hit). A crawl is only owed by a HOLE, and a price outside the frozen rail is refused so a shelf order cannot arm the pivot. Without this the pivot stays on a stale, higher fill and the direction rule then permits re-buys above the market. The sweep is **replay-safe**: the processed-fill ledger is the authority, so attribution runs only when the accounting is not a `duplicate`. A replay already armed the pivot/crawl on its first delivery; re-attributing it re-records an old execution price (live: a 12-minute-old replay re-recorded four crawls and moved the boundary 165 → 169).
|
|
236
241
|
|
|
237
242
|
**The dark level it leaves behind is repaired too.** A slot virtualised while its order stayed live on chain reads as *not active* (`_countActiveOnGrid` needs ACTIVE/PARTIAL) while its order still counts in `chainCount`, so the side reports a shortfall it can never repair — and the planner sees a free level that already holds an order. Three pieces close that:
|
|
238
243
|
|
|
@@ -260,12 +265,12 @@ The underlying rule is `INV-BROADCAST-004`: a capped `get_full_accounts` window
|
|
|
260
265
|
**`manager.ts` lock declaration** — canonical reference in [`developer_guide.md`](developer_guide.md#lock-ordering-for-deadlock-prevention).
|
|
261
266
|
|
|
262
267
|
```
|
|
263
|
-
Level 0:
|
|
264
|
-
Level
|
|
265
|
-
Level 4:
|
|
268
|
+
Level 0: _fillProcessingLock Level 0.5: placement region
|
|
269
|
+
Level 1: _divergenceLock Level 2: _syncLock
|
|
270
|
+
Level 3: _gridLock Level 4: _fundLock
|
|
266
271
|
```
|
|
267
272
|
|
|
268
|
-
Acquire in ascending level order only. AsyncLock is re-entrant (nested `acquire()` run directly, not queued).
|
|
273
|
+
Acquire in ascending level order only. AsyncLock is re-entrant (nested `acquire()` run directly, not queued); the placement region (`modules/order/placement_lock.ts`) is NOT re-entrant — it is a FIFO lease, and nested work must reuse the holder's lease (verified with `manager.isPlacementLeaseCurrent()`).
|
|
269
274
|
|
|
270
275
|
### Historical Correction (1.4.6)
|
|
271
276
|
|
package/docs/LOGGING.md
CHANGED
|
@@ -252,7 +252,7 @@ Prefix tags used in log messages to help operators identify event types. To find
|
|
|
252
252
|
| `[STRATEGY]` | `order/strategy.ts` | Fee event cache and strategy decisions |
|
|
253
253
|
| `[RECONCILE]` | `order/utils/validate.ts` | Grid reconciliation ([GRID_RECONCILE.md](GRID_RECONCILE.md)) |
|
|
254
254
|
| `[RMS]` | `order/grid.ts`, `dexbot_maintenance_runtime.ts` | RMS structural-divergence checks: per-side `metric vs threshold → TRIGGER-RESYNC/no trigger` at `debug` (plus a `checks disabled` variant when the threshold is 0), reset line with threshold + breaching sides at `info` |
|
|
255
|
-
| `[GAP-EVAC]` | `order/utils/validate.ts`, `order/manager.ts`, `dexbot_startup_runtime.ts`, `dexbot_state_recovery.ts` | Stuck in-band (gap-band) order streak warnings, cancel-only evacuation teeth, persisted-streak restore counts |
|
|
255
|
+
| `[GAP-EVAC]` | `order/utils/validate.ts`, `order/manager.ts`, `dexbot_startup_runtime.ts`, `dexbot_state_recovery.ts`, `dexbot_maintenance_runtime.ts` | Stuck in-band (gap-band) order streak warnings, cancel-only evacuation teeth, persisted-streak restore counts, and the committed-geometry stranding sweep (post-commit + maintenance tick) |
|
|
256
256
|
| `[GRID-TYPE-CORRECT]` | `order/grid.ts` | One-time backfill retype of legacy empty slots to rail-typed holes on load |
|
|
257
257
|
| `[LAST-FILL-GUARD]` | `dexbot_cow_runtime.ts` | Last-fill-guard blocks plus gap-evacuation bypass allows/stale-stamp downgrades |
|
|
258
258
|
| `[RESTAMP-BUY]` | `dexbot_cow_runtime.ts` | BUY emitted at/above the last filled BUY pivot (guard bypass / unjudgeable pivot), counted not blocked (P2) |
|
|
@@ -313,11 +313,35 @@ re-plan retries). Kept separate from the generic `refusedCommitCount`.
|
|
|
313
313
|
| `[SPREAD] No fundable side, but a rotation-only repair is available on <side>; using resting inventory (no new commitment).` | Both sides read zero free (or side selection returned no fundable side), but a promoted gap slot can be filled by rotating a resting order. Cross-asset side selection was not overridden when the market price itself was unavailable |
|
|
314
314
|
| `[LAST-FILL-GUARD] Skipping <type> UPDATE for <src> -> <dst>: stale gap-evacuation (...) — next plan re-evaluates` | A plan-build gap-evacuation stamp no longer matches the LIVE boundary/gap (or the live probe is not violation-reducing). The op is dropped instead of falling through to the direction-only last-fill guard; the next plan/reconcile owns the move |
|
|
315
315
|
| `[LAST-FILL-GUARD] Final gate dropping stale gap-evacuation ...` | The final pre-broadcast pivot gate also refuses a stamp whose live geometry went stale after op-building, even when the destination price itself is direction-legal |
|
|
316
|
+
| `[LAST-FILL-GUARD] Stamped evacuation for <src> -> <dst> is stale under live boundary B/gap G, but the live rails already conflict (maxBuy=X > minSell-gap-1=Y) — the retreat this batch commits is forced, so the evacuation proceeds` | Forced-retreat allowance (`liveRailsConflictWithGap`). The stale-stamp refusal assumes the live boundary survives the commit; when the live rails already overlap, NO boundary can host both rails with the gap band, so the batch's retreat is the only consistent geometry and refusing the evacuation is what permanently strands the order in the band (spread collapse). The same allowance is applied by the build loop and by the final pivot gate |
|
|
317
|
+
| `[LAST-FILL-GUARD] Final gate keeping gap-evacuation ... despite live boundary B/gap G: the live rails already conflict ...` | The final-gate mirror of the forced-retreat allowance above (keeping the op is violation-reducing, not a guard bypass) |
|
|
318
|
+
| `[GAP-EVAC] N live order(s) stranded inside the spread band (boundary B, gap G): <slot(side), ...> — scheduling a fill-less re-plan to evacuate (<context>)` | Post-commit / maintenance sweep: live rail orders are resting inside the committed band, so the real top-of-book spread is narrower than the configured one. A fill-less COW re-plan runs against the committed geometry (where the evacuation stamp validates) — plans are fill-driven, so a quiet market would otherwise never heal. Rate-limited (60s) per bot; repeats inside the window log at `debug` |
|
|
319
|
+
| `[GAP-EVAC] ... repair cooldown active (Ns left); teeth queued=N` | The sweep found the same stranding again inside the repair cooldown window; the cancel-only teeth remain the last resort |
|
|
320
|
+
| `[COW] Holding N gap-evacuation cancel(s) back from the pre-batch drain: this batch rotates the same chain order (the rotation IS the evacuation)` | A cancel-only evacuation queued for a chain order the current batch rotates. Draining it first would cancel the batch's own rotation source and the UPDATE batch would be rejected pre-broadcast (`target(s) missing on chain` → structural resync). The entry is restored after the drain and dropped as stale once the slot no longer owns the order |
|
|
321
|
+
| `[GAP-EVAC] Spread band clean: cleared N resolved in-band streak(s)` | The sweep found no live order inside the committed band and dropped N resolved ledger entries, so a future return to the band re-arms instead of inheriting a stale cycle count. Logged only when something was actually cleared |
|
|
322
|
+
| `[GAP-EVAC] ... unknown geometry` (silent) | With no committed boundary (or no known band width) the sweep returns without touching the ledger or the pipeline: absent geometry is not health, it is unknown |
|
|
323
|
+
| `[GAP-EVAC] ... no fill-less re-plan available on this path; teeth queued=N` | The stranding is real but this bot shape cannot run a fill-less rebalance (no `performSafeRebalance`/`updateOrdersOnChainBatch`); the cancel-only teeth own the repair |
|
|
324
|
+
| `[BOUNDARY] restore boundary=B sellStart=S gapSlots=G spreadCount=N\|? activeBuy=... activeSell=...` | Boundary restore telemetry. `gapSlots` is the resolved geometry (`_gapSlots ?? config-derived`) — never `0` for an unpublished band — and `spreadCount=?` means the grid has not been loaded/created yet, so no spread metric exists. A literal `gapSlots=0 sellStart=B+1` now always means a genuinely 0-wide band, not an initialization window |
|
|
316
325
|
| `[SPREAD-CORRECTION] <side> rail is OVERSUBSCRIBED: virtual reservation X exceeds chain free Y by Z — no correction can be funded until the rail is re-sized ...` | `availableFund` is `free − virtual`, so an oversubscribed rail reads 0 while the side still holds inventory. The watchdog escalates this on its short fund window |
|
|
317
326
|
| `[SPREAD-STALE] Spread out of tolerance for Nmin ... (outOfSpread=..., stall=...)` | Persistence warn with the last stall cause; the clock survives single in-tolerance readings and the terminal cases escalate early: `stall=last-fill-blocked` (sell window behind the last fill) on the 10-minute geometry window, a rail oversubscription on the 5-minute fund window |
|
|
318
327
|
| `[SPREAD-STALE] ... (sell window behind the last fill — re-centering)` | The `last-fill-blocked` geometry bind is escalating; placement cannot repair it, a re-center can |
|
|
319
328
|
| `[SPREAD-STALE] Still out of tolerance Nmin after re-centering on fill pivot P: the pivot is outside this generation's placeable side, so a re-center cannot clear it. A fill ... or pivot expiry restores the side; no further re-center will be requested for this pivot.` | Churn cap: a re-center does not move the pivot, so the same fill gets ONE re-center (`_lastGeometryResyncPivotKey`). Logged once per pivot; the same-side rail stays blocked until a fill or the read-time 24h pivot TTL, by design |
|
|
320
329
|
| `[BOUNDARY] Re-anchored from the last fill: SELL filled at slot 153 (0.447640); boundary 146 -> 149 so the fill sits outside its own window` | The window was behind the fill and a ±1 crawl cannot catch up; the fill now anchors the geometry. The anchor is the current fill batch's extremum for that side (max SELL / min BUY), not the last-processed pivot. Refusals stay silent (cold/off-ladder/ceiling-clamped/unsafe preconditions); the fill's own PARTIAL residual at the ANCHOR slot is allow-listed, so a partial fill does not deadlock the repair |
|
|
330
|
+
| `[BOUNDARY] Re-anchor accepted as a violation-reducing repair: boundary X -> Y strands fewer placed orders than the committed geometry (placed_order_in_band)` | The strict gate refused the candidate only because older GAP-EVAC strands are still in band; the move strands STRICTLY FEWER than the committed boundary, so it is accepted. Equal counts and structural refusals (crossed book/ceiling) stay closed. The rule lives in ONE helper (`boundaryMoveReducesStrands`) shared with the rail clamp — see `[COW] Boundary rail-derived` below. The promotion-side counterpart is the in-band absorption logged as `[SPREAD-CORRECTION] N gap slot(s) available for boundary promotion` |
|
|
331
|
+
| `[PLACEMENT] Force-releasing stale placement region held by <kind> for Ns (watchdog Ms); fills/rebalances must not stay parked` | The exclusive placement region outlived `TIMING.PLACEMENT_STALE_CLEAR_MS` (generous: above the longest observed reconcile), so the lease is force-released; the holder's later `release()` becomes a no-op (token guard). This watchdog is the ONE authority that tears a hung region down — when the region also still holds a stale broadcast refcount, it clears that too (`[PLACEMENT] Also clearing the stale broadcast region ...; one teardown for one hung region`) |
|
|
332
|
+
| `[COW] Placement lease was force-released while this batch was in flight (stale-region watchdog); aborting this batch instead of broadcasting without the region.` | The owner re-verifies its own lease with `isPlacementLeaseCurrent()` before broadcasting — the mirror of the nested drain's check. Aborting is the fail-closed answer: another path may own the region by now, and broadcasting anyway re-opens the duplicate window the teardown existed to avoid |
|
|
333
|
+
| `Startup reconcile: placement lease was force-released after planning (stale-region watchdog); discarding the plan instead of broadcasting without the region.` | The reconcile's own lease-liveness gate before Phase 2 (the mirror of `[COW] Placement lease was force-released ...`). Phase 1 touched only the master, so the plan is dropped with no chain effect; the next cycle re-reads the chain after re-acquiring the region |
|
|
334
|
+
| `[PLACEMENT] Watchdog skipped: region held by <kind> for Ns, but the pipeline is still making progress (in flight Ms)` | A bot-level batch/recovery counter younger than the placement bound proves the region is live (e.g. a long create-group reconcile), so nothing is torn down. Only a counter past the same bound is treated as part of the hung region |
|
|
335
|
+
| `[COW] <stage>: exclusive placement region unavailable (timeout/shutdown); aborting this batch instead of overlapping another placement path.` | Another chain-mutating path owns the region and the bounded wait expired. The batch is aborted (never broadcast unprotected) and retried on the next cycle |
|
|
336
|
+
| `Startup reconcile: exclusive placement region unavailable (timeout/shutdown); deferring to the next sync cycle.` | The reconcile could not serialize with a live placement path; it returns without mutating anything |
|
|
337
|
+
| `[DUST] Deferring dust cancels: exclusive placement region busy or shutting down` | Dust cancels mutate the chain, so they need the region. Deferral (not a bypass) is the contract; the next fill batch / maintenance tick retries |
|
|
338
|
+
| `[RESIDUAL] Deferring N residual cancel(s): exclusive placement region busy or shutting down` | Sub-dust residual cancels after a full fill are deferred to the next sync/reconcile instead of racing a live batch |
|
|
339
|
+
| `[MAINT] Deferring price-correction drain: exclusive placement region busy or shutting down` / `[FILL-QUEUE] Deferring price-correction drain: ...` / `[COW] Draining N pending correction(s) before batch` | The correction drain runs inside the region (nested callers pass the holder's lease, verified with `isPlacementLeaseCurrent`). A deferred drain keeps its queued entries for the next tick; the fill consumer and the maintenance tick report the same deferral under their own tags |
|
|
340
|
+
| `[BROADCAST] Stale-flag watchdog skipped: placement region still held by <kind> for Ns` | The refcount watchdog refuses to clear a broadcast region a live placement lease still owns — the mirror rule of the placement watchdog's pipeline-progress check |
|
|
341
|
+
| `[REBUILD] Structural rebuild started (<reason>); fill-driven rebalances deferred` | A trigger-file/startup rebuild owns placement and update-first repair; fill-driven COW rebalances defer instead of re-planning against the order-id-less master |
|
|
342
|
+
| `[SAFE-REBALANCE] Deferred: placement region held by <kind>; rebalance retries after it ends` | A fill-driven rebalance found the region held (reconcile/drain/dust/cancel/swap). The owed fill crawls stay recorded and the region-end hook reschedules the no-fill rebalance |
|
|
343
|
+
| `[FILL-DEDUP] Fill <key>: N/M base units already absorbed by sync pass 1; the transition will not shrink them again` | The open-orders pass resized the slot from the same post-fill snapshot. The explicit applied amount (never the legacy boolean) drives the remainder, so the trade's pays/receives are still booked while the size is released exactly once |
|
|
344
|
+
| `[COW] Pending-broadcast entry <fp> is Ns old but no sync has completed since it was recorded; keeping it (fail-closed) until a caught-up read` / `[COW] Dropped expired pending-broadcast entry ...` | The single pending-broadcast liveness authority (`getLivePendingBroadcasts`): TTL, or TTL + a successful sync after the record, or the 2× hard cap. Every reader (COW guard, reconcile CREATE, reconcile surplus sweep, crossing candidates) obeys it |
|
|
321
345
|
| `[FILL-PIVOT] pivot=... buy=... sell=... n=N src=full/direct` (+ `edge-skipped=K` when present) | One line per fill batch: the LAST-FILL-GUARD pivot after the batch. `edge-skipped=K` means K edge-pinned insurance fills were ignored — they never arm the pivot, so they can never drive the re-anchor |
|
|
322
346
|
| `[FILL-PIVOT] K edge-pinned fill(s) ignored — the guard pivot and the boundary anchor stay on the last window trade` | Edge-only batch: nothing armed, which is the point |
|
|
323
347
|
| `[LAST-FILL-GUARD] Re-armed on the new generation: 0.447640(SELL) from the last real fill (age Ns) — the guard survives a rebuild by design` | A grid rebuild dropped the generation-bound pivot and re-armed it explicitly from the bot-scoped last-market-fill row (`rearmLastFillPivotFromMarketFill`). Provenance stays `fill`; the timestamp is the original fill's, taken from the SAME row that supplied the price (a book-seeded live pivot never lends its clock) |
|