Repository navigation
fix(bearer): per-(scope, channel, gist) lock prevents duplicate emission - #451
Merged
Merged
Conversation
…ssion
Symptom Joel diagnosed 2026-05-04: the same peer broadcast appeared
twice in the monitor stream with identical body + identical session
nonce — meaning bearer_cli yielded it from the gist twice, not that
the peer broadcast twice.
Root cause: nothing prevents multiple bearer_cli recv processes from
running for the same (scope, channel, gist) tuple. Two paths produced
this in practice:
- Scope teardown leaks orphan bearers. cmd_teardown kills processes
via airc.pid, but bearer_cli children spawned by the old monitor
can be reparented to PID 1 if the parent died ungracefully. They
keep polling forever, unbounded by the cleanup that removed the
visible monitor.
- Host-gist-rotation respawns. When the host gist rotates (e.g.
self-heal eviction), a new bearer is spawned against the new gist
while the old bearer may still be alive briefly polling the old
gist. If both their stdouts feed the same downstream, every line
arrives twice.
Fix: bearer_cli.cmd_recv claims a per-(scope, channel, gist) lock at
startup. Pidfile path is derived from --state-file by replacing
.json → .pid (so bearer_state.general.json → bearer_state.general.pid
in the same scope dir). Stale-pidfile recovery follows cmd_connect's
#97 self-heal pattern (kill -0 alone is unsafe — OS reuses PIDs after
sleep/wake; verify cmdline shape matches bearer_cli recv for OUR gist).
Lock claim outcomes:
- Pidfile absent → claim, write our pid+gist.
- Pidfile present, PID dead → stale; claim.
- Pidfile present, PID alive but for a different gist → stale
(rotated-gist case); claim.
- Pidfile present, PID alive AND for our gist → exit 0 cleanly with
a stderr line so the watchdog can see why the second bearer
declined to spawn.
Without --state-file no lock is taken — preserves backwards compat
for legacy / test invocations that don't have a writable scope dir.
Tests: 6 new BearerCliRecvLockTests cover each branch + the
release-only-when-we-own-it semantic that prevents stomping a
successor that took the lock after we ran. All 87 existing bearer
tests still pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR adds a pidfile-based dedup mechanism to bearer_cli recv so only one bearer process should poll a given scope/channel stream at a time, aiming to stop duplicate monitor emissions during leaked-orphan and gist-rotation scenarios.
Changes:
- Add recv-lock helpers in
lib/airc_core/bearer_cli.pyand wire them intocmd_recv. - Verify existing PID ownership via liveness + command-line checks before reclaiming stale locks.
- Add unit tests covering lock claim/release branches in
test/test_bearer.py.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
lib/airc_core/bearer_cli.py |
Introduces pidfile claim/release logic and hooks it into the recv startup path. |
test/test_bearer.py |
Adds unit tests for lock acquisition, stale recovery, duplicate suppression, and release semantics. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+148
to
+185
| if os.path.exists(pidfile): | ||
| try: | ||
| with open(pidfile, "r") as f: | ||
| data = f.read().strip() | ||
| except OSError: | ||
| data = "" | ||
| # Format: "<pid>\t<gist_id>". gist_id may be empty for non-gh bearers. | ||
| parts = data.split("\t", 1) | ||
| try: | ||
| other_pid = int(parts[0]) if parts and parts[0] else 0 | ||
| except ValueError: | ||
| other_pid = 0 | ||
| if other_pid > 0 and other_pid != my_pid \ | ||
| and _pid_alive(other_pid) and _is_our_bearer(other_pid, my_gist): | ||
| print( | ||
| f"bearer_cli recv: another bearer for gist {my_gist or '(none)'} " | ||
| f"already running (PID {other_pid}); exiting cleanly to avoid " | ||
| f"duplicate emission", | ||
| file=sys.stderr, flush=True, | ||
| ) | ||
| return None | ||
| # else: stale (dead pid, OS-reused, or old gist) → take over | ||
|
|
||
| try: | ||
| with open(pidfile, "w") as f: | ||
| f.write(f"{my_pid}\t{my_gist}\n") | ||
| except OSError as e: | ||
| # Loud, not silent — we'd rather know we couldn't lock than | ||
| # silently disable the dedup guarantee. | ||
| print( | ||
| f"bearer_cli recv: could not write pidfile {pidfile}: {e}; " | ||
| f"proceeding without lock (duplicate emission possible)", | ||
| file=sys.stderr, flush=True, | ||
| ) | ||
| return None | ||
| return (pidfile, my_pid) | ||
|
|
||
|
|
Comment on lines
+262
to
+263
| lock = _claim_recv_lock(args) | ||
| if lock is None and getattr(args, "state_file", None): |
| this stream — caller should exit 0 cleanly. | ||
|
|
||
| Pidfile path is derived from --state-file by replacing the .json | ||
| suffix with .pid (e.g. bearer_state.general.json → bearer.general.pid). |
This was referenced May 4, 2026
Merged
Merged
joelteply
added a commit
that referenced
this pull request
May 4, 2026
…inite respawn loop when channels share a gist (#458) fix(monitor): dedup bearer spawns by gist, not by channel Real-world repro Joel hit 2026-05-04: channel_gists collapsed useideem and general onto the SAME gist (host advertising one mesh gist for both subscribed channels). #452's per-(scope, gist) lock correctly admitted only ONE bearer for that gist — but the bash supervisor in _monitor_multi_channel iterated channels and spawned one bearer per channel REGARDLESS of gist sharing. Result: the lock-loser bearer exits 0 cleanly with "another bearer for gist X already running"; supervisor sees the exit as a death, respawns, loses lock again, ad infinitum. bearer_recv.<ch>.log filled with identical exit-cleanly lines, the channel's events_total stayed at 0, and inbound messages on that channel never reached the user. This was the third bearer-related design-mismatch bug in the same session (#451 was process lifecycle, #452 was the lock-key mismatch, this is the supervisor-key mismatch). Fixing at the supervisor: dedup by gist BEFORE spawning. Same invariant in both paths: - Initial spawn (channel_map iteration): track _served_gists set; skip channels whose gist already has a bearer from earlier in the iteration. - Live-refresh add path: build _live_gists from current _pids (resolving each entry's channel→gist via the current map); skip channels whose gist is already covered by another live bearer. The bearer reads the gist once and yields each line; monitor_formatter routes to subscribed channels via the envelope's `channel` field downstream. State files stay per-channel for now (per-gist state- files would be a deeper refactor that touches status/doctor/cmd_send; not blocking tonight's Toby remote-conn test). Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Joel diagnosed 2026-05-04: peer broadcasts arriving twice in the monitor stream with identical body + identical session nonce. Root cause: nothing prevents multiple
bearer_cli recvprocesses from polling the same (scope, channel, gist) tuple. Each yields each new line independently → duplicate downstream.Two paths produced it in practice:
airc.pid, but bearer children spawned by the old monitor can be reparented to PID 1. They keep polling forever.Fix
bearer_cli.cmd_recvclaims a per-(scope, channel, gist) lock at startup. Pidfile is<state_file_basename>.pidin the same scope dir (e.g.bearer_state.general.json→bearer_state.general.pid).Stale-pidfile recovery matches
cmd_connect's #97 self-heal pattern (kill -0 alone is unsafe — OS reuses PIDs after sleep/wake; verify cmdline matchesbearer_cli recvfor OUR gist):Without
--state-file, no lock is taken — preserves backwards compat for legacy / test invocations._release_lockis registered viaatexitand only removes the pidfile if it still contains our PID — never stomps a successor that took the lock after we ran.Test plan
BearerCliRecvLockTestscover every claim branch + release-when-owned semanticspython3 test/test_bearer.py)Coordination
@codex-b741 — would value a second look. Touches the same bearer-internals surface as your #450 (inbox polling). Lock is keyed on (state_file → pidfile derivation), so any path that calls bearer_cli recv with a state-file gets dedup automatically.
🤖 Generated with Claude Code