Repository navigation
fix(bearings): preserve projections through inventory mismatches - #3129
kunchenguid merged 18 commits into
Conversation
Confidence Score: 4/5The PR should not merge until delayed snapshots can no longer start a cooldown that suppresses the current reconciliation need. The current implementation validates endpoint incarnation but not snapshot freshness or the current mismatch, so an obsolete snapshot can still send and commit the same per-home cooldown that tests show suppresses a newer mismatch. Files Needing Attention: bin/fm-secondmate-reconcile.sh Reviews (3): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile |
| SNAPSHOT_OBSERVATION=$(perl -MTime::HiRes=clock_gettime,CLOCK_MONOTONIC -e \ | ||
| 'printf "%020.0f-%010d", clock_gettime(CLOCK_MONOTONIC) * 1000000000, $$') || exit 1 | ||
| else | ||
| SNAPSHOT_OBSERVATION=$(date +%s%N 2>/dev/null || true) | ||
| case "$SNAPSHOT_OBSERVATION" in ''|*[!0-9]*) echo "fm-fleet-snapshot: cannot create an observation identity" >&2; exit 1 ;; esac | ||
| SNAPSHOT_OBSERVATION=$(printf '%020d-%010d' "$SNAPSHOT_OBSERVATION" "$$") | ||
| fi |
There was a problem hiding this comment.
Observation ordering regresses
After a host reboot, CLOCK_MONOTONIC restarts below the generation persisted before reboot, so the reconcile stale-check rejects fresh mismatch, clear, and retry transitions until uptime catches up. Overlapping snapshots can also be ordered by process startup rather than when each home is sampled, causing a later observation to be discarded as stale.
…nings as repairs A backlog-vs-metadata inventory mismatch inside a secondmate home was being reported as "we cannot read that home", which discarded that home's open captain calls, queued work, landed work, and live workers from the whole Bearings digest. The main home already treats the identical mismatch as a harmless disclosure; this makes the secondmate path agree. - fm-fleet-snapshot.sh: the invalidity gate now passes orphan_in_flight, unowned_current, and terminal_in_flight through the partial-structured carve-out alongside child_current_unavailable, so those homes keep their decisions, holds, queued, landed, and live work and leave unreadable[]. missing_backlog and unstructured_current stay on the discard path, because there the backlog itself is untrustworthy. - fm-fleet-snapshot.sh: the same three kinds no longer collapse the home's own classification to "unknown"; the real captain_decision / active_child_work / externally_held classification survives and invalidity carries the warning. An unavailable child state still collapses it, including when a mismatch masks it under strict-invalidity precedence. - secondmate_landed.partial now keys on partial-structured trust rather than an unknown state, so an inventory-mismatch home is still disclosed as partial. Ask the home that owns the wrong books to fix them: - bin/fm-secondmate-reconcile.sh sends exactly one reconcile instruction per mismatch episode through the ordinary steering transport. A persistent mismatch keeps its episode identity and never re-nags; a changed mismatch earns one more ask; a repaired one is forgotten so a recurrence is asked about again. The parent never touches the mate's own files, and a failed send records nothing so the next run retries it. Give integrity warnings their own look on the board: - charted rows take an optional kind of "queued" (the default) or "warning". A warning badges "needs repair" instead of "waiting" and is excluded from the Charted Next count, so alarms stop reading as dispatchable queued work. No fifth board section, and every existing payload stays valid. Tests pin the new policy behaviorally: the retained surfaces and classification for all three mismatch kinds, the still-discarding unstructured_current and missing_backlog cases, the once-per-episode reconcile ask through real durable steering records, and the board rendering exercised through the shipped template under a minimal DOM shim.
…k reconcile background
…r cooldown The reconcile ask needed to fire once per problem without nagging on every recap. The episode-precise record that tried to do that had to be correct in every direction at once - order two concurrent snapshots, tell a repair from a new problem, and never lose a clear - and each direction it got wrong either swallowed a nudge or sent a duplicate. A per-home cooldown removes the whole class. One durable timestamp per home, one nudge per four hours, and nothing to get stale, mis-order, or mis-classify: a home in mismatch is asked once, later recaps stay silent, and a mismatch still sitting there after the window earns one gentle re-nudge. - bin/fm-secondmate-reconcile.sh: state/<id>.reconcile-nudged holds the epoch second of the last ask; FM_RECONCILE_COOLDOWN_SECONDS names the window. The episode identity, ordering generation, pending/clear transitions, and delivery-identity reuse are all gone. A known-undelivered send starts no cooldown so the next run retries it; an unconfirmed one does, because a duplicate ask is worse than one the mate may already hold. - bin/fm-fleet-snapshot.sh, bin/fm-bearings-snapshot.sh: drop the snapshot `observation` monotonic identity, which existed only to order those records. - bin/fm-teardown.sh: retire the cooldown record with the endpoint's other runtime artifacts, so reseeding a retired id is not silenced by its predecessor's window. The inline durable fire-and-forget send is unchanged, and the projection fix and the warning surface are untouched. Tests follow the behavior: the cooldown suite now pins one ask per window, the re-nudge after it, the four-hour boundary, per-home independence, and that the ask stays out of a re-ring ladder that still rings an ordinary steer beside it. The obsolete observation-ordering test is deleted with the machinery it covered.
3607c1b to
8fc89f3
Compare
Intent
Reverse the Bearings projection-bug policy so a secondmate home with a mere backlog-vs-metadata inventory mismatch is no longer treated as fully unreadable, plus two captain-added companions and one captain-directed simplification, all in this one PR (#3129).
BACKGROUND: bin/fm-fleet-snapshot.sh's invalidity gate discarded ALL of a home's structured surfaces whenever any inventory-mismatch kind was set, and forced state:'unknown'. A scout reproduction showed this hid 28 open captain calls and a green PR awaiting merge across three working homes, while the main home already treats the identical mismatch as a harmless disclosure. The captain chose to reverse the strict-invalidity policy PR #875 deliberately introduced.
FIX A: the invalidity gate carves orphan_in_flight, unowned_current, and terminal_in_flight into the existing child_current_unavailable carve-out, so those homes stay partial-structured, keep decisions/holds/queued/landed/live work/endpoints, and leave unreadable[]. missing_backlog and unstructured_current DELIBERATELY stay on the discard path; their existing tests stay green untouched.
FIX B: those three kinds no longer collapse the summary state to 'unknown'; the real captain_decision / active_child_work / externally_held classification survives and invalidity carries the warning. Deliberate refinement: an unavailable CHILD state still collapses to unknown even when a mismatch masks it under strict-invalidity precedence, because a home with an unreadable child cannot be classified confidently. Consequently secondmate_landed.partial[] keys on partial-structured TRUST rather than an unknown state, behavior-identical for every pre-existing case.
CAPTAIN ADDENDUM 1 - RECONCILE HOOK: when the snapshot detects an inventory mismatch in a secondmate home, the parent asks THAT mate to reconcile its own books. Constraints: never auto-edit the mate's queue or metadata from the parent, never block the digest, use the existing steering transport, and do not nag on every recap.
CAPTAIN ADDENDUM 2 - WARNING SURFACE (C-small): optional 'kind' on board charted rows, default 'queued' plus 'warning'. Warning rows badge 'needs repair' (not 'waiting') and are EXCLUDED from the Charted Next count, including the charted_more truncation count. The captain explicitly ruled OUT a fifth board section. Optional-with-default keeps every existing payload valid.
CAPTAIN-DIRECTED SIMPLIFICATION (this is the current shape - earlier review rounds are superseded): the reconcile dedupe is a per-home COOLDOWN, not an episode-precise record. Prior rounds built an episode identity plus a monotonic snapshot 'observation' ordering generation plus pending/clear transitions, and each round surfaced another direction it got wrong - a clear hidden by strict-invalidity precedence, then an unsupported kind read as a clear, then non-atomic clear transitions. The captain judged the mechanism itself wrong and directed replacing it entirely. Now: one durable per-home timestamp at state/.reconcile-nudged, one nudge per FM_RECONCILE_COOLDOWN_SECONDS (4 hours, a named constant), a gentle re-nudge if the mismatch outlives the window, and nothing that can go stale, mis-order against a concurrent snapshot, or mis-classify a repair. The episode identity, ordering generation, snapshot 'observation' field, and pending/clear machinery are all DELETED, and the test that only covered the observation ordering is deleted with them. A known-undelivered send starts no cooldown so the next run retries; an unconfirmed send (exit 3) does start one, because a duplicate ask is worse than one the mate may already hold.
The reconcile send stays INLINE (no background child, no harness-native background task, no terminal-backed dispatcher: Pi has no native background and Codex forbids it, and an untracked child can be reaped to zero asks). It uses fm-send.sh's fire-and-forget plane, which arms no pending-reply expectation and is excluded from the steering inbox's re-ring and escalation ladder, because the parent expects no reply. bin/fm-teardown.sh now retires the cooldown record with the endpoint's other runtime artifacts so a reseeded id is not silenced by its predecessor's window.
OUT OF SCOPE, do not implement: a fifth board section; the parent-pointer backfill; raising FM_SNAPSHOT_SECONDMATE_TIMEOUT (a real but separate latent trigger); and the underlying per-home bookkeeping drift in the affected homes, which is those homes' own data, not code.
TESTS: assertions that pinned the OLD discard policy for orphan_in_flight, unowned_current, and terminal_in_flight were INVERTED on purpose across three suites, including one that demonstrates Fix B by asserting a home keeps active_child_work and its live worker through an orphan mismatch. unstructured_current and missing_backlog assertions are untouched and still pass. The reconcile suite drives the real fm-send inbox plane against a fake tmux backend and asserts durable steering records for the cooldown contract; its fire-and-forget test deliberately drives the signals apart, asserting the reconcile record stays quiet in a ladder that still returns 'ring' for an ordinary steer beside it, so the quiet verdict cannot pass vacuously. tests/fm-bearings-board-render.test.sh builds a real board and executes the SHIPPED template under a minimal DOM shim, asserting rendered badges, the stat strip, and the empty state rather than template source text.
This is firstmate's own shared tracked material, so firstmate-coding-guidelines applies: one sentence per line in tracked Markdown, plain dash never an em dash, no agent co-author, shellcheck-clean bin scripts via bin/fm-lint.sh, colocated tests named .test.sh, and tests that exercise behavior through an executable interface rather than asserting implementation source bytes. Note .github/workflows/ci.yml pins exact test counts (42 bearings, 15 fleet-view); the deleted observation test restores the bearings count to 42, so no workflow change is needed.
What Changed
needs repairwarnings excluded from Charted Next counts and truncation totals.Risk Assessment
🚨 High: The reconcile path can still stall digest generation, issue multiple asks inside one cooldown window, re-ring acknowledged requests, and omit supported legacy mates.
Testing
Targeted snapshot, board, reconcile, inbox, local/remote transport, and fleet-view tests succeeded; end-to-end evidence shows the rendered warning UI excludes repair warnings from Charted Next and the reconcile path durably sends once before entering cooldown.
Evidence: Portable rendered Bearings board HTML
Source: Portable rendered Bearings board HTML
Evidence: End-to-end reconcile transcript with durable fire-and-forget envelope and immediate cooldown behavior
Source: End-to-end reconcile transcript with durable fire-and-forget envelope and immediate cooldown behavior
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-secondmate-reconcile.sh:214- The cooldown commit occurs after fm-send releases the endpoint metadata lock. A teardown can then acquire that lock, remove the inbox and reconcile record at bin/fm-teardown.sh:2822, and finish before this line recreates<id>.reconcile-nudged; reseeding the same ID within four hours is consequently suppressed by its predecessor. Commit or discard the cooldown while holding the lifecycle metadata lock and revalidate that the same endpoint still exists, so teardown and cooldown retirement serialize at their shared boundary.docs/scripts.md:21- The script catalog says reconciliation applies to a “new inventory-mismatch episode,” but the implementation and required contract now use a per-home four-hour cooldown independent of episode identity. Update the purpose clause to describe cooldown-limited nudges.🔧 Fix: Serialize reconcile cooldown commits with mate lifecycle
2 errors still open:
bin/fm-secondmate-reconcile.sh:204- The required criterion says the reconcile hook must “never block the digest,” but the inline path now uses unboundedfm_lock_acquire_waiton the lifecycle control lock. A long-running teardown or relaunch therefore stalls/bearingsindefinitely before digest composition. Use a non-blocking or tightly bounded acquisition and leave the cooldown unset so a later recap retries.bin/fm-secondmate-reconcile.sh:218- The lifecycle serialization still does not verify that the endpoint matches the incarnation sampled by the snapshot. A snapshot can observe mate A, teardown and reseed the same ID can complete before line 204 acquires the lock, and this line then sends A's stale mismatch to mate B and records B's cooldown. Carry the sampledspawn_genthrough the snapshot/reconcile row and compare it under the lifecycle lock before sending or committing the cooldown.🔧 Fix: Reject stale reconcile snapshots across mate reincarnations
3 issues (2 errors, 1 warning) still open:
bin/fm-secondmate-reconcile.sh:194- The required hook must "never block the digest," but the inline path waits without a bound on the reconcile, lifecycle-control, and metadata locks, and holds the first two across fm-send. A teardown, concurrent recap, or delayed remote send can therefore stall /bearings indefinitely. Use non-blocking or tightly bounded lock acquisition and leave the cooldown unset so a later recap retries.bin/fm-secondmate-reconcile.sh:188- The cooldown timestamp is captured once before processing any homes rather than when each nudge is delivered. If an earlier lock or remote send takes two hours, a later successful nudge receives a timestamp two hours old and can be sent again after only two more hours; cooldown checks for later homes also use stale time. Read the clock separately for each check and commit the successful nudge's actual delivery-time timestamp.bin/fm-pending-reply-lib.sh:241- The captain-directed simplification says the reconcile pending/clear machinery is "all DELETED," but this change still expands the shared pending-reply API with caller-selected correlation IDs, while bin/fm-send.sh:677-704 retains the associated FM_SEND_IDEMPOTENT bypass for ordinary reply-bearing sends. Fire-and-forget never calls this pending-reply path, and no current caller supplies FM_PENDING_REPLY_CORR_ID, so these are residual shared-transport changes from the superseded implementation rather than part of the cooldown design. Remove them or explicitly authorize retaining this broader behavior.🔧 Fix: Start reconcile cooldown after delivery completes
2 issues (1 error, 1 warning) still open:
bin/fm-secondmate-reconcile.sh:193- The required hook must “never block the digest,” but the inline path waits without bounds on the reconcile lock, lifecycle-control lock, and metadata lock, and holds the first two across fm-send. A concurrent recap, teardown, or delayed remote send can therefore stall /bearings indefinitely. Use non-blocking or tightly bounded lock acquisition and leave the cooldown unset so a later recap retries.bin/fm-pending-reply-lib.sh:241- The captain-directed simplification says the reconcile pending machinery is “all DELETED,” but this change still adds caller-selected pending correlation IDs, while bin/fm-send.sh:677-704 retains the associated FM_SEND_IDEMPOTENT bypass for ordinary reply-bearing sends. Fire-and-forget does not use this pending-reply path and no production caller supplies FM_PENDING_REPLY_CORR_ID, so remove these residual shared-transport changes or explicitly authorize retaining them.🔧 Fix: Keep reconcile sends nonblocking and remove pending residue
4 errors still open:
bin/fm-secondmate-reconcile.sh:249- The required criterion says reconciliation must “never block the digest,” but this inline call waits for all of fm-send, including synchronous backend doorbell operations and remote SSH delivery, with no deadline. A stalled backend command or unreachable remote can therefore stall/bearingsindefinitely. Bound the send operation or split the required durable enqueue from best-effort notification while preserving the explicitly required inline design.bin/fm-secondmate-reconcile.sh:247- Releasing the reconcile lock before sending leaves the one-nudge-per-window invariant unclaimed. Snapshot A can pass with orphanxand stall, snapshot B can pass after the mismatch changes to unownedy, and both derive the same delivery ID from the absent cooldown. Because inbox idempotency compares the full differing message bodies, both records are written and both asks are delivered within one window. Atomically claim the delivery identity at the durable enqueue boundary and distinguish newly-created from existing delivery without holding lifecycle locks across fm-send.bin/fm-send.sh:916- The new local fire-and-forget idempotent path can return a record already moved intohandled/, but unlike the remote path it still rings it. Concrete sequence: delivery succeeds, the mate handles the record, cooldown commit reportssent-unrecorded, and the next recap retries the same delivery. The resulting doorbell points athandled/*.msgand can make the mate act on the acknowledged reconcile request again. Mirror the remote handled-record guard and return success without ringing.bin/fm-secondmate-reconcile.sh:178- The required hook asks every detected mismatching home, but this filter silently drops snapshots whose secondmate metadata predatesspawn_gen. Legacy metadata without that field is explicitly supported elsewhere, so an upgraded long-lived mate can expose a mismatch yet receive zero reconcile asks. Either carry a supported legacy incarnation identity or explicitly obtain authorization to exclude legacy endpoints.✅ **Test** - passed
✅ No issues found.
bin/fm-test-run.sh tests/fm-bearings-snapshot.test.sh tests/fm-secondmate-reconcile.test.sh tests/fm-bearings-board-render.test.sh tests/fm-bearings-board.test.sh tests/fm-task-inbox.test.sh tests/fm-send-remote-delivery.test.shbin/fm-test-run.sh tests/fm-fleet-snapshot-view.test.shBuilt a realfm-bearings-board.v1throughbin/fm-bearings-board.sh buildand rendered it in headless Google Chrome.Manually drovebin/fm-secondmate-reconcile.sh notify --snapshottwice through the real durable inbox plane, verifying one fire-and-forget record and cooldown suppression on the immediate recap.✅ **Document** - passed
✅ No issues found.
🔧 **Lint** - 1 issue found → auto-fixed ✅
🔧 Fix: Fix reconcile test subshell lint warning
✅ Re-checked - no issues remain.
✅ **Push** - passed
✅ No issues found.