Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(sniper): release abandoned closing locks and bound the reconcile park

nirholas1bf340d78b9e
diff --git a/tests/sniper-reconcile-giveup.test.js b/tests/sniper-reconcile-giveup.test.js
new file mode 100644
index 000000000..a7706ab00
--- /dev/null
+++ b/tests/sniper-reconcile-giveup.test.js
@@ -0,0 +1,55 @@
+// The unreconcilable-position give-up clock.
+//
+// A position parks as `reconcile_pending` when its bag is provably gone from the
+// wallet but the tx that emptied it cannot be found. That park was unbounded in
+// production: five positions wedged at once (one for 40+ hours), each holding one
+// of its arm's max_concurrent_positions slots, which is what stopped the fleet
+// from taking new trades. These tests pin the bound.
+
+import { describe, it, expect } from 'vitest';
+import { shouldGiveUpReconcile } from '../workers/agent-sniper/exit-logic.js';
+
+const SIX_HOURS = 6 * 60 * 60 * 1000;
+const NOW = Date.UTC(2026, 6, 27, 17, 0, 0);
+
+describe('shouldGiveUpReconcile', () => {
+ it('never fires for a position that is not parked', () => {
+ expect(shouldGiveUpReconcile(null, SIX_HOURS, NOW)).toBe(false);
+ expect(shouldGiveUpReconcile(undefined, SIX_HOURS, NOW)).toBe(false);
+ });
+
+ it('holds while the park is inside the window (RPC history lag is seconds to minutes)', () => {
+ const oneMinuteAgo = new Date(NOW - 60_000).toISOString();
+ expect(shouldGiveUpReconcile(oneMinuteAgo, SIX_HOURS, NOW)).toBe(false);
+
+ const almost = new Date(NOW - (SIX_HOURS - 1)).toISOString();
+ expect(shouldGiveUpReconcile(almost, SIX_HOURS, NOW)).toBe(false);
+ });
+
+ it('fires exactly at the boundary and beyond', () => {
+ expect(shouldGiveUpReconcile(new Date(NOW - SIX_HOURS).toISOString(), SIX_HOURS, NOW)).toBe(true);
+
+ // The real production wedge: parked 40 hours, slot held the whole time.
+ const fortyHours = new Date(NOW - 40 * 60 * 60 * 1000).toISOString();
+ expect(shouldGiveUpReconcile(fortyHours, SIX_HOURS, NOW)).toBe(true);
+ });
+
+ it('accepts a Date as well as an ISO string (the DB driver returns Date)', () => {
+ expect(shouldGiveUpReconcile(new Date(NOW - SIX_HOURS), SIX_HOURS, NOW)).toBe(true);
+ expect(shouldGiveUpReconcile(new Date(NOW - 1000), SIX_HOURS, NOW)).toBe(false);
+ });
+
+ it('treats an unparseable timestamp as "do not give up" rather than closing a live position', () => {
+ expect(shouldGiveUpReconcile('not-a-date', SIX_HOURS, NOW)).toBe(false);
+ });
+
+ it('is inert when no window is configured, so a misconfig cannot mass-close positions', () => {
+ const old = new Date(NOW - 40 * 60 * 60 * 1000).toISOString();
+ expect(shouldGiveUpReconcile(old, 0, NOW)).toBe(false);
+ expect(shouldGiveUpReconcile(old, null, NOW)).toBe(false);
+ });
+
+ it('does not fire on a future timestamp (clock skew must not close a fresh park)', () => {
+ expect(shouldGiveUpReconcile(new Date(NOW + 60_000).toISOString(), SIX_HOURS, NOW)).toBe(false);
+ });
+});
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index b9e207b7b..2012533a5 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -21,6 +21,7 @@ import {
checkDailyLoss, recordCustodyEvent,
SOL_FEE_HEADROOM_LAMPORTS,
} from '../../api/_lib/agent-trade-guards.js';
+import { shouldGiveUpReconcile } from './exit-logic.js';
import { buildAmmSellInstructions, quoteAmmBuy, buildAmmBuyInstructions } from './amm-exit.js';
import { getWalletBaseBalance, reconcileVanishedBag } from './reconcile.js';
import { assessTradeSafety, recordFirewallDecision, criticalFirewallReason } from '../../api/_lib/trade-firewall.js';
@@ -590,10 +591,7 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover
// as live risk and held a concurrency slot. The time bound: the park
// itself had none, so a bag whose emptying tx could never be found
// re-parked every sweep forever and wedged that slot permanently.
- const pendingSince = position.reconcile_pending_since
- ? new Date(position.reconcile_pending_since).getTime()
- : null;
- if (pendingSince != null && Date.now() - pendingSince >= RECONCILE_GIVE_UP_MS) {
+ if (shouldGiveUpReconcile(position.reconcile_pending_since, RECONCILE_GIVE_UP_MS)) {
// The bag is provably gone but its proceeds are unknowable from
// chain history. Book it closed so the slot frees, and leave
// realized P&L NULL rather than inventing a number — every P&L
@@ -606,7 +604,7 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover
WHERE id = ${position.id} AND status <> 'closed'
`;
log.warn('reconcile gave up; bag gone, proceeds unknown', {
- ...tag, pending_hours: ((Date.now() - pendingSince) / 3_600_000).toFixed(1),
+ ...tag, pending_since: position.reconcile_pending_since,
});
return { status: 'closed', reason: 'reconcile_unresolved' };
}
@@ -730,6 +728,7 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover
moonbag_last_value_lamports = ${keptValueEst},
moonbag_opened_at = ${retainsMoonbag ? new Date().toISOString() : null},
error = ${null},
+ reconcile_pending_since = NULL,
closed_at = now()
WHERE id = ${position.id}
`;
diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.js
index a2749339d..30f07da30 100644
--- a/workers/agent-sniper/exit-logic.js
+++ b/workers/agent-sniper/exit-logic.js
@@ -257,3 +257,29 @@ export function decideLadderedExit(pos, value, peak, now = Date.now(), sentiment
if (!(sellFraction > 0)) return null; // nothing worth selling; let the bag ride
return { reason, sellFraction, keepsMoonbag: true };
}
+
+/**
+ * Has an unreconcilable position waited long enough to give up on?
+ *
+ * A position parks as `reconcile_pending` when its bag is provably gone from the
+ * wallet but the transaction that emptied it cannot be found in chain history.
+ * That park used to be unbounded, so a bag whose emptying tx never surfaced
+ * re-parked every sweep forever — and because countOpenPositions() counts it,
+ * the position held one of its arm's concurrency slots permanently. Observed in
+ * production: five positions wedged at once, one for over 40 hours, with the
+ * fleet unable to take new trades.
+ *
+ * Giving up books the position closed with UNKNOWN proceeds (realized P&L left
+ * null, never invented) purely to release the slot. Returns false when nothing
+ * is pending, so a healthy position can never trip it.
+ *
+ * @param {string|Date|null} pendingSince when the position first parked
+ * @param {number} giveUpMs how long a park may last
+ * @param {number} [now] epoch ms
+ */
+export function shouldGiveUpReconcile(pendingSince, giveUpMs, now = Date.now()) {
+ if (pendingSince == null || !(giveUpMs > 0)) return false;
+ const since = pendingSince instanceof Date ? pendingSince.getTime() : new Date(pendingSince).getTime();
+ if (!Number.isFinite(since)) return false;
+ return now - since >= giveUpMs;
+}
diff --git a/workers/agent-sniper/strategy-store.js b/workers/agent-sniper/strategy-store.js
index f27980238..10f76784a 100644
--- a/workers/agent-sniper/strategy-store.js
+++ b/workers/agent-sniper/strategy-store.js
@@ -111,14 +111,34 @@ export async function getRealizedNetLamports(agentId, network, sinceHours = 24)
return BigInt(r?.net ?? '0');
}
+// A sell marks its position 'closing' before broadcasting and clears the mark
+// when it settles, so 'closing' is a lock held for seconds. A row still holding
+// it much later can only be an abandoned attempt (worker restart or crash
+// mid-sell). Because 'closing' rows are invisible to the sweep below but still
+// counted by countOpenPositions(), an abandoned one silently costs its arm a
+// concurrency slot forever — one sat that way for 34 hours in production.
+const CLOSING_LOCK_STALE_MS = 10 * 60 * 1000;
+
/**
* Open positions across all agents — the position-loop work set.
*
* Graduated positions (error LIKE 'graduated%') are INCLUDED: the sweep
* re-quotes them off the AMM pool and exits them there, so they no longer park
* indefinitely. The sweep reads `error` to pick the venue (AMM vs curve).
+ *
+ * Abandoned 'closing' locks are released back to 'open' first (see above), so a
+ * crash mid-sell costs one sweep of delay instead of the slot. This is safe
+ * under the worker's single-instance assumption: a genuinely in-flight sell
+ * finishes in seconds, far inside the stale window.
*/
export async function getOpenPositions(network) {
+ await sql`
+ UPDATE agent_sniper_positions
+ SET status = 'open'
+ WHERE network = ${network}
+ AND status = 'closing'
+ AND coalesce(last_quoted_at, opened_at) < now() - (${CLOSING_LOCK_STALE_MS} || ' milliseconds')::interval
+ `;
return sql`
SELECT p.*, s.take_profit_pct, s.stop_loss_pct, s.trailing_stop_pct,
s.max_hold_seconds, s.slippage_bps, s.user_id AS strat_user_id,