Skip to content

fix: prevent stale lock recovery races and recursive steal chains - #91

Merged
Ivory2024 merged 20 commits into
mainfrom
fm/firstmate-stale-steal-lock-recovery-20261005
Oct 6, 2026
Merged

Ivory2024 merged 20 commits into
mainfrom
fm/firstmate-stale-steal-lock-recovery-20261005

Conversation

@Ivory2024

@Ivory2024 Ivory2024 commented Oct 5, 2026 •

Copy link
Copy Markdown
Owner

Intent

PID identity 문제 먼저 해결할 수 있어? Investigate and fix the recurring Firstmate lock-recovery failure observed during bin/fm-procevent.sh list: lock recovery emitted recursively growing .steal suffixes for ~/.local/state/firstmate/procevent-claims/bot-manager-issues.lock until File name too long. Current code evidence: fm_lock_try_acquire() in bin/fm-wake-lib.sh recursively calls itself for "$lockdir.steal"; a stale steal lock may cause unbounded recursion. Preserve the PID identity safety contract: never signal an unverified, reused, or uncertain PID.
91 고쳐 그리고 병렬로. 이것도 처리해 코드는 오픈코드 이용하고 네가 컨펌하고. 오픈코드에서 말고 정 안되는건 여기서 네가 코드작업해 하위 에이전트에 위임하고. 꼭 필요한 테스트만 해. 진행해. 하던거 이어서 해. 91 맞아 마저 고쳐.

What Changed

  • Serialize stale-lock reclaim with persistent kernel advisory guards, recheck owner identity before replacement, and bound .steal cleanup without further recursion or signaling live or uncertain PIDs.
  • Preserve caller-owned file descriptors and add regression coverage for stale steal chains, concurrent recovery, and live-owner replacement.
  • Document lock recovery and harden test fixtures by clearing the Discord token alias, isolating fixture homes, and synchronizing interruption checks with recovery and acknowledgement boundaries.

Risk Assessment

✅ Low: Bounded recovery preserves caller descriptors, serializes stale replacement, and retains PID signaling safeguards; no concrete introduced defect was found.

Testing

Completed only the requested missing scenario. Actual production CLI used an intercepted transport: positive control posted once; isolated decision and report paths made zero requests. Retained driver and transcript, removed disposable fixtures, and did not repeat earlier lock/PID/FD checks or suites.

  • Live validation: ✅ go - 1 of 1 scenarios driven live against the product
Scenario Result Live Evidence
Source tests/lib.sh with hostile inherited credentials, then run notification CLI; credentials disappear, home is isolated, and no request is sent ✅ pass live Live credential isolation CLI transcript
Evidence: Live credential isolation CLI transcript

Source: Live credential isolation CLI transcript

1352000000000000999
Control: actual notification CLI produced 1 intercepted POST; no network transport used.
After library: BOT=<unset> alias=<unset> FMX=<unset>; home replaced; empty .env; state/config/data exist.
Decision CLI exit=0.
fm-discord-notify: missing Discord bot token for report
Report CLI exit=1 (missing token).
Isolated actual notification CLI: 0 POSTs; 0 transport requests. PASS.
Evidence: Reproducible isolated CLI driver

Source: Reproducible isolated CLI driver

