oc-codex-multi-auth icon indicating copy to clipboard operation
oc-codex-multi-auth copied to clipboard

[BUG] Constant erroring Lock file in use

Open AceRothstein71 opened this issue 3 months ago • 1 comments

And afterwards it completely stalls the sub tasks

Also ton's of sub agents don't spawn correctly but this is probably an opencode issue.

latest version of opencode and your plugin.

Image

AceRothstein71 avatar Aug 09 '26 15:08 AceRothstein71

Coding Plan

Summary

root cause: the only hard cross-process lock, proper-lockfile in lib/config.ts:180, rejects with a raw ELOCKED under parallel-subagent codex-pool contention and propagates unhandled through lib/tools/codex-pool.ts:250, aborting sub tasks.

primary fix: add a lock-free no-op/dryRun fast path to cut contention, wrap lock() to classify ELOCKED into a defined non-fatal outcome with bounded extra patience, and catch it in the codex-pool tool to return a retryable message instead of crashing.

recommendation on the contention signal: prefer a typed ConfigLockContentionError over a contended result field, because sibling tools already branch on caught errors and this keeps ModelAccountPoolMutationResult a pure success shape — pick one and keep it consistent across lib/config.ts and lib/tools/codex-pool.ts.

supporting: throttle the advisory Multi-worktree collision detected warning in lib/storage/load-save.ts, document both signals in docs/troubleshooting.md, and add regression tests for exhausted-lock contention and the no-op fast path (real multi-process contention remains untested and is flagged).

Design Choices
Design Choice 1: which lock produces the user-visible "lock file in use" string?

Options Considered:

  1. config lock in lib/config.ts:180 (proper-lockfile → ELOCKED "Lock file is already being held"). unhandled, propagates through codex-pool to the host.
  2. storage atomic-write EBUSY → formatStorageErrorHint "File is locked at …" in lib/storage/errors.ts:30. this path is swallowed by saveToDiskDebounced (lib/accounts/persistence.ts) as log.warn and never reaches the agent.

Chosen Option: 1

Rationale: two locks exist and only one can reach the agent as an unhandled error. the config lock is the only lock whose error propagates unhandled to the agent, and its wording ("Lock file …") matches the ticket; the storage lock option is already non-fatal by design.

💡 User Tips

Regenerate the plan with different choices with @coderabbitai <feedback>.

Implementation Steps

Phase 1: harden config-lock acquisition and remove needless contention

this phase attacks the root cause. under many parallel subagents each calling codex-pool, N processes race on one OS lock (lib/config.ts:180), the retry budget (20 retries, ~200ms cap, a few seconds total) gets exhausted, and lock() rejects with ELOCKED. the goal is fewer processes ever needing the lock, and no raw rejection when they do.

Task 1: add a lock-free no-op fast path to `updateModelAccountPool`

skip the OS lock entirely when the mutation changes nothing.

  • update lib/config.ts updateModelAccountPool (172-208) to read current config first with the existing lock-free reader (loadPluginConfig, plain readFileSync) before acquiring the lock.
  • compute the prospective changed outcome from that read. if options.dryRun === true, or the mutation would produce no change, return the ModelAccountPoolMutationResult immediately without calling lock().
  • rationale: many parallel subagents repeatedly setting the same pool (or previewing) currently all contend on the file lock for a write that never happens. this collapses that contention to near zero for the common repeated/idempotent case.
  • concurrency note: this is a fast-path optimization only. the authoritative read-modify-write still happens under the lock, so a racing writer between the pre-read and the lock cannot cause a lost update — the locked performModelAccountPoolMutation re-reads and recomputes.
Task 2: classify and handle `ELOCKED` around `lock()`

