Skip to content

fix(bearer): per-(scope, channel, gist) lock prevents duplicate emission - #451

Merged
joelteply merged 2 commits into
canaryfrom
mac-vhsm/bearer-pidfile-lock
May 4, 2026
Merged

joelteply merged 2 commits into
canaryfrom
mac-vhsm/bearer-pidfile-lock

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

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 recv processes from polling the same (scope, channel, gist) tuple. Each yields each new line independently → duplicate downstream.

Two paths produced it in practice:

  • Scope teardown leaks orphan bearers. cmd_teardown kills via airc.pid, but bearer children spawned by the old monitor can be reparented to PID 1. They keep polling forever.
  • Host-gist-rotation respawns. A new bearer for the new gist races a brief-still-alive old bearer for the old gist. If their stdouts share a downstream, every line arrives twice.

Fix

bearer_cli.cmd_recv claims a per-(scope, channel, gist) lock at startup. Pidfile is <state_file_basename>.pid in 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 matches bearer_cli recv for OUR gist):

Pidfile state Action
absent claim
PID dead stale → claim
PID alive, different gist stale (rotated case) → claim
PID alive, same gist exit 0 cleanly with explanatory stderr

Without --state-file, no lock is taken — preserves backwards compat for legacy / test invocations.

_release_lock is registered via atexit and only removes the pidfile if it still contains our PID — never stomps a successor that took the lock after we ran.

Test plan

  • 6 new BearerCliRecvLockTests cover every claim branch + release-when-owned semantics
  • All 87 existing bearer tests pass (python3 test/test_bearer.py)
  • CI clean-install matrix
  • Local: spawn two bearer_cli recv processes for the same gist; second should exit 0 with the explanatory stderr

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

…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]>
Copilot AI review requested due to automatic review settings May 4, 2026 16:26

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py and wire them into cmd_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 thread lib/airc_core/bearer_cli.py Outdated
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 thread lib/airc_core/bearer_cli.py Outdated
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).
@joelteply
joelteply merged commit da16768 into canary May 4, 2026
5 checks passed
@joelteply
joelteply deleted the mac-vhsm/bearer-pidfile-lock branch May 4, 2026 16:33
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]>
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.

2 participants