@botbuddy/cli 1.113.0 → 1.115.0

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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.115.0
4
+
5
+ - BOT-3478: a preempted lease says why. The receipt from `bb stack run` and `bb stack touch` now carries `preempt_reason` (`idle`, `over_limit`, `operator` or `host_drain`). When the agent held more stacks than its tenant's stacks-per-agent limit while another lease waited, the receipt also names `stacks_per_agent_limit`, `kept_lease_id` and `waiting_lease_id`, and the error says the stack was reclaimed for the limit, not for idleness. A child that fails before the next heartbeat sees the preemption (its database went away) still ends with the typed receipt: after a failed child the run reads the lease once. The exit code is unchanged (6). Needs MCP 2.157.0.
6
+
7
+ ## 1.114.0
8
+
9
+ - BOT-3483: `bb wait` rides out a short lock wait when it registers. Registration fences the agent's session row; while another transaction held a row that references the session (the hourly sensor job linking usage, an ingest batch) the database cancelled it at the statement timeout and the wait failed closed with `register_failed`. The fence now takes `FOR NO KEY UPDATE`, which those writers no longer block, and still refuses a stale session-token generation. When the relay still reports a lock wait (`wait_registration_contended`, SQLSTATE 57014 or 55P03; the relay sends it from this release on), the CLI retries the registration up to 3 times (after 2 s, 6 s and 12 s, never past the wait's own deadline) on the same logical wait id, so it never registers twice, then fails closed with exit 5 and a `wait_registration_contended` receipt carrying the SQLSTATE and the number of attempts.
10
+
3
11
  ## 1.113.0
4
12
 
5
13
  - BOT-3496: the fleet host daemon reports each running test child's memory so the host's memory admission ledger counts the child once instead of twice (its unit's memory was in the host's baseline as well as in its reservation). The runner learns each live unit's cgroup from the `systemctl show` it already makes. When the heartbeat builds a resource sample, it reads the child's working set at that instant (`memory.current` − `inactive_file` from `/sys/fs/cgroup/<ControlGroup>`, the measure containers already use), and the next claims carry it as `child_memory` with that sample's `observed_at`. A child with no readable cgroup sends nothing, so the ledger keeps its fail-closed count. Needs MCP 2.153.0.
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.113.0",
3
- "source_commit": "4d0931b1467b33ed4d8f2f90dce2400dde11147d",
4
- "source_sha256": "9bc939e955b79b62178d34963c2b5370e5a78d671b1c04daf220a5d7d7773095",
2
+ "release_version": "1.115.0",
3
+ "source_commit": "0496a70466cc80aec34241b344416497d3a6fb9b",
4
+ "source_sha256": "2e08f76a178677b80a21fdf689b62f7bb1e74eed776a79b347c05658bc6d73ed",
5
5
  "target": "darwin-arm64",
6
- "sha256": "24a977fdb1056ac49539a8fe732e0566add0e2152b202d18944b11a6a9f86591"
6
+ "sha256": "9ecbe48d2541c2c4f7d8c53a534f90d800de6a262eee2d31f78b24a1feeaa85c"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.113.0",
3
- "source_commit": "4d0931b1467b33ed4d8f2f90dce2400dde11147d",
4
- "source_sha256": "9bc939e955b79b62178d34963c2b5370e5a78d671b1c04daf220a5d7d7773095",
2
+ "release_version": "1.115.0",
3
+ "source_commit": "0496a70466cc80aec34241b344416497d3a6fb9b",
4
+ "source_sha256": "2e08f76a178677b80a21fdf689b62f7bb1e74eed776a79b347c05658bc6d73ed",
5
5
  "target": "linux-x64",