stop leaking raw proper-lockfile errors and give contention a defined outcome.

  • wrap the await lock(CONFIG_PATH, …) call in lib/config.ts:180 in try/catch.
  • on a caught error with err.code === "ELOCKED", do not propagate the raw error. instead throw a typed, plugin-owned error (add a small ConfigLockContentionError in lib/config.ts or lib/errors.ts) that carries CONFIG_PATH and a stable code, or return a discriminated result field on ModelAccountPoolMutationResult (e.g. contended: true) — pick one and keep it consistent (see approach summary).
  • for any non-ELOCKED error, rethrow unchanged so genuine faults (permission, disk) still surface.
  • increase the acquisition patience modestly for real contention: raise proper-lockfile retries and/or maxTimeout so short bursts of parallel subagents settle instead of failing fast. keep it bounded (a few seconds worst case) so it can never hang. reuse exponentialBackoff/addJitter (lib/rotation.ts:462-484) only if an application-level retry loop is added; otherwise tune the built-in retries object.
  • windows edge case: performModelAccountPoolMutation writes the config via a temp file + renameWithWindowsRetry. keep that path intact; the new try/catch must sit around lock(), not around the rename, so windows EPERM/EBUSY rename retries are unaffected.
  • do not touch the queue-reset lines (modelAccountPoolMutationQueue = pending.then(() => undefined, () => undefined)); they already self-heal and prevent in-process wedging.
🤖 Prompt for AI agents
implement the root-cause fix for the config lock contention in `lib/config.ts`.
goal: reduce how often the OS lock is ever needed, and never leak a raw
`ELOCKED` rejection.

first, add a lock-free fast path to `updateModelAccountPool` (lines 172-208):
read the current config with the existing lock-free reader (`loadPluginConfig`,
plain `readFileSync`) before calling `lock()`. compute the prospective `changed`
outcome from that read. if `options.dryRun === true`, or the mutation would
produce no change, return the `ModelAccountPoolMutationResult` immediately
without ever acquiring the lock. note this is a fast-path optimization only —
the authoritative read-modify-write still happens under the lock in
`performModelAccountPoolMutation`, so a race between the pre-read and the lock
cannot cause a lost update.

second, wrap the `await lock(CONFIG_PATH, …)` call at `lib/config.ts:180` in
`try/catch`. on `err.code === "ELOCKED"`, do not propagate the raw error — throw
a typed, plugin-owned error (e.g. `ConfigLockContentionError` in `lib/config.ts`
or `lib/errors.ts` carrying `CONFIG_PATH` and a stable code) or return a
discriminated `contended: true` field on `ModelAccountPoolMutationResult`. pick
one approach and use it consistently across `lib/config.ts` and
`lib/tools/codex-pool.ts` (phase 2 depends on this). for any non-`ELOCKED`
error, rethrow unchanged.

modestly raise `proper-lockfile` `retries`/`maxTimeout` to absorb short bursts
of parallel subagents, bounded to a few seconds worst case so it never hangs.
only reuse `exponentialBackoff`/`addJitter` from `lib/rotation.ts:462-484` if an
application-level retry loop is added.

keep the `try/catch` scoped to `lock()` only — do not wrap the temp-file-write +
`renameWithWindowsRetry` path, since that has its own windows `EPERM/EBUSY`
retry handling that must stay intact. do not modify the existing queue-reset
lines (`modelAccountPoolMutationQueue = pending.then(() => undefined, () =>
undefined)`).

Phase 2: make the codex-pool tool degrade gracefully

lib/tools/codex-pool.ts:250 execute() has zero try/catch, unlike every sibling mutating tool. a rejected updateModelAccountPool currently travels unmodified to the opencode host and aborts the subagent. this is the observed "stall".

catch config-lock contention in `execute()` and return a non-fatal result

turn a lock race into a readable, retryable tool response instead of a crash.

  • update lib/tools/codex-pool.ts execute() to wrap the updateModelAccountPool(...) call in try/catch.
  • on the ConfigLockContentionError (or contended result) from task 1.2, return a formatted, non-error tool payload in both json and text modes. the message must state that the account-pool config is busy because another process holds the lock, that no change was applied, and that the agent can retry. follow the existing renderJsonOutput/text-summary pattern already in this file.
  • for any other error, rethrow (do not swallow real faults).
  • rationale: codex-pool mutations require an opencode restart to take effect (per its own output and docs/tools-and-cli.md), so a busy-lock outcome is safe to report as "not applied, retry later" rather than as a failure that stalls the calling subagent.
🤖 Prompt for AI agents
harden `lib/tools/codex-pool.ts` `execute()` (line 250) so it no longer crashes
the calling subagent on config-lock contention.

wrap the `updateModelAccountPool(...)` call in `try/catch`. on catching the
`ConfigLockContentionError` (or `contended` result) produced in phase 1, return
a formatted, non-error tool payload — not a thrown error — in both `json` and
text output modes, following the existing `renderJsonOutput`/text-summary
pattern already used in this file. the message must state that the account-pool
config is busy because another process holds the lock, that no change was
applied, and that the agent can retry.

for any other error type, rethrow it unchanged — do not swallow genuine faults.

note why this is safe: `codex-pool` mutations already require an opencode
restart to take effect (per this tool's own output and `docs/tools-and-cli.md`),
so reporting a busy-lock outcome as "not applied, retry later" is correct and
non-destructive.

Phase 3: reduce log noise, document the failure, and add regression coverage

supporting changes so users understand the message and so this does not regress.

Task 1: throttle the advisory worktree-lock collision warning

under many concurrent live subagent processes sharing one project, checkWorktreeLockForCurrentStorage logs "Multi-worktree collision detected on account storage" on every load and save with no dedup (lib/storage/load-save.ts:294,599). this reads to users as "constant erroring" even though it is advisory and never blocks.

  • add throttling so the warning logs at most once per foreign-lock generation change, not once per storage op. track the last-warned foreign pid/hostname (or a timestamp window) in lib/storage/worktree-lock.ts or in the checkWorktreeLockForCurrentStorage caller in lib/storage/load-save.ts.
  • keep the advisory, non-blocking behavior exactly as-is; only change log frequency, not control flow.
Task 2: document lock contention in troubleshooting

there is no user-facing guidance for this message anywhere in docs/.

  • add a new ## Storage & Lock Contention section to docs/troubleshooting.md, placed after ## Request Errors and before ## OAuth Callback Issues, using the existing <details> + **Symptoms:** / **Cause(s):** / **Solutions:** format.
  • cover both signals: the codex-pool "config busy / Lock file" outcome (many parallel subagents mutating pools; note it now retries and reports gracefully, and that a mutation needs a restart so it should be called rarely), and the advisory Multi-worktree collision detected warning (two sessions/worktrees sharing one project storage; inspect the <storage>.lock sidecar pid/hostname/cwd/lastActive).
  • acknowledge that subagents "not spawning correctly" is an opencode host behavior, not this plugin, per the ticket.
Task 3: add regression tests

current coverage tests only in-process serialization; there is no test for lock-exhaustion contention surfacing gracefully.

  • extend test/model-pool-config.test.ts to hold a foreign proper-lockfile lock on CONFIG_PATH past the retry budget and assert updateModelAccountPool now yields the defined contention outcome (typed error or contended result) instead of a raw ELOCKED, and that the in-process queue stays healthy for the next call.
  • add a test asserting the task 1.1 fast path: a no-op / dryRun mutation returns without ever acquiring the lock (e.g. assert no lock file is created, or the pre-read short-circuits).
  • add a codex-pool execute() test (new or in an existing test/ file for that tool) asserting a contended mutation returns a formatted non-fatal payload in both json and text modes rather than throwing.
  • flag: no existing test spawns real separate OS processes, so true multi-process contention is still only simulated via a foreign lock holder in one process. call this out in the test comments so future work can add a real multi-process chaos test if needed.
🤖 Prompt for AI agents
ship the supporting changes for the lock-contention fix: log throttling, docs,
and regression tests.

log throttling: in `lib/storage/load-save.ts` (lines 294 and 599),
`checkWorktreeLockForCurrentStorage` currently logs "multi-worktree collision
detected on account storage" on every load and save call with no dedup. add
throttling in `lib/storage/worktree-lock.ts` or in the
`checkWorktreeLockForCurrentStorage` caller so the warning logs at most once per
foreign-lock generation change (track last-warned foreign `pid`/`hostname`, or a
timestamp window). do not change the advisory, non-blocking control flow — only
the log frequency.

docs: add a new `## Storage & Lock Contention` section to
`docs/troubleshooting.md`, positioned after `## Request Errors` and before `##
OAuth Callback Issues`, using the existing `<details>` + `**Symptoms:** /
**Cause(s):** / **Solutions:**` format. cover both the `codex-pool` "config busy
/ Lock file" outcome (note it now retries and reports gracefully, and that
mutations need a restart so they should be called rarely) and the advisory
`Multi-worktree collision detected` warning (two sessions/worktrees sharing one
project storage; inspect the `<storage>.lock` sidecar's
`pid`/`hostname`/`cwd`/`lastActive`). note that subagents "not spawning
correctly" is an opencode host behavior outside this plugin's control.

tests: extend `test/model-pool-config.test.ts` to hold a foreign
`proper-lockfile` lock on `CONFIG_PATH` past the retry budget and assert
`updateModelAccountPool` yields the defined contention outcome (typed error or
`contended` result) instead of a raw `ELOCKED`, and that the in-process queue
stays healthy for the next call. add a test for the phase 1 fast path confirming
a no-op/`dryRun` mutation returns without acquiring the lock (e.g. no lock file
created). add a `codex-pool` `execute()` test asserting a contended mutation
returns a formatted non-fatal payload in both `json` and text modes instead of
throwing. flag explicitly in test comments that no existing test spawns real
separate OS processes — multi-process contention is only simulated via a foreign
lock holder in one process — and that a real multi-process chaos test is a
future gap.
Research

index.ts is the single plugin entry opencode loads per process. account rotation and storage writes are serialized only in-process: withStorageLock in lib/storage/state.ts is an intra-process promise-chain mutex, and lib/storage/worktree-lock.ts is an advisory, non-blocking cross-process sidecar (<storage>.lock) that only warns.

the sole hard cross-process lock is proper-lockfile's lock(CONFIG_PATH, …) in lib/config.ts:172-208, used only by updateModelAccountPool, which is called only by the codex-pool tool (lib/tools/codex-pool.ts:250). that tool has no try/catch, and updateModelAccountPool has no try/catch around lock(), so an exhausted-retry ELOCKED propagates raw to the agent.

existing backoff primitives live in lib/rotation.ts:462-484 (addJitter, exponentialBackoff). the storage save path already swallows failures via log.warn in lib/accounts/persistence.ts, so it does not surface to the agent — which is why the visible error is the config lock, not the storage lock.


🚀 Next Steps

🤖 All AI agent prompts combined
Task: 1

implement the root-cause fix for the config lock contention in `lib/config.ts`.
goal: reduce how often the OS lock is ever needed, and never leak a raw
`ELOCKED` rejection.

first, add a lock-free fast path to `updateModelAccountPool` (lines 172-208):
read the current config with the existing lock-free reader (`loadPluginConfig`,
plain `readFileSync`) before calling `lock()`. compute the prospective `changed`
outcome from that read. if `options.dryRun === true`, or the mutation would
produce no change, return the `ModelAccountPoolMutationResult` immediately
without ever acquiring the lock. note this is a fast-path optimization only —
the authoritative read-modify-write still happens under the lock in
`performModelAccountPoolMutation`, so a race between the pre-read and the lock
cannot cause a lost update.

second, wrap the `await lock(CONFIG_PATH, …)` call at `lib/config.ts:180` in
`try/catch`. on `err.code === "ELOCKED"`, do not propagate the raw error — throw
a typed, plugin-owned error (e.g. `ConfigLockContentionError` in `lib/config.ts`
or `lib/errors.ts` carrying `CONFIG_PATH` and a stable code) or return a
discriminated `contended: true` field on `ModelAccountPoolMutationResult`. pick
one approach and use it consistently across `lib/config.ts` and
`lib/tools/codex-pool.ts` (phase 2 depends on this). for any non-`ELOCKED`
error, rethrow unchanged.

