Skip to content

Commit 0e4b311

Browse files
committed
Reconcile signals across restart claims and lock handoff resolution
1 parent 6c5b741 commit 0e4b311

5 files changed

Lines changed: 124 additions & 5 deletions

File tree

‎docs/README-lanes.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3203,3 +3203,10 @@ which keeps the exact operation as a child and forwards its operation/attempt
32033203
tokens. The historical #94 incident above describes the earlier launcher. A
32043204
respawn also forwards configured `LANES_LANE_STATE_ROOT` and
32053205
`AGENT_PROTOCOL_ROOT` with shell quoting so its durable intent remains readable.
3206+
3207+
Legacy lane rename is an explicit publication exception: it already holds the
3208+
writer mutex and now refuses unfinished/failed restart ownership before moving
3209+
inputs. Its existing four-file transaction uses EXIT rollback, including stamp
3210+
write failures; it is not crash atomic across those files. This change does not
3211+
claim stronger crash durability for ordinary rename. Restart preservation and
3212+
resume-stamp publishers use the atomic checksum-fenced publication helper.

‎lane-handoff‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -817,10 +817,20 @@ supervise_run() { # <lane> <operation>
817817
LANES_NO_FETCH=1 "$LANES_EDIT" legacy-restart-check "$sr_lane" ||
818818
die "managed ownership blocks this legacy retry. Nothing was started." 2
819819
sr_claim_gen="$RI_GEN"
820+
SV_CLAIMED_GEN=""; SV_CLAIMED_ATTEMPT=""; SV_CHILD_LAUNCH_STARTED=0
821+
SV_DEFERRED_SIGNAL=""; SV_DEFERRED_STATUS=""
822+
SV_CLAIMING=1
820823
sr_crc=0
821824
LANES_NO_FETCH=1 "$LANES_EDIT" set-restart-intent "$sr_lane" starting \
822825
--expect "$RI_STATE" --expect-operation "$sr_op" --expect-generation "${RI_GEN:-0}" --expect-attempt "$RI_ATTEMPT" \
823826
"${sr_att[@]}" --new-transcript none --reason "supervisor claimed the operation" >/dev/null 2>&1 || sr_crc=$?
827+
# The writer is the authority for a successful CAS; publish its exact
828+
# requested identity before replaying a signal deferred during the claim.
829+
if [ "$sr_crc" = 0 ]; then
830+
SV_CLAIMED_GEN="$sr_claim_gen"; SV_CLAIMED_ATTEMPT="$sr_claim_attempt"
831+
fi
832+
SV_CLAIMING=0
833+
[ -z "$SV_DEFERRED_SIGNAL" ] || sv_signal "$SV_DEFERRED_SIGNAL" "$SV_DEFERRED_STATUS"
824834
case "$sr_crc" in
825835
0) : ;;
826836
7) die "lane $sr_lane's restart intent moved between reading it and claiming it: another act owns operation $sr_op now. Nothing was started. Read it: $prog --restart-status --lane $sr_lane" 2 ;;
@@ -914,6 +924,7 @@ supervise_run() { # <lane> <operation>
914924
# `9<&-` CLOSES THE SAVED COPY IN THE CHILD once it has become its
915925
# stdin: the pane's descriptor is this process's bookkeeping and is no
916926
# part of the environment an interactive Claude should be handed.
927+
SV_CHILD_LAUNCH_STARTED=1 # conservative before the fork/pid-file boundary
917928
if [ "$SV_STDIN_SAVED" = 1 ]; then
918929
supervise_child <&9 9<&- &
919930
else
@@ -1105,6 +1116,9 @@ SV_PIDFILE=""
11051116
SV_SIGNALLED=0
11061117
SV_WATCH_PID=""
11071118
SV_WATCH_DIR=""
1119+
SV_CLAIMING=0
1120+
SV_DEFERRED_SIGNAL=""; SV_DEFERRED_STATUS=""
1121+
SV_CHILD_LAUNCH_STARTED=0
11081122
# Never signal a saved PID: an observer can finish hours before its child.
11091123
# Cancellation uses a private marker; wait addresses our owned shell job.
11101124
sv_stop_watch() {
@@ -1144,6 +1158,12 @@ sv_on_exit() {
11441158
# Cancellation writes only an owned attempt. A live or unknown child keeps
11451159
# starting and blocks retry; an unclaimed pending intent remains unchanged.
11461160
sv_signal() { # <signal name> <exit status>
1161+
# Bash may deliver a deferred signal as the CAS returns, before the caller
1162+
# records its successful claim. Finish publication before reconciliation.
1163+
if [ "$SV_CLAIMING" = 1 ]; then
1164+
SV_DEFERRED_SIGNAL="$1"; SV_DEFERRED_STATUS="$2"
1165+
return 0
1166+
fi
11471167
SV_SIGNALLED=1
11481168
# THE OBSERVER GOES FIRST, AND IS REAPED (Copilot round 2 on
11491169
# openRepoTools#121). It is a background job of this shell and a signal to
@@ -1184,12 +1204,20 @@ sv_signal() { # <signal name> <exit status>
11841204
[ "$sv_sg_hrc" != 8 ] || sv_sg_state=failed
11851205
fi
11861206
fi
1207+
if [ "$SV_CHILD_LAUNCH_STARTED" = 0 ]; then
1208+
sv_sg_alive="no child was launched"
1209+
sv_sg_hrc=0
1210+
LANES_NO_FETCH=1 "$LANES_EDIT" lane-holders "$lane" >/dev/null 2>&1 || sv_sg_hrc=$?
1211+
[ "$sv_sg_hrc" != 8 ] || sv_sg_state=failed
1212+
fi
11871213
sv_sg_fence=()
11881214
[ -n "$SV_CLAIMED_GEN" ] && sv_sg_fence=(--expect-generation "$SV_CLAIMED_GEN" --expect-attempt "$SV_CLAIMED_ATTEMPT")
1215+
sv_sg_reason="supervisor received SIG$1 before readiness; $sv_sg_alive"
1216+
[ "$sv_sg_state" != starting ] || sv_sg_reason="INDETERMINATE: $sv_sg_reason"
11891217
LANES_NO_FETCH=1 "$LANES_EDIT" set-restart-intent "$lane" "$sv_sg_state" \
11901218
--expect 'pending|starting' --expect-operation "$operation" \
11911219
${sv_sg_fence[@]+"${sv_sg_fence[@]}"} \
1192-
--reason "INDETERMINATE: supervisor received SIG$1 before readiness; $sv_sg_alive" \
1220+
--reason "$sv_sg_reason" \
11931221
>/dev/null 2>&1 || :
11941222
ri_load "$lane" >/dev/null 2>&1 || :
11951223
say ""

‎lanes-edit.sh‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10649,7 +10649,6 @@ lane_restart_missing() { # <file> <canonical lane>
1064910649
for (i=1;i<=n;i++) allowed[keys[i]]=1
1065010650
allowed["prepared_digest"]=1
1065110651
}
10652-
/^$/ { next }
1065310652
{
1065410653
if ($0 ~ /[[:cntrl:]]/ || $0 !~ /^[A-Za-z_]+: /) {bad["record"]=1; next}
1065510654
k=$0; sub(/:.*/, "", k)
@@ -14151,6 +14150,7 @@ EOF
1415114150
[ "${#pbh_digest}" = 64 ] || die "publication requires the complete prior SHA-256" 64
1415214151
case "$pbh_digest" in *[!0-9a-fA-F]*) die "publication requires SHA-256" 64 ;; esac
1415314152
[ -f "$pbh_source" ] && [ -r "$pbh_source" ] && [ -s "$pbh_source" ] || die "the prepared handoff is unreadable or empty" 1
14153+
acquire_lock
1415414154
pbh_links=0
1415514155
while [ -L "$pbh_target" ]; do
1415614156
pbh_links=$((pbh_links+1)); [ "$pbh_links" -lt 40 ] || die "the handoff link chain cannot be resolved" 2
@@ -14160,7 +14160,6 @@ EOF
1416014160
pbh_parent="$( CDPATH=''; cd -P -- "$(dirname -- "$pbh_target")" && pwd -P )" || die "the handoff parent is missing" 1
1416114161
pbh_target="$pbh_parent/$(basename -- "$pbh_target")"
1416214162
[ -f "$pbh_target" ] && [ -r "$pbh_target" ] || die "the handoff target is unreadable" 1
14163-
acquire_lock
1416414163
pbh_irc=0; pbh_intent="$(lane_restart_read "$lane")" || pbh_irc=$?
1416514164
case "$pbh_irc" in 0|8) : ;; *) release_lock; die "restart ownership could not be read; no handoff was published" 1 ;; esac
1416614165
pbh_current="$(printf '%s\n' "$pbh_intent" | awk -F'\t' '$1=="state" {print $2; exit}')"

‎specs/005-supervised-legacy-ctx/plan.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ Each starting attempt consumes `new_transcript: none` exactly once. Later writes
3737
expect the reserved UUID as well as operation, generation and attempt. Stamp
3838
publication resolves a final-component symlink and atomically replaces its target
3939
from a same-directory temporary file. The helper holds the same writer mutex
40-
through ownership and prior-digest checks and replacement. All shipped handoff
40+
through ownership and prior-digest checks and replacement. All restart preservation and resume-stamp
4141
publishers use this path; manual edits must follow the staging/publication skill
4242
contract. Existing records with missing, duplicate or invalid fields refuse
4343
transitions rather than being silently repaired.
@@ -60,3 +60,10 @@ record publication. Intent writes use private same-directory temporary files.
6060
Rename takes the existing mutex and refuses unfinished/failed restart records.
6161
Observers stop through a private marker and are reaped before marker removal,
6262
without signaling a numeric PID that may already have been recycled.
63+
64+
Legacy lane rename is an explicit publication exception: it already holds the
65+
writer mutex and now refuses unfinished/failed restart ownership before moving
66+
inputs. Its existing four-file transaction uses EXIT rollback, including stamp
67+
write failures; it is not crash atomic across those files. This change does not
68+
claim stronger crash durability for ordinary rename. Restart preservation and
69+
resume-stamp publishers use the atomic checksum-fenced publication helper.

‎tests/test_supervised_restart_regressions.py‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -938,7 +938,7 @@ def test_existing_invalid_state_root_is_not_absent_intent(restart_box, kind):
938938
assert not box.claude_runs()
939939

940940

941-
@pytest.mark.parametrize("extra", ["future_key: preserve-me\n", "garbage\n", "profile:test\n",
941+
@pytest.mark.parametrize("extra", ["future_key: preserve-me\n", "garbage\n", "profile:test\n", "\n",
942942
"schema: 1\n", "prepared_digest: none\n",
943943
"pane: testsess:@1.%1\tignored\n"])
944944
def test_restart_strict_schema_preserves_unrecognized_or_malformed_records(restart_box, extra):
@@ -1189,3 +1189,81 @@ def test_new_restart_explicitly_clears_previous_operations_profile(restart_box):
11891189
assert record["profile"] == "none"
11901190
assert record["operation"] != "op-test"
11911191
assert "respawn-pane" in box.tmux_log.read_text()
1192+
1193+
1194+
@pytest.mark.parametrize("claim", ["success", "lost"])
1195+
def test_signal_during_claim_publication_reconciles_only_owned_attempt(restart_box, claim):
1196+
box = restart_box
1197+
prepare_restart(box)
1198+
before = intent_path(box).read_bytes()
1199+
real = box.bin / "lanes-edit-real.sh"
1200+
(box.bin / "lanes-edit.sh").rename(real)
1201+
action = f"'{real}' \"$@\"; result=$?" if claim == "success" else "result=7"
1202+
_write(box.bin / "lanes-edit.sh", f"""#!/usr/bin/env bash
1203+
case "$*" in
1204+
*"supervisor claimed the operation"*)
1205+
{action}
1206+
kill -TERM "$PPID"
1207+
exit "$result" ;;
1208+
esac
1209+
exec '{real}' "$@"
1210+
""")
1211+
result = supervisor(box, "--supervise", "--lane", LANE, "--operation", "op-test")
1212+
assert result.returncode == 143, (result.stdout, result.stderr)
1213+
assert not box.claude_runs()
1214+
if claim == "lost":
1215+
assert intent_path(box).read_bytes() == before
1216+
assert "before the restart claim" in result.stdout
1217+
else:
1218+
record = dict(line.split("\t", 1) for line in helper(box, "restart-intent", LANE).stdout.splitlines())
1219+
assert record["state"] == "failed" and record["attempt"] == "1"
1220+
assert record["generation"] == "7" and record["operation"] == "op-test"
1221+
assert "no child was launched" in record["reason"]
1222+
assert "retry:" in result.stdout
1223+
1224+
1225+
def test_handoff_target_is_resolved_after_waiting_for_writer_mutex(restart_box):
1226+
box = restart_box
1227+
original = prepare_restart(box)
1228+
assert helper(box, "set-restart-intent", LANE, "ready", "--expect", "pending").returncode == 0
1229+
other = _write(box.wip / "handoffs" / "other.md", "other preserved work\n", 0o600)
1230+
alias = box.wip / "handoffs" / "alias.md"
1231+
alias.symlink_to(original.name)
1232+
prepared = _write(box.root / "prepared.md", "replacement bytes\n", 0o600)
1233+
digest = hashlib.sha256(original.read_bytes()).hexdigest()
1234+
before = (original.read_bytes(), other.read_bytes())
1235+
lock = box.wip / "lanes" / ".lanes-edit.lock"
1236+
lock.mkdir()
1237+
(lock / "pid").write_text(str(os.getpid()) + "\n")
1238+
marker = box.root / "waiting-for-writer"
1239+
real_mkdir = shutil.which("mkdir")
1240+
_write(box.fakebin / "mkdir", f"""#!/usr/bin/env bash
1241+
case "$*" in *.lanes-edit.lock*) touch '{marker}' ;; esac
1242+
exec '{real_mkdir}' "$@"
1243+
""")
1244+
proc = subprocess.Popen([str(box.bin / "lanes-edit.sh"), "publish-handoff", LANE,
1245+
str(alias), str(prepared), "--expect-digest", digest],
1246+
env=box.env, cwd=box.lane_dir, stdout=subprocess.PIPE,
1247+
stderr=subprocess.PIPE, text=True)
1248+
try:
1249+
deadline = time.monotonic() + 10
1250+
while not marker.exists() and time.monotonic() < deadline:
1251+
assert proc.poll() is None
1252+
time.sleep(.02)
1253+
assert marker.exists()
1254+
alias.unlink()
1255+
alias.symlink_to(other.name)
1256+
(lock / "pid").unlink()
1257+
lock.rmdir()
1258+
out, err = proc.communicate(timeout=15)
1259+
assert proc.returncode == 7, (out, err)
1260+
assert "changed before publication" in err
1261+
assert (original.read_bytes(), other.read_bytes()) == before
1262+
assert alias.is_symlink() and alias.resolve() == other
1263+
finally:
1264+
if lock.exists():
1265+
(lock / "pid").unlink(missing_ok=True)
1266+
lock.rmdir()
1267+
if proc.poll() is None:
1268+
proc.terminate()
1269+
proc.communicate(timeout=5)

0 commit comments

Comments
 (0)