6
- "sha256": "5c5ae7577c8c5151de741868af68868a588e1738480540db1614fd4ffc59ee2c"
6
+ "sha256": "39fe2b3af2de0f90c8f0caf9a2210fb724c40dd66a3d58f3f49ade6f2abd7685"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.113.0",
4
- "source_commit": "4d0931b1467b33ed4d8f2f90dce2400dde11147d",
5
- "source_sha256": "9bc939e955b79b62178d34963c2b5370e5a78d671b1c04daf220a5d7d7773095",
3
+ "release_version": "1.115.0",
4
+ "source_commit": "0496a70466cc80aec34241b344416497d3a6fb9b",
5
+ "source_sha256": "2e08f76a178677b80a21fdf689b62f7bb1e74eed776a79b347c05658bc6d73ed",
6
6
  "targets": {
7
7
  "darwin-arm64": {
8
8
  "goos": "darwin",
9
9
  "goarch": "arm64",
10
10
  "binary": "daemon/bin/darwin-arm64/botbuddy-daemon",
11
- "sha256": "24a977fdb1056ac49539a8fe732e0566add0e2152b202d18944b11a6a9f86591",
11
+ "sha256": "9ecbe48d2541c2c4f7d8c53a534f90d800de6a262eee2d31f78b24a1feeaa85c",
12
12
  "mode": "0755"
13
13
  },
14
14
  "linux-x64": {
15
15
  "goos": "linux",
16
16
  "goarch": "amd64",
17
17
  "binary": "daemon/bin/linux-x64/botbuddy-daemon",
18
- "sha256": "5c5ae7577c8c5151de741868af68868a588e1738480540db1614fd4ffc59ee2c",
18
+ "sha256": "39fe2b3af2de0f90c8f0caf9a2210fb724c40dd66a3d58f3f49ade6f2abd7685",
19
19
  "mode": "0755"
20
20
  }
21
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botbuddy/cli",
3
- "version": "1.113.0",
3
+ "version": "1.115.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
package/src/stack.mjs CHANGED
@@ -463,6 +463,9 @@ ${bold("IDLE LEASES")} (BOT-1803)
463
463
  usage {client_connections, last_client_query_at} (docker exec … psql pg_stat_activity, 5 s cap;
464
464
  no usage at all when it cannot be read). A lease preempted under a running child ends it:
465
465
  exit 6, code LEASE_PREEMPTED, volumes_kept true; \`stack touch\` exits 6 with outcome "preempted".
466
+ Both carry preempt_reason (idle | over_limit | operator | host_drain). over_limit (BOT-3478):
467
+ the agent held more stacks than its tenant's stacks-per-agent limit while another lease waited;
468
+ the receipt adds stacks_per_agent_limit, kept_lease_id and waiting_lease_id.
466
469
 
467
470
  ${bold("REMOTE LEASES")} (BOT-2142, stack run)
468
471
  The receipt carries execution_mode (local|remote), execution_host_key, requester_host,
@@ -3741,6 +3744,28 @@ export function isPreemptedAnswer(d) {
3741
3744
  return d?.code === "LEASE_PREEMPTED" || (d?.success === false && d?.reap_reason === "preempted");
3742
3745
  }
3743
3746
 
3747
+ /**
3748
+ * BOT-3478 (AC-7): the typed preemption fields a LEASE_PREEMPTED answer carries — why
3749
+ * (`over_limit`, `idle`, `operator`, `host_drain`) and, for `over_limit`, the tenant's
3750
+ * stacks-per-agent limit, the lease the agent kept and the lease that was waiting. Absent
3751
+ * fields (an older server) are left out.
3752
+ */
3753
+ export function preemptionFields(d) {
3754
+ const out = {};
3755
+ if (typeof d?.preempt_reason === "string") out.preempt_reason = d.preempt_reason;
3756
+ if (Number.isInteger(d?.stacks_per_agent_limit)) out.stacks_per_agent_limit = d.stacks_per_agent_limit;
3757
+ for (const key of ["kept_lease_id", "waiting_lease_id"]) if (typeof d?.[key] === "string") out[key] = d[key];
3758
+ return out;
3759
+ }
3760
+
3761
+ /** BOT-3478: the over-limit sentence of a preempted receipt, or null for any other reason. */
3762
+ function overLimitPreemptionError(leaseId, fields, ending) {
3763
+ if (fields.preempt_reason !== "over_limit") return null;
3764
+ return `lease ${leaseId} was preempted because its agent held more stacks than the tenant's stacks-per-agent limit ` +
3765
+ `(${fields.stacks_per_agent_limit ?? "?"}) while lease ${fields.waiting_lease_id ?? "?"} waited; the agent kept lease ` +
3766
+ `${fields.kept_lease_id ?? "?"}. ${ending}`;
3767
+ }
3768
+
3744
3769
  /**
3745
3770
  * BOT-1803: `stack touch` bumps the idle clock and, for a co-located lease, reports the
3746
3771
  * measured client use (AC-12). Reading the lease first (for its project + Docker target)
@@ -3758,10 +3783,12 @@ export async function cmdTouch(leaseId, opts, { rpc = retryingStackCall(), emitR
3758
3783
  const r = await rpc.call("touch_stack_lease", { lease_id: leaseId, ...(usage ? { usage } : {}) });
3759
3784
  if (!r.ok) return emitResult(buildReceipt({ command: "touch", outcome: "error", lease_id: leaseId, error: r.error }), opts, r.auth ? EXIT.AUTH : EXIT.BACKEND);
3760
3785
  if (isPreemptedAnswer(r.data)) {
3786
+ const preemption = preemptionFields(r.data);
3761
3787
  return emitResult(buildReceipt({
3762
3788
  command: "touch", outcome: "preempted", code: "LEASE_PREEMPTED", lease_id: leaseId, volumes_kept: true,
3763
- state: r.data.state ?? null, reap_reason: r.data.reap_reason ?? "preempted",
3764
- error: "the lease was preempted (its idle capacity went to a queued lease); the stack was stopped with its volumes kept — request a new lease",
3789
+ state: r.data.state ?? null, reap_reason: r.data.reap_reason ?? "preempted", ...preemption,
3790
+ error: overLimitPreemptionError(leaseId, preemption, "The stack was stopped with its volumes kept — request a new lease when capacity is free.")
3791
+ ?? "the lease was preempted (its idle capacity went to a queued lease); the stack was stopped with its volumes kept — request a new lease",
3765
3792
  }), opts, EXIT.LEASE_FAILED);
3766
3793
  }
3767
3794
  if (!r.data.success) return emitResult(buildReceipt({ command: "touch", outcome: "error", lease_id: leaseId, code: r.data.code, error: r.data.code }), opts, EXIT.BACKEND);
@@ -5936,7 +5963,7 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5936
5963
  if (touched?.ok && isPreemptedAnswer(touched.data)) {
5937
5964
  // BOT-1803 (AC-11): the control plane reclaimed this lease's capacity. Stop the
5938
5965
  // child and end typed — never the generic lost-lease wording.
5939
- preempted = { state: touched.data.state ?? "reaping", reap_reason: touched.data.reap_reason ?? "preempted" };
5966
+ preempted = { state: touched.data.state ?? "reaping", reap_reason: touched.data.reap_reason ?? "preempted", fields: preemptionFields(touched.data) };
5940
5967
  fencing = true;
5941
5968
  stopChild("SIGTERM", EXIT.LEASE_FAILED);
5942
5969
  return;
@@ -5992,6 +6019,21 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5992
6019
  if (retention) { clock.clearInterval(retention); retention = null; }
5993
6020
  if (hardTimer) clock.clearTimeout(hardTimer);
5994
6021
  await closeTunnel();
6022
+ // BOT-3478 (Codex #1913): an actively used stack preempted over its agent's limit can make the
6023
+ // child fail (connection lost) before the next heartbeat sees it. Ask once, after a failed
6024
+ // child only, so the run still ends with the typed LEASE_PREEMPTED receipt.
6025
+ if (!preempted && !receivedSignal && !fencing && childResult?.code !== 0) {
6026
+ try {
6027
+ const got = await api.get(leaseId);
6028
+ // The Helper may already have finalized the reap (`reaped`) by the time we ask.
6029
+ if (got?.ok && (got.data?.state === "reaping" || got.data?.state === "reaped") && got.data?.reap_reason === "preempted") {
6030
+ const typed = await api.touch(leaseId);
6031
+ const answer = typed?.ok && isPreemptedAnswer(typed.data) ? typed.data : got.data;
6032
+ preempted = { state: answer.state ?? "reaping", reap_reason: "preempted", fields: preemptionFields(answer) };
6033
+ fencing = true;
6034
+ }
6035
+ } catch { /* unreadable: the child's own exit stands */ }
6036
+ }
5995
6037
  // BOT-1803: a run that ended on its own (the child exited, success or not) leaves its
5996
6038
  // lease IDLE for the next run on this slot — no reap wait. `--reap`, a signal, the
5997
6039
  // hard TTL, a fenced/preempted heartbeat and a lost tunnel keep the eager signed reap.
@@ -6027,7 +6069,9 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
6027
6069
  if (preempted && !receivedSignal) {
6028
6070
  return {
6029
6071
  exitCode: EXIT.LEASE_FAILED, outcome: "failed", code: "LEASE_PREEMPTED", volumesKept: true, leaseId, childExitCode: childResult.code, cleanup, fenced: true,
6030
- error: `lease ${leaseId} was preempted while the child ran (its capacity went to a queued lease); the child was stopped and the stack ` +
6072
+ preemption: preempted.fields ?? {},
6073
+ error: overLimitPreemptionError(leaseId, preempted.fields ?? {}, "The child was stopped and the stack stopped with its volumes kept — re-run the batch when capacity is free, or on the stack you kept.")
6074
+ ?? `lease ${leaseId} was preempted while the child ran (its capacity went to a queued lease); the child was stopped and the stack ` +
6031
6075
  "stopped with its volumes kept — re-run the batch to get a new lease",
6032
6076
  ...(parkIncident ? { incident: parkIncident } : {}),
6033
6077
  };
@@ -6139,6 +6183,8 @@ export function runReceiptFields(result) {
6139
6183
  release: `bb stack done ${result.leaseId} --reap`,
6140
6184
  } } : {}),