modestly raise `proper-lockfile` `retries`/`maxTimeout` to absorb short bursts
of parallel subagents, bounded to a few seconds worst case so it never hangs.
only reuse `exponentialBackoff`/`addJitter` from `lib/rotation.ts:462-484` if an
application-level retry loop is added.

keep the `try/catch` scoped to `lock()` only — do not wrap the temp-file-write +
`renameWithWindowsRetry` path, since that has its own windows `EPERM/EBUSY`
retry handling that must stay intact. do not modify the existing queue-reset
lines (`modelAccountPoolMutationQueue = pending.then(() => undefined, () =>
undefined)`).
===============================================================================

Task: 2

harden `lib/tools/codex-pool.ts` `execute()` (line 250) so it no longer crashes
the calling subagent on config-lock contention.

wrap the `updateModelAccountPool(...)` call in `try/catch`. on catching the
`ConfigLockContentionError` (or `contended` result) produced in phase 1, return
a formatted, non-error tool payload — not a thrown error — in both `json` and
text output modes, following the existing `renderJsonOutput`/text-summary
pattern already used in this file. the message must state that the account-pool
config is busy because another process holds the lock, that no change was
applied, and that the agent can retry.

for any other error type, rethrow it unchanged — do not swallow genuine faults.

note why this is safe: `codex-pool` mutations already require an opencode
restart to take effect (per this tool's own output and `docs/tools-and-cli.md`),
so reporting a busy-lock outcome as "not applied, retry later" is correct and
non-destructive.
===============================================================================

Task: 3

ship the supporting changes for the lock-contention fix: log throttling, docs,
and regression tests.

log throttling: in `lib/storage/load-save.ts` (lines 294 and 599),
`checkWorktreeLockForCurrentStorage` currently logs "multi-worktree collision
detected on account storage" on every load and save call with no dedup. add
throttling in `lib/storage/worktree-lock.ts` or in the
`checkWorktreeLockForCurrentStorage` caller so the warning logs at most once per
foreign-lock generation change (track last-warned foreign `pid`/`hostname`, or a
timestamp window). do not change the advisory, non-blocking control flow — only
the log frequency.

docs: add a new `## Storage & Lock Contention` section to
`docs/troubleshooting.md`, positioned after `## Request Errors` and before `##
OAuth Callback Issues`, using the existing `<details>` + `**Symptoms:** /
**Cause(s):** / **Solutions:**` format. cover both the `codex-pool` "config busy
/ Lock file" outcome (note it now retries and reports gracefully, and that
mutations need a restart so they should be called rarely) and the advisory
`Multi-worktree collision detected` warning (two sessions/worktrees sharing one
project storage; inspect the `<storage>.lock` sidecar's
`pid`/`hostname`/`cwd`/`lastActive`). note that subagents "not spawning
correctly" is an opencode host behavior outside this plugin's control.

tests: extend `test/model-pool-config.test.ts` to hold a foreign
`proper-lockfile` lock on `CONFIG_PATH` past the retry budget and assert
`updateModelAccountPool` yields the defined contention outcome (typed error or
`contended` result) instead of a raw `ELOCKED`, and that the in-process queue
stays healthy for the next call. add a test for the phase 1 fast path confirming
a no-op/`dryRun` mutation returns without acquiring the lock (e.g. no lock file
created). add a `codex-pool` `execute()` test asserting a contended mutation
returns a formatted non-fatal payload in both `json` and text modes instead of
throwing. flag explicitly in test comments that no existing test spawns real
separate OS processes — multi-process contention is only simulated via a foreign
lock holder in one process — and that a real multi-process chaos test is a
future gap.
💡 Iterate on the plan with: `@coderabbitai` <feedback>
Example Feedback
- `@coderabbitai` You can skip phase 3. Add a simple unit test case for phase 2.
- `@coderabbitai` For design choice 1 go ahead with option 3 and replan.

💬 Have feedback or questions? Drop into our discord!

coderabbitai[bot] avatar Aug 09 '26 16:08 coderabbitai[bot]