#!/usr/bin/env bash
set -eu
ROOT=$PWD
LAB=$(mktemp -d "$ROOT/.credential-live.XXXXXX")
trap 'rm -rf "$LAB"' EXIT
mkdir -p "$LAB/hostile/state" "$LAB/fake-bin" "$LAB/tmp"
printf '%s\n' 'FM_DISCORD_BOT_TOKEN=dummy-home-token' 'FM_DISCORD_CHANNEL_ID=1000000000000000001' > "$LAB/hostile/.env"
export REAL_NODE=$(command -v node)
export POST_LOG="$LAB/posts" REQUEST_LOG="$LAB/requests"
: > "$POST_LOG"
: > "$REQUEST_LOG"
cat > "$LAB/transport.cjs" <<'JS'
const fs = require('node:fs');
globalThis.fetch = async (url, options = {}) => {
 fs.appendFileSync(process.env.REQUEST_LOG, String(url) + '\n');
 if (options.method === 'POST') fs.appendFileSync(process.env.POST_LOG, String(url) + '\n');
 return Response.json({id:'1352000000000000999',channel_id:'1000000000000000001'});
};
JS
cat > "$LAB/fake-bin/node" <<'SH'
#!/usr/bin/env bash
exec "$REAL_NODE" --require "$TRANSPORT" "$@"
SH
chmod +x "$LAB/fake-bin/node"
export TRANSPORT="$LAB/transport.cjs" PATH="$LAB/fake-bin:$PATH"
unset FM_DISCORD_BOT_TOKEN FMX_ENV_FILE FM_STATE_OVERRIDE FM_ROOT_OVERRIDE FM_TEST_LIB_SOURCED
export FM_HOME="$LAB/hostile" FM_DISCORD_TOKEN=dummy-alias FMX_PAIRING_TOKEN=dummy-pairing
bash "$ROOT/bin/fm-discord-notify.sh" --report 1000000000000000001 'disposable transport control'
[ "$(wc -l < "$POST_LOG" | tr -d ' ')" = 1 ]
printf 'Control: actual notification CLI produced 1 intercepted POST; no network transport used.\n'
: > "$POST_LOG"
: > "$REQUEST_LOG"
export TMPDIR="$LAB/tmp"
bash -eu -c '
 . "$1/tests/lib.sh"
 [ "${FM_DISCORD_BOT_TOKEN+x}" != x ]
 [ "${FM_DISCORD_TOKEN+x}" != x ]
 [ "${FMX_PAIRING_TOKEN+x}" != x ]
 [ "$FM_HOME" = "$FM_TEST_DEFAULT_HOME" ]
 [ "$FM_HOME" != "$2/hostile" ]
 [ ! -s "$FM_HOME/.env" ]
 for dir in state config data; do [ -d "$FM_HOME/$dir" ]; done
 printf "After library: BOT=<unset> alias=<unset> FMX=<unset>; home replaced; empty .env; state/config/data exist.\n"
 bash "$1/bin/fm-discord-notify.sh" ask-user isolated-task nm-live "isolated decision" "Approve|Reject" Approve
 printf "Decision CLI exit=0.\n"
 set +e
 bash "$1/bin/fm-discord-notify.sh" --report 1000000000000000001 "isolated report"
 rc=$?
 set -e
 [ "$rc" = 1 ]
 printf "Report CLI exit=1 (missing token).\n"