6141
6185
  ...(result.volumesKept ? { volumes_kept: true } : {}),
6186
+ // BOT-3478 (AC-7): why the lease was preempted, and for over_limit the limit and both leases.
6187
+ ...(result.preemption ?? {}),
6142
6188
  ...(result.idleLease?.reused ? { reused: result.idleLease.reused } : {}),
6143
6189
  ...(result.idleLease?.reprovisioned ? { reprovisioned: result.idleLease.reprovisioned } : {}),
6144
6190
  ...(result.idleLease?.previousLeaseId ? { previous_lease_id: result.idleLease.previousLeaseId } : {}),
package/src/wait.mjs CHANGED
@@ -790,6 +790,13 @@ async function registerWait(opts, conditions, deadlineIso) {
790
790
  // BOT-2855: keep the relay's typed reason for the caller and the receipt.
791
791
  err.errorCode = typedCode || "register_failed";
792
792
  err.httpStatus = res.status;
793
+ // BOT-3483: a lock wait on the session fence is transient — retry it.
794
+ const sqlstate = typeof body.sqlstate === "string" ? body.sqlstate : null;
795
+ if (typedCode === "wait_registration_contended" || WAIT_REGISTER_CONTENTION_SQLSTATES.includes(sqlstate)) {
796
+ err.contended = true;
797
+ err.sqlstate = sqlstate;
798
+ err.errorCode = "wait_registration_contended";
799
+ }
793
800
  if (body.error === "initial_eval_failed") {
794
801
  err.initialEval = true;
795
802
  err.detail = body.detail || "initial evaluation failed";
@@ -1207,6 +1214,25 @@ export const DEFAULT_SSE_IDLE_TIMEOUT_MS = 70_000;
1207
1214
  // to spare (asserted in bot2360-abandoned-wait.test.mjs against the registered cron job).
1208
1215
  export const WAIT_CONNECT_TIMEOUT_MS = 30_000;
1209
1216
 
1217
+ // BOT-3483: register_wait_session_fenced fences the agent's `sessions` row, so a
1218
+ // registration can queue behind another transaction's row lock and be cancelled by
1219
+ // the statement timeout (57014) or refused by lock_timeout (55P03). The relay types
1220
+ // that as `wait_registration_contended`; retry it this many times with this backoff
1221
+ // (total 20 s, inside a wait's own deadline) on the SAME logical wait id, then fail
1222
+ // closed with the typed code. BOTBUDDY_WAIT_REGISTER_BACKOFF_MS="a,b,c" overrides
1223
+ // the delays (tests); an unparsable override keeps the defaults.
1224
+ export const WAIT_REGISTER_CONTENTION_BACKOFF_MS = Object.freeze([2_000, 6_000, 12_000]);
1225
+ export const WAIT_REGISTER_CONTENTION_SQLSTATES = Object.freeze(["57014", "55P03"]);
1226
+
1227
+ function waitRegisterContentionBackoffMs() {
1228
+ const raw = process.env.BOTBUDDY_WAIT_REGISTER_BACKOFF_MS;
1229
+ if (!raw) return WAIT_REGISTER_CONTENTION_BACKOFF_MS;
1230
+ const parsed = raw.split(",").map((v) => Number(v.trim()));
1231
+ return parsed.length === WAIT_REGISTER_CONTENTION_BACKOFF_MS.length && parsed.every((ms) => Number.isFinite(ms) && ms >= 0)
1232
+ ? parsed
1233
+ : WAIT_REGISTER_CONTENTION_BACKOFF_MS;
1234
+ }
1235
+
1210
1236
  function waitConnectTimeoutMs() {
1211
1237
  const raw = Number(process.env.BOTBUDDY_WAIT_CONNECT_TIMEOUT_MS);
1212
1238
  return Number.isFinite(raw) && raw > 0 ? raw : WAIT_CONNECT_TIMEOUT_MS;
@@ -2312,6 +2338,9 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2312
2338
  // is idempotent on the checkpoint's logical_wait_id (BOT-1656), so the
2313
2339
  // reservation above is not repeated.
2314
2340
  let attempts = 0;
2341
+ // BOT-3483: retries of a contended registration (same opts.localWaitId each time).
2342
+ const contentionBackoff = waitRegisterContentionBackoffMs();
2343
+ let contentionRetries = 0;
2315
2344
  let reg;
2316
2345
  for (;;) {
2317
2346
  try {
@@ -2319,6 +2348,17 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2319
2348
  reg = await registerWait(opts, serverConditions(conditions), new Date(deadlineMs).toISOString());
2320
2349
  break;
2321
2350
  } catch (error) {
2351
+ if (error && error.contended) {
2352
+ const delay = contentionBackoff[contentionRetries];
2353
+ // Never back off past the wait's own deadline.
2354
+ if (delay !== undefined && Date.now() + delay < deadlineMs) {
2355
+ contentionRetries += 1;
2356
+ await new Promise((resolve) => setTimeout(resolve, delay));
2357
+ continue;
2358
+ }
2359
+ error.attempts = contentionRetries + 1;
2360
+ throw error;
2361
+ }
2322
2362
  if (!shouldRenewCachedSession(error, opts.credentialSource, attempts)) throw error;
2323
2363
  attempts += 1;
2324
2364
  await clearAgentState(process.cwd());
@@ -2638,6 +2678,26 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2638
2678
  process.exit(EXIT.INTERNAL);
2639
2679
  }
2640
2680
  if (err instanceof WaitCheckpointError) return emitSavedWaitError(err);
2681
+ if (err && err.contended) {
2682
+ // BOT-3483: still contended after every retry. Fail closed (never arm
2683
+ // untracked) with the typed code; re-running `bb wait` is the next step.
2684
+ process.stderr.write(`bb-wait: wait-session registration failed (wait_registration_contended) after ${err.attempts ?? 1} attempts — the session row stayed locked by another transaction (SQLSTATE ${err.sqlstate ?? "unknown"}); failing closed, not arming untracked. Re-run the same bb wait: ${err.message}\n`);
2685
+ await emitReceipt(withPrincipalReceipt(
2686
+ {
2687
+ schema_version: 1,
2688
+ outcome: "error",
2689
+ error: "wait_registration_contended",
2690
+ error_code: "wait_registration_contended",
2691
+ sqlstate: err.sqlstate ?? null,
2692
+ attempts: err.attempts ?? 1,
2693
+ detail: String(err.message),
2694
+ ...(Number.isInteger(err.httpStatus) ? { http_status: err.httpStatus } : {}),
2695
+ },
2696
+ null,
2697
+ { sessionTenant: sessionTenant ?? null, agentId: null },
2698
+ ));
2699
+ process.exit(EXIT.BACKEND);
2700
+ }
2641
2701
  if (hasClaim) {
2642
2702
  process.stderr.write(`bb-wait: claim=true wait-session registration failed (failing closed, not arming untracked): ${err && err.message || err}\n`);
2643
2703
  await emitReceipt({ schema_version: 1, outcome: "error", error: "claim_registration_failed" });