Skip to content

Crash/reboot resilience + atomic O_EXCL lock (fix WSL2 mkdir non-atomicity) - #48

Closed
owenzhang26-sys wants to merge 2 commits into
kunchenguid:mainfrom
owenzhang26-sys:fm/crash-resilience
Closed

owenzhang26-sys wants to merge 2 commits into
kunchenguid:mainfrom
owenzhang26-sys:fm/crash-resilience

Conversation

@owenzhang26-sys

Copy link
Copy Markdown

Why

A WSL VM teardown (host sleep, idle timeout, or a Windows Update reboot) kills tmux and every crewmate at once, and nothing relaunched firstmate after the VM came back — the fleet stayed dead until the captain reconnected. Separately, the test suite was intermittently flaky.

Crash/reboot resilience

  • systemd/firstmate.service + bin/fm-resume.sh — a watchdog recreates the persistent firstmate tmux session on boot and self-heals if it dies. KillMode=process means stopping the unit never kills a live firstmate. Verified: restarts ~10s after a kill; survivor session untouched.
  • bin/fm-install-autostart.sh — install / status / uninstall; fully reversible, never touches a running session.
  • Recommended companion (not in this repo): ~/.wslconfig with vmIdleTimeout=-1 to prevent the idle teardown in the first place (needs wsl --shutdown to apply).

Lock correctness (root cause of the flakiness)

The wake-queue / watcher-singleton lock used mkdir as its atomic primitive, but mkdir is not atomic on WSL2's filesystem — a 20-way barrier race produced up to 4 concurrent mkdir successes on one path. The lock therefore double-granted under contention (duplicate watchers, raced wake-queue drains, flaky tests). A canonical mutex probe showed 4–8 double-grants per run.

Replaced the primitive with an O_EXCL (noclobber) create — atomic on Linux, WSL2, and macOS — which also writes the holder pid in the same step, eliminating the empty-pid window. Dead holders are reclaimed in a single try_acquire (so fm-watch.sh takes over a crashed watcher); a live holder's lock is never stolen. Probe now reports 0 double-grants.

Tests

  • tests/fm-lock-exclusivity.test.sh — canonical mutex probe + dead/live reclaim (guards the lock fix).
  • tests/fm-resume.test.sh — base-index-safe session creation + idempotency (runs against an isolated tmux server).
  • tests/fm-wake-queue.test.sh — singleton-start now polls for the invariant instead of a fixed sleep.

Local CI green: shellcheck bin/*.sh tests/*.sh, all 5 test files, and the repo invariants.

Also included

fix(spawn,teardown): fm-spawn waits for a */.treehouse/* cwd before recording the worktree; fm-teardown ignores the tracked .claude/settings.local.json (turn-end hook) in its dirty check.

🤖 Generated with Claude Code

root added 2 commits June 23, 2026 10:34
…ocal.json in dirty check

fm-spawn waits specifically for a */.treehouse/* cwd rather than any change off
the project dir, so a transient default-cwd reading is never misrecorded as the
worktree. fm-teardown's dirty check ignores the tracked .claude/settings.local.json
that the turn-end hook modifies, so teardown is not blocked by firstmate's own hook.
Crash/reboot resilience: a WSL VM teardown (host sleep, idle timeout, Windows
Update reboot) kills tmux and every crewmate at once and nothing relaunched
firstmate afterward. systemd/firstmate.service runs bin/fm-resume.sh as a
watchdog that recreates the persistent firstmate tmux session on boot and
self-heals if it dies (KillMode=process, so stopping the unit never kills a live
firstmate). bin/fm-install-autostart.sh installs/removes it. Pair with
~/.wslconfig vmIdleTimeout=-1 to prevent the idle teardown in the first place.

Lock correctness: the wake-queue/singleton lock used mkdir as its atomic
primitive, but mkdir is NOT atomic on WSL2's filesystem (verified: 4 concurrent
mkdir calls succeeded on one path in a barrier race), so the lock double-granted
under contention - duplicate watchers, raced wake-queue drains, flaky tests.
Replaced with an O_EXCL (noclobber) create, atomic on Linux, WSL2, and macOS,
which also writes the holder pid in the same step (no empty-pid window). Dead
holders are reclaimed in one call; a live holder's lock is never stolen.

Tests: fm-lock-exclusivity (canonical mutex probe + reclaim) and fm-resume
(base-index-safe create + idempotency) guard both fixes; the singleton-start
test now polls for the invariant instead of a fixed sleep.
@kunchenguid

Copy link
Copy Markdown
Owner

Thanks for the PR! This branch currently has a merge conflict with the base branch.

When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again.

Noted for firstmate#48 at a18bf14b.

This was referenced Aug 7, 2026
@erni-tf

erni-tf commented Sep 6, 2026

Copy link
Copy Markdown

Q6 polish applied: O1-O8 from the G6 cert report fixed in data/math-fish-q6-split/proof.tex, proof.pdf recompiled clean (9pp, ledger pinned p.1, zero em-dashes). O1/O7 mandatory gates satisfied. No verdict, derivation, or measurement changed; engine empty-half behavior untouched (routes to #63). Fix note: data/math-fish-q6-polish/report.md.

@biz-twoASone

Copy link
Copy Markdown

PRR checklist

  1. Limits/cost. Applies. Per run: one page load plus at most MAX_LIST_RESPONSES = 400 list requests (5 orders each) [TBD - measure]; the run stops before scrolling past the cap. Per month [INFERENCE]: without extension order dates every read is a full read, capped at 400/day (~12,000/month, and every read of >2,000 orders ends run-cap and backs off); with dates ~16-54/day plus a weekly full read (~2,200-3,300/month at 2,000 orders). Time per 400-page read ~37-55 min [INFERENCE, TBD - measure], longer than the tracker browser's abandoned-read deadline: tracked. Page memory: every loaded order card plus the hook's kept responses in the page; 2,000-order renderer memory vs the unit's 1,536 MiB MemoryMax is [TBD - measure].
  2. Failure and restart. Applies. Top-level catch in runAnchorRead posts not-ready and shows the error (a named stop keeps its stop line even when delivery fails). Terminal, no retry: every named stop; nothing retryable inside a read. Stop-on-wall checked before any freshness gate. Browser restart mid-run: nothing posted, daily pending becomes abandoned and backs off, marker last_attempt_at stops moving. Duplicates/bursts: unchanged single-flight (reader refuses a second start, shared execution lock, daily check serialized); a step carries the run key and refuses another run's, a stopped run's (popup Stop marks the page) or an unarmed page; the detail pass starts only after the last step.
  3. Monitoring from outside. Applies. A stopped or incomplete read posts complete:false, so it never refreshes tracker.shopee_complete_read last_success_at or /v1/refresh-need last_complete_read_at; marker last_error is the stop class token (existing one-token format), else incomplete-read. No new transport.
  4. Rollback and deploy safety. Applies. Revert, restart the tracker browser (driver reload) so versions shows shopee-anchor-reader/7 / extension 2.11.0, reinstall the receiver from the release for marker tokens. No receiver migration; stored snapshots with the new labels read back as ordinary incomplete reads.
  5. Real-shape tests. Applies. Product tests run the real hook, reader, outbox and HTTP receiver on the cited public live list shape (tests/fixtures/shopee_all_order_list_pages.json, synthetic values) with the page loading its next list page only when scrolled; reader tests use fake page/clock. Labelled synthetic; live proof is the pilot (shopee-p7-schedule-pilot) and omen-p11-live-verify. Untested live (all 6 pipeline test scenarios, accepted without live proof by firstmate decision nm-01M5S17G4DJ9RBGP9V3AHK203W-test; no Shopee or tracker-browser action was allowed in this task): (1) Scroll the purchase list (one human-paced step per look until the list ends, then never again; a tab off the list is navigated there in front); (2) Incremental read stops at the known boundary (delta stops at the proving page; an unproven delta reads the whole list); (3) Captcha, wall or error code stops the run (wall-login, wall-captcha, wall-antifraud, list-error, unknown-shape; never retries or scrolls again); (4) The stop is visible (badge and popup show 'stopped: - solve it in the browser and run again', also when the receiver is unreachable; receiver stop classes match); (5) Account protection (human input, navigation, reload, status tab or run cap stop the read; badge input does not; nothing scrolled afterward); (6) Single-flight and cancellation (a second Start is ignored while scrolling; Stop ends the run with nothing scrolled afterward). Live proof is the staged pilot ladder on the Omen with the captain present (one automated 5-screen scroll, a 25-page run, then a daily incremental run): shopee-p7-schedule-pilot, omen-p11-live-verify, shopee-p5-live-verify (in-repo as shopee-detail-live-verify).
  6. UI evidence. Applies. Popup stop text and page badge (reading and stop) rendered in a local scratch Chrome from the real popup.html / showBadgeInPage with a stubbed chrome API, at 1280, 390 and 320 px (no Shopee, no tracker browser).
  7. Permissions and privacy. Applies. No manifest permission or content-script change; the scroller is injected by scripting.executeScript only into the read's own tab after its fresh load of the list page, in the isolated world. Failure detail adds only stage scroll and a reason word; markers stay fixed tokens.
  8. Design sweep. Applies. Entry points: popup Read, auto-start link (banner shows the stop line), daily trigger (walls pause, other stops back off; wall line names the noVNC view), tracker browser driver (safe-failure whitelist names the stop classes), detail pass (after the last step), manual Read during a run (ignored). Receiver: anchor.FAILURES, DETAIL_STAGES, markers, gate reader.
  9. No merged deferrals. Applies. Tracked in docs/shopee-delta-anchor.md: shopee-p4-pacing-measure (pacing, IDLE_MS, cap, memory, duration from received_at_ms), shopee-p4-first-read-over-cap (a list over 2,000 orders cannot become a first anchor under the cap; captain decision); existing shopee-stored-order-dates-writer, shopee-p7-schedule-pilot, omen-p11-live-verify (plan updated). Live verification tracked as shopee-p7-schedule-pilot, omen-p11-live-verify, shopee-p5-live-verify (in-repo as shopee-detail-live-verify).
  10. Incident-to-automatic-check. Applies. "after a wall, a refusal, a list error, an unknown shape or a human, the run never retries and never scrolls again" and "Stop while the page is being scrolled ends the run at the next look, and nothing is scrolled after it" (tests/test_shopee_anchor_reader.js); "a step refuses a run that is not armed, not this run, or stopped" (tests/test_shopee_autoscroll.js); product run-cap scenario (no request beyond the cap).

UI evidence (item 6): local-only screenshots of the real popup and page badge (stubbed chrome API, synthetic state) at 1280, 390 and 320 px are kept outside the repo with the firstmate task data (data/shopee-p4-autoscroll/ui/).

@kimdavid333

Copy link
Copy Markdown

Measurement note (from the task worker)

  • The 85% acceptance for the on-device model path was not measured live. The model could not run in this session's iOS 26.5 simulator: the Foundation Models asset (com_apple_MobileAsset_UAF_FM_GenerativeModels) was never downloaded into the fresh simulator, every respond failed at once with GenerationError error -1, and the "Ready for Apple Intelligence" setup needs a tap no tool here can perform. Offline, the new guard applied to the audit's recorded model rows lists 82% dishes on the four reference menus (was 74%), still under the 85% bar, so the rules-default fallback from the audit's G1 is applied: Built-in rules are the default and the model is the Settings option.
  • When the 8 s budget runs out, the native extract call is not cancelled and keeps running in the background; a rescan then starts another model run beside it. This only affects the opt-in model path now. Follow-up, not changed here.
  • Further price edge cases noted by review and left as follow-ups: a bare integer the model leaves in a name ("Margherita 9") now stays in the shown name, since neither the guard nor tidyMenuLine strips it.
  • Full evidence, harness and recipe: the task's test report in Firstmate data (menu-g1-safe-default/test-report.md).

fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
* Add private Lavish decision surface

* Declare decision and upstream watch surfaces
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 18, 2026
…heck the publishing guards (kunchenguid#48)

* feat(bin): give every new owner a private add-on at first setup and confirm the publishing guards

bin/fm-addon.sh create makes the signed-in owner a private repository from a
minimal starter, keeps it at projects/<repo> and writes config/addon; with no
GitHub sign-in it stops with the sign-in steps. bin/fm-addon.sh guards confirms
the user role, installs and confirms the pre-push leak check on the checkout
and the add-on (new fm-leak-prepush.sh status), and starts config/leak-words.
The first voyage now runs both before the first project, and the team and
onboarding docs make the add-on the standard place for an owner's changes.

* no-mistakes(review): Ask before creating the add-on; never count it as project

* no-mistakes(review): Restore add-on project route; registry rebuild still skips it

* no-mistakes(test): Treat skip-to-project requests as step 4 declines

* no-mistakes(test): Gate first project on private add-on; fix leak hit

* no-mistakes(document): Note add-on create, guards and first-project in docs
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.

5 participants