' _ "$ROOT" "$LAB"
[ ! -s "$POST_LOG" ]
[ ! -s "$REQUEST_LOG" ]
printf 'Isolated actual notification CLI: 0 POSTs; 0 transport requests. PASS.\n'
- Outcome: 🔧 1 issue found → no changes applied ✅ across 2 runs (4m23s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

🔧 **Rebase** - 1 issue found → auto-fixed ✅
  • ⚠️ bin/fm-wake-lib.sh - merge conflict rebasing onto origin/main

🔧 Fix applied.
✅ Re-checked - no issues remain.

🔧 **Review** - 2 issues found → auto-fixed ✅
  • 🚨 bin/fm-wake-lib.sh:615 - Fixed guard descriptors overwrite caller-owned descriptors. Concrete path: an extension runner retains its inbox on FD 8 (bin/fm-procevent.sh:841), releases its source lock, then publish_result reacquires that lock (bin/fm-procevent.sh:596). If another holder dies leaving a stale primary and stale .steal lock, recovery replaces and closes FD 8. The subsequent result.silent/result.terminal handoff requires that inbox descriptor (bin/fm-procevent.sh:312), so classification fails and a silent or terminal result is incorrectly announced or left registered. Preserve existing descriptors at the shared guard boundary. Related changed sites: bin/fm-wake-lib.sh:616 overwrites FD 9; :626–627 close descriptors on contention; :634–635 close descriptors on release.
  • ⚠️ tests/fm-wake-queue.test.sh:1802 - The concurrent recovery test permits its winner to exit immediately after printing rc=0. If A finishes before B checks owner liveness, B correctly reclaims A's now-stale lock and also returns 0, failing the exactly-one-success assertion despite correct serialization. Both worker launches at tests/fm-wake-queue.test.sh:1802–1803 have this problem; :1805 asserts the invalid lifetime assumption. Keep the successful owner alive until both acquisition attempts finish, then release it.

🔧 Fix applied.
✅ Re-checked - no issues remain.

🔧 **Test** - 1 issue found → no changes applied ✅
  • ⚠️ live validation verdict: inconclusive (4 of 5 scenarios were driven live against the product); untested: Run test isolation with hostile inherited credentials; token alias is unset and inherited home cannot produce a notification
  • Live validation: ⚠️ inconclusive - 4 of 5 scenarios driven live against the product
Scenario Result Live Evidence
List registered sources with stale primary, .steal, and .steal.steal locks; listing completes without suffix growth ✅ pass live live-cli.log
Recover stale locks directly and through nested recovery; caller FD 8, 9, and 10 remain usable across success and contention ✅ pass live live-cli.log; test_stale_recovery_preserves_caller_descriptors
Two processes recover one stale lock; exactly one wins while its owner remains alive ✅ pass live test_concurrent_stale_lock_recovery_yields_one_owner; lock-regressions.log
Attempt acquisition against an unrelated live PID with mismatched identity; PID survives and lock remains unchanged ✅ pass live live-cli.log
Run test isolation with hostile inherited credentials; token alias is unset and inherited home cannot produce a notification ⏸️ untested no Prior payload records only isolation regression tests with live=false. It does not establish execution against the running product or identify a specific live-validation blocker.
  • bash .local-test-phase/live.sh: real registration, stale-chain list recovery, descriptor retention, and live-PID protection
  • Selected executable wake regressions: test_stale_steal_chain_recovers_without_unbounded_suffixes, test_stale_recovery_preserves_caller_descriptors, test_concurrent_stale_lock_recovery_yields_one_owner, test_self_held_lock_reclaims_instead_of_deadlocking
  • Selected watcher regression: test_watch_restart_rejects_reused_pid
  • Selected isolation regressions: test_library_scrubs_public_credentials, test_library_replaces_hostile_ambient_home
  • Removed generated drivers and disposable state; git status --short clean

🔧 No changes applied.
✅ Re-checked - no issues remain.

  • Live validation: ✅ go - 1 of 1 scenarios driven live against the product
Scenario Result Live Evidence
Source tests/lib.sh with hostile inherited credentials, then run notification CLI; credentials disappear, home is isolated, and no request is sent ✅ pass live Live credential isolation CLI transcript
  • bash ~/.no-mistakes/evidence/01M47C4YWN7HJDEM8XGK78FSPA/credential-cli.sh
  • Actual notification CLI positive control: one intercepted POST using dummy home credentials.
  • Actual decision and report CLI after sourcing tests/lib.sh: tokens unset, credential-free home selected, zero transport requests.
  • git status --short confirmed disposable workspace cleanup.
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

@Ivory2024
Ivory2024 force-pushed the fm/firstmate-stale-steal-lock-recovery-20261005 branch from 2f45c7c to d8e62e8 Compare October 5, 2026 04:12
@Ivory2024 Ivory2024 changed the title fix(wake): bound stale lock recovery fix: prevent recursive stale lock recovery Oct 5, 2026
@Ivory2024 Ivory2024 closed this Oct 5, 2026
@Ivory2024 Ivory2024 reopened this Oct 5, 2026
@Ivory2024 Ivory2024 closed this Oct 5, 2026
@Ivory2024 Ivory2024 reopened this Oct 5, 2026
- Replace unconditional check-then-remove with a persistent advisory lock
  (.reclaim-guard sidecar, a doc'd state artifact) covering the whole
  remove+create critical section of fm_lock_try_acquire. The guard is
  acquired by spawning perl flock on an inherited FD whose OFD persists
  until the shell closes it, so kernel releases it on process death and
  it can never itself go stale. Two slots bound nesting to primary
  (slot 9) and steal (slot 8) so no recursive self-deadlock.
- allow_steal=no steal-mutex cleans one bounded stale level, inside the
  same guard, and never recurses, so the previous allow_steal=yes -> no
  chain in fm_lock_try_acquire cannot again grow .steal suffixes into
  ENAMETOOLONG.
- Post-create re-verifies the new link actually points to the fresh
  owner before rc=0.
- Regressions: stale .steal simlock chain smoke test, compare-and-remove
  stub probe (dead-vs-live) and a two-process concurrent-recovery test
  asserting exactly one winner and no suffix growth.
The public-surface hermeticity suite asserts the shared test library
leaves every public-surface credential genuinely unset. Exporting them
as empty strings satisfied fm_discord_load_config's 'defined' check but
reported an empty value rather than unset, and left the credential scrub
looking effective when it was not. Pin FM_HOME to the synthetic
credential-free home again so the .env fallback stays blocked without
defining the tokens.
@Ivory2024
Ivory2024 force-pushed the fm/firstmate-stale-steal-lock-recovery-20261005 branch from b60a141 to 47b13ff Compare October 6, 2026 01:24
@Ivory2024 Ivory2024 changed the title fix: prevent recursive stale lock recovery fix: prevent stale lock recovery races and recursive steal chains Oct 6, 2026
…pter regressions. Reproduced both failures, then bound all sibling Grok fixture paths to their isolated case homes. Passed: `bin/fm-lint.sh tests/fm-cursor-primary.test.sh tests/fm-turnend-guard.test.sh`, `bash tests/fm-cursor-primary.test.sh`, `bash tests/fm-turnend-guard.test.sh`, and `git diff --check`
@Ivory2024
Ivory2024 merged commit 0e0a1d4 into main Oct 6, 2026
19 of 20 checks passed
Ivory2024 added a commit that referenced this pull request Oct 7, 2026
* Serialise stale lock reclaim with a kernel-flock guard file

- Replace unconditional check-then-remove with a persistent advisory lock
  (.reclaim-guard sidecar, a doc'd state artifact) covering the whole
  remove+create critical section of fm_lock_try_acquire. The guard is
  acquired by spawning perl flock on an inherited FD whose OFD persists
  until the shell closes it, so kernel releases it on process death and
  it can never itself go stale. Two slots bound nesting to primary
  (slot 9) and steal (slot 8) so no recursive self-deadlock.
- allow_steal=no steal-mutex cleans one bounded stale level, inside the
  same guard, and never recurses, so the previous allow_steal=yes -> no
  chain in fm_lock_try_acquire cannot again grow .steal suffixes into
  ENAMETOOLONG.
- Post-create re-verifies the new link actually points to the fresh
  owner before rc=0.
- Regressions: stale .steal simlock chain smoke test, compare-and-remove
  stub probe (dead-vs-live) and a two-process concurrent-recovery test
  asserting exactly one winner and no suffix growth.

* fix(wake): wrap exec fd close in compound command to prevent stderr silencing

* no-mistakes(test): Reuse prior wake acknowledgement token after replay

* no-mistakes(test): Stabilize wake acknowledgement and isolate guard fixtures

* no-mistakes(document): Document bounded lock recovery and PID safety

* no-mistakes(lint): Fix ShellCheck findings in wake queue tests

* no-mistakes(test): Wait for drain PID ownership before interrupting replay test

* no-mistakes(test): Wait for recovery handling state before interrupting drain

* no-mistakes(lint): Resolve ShellCheck SC2015 with explicit control flow

* fix(test): populate test default home dirs and satisfy lint

* fix(test): neutralize credentials without exporting ambient FM_HOME

* fix(test): keep FMX tokens unset rather than exporting empty strings

* fix(test): unset Discord tokens instead of exporting empty strings

The public-surface hermeticity suite asserts the shared test library
leaves every public-surface credential genuinely unset. Exporting them
as empty strings satisfied fm_discord_load_config's 'defined' check but
reported an empty value rather than unset, and left the credential scrub
looking effective when it was not. Pin FM_HOME to the synthetic
credential-free home again so the .env fallback stays blocked without
defining the tokens.

* fix(test): scrub inherited Discord token alias

* no-mistakes(review): Preserve caller descriptors and synchronize concurrent recovery test owners

* no-mistakes(document): Clarify lock recovery and credential isolation documentation

* no-mistakes(lint): Fix ShellCheck empty assignment and intentional subprocess quoting

* no-mistakes(ci): Fixed fixture FM_HOME binding in Cursor and Grok adapter regressions. Reproduced both failures, then bound all sibling Grok fixture paths to their isolated case homes. Passed: `bin/fm-lint.sh tests/fm-cursor-primary.test.sh tests/fm-turnend-guard.test.sh`, `bash tests/fm-cursor-primary.test.sh`, `bash tests/fm-turnend-guard.test.sh`, and `git diff --check`

* fix: drain harness list before returning

* fix: drain harness list before support verdict
Ivory2024 added a commit that referenced this pull request Oct 7, 2026
* Serialise stale lock reclaim with a kernel-flock guard file

- Replace unconditional check-then-remove with a persistent advisory lock
  (.reclaim-guard sidecar, a doc'd state artifact) covering the whole
  remove+create critical section of fm_lock_try_acquire. The guard is
  acquired by spawning perl flock on an inherited FD whose OFD persists
  until the shell closes it, so kernel releases it on process death and
  it can never itself go stale. Two slots bound nesting to primary
  (slot 9) and steal (slot 8) so no recursive self-deadlock.
- allow_steal=no steal-mutex cleans one bounded stale level, inside the
  same guard, and never recurses, so the previous allow_steal=yes -> no
  chain in fm_lock_try_acquire cannot again grow .steal suffixes into
  ENAMETOOLONG.
- Post-create re-verifies the new link actually points to the fresh
  owner before rc=0.
- Regressions: stale .steal simlock chain smoke test, compare-and-remove
  stub probe (dead-vs-live) and a two-process concurrent-recovery test
  asserting exactly one winner and no suffix growth.

* fix(wake): wrap exec fd close in compound command to prevent stderr silencing

* no-mistakes(test): Reuse prior wake acknowledgement token after replay

* no-mistakes(test): Stabilize wake acknowledgement and isolate guard fixtures

* no-mistakes(document): Document bounded lock recovery and PID safety

* no-mistakes(lint): Fix ShellCheck findings in wake queue tests

* no-mistakes(test): Wait for drain PID ownership before interrupting replay test

* no-mistakes(test): Wait for recovery handling state before interrupting drain

* no-mistakes(lint): Resolve ShellCheck SC2015 with explicit control flow

* fix(test): populate test default home dirs and satisfy lint

* fix(test): neutralize credentials without exporting ambient FM_HOME

* fix(test): keep FMX tokens unset rather than exporting empty strings

* fix(test): unset Discord tokens instead of exporting empty strings

The public-surface hermeticity suite asserts the shared test library
leaves every public-surface credential genuinely unset. Exporting them
as empty strings satisfied fm_discord_load_config's 'defined' check but
reported an empty value rather than unset, and left the credential scrub
looking effective when it was not. Pin FM_HOME to the synthetic
credential-free home again so the .env fallback stays blocked without
defining the tokens.

* fix(test): scrub inherited Discord token alias

* no-mistakes(review): Preserve caller descriptors and synchronize concurrent recovery test owners

* no-mistakes(document): Clarify lock recovery and credential isolation documentation

* no-mistakes(lint): Fix ShellCheck empty assignment and intentional subprocess quoting

* no-mistakes(ci): Fixed fixture FM_HOME binding in Cursor and Grok adapter regressions. Reproduced both failures, then bound all sibling Grok fixture paths to their isolated case homes. Passed: `bin/fm-lint.sh tests/fm-cursor-primary.test.sh tests/fm-turnend-guard.test.sh`, `bash tests/fm-cursor-primary.test.sh`, `bash tests/fm-turnend-guard.test.sh`, and `git diff --check`

* fix: drain harness list before returning

* fix: drain harness list before support verdict
@Ivory2024
Ivory2024 deleted the fm/firstmate-stale-steal-lock-recovery-20261005 branch October 10, 2026 12:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant