ops chunk verify does not read the v1.0.0 volume directory layout: on a
healthy volume it reports a missing VOLUME, or (by its full name) false
identity findings. Remove its steps and claims from the guides and the
README, and state the limit in the release note.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The untested replica wipe needs a --durable-root that holds that volume
only: the data files' names can match another volume's in a shared root.
It removes the data files and the epoch table and keeps the replica floor.
Exit 75's causes are examples, assignment_timeout added. The blocked reads
with kernel defaults are 552 s and 614 s as recorded; the slowest guest
answer during a store outage was measured once and its record not kept.
The cut's ~30 s answer is the chunk upload deadline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Removed GC and --grace text replaced by the holder's cleaning; the replica
wipe scoped to that volume's own files; outcome_unknown on a restore
target's delete means I/O stopped until settlement; the recovery point is
the last successful snapshot, not a one-day bound; snapshots above about
150 GiB changed need several requests and the schedule retries by itself;
Kubernetes timings scoped to NVMe/TCP; exit 75's causes; the restore CLI
row; the per-cut metadata depends on the volume name length; connection
age with gRPC jitter; the cluster-spec identity cure needs a restart;
throughput and memory figures qualified; the upgrade wording.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxNewVolumeBytes is 256 GiB (65,536 chunks of 4 MiB), derived from the
measured number of chunks a commit checks within one 2 s update of HEAD,
halved and rounded down. The release note states the limit, why, that a
restore target takes its source's size, and that it is planned to be
removed in 1.0.1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The three servers' port pairs were picked together before the master
started, and the filer binds its pair seconds later; a listener that
appears in between (another job's weed on the same host) took the filer's
gRPC port. Each pair is now picked right before its server starts. A
cluster with a fault-injection filer front gets the same fresh-ports
retry: its front is built again on each start's ports.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CreateVolume and the cluster-spec start check refuse a new volume above
geometry.MaxNewVolumeBytes with ErrVolumeTooLarge, naming the size and the
maximum, before any record or store exists. The check is at creation
only: a volume that already exists keeps opening under the uint32-LBA
limit. The value is a placeholder (MaxVolumeBytes) until it is set from
the measured capacity limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A scheduled snapshot or periodic cut refused because an earlier HEAD
commit's outcome is unresolved logged only the raw error. Every later
cut, snapshot and detach of the volume is refused until that settles,
so the line now names the state (PendingUnresolved), its cause and the
cure, once per attempt, never per write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests and ledger only; the product code is byte-identical.
- The cap oracle is the literal 32 (a 32 -> 64 change of the constant
fails it: 64 in flight).
- Every wait is bounded, and each control's cleanup opens its gates,
cancels and joins the commit, so a failing control returns promptly.
- The cancel control holds every admitted lookup past the cancellation
until the test opens their exit: a commit that returns before that did
not join them (a removed-join mutant fails), HEAD takes no update, and
a keep-admitting mutant starts 502 lookups.
- The order control holds the earlier lookup until the later failure has
fully returned and nothing else is in flight (a first-to-finish mutant
fails both ways).
- invariants.md: the wait rows name the caller-held LayoutRemote.mu
(CASHead, CommitPendingSnapshot).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tests only, plus the ledger; the product code is unchanged.
- TestCommitLookupsNeverExceedTheCap: every lookup is held until the cap
is reached; no 33rd starts (a cap-33 mutant fails it).
- TestACancelledCommitStopsJoinsAndWritesNothing: cancelled before any
lookup and mid-flight, the commit returns within a bound with no lookup
still running, admission stopped and HEAD not written (a mutant that
keeps admitting after a failure starts 502 lookups and fails it).
- TestTheEarliestFailureByPositionDecidesTheError: of two failures the
earlier position wins, whichever finishes first (a first-to-finish
mutant fails it both ways).
- invariants.md: the admission and join waits of allOwnedBySession in
C.W, and the scale, detach and control tests on
INV-SNAPK-COMMIT-REACH-001.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Once a lookup fails, no new one starts: lookups start in order, so every
object before the failure has started and is waited for, and the first
failure in order is still the one reported.
The test object store's Stat is now safe for the concurrent lookups (its
hook runs outside the lock), and TestRunCommit_LooksUpOnlyWhatIsNew
compares the set of objects looked up, not their order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RunCommit checked every new own chunk, every segment and the root with
one filer lookup each, one at a time, before its conditional update. The
work grows with the proposal and the cut's deadline does not: a first
snapshot of a 1 TiB volume names all 262,144 chunks, and each attempt
(and each re-proposal, and a restart's next commit) ran out of the 5 min
cut context around chunk 250k, so no retry could ever land.
The check now runs at most 32 lookups at once. It is unchanged in what
it decides: every object must be written by this session and unmarked,
the first failing object in the same order decides the error, and no
update is issued unless all pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A start whose master gRPC port is held by another listener never brings
up its filer; the wait for a listening server stopped the test with
t.Fatalf before the fresh-ports retry could run. The start now returns that
error, so it is discarded and started again like a start that never
accepts a write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockmaster holds a best-effort volume on a lost primary; only the
operator's forced failover moves it, which may lose the writes
acknowledged last.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
--chunk-capture-interval defaults to 0 (no timer); when set it must be at
least 5 minutes. The design text still said 15 minutes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A best-effort write waits for no replica, so a replica whose connection
dropped can keep showing healthy while it misses writes; use sync-quorum
when the replicas must hold the data.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A rerun finds the chunks a timed-out request already uploaded and sends
only the rest. With --host-limit-dir set, uploads are paced at about
16 MiB/s per volume and charged for present chunks too, so more than about
4.7 GiB changed cannot finish within 5 minutes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A snapshot takes about 2 s per GiB changed since the last cut; the CLI
waits 60 s by default and the server at most 5 minutes per request.
State the answer codes of a timed-out request, what it leaves, and that a
rerun with the same name is the next step.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Durability states the recovery point: a stopped volume keeps what it
acknowledged; a lost host comes back from its last cut, which with the
defaults can be up to a day old; --chunk-capture-interval (at least 5
minutes) or a snapshot before risky work makes it newer.
- Kubernetes is an alpha in v1.0.0 (lab clusters, not production; no
backup, snapshot or restore claimed), and its CSI node's plain connect
holds a pod's I/O about 600 s, or some 13 minutes for a powered-off node.
- The SeaweedFS filer is a single point of availability for cuts,
snapshots and moves.
- The connect waits say which case each is for: 181 s for a stopped
holder with its host up (the standalone guest), 464 s for a powered-off
host and a guest on another host.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A refused restore answers not_admitted after a misleading "layout store
not ready:" prefix and leaves the target name bound (target_exists):
restore under another name.
- A delete refused with snapshot_has_dependents has already reserved the
volume: it does not serve again.
- A volume created at run time and not in the cluster spec is served only
with --lifecycle-product-loop-interval set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The release note for v1.0.0: the single-replica walstore-chunk volume is
the supported configuration (store layout, upgrade, durability and
start-up, cleaning, authentication, limits, what is not in the release,
operator rules, known limits), and replicated volumes are a preview with
their own note. Every flag, default, limit, exit status and refusal text
named here was checked against the release candidate's code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
v1.0.1 is planned to support RF3 sync-quorum installed on hosts (writes
continue through one replica's fault, which returns by itself) and RF2
sync-quorum with its limit (no acknowledged write lost, automatic failover,
writes stop while either replica is out); sync-all and Kubernetes RF3 stay a
preview; a partitioned old primary may serve older reads until its lease
ends.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With a high ephemeral lower bound the weed pair range ran to 40000, so one
shard's HTTP slice (20000-29999 for shards 1-2, 30000+ for shards 3-4)
could meet another shard's gRPC ports (HTTP + 10000). weedPairRange caps
the HTTP range at 30000, below every gRPC port, and below the ephemeral
range less 10000 when that leaves room (the Linux default, 32768, still
gives 20000-22767). TestWeedPairSlicesNeverMeetAcrossShards checks every
pair of shards' HTTP and gRPC slices for ephemeral bounds from 28000 to
61000; with the old cap it fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The process-level job ran its 44 named tests in sequence, about 53 min of
the CI time. They now run in 4 parallel shards in the same job, so the
required check keeps its name and its gate: shard-named-tests.py splits
the names file by each test's last measured time
(.github/process-level-seconds.txt; longest first into the least-loaded
shard; about 787 s each), each shard runs run-named-tests.sh with its own
slice of the test port ranges (SWBLOCK_TEST_PORT_SHARD) and its own TMPDIR,
and required-tests-check.py then judges every named test from all the
shards' events and statuses. shard-named-tests-test.py runs in the gate's
self-test step.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Several process-level test binaries can now run in parallel on one host:
with SWBLOCK_TEST_PORT_SHARD=k and SWBLOCK_TEST_PORT_SHARDS=n, the harness's
random port pickers (handoffAddress, the head-size pickers, and the weed
pair picker's usable range) draw only from the k-th of n equal slices, so
two shards never pick the same port. Unset, the whole range, as before.
TestTestPortSpanGivesEachShardItsOwnSlice covers the slices and the
fallbacks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
v1.0 is two designs: the single-replica walstore-chunk volume with the
object store (snapshots, restore, moves, object-store copy) and replicated
volumes on local stores without any of those. walstore-chunk refuses
replication at start and on any assignment with replica slots, because a
chunk snapshot takes its position from the local log, which replicas may
not hold. The preview section and the release note say so.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Acknowledged data is kept in the acknowledging modes only; best-effort
can lose the writes acknowledged last in a failover.
- Wipe and add again is written out (stop the unit, clear its
--durable-root, start it again; the replica rebuilds empty) and marked
as not a tested procedure in this preview; an interrupted re-add needs
another wipe.
- --wal-retention-lsns does not help in this release.
- Kubernetes has no remedy for a left-out replica in this preview.
- The release note says no store format change is planned for the
release that lifts the preview, as a plan, not a guarantee.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The operator guide gains "Replicated volumes (preview)", the standalone
page's replicated section points to it, and the release notes gain a
note. The limits, in operator terms: under a writing guest a replica that
misses writes (restarted, or fenced by a failover) is not caught up by
itself and must be wiped and re-added; a durability shortfall reaches the
guest as an immediate I/O error, not a wait; sync-all refuses writes while
any replica is down; a target that is no longer the primary does not fail
the guest over to another path (no multipath in v1.0); the same holds on
Kubernetes RF3. Acknowledged writes read back intact throughout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The failover text covered only a lost host. When only the primary's
holder stops, the guest is still running and its I/O waits and then fails
as described (or completes if the holder restarts first); either way the
guest is started on the new primary's host after a failover.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A standalone guest runs on the volume's primary host and goes down with
it, so the failover step is to start the guest on the new primary's host,
not to disconnect a controller first; the disconnect step is dropped. Both
measured timings stay as facts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Kernel defaults are 60 attempts (600 s / 10 s): about 600 s when the
holder's host refuses the connection, and some 13 minutes (60 x (10 s +
the ~3 s connect timeout)) when it is unreachable, marked derived. The
Kubernetes paragraph says the same instead of "up to 600 s".
- Each case names its deployment: a standalone guest connects over
loopback and meets the stopped-holder case and the disconnect step; the
unreachable-host case is a guest on another host, in v1 a Kubernetes pod.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Measured with the guide's options (ctrl-loss-tmo 180, reconnect-delay 2,
fast_io_fail_tmo off): a stopped holder process refuses each attempt at
once, and a pending write fails with EIO after 181.5 s (90 attempts 2 s
apart); a powered-off or unreachable host answers nothing, each attempt
waits for the connect timeout (about 3 s), and the write fails after
464 s (kato + 90 x (2 s + connect timeout)). Linux bounds the retries by
count, not by time.
After a failover the guest's first step is nvme disconnect of the lost
primary's controller: its pending I/O then fails at once (EIO 1.5 s
after the disconnect) instead of after up to 464 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The harness checks each weed port pair free and releases it before weed
binds it, reserving it only inside the test process. On a runner host shared
with another job, a port can be taken in between; the master then cannot
reach the volume server's gRPC port and the cluster never accepts a write,
failing the test as an environment flake.
A start whose probe never accepts a write is now stopped (each process's log
tail logged) and the cluster is started again on fresh ports in a
subdirectory of the same root, up to 3 starts. A cluster with a
fault-injection front keeps one start.
TestWeedStartAgainOnFreshPortsWhenAPortIsTaken holds the first start's
volume gRPC port with a plain HTTP server (as another job's listener): the
first start fails as the CI runs did, and the second accepts a write. With
one start only, the test fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The operator guide says what to do when a snapshot answers head_conflict
(retry with the same name) and, in this release, when that retry answers
internal "not in HEAD after its commit" (retry once more): the data is
committed either way and the name exists only after a request succeeds. A
retry that names the snapshot at once is planned for 1.0.1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The empty-snapshot test reads the named snapshot's own root from the
store: block 1 holds the write, block 2 (unwritten, same chunk) is zero.
- KNOWN DEFECT (v1, fixed in 1.0.1), pinned: a snapshot whose commit loses
to a genuine concurrent HEAD writer (an operator deleting snapshots
during it, more often than the commit's bounded retry) answers
head_conflict with HEAD's image and names unchanged; the immediate retry
commits the requeued data without the name (HEAD idle, position moved)
and answers "not in HEAD after its commit"; a further attempt names it.
When the retry is fixed, the test fails and is turned around.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every assignment to ownGen in layout_remote.go is listed with its function
and whether the same statement records the image (seen): the two commits
that change HEAD's image record it; the session begin, the abort and end of
a dead session or cleaning, and the cleaning's begin and end change only
HEAD's activity. A new own write fails the census until it is classified.
Undoing the empty-image fix, or adding an unclassified site, turns it red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The first snapshot of a volume never written names its empty image with a
commit of its own, which gives HEAD its first root. The commit recorded
only its own generation, so the view kept the rootless image. The next
HEAD write by anyone else (a snapshot delete, through the holder or the
store) then looked like an image change: the generation the engine sees
moved, and the next cut lost its commit with head_conflict; its retry
answered internal ("not in HEAD after its commit").
CommitPendingSnapshot now records the image it committed, as the cut's
commit does, so a later write that leaves the image in place does not move
the engine's generation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lost-reply tests now run through the executor's registered callbacks:
a proxy forwards every frame to the replica (which admits and acts on it)
and discards its replies, so the fence and the catch-up really fail at
the sender; the failure is forwarded and the healthy verdict that
follows heals the peer, and live traffic is acknowledged. A behind peer
(R < H) is not healed by the healthy verdict, heals only through a
catch-up's registered close (every block equal to the primary's), and
then takes live traffic. The census now covers every reference to the
session order in the adapter's production source (constructor binding
and each draw by case), with helper, alias and outside-a-case controls.
Each control is red against its mutant: no afterFence wiring, no
afterSessionClose wiring, no re-draw on failure.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The replica takes a session's lineage when it admits it; the sender saw
only the exchange's result. A fence the replica admitted whose reply was
lost, or a recovery session whose close failed, left the replica above
the live session with no re-draw. The fence-complete and session-close
callbacks now re-draw the live session above the session on any outcome
(a completed recovery still advances the cursor and heals). A guard test
over the adapter's draw switch lists every command kind that draws a
session and what re-draws after it; the refresh's log line names the
session and the reason instead of 'after recovery='.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fence mints its own session from the peer's one session order; once
the replica acknowledges it, the replica holds the fence's lineage, above
the peer's earlier live session, and refuses every later barrier or ship
on that live session as stale. A rejoining replica already at the
primary's end (no recovery session, so no post-recovery refresh) was
never healed. The fence-complete callback now calls the same
RefreshLiveShipSessionAfter the recovery close uses, after the fence's
barrier was acknowledged and before the engine publishes healthy.
The replica's stale-refusal log lines now name their cause (a primary
listener, an epoch below the floor, no role yet, below the held lineage,
or the same lineage with another frontier hint).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replica already at the primary's end is fenced at the peer's epoch with
a session the fence mints, above the live session drawn at the peer's
creation; the replica then holds the fence's lineage, and the engine's
healthy verdict, a barrier on the live session, is refused as stale:
the peer stays degraded. A second test fixes the order: a live session
re-drawn before the fence is acknowledged makes the replica refuse the
fence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The classification moves into .github/scripts/docs-only-scope.sh: it
writes git's NUL-delimited list to a file and reads it to the end, so no
pipe stops early and a writer's error cannot read as "no other file". A
failed git diff exits nonzero, and the step then runs the tests.
docs-only-scope-test.sh runs first in the step, against real commits:
docs only, docs and a test file, no file, a docs-like prefix, README, a
move out of docs, a docs deletion, 20000 docs files with one other file
last, an unknown revision (an error), and that test.yml applies the check
only to a pull request's process suite and gates all four process steps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A pull request whose changed files are all under docs/ runs no product
code the process-level tests could exercise, yet waited about 55 minutes
for them. The process job now compares the merge commit with its base
parent; when every changed file is under docs/ it prints "skipped: docs
only (N files under docs/)" and skips the SeaweedFS fetch, the builds and
the named tests, so the required check still reports success. Pushes to
main always run them, as does any pull request with another changed file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Against the real master: a volume-delete refused with
snapshot_has_dependents has already reserved the volume, so workspace
show answers "workspace: volume is being deleted" (exit 1) and HEAD with
its snapshots is unchanged. The control, a delete refused before any
reservation (an established volume under a live lease), leaves show
answering the volume normally. The volume-lifecycle row cites it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A holder keeps serving for the rest of its lease during an outage, and
the restart barrier is a lower bound, so the outage paragraph states the
known lower bound of the guest's wait and that an outage longer than
ctrl-loss-tmo less the barrier can fail guest I/O, without a threshold
number.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A run with exactly --ctrl-loss-tmo=180 --reconnect-delay=2 (no
fast_io_fail_tmo): the holder killed and started again 5 s later, a
pending write completed after 6.1 s with no error; the holder kept away,
the write failed with EIO after 181.5 s. The table is no longer marked
derived, not yet run. The failover time stays derived.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The ctrl-loss-tmo derivation shows its sum (re-grant, the start's grant
wait, the unit restart: about 100 s) and the table is marked derived,
not yet run.
- reconnect-delay is a retry interval.
- The blockmaster-outage sum: 20 s + the outage + 50 s, so more than about
110 s outlasts 180 s; the link names the restart text.
- After a failover the options do not redirect the controller: a
standalone guest reaches only its own host's loopback target, so it must
run on the new primary's host and connect there (how to tell which host).
- The standalone connect command carries the same options.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The operator guide gains "Host connect settings": the nvme connect
options ctrl-loss-tmo, reconnect-delay and fast_io_fail_tmo, values
derived from the longest wait for a target to serve again (the re-grant
barrier, 65 s with default flags), what the guest sees with these values,
with the kernel defaults (up to 10 minutes) and with values too short
(I/O errors reach the filesystem), how a long blockmaster outage relates,
and that the CSI node connects with the kernel defaults, so a pod whose
holder does not return is recovered by recreating it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The extent-writer census also inspects declaration initializers and keys
each site by its receiver-qualified owner, with negative controls for a
package-level method-expression alias, a package-level closure and a
same-named method on another receiver. The paused-cycle test bounds its
entry and completion waits, and releases and joins the cycle (bounded)
on any failure before the store's cleanup; under an injected failure
while the cycle is paused it ends at once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A flusher cycle that started before the owner armed the hold (the flusher
runs from open) could pass the entry check, pause, and then drain the
dirty map Recover filled after the hold. The hold is now checked under
store.mu with the dirty-map snapshot: Recover takes store.mu after the
hold is set, so such a cycle sees it (red locally without this: the
paused cycle advances the checkpoint 1 -> 2 before attach).
writeExtentUnlocked refuses while held and no layer is attached, so a
writer the census misses fails loudly. The census counts every reference
(calls, aliases, method expressions) per site, with negative controls.
Tests: the provider holds on create and open (walstore-chunk only); the
post-attach drain advances the checkpoint and a fetch of the chunk keeps
the now-local block. block-design.md's WAL lifecycle shows the hold.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After a crash, Recover replays a synced write into the dirty map; the
flusher drained it to the extent before the chunk layer attached, so the
block was not marked local and the next fetch of its absent chunk
installed the snapshot's block over the acknowledged write.
The durable provider now holds the drain on a walstore-chunk store before
Recover (HoldExtentDrainUntilChunkLayer); every flusher drain, the stop's
included, does nothing while held; the replayed write stays in the WAL
and is served from the dirty map; attach releases the hold, so the first
drain marks it local. A held store takes no BASE. Writers of the extent
are enumerated by a guard test; INV-CHUNK-LOCAL-BEFORE-FETCH-001.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A volume-delete refused with snapshot_has_dependents has already
reserved the volume: it does not serve again; delete or release the
restored volume, then rerun with the same request id.
- A sync-quorum volume gets its new primary about 30 to 35 s after its
host is lost with default flags (freshness window, then two probe
rounds of at most 2 s each).
- The ack profile change order: stop the replicated volumes, change both
flags, restart blockmaster, start the volumes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A synced write into an absent chunk, a crash, a reopen: the flusher
drains the replayed write to the extent before the chunk layer attaches,
so the block is not marked local and the next fetch of its chunk installs
the snapshot's block over it (reads 0x89, want 0xE9). Adds the owner's
hold call (HoldExtentDrainUntilChunkLayer, a no-op here) and the test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume at the snapshot limit refuses every scheduled snapshot before
its cut, so the schedule would no longer publish the image. The scheduled
pass now runs its ordinary cut after a snapshot_limit refusal and still
records the refusal (status lastFailure snapshot_limit, then
snapshot_overdue).
Tests read the committed image back: after the refusals and the next cut,
and after the scheduled pass at the limit, the distinctive block written
while refused is in the image HEAD names. INV-SNAPK-HEAD-BOUND-001 names
the pre-check, the mapping, the scheduled cut and their tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- best-effort volumes and an ack-profile mismatch are held, not failed
over by themselves (best_effort_no_automatic_failover,
ack_profile_mismatch); blockmaster refuses an unknown
--launcher-replication-ack.
- Change the ack profile only with the replicated volumes stopped; a
primary assigned under another profile does not serve and says so.
- A volume created at run time and not in the cluster spec is served only
with the lifecycle loop on.
- volume-lifecycle: a delete under a live lease answers not_admitted
("deletion refused before persistence"); ordinary snapshots never refuse
a delete, a snapshot with dependents does (snapshot_has_dependents);
blockmaster has no same-host refusal for a forced move.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A snapshot request on a volume already holding the maximum number of
snapshots ran its cut first and met the limit only at the commit. With new
data, the cut committed unnamed; with none, the cut's session stayed open
on HEAD. Either way HEAD moved, and the answer was 500 internal because
the HTTP mapping had no case for the limit or for a taken name.
SnapshotVolume now checks the count under the volume's snapshot lock,
before it names the cut or opens a session, so the refusal writes
nothing. The holder answers 409 snapshot_limit (new code) and 409
snapshot_exists, neither retryable. The in-commit check stays as the
backstop.
Tests: the snapshot past the limit through the real provider, chunk
control and HTTP route answers 409 snapshot_limit with HEAD unchanged
(generation, activity, root, position), with nothing new and with new data
waiting; the provider test changes from "the cut commits unnamed" to the
same; a volume-delete under a live lease against the real master answers
not_admitted with "deletion refused before persistence".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
restartedHolderRefresh decides only when the line it reads is this
replica's at exactly the ask's addresses, and builds ExpectCurrent from
that read, so a move between the tick's address check and this read
yields no refresh rather than one expecting the moved line.
The controller's same-ask dedupe compares the expected line: a refresh
refused because an earlier refresh moved the line is asked again against
the new line instead of being suppressed as a duplicate (red locally
without this: TestControllerReasksARefreshRefusedAfterTheLineMoved times
out waiting for the re-ask).
The host-level stale-refresh test now waits for the publication path's
own refusal of that ask (bounded), instead of a sleep. block-design.md's
authority diagram shows the conditional refresh.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tick read the line twice: its address check, then the refresh, which
built its expectation from the second read while writing the ask's
(source) addresses. With a move between the reads the expectation names
the moved line and the publisher accepts it. After a real clean move, the
source's refresh must not be decided at all.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The publisher refuses an endpoint refresh whose ExpectCurrent (replica,
epoch, and the addresses read) is no longer the volume's line, under its
lock, as it does for a conditional reassign. Both refresh producers name
the line they read: the topology controller's refreshAsk and the product
loop's restartedHolderRefresh. invariants.md: the Bound -> Bound refresh
guard and INV-AUTH-RESTART-REISSUE-001's sites and tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A restarted source holder's refresh, built before the operator's clean
move to another host and applied after it, must not rewrite the moved
line (same replica, next epoch, target addresses) back to the source.
Adds ExpectedLine's addresses and the refresh's decided-against line as
fields, with tests at the publisher (the refresh is refused with
ErrExpectedLineMoved; one decided against the current line applies), the
controller (its refresh names the line it read), and the host (the stale
refresh through the normal publication path after a real clean move).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The control minted its line before the holder started, then ran one
product tick after the start. When the holder had already reported its
process by that tick, the unbound placement went through the controller,
which re-issued the line for that process, and the control passed. The
control now waits for the early line, checks that it names no process,
and runs no tick after the holder starts (the order the fixture used
before), so the holder refuses the line on every run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-WS-REVOKE-ACK-RETRY-001 was inserted inside Part A's M4 table; it
now sits in Part B beside INV-WS-REVOKE-ACK-001, and M4 Fenced ->
Drained, Acked states the retry guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A real guard and the real master: the first ACK gets no answer, either
because its answer is lost after the master committed it, or because the
master's first HEAD read outlasts the guard's 5 s bound. The guard asks
again, its drain ends without error (exit 0, not 75), and the master
holds one ACK with the holder's identity, the stopped generation and the
HEAD position. On the parent commit (one attempt) both end with
DeadlineExceeded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the direct path finds the line current by address but the slot's
reported incarnation is not the line's (a restarted holder, or a move
target whose line names no process), it submits the existing endpoint
refresh (IntentRefreshEndpoint with that incarnation), as the topology
controller does for a static volume (endpointStale, refreshAsk).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A CreateVolume RF1 workspace volume is served only by the product loop's
direct path, which treats a line at the same addresses as current. A
holder restarted there (a new incarnation), or a move's target started
after the move minted a line naming no process, refuses that line and is
never re-issued one. The tests expect the next tick to re-issue the line
for the reporting process (EV+1 naming it), and nothing for the same
report.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A primary line is issued for the process at its endpoints and blockvolume
refuses a line that names no process. For a workspace-bound RF1 volume the
product loop's direct path never re-issues a line whose addresses already
match, so a line minted from a hand-ingested observation before the holder
started was never replaced, loop or not. Both tests now start the holder,
wait until blockmaster observes its slot with its process incarnation, and
only then run the product tick that binds, as production orders it.
SWBLOCK_TEST_EARLY_LINE=1 is the control: the line is minted from a
hand-ingested observation before the holder starts, with no product loop,
as before. Native: lease PASS, control FAIL at "unleased host did not adopt
assignment"; move control FAIL at "source did not serve" with the
empty-process refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The refusal is read once and named first, since it is also why the
durable backend refuses. invariants.md M1 Recovering -> Serving and the
Kubernetes failover diagram carry the primary's profile check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the durable backend wired as the status source (as blockvolume
does), status reports the backend's generic stale-primary reason, not the
profile mismatch naming both profiles.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestBinaryWorkspaceLeaseOptInOwnsCLEANShutdown minted its line from a
hand-ingested observation before the holder started, like the layout move
test, so the holder refused the line that named no process. Both tests now
share runProductLoop (the lifecycle product loop every 100 ms, as
blockmaster runs it) and blockvolumeUnderTest (the gate's prebuilt binary
when SWBLOCK_TEST_BINS is set). The control is now
SWBLOCK_TEST_NO_PRODUCT_LOOP=1, for both tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A line is issued for the process at its endpoints, and a holder refuses a
line that names another process. The test minted the initial line from a
hand-ingested observation before the source started, so it named no
process and the source refused it ("issued for process <empty>"; source did
not serve). The test now runs the lifecycle product loop as blockmaster
does, which re-issues a line once the process reports itself (the initial
line, and a move's target). LAYOUT_MOVE_NO_PRODUCT_LOOP=1 leaves the loop
off and reproduces the refusal (the control). With SWBLOCK_TEST_BINS set
(a gate run) the test uses that prebuilt blockvolume instead of building a
race-enabled one, so the binary it runs is the one the gate hashed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-WS-REVOKE-ACK-RETRY-001: asked again only after no answer
(DeadlineExceeded, Unavailable), within the lease deadline and the 19 s
closeout; the master answers a repeat of a recorded ACK as recorded while
the line is revoking.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every assignment names blockmaster's ack profile; a primary of a
replicated line whose own --replication-ack is another one is not Healthy
(its status names both), so a lost primary that cannot answer
acknowledged under the master's profile. fencedDecision also holds on
the fencing round's own ProfileMismatch, the evidence it counts.
invariants.md: the M3 promotion-candidate row, the MATCH row's fencing
round, and the new INV-PRIMARY-ACK-PROFILE-001; the Kubernetes design
no longer says best_effort is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The survivors' answers cannot show the profile the lost primary
acknowledged under. Adds AssignmentFact.ack_profile (blockmaster's
profile) with tests: an assignment names the master's profile; a primary
of a replicated line in another profile (or under a master that names
none) does not serve and says why, while its own profile or an RF1 line
serves; and a fencing round answered in another profile publishes
nothing, on both gates.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-PROMOTE-FRONTIER-BEST-EFFORT-001 now states the hold (it said the
gate promoted the highest-durable candidate) and names the renamed
product-loop test; INV-PROMOTE-ACK-PROFILE-MATCH-001 is new.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The volume answers each promotion probe with its own --replication-ack;
the probe round names every answer whose profile is missing or differs
from blockmaster's (or an unknown master profile), and both gates hold
such a volume before any fencing round (ack_profile_mismatch), as they
hold a best_effort one. One helper (automaticFailoverHold) decides both,
called before the unsupported gate reads its candidates, so a held volume
always shows why. blockmaster refuses an unknown --launcher-replication-ack.
The best_effort product-loop test now expects the hold.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An ACK call that got no answer (DeadlineExceeded, Unavailable) is made
again until the lease deadline; the master answers a repeat of a recorded
ACK as recorded, so a busy master no longer turns a clean stop into exit
75. The closeout wait becomes 19 s: the units' TimeoutStopSec=30s less
the 5 s drain, the 5 s exit wait and 1 s margin. blockmaster logs each
AckWorkspaceRevoked step's time (lock, HEAD read, recorded, answered).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A first ACK answered DeadlineExceeded or Unavailable (the master busy)
must be asked again, and the repeat's answer completes the stop with
status 0; a refused first ACK stays final (exit 75). A second test checks
the closeout fits the units' TimeoutStopSec with the drain and the exit
wait.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The gate reads every frontier rule from blockmaster's
--launcher-replication-ack, but a volume runs its own --replication-ack.
Adds the wire field (ProbeAnswer.ack_profile) and the result fields, with
tests: both gates hold, without fencing, when an answer's profile is
missing or differs from the master's, or the master's is unknown; the
probe round names the mismatch; the volume answers its own profile;
blockmaster refuses an unknown --launcher-replication-ack.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The new primary holding every acknowledged write, and a partitioned old
primary's writes being refused, hold for sync-quorum and sync-all. With
best-effort (the default) a write is acknowledged with no replica: an
automatic failover can lose the writes acknowledged last, and a
partitioned old primary keeps accepting writes. The replicated start sets
--launcher-replication-ack sync-quorum, equal to the volumes'
--replication-ack. INV-PROMOTE-UNKNOWN-CURRENT-001's statement names the
fresh heartbeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A best_effort volume promises no frontier on a survivor, so the
automatic promotion gate now holds it (blocked event
best_effort_no_automatic_failover) instead of fencing a successor.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On both gates a best_effort volume whose primary is ineligible must get no
fencing round, keep its line and show best_effort_no_automatic_failover;
the same setup under sync-quorum fails over (the control). Red: today the
best_effort volume is fenced and failed over. The probe fake gains an ack
profile; the reason constant is added for the test to name.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under --cluster-spec with the lifecycle loop on, a primary whose heartbeat
is stale, or that answers not ready, is replaced through a fencing round
when enough replicas answer; a primary with a fresh heartbeat that does not
answer the probe is never replaced automatically. The operator's failover
is for a round that cannot decide (fence_round_incomplete) and for a static
--topology. An old primary cut off from blockmaster but reachable by its
clients can serve reads of its old data until the partition ends; its
writes are refused. INV-PROMOTE-UNKNOWN-CURRENT-001's limits match.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The repository's public-text gate refuses a pull request that adds a line
naming the team runner label, and the separate process-level job added a
second runs-on line. It now runs as the 'process' entry of the existing
job's two-entry matrix (unit | process), under that job's unchanged
runs-on line; each step is gated on matrix.suite, and the job name and
timeout are templated so the two checks keep their names ('go test
(linux)', 'process-level tests (real binaries)') and bounds (40 / 90 min).
The old two-test step stays folded into the named list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockmaster logs "lock acquired" before it imports the cluster spec, which
creates each volume's layout on the filer, and serves only after that. A
harness that looks a volume up right after that line can find it not
serving yet (F1 with ten volumes: DeadlineExceeded waiting for the
connection). layoutID now retries an Unavailable or DeadlineExceeded
answer within 60 s; any other answer still fails at once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under F1's load a write can be refused with a retryable status (namespace
not ready, Do Not Retry clear) when local admission waits past its bound;
the command is not acknowledged and the Linux host retries it. The load
writers now do the same through retryLikeHost: only a Do-Not-Retry-clear
status is retried, at most 5 times (nvme_core max_retries), and the round
fails once the retries are used up, as the host returns EIO then. A status
with Do Not Retry set, a transport error or a lost byte still fails at
once. Each round reports busy_refusals and max_consecutive_busy per volume.
F1_NVME_RETRIES=0 turns the retries off. Controls: five refusals then
success pass; six fail; retries off fails on the first refusal; Do Not
Retry set and transport errors fail at once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
w4FreePortPair checked a pair free and weed bound it later; a pair inside
ip_local_port_range could be taken in between by any outgoing connection's
source port (seen: a filer's gRPC port 43775 inside a host's 43255-47350,
"bind: address already in use", with extra volumes adding connections).
handoffAddress already stays below that range for the same reason.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit a54fcdde5ea81b1d23396c45ace385038288553a)
With the loop off, blockmaster refuses to start when its cluster spec
lists a replicated volume, and refuses to create one; a replicated volume
of another factor than --expected-slots-per-volume is refused likewise.
Only a static --topology is not checked at start. Each refusal is quoted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fake ACK records that it was entered with a live context and the
deadline it carried; the test requires DeadlineExceeded, that deadline at
the 1 s lease deadline (before the 5 s ACK bound and the caller's), no
held lease afterwards and no completed ACK. A pre-dispatch error and an
ACK bounded by the parent context alone each fail it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The read-failure case now runs on a deleting and on a deleted HEAD, and
also checks the fake filer's update and delete counters: the failed
re-run releases no source and deletes no object.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A revoking lease valid for 1 s and a master answering after 3 s: the ACK
call is cancelled at the lease deadline (about 1 s), not at the 5 s ACK
bound, and nothing is reported acknowledged; an ACK bound by the parent
context alone fails it. The invariants note now names the 6 s closeout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A root whose read fails with an ordinary error (not missing, not corrupt)
on a deleting HEAD makes the re-run return that error, skip nothing and
leave HEAD unchanged; the fake filer gains a failLookup hook (test only).
Skipping every error on a deleting HEAD fails it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The holder gave its revocation ACK call 2 s and the closeout 3 s, while the
master's handler spends up to 2 s on its bounded HEAD read and then writes
the ACK and reconciles the bindings (about 0.3 s, measured), behind its
workspace lock. A slow but successful ACK could fail at the holder (exit
75), also after the master recorded it.
WorkspaceAckTimeout (5 s, about 2.7 s above the master's measured steps,
stated in its comment) bounds the ACK call, still within the lease
deadline; the post-drain closeout is that plus 1 s. Constants only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BCatalog.DeleteVolume finds the volumes to release by reading every root
the volume's HEAD names (foreignOwners). A deleted HEAD still names its
roots, whose objects the first run deleted, so the documented re-run ("a
re-run on a deleted volume sweeps any object that landed late") failed
with "layout: object missing"; so did the re-run of a delete interrupted
after it began deleting objects.
layout.DeleteVolume deletes a volume's objects only after it released the
volume from every source, so on a deleting or deleted HEAD a root whose
objects are gone has nothing left to release. foreignOwners now skips
exactly that: layout.ErrMissing on a deleting or deleted HEAD. A corrupt
object, an I/O error, and a missing root of a live HEAD stay errors. The
skipped roots are returned, and volume-delete reports them
(already_deleted_roots).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-AUTH-ONE-REPLICATED-FACTOR-001's limits: only a static --topology file
with a mismatched volume goes unchecked at start; a cluster spec is checked
(INV-AUTH-REPLICATED-SPEC-NEEDS-LOOP-001).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A snapshot delete is one conditional update of HEAD, and the holder's
cleaning kicked by the previous delete also updates HEAD; D4's second
delete lost that race once (status 500, "HEAD generation moved"). The
helper retries exactly that answer, within 30 s, as the CLI reports it
retryable; every other answer is returned unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The holder's cleaning or a snapshot can change HEAD between the delete's
read and write; the delete then exits 1 with code conflict, retryable,
having changed nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The refusal test ran run() in a goroutine and could leave it serving on a
hang. It now re-executes the test binary as a helper process under a
10 s context (killed at the deadline and joined; exec closes its pipes).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A read fetches its chunk only when the block read is not local; the
helper read each chunk's first block, which the ladder images write, so a
chunk whose first block the guest wrote was never filled (two chunks of
C3-kill stayed absent). It now reads each chunk's last block, which no
ladder image writes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only the lifecycle product loop binds, mints and promotes a replicated
lifecycle volume. With --lifecycle-product-loop-interval at 0 a replicated
create was admitted (its factor matching) and never got a primary.
blockmaster now tells the master whether its loop runs
(Config.LifecycleProductLoop), and CreateVolume refuses RF > 1 while it
does not, naming the flag; RF1 creates are admitted either way.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A placement-only replicated entry (no size_bytes) has a placement intent
and no volume spec, so checking the volume specs let it through both
refusals. Both now read the placement intents (DesiredRF), which every
entry has; red tests for a placement-only RF2 on an expected-3 master and
a placement-only RF3 with the loop off.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replicated cluster-spec volume whose replication factor differs from
--expected-slots-per-volume would make the controller refuse every
decision (one slot count per cluster); blockmaster now refuses to start,
naming the volume and both counts, also with the product loop on.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the four mutual-TLS flags, blockmaster refuses to start without
--audit-log. The replicated start runs with authentication (its failover
needs an admin certificate), so it carries the four flags and --audit-log.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The controller validates every replicated volume it decides against the
master's one slot count (--expected-slots-per-volume) and refuses the whole
decision when one differs. CreateVolume accepted any replication factor, so
an RF2 create on an RF3 master gave a 2-slot placement which, once its
replicas heartbeat, stopped assignment and failover for every replicated
volume of the cluster.
CreateVolume now answers FailedPrecondition, naming both counts, when a
replication factor above 1 differs from the master's. Single-replica
volumes (which never reach the check) are admitted as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockmaster replaces a primary by itself only when it answers not ready;
a primary whose host is off or unreachable is not replaced, at every
replica count, loop on or off: the operator cuts the old node off and runs
sw-block ops failover. The replicated start carries both non-default flags
(--lifecycle-product-loop-interval 100ms and --failback-runtime-rpc);
without the second there is no manual failover. A restore target starts
with the source's --durable-blocks and --durable-blocksize.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
--expected-slots-per-volume is one number for the cluster: one replicated
volume with another slot count stops assignment for all of them. Single-
replica volumes can share a --cluster-spec cluster with 3-replica ones;
2- and 3-replica volumes cannot share one; a static --topology holds one
factor. A replicated volume fails over by itself only under --cluster-spec
with the lifecycle loop on; on a static --topology the operator runs
sw-block ops failover and reruns it after a refused fencing round.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With --cluster-spec, a replicated volume's placement is bound, its line
minted and its promotion gate run only by the lifecycle product loop. With
--lifecycle-product-loop-interval at its default 0 that loop never runs,
so the master starts, accepts heartbeats and never gives the volume a
line; every replica waits at epoch 0 with no error.
blockmaster now refuses to start when its cluster spec holds a volume with
replication factor above 1 and the loop is off, naming the flag. A static
--topology (whose observation controller mints) and single-replica volumes
are untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With replication_factor above 1 under --cluster-spec, blockmaster assigns
the primary through its lifecycle loop, which runs only with
--lifecycle-product-loop-interval (100ms, as the shipped chart sets); the
default 0 leaves such a volume without a primary. The single-replica starts
need no loop. The operator guide names the tests that run the replicated
start.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A kill before then leaves the chunks it made local absent again; they are
fetched again from the source's snapshot, with no data lost.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A chunk made local is recorded in the store at its next checkpoint, so a
kill shortly after a fill may leave that chunk absent again; it is fetched
again on its next read and no data is lost. The test no longer requires
fill progress to survive the kill (it logs it) and keeps every data check:
no partly filled chunk is served, and every acknowledged write survives.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each round's restore target was listed with size_bytes, so blockmaster
created it as an ordinary volume and the restore into it was refused
(target_exists: bound to another restore request). Targets now carry their
placement only and their restore creates them; sources are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Run 3 at 19cef1c printed each failed test's own file:line lines, but for
two tests the twelve shown were all cleanup headers ('<process> log:',
'---- <x> log tail ----'), pushing the failing assertion out. Those
headers and successful command echoes are no longer counted. Control: the
reason is shown behind 21 such headers; a mutant without the filter turns
it red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-WS-DELETE-NO-LIVE-HOLDER-001 notes that in this release a never-started
line that holds a lease is deleted once its lease horizon passed; the
immediate delete is a later fix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The v1-limit note on INV-WS-DELETE-NO-LIVE-HOLDER-001 moves to the
documentation change: a test-only change touches tests and testdata only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Step 5 holds the first start of a fresh volume before the attach commit
retires the fresh state, kills it there, and must see the store still
fresh. It looked for a <volume>.chunkfresh sidecar, which the cutover to
the content-named store removed: the fresh state is now in the store's
descriptor (WALStore.SetLayoutIdentity / LayoutIdentity). Every try
therefore read "marker always gone" although the product held at the
right boundary.
kzFreshAtStop opens the killed store (under its <volume>-<id8> layout
directory, or under the root without one) and requires LayoutIdentity()
set and fresh; markers_at_stop records the store read and what it held.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Step 4 is refused with "live until <time>" while the lease its first start
was granted could still be live; the same command run after that time
completes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A never-started line that holds a lease (a first start stopped at the
grant, a clean-move target that never started) is refused by the delete's
reservation while that lease may be live, and completes when the same
delete is rerun past the horizon the refusal names (nobody renews it).
The three tests now assert that, through deleteAfterTheHorizon: any
other refusal still fails them, and every fencing assertion stays (a late
start after the delete is still refused, the claimed control is
unchanged). The immediate delete of such a line is the 1.0.1 fix.
INV-WS-DELETE-NO-LIVE-HOLDER-001 states the v1 limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The move to GitHub-hosted runners is held until the account's billing is
fixed; the job uses the Go suite's runner selection again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Run 2 at 774ee23 showed the last 40 lines of each failed test, which were
the harness's SeaweedFS log tails printed after the failure; the test's
own file:line messages fell outside. The gate now prints the test's own
messages (its last 12 file:line lines at the test's indent) and then its
last 5 lines. Control: the reason line is shown behind 60 lines of log
noise; a mutant that drops the own lines turns it red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The named tests need no root; a hosted ubuntu-latest runner is free for
this public repository, so the team's runners stay free for the Go suite
and the lab. SeaweedFS is still fetched and sha256-checked each run;
nothing is assumed of a runner cache.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The events file is not kept, so the job log showed which tests failed but
not why. The gate now prints the last 40 output lines of every named test
that did not pass. Control: a failed test's reason line appears.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Its stop runs once, from the test or at cleanup, so a failure before the
explicit stop (awaitFill, awaitAbsent) still ends and joins the reader.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- KZ: each restore target is listed with its placement only (no
size_bytes), and the test requires that the master has no record of it
before its restore. Sources and crash volumes are still created.
- C3: a restore from the restored volume's own snapshot is refused
(not_admitted, naming another volume's chunks); filling makes bytes local
but leaves the source's chunks named. The restored volume's image is
read directly; the source's snapshot still restores unchanged.
- C3 kill: the second kill waits for a running fill: the reader has
completed a read without error and is still reading, and the absent
count fell since it started. fillWitness has controls for a reader that
never starts, fails, finishes, or makes no progress.
- Invocation guard: each call runs in a child process killed at its
deadline; the master resolves every name and the filer dial and restore
RPC answer a sentinel only reachable after every argument check. A call
still running at the deadline fails. Controls: snapshots or
snapshot-delete without --chunk-filer, and restore without --master, are
refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Code review at 1fb51fc: the loop printed each process's exit status and
dropped it, and the checker ignored package-level failures, so a test
that reported PASS and then failed, panicked or hung on its way out
passed. run-named-tests.sh now keeps each process's status; the checker
(--status) passes a named test only with a PASS event and exit 0, and any
package-level failure fails the run. Controls: 7 new gate cases, and a
real-shell control with fake test binaries (PASS then exit 1, PASS then a
hang until the timeout) that both fail the gate; dropping the status in
the runner turns two of them red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestAVolumeThatServedBeforeItsFirstGateTickFailsOver: a volume that
served before the gate's first tick still fails over. 44 tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The restore exits 1 with not_admitted and a message naming another
volume's chunks (not restore_source_not_own), and the refused request
leaves the target name bound to it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The source's snapshot cannot be deleted while restore targets depend on
it: the blast-radius test now requires snapshot_has_dependents while v2 is
refused and v3 serves, deletes both targets through the page's steps (v2
on a root with room), and then requires the snapshot delete and the
source's delete to complete. B1's restore from a restore target's snapshot
requires what the CLI prints: not_admitted, naming another volume's chunks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
volume-delete answers {"volume":"<name>-<id8>","state":"deleted"}; the
test decoded a completed field the command no longer prints.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ops chunk snapshots prints a JSON array of {name, root, dependents} in
name order, and a listed snapshot is published; the list carries no state
or cut position. The ladders now decode that array and check identity by
name and root: three snapshots with roots of their own, s4 listed only
once published and then unchanged, a retried snapshot keeping its root.
Contents stay checked by the restores that follow. A snapshot of a restore
target that is not fully local is now taken, and a restore from it is
refused with restore_source_not_own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The former operator examples named the retired storage HEAD fields remoteLSN and detachedBy and called live state active. Document the current ops chunk show wrapper and exported layout.Head field spelling: Position, ClaimID, empty live State, detached State and Current. The detached HEAD is the stop image; generation is record readout. This supplies the operator contract for the procedure HEAD-view fixture migration. No product behavior changes.
ops chunk snapshots answers a JSON array of {name, root[, dependents]} in
name order; an entry has no state or cut position. snapshot-delete answers
{"volume":"<name>-<id8>","name":...,"state":"absent"}.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FIXTURE: the procedure helpers decoded ops chunk show into the retired storage HEAD. The CLI emits layout.Head: live state is empty, committed position is Position, and the detached HEAD itself is the stop proof. Port each procedure HEAD reader plus the shared seal and successor checks; preserve holder, epoch, image, position and generation assertions. No product deadlines or expected exit codes change.
The real layout.Head JSON passed to the legacy decoder reproduces position zero and nil DetachedBy. Current checks and captured-output controls pass 10x; the Linux subprocess/chunkstore_integration test binary compiles. Full real-binary procedure rerun remains pending.
Adding a restore target to the cluster spec means restarting blockmaster.
Serving volumes ride through a restart answered within 10 s; a longer one
is fail-closed (fence at lease end, exit 75, serve again after the barrier,
at least 50 s after the restart), each with the test that shows it. The
start-wait text no longer describes a start that ends before the barrier,
and the operator guide's host-loss step says the returning old host exits
78 and is not restarted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A restore target is listed in the cluster spec with its placement and no
size_bytes, so the restore creates its record with the snapshot's
geometry; an entry with size_bytes creates an ordinary volume and the
restore into it is refused with target_exists. The old host after a forced
move exits 78 (reason=moved) and is not restarted. The started-too-early
gate row is removed (a start now waits through the barrier), and the
headroom test name is updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fixture read <chunk-path>/<name>/HEAD and counted top-level segments
in it, and counted <name>/keys: names the layout no longer writes (a 404,
or a silent 0). It now resolves the store directory <name>-<id8> from
blockmaster's record, decodes HEAD, counts the segments of its current
root, and counts the volume's pool objects.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
startHandoffEnvWith imported each target as an ordinary volume record, so
the first restore into it was refused as target_exists (bound to another
restore request). Targets now carry placement only and their restore
creates them; startHandoffEnvVolumes keeps the old form for the tests that
start their extra volumes without a restore. Assertions are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
record() rebuilt a volume's store record from a new attestation and
carried Initial and AwaitingFirstReady over but not DeleteWithoutAck, so
a late attestation of the last store erased the mark and ended the frozen
wait. The mark is now carried like the other one-way fields and compared
in sameAttestation. TestTheDeleteMarkFreezesTheStoreWait (an attestation
of every store after the mark, then a restart) is the red control.
A source census pins the rules: a record is built only in open and in
record, record carries the mark over, and only markDeleteWithoutAck
writes it (true); its controls break each rule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The delete without the holder's acknowledgement was admitted whenever the
end of creation was not recorded. That includes a volume that is serving
acknowledged writes whose end the master could not read (after a master
restart or a partition): the reservation stopped its grants, the proof
then found a write and refused, and the volume could neither serve, fail
over nor be deleted.
It is now admitted only in stage 1, while the master's record still
awaits a replica store (the primary serves nothing until every store is
recorded). The mark is written durably first, in the lock that ends the
wait, and freezes the record in stage 1: stores attested after it never
end the wait, so the primary never starts serving. Past stage 1 the
live-lease refusal stays; a broken creating primary's lease ends by
itself and the ordinary delete then applies. The survivor proof at the
HEAD update is no longer needed and is removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- ops chunk show and snapshots built as argument slices get --master;
the guard now also checks []string{"ops", ...} literals.
- A returning old host after a forced move exits 78 with reason=moved
(the master's typed MOVED refusal), as the product documents.
- TestProcedureStartTooEarlyExitsAndARestartServes is retired: a start
before the barrier now waits through it and is re-granted, which
TestProcedureStartInsideTheBarrierWaitIsReGranted covers.
- ops chunk gc is gone: D4 deletes through the holder, whose cleaning
pass removes exactly the deleted snapshot's chunks from the pool; the
headroom test asserts the source snapshot of a waiting restore target
cannot be deleted and keeps its chunks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test's volume host has no replication slot, so it never attests
stores and the volume stayed in its creation phase. The fixture now sends
r1's heartbeat with its store attestation through the master's own
ReportHeartbeat RPC, as a replicated primary does after its peers'
barriers: no test hook, no hand-written record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The never-created delete was admitted for any creation-hold reason,
including a volume whose primary had acknowledged writes before the
master recorded anything. Now:
- it is admitted only while creation has not ended, and the master's
record is marked durably first, in the lock that ends creation, so
creation never ends after the admission (the delete reads the record as
it was admitted, also after a restart);
- deleting HEAD waits out the holder's lease horizon as before, and then
requires proof that the volume is empty, read after the horizon: stage 1
(not every store attested: the primary served nothing), or N-K+1
survivors that answered on valid tables at end 0. A survivor holding a
write, a silent survivor or an unknown ack profile refuses;
- a volume whose creation ended keeps the live-lease refusal.
Part A (M2) and the ledger row INV-WS-DELETE-WITHOUT-ACK-001 name the rule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A start inside the barrier wait is now re-granted, so the test that
expected it to exit is retired; TestProcedureStartInsideTheBarrierWaitIsReGranted
covers that path. 43 tests remain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The known-zero acceptance's first-start crash step (step 5) needs
KZ_HOLD_BIN, a test-only blockvolume built with -tags kzhold; without it
the test refuses at that step once it gets there. The job builds it
beside the other binaries and exports KZ_HOLD_BIN.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Through the production binaries: an RF3 sync-quorum primary serves and
acknowledges a write after its stores are attested and is killed before
the next product tick (30 s loop); the survivors' write ends creation, the
gate fails the volume over and the write reads back on the new primary.
The test checks that the window really occurred.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume's creation phase ended only at the primary's first ready answer,
read by a gate tick. A primary that served right after its stores were
attested and died before the next tick left a volume that had acknowledged
writes held as creating for good: no gate, no operator failover.
Creation now ends, durably and for good, at the first of:
- the line's primary answering ready, or
- a survivor answering DurableLSN > 0 at the current line (its epoch-table
row at the current epoch, or none): under the quorum ack every
acknowledged write is on a survivor.
A failed write of the end of the store wait keeps the volume held (it is
reported as one store awaited) instead of releasing it with no record of
its next stage.
Tests: the gap through the operator's failover, the first-of rule and its
one-way record across a restart, the failed stage write under both gates,
the operator's move and a restart, and the primary's awaiting answer alone
holding an established volume on both gates and the fenced operator path
(each red with its guard removed).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The process-level tests (cmd/blockvolume, tags subprocess and
chunkstore_integration) were only compiled; the workflow ran two of them.
A new job runs every test named in .github/process-level-tests.txt, each
in its own bounded process of one prebuilt test binary, against the
pinned SeaweedFS release. required-tests-check.py fails the job unless
every named test passed: a skip, a failure, a test that never ran or one
cut off mid-run is a failure. Its self-test runs first in the job.
The tests that need root, a mapped device or systemd stay outside CI
(named in the list's header). The previous two-test step is folded in.
A restored volume takes no scheduled snapshot until its device has been
read once; a manual one names the source's chunks and cannot be
restored. ops chunk release is a repair step. The lifecycle rules name
one blockmaster per cluster, no restore of its directory from an older
copy, and that a deleted volume's name cannot be created again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Restore is created with --master and fills on access (no restore driver,
no background copy); its source snapshot stays a dependent for the
target's life. Fork and template retirement are not in this release.
The documented show, snapshots and snapshot-delete commands get the
required --master.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
v1 has no background fill: hydrate reads one block of every chunk, then
requires none absent, and the killed-mid-fill test drives its fill with
a background reader. The guard also checks the harness's run calls, and
the show and snapshot-delete calls it found get --master.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A guard runs every literal `sw-block ops ...` call in cmd/blockvolume's
tests through the CLI's own argument handling, so a call the CLI refuses
fails CI instead of a lab run. The calls it found are brought to the
current CLI: --master on restore and snapshot commands, the removed
restore driver and fork replaced or dropped, and the killed-mid-fill
test converted to background hydration.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The layout delete's reservation was refused while any lease was live, and
a creating primary that is stuck (a replica store never attested) keeps
renewing, so the only exit from the creation phase, delete and recreate,
was closed. A volume whose master record never left the creation phase
(it served nothing, acknowledged nothing) is now reserved for delete under
a live lease: the reservation stops every grant at once, the delete's HEAD
update still waits until no lease is live, and HEAD deleting then admits
no claim or commit. A volume that ever completed creation keeps the
live-lease refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Not at the last store attestation: a primary restarted after the last
attestation, before it adopts the complete assignment, was no longer
creating by the record and could be replaced. The record now sets
awaiting_first_ready in the same write that clears its initial set, and
clears it, durably and for good, at the line's primary's first ready
answer; until then the volume is creating. A record written before the
field existed carries none, so an established volume is never reopened.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review amendments (no product change):
- storage: both refusal controls read the chunk's blocks from the extent
file before the refused fill and after it, and require them unchanged;
a fill that installs damaged bytes and then refuses is now red (it left
absent and localBlocks untouched, so the old assertions passed).
- chunkstore cut test: the child's stdout is read to EOF, so an upload
begun during the delay or the kill is counted; CUT-ERR at any point
fails the round; the child must have died by SIGKILL; objects 0..last
(at least the first four) are validated every round (an object never
begun must be absent) and all of them are completed by a new session.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The master test's freshness window is one second; a target report one
second old had already expired, so no report was found at its endpoints.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A guard on hostConfig's LinesNameTheirProcess, the refusal control also
checks nothing is recorded, and the M3 diagram and table state the
adoption guard (the row maps to M2 refresh and M3 adoption).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every read of a pool object already verifies its bytes against the name
twice: the layout reader (ErrCorrupt -> ErrRemoteDamaged) and the
engine's fill (sha256 and size against the HEAD ref). The engine's
refusal was an untyped string; it is now ErrChunkContentMismatch, on the
read-miss fill and on the cut COW fill alike.
Controls:
- storage: a seeded chunk whose bytes are flipped, truncated or extended
is refused with ErrChunkContentMismatch on a guest read miss and on
HydrateAll; nothing is served or installed, and once the remote serves
the named bytes the same reads return HEAD's data.
- durable, end to end over the real layout remote: a chunk captured to
the pool, its blob damaged under the filer entry, a fresh replica
attached from HEAD: the guest read fails with a typed error and never
returns the stored bytes; restored, it reads HEAD's data.
- chunkstore (real filer, chunkstore_integration): a child uploading
pool objects through EnsureObject is SIGKILLed at random points over
many rounds; each object it began is absent or holds exactly the bytes
its name hashes, and a new session completes it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The incarnation source looks up the slot at the ask's endpoints, never
the same replica reported by another host. A production volume adopts
no line that names no process; the target's first report re-issues it
once for that process.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A creating volume is no longer replaced when its primary is not ready for
another reason, answers a stale epoch, or has an unacceptable slot: no
promotion decision is even probed (the owner's ruling and its model).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The workspace record writer copies the line's incarnation, so a lease or
journal write no longer erases it before a reload; a queued refresh for
one process is replaced when another reports at the same address; the
RefreshEndpoint transition names the restart case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A heal, a planned or workspace move or an operator's request names no
incarnation; the publisher records the one the target reports now, so
the promoted process's first report re-issues nothing. The volume's
refusal of a line issued for another process now comes before anything
of it is recorded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A primary restarted at the same epoch and address started its sessions
at 1 while each replica held the dead process's higher one, so every
session was refused as older. The line now records the process it was
issued for (durable); a current primary reporting another process is
re-issued its line at the next endpoint version, and a primary adopts no
line issued for another process.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume whose first line has not reached Healthy is never subject to a
replacement decision: no reassign, no fencing round, no heal at a higher
epoch. One predicate, checked first in both gates and in the operator's
move: the master's record still awaits a replica store, or the current
primary's own answer says its assignment at this line's epoch awaits
them. The creation-wait excuse that judged such a primary ready (and so
let the supported gate fence its replicas at e+1 and heal the primary at
e+1 before epoch 1 was ever healthy) collapses into it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume re-created under the same name is another volume, so a commit's
reference is own only when both the owner's name and id are this
volume's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A restore target keeps or drops its source's references and never gains
one, so a dependency stays one step deep: RunCommit refuses a manifest
that holds another volume's chunk at an index where the previous manifest
did not hold that same chunk.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lane-routing harness gets a store, and the ingress version test
starts from a replica that holds 1..119, so their live entries arrive at
the next LSN.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Its image could not be brought up to date, and the latch clears only on a
completed rebuild: a probe or fencing round answer from it is never
ready, so no promotion (automatic, the operator's failover or a planned
move, each requiring the target's ready answer) can make it primary.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replica removed and added back with its older store cannot be rebuilt
on v1 (its BASE is still installed). The store now returns the typed
storage.ErrRebuildRetainedBase, the replica listener keeps that refusal
until a rebuild completes, and the volume host reports it on its
heartbeat slot as rebuild_retained_base (ineligible), naming the replica.
The operator guide gives the recovery: wipe the data directory, re-add.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Live-ship and recovery session ids came from two process-wide counters;
once the live counter ran ahead, the replica refused every recovery as
older. Each replica now has one order, kept by the volume across its
peers and executors, and every session toward it takes the next id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The recovery begins with BeginEpochRecovery, so the primary's live
session stays admissible and only the invalid epoch table can refuse its
frames; a recovery begun and ended is the control. The test is its own
package so its sessions do not reorder another test's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The runtime checked --expect-current once, then ran the gate and published
without it: a move landing in between let the stale request move a line
the operator never saw. The reassign now carries the expected line and the
publisher mints only while the volume's line is exactly it (under its
lock); the gate decides on that same line (reachability and the fencing
round are the expected line's, never one read later).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
While a recovery owns a replica's store its epoch table is invalid and its
end may sit above a gap. Such a replica is never a fencing round's target,
also with the highest end, and never completes a sync_all or sync_quorum
write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The copy into $SWBLOCK_TEST_LOG_DIR moves to an untagged helper, so a
filesystem-only test runs with the ordinary suite: a log longer than the
kept output is copied byte for byte, an unset directory copies nothing,
and the check refuses a truncated copy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The volume's listener always has the apply gate installed, and the gate
checks each block's staleness, not the position, so the live-lane rule
applies on both paths. The tests build the listener as the volume does,
on walstore and smartwal, and check that no live entry lands while a
recovery owns the store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The line was published at the data and control addresses the caller sent
(CLI flags, or the Kubernetes object's fields): a typo or a writer of that
object could make the fenced replica primary at an endpoint clients never
reach. The runtime now requires the master's own record of the target
(its fresh heartbeat slot, else its placement) and refuses a request whose
addresses differ, or a target with no record, before the gate runs, so a
refused request fences nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Inside an epoch, a live entry above the store's next LSN is refused and
the connection closed; the primary's catch-up from the barrier end then
applies the gap in order. Fixtures that shipped hand-picked LSNs now ship
at the store's next LSN.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review: the catalog reader converted the entry's seconds to nanoseconds
without a range check, so an out-of-range mtime (year 9999) wrapped to a
negative time where the HTTP reader had reported it unknown (0). The
conversion is guarded; the master reader's refusal table has the
out-of-range case again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
v1 reads HEAD through the layout catalog. A unit or script that still
passes the removed flag is refused at start with a typed error
(errRemovedInV1) that names the replacement, --chunk-filer and
--chunk-path, rather than Go's generic unknown-flag message; the flag
is never accepted and ignored.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sw-block ops failover is the operator's failover of a standalone
deployment: one call to blockmaster's admin-only FailbackService over
mutual TLS with the expected current line, after the operator confirms the
old node is off or cut from its clients. blockmaster decides the move.
The alpha stack now deploys what its notes describe: blockmaster serves
the failback RPC, and the failback executor (admin client Secret,
execution on) runs in kube-system; install applies the CRD and executor,
uninstall removes both.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The 'starting' latch could outlive a frontend that opened and failed
between two samples, excusing a real failure. It is gone: the probe answer
reads the replica-store wait before its readiness (the frontend gate reads
the same value), so a not-ready answer names the wait only if the wait
held, and a stores-complete assignment opens the frontend only after the
peers' expected stores are installed. The gate is a guard in the ledger
(INV-PROMOTE-CREATION-WAIT-001); the probe round's copy of the field is
tested on the wire.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The master read HEAD two ways with two settings: the layout catalog
(filer gRPC, --chunk-filer) for create and restore, and plain filer HTTP
?metadata=true (--workspace-head-base-url) for the workspace move admission
and the revoke ACK. The workspace reader now reads through the catalog it
already dials: BCatalog.ReadHeadObserved returns HEAD, decoded by the same
DecodeLayoutHeadEntry, with the entry's modification time from that same
lookup (seconds, as the HTTP metadata gave it). The proof mapping is
unchanged: identity from the master's lifecycle record, deleting, unclaimed,
detached, generation, epoch, holder and position; an absent HEAD refuses
with ErrHeadAbsent.
The HTTP reader and --workspace-head-base-url are deleted, with the unit's
and the env file's setting and the docs. The master tests run the same
refusal table against a catalog on the in-memory filer (the HTTP-only
redirect and envelope cases have no counterpart). The fixtures that passed
the flag give the master the filer flags instead; the head-size and F1
ladder masters had none and could not dial the catalog at all.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The operator's fencing round may fence survivors above the line whatever
it decides, and an allowed decision may still fail to publish: the fence
is now pending from the attempt until a line reaches its epoch. The
unsupported gate continues the line's own primary at e+1 on a pending
fence before any candidate check, as the supported gate does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stores-complete assignment set the awaited count to zero before the
frontend opened, so a probe in between answered not ready without the
awaiting epoch: the shape the master reassigned. The line now stays
"starting" from its wait until its frontend has opened on it (seen by a
probe answer or a heartbeat); a later not-ready answer is a real one. The
epoch, the counts and that start are one value under one lock, so a probe
never pairs a new epoch with an old count.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A reachable RF3 sync_quorum primary's move is a planned move again and
stays refused for want of a seal; only the operator's failover of an
unreachable primary is decided on the fencing round. Adds the test where
the operator's failover and the master's promotion loop decide the same
volume at once: both fence at the same next epoch, one line is published.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The promotion gate excused a new volume's not-ready primary from the
master's own reading of the creation wait, which a master restart forgets
and which ends a moment before the primary opens its frontend. The fact's
owner now reports it: the probe answer carries the epoch of the primary's
assignment that still awaits replica stores, and the gate excuses a
not-ready primary only on that answer for the current line and while its
own fresh slot is acceptable. The master-side wait check is deleted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An operator failover whose primary has no fresh, reachable heartbeat (a
lost host) is no planned move from a live primary: it is now decided on
the fencing round for RF2 as for RF3 (one path, basis Fenced). A failover
from a reachable RF2 primary stays planned; best_effort stays refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A planned move of an RF3 sync_quorum volume needs a seal (its target is
not in every acknowledgement set), so the operator's failover was refused
and a volume whose primary host is lost could not be moved at all. The
fencing round is that seal: the failover now fences every other replica at
the line's next epoch and publishes only on the round's decision (enough
fenced survivors; the target holds the highest fenced end and is ready),
with basis Fenced. A refused round leaves the fence pending so a returning
primary is continued at e+1. RF2 and sync_all stay planned moves.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The harness printed only the last 16 KB of each daemon's log, so a
decision made at bring-up was cut off. With SWBLOCK_TEST_LOG_DIR set (the
layout gate sets it per entry to an evidence folder it collects), a
failed test also writes each daemon's whole log there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review: a second busy refusal lost the kick and fell back to the hourly
interval, so a snapshot session longer than the 30 s retry defeated it.
The kick now stays pending until a pass the volume does not refuse as
busy; every busy retry comes after the short delay. KickMaintenance
reports only a running loop (not a stopped one, nor one that ended on a
fence or lineage change).
Tests: busy -> busy -> success, then back on the interval; kicks during a
held pass coalesce into exactly one follow-up; the running-loop check;
the cut-cancels-cleaning regression bounds every wait and cancels and
joins its cleaning on failure.
Protocol contract (M8 timing change): MaintenanceOwner.tla gains the
kick, the session that makes a pass busy, and NoLostKick, with a negative
config (lost_kick: a busy pass drops the kick) that violates it; the four
existing configs keep their results. The design diagram gains the kick
and busy-retry edges; the ledger gains INV-MAINT-KICK-001 and
INV-MAINT-KICK-RETRY-001; the spec README records the run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Owner decision: automatic cleaning is on in v1. The holder's maintenance
pass already cleans through its own layout remote (holder-only, one
entry, refused while a snapshot session is open, the two-step conditional
removal, a cut or stop cancels it with bounded waits); it was behind
--chunk-maintenance-gc, off by default.
- --chunk-maintenance-gc defaults to true; =false is the one switch that
turns the cleaning off. The pass still runs every
--chunk-maintenance-interval (default 1h; 0 disables the whole pass).
- A snapshot deleted through the holder's control route kicks the
volume's maintenance loop for one pass now (kicks coalesce; the same
bounded pass). A kicked pass refused as busy (a cut session open) is
tried again after 30 s instead of an interval later. Retention's deletes
already precede the cleaning in the same pass; a delete made offline is
cleaned by the next periodic pass.
- Docs: operator guide, standalone deployment, and the spec README line
that called automatic GC opt-in.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lagged rounds only showed one write after the other (a 5 ms lag
against a ~1 ms conditional write), never a delete whose check and
removal overlap a reuse in flight. 128 rounds now release both kinds at
the same instant, with the same assertions whichever wins; the 8 lagged
rounds stay, for outcome coverage. The writers' 16 connections are kept
across rounds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cleaning is on by default, so the remover's DELETE and a successor's
REUSE of the same marked entry race in production. On a real weed, 16
writers per round (half DELETE with the entry's mark, half REUSE on the
metadata they read) are released together: exactly one succeeds at the
filer. A delete leaves no entry and every reuse refused; a reuse leaves
the entry unmarked under its session and every delete and other reuse
refused. Never both.
The fixture's readbacks fail the test on a read error (an unreadable
entry is never taken as absent), and each subtest bounds its setup and
readbacks with its own deadline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A restore dies between its VOLUME and its HEAD; the operator releases it,
the snapshot is deleted and the name is taken by a new volume. The
abandoned restore's late HEAD create must be refused (the deleted HEAD in
its never-reused directory) and the new volume untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cutover removed the store's concurrent CAS test with the legacy
store. This one runs on the layout store against a real weed: 16
writers, each on its own connection, are held at the filer write until
all have arrived (after every client-side pre-read) and released
together, 4 rounds each, for HEAD updates at one generation, exclusive
HEAD creates, MARKs of one object entry, and conditional deletes of it.
Exactly one writer succeeds at the filer, the others are refused, and
the entry holds the winner's bytes; a delete with a mark the entry never
carried never succeeds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The store adapter needs no model only if the filer's conditional write
holds. On a real weed filer: a second exclusive create, a stale and a
future generation, and the right generation under another volume's
identity are each refused by the filer and leave HEAD's generation and
bytes unchanged; the same write with the true condition lands.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cleaning has taken its HEAD view when the operator deletes a
snapshot: one HEAD update by nobody's lease that leaves the clean
activity open. The pass keeps every chunk its view named, never marks a
chunk a root still names (K6 checked at every mark), and ends; the next
pass removes the chunk only the deleted snapshot named.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The runtime stores each volume in one content-named layout on the filer:
immutable chunks, segments and roots are ordinary filer files, and one
HEAD entry per volume carries every conditional commit. A holder claims
HEAD under its granted epoch and claim id, cuts in its own session,
commits by HEAD generation and position, and is fenced when its identity
moves. Catalog, restore, snapshot, retention, cleaning, verify and volume
delete run through the layout kernel; the master mints the layout
identity, reads HEAD proofs and holds the delete reservation and lease
barrier. The legacy store, its intents and its compatibility paths are
removed; existing stores are recreated, not converted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A new volume's primary hides its frontend until the master has recorded
every replica's store, so it answers the promotion probe "not
primary-ready" by design. Past its boot grace, the promotion gate took
that for a failed primary and fenced it, reassigning the volume. While the
master still awaits the volume's stores (read before the probe), and only
while the primary's own fresh slot is acceptable, the not-ready answer is
judged as the wait; an unreachable, ineligible or withdrawn primary is
still replaced. Fixtures that fail over an established volume now attest
its stores.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
85171f71 removed core/host/master/promotion_probe.go; the probe round
(core/host/master/probe_round.go) sets SyncAckKnown since. The row's
"Enforced in" cell still named the removed file, so
TestActiveInvariantRowsCiteExistingPaths failed (the -short CI run skips
internal/invcheck).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The re-send on a store record change held the last line in a local
adapter.AssignmentInfo variable, which the non-forgeability guard refuses
(only the publisher mints one). The stream now keeps a closure that
rebuilds the fact from the line it received.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
volume, replication: a fallen-out replica rejoins without an operator (role-call retry; degraded re-probe on by default without racing the live session)
The control slept a fixed time and could pass with no connection accepted
and dropped. It now waits for the listener's accept-then-drop and fails if
none happened; without the transport fix it fails at the store assertion.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A send or receive failure left session.conn in place, so a caller that
does not invalidate the session (the store learner) reused the dead
socket on every retry and never learned a restarted replica's store. The
barrier now detaches and closes the connection, as the catch-up and
rebuild senders do; the next barrier re-dials.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The learning barrier used the peer's connection from its own goroutine,
outside the work queue that keeps one writer per connection, so on an
exposed volume it could overlap the first ship. It is now a queue job on
that worker; it is queued only when there is room (it never saturates the
queue, which would degrade the peer) and retried otherwise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At bring-up the primary may install a peer whose replica does not listen
yet. The barrier that learns the replica's store then failed and degraded
the peer; nothing re-probes a degraded peer before a write, so its store
was never attested and a new volume never left creating. The store-learning
barrier now leaves the peer as it is on failure and retries in the
background (100 ms doubling to 2 s) until the store is learned or the peer
leaves.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A supporting fact cleared pendingSupport unconditionally, so a late replay
of an older line (its role call refused as stale) wiped the assignment a
newer fact left pending; the retry then admitted the newer listener but
never completed its assignment. A fact now clears or replaces the pending
assignment only when its epoch is the same or newer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fact's own successful role call released selfFenceMu before it
completed the supporting assignment, and facts run concurrently by design,
so a newer self-primary or excluding fact could cross: the old admission
then cleared that fact's primary watchdog or emitted an old marker. The
direct path and the retry now both complete through
completeSupportingIfCurrentLocked, which checks and completes without
releasing selfFenceMu: only while the desired role is still replica at that
epoch and no newer fact was seen. A newer fact records its epoch under the
lock before it acts, so it waits for the completion or supersedes it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The retry released selfFenceMu before completing a skipped supporting
assignment, and only supporting completions took the lock that ordered it,
so a newer self-primary or excluding fact could act in between; the retry
then ran supportingAdmitted for the old epoch (clearing the primary
watchdog) and emitted an old ready marker. The retry now completes under
selfFenceMu, and every fact records its epoch under that lock at the very
start of applyFact, before it acts at all (the watchdog runs before the
role call); the retry completes only while no newer epoch was seen. A newer
fact waits at that record until the completion is done. Only the record is
under the lock, so facts applied concurrently by design do not nest it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A mutex around all of applyFact deadlocked facts applied concurrently by
design (a replay worker beside the stream, a fact applied from inside
another's hook). supportMu now spans only the completion of a supporting
assignment, in the fact path after its role call released selfFenceMu and
in the retry (supportMu, then selfFenceMu), so an older epoch's completion
never lands after a newer one's. The retry completes the pending
assignment only while the host still wants the replica role at its epoch;
a newer fact moves that epoch or replaces the pending entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When a supporting fact's replica role call failed, the fact returned before
the adapter took the line's identity and before the supporting admission
was recorded. The retry cleared the latch but never applied those, so with
no new fact the engine stayed at the old line. The skipped assignment is
now kept (pendingSupport) and the retry completes it once its role call
succeeds at that epoch, with the same steps as the assignment path. A new
mutex serialises applyFact with that completion (order: it, then
selfFenceMu), and every applied fact supersedes a pending one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After PrimePendingFor's identity check the registry lock is released
before OnAssignment, so the peer can be replaced in between. That window
is closed by the executor: every command the adapter issues runs through
the old peer's BlockExecutor and enters through beginAsyncOperation, and
UpdateReplicaSet stops a replaced peer's executor (stopped under its lock,
then in-flight work drained) before it installs the replacement and seeds
it. The lock graph on PrimePending now says so, and a test holds the
dispatch in that window (a package-private hook), replaces the peer at the
same lineage on another address of the same replica, and checks that no
late connection reaches the replica and the replacement keeps its session.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Priming and the adapter lookup were keyed by ReplicaID. A dispatch the loop
admitted for an old degraded peer, delayed while a lineage bump replaced the
peer under the same ReplicaID, then primed the new healthy peer's adapter,
whose probe raced the volume's live session again. The registry now keeps
the exact peer each adapter was added for; PrimePendingFor and
AdapterForPeer compare it under the registry lock, and a mismatch primes
nothing and sends no wire probe.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test waited for its registry adapter to probe the new peer right after
the add, which is the adapter acting on a healthy peer the volume's live
session owns. It now checks the adapter has issued nothing at the add and
wires the probe loop as the binary does (priming on the first dispatch for
a degraded peer); its degrade, recover and replay assertions are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the degraded-peer probe loop on, the per-peer adapter registry primed
each new peer's engine at the add, and the engine's assignment probe and
fence ran on the replica with sessions of their own while the volume's
seed barrier and live ship owned it. The replica keeps the newest session,
so it refused the volume's own barrier as stale and the next write missed
quorum. The registry now records the identity at the add and primes the
adapter only on the probe loop's first dispatch for the peer, which comes
only once the peer is degraded (its live session failed and was
invalidated); that first dispatch is the adapter's own probe, not a second
one. With the race gone, --degraded-probe-interval defaults to 5s, so a
replica that fell out of the volume rejoins without an operator.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replica whose floor could not be persisted (a full or read-only disk)
latched its role failure and stayed out of the volume until an operator
restarted it. The host now re-applies the current replica role with
backoff and clears the latch on success; a refusal that a retry cannot
change (ErrRoleRefused: the ingress is closed, or the volume refuses
replica peers) keeps its reason and is not retried.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The move of the ship order to the store keyed on the listener role, which
a primary fence sets before the move runs. A refused move followed by a
replay of the same line skipped it, and so did a genuine primary after the
excluded-replica path had fenced the listener as primary only to close
ingress. The host now records 'ship order prepared' itself: cleared when
it takes a replica role, set only after a successful move.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An initial replica replaced during the wait (a new replica id) is no
longer waited for: the count is over the current replica slots, and the
wait is cleared for good the first time every current replica has a
recorded store, so a later replacement never closes the volume again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A host whose replication slot does not count peers by recorded store
counts no peer ack, so the creation wait does not close its frontend.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The frontier-0 store barriers run in parallel after UpdateReplicaSet
releases v.mu. A replica refused for an unrecorded store stays Healthy with
its learned store, so the next attestation records it with no operator.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test's gate fake fenced its survivors without saying their evidence
was read, so since a fenced answer counts only on a read, valid table, it
had no survivor and the failover it asserts never came.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A replica applies entries through replication, so its store's next LSN
moves while the write observer's ship cursor stays where the observer was
installed. Promoted, its first local write waited in the LSN resequencer
for an entry that never comes as a local write, and every write after a
failover failed at its deadline. On a transition into the primary role
(listener fenced as primary, frontend not serving yet) the host moves the
ship cursor to the store's next LSN.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A peer counts toward write ACKs only while its barrier store equals the
store the master recorded for it from a primary's attestation, carried in
the replica descriptor; empty never matches, and the peer's own word never
changes it. A record change re-sends the assignment at the same
generation and the primary updates expected stores in place.
A volume's first bind records its initial replicas: until each has an
attested store the fact carries the awaited count, the primary serves no
frontend I/O and reports "creating: waiting for replica attestations
(n of N)"; the primary learns new peers' stores with a barrier at LSN 0.
Replica rows show store_attested/store_id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unacknowledged replica's ack does not complete a sync_quorum flush
(it does once its store is acknowledged). The first-heartbeat window's
defect is pinned by a skipped red test: a fresh primary with healthy
replicas must fail no flush before its first acknowledged heartbeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Where the primary attests its write-ACK stores (every heartbeat of a
volume host), a Healthy peer counts toward write ACKs only once the
master has acknowledged the attestation naming its current store. A peer
rebuilt onto a new store still answers barriers (that is how its store
is learned) but does not count until that store is acked, so it can
never be the only holder of an acknowledged write that a promotion
cannot verify. The host passes an acknowledged attestation to the
replication volume after each successful heartbeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An answer whose epoch table is absent, or whose evidence could not be
read, reported no table and so was never marked invalid: it counted
toward N-K+1 with end 0 and could let a lower end become the target.
A fenced answer (and the heal's own answer) now counts only when its
evidence was read on a present, valid table, from the attested store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A read-only durable root does not stop root from writing the floor record,
so the test skipped as root and a root-run gate could never pass it. The
fault now moves the root aside and puts a regular file at its path: a new
file under it fails with ENOTDIR for any user, while the files the replica
already holds open keep working. The rejoin removes the file and moves the
root back.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
transport: the persist interrupted at each step (write, rename, dirsync)
makes no promise and a restart loads the old floor or the fence epoch,
never anything else; a drain timeout makes no promise; concurrent rounds
never lower the floor.
volume, on a real listener and floor record: after the answer at e+1 the
old primary's ships at e and below are refused, also after a restart, and
the line re-issued at e+1 is admitted; a superseded round answers its
higher floor and lowers nothing; a crash before the persist answers
nothing and binds no restart; a crash after the persist binds the restart
and the re-asked round answers at the same floor.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RF3 sync_quorum from a cluster spec: a survivor that cannot persist its
floor leaves the fencing round one short; the stopped primary is healed at
the next epoch once it answers, serves a new write, and reads back both.
The last step (the survivor rejoining after its disk recovers) is red:
a failed replica role call is not retried.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The heal of a failed fencing round reassigns the current replica at its
own endpoints, which the product tick and the publication admission both
dropped as already current. A reassign with a fenced epoch skips that
check: the mint takes it only at that epoch, so it cannot advance twice.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The host finds its fencer through the self fence, which in the binary is
the replication ingress; it had no FenceFloor/DurableFloor, so a replica
answered a fencing round without raising its floor and the master counted
no survivor. The ingress now forwards both to its listener.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A scenario under testops/scenarios/*.yaml is a test definition, so a PR that
changes only scenarios (and tests) passes as kind TEST. Production Go next to
a scenario still fails TEST, as do a script beside the scenarios and a yaml
outside testops/scenarios.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An attestation is merged into the volume's record: each replica it names
gets that store as its reference, and a replica it does not name keeps
its last one, since it may be the only holder of an acknowledged write.
A new attestation after a rebuild replaces it; a wiped store has another
id and is still not a survivor.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A listener in the primary role refuses FenceFloor (ErrFencePrimary),
checked under the lock that raises the floor, and keeps its floor at the
epoch it serves; the caller sends no answer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On a probe round with a fence epoch naming its store, the replica raises
its epoch floor in memory (new frames below it are refused at once),
waits for every mutation admitted before to finish, persists the floor,
and only then reads its evidence and answers with the durable floor. A
failed fence is not answered; a round naming another store raises
nothing; a plain round reports the floor. The floor never goes down, and
the line re-issued to the same primary at the fenced epoch is admitted
as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A table trimmed at its row cap may no longer reach the probed LSN, so a
replay has no row to compare. It then rests on the store id and the
durable end; a first promotion still needs the row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A rebalance moves the primary while it is alive, so it is a planned move,
yet it needed only the gate's promotion evidence. Under RF3 sync_quorum
the old primary can be acknowledged by the other replica alone while the
target adopts. The gate now marks a slot PlannedMoveAllowed from the same
plannedMoveAllowed(profile, replicas) a failback uses, and the controller
publishes a rebalance only to such a slot.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A line at an epoch the store already holds rows at was adopted as a
replay before any check, so a same-epoch promotion naming another store,
no store, or an end this store does not hold was admitted. A promotion
now runs its checks on every delivery; a genuine replay still matches,
since the row noted at the new epoch starts past the probed LSN.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
LocalPrimaryEvidence synced after reading the table, so a row appended in
between was paired with a newer end. Sync first, then read the table.
The workload-plan HTTP provider has no production caller since the probe
round; it moves to a test file so the round is the one way to evidence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The primary attests, in its heartbeat, the store id (superblock UUID) of
each replica counted toward its write ACKs. A probe round answer carries
the replica's store id; a candidate is ready only when that id is the one
its primary attested (a replaced or never-attested store is not a
survivor). The promotion line carries the probed store id, and the target
refuses a promotion whose store id is missing or is not its own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A line names how it made its primary the primary: BOOTSTRAP (the volume's
first primary), PROMOTION (with the gate's evidence: the target's durable
LSN and its epoch-table row there) or FORCED. The one mint refuses a
reassign without a kind, the kind and evidence are kept on the durable
authority record so a replayed line carries them, and AssignmentFact
carries them to the target.
The target adopts the primary role of a replicated volume only if its own
store still shows what was probed: a replay of an epoch it adopted needs a
valid epoch table; BOOTSTRAP needs no data; PROMOTION needs a valid table,
a durable end at or above the probed LSN and the probed row at that LSN
(a tail beyond it is its own log); FORCED adopts. A line without a kind to
a node holding data is refused, except a store from before the epoch
table replaying the line of its own durable floor (the upgrade). A
refusal latches the role admission failure (the slot becomes ineligible),
and the next round shows the store's real end and row. A single-replica
workspace move keeps its own start check.
Red: the promotion adoption trace (a store replaced between the line and
its adoption, an acknowledged block lost) fails on main and passes; one
row per guard of the adoption check; the mint refuses a kind-less reassign.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The promotion gate (one function: the probe round's answers -> the allowed
replica and its evidence) now covers every replicated volume, RF2
included: on main RF2 and every observation-fed failover promoted on
heartbeat readiness with no evidence of the candidate's data. The gate
puts its evidence on the slot it allows; the controller's failover and
rebalance carry it and publish nothing without it. The legacy PolicyOwner
(no production caller) is deleted. Failback is the operator's planned move
through the gate: the target is probed by the round, and the move is
allowed only when the target is in every acknowledgement set (sync_all at
any replica count, sync_quorum with RF2); RF3 sync_quorum (needs a seal)
and best_effort (forced only) are refused with typed errors.
About forty tests encoded the evidence-free decision. Their subjects are
unchanged; each now gets the candidate's evidence the way the gate gives
it (the controller's candidate helper, the convergence snapshots, a
stand-in gate sink for the observation-fed routes, a static round answer
for the RF2 and failback tests). None is skipped or loosened. New: ready
replicas without the gate's evidence promote nothing; RF2 promotes on a
ready answer and not without one; the planned-move guard, one row per ack
profile and replica count.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When blockmaster decides a promotion it mints a fresh round id and sends a
ProbeRound to the node of each replica it asks, over that node's
authenticated round stream (SubscribeProbeRounds); each replica answers
from its store as it is now: durable end, the epoch-table row there,
whether the table is present and valid, and its role (AnswerProbe). Only
an answer with this round's id, from the node asked, for the replica
asked, counts; reports, old answers and answers from another node never
do. The round replaces the /status probe, which mutual TLS keeps on
loopback, and is installed at startup for every deployment (it was
launcher-only). Both methods are node-only.
Regenerated with the pinned protoc-gen-go v1.27.1 and protoc-gen-go-grpc
v1.3.0 (the gRPC file's header now names protoc v7.34.1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The chart sees Secret names, not roles: rendering fails when
tls.clientSecrets.csiNode or .operatorStatus names the CSI controller's,
the failback executor's or blockmaster's own Secret. A test renders the
chart with each such override and expects the refusal. The operator
guide says the CSI node's certificate must have the viewer role in the
role file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The launcher and the alpha certificate helper both refuse a server id
whose Secret name has an empty or malformed DNS label (a..b, a.-b, a
label over 63 characters). The helper reissues a leaf that no longer
verifies against its CA (the CA was regenerated), and keeps the server
ids issued by earlier runs in the role file and the applied Secrets.
Node certificates are client-only, so they carry no subjectAltName. The
operator guide says how to upgrade a blockmaster started with
--insecure-external-bind.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A lane start without the LSN it starts after took the mark unconditionally;
it is now refused (nothing is released on this wire). A live entry passed
its note and could be held while a recovery took the mark and installed a
base, then land as a stray block under a table later made valid: live
applies now hold the apply fence shared and run only while the table is
valid, so a recovery's Invalidate drains them. Every lane start sender
states its from-LSN (EncodeRecoveryLaneStart).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The CSI node and the status operator mount viewer certificates; the CSI
controller (it deletes volumes) and the failback executor mount admin
ones. The alpha certificate helper issues one certificate, role-file line
and Secret per client, and the chart takes one Secret per client
(tls.clientSecrets). A chart-render test fails when a client mounts a
Secret other than its own, when an admin Secret appears outside the CSI
controller and the failback executor, or when the role file gives a
client more than its role. A node's refused reattach event is one log
line and is not retried.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the promotion-loss regression PR, with the epoch tables production
keeps beside each store (both wrote LSN 1 at epoch 1; the new primary
wrote LSN 2 at epoch 2; the rejoining replica's LSN 2 is the old primary's
epoch-1 tail, or in the control the new primary's entry). It fails on main
(a conflicting same-length tail acknowledged at LSN 2) and the conflicting
tail is refused with the epoch-table reconciliation; the control still
acknowledges.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An apply admitted under recovery A's mark could land after recovery B took
the mark and completed: its entry lay under B's valid table, labelled B's
epoch. Every recovery-data apply (both lanes, dual lane through the gate)
now runs under the table's apply fence, shared, and only while its token
owns the mark; Invalidate, CompleteRecovery and Replace take the fence
exclusive, so a change of owner waits for in-flight applies to settle and
the old owner's later applies are refused. A catch-up may complete only if
the table was valid when it took the mark (one persisted bit); after any
overlap only a rebuild makes it valid. A catch-up states the LSN it starts
after, and the replica takes the mark only if its durable end matches. A
live entry of a new epoch is accepted only at the store's next LSN.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockmaster refuses --insecure-external-bind (a non-loopback --listen needs
mutual TLS; the runtime HTTP listener stays on loopback), and
--launcher-master-tls-secret-prefix makes each generated volume mount its
server's node certificate Secret and dial with it. The chart, the launcher
renderer, the alpha/g15b/g15d manifests and gate scripts mount the Secrets
and pass the TLS flags; network.externalStatus and the frontend runtime
HTTP option fail the render. scripts/k8s-alpha-certs.sh issues development
certificates and the role file. The systemd startup gate runs its
off-loopback master with mutual TLS.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The dual-lane path held the invalid mark under a sentinel no completion
presented, so a replica recovered through it reported no history for ever
and was rebuilt again. Its session now takes a tokened mark at
SessionStart, before any data frame (the per-frame invalidation is gone),
the primary's sender carries its epoch rows on the final barrier, and the
receiver completes under its token once the data is synced, before the
barrier is answered. Replace, the one unconditional writer, is pinned to
the primary role's adoption, after which the listener refuses every
inbound recovery frame.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two overlapping recoveries: A synced its data and paused, B started and
imported newer bytes (the table already invalid), then A's replace made the
table valid over B's data. Invalidate now draws a fresh random token,
persists it as the mark's owner and returns it; a later recovery takes the
mark over. A recovery completes only under its own token, checked and
written under one lock; any other completion is refused and not acked, and
a dead recovery's token is never presented again, so after a reload the
table stays invalid until a new recovery completes. Dual-lane sessions hold
the mark under a sentinel no completion presents. A promotion over an
invalid table clears the owner. The block design gains the epoch table's
state diagram.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A catch-up or rebuild applies history whose epochs arrive only at its end.
If the data was synced and the replace then failed or the node stopped,
the old rows named the new data, and after a promotion an old survivor
with different entries at those LSNs reconciled as shared. The table is
now durably invalid from the recovery lane's start, a rebuild's first base
byte and every dual-lane session, until the final replace: invalid reads
as no table, which reconciles as diverged, and a live note is refused. A
promotion over an invalid table makes it exactly [(epoch, next LSN)].
A census classifies every peer-apply path as row first or invalid first;
the writer census honours build constraints and fails on any type-check
error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two tables can agree on an epoch number and still describe different
histories: a survivor whose epoch 2 starts at 7 (an old tail 5..6 kept)
read as in sync with a primary whose epoch 2 starts at 5. The reply is
56 bytes (40 from a replica without the table); SharedEnd takes the
replica's (epoch, first LSN, end) and a different first LSN is diverged.
A rebuild whose table replace fails is not acknowledged, and the stale
table reconciles as diverged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A catch-up ships history under the session's epoch, and the replica noted
that epoch for it, so a byte-identical survivor of the older epoch later
reconciled as diverged. The recovery lane notes nothing; the catch-up's
final barrier carries the primary's rows and the replica takes them, cut at
its synced end, before the ack. The writer census type-checks the packages
and finds every call on an *EpochTable whatever the receiver is called
(alias and field controls). The block design's peer-state diagram shows
that every route to Healthy reconciles by (epoch, LSN) and that diverged
history goes to NeedsRebuild.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A primary that adopted an epoch over an unsynced tail, lost the tail in a
crash and adopted the epoch again kept the row's higher first LSN: its new
writes below it were attributed to the previous epoch, so an old primary's
unacknowledged tail in that range reconciled as shared. The ingress now
trims rows above the store's next LSN after recovery, and the next note
appends the row at its real first LSN. Every write keeps the newest 512
rows, so the record always fits the read bound; the rebuild-done list is
bounded the same way.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The engine's healthy verdict (a probe saw R >= H) and a completed recovery
session set the peer Healthy on length. Both now run a barrier and compare
the peer's (last data epoch, end) with the primary's epoch table: in sync
-> Healthy; diverged -> NeedsRebuild; behind or unanswered -> Degraded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ingress owns the volume's epoch table: the listener notes shipped
entries, the primary's row (epoch, durable end + 1) is made durable before
a primary role is adopted, and the replication volume reads it at the seed
barrier. A survivor whose entries are not the primary's (an equal length at
another epoch, a tail above the frontier, data without a table) needs a
rebuild and is not counted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Leader-epoch reconciliation: an entry's identity is (epoch, LSN). The table
answers, for a replica's last data epoch and end LSN, up to where its
entries are the primary's; an equal length at an older epoch is divergent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the degraded-peer probe loop on, a peer the seed barrier degraded for a
divergent tail would otherwise be probed, classified caught up (R >= H) and
fenced back into healthy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Write acknowledgements already count only peers that were healthy; the
sync barrier counted any peer whose reported length covered the target,
so a degraded survivor holding a divergent tail satisfied sync-quorum.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Above the promoted primary's frontier a survivor holds entries the primary
never had: an unacknowledged tail of the old epoch. The seed barrier
accepted it as caught up on length, kept the peer healthy and counted its
acks; it is now degraded like a peer below the frontier.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Until a replica has accepted the current epoch it holds only entries of
older epochs, and above the new primary's start position those were never
acknowledged. R above that start pins a rebuild instead of the caught-up
fence-then-healthy path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Keep main's claim-id and delete-authority rows and add the detached
rows; the delete row starts from live or detached.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GitHub-hosted jobs for this repository wait in a shared queue: since
04:21Z every spec trace job sat queued on ubuntu-latest with no runner,
so no pull request could pass its checks. The workflow's own comment had
said so (the hosted queue can wait for hours).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every pull request that added a row edited the hand-kept count line, so
each merge to main re-conflicted every open pull request. The check now
prints the count and fails if the file states one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The check runs no PR code and needs no project host, but it queued behind
the self-hosted test jobs; every PR's merge waited on that queue.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The M9 introduction names its one HEAD create (the deleted HEAD the
operator's remove-dependent writes for a restore target without HEAD);
the diagram and the transition table add absent -> deleted (tombstone)
and the release of a target from a source's dependents.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The strict-method guard is inverted: a new operator or admin method added
without Strict fails, and ReportClusterEvent (event log append only) is the
one named exception. The guide says the attempt line survives a blockmaster
crash, not a host crash.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The delete checked once that no block held the volume, then marked HEAD
deleting by a separate read: a grant and claim in between let it delete a
live volume. The delete now first has the master record its delete
reservation (no line is granted for the volume after it), then checks
that no line holds a live lease between the HEAD read and the
conditional update that marks HEAD deleting. After the reservation no
live lease can appear, and a claim landing between the read and the
update fails the update.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the claim id on, the transition table's holder rule is the epoch,
the server and the claim id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The removal planned only unmarked candidates, so a name marked by a
cleaning that died before its delete stayed in the pool for ever. Every
found candidate is now planned with its whole tag (session and mark) as
read; the conditional mark replaces an abandoned mark, and the dead
remover's late delete, conditional on its own mark, fails. The interrupt
test now requires every orphan gone after the re-run.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Start checked the local root against its first read of HEAD, then
claimed through a transition that read HEAD again without the check: a
claim by another lineage, or a published position rising past the local
root, between the two reads was written over. The local-root check now
runs again inside the claim's transition, on the very HEAD the
conditional update replaces.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The invalid-UTF-8 holder fixture lacked a volume id and a claim id, so it
was refused for those first and a mutant dropping the holder's UTF-8
check survived; every UTF-8 case now carries the other fields and
asserts the UTF-8 refusal itself. The M9 diagram and transition table
name the claim id in Claim (replay on epoch, server and claim id;
another claim id at the same epoch and server refused).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The operator's remove-dependent now writes the deleted HEAD for any
target without HEAD, not only one without VOLUME too: a restore that
died between its VOLUME and its HEAD would otherwise leave a target
that could be neither released nor deleted, pinning the source's
snapshot for ever. The later HEAD create of such a restore fails on the
tombstone, as before.
A volume delete refuses, before any write, a listed path that is not a
pool, segment or root object, so HEAD (which stays, deleted), VOLUME and
the directory are never removed. A source scan lists every delete and
every directory-naming site in core/ and cmd/ and fails on a new one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume's directory is <name>-<first 8 hex of its volume id>, created
exclusively and never reused; the reader reads a foreign chunk from the
directory its reference's owner name and id give, after checking that
directory's VOLUME id. For a restore target never created, the
operator's remove-dependent writes a deleted HEAD exclusively in the
target's directory (a tombstone, which needs no holder) and only then
releases the dependent, so the restore can never create the target
afterwards; if the target's HEAD appears first, the release is refused.
Only that command creates a tombstone (source guard).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DecodeWALRecordV3 wraps the decoder recovery uses (same geometry, size
and CRC checks and errors) and returns LSN, type, LBA, length and the
whole record size; WALRecordHeaderBytesV3 is the header the codec adds.
For read-only tools that analyse crash images; recovery does not use it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Read lazily after HEAD, a candidate's tag could already be a
successor's: a stale remover that paused after reading HEAD would then
mark and delete a chunk the successor had reused and committed. The
removal now reads every candidate's tag first, only then reads HEAD and
requires it is still this holder's with its own cleaning, and marks
against the earlier tags: a successor that acted before the HEAD read
leaves a HEAD that is not this holder's (nothing is written); one that
acted after rewrote the tag (the mark fails). Tests cover both, and the
old order fails the first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An integration test (stock weed, chunkstore_integration tag) runs the
layout's object writes against a real filer through a filer-backed
object store whose entries carry the writer's session and the removal
mark as extended attributes: a delete with another mark is refused; a
reuse by a successor makes the remover's late mark and late delete both
fail their conditions and the object stays; a mark on the current
metadata and its own delete remove it; deleting a missing entry
succeeds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A root counts as fresh from its creation until its restore's base is
durable, across any crash in between, so a restart continues the
restore (tested); a deleting volume does not start at the holder's own
epoch or above (the claim refuses it; tested now that both are on one
branch); a stale-root refusal names its cure: after a clean stop the old
directory holds nothing the published image lacks, clear it and start on
a fresh root (a planned move away and back).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every object entry now carries the id of its volume, stamped by the
store at create, and the store deletes on that condition
(DeleteOfVolume). DeleteVolume deletes its objects that way, so a late
delete of a finished run never removes the object of a volume created
again under the name (content names repeat across volumes). The removal
of the merged 7' change stays mark-gated; the guard keeps DeleteVolume's
order with the conditional delete.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DecodeHead now takes the id from the same directory's VOLUME and refuses
a HEAD carrying another volume id (ErrIdentity): a HEAD left by an
interrupted delete, or created late by an old restore, under a name
since given to another volume, is never read as this volume's. HEAD's
check refuses a holder without a claim id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The removal no longer rests on a lease check before an unconditional
delete, which a delete landing after the lease and a successor's commit
defeated. Every object entry carries the session of its last writer and
a mark. RemoveUnreachable plans after BeginClean, then for each
unreachable candidate MARKs it (conditional on the metadata read for
the plan, unmarked) and DELETEs it (conditional on that mark). Writing an
object for a session (EnsureObject) creates it, or reuses an existing
one by a conditional update that sets the session and clears any mark,
so a reuse after the plan or after the mark makes the remover's write
fail its own condition, however late it lands. A commit names only
objects its own session wrote or reused, unmarked.
The source guard now requires DeleteMarked as the remover's only
removal, each immediately after a gate on its mark's error. Tests cover
both reuse windows (after the plan, after the mark), another session's
mark, the commit's session rule and the cleaning killed at each of its
six writes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At an epoch above HEAD's a holder now claims only with a fresh root (it
restores from HEAD) or the root whose claim id HEAD holds (the
continuing lineage); any other root holds data older than HEAD's image
and is refused as stale, HEAD unchanged: the directory may be the only
copy of a reported lost range, and discarding it is the operator's act.
A root carrying HEAD's claim id but synced below HEAD's published
position is an old copy and is refused too. A start killed at its claim
restarts with the same marker and continues: the claim id it writes is
the one its local root already carries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Start is the HEAD side of a holder starting on its granted line with the
claim id its local root's marker carries. At HEAD's epoch and server it
continues only on the root whose claim id HEAD holds (its own restart,
or a claim whose reply was lost); a fresh root with another claim id is
refused as a missing local root, naming the likely cause and the way
back (a forced move, also to the same host); an older root with another
claim id is refused as stale and fenced; neither writes HEAD. At a
higher epoch it claims with its local claim id. The package guard makes
Start the only caller of the claim; the HEAD reader enumeration
classifies its read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The removal and HEAD-write rows exceeded the ledger's 300-character
statement limit; each is now split into rows of one property (the
removal itself, what stops it, its source guard; the HEAD write path and
its source guard).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In RemoveUnreachable every call of a Delete* or Remove* method must be
immediately preceded by an if on StillHeld's error that returns: an
ignored check, one check reused for a second delete and an unlisted
removal method each fail (controls built from the real remove.go). The
removal refuses an older epoch of the same server and the same epoch of
another server, each alone, and every non-Run function taking a
HolderID must be covered by such a case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The release step alone does not look at the target, so as the
operator's command it could release a live restore target and leave its
foreign references unprotected. It is now used only by the target's own
delete (its HEAD already deleting) and by OperatorReleaseDependent,
which reads the target first and releases only if it exists and is
deleted (HEAD deleting or deleted, or its name holding another volume
id) or no root in its live HEAD names a chunk of the source. A live
target still naming the source, one being created and one never created
(the restore could still create it) are refused, and the source is not
written. The package guard restricts the release's callers and requires
the operator's read of the target; the HEAD reader enumeration
classifies it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume delete runs in its order, each prefix safe and the whole
re-runnable: HEAD deleting (only with no holder, checked immediately
before, no open transaction and no snapshot with dependents), then this
volume released from every source's dependents, then its objects
deleted, then HEAD deleted. HEAD gains a state; from deleting on, every
holder transition, a claim and a removal are refused. A dependent is
released from a source by the target's volume id in one conditional
update, the delete's step and the operator's remove-dependent command.
The package guard allows DeleteVolume as the second remover and
requires its order (controls: the pool before the release, no holder
check); the stale-holder table now covers holder transitions only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A VOLUME record carries a random volume id, and identities never rest on
a name that can repeat: HEAD carries the volume id; every chunk
reference in a segment carries its owner's volume id, which a read
checks against the owner's VOLUME before fetching (a volume created
again under the name is ErrIdentity) and the remover uses to tell its
own chunks; every dependent records the target's volume id and the
snapshot's root hash; and a holder is its epoch, server and the claim
id its claim writes into HEAD, so every transition refuses the same
server with another claim id. Encodings stay canonical and decoding
refuses anything else; the segment format is version 2. Nothing writes
these shapes to a store yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reload used Load, which hides skipped corrupt records, and accepted
no record. The child stops after the rename without a power loss, so the
record is on disk: reloadExactly requires LoadWithSkips to return it
(deep-equal) with no skip, and its own controls refuse a corrupt, a
missing and a different record. The latch note and comments no longer
name a directory sync failure as a latch cause (that case fail-stops).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RemoveUnreachable is the cleaning's removal step for one pool shard: for
the holder with its own clean(session) open, it deletes each candidate
chunk that no root in HEAD (current or any snapshot) names in this
volume's pool, and checks its own lease immediately before every delete.
HEAD is read once after BeginClean: no commit can add a root while the
cleaning is open, and a claim that voids it waits for this lease to end,
which the next check sees. An unreadable root or segment stops the pass
before any delete; a lapsed lease stops it before the next one; an open
snapshot refuses it.
The package guard now allows Delete/Remove names only in
RemoveUnreachable and requires a lease check before every delete in the
same block (controls: no check, check after the delete, one check
before the loop). The HEAD reader enumeration classifies its read, and
the ledger gains the removal row and the read path's row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The rename is done, so a failed directory open or fsync leaves the
record's durability unknown. Reporting "failed" let a restart reload a
write its caller had acted on as failed. blockmaster now exits
(ExitDurabilityUnknown = 74, typed line) for every record type; the
restart reloads whatever survived. A close error after a good fsync is
reported written. Windows keeps its previous behaviour. The fault seam
names the step (open, fsync, close). INV-AUTH-PERSIST-BEFORE-PUBLISH-001
rewritten to match.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The child process does one Put with an injected directory fsync failure;
it must exit ExitDurabilityUnknown with the typed line and never return
to its caller. The parent reloads the store: the record or none.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unreadable directory or file was read as empty, so a partial inventory
could resolve as exactly one device; fs.Glob also dropped directory
errors during discovery. Every read error now refuses (the wait retries),
discovery lists nvme-subsystem and reads each subsysnqn, and the
literal-path fixture holds that path as an NQN so only the prefix guard
refuses it. Adds three partial-inventory controls.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The HEAD reader enumeration finds the layout package's one read path,
runTransition. Over an absent HEAD it refuses with ErrHeadAbsent and
writes nothing; a probe pins it with a store whose HEAD is absent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
nvme list-subsys -o json does not list namespaces on every nvme-cli, so
the device never resolved on a real host although the kernel connected.
kzResolve now reads /sys/class like the CSI node (subsysnqn, controllers,
transport, serial, namespaces under the subsystem or the controller) with
the same refusals, and a timeout reports the last refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockvolume refuses a non-loopback status bind; sw-block ops reach it
with --status-addr from the same host, so it uses headSzLoopbackAddr
like the NVMe listener.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockvolume refuses a non-loopback frontend listen; the test reaches its
NVMe target only from the same host (user-space client or kernel nvme
connect), so the NVMe address stays 127.0.0.1 (headSzLoopbackAddr) while
data and ctrl use SWBLOCK_TEST_LISTEN_HOST.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
blockmaster refuses a non-loopback --listen without it; a two-host run
(SWBLOCK_TEST_LISTEN_HOST set) now passes it. Loopback runs are unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Part A gains M9, the HEAD transactions of the content-named layout
library (diagram and transition table, Begin so far), and Part B gains
B.10 with the rows its tests enforce: canonical names and encodings,
the one HEAD write path, the HEAD encoding, and Begin. The library has
no production caller; the notes say so.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each transition is refused for an older epoch of the same server and
for the same epoch held by another server, in idle, snap and clean; the
table must name every Head method returning (Head, bool, error), so a
new transition fails until it is added.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EndClean over idle succeeds without a write whether the cleaning ended
or never began. A same-epoch caller that is another server is refused
(control added; with the holder check reduced to the epoch it fails).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Added beside the real claim.go, the control's RunClaim was hidden by
the real one's lease wait once claim.go exists; it now replaces the
file, as a changed claim would.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An empty image is a real root: once it is HEAD's current root, a commit
with an empty previous manifest builds on it instead of being refused
as a stale base. Before any commit a previous manifest must be empty;
after one it must build to HEAD's current root.
The snapshot transaction's interrupt test now checks, right after each
kill, every object any root in HEAD reaches (current and snapshot roots,
their segments, this volume's chunks, bytes hashed against names), on a
fixture that stores real objects. Controls delete a reachable chunk, a
segment or a snapshot root, or tamper with a chunk, and each is
reported. Abort after a commit leaves the commit in place.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Abort when HEAD is already idle succeeds without a write whatever came
before (aborted, committed or never begun); its result never says
whether the session's work was committed, which is read from HEAD's
current root. Controls cover the never-begun and already-aborted cases.
The interrupt helper again requires exactly one HEAD write per
transition.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lease rule checked whether the name RunClaim was used, not whether
the function was declared, so a declared RunClaim with no wait passed.
The guard now checks the package's declared functions: a declared
RunClaim must use OldLeaseEnded, and every declared exported Run
function must go through runTransition. Each negative control now
asserts the finding it is meant to cause.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guard now records every use of UpdateHead, runTransition,
OldLeaseEnded and Delete/Remove names, in function bodies and in
package-level initializers: a call, a method value or alias, a method
expression and an inline interface all count. Negative controls add
each form to the package's real sources and must be refused. The
comments on invalid UTF-8 now state what the old encoding did: it wrote
an escaped U+FFFD that its own canonical decode refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The JSON encoding turns invalid UTF-8 into U+FFFD and still re-encodes
the same, so HEAD would store another holder, session, snapshot or
dependent name than the caller gave and a later lookup by that name
would find nothing. check() refuses such names, and runTransition
checks the next HEAD before writing it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The whole transaction (Begin, every new chunk, segment and root, then
Commit) is run once to enumerate its writes; for each it is killed
before the write applies and after it applied with its reply lost. The
restarted holder rolls back the session it finds open, begins a new
one, recomputes what is new against HEAD's current root, reuses the
objects already written by name and commits. Every run ends at the
committed image with every object it reaches present.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Begin now writes through runTransition, the one read-apply-update path
every transition will use. A source-scan guard holds for the whole
series without edits: only runTransition calls UpdateHead and the store
cannot create a HEAD; every Run transition must have its closure and
interrupt tests; only a claim waits for the old lease; and no function
removes a store object until removal brings its own lease re-check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A source scan fails when UpdateHead is called anywhere but the shared
read-apply-update path, when a transition is added or removed without
being listed, when the HEAD store gains a way to create a HEAD, or when
the old-lease wait moves out of the claim. Every pure transition is
checked to refuse a holder below HEAD's epoch in every activity.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BeginClean moves activity idle -> clean(session) and EndClean moves it
back to idle, each by one conditional update for the holder at HEAD's
epoch. A cleaning and a snapshot exclude each other through the one
activity field; a claim voids an open cleaning. Replays of a lost reply
write nothing. Removal of pool names inside the session comes
separately.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claim lets a holder granted a newer epoch take HEAD: epoch and holder
are set and any open session or cleaning is voided (activity idle); the
image and snapshots are unchanged. The wait for every older holder's
lease to end is an explicit guard, run after HEAD is read and before
the one conditional update, on every claim that changes HEAD. A HEAD
already held by the caller at that epoch is a replay; an older epoch,
or the same epoch held by another server, is refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Commit ends a snapshot session: for the holder at HEAD's epoch with
snap(session) open, one conditional update sets the current root, the
position and an optional named snapshot and returns activity to idle.
Before it, every object the new root reaches must be written: the
chunks of this volume that are new against HEAD's current root, every
segment, and the root. The previous manifest must rebuild to HEAD's
current root, so what is new is checked, not trusted; unchanged and
foreign chunks are not looked up. A HEAD that already shows the commit
is a replay and nothing is written or looked up.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Abort moves activity snap(session) -> idle for the holder at HEAD's
epoch by one conditional update and changes nothing else; it is also
how a holder rolls back the session HEAD names after its own crash.
Abort over idle is a replay of a lost reply and writes nothing; another
open session or a cleaning is refused. Begin and Abort share one
read-apply-update path that refuses an absent HEAD.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The harness constructor picks five ports; the target role now reserves
the data and ctrl ports from the handoff before it runs, so none of them
can be picked locally and then refused as a collision
(TestKnownZeroTargetReservesBeforeHarness). Comments name the steps
instead of internal document revisions.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
HEAD is the volume's one mutable entry: epoch and holder, the open
transaction (activity idle, snap(session) or clean(session)), the current
root and position, and the named snapshots with their dependents (at
most 100). Its encoding is canonical JSON; decoding refuses unknown
fields and any bytes Encode would not write.
Begin moves activity idle -> snap(session) for the holder at HEAD's
epoch, by one conditional update on HEAD's generation. Begin of the
session already open is a replay and writes nothing; another open
session, a cleaning, another epoch or another holder is refused; an
absent HEAD is refused and never created.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- device mode reads the first block of every written file (FIEMAP via
filefrag, 4 KiB blocks) through the user-space client and requires it to
equal what was written: the block witnesses step 4 reads before hydration
- step 1 passes only with 0 candidates in S0 and every chunk known-zero
(kzStep1Pass; a partial certification or any scan refuses)
- a file write fails on any writer error, also one with output, and on a
read-back sha256 that differs (kzCheckWrite)
- the target role reserves the handed-off data and ctrl ports before it
picks its own (kzReserve)
Table tests for all four in known_zero_checks_test.go (no build tags).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Reader opens a root of a volume and resolves a chunk index through the
shard's segment to its ref, then reads the bytes from the pool of the
volume the ref names (a restore's source for a foreign chunk). An index
the root does not name reads as zeros; a root, segment or chunk the root
reaches but the store lacks is ErrMissing, never zeros; bytes that do
not hash to their name, or a segment holding another shard, are
ErrCorrupt; a failed fetch is neither. DecodeRoot now checks the error
of its re-encoding as DecodeSegment does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CI runs go test -short; the check builds blockvolume twice (a few
seconds) and must run there, not only in a full local run.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
TestKnownZeroAcceptance (tags subprocess chunkstore_integration, KZ_RUN=1)
runs the five acceptance steps on a fresh volume (KZ_SIZE, default
1T), each printing one "KZ STEP n PASS|FAIL" line with its counters into
KZ_REPORT:
1. the empty first snapshot stages and uploads nothing and HEAD names no
segment; the fresh attach certified the chunks known-zero;
2. mkfs (ext4 and xfs) or known blocks, sync, snapshot: the cut's work is
bounded by the chunks touched;
3. restore and fork of that snapshot on another server node: contents
equal, the first snapshot of each target without a full scan;
4. reads of snapshot-named blocks before hydration return data, never
zeros, and each read waits for its own fetch (AbsentChunks, Hydration);
5. the first start of a fresh volume killed before its attach commit: after
the restart nothing is certified known-zero, the first cut scans every
chunk once, the data reads back exactly.
KZ_ROLE source|target splits steps 3-4 onto a second host through a handoff
file; SWBLOCK_TEST_LISTEN_HOST (default 127.0.0.1) lets the test harness
bind a host address instead of loopback. KZ_DEVICE=1 uses the kernel
NVMe/TCP device, resolved only by the run's own NQN (kzResolve, with table
tests); a path given by name is never formatted.
Step 5 stops the process at the provider's existing boundary before the
fresh marker is retired, through a binary built with -tags kzhold
(HoldBeforeChunkFreshRetireForTest); a normal build contains none of it,
which TestKZHoldNeverInReleaseBuild checks.
The volume-size test's cluster and volume start move into shared helpers
(headSzStartCluster, headSzStartVolume) used by both tests.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A pure package for the content-named store layout: a chunk is named by
its index and the SHA-256 of its bytes and lives under
pool/<index/10000>/; a manifest is split into one segment per shard
(seg/<shard>-<sha256>) and a root naming them (root/<sha256>). Encodings
are canonical: decoding refuses any bytes Encode would not write, so an
object has one encoding and one name. Present and MissingOwn look names
up only: an entry that exists is complete, and a failed lookup is an
error, never absent. Nothing uses the package yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A source scan lists every non-test function in core/ and cmd/ that reads
a volume's HEAD (ReadHead, GetHead, GetHeadRoot, getHeadRoot, headExists,
or a LookupEntry of HEAD) and fails when a reader is added or removed
without classifying it. Each reader names what it does when HEAD is
absent and the probe that pins it; readers that take an absent HEAD for
an empty one are marked GAP, so a change to that behaviour flips their
probes on purpose.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A trace-driven matrix: each command is run once through a recording
filer to enumerate its filer writes (its step boundaries); then for every
write it is killed before the write reaches the filer and after it
applied with its reply lost, the catalog restarted, and the command
re-run (twice) with the same request id. The end state and the data are
checked: the volume deleted and refused, or the fork's or restore's
image reading back byte for byte. A killed fork's copy intent may outlive
the replay; the test checks it is that request's and that the copy sweep
past the deadline settles it with the image intact. A step added to a
command is covered without editing the test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unknown fact is not a failed one: the unsupported promotion path now
moves the line only on the current primary's own not-ready report, like
the supported path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Phase 0, S6: AuditLog writes one JSON line per event: every operator and
admin call (accepted or refused, including a handler's RequireRole
refusal), refused node calls at most once a minute per (fingerprint,
result, method), and every role-file reload with its outcome; accepted
node calls are not recorded. blockmaster --audit-log turns it on (with
authentication only).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Phase 0, S5: heartbeat, assignment stream (every volume), renewal and ACK
require the caller's certificate id to be the request's server id
(auth.RequireNode); the registered-host address checks stay beside it.
QueryVolumeStatus admits a node only for a volume whose line it
holds. A forced MoveWorkspace needs an admin. Development mode admits as
before. T2 starts its master.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A delete admitted as never started that stopped before it marked HEAD,
after which the holder claimed HEAD, was refused at the master on every
rerun, before the catalog step that gives the reservation back: the
volume stayed reserved for ever. A rerun whose token already holds the
reservation (or a committed one) now skips the verdict; the catalog
step's HEAD fence refuses the live HEAD and gives back.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Phase 0, S4 (volume side): --master-tls-cert, --master-tls-key and
--master-ca put the volume host's master link and the GC epoch pull on
mutual TLS (the filer links are unchanged). The start is refused when the
node certificate's CN differs from --server-id, when the set is partial,
or together with --allow-external-status-bind.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Phase 0, S4 (master side): --tls-cert, --tls-key, --tls-client-ca and
--role-file together turn on mutual TLS and per-call authorization; a
partial set, or authentication with --insecure-external-bind, is refused;
the authenticated listener may bind any address. SIGHUP reloads the role
file (a bad file keeps the previous table and says so). The start-up line
gives the master's own certificate's expiry; development mode repeats its
UNAUTHENTICATED warning once a minute.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Phase 0, S4 (transport): TLSFiles (cert, key, CA: all or none, checked at
start), ServerCredentials (client certificate required and verified to the
CA), ClientCredentials, DialMaster (TLS or development-mode plaintext), and
a 24 h connection age. Both sides read their certificate at every
handshake, so a rotated file takes effect without a restart. Dial (the
SeaweedFS filer links) is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Phase 0, S3 (master part): masterRules covers all 24 blockmaster methods
(PHASE0-AUTH section 3); the gRPC server takes Config.Auth's interceptors,
or development-mode ones when authentication is not configured, and
Config.ServerOptions. T2: every registered method has a rule and every rule
a method.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Phase 0, S3 (core part): the unary and stream interceptors authenticate
every call (PeerIdentity), apply the method's rule (people from a minimum
role up; nodes where allowed; a method without a rule is refused), and put
the principal on the context for RequireNode (own server id) and
RequireRole. A stream re-authenticates before every send and at every
role-file reload, so a removed caller loses its open stream at the reload.
Development mode marks calls explicitly; a call no interceptor saw is
refused by the handler checks (fail closed).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
core/auth (phase 0, S2): ParseRoleFile/LoadRoleFile (sha256:<hex> role id),
an Authenticator whose table swaps atomically (a failed reload keeps the
previous table), and PeerIdentity: the leaf certificate the TLS handshake
verified to the client CA, its fingerprint bound to a role and id, CN equal
to that id, not expired on the master's clock; every failure is
UNAUTHENTICATED. authtest issues test CAs and certificates.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The HEAD reader refused a deleting, purging or deleted HEAD as invalid,
so a never-started delete whose commit timed out (or whose mark's outcome
was unknown) was refused on every re-run: the volume stayed unusable and
undeletable. Such a HEAD can no longer be claimed, so it is past the
fence: the reader returns it with ErrWorkspaceHeadDeleting and the
verdict admits it (HolderDeleting).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The directory fsync after the rename was best-effort for every record but
a workspace lease: its error was ignored, so a write a crash could undo
was reported as written. It now fails closed for every record. Windows,
which cannot fsync a directory, skips it as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adopting the master's assignment comes before the HEAD claim; a start
that adopted and then lost the HEAD race to the delete never served.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The master's HEAD reader refused the initial HEAD (epoch 0, no holder) as
invalid, so the delete saw every never-started line as unreadable. It now
returns that HEAD with ErrWorkspaceHeadUnclaimed: every caller that needs
an identity still gets an error; the delete evidence reads it as epoch 0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TERM-LIVE-HOLDER-001 (the one verdict), INV-WS-DELETE-NO-LIVE-HOLDER-001
replacing INV-WS-DELETE-NEEDS-ACK-001 (ARCHIVED with its reason), and the
M2 'none, Granted or Expired -> Deleting' transition.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One pure verdict for 'live holder of V' (TERM-LIVE-HOLDER-001):
WorkspaceHolderState(line, ACK, HEAD) -> no line, drained, sealed,
never started (HEAD below the line's epoch), live, or unknown. The chunk
volume delete's admission (MarkVolumeDeleting) reads HEAD before its
locks, bounded at 5 s, and admits no line, drained and never started; a
sealed HEAD without an ACK, a live one, or an unreadable HEAD is refused
as before. The delete's HEAD compare-and-swap to deleting stays the only
fence against a claim that lands after the read. The lifecycle
DeleteVolume reads no HEAD and keeps refusing a line without an ACK.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
It measures the store write p99 beside the master's store before and
after the restart and asserts the bar only below 20 ms; otherwise it
reports the numbers without failing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The host owns the startup wait's one bound: it keeps the wait's start and
opens the window at the first reply at or after it; the run of replies
(and the window) ends on a transport, credentials or identity refusal;
/status shows the same bound. The provider asks the host for the bound
given its own start, and checks it on the attach retry path too: a
granted attach that keeps failing no longer holds the lease for ever
without serving. An identity refusal ends on an accepted identity-checked
call (the run of replies restarts there) or after 30 s of replies with no
new identity refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The master refuses an unregistered server id or a wrong host with a
typed IDENTITY detail (kind unregistered or wrong_host) on the lease
renewal and the assignment stream, text unchanged. The volume treats it
like refused credentials: no bound, /status reason "identity refused:
<kind>" with its age, never serves; it ends when an identity-checked
call (renewal, delivered assignment) is accepted, not on a heartbeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The 30 s window opens at the first reply from blockmaster received after
the store is opened and recovered (or at a later streak's start), and runs
from the master's barrier time when that is later; local open and
recovery count toward nothing. The host hands the provider its contact
facts (streak start, latest reply, barrier time, final refusal).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The host's bound counts from the first answer, but the lease guard (the
only source of the barrier time) starts after the local open and
recovery: a slow open found the bound already spent and exited 75 on
every start. The wait now ends no earlier than its limit from its own
start, and a grant on the same tick attaches before the bound is checked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lifecycle page says how the start waits (no bound while blockmaster
gives no reply, 30 s from the first answer or the barrier), what the new
log lines mean, and what to do on exit 78 reason=moved or reason=deleted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
For 5 s after the master's barrier time the pre-grant poll is 200 ms
(jittered): every lapsed volume re-grants at once, and the ones that find
the publisher busy retry soon instead of a second later (20 volumes:
worst 2.2 s after the barrier with the 1 s poll).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A row and a test for the two per-volume counters the status already
reports: the HEAD-named chunks still to hydrate (AbsentChunks) and the
chunks hydrated so far (Hydration.Completed, cumulative). On a restore
target whose HEAD names two chunks they start at 2 and 0; a read of an
un-hydrated chunk moves both by one and a repeat read moves neither, so a
caller can prove a read happened before its chunk was hydrated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason line and its 10-minute repeat no longer depend on someone
reading /status. A flapping master postpones the bound and never ends
the wait early: tested and noted under INV-WS-MASTER-WAIT-001.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guard reads the host's barrier time (one copy) and wakes 100 ms past
it plus up to 500 ms of jitter, capped at 2 min; its 1 s pre-grant poll is
jittered by 20 %. The master's retry_after uses the same two predicates
as admission: lease expiry plus skew (wall) and the grant deadline plus
skew (its monotonic clock), each measured from now.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A line naming another replica at the caller's epoch or below is OTHER,
not MOVED: a false MOVED is exit 78, which the unit does not restart.
Tests: the decision table, and a move away and back on the real master.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A restore target whose HEAD names two chunks, held at the attach commit
boundary: a frontend read of a HEAD-named block is not served, the remote
serves no chunk read, and after the commit both named chunks are still
absent with no fetch started (no fill wrote the extent); the read then
returns HEAD's data. A shortfall in the fresh attach's certification is
logged as a warning.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A source-level test checks that the store opener binds exactly one data
sync for its file and that both the flusher's extent sync and the WAL
sync use it (a range sync, a second descriptor, or a WAL sync that no
longer calls the shared sync fails it). The checkpoint bound over a
superseded synced record rests on this. The crash test helpers also close
the owned-map file of a crashed store, so the crash tests' directory
cleanup no longer fails where an open file cannot be deleted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ApplyFreshKnownZero now records the count in Stats.KnownZeroChunks and
logs it; when some sampled chunks stay unknown (a failed map publication
or a raced write) the log says the first cut will scan them, so a lab
run that sees a full first scan has the reason in the status and log.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two parts of the rule are added. Certification needs the store to have
been created by this process start (an in-memory bit, never persisted):
a fresh marker left by an earlier start, an older binary or another
opener is never trusted, so a first start that dies before its attach
commit pays one scan. And the order is: the attach commit retires the
marker, then the marking is made durable, then the volume serves; a
crash between the first two leaves no marker and every chunk UNKNOWN
(one scan). The user guide states that every explicit implementation
other than walstore-chunk refuses a chunk root.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fresh store (its .chunkfresh marker present at the attach, no BASE) has
never had a write or a fill reach it, so every chunk its claimed HEAD
does not name is zero on both sides. Its attach samples, under the
capture barrier, the token of each such chunk whose owned-map entry is
still the creation value, and clears only their UNKNOWN through the cut's
own map publication, before the attach commit. The first cut of a fresh
volume, hand-over target or restore target then scans only the chunks
written since, not every chunk of the volume. Chunks HEAD names stay
absent and are hydrated from HEAD.
The premise is enforced: every implementation other than walstore-chunk,
explicit as well as auto, refuses a root carrying chunk metadata, so no
plain walstore write can reach a store whose marker says none did.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A store created empty against a HEAD never claimed, with two chunks
written (one checkpointed out of the WAL), must have two first-cut
candidates and publish both; today all chunks start Unknown and every
chunk of the volume is scanned. Two tests that pass today pin the scope:
a store created against a claimed HEAD, and a restore target, keep every
locally held chunk a candidate.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-WS-MASTER-WAIT-001 (new, ACTIVE), its C.W wait site, and the
startup-wait wording of the M2 exit transition, INV-WS-SERVE-LEASE-HELD-001,
TERM-SERVING-001, TERM-STOP-EXIT-001 and the supervisor retry row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replaces the measurement of today's give-up (start limit after ~6 min)
with the requirement: one fence restart, never failed, MasterWait
unreachable on /status, serving within 2 s of the master's barrier.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
b=X and c=Y synced, then b=Z unsynced: the flusher skips b (its newest
entry is unsynced) and its checkpoint passes X's record, which never
reached the extent. Crash after the checkpoint, with the WAL region as of
the last sync that covered it: b reads Z, because the flusher's sync is
the whole-file fsync of the one descriptor. The control models an
extent-only flusher sync and loses X (b reads the bytes from before X),
showing the checkpoint bound rests on that. INV-WAL-FLUSH-SYNC-COVERS-WAL-001
moves from STUB to ACTIVE with this test; INV-WAL-V3-WRITE-AHEAD-001
states the dependency.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The flusher keeps only the snapshot's synced entries before its empty
check, so a cycle over unsynced writes alone writes no extent and makes
no fsync (it fsynced an empty batch before). A new test drives a guest
that never flushes: below the WAL pressure threshold nothing reaches the
extent; past it, the flusher's pressure sync makes the writes durable and
the same cycle writes every block's newest bytes and advances the
checkpoint.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Page writeback has no order across offsets of one file, so an extent
written from a WAL record that is not yet durable could survive a power
loss that loses the record: extent bytes no recovered record or map
entry accounts for, under a chunk certified equal to HEAD. The flusher
now skips dirty entries above the synced (acknowledged) WAL frontier;
they stay dirty until a Sync or the pressure sync makes them durable,
and the checkpoint is computed from the written entries only (it was
already clamped to that frontier). Recover and the install log already
fsync their records before raising the frontier.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The flusher writes a dirty block's extent before its WAL record is synced
(below the WAL pressure threshold it does not sync first). The test runs
the real flusher, cuts the power at its fsync (the extent page it wrote
kept, the unsynced WAL record lost, no checkpoint), recovers and
re-attaches: the block reads the lost write's bytes locally while HEAD
holds the chunk without them, and the chunk is not a cut candidate, so
nothing reconciles local and published. Fails on main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The startup authority wait no longer runs out while blockmaster gives no
reply or refuses the node's credentials. Its 30 s bound counts from the
first answered contact, or from the master's barrier time when later;
a typed MOVED or DELETED renewal refusal ends it at once with exit 78.
Before its first grant the lease guard sleeps until the barrier time
instead of polling every second.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RenewWorkspaceLease refusals carry a WorkspaceLeaseRefusal status detail
(code and text unchanged): BARRIER with the time left until the
forced-move barrier passes, MOVED only when the published line names
another replica or a newer epoch owned by another known server, DELETED
only for a committed deletion. Everything else carries none (OTHER).
The barrier comes from a typed error, never from the text.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume process will wait through a master outage on one channel, so
gRPC's default back-off (to 120 s) would delay the first call after the
master returns by up to two minutes. Only the two blockmaster dials
change; MinConnectTimeout stays 5 s for the handshake.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
StagedChunks is counted when staging remembers a chunk for reuse, so a
round interrupted partway counts what it finished instead of nothing;
the copy window, which shares the upload stream, does not count. The
counter's contract (only grows, a re-staged chunk counts again,
in-process) is stated in the status and in a new invariant row with its
tests: an exact count of 6 for a failed attempt, 0 for its reusing retry,
and 5 of 6 for a round whose upload fails at the sixth chunk.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A cut's PayloadNs now counts its staging rounds even when they uploaded
nothing (every staged chunk was zero), so a first cut that spent its time
reading and hashing shows it. The layer status gains StagedChunks: the
chunks staged by every cut attempt, failed ones included, so a cut retried
after its deadline shows the progress its earlier attempts made.
DirtyChunks is documented as the next cut's candidates, not its progress.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TEST V1-SPEC r2.104: after every cut attempt HEADSZ stores the volume's
whole chunk section of its durable status as served (every counter and the
full LastCut), so a term the named fields do not cover can still be read.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
TEST V1-SPEC r2.100: after every cut attempt HEADSZ records the volume's
DirtyChunks (capture candidates) and its last successful cut's
CandidateChunks, UnchangedChunks and PayloadNs, as the durable status
reports them, so the candidate count and its cost are measured per size.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
TEST V1-SPEC r2.99/r2.100: the shared sw-block runner kills a command after
150 s, so a cut longer than that never reached the server's own operation
deadline. HEADSZ now runs the snapshot command with its own bound, the
command's --timeout plus a minute, and records a command it still has to
kill as an attempt. It also records the volume's DirtyChunks (its capture
candidates) before the first cut.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Under systemd blockvolume refuses --volume-lock-dir-test-only (exit 2), so
the first run never reached the filer check. systemd 249 reports the start
limit as a failed unit with Result=exit-code and 'Start request repeated
too quickly', not Result=start-limit-hit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TEST V1-SPEC r2.99: HEADSZ_SNAPSHOT_TIMEOUT passes the snapshot command's
--timeout (the server caps it at its operation deadline); HEADSZ_ATTEMPTS
retries a failed cut with the same request id. Every attempt is recorded
with its error, wall time, the volume's last cut and its chunk-key count in
the filer afterwards, so a retry shows whether an earlier attempt's uploads
were kept. A cut that never completes is recorded as cut_not_completed.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
INV-VOL-GEOMETRY-FLAGS-RECORD-001: in create mode a ReadVolume error was
taken as an absent record, so a wrong --durable-blocks could still create a
wrong-size store when the record could not be read. The error is now
classified (one type check): the filer failed the read (remote unavailable,
deadline) -> exit 75, retried: 'the volume record of V could not be read
(<cause>); no local store was created; retrying'; the record is there but
does not decode -> exit 78, not a retry loop: 'the volume record of V is
unreadable (corrupt: <cause>); no local store was created; restore or
recreate the record'. An absent record (not found) keeps the create path.
A first start with the filer down was already safe: it ends at the startup
filer check (exit 1) before this one.
Tests: unit, both classes (a failing LookupEntry -> 75 for a wrong and a
right flag, the record read; a corrupt VOLUME entry -> 78);
TestCorruptRecordIsRefusedBeforeTheStoreIsCreated (filer up, the VOLUME
entry undecodable: 78 and no store for both flags; restored: 78 for the
wrong flag, the right flag serves); TestFirstStartWithTheFilerDownCreatesNoStore
(guard). The ledger row and the operator guide say so.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-WS-DELETE-NO-LIVE-HOLDER-001; red on main by design (the fix is the
live-holder change). Three routes, none needs root, each asserted by the
master's authority record (the line) and HEAD before any delete:
- S1: a first start with the store down (line at 1, no lease, HEAD 0);
- S2: a first start stopped at the lease grant (line and lease at 1,
HEAD 0; the next candidate when the claim wins);
- a clean move whose target never starts (line and lease at e+1, HEAD at
e, detached).
volume-delete without a revoke must complete (at once, after the lease
lapsed, after a master restart), a later start must not claim, and a
racing start and delete have one winner. Guards, green on main: a
never-attached target is deletable and fenced, and a claimed target stays
refused after a master restart.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IMPL V1-SPEC r2.94: an env-gated integration test (HEADSZ_RUN=1) that writes
one 4 KiB block in every 1 GiB segment of a volume per size in HEADSZ_SIZES,
takes a snapshot, then snapshots after one changed block each, and reports
per cut the HEAD entry's byte size from the filer, the segments it lists, the
cut's timings and the bytes it uploaded. A size the durable root cannot hold
is recorded as refused by the headroom check. No assertion on the numbers.
The weed cluster helper gains a sized variant; existing callers keep the
same 32 x 256 MB volume server.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The unreadable-record control reads a valid volume through a filer whose
lookups fail and asserts the read happened. The cure test's right-flag
start on the planted store must exit 75 with the attach check's
geometry_mismatch and never log a frontend phase over its life. The
ledger statement keeps its meaning in 288 characters.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-VOL-GEOMETRY-FLAGS-RECORD-001. A create-mode start whose
--durable-blocks/--durable-blocksize disagree with the volume record exits 78
(no restart) with a line naming both geometries, before the durable provider
is built, so no local store of the wrong size is created. An existing local
store is never rechecked against the flags (its geometry is checked at
attach, as before); a missing record keeps the create path; an unreadable
record falls through to the attach check.
Tests: TestGeometryFlagsRefusalComparesTheRecord (unit);
TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated (real binaries, red on
the previous main: exit 75 after 35 s and a wrong-size store). The cure for a
store an earlier release left stays: TestWrongGeometryCureAsWritten plants
that store from a readable text fixture of a 2129a736 capture (sha256 checked
per file); the operator guide scopes the cure to such a store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The retry bound is the snapshot command's 60 s operation bound
(F1_SLOT_RETRY_SECONDS, 0 = no retry, the negative control). A snapshot
still refused at the bound fails the rung as not admitted; restore_exact
reads "not_run" for it, never false. The slot wait is reported and the
write window starts at the admitted attempt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
N volumes snapshot at the same instant against fewer host slots; the slot
refusals (host_slot_busy, capture_refused from the host limiter) are
retryable by contract. F1 now resends them with the same request id every
250 ms for up to 120 s, records the count per round, and keeps the wait in
the request-to-commit time the starvation bound checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A runCLI goroutine that outlives its test would make t.Logf panic; a done
flag set in t.Cleanup turns logCommand into a no-op from then on.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
h.run and runCLI write each command's argv, exit status and output (each
stream capped at 4 KiB) to the test log, so a refusal is visible without a
rerun.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A blockvolume started with half the spec's --durable-blocks creates its
local store at that size, never claims HEAD and exits 75; a right-flag
start then fails on geometry_mismatch. The test checks the guard (ops chunk
show: epoch 0, no holder), removes the four local files, starts with the
right flags and serves; the guard then reads as claimed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dialNVMe sets one deadline 60 s after the dial; the F1 writer runs for
F1_WRITE_SECONDS (120 by default), so the connection timed out after about
4096 writes, just as the snapshots began. Each write now gets its own 30 s
deadline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review: a refused chunk create left its fresh marker; a fresh 256 MiB store
(WAL only allocated) with 256 MiB free gave no warning.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A full local disk fails guest writes (a Linux guest sees EREMOTEIO after
about 75 s), so the defence is headroom (V1-SPEC r2.60, issue 484): create
needs free space >= volume size + the 64 MiB WAL, and the refusal names both
numbers; an existing volume opens, with a loud warning, when its remaining
sparse growth + WAL exceed the free space. No new state.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A healthy lease admitted beside an urgent fallback lease kept no pacing
(review). The pacing error wrapper now has a test: prefix, cause, no put.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On a full local disk every flusher cycle failed its extent write with ENOSPC
and logged it, about 100 lines in 10 s. Terminal errors stay unlimited.
Issue 484.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On a full or unusable --host-limit-dir only urgent work (the seal at stop)
runs, on the static fallback. Pacing it at BytesPerSecond/FallbackVolumes
(320 KiB/s by default) made detach --plain time out, reported as 'chunk
remote unavailable'. With no shared cap to protect it is not paced now, and
an upload-pacing error says so. Issue 486.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
release: OSS train 29 (heartbeat order per slot #453; permanent recovery cause at the guest gate #464; delete refusal names its cure #448; fork deadline before metadata writes #454)
The unit ladder's dying cut retried its failing uploads until a context it
shared with the restarted process expired; it now has its own short
context. The procedure test proves the kill landed mid-upload (new chunk
objects on the filer, HEAD unchanged) and otherwise adapts the delay and
repeats with a new image. The fresh-root test kills once 8 writes are
flushed, so the reader is still filling.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Single-volume coverage gap 2, procedure part (cells P8.7, P9.4, P11.3;
V1-SPEC r2.55): image A is cut, every block rewritten (image B), and the
holder SIGKILLed half-way through the second cut. After the restart HEAD
verifies whole at depth data, the volume reads B, and the next cut,
restored into a new volume through a snapshot, is B.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Single-volume coverage gap 2, unit part (cells P5.4, P6.4, P8.7, P9.4,
P10.4, P11.3; V1-SPEC r2.55): a cut dies after admission, at the barrier,
during the upload, before the HEAD CAS and after the CAS applied (before
its reply). The process death closes the store without cleanup and loses
every later remote call. After the restart HEAD is whole (old before the
CAS, new after it), every synced local write reads back, and the next cut
publishes the volume as it is.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Single-volume coverage side finding (c) (V1-SPEC r2.55):
walstore_sticky_fsync_test.go, walstore_midhistory_hole_test.go,
walstore_checkpoint_crash_linux_test.go and walstore_checkpoint_safety_test.go
held only helpers or constants with no caller (their tests were retired
with format v2; docs/design/format-v3-legacy-test-inventory.md lists them
and their v3 replacements). walstore_recovery_hardening_test.go keeps its
one used helper, crashRecoveryHardeningStore. A comment that pointed at a
deleted file is removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Single-volume coverage gap 1, cell A3.5 (V1-SPEC r2.55): after a clean move
to s2 (fresh root, lazy hydration), a reader walks 60 chunks that only HEAD
holds while a writer streams Flush-acknowledged writes into other chunks;
s2 is SIGKILLed mid-walk and restarted at the same epoch; every source
chunk must read back (fills redone) and every acknowledged write survive.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Single-volume coverage gap 1, cell A2.4 (V1-SPEC r2.55): a qd1 NVMe/TCP
writer streams distinct blocks with a Flush every 8 writes; the holder is
SIGKILLed mid-stream and restarted inside the lease at the same epoch;
every Flush-acknowledged write must read back, and what survives past the
last acknowledged Flush must be a prefix of the stream, untorn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
V1-SPEC r2.53. The rung polls the master's view of every source volume's
replica each second (GetVolumeStatus) and records each span the master does
not observe it, epoch changes and frontend-not-ready polls; it counts the
master's per-slot "heartbeat superseded" lines per volume. Pass rule: zero
slot expiries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
V1-SPEC r2.49/r2.52. Opt-in (F1_RUN=1, a large test, never in CI): N
blockvolume processes under ONE server id, each its own replica id and
ports, snapshotted at the same instant per round under write load; every
snapshot restored and verified (ledger exact, load a prefix); the JSON
report carries cut time and barrier pause, client write p50/p99/max inside
and outside snapshot windows, request-to-commit time, host-slot waits,
restore time, chunks/bytes uploaded, filer entries per round and RSS. The
procedure harness's bvHost gains optional server and replica ids.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
B1: the list is exactly the committed snapshots, in order, active, with
the point, generation and chunk count their creation answered; a prefix
shows one; a snapshot being taken is listed only committed and stays; a
refused snapshot (a restore volume not yet independent) leaves no name.
C1: a five-chunk image restored to independence equals the snapshot block
by block. C2: the second and the third incremental snapshots restore to
independence as their points. C3: a restored volume, once independent,
written and snapshotted, restores with its writes, and the source's
snapshot still restores unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ladder's blockvolumes run with --chunk-capture-interval 0 and
--chunk-snapshot-schedule off, so A2 counts only its own snapshot's
uploads. A1, A2 and A4 also read a block in an untouched chunk and the
volume's last block through the restore. A3 runs three snapshots that start
after 0, 40 and 120 of their writes, logs the prefix each holds, and fails
as inconclusive if every one landed before or after all its writes. The
header says an A test never deletes a snapshot or runs GC.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A3: blocks written one after another while snapshot 2 runs; its restore
holds a prefix of those writes (one point in time) and snapshot 3 holds
them all. A4: one block holds A, B, then A again with a snapshot after
each; the three restores read A, B, A.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A1: one block written, one snapshot, the snapshot read back block by
block holds that block and zeros around it. A2: an incremental snapshot
holds the volume at its point, the first snapshot is unchanged, and the
second snapshot uploads only the two chunks that changed. A snapshot is
read through the product's own path, a restore into a new volume, so the
tests do not depend on the chunk format. The procedure harness gains
restore-target volumes in the cluster spec, each on a node of its own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A line starting with "<<<<<<< " or ">>>>>>> ", or a line that is exactly
"=======", in docs/design/invariants.md or the lists invcheck reads fails
the test with its file and line. The marker check is pinned on a fixture
that holds a conflicted region and two look-alikes it must not report.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lock directory and its parent are chmod'ed only when this call's own
Mkdir created them, so an existing or concurrently created directory keeps
its mode; an existing lock path that is not a directory refuses (Lstat), as
the constructor did before. The invariant row links the mode tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The new helper treats any existing lock path as the directory; the old
constructor refused a non-directory. Controls: an existing parent and an
existing lock directory keep their modes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A missing /run/sw-block is created 0755 and the locks directory 0700, with
the modes set explicitly (the umask cannot narrow them); existing
directories are left alone. The cure line also names the parent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
V1-SPEC r2.45 (1): MkdirAll(locks, 0700) also makes a missing parent
/run/sw-block 0700; created by root, it keeps the unit's user out even after
the locks directory is chowned. The tmpfiles.d layout is parent 0755,
locks 0700.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A test runner that is itself a systemd service (the CI runner unit) passes
its INVOCATION_ID to every child, and blockvolume rightly refuses
--volume-lock-dir-test-only under systemd. Every subprocess start that
passes the flag now builds the child's environment without INVOCATION_ID
(one helper per test package). The product rule is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The rolled-back copy makes no HEAD CAS attempt (counted at the remote,
not inferred from PUTs).
- Control: an exact copy passes the preliminary HEAD read; HEAD then
advances at the same epoch and holder before the claim's own read; the
claim-image recheck refuses it as stale, with no CAS.
- The refused second provider leaves its storage root empty.
- The --help capture registers stderr restoration and pipe closes first,
closes the writer before joining the reader, and bounds the join.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The lock directory is created (0700) when missing; only a directory or
lock file that cannot be created or opened refuses, with the cure
(install the tmpfiles.d entry, or chown the directory and its lock files
to the unit's user).
- The lock file is opened read-only (an existing file first, created 0644
only when missing), so a lock file another user created stays lockable;
it is never unlinked, and the next owner locks the same file.
- A stale-root startup end carries its cure into the final exit line:
exiting status=78 reason=superseded cure="...".
- Tests: a cut's remote_lsn is locally durable at its HEAD CAS, and the
root's crash image at the CAS reattaches and serves; the rolled-back copy
makes no claim or PUT, admits no I/O, keeps its data and durable LSN; an
exact copy at HEAD attaches; a read-only lock file is taken.
- Invariants: INV-WS-ONE-PROCESS-PER-HOST-001 and its M4 edge; the
rollback row names its test file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
V1-SPEC r2.45.
(1) The provider takes an exclusive, non-blocking lock on
/run/sw-block/locks/<volume id>.lock before the volume's store opens and
releases it after the store closes (HostVolumeLock, set by blockvolume). A
missing directory refuses the provider with the cure; the tmpfiles.d
entry ships in deploy/systemd and both units may write it under
ProtectSystem=strict. --volume-lock-dir-test-only (hidden, refused under
systemd, warned at start) is for plain subprocess tests and harnesses.
(2) An existing root whose HEAD names this holder attaches only if its
local durable LSN reaches HEAD's remote_lsn; otherwise the existing
stale-root refusal, no retry (78 superseded), with the cure.
(3) docs/releases/one-process-per-volume.md: the lifecycle do-not list.
No HEAD change, no format bump, no new persisted file, no new exit reason.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A second provider for the same volume on one host (another storage root,
the same host lock directory) must be refused before its store opens; a
missing lock directory, the default one included, refuses the provider;
blockvolume's test-only lock directory is hidden from --help and refused
under systemd.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
V1-SPEC r2.45 (2): an existing root whose HEAD names this holder must
reach HEAD's remote_lsn with its local durable LSN. A copy taken before a
later cut attaches today.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The move to s2, HEAD reclaimed by s2, the forced move, its dry-run
previews (refused with an admissible time, then admitted) and lost-range,
captured from a passing gate run, are read by the default-build check
test; each check also refuses a neighbouring output.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The old host returning after a forced move: the absence checks run only
while it is alive; it must exit 75 and log a refusal; a supervised
restart and a start on a fresh local root (a control: no stale root to
refuse) must do the same. The refusal text that the product never
prints is dropped.
- The same-host restart is the page's systemctl restart (SIGTERM, a start
within RestartSec); the crash restart is its own test. Both must serve
within 15 s, as s1/r1 at the same epoch.
- The barrier wait requires at least one barrier refusal, compares with
one second of log resolution, and requires the re-grant line.
- Too early: the exit reason assignment_timeout, and the same serving
predicate as the barrier wait.
- The planned hand-over runs the page's step 1 and reads a never-written
block as zero (a control).
- The lapsed-lease return must serve within its 30 s authority wait, as
s1/r1. Comments match the order of the revoke-without-ACK steps.
- Harness ports come from 10000-19999, below weed's range; sw-block output
can be captured to HANDOFF_CAPTURE_DIR for the fixtures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Table for wrongOwnerEndpoints: both positive passes; an unreadable log, a log with no
forced-epoch delivery, an empty log, or another host's endpoints in either recipient
rejects (#425).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stop test now observes the worker's return on its own channel with
bounded joins on both paths (a re-check that ignores the stop fails in 12 s);
agent-workspace-design.md's supervisor diagram adds Serving -> Exit78 on a
runtime HEAD fence (head_fenced), independent of the lease.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
V1-SPEC r2.39: StorageBackend.AdmitsIO is the I/O gate itself (the backend
admits I/O AND the guarded projection names this lineage as the healthy
primary). /status FrontendPrimaryReady and NotReadyReason read it through
the provider (lease_not_held stays first; an unopened volume fails closed).
A workspace chunk primary's frontends start once AdmitsIO passes after the
backend first admitted I/O (firstAdmitted: a bounded 50 ms re-check until
first served, workspace primaries only; the backend has no projection-change
signal). Non-chunk volumes and supporting replicas start after open as
before (the #410 design condition, V1-SPEC r2.39), now pinned by a test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-FE-PRIMARY-READY-OPERATIONAL-001 keeps the readiness and listen
property; the fence-to-exit bound is its own row, INV-FE-FENCE-EXIT-001,
stated as what is guaranteed: the fence's detection time (a HEAD fence:
50 ms) plus the existing 5 s cleanup bound from the decision. 307 rows,
221 ACTIVE.
Provider Close joins each layer's fence watcher through p.inflight
(counted under p.mu while not closed). C.W lists the two new waits.
The runtime-fence watcher test owns its worker: cleanup registered before
the start, the return joined with a bound on both paths.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A chunk layer that fences after startup (HEAD has another publication
owner) while the lease is still valid now latches the backend not
operational with that evidence, and the process owner chooses the
no-restart exit 78 head_fenced through processExit.choose. I/O is refused
from the fence itself.
The first-grant log line is written only for a reply that grants: a first
reply that revokes fences the guard and logs no grant.
The frontend-gate tests own their workers: cleanup is registered before
each worker starts and every receive is bounded.
docs/design/invariants.md: INV-WS-SERVE-LEASE-HELD-001 (V1-SPEC r2.37);
INV-FE-PRIMARY-READY-OPERATIONAL-001 statement within 300 characters, with
the runtime fence enforcement and tests; M1 diagram and table carry the
lease-held order and the runtime fence exit; C.W names the runVolume
receive of the stop waiter's result. 306 rows, 220 ACTIVE.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A workspace primary whose lease guard is missing or holds no granted lease
now reports NotReadyReason=lease_not_held first (the guard decides, through
the new WorkspaceLeaseGuard.Held, the lease term permits already used). The
guard logs its first grant once, as "re-granted after N refused renewal(s)"
when renewals were refused first (a restart before the forced-move barrier),
with the request-start time in unix_ms.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A restarted old holder (G-O2 r8) started its NVMe target unconditionally
at startup and reported FrontendPrimaryReady=true from the authority view
alone, before and after its chunk-layer claim was refused ("fenced, not
serving"). The admit gate refused every command with Namespace Not Ready,
but that status is retried on the same path and then fails to the guest,
and the path advertised ANA optimized, so a listening, ready-looking but
fenced target is not safe.
- status: FrontendPrimaryReady is false while the volume's local durable
backend admits no I/O (attach pending, fenced, detached), with the
backend's evidence in the new NotReadyReason; Healthy stays the authority
view.
- blockvolume: the iSCSI, NVMe and ublk targets start only once the backend
first admits I/O (awaitBackendAdmitsIO, 10 ms); signals and the workspace
lease guard now start before that wait, and a stop requested during it
skips the frontends and goes straight to shutdown.
INV-FE-PRIMARY-READY-OPERATIONAL-001 (304 rows, 218 ACTIVE); M1 Recovering
-> Serving names the guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Test review of #42979d5d9f7:
- wrongOwnerEndpoints fails a recipient whose log cannot be read or shows no forced-epoch
delivery, so each recipient must positively receive the owner's line.
- The unknown-owner unit check requires the volume unsupported or exactly the
no-observation placeholder (no server, the line's endpoints), so neither s1's nor s2's
report may supply it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Design review of #429 (V1-SPEC r2.40, INV-AUTH-HOLDER-IDENTITY-001, TERM-HOLDER-001):
- PublishedLine.Owner is the single owner decision (move-named server; move-named but
unknown; not from a move), called by Host.workspaceLineOwner and expectOwnerForLine.
- A move-minted line whose owner is unknown binds its replica to no server: no health,
endpoints or refresh from anyone (control: the placement server's fresh report changes
nothing). Only a line no move minted keeps the accepted topology.
- var _ lineOwnerReader = (*Publisher)(nil): dropping the method is a build error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An added line that begins with '++ ' is an added line, not a diff header;
the share path is matched with either slash; a missing title or
description file, an unknown commit or a failing grep is an error (exit 2),
never 'clean'. Controls for each in the self-test; each fails on the
previous script.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A check on the lines a pull request adds, its commit messages, its title
and its description: internal seat names and internal file-share paths
are refused, each hit printed with file and line. Runs beside the spec
trace check from the base branch; no pull request code is run.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
#425 (V1-SPEC r2.40, INV-AUTH-HOLDER-IDENTITY-001): the topology controller took the line
replica's facts from the server the accepted topology names (the old host after a forced
move); the returning old host's report raised an endpoint refresh that republished the
line (EV+1, owner s2) with s1's endpoints. BuildSnapshot now binds the expected slot of the
line's replica to the move-named owner (PublishedLine.IssuedHost), so that replica's
health, endpoints and refreshes come only from the owner.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings the two-process procedure gate (origin/test/procedure-gate, its three test
files) onto main and adds the assertion to TestProcedureForcedMoveWithTheOldHostReturning:
every assignment line delivered at the forced epoch, to s2 and to the returning s1, carries
s2's own data and control endpoints (V1-SPEC r2.40, INV-AUTH-HOLDER-IDENTITY-001).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 review of #416 2cba5881: two primary-owned units of one IQN (q/LUN1 at A, q/LUN2
at B) are two targets, never one multipath target with LUN1 for both. Control added.
INV-WS-RENEW-NONBLOCKING-001 lists TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 review of #416 3439d278 (INV-AUTH-HOLDER-IDENTITY-001, INV-WS-RENEW-NONBLOCKING-001):
- P1: primaryOwnedFrontends keys an iSCSI target by IQN AND LUN, so a supporting q/LUN2 never
becomes a multipath path of the primary's q/LUN1 (mismatch and nonzero-match controls).
- P2: TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite renews through holderMatches over
gRPC while a registration write is held (NodeInventoryStore.HoldWritesForTest), and shows
the hold is real.
- Standards: the workspace lease diagram's holder edges name the registered-host guard; the
snapshot test's control reader has a bounded, owned join.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 review of #416 e56f1de1 (INV-AUTH-HOLDER-IDENTITY-001, INV-WS-RENEW-NONBLOCKING-001):
- P1-1: the holder host check reads NodeInventoryStore.GetNodeSnapshot (published after each
committed write), never the store mutex RegisterNode holds across file I/O.
Held-registration-write control in core/lifecycle.
- P1-2: a primary slot with no frontend lists nothing; status frontends carry their replica
(FrontendTarget.replica_id = 8); CSI publishes a target only when the primary has a usable
frontend, another replica's frontend joining only as an extra path to the same target.
Real CSI lookup negatives (no primary frontend; rejected loopback primary).
- P2: a deletion-reserved workspace volume keeps the assignment stream host check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 review of #416 (INV-AUTH-HOLDER-IDENTITY-001):
- P1: when the line's server has no evidence for the primary, QueryVolumeStatus lists no
frontend, so CSI never publishes a supporting replica's frontend under the primary.
Real CSI ControlStatusLookup negative (old host only: not found) and positive cases.
- P2: the primary replica row (server id, node, frontend) is the issued holder as a whole.
- Row: guard trace (Enforced in), tests, host scope and limits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The holder host check (INV-AUTH-HOLDER-IDENTITY-001) reads the gRPC network peer and
requires a registered server id; tests that call the service in-process now arrive as
from 127.0.0.1, and tests that renew as node-a register it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-AUTH-HOLDER-IDENTITY-001 (claude06 review of #416; claude01 decisions):
- holderMatches (lease renew and revocation ACK) refuses an unregistered server id and a
call whose gRPC network peer is not on the host registered for its server id.
- SubscribeAssignments refuses the same for a workspace volume, so the line is never
delivered to a second host with a copied --server-id; SubscribeRequest carries the
subscriber's server_id (field 4), sent by the volume.
- Refusals are logged. The heartbeat check stays (observations).
- Limits: trusts the network peer address (no NAT or proxy between volume and master in
OSS); not authentication.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-ASSIGNMENT-HOLDER-IDENTITY-001.
- ReportHeartbeat refuses (FailedPrecondition) a heartbeat whose slot addresses are
on a host other than the one registered for its server id. Only the host part is
compared; several server ids on one host stay allowed; an unregistered id has
nothing to contradict.
- QueryVolumeStatus lists the primary's frontends from the server on the authority
line (workspaceSourceHost), never a fresher same-replica claim from another server.
- ClusterStatus primary node is the line's server (issued holder), not placement, and
the primary replica's evidence and publish target come only from that server.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
INV-ASSIGNMENT-HOLDER-IDENTITY-001: the same --server-id reported from a host other
than its registered one must be refused, and the CSI portal and displayed primary must
come from the server on the authority line, not the freshest heartbeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
What v1.0 supports and the layout rule (blockmaster off every volume
host, and why), install, sizing, the recovery point and what publishes
it, snapshots and the two-step space return, moving and returning a
volume, the steps after a host loss, the stated limits, and every command
on these pages with the test that runs it. The README links it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two procedure tests for a holder that returns after its lease ended but
before the re-grant barrier. Started 35 s after the stop (default flags),
the barrier passes within its 30 s authority wait: it must not serve while
its renewals are still refused for the barrier, then serves at the same
epoch. With --workspace-max-clock-skew 50s and a start 31 s after the
stop, its wait ends first: it does not serve and exits 75, and a
supervised restart that waits past the barrier serves at the same epoch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Five tagged binary tests run the procedures of the volume lifecycle page
as written, on two blockvolume processes with server ids s1 and s2 that
share one blockmaster and one SeaweedFS: the planned hand-over to another
host, a same-host restart inside the lease, a return after a lapsed lease
started 65 s after the stop, a forced move with the old host returning,
and a revoke without an ACK followed by a forced move.
The harness takes N hosts (cluster spec nodes s1..sN); the checks that
read each step's output take the host and stay in the default-build
check file with the existing ones.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
core/storage alone took 602 s under -short on the shared runner on main,
past the 10 minute per-package limit, so a PR that touches it fails on
the limit, not on a test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A step after the default pass runs the documented standalone planned
hand-over and its refused clean move without the ACK (cmd/blockvolume
TestStandalone*, build tags subprocess and chunkstore_integration) with
weed 4.53 linux_amd64 from the SeaweedFS release, checked against its
sha256 before every use, also from the runner's tool cache. A mismatch
fails the step. It follows the job's rules: pushes, train PRs and
non-Draft PRs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The planned hand-over waits 30 s for the old blockvolume's own exit, the
lease bound the lifecycle chapter states.
TestStandaloneCleanMoveWithoutTheACKIsRefused makes the chapter's
negative check deterministic: the volume is sealed, its blockvolume is
killed (a signal sends no ACK), the lease is revoked with the sealed
generation, and the clean move exits 1 with the documented refusal while
workspace show keeps no ACK. Its output is captured into the fixtures and
read by the shared checks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Runs the lifecycle chapter's commands in order against real blockmaster,
blockvolume, sw-block and SeaweedFS on loopback: cluster spec and
lifecycle store, adopt, write and flush a block over NVMe/TCP, plain
detach, revoke with the sealed generation, the old process acknowledges
and exits 0 by itself, show the ACK, clean move to the same host (and its
replay), reopen at the new epoch, and the block reads back unchanged.
The checks that read each step's output are shared with a default-build
test that runs them on output captured from the real binaries
(testdata/planned-handoff), each also refusing another step's output.
The NVMe/TCP host runs in the test process: no root, no nvme_tcp.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A preparer (the flusher's checkpoint, the chunk layer's captured-map
publication, BASE complete) captures prior under descMu and prepares later.
If, in between, another root is published and a second publication writes
it into the other slot, prior is released: its extents are free in the live
snapshot, yet the prepare reused prior's page references for unchanged
pages and could allocate its own page or root into the same extent. The
candidate then names a page whose bytes no longer match its hash, and the
next open of the volume fails (open validates only the newest slot's map).
prepareLockedV3 now checks prior's liveness in the same liveMu section that
snapshots the live set (liveSnapshotWithPriorV3) and refuses a released
prior with mapCoverageRefusal("prior_released") before the latching defer;
the caller's next cycle prepares from the current root. The refusal is
counted in ChunkMapStats.PriorReleased. From the snapshot on, nothing else
allocates while m.mu is held and the candidate pins every page it
references, the reused ones included, until it is published or superseded.
INV-WAL-V3-MAP-PRIOR-LIVE-001 (Part B: 304 rows, 218 ACTIVE).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One page for the operator: the three records to look at (lease, HEAD,
revoke ACK), the planned hand-over step by step with the shipped
commands, the same-host case, what to do after a crash or a lapsed
lease, the forced move, and a symptom table with the exact messages.
Corrects stale sentences in the README, the standalone guide, the
workspace protocol note and the blockmaster config comment.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The lock-order row claimed the store lock is always released before slot
I/O; recovery, BASE transitions, the checkpoint publication and rollovers
hold it on purpose to exclude writers. The record-refusal row claimed CRC
and footer are refused before a payload is allocated; the scanner must
read a record to check them, after its size is bounded. Both rows stay
STUB.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Each promoted row runs in production by default and every clause of its
statement is asserted by a named test in the default suite. 27 rows stay
STUB; a note groups them by reason (a clause has no asserting test, the
tests only exercise the path, or the asserting test needs a build tag).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Production creates and opens format-v3 stores, so most 'dark', 'not yet
wired' and 'until activation' phrases in the contract were false. Each
phrase was checked against its production caller and now says what is
true: reachable by default, reachable only with a named flag, or no
production caller. Row status is unchanged. Also cites two merged tests
on INV-CUT-STAGED-REUSE-001.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The walkthrough's lookup and the CSI node plugin resolve the namespace
under /sys/class/nvme-subsystem, which holds it only with nvme_core
multipath=Y. Say so, with the check.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The chunk control API answers a cut, snapshot or detach that host
admission refused because every slot is held (or urgent work is
pending) with 503 host_slot_busy, retryable, so a caller resends on
exactly that refusal without reading messages; other capture refusals,
a plain host busy included, keep capture_refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A blockvolume that blockmaster does not know serves nothing and says
little. The standalone document now states the topology file and the
matching flags as required steps, how to check before and after, and
which log line means which missing step.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
INV-WAL-DATA-SYNC-001 becomes five rows of one property each (automatic
sync choice, explicit override, status, allocation at create, prezero).
Three clauses with no test of their own are listed as enforced by
reading. Every statement in the ledger is now at most 300 characters.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A walstore-chunk volume's data is held in needles that no file's chunk
list names, so volume.fsck with its delete flags would remove it. The
operator document now says which commands must never run on such a
cluster, which only report, and which are safe.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A TEST change may not touch the ledger; the row's Tests cell is updated
in a separate docs change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Opening a volume on an empty remote now publishes HEAD generation 1 (the
open claim), without a cut. The slot-wait tests read HEAD after open and
check it does not move while the slot is held, and that no admission
succeeded then; publication and the seal are checked against that
baseline.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A re-send of an already completed key is now counted before the fake
remote sees it (the real put path reconciles such a re-send), and the
test asserts no completed key is re-sent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A cut whose host budget is revoked after two of five chunk PUTs (the
limiter's MaxHold abort) leaves HEAD unchanged; the next cut uploads only
the three chunks not yet uploaded, retransmits nothing, and publishes
the full image.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The provider tests wrap the real limiter and record every Admit call
with its time and outcome. Retry gaps are measured between recorded
held-slot refusals, and the first admission after the slot frees is
timed from the release (<= 400 ms); publication is bounded separately.
- The close-race control bounds its wait for Close and joins it from a
cleanup registered before the goroutine starts.
- Wording: a shorter delay range makes a late volume likely, not certain,
to retry first; the seeded one-slot simulation is a regression check,
not a proof of the bound.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A pool file, urgent-pending, signals urgent work on the host. An
urgent cut holds it shared for its lease, and HoldUrgentPending lets a
caller hold it across a stop or a drain. A Normal admission probes it
exclusively without waiting and, while it is held, is refused with
ErrUrgentPending (an ErrSlotsHeld, so the timer waits instead of
failing). Urgent admissions are unaffected.
- blockvolume checks --host-limit-dir before using it and refuses to
start when it is missing or not a directory, under a temporary
directory (/tmp, /var/tmp, /dev/shm, the process temp dir), on a
network file system (NFS, CIFS, SMB2, FUSE on Linux), or already in
use with different host-limit flags.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace the build-tagged constant with durable.MinCaptureInterval
(default 5 minutes). The flag check and the flag help read it; a
program that builds blockvolume with a shorter floor sets it before
parsing flags. The OSS binary behaves as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A timer cut refused for held host slots retries after a delay drawn
below 200 ms x interval/(interval+late), so the volume furthest behind
its interval retries soonest; a fixed per-volume phase let the same
volumes win every round. A deterministic test runs V timer policies
against one slot (service T, all due at once) and checks no volume
waits longer than (V-1)(T + poll + 200 ms) and every volume keeps
cutting.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The 5-minute --chunk-capture-interval floor moves to capture_floor.go,
built unless the swb_enterprise tag is set; a build with the tag supplies
its own minChunkCaptureInterval. The OSS build behaves as before: below
5m is refused (60 s now tested), and the refusal and the flag help name
the floor from the constant.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Status ends a recorded host slot wait once the layer's CutSeq moves
past the one it was recorded under, so a detach's seal (made after the
timer stopped) or an explicit cut clears it; the count is kept.
- A successful cut observed during a slot wait also drops the pending
slot retry.
- Admission that finds the limiter closed after acquiring its pool slot
returns ErrRevoked, not ErrSlotsHeld.
- The provider test witnesses every refused attempt with a timestamp
(at least 8 in 2.5 s, none more than 400 ms apart), then bounds the
admission after the slot frees (400 ms) and publication (5 s)
separately.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
StorageBackend records stopFlipAt under mu right after operational goes
false (setOperationalLocked and both TryStopIO flips); the detach logs it
as 'admission closed at' beside 'StopIO returned at'. Admission is
unchanged: an I/O whose gate ran before the flip is admitted and drained
by StopIO; every gate after it refuses (INV-STOP-FLIP-CUTOFF-001). The
stamp is taken after the store (errs toward a false alarm) and logged
only on a successful stop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Host admission is a try-lock. With one cut slot per host, every volume
whose timer fires while another volume's cut holds the slot was refused
and backed off 1 s doubling to 30 s, adding up to 30 s to its interval
and favouring whichever volume happened to win.
hostlimit returns ErrSlotsHeld (an ErrBusy) when every slot is held. The
cut policy treats that refusal as a wait: no backoff, no minimum
spacing, the timer is not reset, and the retry comes after the volume's
stable slot jitter (at most 200 ms). Other errors, an oversized payload
or an unusable pool included, keep the backoff. Status reports
CutSchedule.HostSlotWaits and HostSlotWaitSinceNs, the start of the
current wait (0 when not waiting). Ledger row INV-CUT-TIMER-SLOT-WAIT-001.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A periodic cut refused because every host cut slot is held must be a
wait, not a failure: no backoff, retry after the volume's jitter, and
the wait reported in status. The types the tests name are added; the
behaviour is not.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Seventeen over-long rows of the local WAL store (format v3) become 92 rows
that state one property each, every statement at most 300 characters.
Clauses that only repeated a Part A transition guard point to that
transition; the write-admission wait gets its line in the table of bounded
waits. The long-statement list shrinks from 18 to 1.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
HeadReopenBelt, PlainSealReplay and SealedReopen arrived on main with
their results in the README; each gets its Exhausted bounds row from those
figures. Nothing re-run.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Eleven over-long rows (authority store, workspace lease, forced move and
lost range, operator confirmation, frozen-request validation, host cut
budget, replica per-LBA rule, RF=3 promotion) become rows that state one
property each, every statement at most 300 characters. Clauses that only
repeated a Part A transition guard now point to that transition. 185 rows
become 216; the long-statement list shrinks from 28 to 18.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A guest error after the flip is a refusal by contract; only an error on
I/O admitted before the flip is a data-path failure. The detach now logs
'I/O stop began at' (taken just before the flip: plain stop, live
StopIO, or the pre-copy TryStopIO) beside 'StopIO returned at', both
RFC 3339 nanoseconds, so a measurement can count from the flip (#375).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Red on main: only 'StopIO returned at' is logged, so a test measuring
guest errors cannot tell a refusal after the operational flip (by
contract) from an admitted I/O that failed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/spec/README.md gains an Exhausted bounds table: one row per spec with
a configuration TLC explored completely, its bounds, its distinct state
count and what the model leaves out. internal/invcheck checks every row
(the spec and configuration exist, no cell is empty) and that every spec
has a row or is in a list that only shrinks (21 today). Eight rows are
added from results the README already states; nothing was re-run.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
assembleVolumeTopology now ignores a fresh fact for a replica reported by
any server other than the one the expected slot names, so another host
cannot put its addresses or health into the assignment line of a replica
it does not host (its doc comment already said so). With no fact from
the expected server the slot stays a placeholder, as for a missing fact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Red on main: assembleVolumeTopology keys fresh facts by replica id from
whichever server reported them first, so another server's fact for r1
supplies r1's addresses and health.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The 'not reachable in this release' marker added to its statement is
already stated in the note under the table; the length check added
in the same train rejects the longer statement.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The list's size is pinned by a constant and, where the base commit is at
hand, every listed row must have been listed there. The head-belt fence
row again says the re-read owner is compared with the publisher's own.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Ten over-long rows of the chunk cut, workspace and GC machines become
rows of one property each (statements at most 300 characters); clauses
that only repeated a Part A transition guard become pointers to it. The
invariant check gains a length test with a list of the rows still over
300 characters, which may only shrink. Two test comments lose a
reviewer reference.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Main's wording wins where it changed a row; the not-reachable marks, the
two new rows and the note are kept; the count is recomputed from the
tables and the document check passes.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A detach request with frozen set is answered 409 frozen_detach_unsupported
before any provider call, and blockvolume refuses to start with
--chunk-detach-precopy. Nothing is deleted: both mechanisms become
unreachable in this release. The request fields stay so the strict
decoder keeps answering the typed refusal.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Red on this commit: a detach request with frozen set still reaches the
provider, and blockvolume still starts with --chunk-detach-precopy.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Each member stated the count for its own rows on main; together the
tables hold 163 rows (141 ACTIVE, 19 STUB, 3 ARCHIVED).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With --status-addr the create result goes to stderr, so stdout carries only
the driver status (one JSON document). A driver start refused after the create
(for example the target is not attached at that blockvolume yet) adds a line
saying the target was created and the --volume command that starts the
restore once it is attached.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sw-block ops chunk restore --source --snapshot --target creates the target
from the snapshot with Catalog.Restore (idempotent by --request-id) and, with
--status-addr naming the blockvolume that serves the target, starts the
restore driver there in the same command and prints both results. Without
--status-addr it creates the target and prints the command that starts the
driver once the target is attached. --volume keeps driving an existing
restore. README lists both forms.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The previous commit carried the tree of main plus this change but named
only one parent, so the branch looked diverged. Same tree, both parents.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The Train 9 merge committed conflict markers in docs/design/invariants.md. Both
sides added a B.2 row after the same anchor: keep main's
INV-MASTER-JOURNAL-ISOLATION-001 and this PR's INV-SEC-CONTROL-BIND-001, and
recount the Part B summary from the tables (161 rows: 139 ACTIVE, 19 STUB,
3 ARCHIVED, 146 new).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Three stale test names it found are fixed (one rename, one test removed
with the retired engine and replaced by its neighbour, one name that
exists nowhere). The count check accepts the document's wording.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Only conflict: the Part B summary line; recounted from the tables (161 rows:
139 ACTIVE, 19 STUB, 3 ARCHIVED, 146 new). Train 9 brought no new raw gRPC
site: the guard passes on the merged tree.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main pushes and train PRs run the light set only; the legacy-fixture
job is removed. Each train runs both full configurations on a
separate test VM before it merges.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The gRPC control API (--listen) and the runtime HTTP API
(--frontend-publication-runtime-listen, when enabled) are unauthenticated, so
binding them to the node network is now an explicit choice: a non-loopback
address is refused at startup unless --insecure-external-bind is given. The
Helm chart and the shipped k8s manifests, which bind 0.0.0.0 with host
networking, pass the opt-in explicitly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Any use of grpc.NewClient / Dial / DialContext / NewServer or
insecure.NewCredentials counts (f := grpc.NewClient builds a raw link just the
same), qualified under any import name or unqualified under a dot import;
fixtures for a function value, an aliased value and a dot-imported value.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- link.DialWith(target, opts...) builds a link with exactly the caller's
options (no default credentials); the failback runtime uses it for injected
options, so its prior semantics hold and no production file calls
grpc.NewClient directly.
- The guard parses every non-test file and finds grpc.NewClient / Dial /
DialContext / NewServer and insecure.NewCredentials under any import name
(alias or dot import); a detector test proves each form is found and a
link-only file is clean; routing failback back to grpc.NewClient fails the
guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
core/rpc/link builds every gRPC link: Dial is grpc.NewClient with plaintext
credentials exactly as before (caller options follow), NewServer runs the
caller's unary and stream interceptors in order (none by default). Every
production site now goes through it: nine dials to blockmaster, the two
SeaweedFS dials and both servers; the failback runtime keeps its injected
dial options unchanged. No behaviour change.
INV-SEC-ONE-SEAM-001: a guard test fails if a non-test file outside the
package creates insecure credentials or a raw gRPC server (red on the base: it
lists the 12 files with the 13 raw sites).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fork row no longer names a claim: every attempt of a fork reads its
parent again. Rows main changed keep main's text; count recomputed from
the tables.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
When TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore fails it now
prints the longest gap between successful renewals, the gap when the
fence was seen, and the cause the guard records, so a starved runner
can be told from a guard that fenced with renewals in time. No bound
changed, nothing skipped.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Review fold: the light set dropped the four heavy packages even when the PR
changes them, so a PR's own Red-first tests there first ran in a train. The
step now adds back each heavy package with a file of the PR's diff in it
(checkout depth 2: the merge commit and its base parent).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
core/storage, core/frontend/durable, core/host/master and core/authority
take minutes each and hold the timing-sensitive tests; under the CI host's
lowered I/O and CPU weight they reached the 10 minute package timeout on
PRs that do not touch them. A PR now runs every other package; pushes to
main and train PRs run the full list. Branch names reach the script only
through the environment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The chunk commands' single-filer start check now comes from main; this
branch's own copy and its tests are removed. verify runs the check
inside its --timeout: against a split filer view it would report false
findings.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Train 8 carries the fork-claim removal; the three docs conflicts resolve to
the no-claim union: the claim-free Fork, Retention and diagram text with this
part's Hydrating/Owning rows and steps; INV-RESTORE-PARENT-HOLD-001 archived;
both B.6 notes; the S10 row is the no-claim model, S11 ForkDelete kept.
Ledger recounted from the tables: 138 rows, 118 ACTIVE, 17 STUB, 3 ARCHIVED,
123 new.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The free space of the side file's filesystem (--durable-root, statfs on
Linux) is read at each cut, for the staging bound and when the copy
window opens; a read error counts as no free space. At the cap the cut
aborts (cow_capacity) and the guest write completes. Adds Part E.
Quantities to the ledger with this row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A per-volume worker takes a named snapshot of class scheduled once per
period, through the same seal path as an explicit snapshot (resolve the
request, one urgent cut, record that cut's HEAD). A restoring volume
(chunks its HEAD names still absent) is skipped and counted; a failure
keeps the control endpoint's code and is retried with a backoff doubling
from 1m to 1h; status carries the schedule state and snapshot_overdue.
Retention keeps the newest N scheduled snapshots (N from the newest one's
swb.schedule.keep label) separately from other snapshots.
--chunk-snapshot-schedule=daily:N|weekly:N|off, default daily:7.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The suite writes real files with fsync to the self-hosted runners' disk:
about 650 GiB an hour on tp04 today, most of it from repeated runs on Draft
PRs and from the second full pass with the legacy-fixture tag on every PR.
A Draft PR now runs no Go suite (marking it ready starts one), and the
legacy-fixture pass runs on pushes to main and on train PRs, which carry
every change that merges.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The three deadlock failures of
TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose now print the
stack of every goroutine. One CI failure of this test gave no way to see
where the parties were blocked. No timeout changed, nothing skipped.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
docs/status-schema.md is generated from the Go field comments (#341);
#338 rewrote the StageRounds comment group, so the composed train needs
the page regenerated (STATUS_SCHEMA_UPDATE=1). Docs only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A pause's drain waits for every admitted I/O (two in flight), a pause
does not begin on an unusable backend, a drain that loses readiness
ends with an error, the sample history is bounded at 32, the round loop
retries only the named errors, the attach wait fails fast on a terminal
state, a plain-detach stop refuses a closed backend. Tests only.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The test records the owned goroutine's settlement and Close's return with
sequence numbers and requires settlement first; before releasing it gives a
Close that does not join 200 ms to return while the goroutine is held. One
Close launcher (sync.OnceFunc) serves the body and the pre-registered cleanup,
which always cancels, releases and joins, also when GoOwned or the start wait
fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The pacing test measures each admission from a time taken before the call,
a lower bound of the walker's own start, keeping the exact 8 fills, Gets
and admissions.
- The GoOwned test bounds every wait, pre-registers release and a bounded
join of Close, and witnesses that Close does not return while the owned
goroutine is held after its ctx ended (no sleep).
- The owner-close driver test releases the held provider call before the
owner's join at teardown, so its red case cannot leave a worker behind.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- OwnBatch, its cut candidates and its progress use one predicate: a chunk is
local when present or when every block was written locally (a guest
overwrite flushed before the walker reached it), so such a chunk is owned
with no fetch instead of stalling the driver.
- OwnBatch drops a remembered payload of a picked chunk that matched HEAD and
was never uploaded (no key), so the cut reads and uploads it under an own key.
- The driver runs inside the serving provider's lifetime (DurableProvider
GoOwned: ctx ends at Close, Close joins it); a closed provider admits none.
- Tests (each red without its fix): fully overwritten absent chunk owned with
no Get; equal keyless payload from a failed cut still re-owned; a second
start joins the running run (one walk); owner close cancels and joins a run
held in a provider call and no marker follows; Close joins GoOwned; the
pacing test requires all 8 fills and Gets and witnesses admission times.
- Restore diagram and bullet without claims (same text as the snapshot-delete
change).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The restore diagram's first state reads the parent (no claim, publish before
read time + deadline); the S10 model row is marked as the claim-era model.
The two post-GC checks go through chunksMismatch, which requires exactly the
expected indexes and every payload; a negative test shows a missing index is
caught.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The model this part rests on, as checked (no-claim variant; only comment lines
changed: seat and note names removed), with its 26 configurations: the
no-claim safe cfgs exhausted with no error (360 k to 2.75 M states), the
boundary G >= D on one clock (ForkDelete's G >= D + E + P with E = P = 0),
13 reds and 2 witnesses on their properties, and the claim-frame regression
cfgs. The claim-era configurations not re-run against this spec are removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fork/restore versus snapshot delete model this change rests on, byte for
byte as checked (sha256 c9c7c7fa), with its 28 configurations: 11 safe
(exhausted, no error, 18,672 to 15.7 M states, including every boundary
G = D + E + P), 12 reds and 5 witnesses each on its expected property.
README rows; the invariant rows drop the simulation tag.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On pull_request_target, base.sha is the base recorded when the PR was last
synchronised, so a PR opened before the spec-trace scripts landed checked
out a tree without them and failed with 'No such file or directory'.
github.sha is the base branch tip at the event; the diff still uses the
merge base of the PR's base and head.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Nothing is stored about a reference except that a root carried it. An
object (a chunk or a manifest segment, by owner and key) has one outcome
from its one check; whether a reference to it is sound is a pure function
of that outcome and the reference, so the findings no longer depend on
which reference was seen first. An object that had a problem under any
reference seen and yields no finding is counted once.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Review fold. The check ran the tool with go run, which takes the .go
arguments as more source files, so in CI every DOCS PR touching Go would
have been refused; the self-test hid it by building the tool itself. The
check now builds the tool into a temporary directory, the self-test runs
that same path, and a build or tool failure exits 2 (the check did not
run) instead of reporting changed tokens. In a file that uses cgo every
comment counts (the grouped import ("C") form dropped the preamble).
The template says DOCS may still change contract text, with the reviewer
as the gate; the script header names the go:embed limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold. The line-multiset comparison let reordered statements,
directive comments (//go:build, //go:linkname, the cgo preamble), a //
inside a string after a rune quote, a line inside a multi-line raw
string and spacing inside a string all pass as comment-only. A small Go
program (sametokens.go, go/scanner) now requires the old and new token
sequences of each changed non-test Go file to be identical, comments
dropped except directives and the cgo preamble; gofmt realignment passes
by construction. The workflow passes old/new blobs instead of a diff.
DOCS no longer covers docs/spec (the models); CI no longer covers
scripts/, which holds shipped install and deploy scripts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A PR that changes no behaviour names one of three kinds instead of
IMPL, FIX or CHANGE. TEST may touch only tests, testdata and test
helpers; CI only .github/ and scripts/; DOCS docs, tests and Go whose
hunks change only comments. For DOCS the workflow passes the diff of the
non-test Go files, and the check compares removed and added lines with
line comments (outside strings) and spacing dropped; every changed Go
file must appear in that diff. Ten self-test cases added.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A closing read of HEAD that finds no HEAD, or one that does not decode,
leaves the final view without a HEAD root and the result incomplete
(head_absent, head_invalid); it no longer keeps the earlier view. A
manifest segment is checked once per owner and key with one outcome, like
a chunk; a root whose reference does not match the content gets one
mismatch, and segment findings follow the one-per-key-and-class rule
under the first root that names the key.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The re-own candidates join through captureCandidates (addOwnCandidatesLocked)
and the HEAD-equal skip is a predicate (unchangedFromHead) in chunk_own.go:
captureLocked gains no branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The driver walks (64 MiB/s, BackgroundFill), cuts bounded batches (64 chunks)
until no foreign ref is left, then writes RESTORE-INDEPENDENT
(M6.Restore Restoring>Hydrating>Owning>Owning>Independent). It decides only
from the target's VOLUME, HEAD and marker, so a rerun resumes from the remote
state and a deleted source is a normal state. POST /chunk/restore starts or
joins one background run per volume and returns its status; GET (or
statusOnly) reports it; sw-block ops chunk restore calls it. Docs: M6 restore
rows, INV-RESTORE-OWN-BATCH-001 and INV-RESTORE-DRIVER-001, the restore
quantities, the workspace design diagram.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OwnBatch(n, foreign) runs one ordinary cut whose candidates include up to n
local chunks whose HEAD keys name another volume; streamCutPayloads uploads
each under a new own key even when its bytes equal HEAD's, and the cut's one
intent and HEAD CAS publish them (M6.Restore.Owning>Owning). An absent chunk is
never fetched by a batch; with nothing to own no cut runs. HydrateAllAt paces
the walker to a byte rate before admission (HydrateAll = unpaced).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pass kept three kinds of state: a chunk (unseen, queued, settled with
one outcome, never re-checked), the HEAD view (replaced by each refresh)
and each selected snapshot's view. Settling a chunk records its outcome
and reports nothing. The pass closes on a read of HEAD and of the
snapshots' state that names no unseen key; that same read is the final
view. Findings are computed once, from the outcomes and the final view:
at most one per chunk key and class, under the first root that names the
key; a bad chunk that no root names is counted, not reported. A key the
pass saw named, then not named, then named again is reported. If the
closing rounds run out the result is incomplete, never clean.
This replaces the reporting done as reads settled and as refreshes
arrived, together with the late-reference list and the per-finding
rechecks.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A fork or restore no longer claims its parent snapshot, and neither
DeleteSnapshot nor retention reads a claim: a deadline-exceeded fork or a
failed restore can no longer make its parent (and so its volume) undeletable.
Safety now rests on time: a fork takes its deadline start before it reads the
parent, every attempt (a retry included) reads it again, and it publishes its
HEAD only before start + operation deadline; GC keeps a deleted attempt rooted
for its grace, and NewCollector now requires
grace >= operation deadline + clock skew + CAS apply bound (new GCConfig
field, default: the operation deadline). An unknown publish keeps the fork
intent, which roots the keys until the target is resolved.
Removed: claimForkParent/dropForkClaim/removeForkClaim (replaced by
readForkParent), the claim branch of markDeleting, liveClaims, claimedErr and
snapshot_claimed, retention's ForkHeld outcome and the fork_parent keep
(forkParentsNeeded). A claims xattr written by an older version is ignored.
Tests: three new tests (fork retry after delete re-reads the parent; delete
during a fork in flight; unknown publish keeps the keys while its intent
exists), each red on the base with snapshot_claimed; the construction check
with its boundary; claim-mechanics tests removed, the others rewritten to the
new rule. Docs: invariants.md M6 rows, INV-SNAP-DELETE-ANY-ORDER-001 (new),
INV-SNAP-EXPLICIT-DELETE-001 and INV-GC-GRACE-DEADLINE-001 restated,
INV-RESTORE-PARENT-HOLD-001 archived; workspace design section 6.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GitHub-hosted jobs in this org can queue for a long time; the test
workflow already sends same-repository PRs to the self-hosted runners and
forks to a hosted one. The spec-trace job does the same. It runs no PR
code on either.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts kept both sides: agent-workspace-design.md (restore diagram, then
attached-volume scheduling); invariants.md B.6 (the INV-MAINT-* rows, then the
INV-GC-REACHABLE-001 row with restore owner rooting). Part B summary recounted
from the tables: 131 rows, 112 ACTIVE, 17 STUB, 2 ARCHIVED, 116 new.
RestoreIndependence is now exhausted (breadth-first, complete graph): the spec
README row and the invariant rows drop the simulation tags.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A miss or a read error was reported against the references known when the
chunk was queued. A reference added by a HEAD refresh, before or after the
read ended, is now given the same outcome under the usual recheck, without
reading the chunk again. Tests that hold a call open get an independent
bound so a broken implementation fails instead of hanging.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- A failed refresh cancels reads in progress before joining them and is
the error returned.
- A reference to a chunk already read is compared with that content; two
references to one key that disagree are a finding.
- A snapshot is identified by the name it was looked up by; a document
naming another snapshot or volume is ROOT_INVALID and excuses no miss.
- The single-filer check of every ops chunk command runs within the
command's --timeout.
- SWFS.Get reports not found only after a fresh volume lookup whose every
location answers 404; a warm, correct cache costs no extra lookup.
- The verify rows move to Part B of the invariant document.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A second Machine/INV line (plain, list or bold form) could carry a second
kind past the check; every trace key must now be declared once. Three
self-test cases added.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold: Machine/INV must carry exactly one kind token that ends at a
space, comma, slash or the line end; trace keys count only at the start of
a line; a value still holding the template placeholder fails; deleting
non-test Go under core/ or cmd/ also needs Simplest; an unknown status or a
record cut off before its NUL is a malformed change list (exit 2). The
self-test grows to 31 cases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The PR template now carries the five trace lines (Feature, Machine/INV,
Model, Red-first, Simplest). A pull_request_target workflow checks the
description from the base branch's script: the four trace lines are
present, NONE carries a reason, Machine/INV starts with the PR kind
(IMPL <machine>.<transition>, FIX <INV-ID> or CHANGE <machine>), and
Simplest is present when non-test Go under core/ or cmd/ changes.
The self-test runs before the check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test now checks that the context the filer receives is live on entry (it
does not inherit the caller's cancellation) and ends with its own deadline
(context.DeadlineExceeded), not Canceled. Release and bounded join at cleanup
are kept. Mutants: inheriting the cancelled parent fails on entry; no deadline
fails on the deadline check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fail when a row names a test that does not exist, an ACTIVE row names no
test, an ID repeats, or the stated row count differs from the tables.
Three ACTIVE rows named removed tests; drop those names (each row keeps
its other tests).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
- Walker tests that call HydrateAll synchronously run under a ctLocalBound
timeout, so a walker that never finishes fails instead of hanging.
- The dropIntent test releases and joins its worker at cleanup (an unbounded
delete, the failing case, no longer leaks a goroutine).
- invariants.md: INV-RESTORE-PARENT-HOLD-001 is Go only (the model does not
cover retention of an aborted target); new INV-CAT-INTENT-DROP-BOUNDED-001
row and M6 transition for the bounded catalog intent delete.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Public text states what the code guarantees, not who asked for it or
where an internal note lives. Comments and docs only; no code change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comments in the restore code, tests and spec header now say what the code
guarantees, without review or design-note references. The real-limiter walker
test no longer asserts zero deferrals: a permit is released asynchronously
(when its flight settles, then closed by the limiter), so the next admission
can find every fill slot still closing; it now requires the limiter's skips to
equal the walker's deferrals (flaked 4 of 90 runs on Linux before).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add rows, each with its enforcing function and test checked against the code,
for: the bounded guest wait and the logical read path during a cut; the named
snapshot's point and durability; fork from a published snapshot; GC deleting
the exact recorded fid; the grace restart; strict journal isolation on move
and placement targets. The WAL flusher sync row is a STUB (no test yet).
Clauses enforced only by reading are listed in the notes. Also: M7 in the
contents, the row count recounted from the tables, Part A protects columns.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The only conflict is the ledger summary line in docs/design/invariants.md,
which #318 and #320 both recounted. Recounted from the merged Part B tables:
126 rows (107 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept, 111 new).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- HydrateAll admits each fill as a background fill permit with no cut payload
(the real limiter refuses a payload for BackgroundFill, so no fill ever ran),
and the permit now belongs to the flight: the walker queues the shared flight
without becoming a waiter and a layer-owned goroutine releases the permit
when the flight's I/O is over (new settled signal, closed by the worker after
fillOnce or when an unrun flight is removed), also after an early return on
cancel, revocation or close. The limiter's abort callback stops the walker.
The flight lookup is factored into hydrationFlightLocked (shared with
OnReadMissContext, no behaviour change there).
- CreateSnapshot on a restore volume also checks the supplied image: a cut
saved before the marker that still names another volume's chunks is refused.
- dropIntent keeps outliving the caller's cancellation but is bounded by
dropIntentTimeout (it had no deadline at all).
- Tests: the real hostlimit limiter (fill permits, payload 0, all released),
permit held while a cancelled walker's Get is held, revocation, a witnessed
pause for guests, cancel returning while the Get is held, bounded joins;
stale pre-independence image refused; aborted first HEAD keeps the parent
as fork_parent until the target is deleted; dropIntent bounded.
- Docs: invariants.md M4/M6 rows and INV-RESTORE-* rows, GC owner rooting
recorded as load-bearing in INV-GC-REACHABLE-001; restore diagram in the
workspace design; RestoreIndependence in docs/spec/README.md (simulation).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TLA+ model of the restore: claim, two-step fork, hydrate, bounded batch cuts
(upload own fids under an intent, one HEAD CAS per batch), marker after the last
foreign ref, claim drop; GC, source delete, snapshot retention and crashes with a
resume from remote facts at any point. Invariants NoGap, Independent,
NoForeignList, ClaimUntilHead_Inv (option 1: today's fork claim semantics),
LifecycleFree, StateRemote. cfgs: option-1 safe at three sizes, the stricter
claim-until-independent variant, two witnesses, and one red cfg per mutant
(each red at its expected invariant in simulation). Simulation only so far:
no violation in about 0.81M states per safe cfg (3 seeds x 60000 traces, depth
40); not exhausted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add Catalog.Verify and 'sw-block ops chunk verify': a read-only check of a
volume's remote image at three depths (meta, bindings, data). GC's mark does
not look up the bindings of the keys it roots and never reads chunk data, so
a missing binding or a damaged needle was found only by a guest read.
A miss is reported only if its root still names the chunk: verify re-reads
HEAD (superseded during verify) or the snapshot attempt (root deleted during
verify) before reporting, since a pass can outlive GC's grace. A needle is
NEEDLE_MISSING only when the store answers not found; any other read failure
is retried and then reported as READ_ERROR (not verified). Exit code 3 means
the pass completed with findings.
The single-filer start check now also runs in the shared dial path of the
'ops chunk' commands and in gc.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A snapshot taken while a restore still names its source's chunks would keep that
lineage for its whole retention. CreateSnapshot on an Origin restore volume is
refused (restore_incomplete) until RESTORE-INDEPENDENT exists; a refused request
leaves no name or attempt. Test covers before, after own chunks without the
marker, and after the marker (the snapshot then names no foreign ref).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HydrateAll makes every HEAD-named chunk local, lowest index first, through the
same shared fill flights as guest read misses (one fetch per chunk; queue bound
and read-miss timeout apply). It yields while any flight has guest waiters and
admits each fill through the host limiter (cfg.Budget) with the caller's ctx, so
the restore driver sets hostlimit.BackgroundFill on it. A refused admission or a
pending fill backs off and retries; ctx cancel returns the remaining count.
ChunkLayerStats.AbsentChunks reports what is still to fetch (0 = fully local).
Tests: every chunk fetched exactly once and the HEAD image reads back, a second
walk does nothing; local writes (full and partial chunk) are never overwritten;
the walker issues no fetch while a guest waits and never fetches twice; each fill
is admitted once and released, refusals are deferred, the caller's class reaches
Admit; cancel reports the remaining count; AbsentChunks before/after.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Restore is Fork recorded with Origin restore (same claim semantics: live until the
target has a HEAD). Every reader of the fork record accepts OriginRestore; a replay
onto a volume of the other origin is refused. MarkIndependent writes the write-once
RESTORE-INDEPENDENT entry only when the resolved HEAD holds no ref to another
volume (ForeignRefs: owner-qualified keys whose owner is not the volume).
Tests: restore records origin/fork record and attaches; replay and origin mismatch;
marker refused while foreign refs remain, write-once replay; source snapshot and
source volume deleted mid-restore (attach, replay and finish stay normal); GC keeps
every chunk the restored HEAD names with the snapshot and the source gone; a restore
without a live HEAD never attaches.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A forced move whose issuing authority write may have reached the store
but reported an error (memory left unissued), or any move on a volume
whose workspace persistence is already uncertain, now fails with the
typed authority.ErrWorkspaceOutcomeUncertain. MoveWorkspace answers it
as Internal (UNKNOWN outcome: restart, then rerun with the same request
id) and logs it as unknown, never as a refusal; admission refusals and
failures before the issue stay FailedPrecondition.
FileAuthorityStore gets a test-only after-rename fault hook
(SetPutAfterRenameFaultForTest) for the durable-write-then-error control.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- S1: a failure after a forced move is issued (binding reconciliation,
or a publisher error with the move already issued) is answered as
Internal naming the move ISSUED, never FailedPrecondition; the client
reports it as unknown with the same-request-id recovery; the issued
forced grant is logged before anything after the issue can fail.
- S2: the client binds the grant to the request (request, volume,
expected holder and epoch, target replica and host, higher epoch) and
the range to the grant (volume, request, epochs, old replica, HEAD
gen, frontier); lost-range answers must name the asked volume/request.
- S3: the exit-4 recovery command carries --master, shell-quoted.
- S4: HEAD time labelled "(publishing host clock as recorded in the
filer, 1 s resolution)".
- T1: master test registers cleanup as soon as the master starts.
- Ledger: INV-WS-LOST-RANGE-READOUT-001 statement and tests, M2 issue row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sw-block ops workspace force-move (forced only, --confirm-forced
<volume>@<epoch>, --dry-run preview) and lost-range, over one shared
client package core/rpc/wsclient.
- WorkspaceGrant carries the stored lost range on issued forced grants
(also on replay), or lost_range_error when the record is missing or
fails its checks.
- New RPCs QueryWorkspaceLostRange (all stored ranges in issue order, or
one; DataLoss when unproven) and PreviewWorkspaceMove (read-only
forced admission; HEAD read only once admitted).
- The HEAD reader takes the HEAD entry's filer mtime from Last-Modified;
the lost range stores it beside the v1 ranges with its own checksum
(older binaries still verify the file; unknown when absent).
- The master logs every issued forced grant.
- Ledger: INV-WS-LOST-RANGE-READOUT-001, INV-WS-FORCED-CONFIRM-001; M2
forced and issue rows.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Discard a reservation reply that lost a race with a retirement; keep a
slot's fid while an upload to it is unresolved and read it back before
giving it up; send under the token's deadline; make a rejected token and
used-up replacements final through storage; count every reservation
attempt; validate key width, offset overflow and location.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Docs-only conflicts with #311 resolved as a union: invariants.md keeps the
INV-CUT-PLAIN-DETACH-001 row and #311's INV-CUT-PRECOPY-001 row; spec README
keeps both the PrecopyFixedAdmission and PlainDetach sections.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Seven of the last 80 runs were cancelled at the 25-minute job limit while the
tests were still running under host load (the default pass alone takes 11-16
minutes on a busy tp04). Each job now carries one pass, and 40 minutes leaves
room for a loaded runner without letting a hung run sit for long.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The hosted runner queue for this org waited 2 h 18 min for the job on this
PR's own run (created 18:03Z, started 20:21Z), which blocks every merge on
it. tp04 now has two runner instances with the same label, so the
legacy-fixture job uses the default job's routing: same-repo PRs and pushes
run both passes in parallel on tp04, fork PRs stay on a hosted runner.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The two test passes ran back to back on the single tp04 runner and, under
load, together outran the 25-minute job timeout. The legacy-fixture pass
now runs as its own job on ubuntu-latest, in parallel with the default pass
on tp04, so each job carries one pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The revocation ACK test records whether its worker was launched: every
exit still releases the held call, but only a launched worker is joined,
so a setup failure before the launch no longer waits 10 s for a sender
that does not exist or reports a join failure that did not happen.
The detach-freeze witness checks the held CAS's context deadline only
when the context carries one, and in every case that the CAS ended no
earlier than the cut deadline, so it also holds if the cut bounds the CAS
by a cancelling timer instead of a deadline.
Refs #300
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflicts were only between the v2 removal and the sync policy from #286:
- wal_writer.go: stays deleted (no v3 code uses walWriter); #286's change there applied only to the v2 writer.
- walstore.go, legacy create/open constructors: stay deleted.
- walstore.go, openInitializedV3: keeps the v3 signature and the unconditional init, and takes #286's newDataFileSync for both the WAL and extent syncs.
The two plain f.Sync() calls that main has and this tree drops are in the legacy create constructor and the legacy superblock writer, both removed with v2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DetachFreeze now witnesses the held detach CAS itself: it was held, ran
under exactly the cut deadline, and was released by that deadline expiring
before the detach returned. The budget is checked from its one origin (the
settlement deadline a quarter of the bound after the cut deadline), not
against a start time sampled outside DetachVolume.
The revocation ACK test registers, before either worker launches, an
idempotent release and a join bounded on its own, so a blocked ACK that
used up the fixture context still releases and joins the held operation.
hangGuard keeps a tenth of the remaining budget (at most 30 s) before the
binary's deadline, also for short or nearly expired budgets, and an
expired budget gives an expired guard; unit-tested.
Refs #300
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ACK in TestWorkspaceBindingRemoteReadDoesNotBlockAck ran under a
fixed 1 s deadline that also covered a durable persist, so a loaded host
could fail it with nothing blocked. It now runs under the test's own
context: the held remote call is released only after the ACK returns,
so an ACK that waited for it still fails at that deadline.
Refs #300
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The restore tests ran under a fixed 4-10 s test context; under load the
whole test outran it and a HEAD read or claim failed with a deadline.
They now use a hang guard derived from the test binary's own deadline.
The detach-freeze test held the next CAS, which a running chunk loop
could take instead of the detach, and gave the settlement 75 ms. It now
holds only the detach CAS, uses a 2 s freeze bound (the settlement keeps
500 ms), and checks the abort against the deadlines the detach traced:
the cut deadline at three quarters of the bound, the abort at or after
it, the return within the bound.
Refs #300
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The behavioural test runs its renewal after the publication helper
returns, so a helper split into two lease-lock sections (refresh the
view, then set the deadline) still passes it: nothing in the gap
between the sections can be intercepted without a production hook.
Add a source-structure guard, like the existing non-forgeability scan:
the helper takes the lease lock exactly once, holds it to return,
assigns both the derived view and the deadline under it, and calls no
other publisher method that takes the lease lock, directly or
transitively.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A move issue published the new epoch's lease view and then, in a
separate lease-lock section, replaced the deadline with issue + TTL. A
renewal of the new epoch landing between the two raised the deadline,
and the issue then lowered it under the outstanding grant, so later
renewals inside that grant were refused. The view and the initial
deadline are now published in one section, and the issue never lowers a
deadline.
A forced move now accepts any HEAD at an epoch below the expected one,
read after admission, with the lost range from that HEAD's RemoteLSN.
Requiring the HEAD generation and LSN recorded at the issue refused the
volume for good when an earlier holder's in-flight claim landed after
the next move was issued and that move's holder then died unclaimed. A
HEAD at the expected or a higher epoch that is not the expected holder's
is still refused; clean moves are unchanged.
Comments now say what admission guarantees: the expired holder starts
no new claim or cut, but a claim already sent may still land. The
paused-holder test witnesses the refused attach decision instead of
watching HEAD for a fixed time, and the design document and invariants
record the issue-to-lease transition, the forced HEAD rule and the open
model check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolves the one conflict in docs/design/invariants.md: keeps main's
INV-WS-HEAD-BELT-001 and INV-WS-HEAD-CAS-001 rows, and lists the union
of both sides' tests for INV-WS-HEAD-MONOTONE-001.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A detach whose final cut provably did not publish resumes serving, but
the stop-pending mark set at the start of the detach stayed latched on
the host and on its lease guard, so a host that kept serving renewed
about four times a second for good instead of once per renewal delay.
The detach hook now returns an attempt token, and the provider calls a
second hook with that token only after it resumed serving on a proven
abort. The host clears stop-pending, on itself and on its guard, only
for the latest attempt, so an older attempt's resume cannot clear a
newer pending detach; an applied, fenced or unknown outcome keeps it.
Tests: the guard's sleep is now observable through a scheduling seam,
so the cadence test asserts the delay chosen after each renewal and the
kick path separately, with no wall-clock window; the detach hook is
witnessed before the drain starts; test workers are joined, bounded and
failing on timeout, before their providers are closed. The invariants
document gains the StopPending mode of the lease guard (scheduling
only, no admission or ACK change) and INV-WS-STOP-PENDING-001. Comments
now say that 250 ms bounds the sleep after a completed renewal, not the
time from a revocation to its ACK.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On a graceful stop the chunk layer is detached first and the master marks
the lease revoking right after, but the host's lease guard only learned of
the revocation on its next renewal, up to 10 s later (3-6 s measured), and
the guest's writes were refused all that time.
A detach now calls an optional provider hook, OnChunkDetach, which the
blockvolume host connects to its lease guard: the guard renews at once and
then every 250 ms until it fences. The pending mark is never cleared; a
detached host does not serve again under the same guard. The hook fires
only on the detach path, not on the lease-fence StopIO.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A move issue cleared the lease and the new holder's lease was created
only by its first renewal. A holder that died between its grant and its
first renewal left the volume with no lease, so no move was ever
admitted again, not even a forced one. A holder that died after renewing
but before claiming HEAD was stuck too: HEAD still named its predecessor
and the forced move refused it.
The issue write now starts the new holder's lease (horizon issue +
1.5*TTL, granted deadline issue + TTL, the same values a first grant
uses), so an unclaimed grant expires like any other lease and a forced
move is admitted after that lease's expiry plus the skew bound, never on
a predecessor's lease. The holder's first renewal is an ordinary renewal
of that lease, with no extra write.
A forced move also accepts a HEAD that still names the predecessor when
it is unchanged since the move to the expected holder was issued (same
generation and remote LSN, older epoch). Clean moves are unchanged.
Blockmaster reads HEAD for a forced move only after its lease admission
holds, so the HEAD the move and its lost range rest on can no longer be
changed by the expired holder. A holder resuming after the forced move
is refused at attach by its lease-gated projection.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The lease extension's durable store write is timed around the write
alone and recorded under the lease lock: the latest duration and the
slowest of the last minute (rolling, one bucket per second, like the
clamp counter). LeaseStats and the status endpoint carry them
(extension_write_last_ms, extension_write_max_last_minute_ms; -1 before
the first write, or with none in the last minute). Write latency is the
early lag signal; the headroom alarm and clamps follow it.
Storage identity gains statfs f_fsid (Linux). Two identities that both
know it must agree on machine id, device and fsid; when either side's
fsid is unknown (an older reporter, a platform without statfs) the
comparison falls back to machine id and device. Heartbeats carry it in
the new durable_root_fsid field (regenerated with the pinned
generators); the volume host reports it and the master samples its own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Strict journal isolation refuses new work, never an issued decision.
MoveWorkspace now asks the publisher, read-only, whether a request is an
exact replay of an issued move (same id, same validated body) before the
co-location guard; a replay gets its durable grant back, a new id or a
changed body is still refused. PlaceWorkspace keeps the idempotent result
of repeating the recorded placement.
The master samples its authority store's file system after Bootstrap has
created the directory, so a first start detects co-located nodes too.
The heartbeat serving exemption reads the committed authority lines from
the lease views (leaseMu only), with the issued move's target host derived
there, instead of taking the publisher lock held across authority writes.
The headroom alarm fires at the latest with the first clamped grant of a
streak, logged before the clamp line. The per-minute summary is flushed by
the first renewal attempt after the minute, granted or refused.
The status endpoint bounds read, write and idle time, and Close
force-closes connections a timed-out graceful shutdown leaves open.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume whose durable root sits on the authority store's file system
shares its jbd2 journal: under a WAL fsync storm the lease extensions
lag, grants clamp to the durable horizon and leases run out.
- core/storeident: (machine-id, st_dev) identity of a directory; unknown
never matches.
- Heartbeats carry the durable root's identity (machine_id,
durable_root_dev); the master compares it with its authority store,
logs and counts co-located nodes once per detection.
- --strict-journal-isolation (default off = alarm only): refuses
heartbeats of a co-located node that serves no volume (durable state
decides), and refuses PlaceWorkspace/MoveWorkspace and new product-loop
placements onto co-located nodes.
- Publisher: headroom alarm while an extension is pending and headroom
< 1.125 TTL (before the first clamp), clamp counters (total, last
minute), min headroom at grants, lazy per-minute summary;
WorkspaceLeaseStats snapshot.
- --status-listen (loopback only): GET /status/workspace-lease JSON.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
isTarget compares resolved addresses with netip (IPv6 zone included);
an address that does not parse never matches. A round whose bound ran
out while a later master was still being asked does not pass on an
earlier favourable answer. The ledger row maps to the M4 table.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A pass now needs a master listing exactly the configured filer (same
gRPC port, same or co-resolving host). Every master is asked: any
master listing another filer or several refuses at once, whichever
answers first. Each master call is bounded within the remaining time,
so a stalled master no longer consumes the whole bound. Startup census
only; invariant INV-WS-SINGLE-FILER-001 and its M6 row record it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fresh filer registers with its master some seconds after it serves
(14 s in the swap smoke), so "no filer listed" is asked again every
second until a 60 s bound and refused only then. Several filers are
still refused at once; an unreachable master is retried the same way.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Block metadata needs exactly one filer behind --chunk-filer. At startup
the chunk wiring asks that filer for its masters and filer group
(filer_pb.SeaweedFiler/GetFilerConfiguration), then the masters for the
filers of that group (master_pb.Seaweed/ListClusterNodes). It refuses
unless a master lists exactly one, and when it cannot get that answer
within 15 s. The filer subset gains GetFilerConfiguration and a master
subset carries ListClusterNodes, generated with the committed plugin
versions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On platforms without SIGUSR1 a set --cpu-profile-dir is refused in flag
parsing; the default (off) stays common to all platforms.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parseFlags refuses an unusable --cpu-profile-dir (and a platform without
SIGUSR1) before run() activates anything; the handler is installed at
the top of run(). stop removes the handler, stops and joins the signal
worker, then writes out a running profile, so a buffered SIGUSR1 cannot
start a profile after it. Tests decompress the whole profile and check
that no profile runs after stop.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
--cpu-profile-dir (default $SWBLOCK_CPU_PROFILE_DIR) names an existing
directory; SIGUSR1 then starts a CPU profile written there as
blockvolume-<pid>-<n>.pprof and the next SIGUSR1 stops it. Shutdown
writes out a running profile. Unset (the default), nothing is installed
and blockvolume is unchanged. No port is opened, so a harness can
profile any running volume with kill -USR1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A reproduction that starts passing fails the job and names its issue, so its
skip is removed. A fix PR drops its line here with its skip.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolves the overlap with the merged checkpoint diagnostics: the merged
versions are kept, plus this branch's explicit map-proof mutation in the
two refusal tests (newer WAL appends alone no longer refuse). The bounded
stale-prepare test keeps the exact refusal reason check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Supplied distinct times show an advancing success updates LastAdvance
while an unchanged success, a refusal and a failure keep it; the
starved-checkpoint test now requires the second advance to be later.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CheckpointPersistenceStatus now carries the persisted CheckpointLSN and
the count and time of the checkpoint calls that moved it. A success that
was clamped or left the checkpoint unchanged is not an advance, so a
starved checkpoint shows Successes rising while LastAdvance stays frozen.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The self-hosted runner keeps GOCACHE/GOMODCACHE on disk; the setup-go post
step uploading them (~4 GB) outlasted the 25-minute job timeout after all
tests had passed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The extension write is held only when every eligible volume (and the
clean volume) has positive host validity at the frozen instant, read from
its own renewal view; under the hold every renewal started before the
writers must grant (any refusal fails).
- The clock is frozen through the set-up binds (fsync writes could outlast
a TTL and expire the first-bound volume before its renewer started) and
from the hold until the clean volume's revoke ACK (queued behind every
extension write); it then resumes from the frozen instant.
- The clock unit test registers stop + a bounded join before its readers
start, so every exit settles them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold (codex01, test only): the frozen check, time.Now and the offset
were separate reads, so a reader paused across freeze+release could see the
clock go backwards. leaseTestClock serializes Now/Freeze/Resume/SetOffset
under one mutex and never returns an earlier time than a previous Now.
TestLeaseTestClockMonotonicAcrossFreezeResume runs readers across 50
freeze/resume transitions. The held-entered and under-hold progress waits
get 30 s real-time failure exits (never a pass); the cleanup releases the
hold and joins every worker.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose hung ~9m40s in a
loaded qual run (goroutine dump: one extender held in the store hook, four
queued on p.mu, renewers looping, the test in the progress loop). Cause: a
test bug. The test's publisher clock was real time with a 2 s TTL; while the
held extension write holds p.mu no horizon can move, so a late test
goroutine let horizons expire, renewals were refused, and the progress
condition (a grant under the hold for every eligible volume) could never
hold. Not a product stall: renewals never waited for the store.
The clock is now frozen while the extension write is held and resumes from
the frozen instant at the release (no jump over a horizon), so extensions
again run in real time alongside the writers and Close. A 3.5 s late test
goroutine after the hold is now part of the test; without the freeze it
fails ('revoke ACK: lease expired').
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fold of the #260 review:
- the target endpoints get the binding endpoint rules before admission
(host:port, numeric port 1..65535, data and ctrl distinct), without
registering anything: a host match alone admitted ':0', ':65536', a
non-numeric or empty port, or identical data and ctrl, and the move
would have issued and cleared the source lease;
- host parts compare in canonical form (equivalent IP spellings);
- the refusal log runs after workspaceMu is released;
- the comment no longer calls the host match a proof; the invariants
ledger gets the move-admission row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The pattern required a unit prefix ("ms", "µs", "ns") before "s", so a
stage that took a second or more ("1.453517616s", seen under load on a
slow fsync) failed the test. It now matches a duration at any scale.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A volume without per-volume bindings could move only to the target
node's single registered address pair, which models one slot per node: a
host serving several slots refused every move whose target landed on a
slot other than the registered one (slot 1 while slot 0 is held). The
target now needs both endpoints on the node's registered hosts (literal
host part, any port, no name resolution), and the existing collision
check still refuses endpoints another live assignment or binding owns.
Volumes with per-volume bindings keep the exact binding match.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MoveWorkspace refused four different conditions with one message and no
log line: an unknown source, an unregistered target node, a target that
is the source, and target endpoints that are not registered. Each now has
its own FailedPrecondition message, logged with the volume and request.
The endpoint refusal also says what is registered: the node's own pair
for a volume without per-volume bindings, else its live bindings on that
node (a slot-1 target on a node registered at slot 0 shows up here).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold (codex01 r4 residual P1): the post-rollover check still preceded
w.append's descriptor snapshot, writer lock wait and encoding; a concurrent
Sync's slot write can hold the descriptor lock (without the store lock)
until the command expires. walWriterV3.append now takes the budget and
checks it after those waits and the encoding, before the first physical
write (no cancellation of a write already started). Red test:
TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync (a real Sync
parked at its leader point, released after the write's rollover snapshot,
holding the descriptor lock in its slot write until expiry).
P2: codex03's TestWALStoreV3WriteBudgetRechecksAfterRollover (real pinned
fallback, rollover slot I/O held/faulted; expired/healthy/fault) and
TestWALStoreV3LocalBudgetIncludesWitnessedCaptureWait from his local
amendment evidence; test cleanup joins are bounded; the invariant ledger
names the current tests and the short-lock/writer-budget rules.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Takes over codex03's fix/write-command-budget at 2d6d9711.
- P1 (codex01): appendWriteV3 / writeBatchV3Locked take the command budget
and check it after rolloverCheckpointV3Locked (its metadata I/O completes
and stays owned) and before the payload append, so an expired command
never starts new payload WAL I/O. Red test:
TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover (single, batch).
- P1 (claude05/codex01): the short locks (s.mu in Write/WriteBatch and the
pressure sampler's s.mu, descMu, writer.mu) are taken blocking again, so
they keep RWMutex writer preference; the budget is checked once they are
held. Only captureMu/lifecycleMu keep the bounded wait. Red test:
TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders. The polling-era
lock tests become TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait.
- P1 (codex01): a batch that returns a committed prefix plus a storage error
keeps that error when a required observer then fails: the classifier sees
both causes (errors.Join), so a physical fault stays terminal. Red test:
TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline.
- P2: the contextless Write/WriteBatch fallbacks refuse an already-expired
command before a fresh mutation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Resolve the conflict in the ProviderConfig comments: keep main's new DetachFreezeTimeout field and the corrected ChunkDirtyThreshold comment.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Fold of the #255 r2 review:
- the lost-range methods are part of AuthorityStore instead of an
optional capability, so no store (and no wrapper embedding one) can
issue a forced move without recording its range;
- a pending forced reservation resumes only with the exact range recorded
before it; a missing one is refused, never recomputed (a new request
records a fresh range);
- fault hooks inside the file store cover a failure before the rename and
one at the directory sync.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fold of the #258 review:
- the probe opens the volume once, locks that descriptor first, then
identifies the same open file as v3: a path replaced between two opens
can no longer yield a false unheld, and a locked file is held whatever
it is;
- locking before reading also fixes Windows, where an owner's byte lock
refused the probe's earlier read (it reported unknown, not held);
- the test reaps its holder process on every path; the CLI test closes
its store unconditionally;
- the usage text adds that the probe is momentary and reserves nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fold of the #255 review: a field in the record changed its checksummed
body, so a binary that predates it skipped the whole record and reloaded
the volume unbound. The record body is now unchanged. The forced move's
lost range (kept HEAD frontier, forced barrier) goes to a per-volume side
file that authority loaders never read, written atomically before the
move record; an entry without a matching issued move is ignored. A failed
range write refuses the move. The admission keeps its two original
predicates; the audit bound is computed separately.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ProbeVolumeUnheld takes and releases the exclusive, nonblocking advisory
lock that every v3 owner holds while its store is open; the kernel drops
it when the owner process exits. nil means no process on this host holds
the volume; ErrVolumeHeld means one does; anything else is unknown (a
non-v3 file is refused: its owner would not take the lock).
`sw-block ops volume-unheld --path P` exits 0 only when unheld (1 held,
2 unknown). The proof is per host and for local filesystems only; host
cleanup must also check that the owner process is gone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A candidate prepared successfully and then refused because its proof
went stale during the prepare's I/O was left in flight until reopen;
both preparation paths now release it before returning
ErrMapCoverageStale.
A publication whose slot write and fsync succeeded but which a fault
latched meanwhile refuses at its success boundary may still be named by
the slot on disk. It is now recorded as uncertain, so its candidate
stays pinned until reopen instead of being released for reuse.
The map's file-size counter now follows every write and truncation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
New map pages and roots go into 4 KiB extents that no live root
references, lowest first, instead of always being appended. Live roots
are the roots named by the two descriptor slots and every prepared
candidate not yet published or superseded. After each publication the
publisher reports both slots; an extent is released only once neither
slot's root references it. New pages and the root are fsynced before a
publication names them. The free tail is truncated when the file
exceeds 4x the live bytes. The on-disk format is unchanged.
WALStore.ChunkMapStatsV3 reports the file bytes, live bytes and
truncations.
Fixes#236.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A forced move abandons the old holder's writes after the HEAD frontier
it keeps (already recorded as RemoteLSN). The record now also carries
LostUntilNS: the forced barrier (lease horizon or restart deadline,
whichever is later, plus skew), the latest master time at which any of
those writes can have been acknowledged. It is journaled with the
record; clean moves leave it unset and keep their encoding.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test waits out the real ~45 s horizon; a 60 s budget left ~15 s for
the takeover, cut, detach and delete, which load and -race exceeded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A holder that exits never detaches or ACKs, so its live authority keeps
a volume delete refused. The existing path recovers it: after the lease
horizon plus skew a forced move grants epoch+1 on another host, which
claims HEAD, serves the last cut and writes past it, then detaches with
a clean ACK, after which the delete is admitted and later renewals and
moves are refused. Real master runtime and providers, in-memory remote.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The expiry case now waits until the host's own lease guard installed a new
deadline less than 1 s ahead (the 3 s grants install about 3 s ahead), read
under the guard's lock, before it stalls renewals; a blocked renewal then
follows. A completed renewal call is no longer taken as an accepted grant.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- g2Refused's probe uses a fixed lineage above every test epoch, so it is
always admissible (probes are refused only below the active epoch) and
its answer cannot depend on what the mutation did. The lineage argument
is dropped. New TestG1_ProbeHandshakeClassifiesByEffect: an accepted ship
is visible after the answer, a refused lower-epoch ship never is.
- Host lease expiry case: after a 300 ms grant was served and renewals were
stalled, wait until a renewal arrived blocked; serial renewals make that
the witness that the client accepted the 300 ms grant and is not renewed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestWorkspaceHostLeaseExpiryAndRevokeCloseRealProvider ran every case under a
300 ms lease, so on a loaded runner the lease could expire before the write,
cut or detach steps (detach-then-revoke failed #248's CI). The setup now runs
under a 3 s lease; the expiry case shortens it to 300 ms, waits until one
300 ms grant was served, and only then stalls renewals.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- durable TestRestoreWaitsForFirstAssignment / TestRestoreDeferredAssignment
WaitEndsOnDeadlineAndClose: the 2 s test bounds become progress waits; the
40 ms ChunkAssignmentTimeout under test is unchanged; the limit poll fails
at once if the backend becomes operational without an assignment.
- TestWALStoreChunk_ExplicitCutRestartsTheTimer: the final wait for the
automatic cut is a progress wait; the early-cut window check (with its
slow-host skip) is the timing assertion and stays.
- storage TestChunkLayerV3_BASEBeginDrainsWholeCut: the held-upload, drain,
settlement and resume waits are progress waits (were 5 s).
- TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap: stop
the automatic flusher before writes, as walstore_test does, so the
simulated crash cannot race its use of the descriptor ('volume locked').
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#227: g2Refused gave the listener 500 ms to close a refused connection; a
loaded machine can take longer and the refusal was misread as acceptance.
A probe at the same lineage now follows the frame on the same connection:
the listener handles frames in order, so it either closes (refused) or
answers after the frame's effect (accepted). g1Ship checks the bytes once
after that answer instead of polling for 2 s; g1Barrier drops its deadline.
New TestG1_SlowPersistFailureIsStillARefusal: a persist failure slowed past
the old window is still a refusal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fold of the #248 review:
- the v3 seed logs after the capture and lifecycle locks are released,
and names its intervals for what they include (lock wait, store mutex
and validation, data sync incl. sync serialization, checkpoint publish);
- the HEAD claim logs its start before the claim's own HEAD read and its
elapsed time on failure; the observed HEAD is logged as an observation;
- a close during the attach retry backoff ends the wait as closed, not
superseded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- master slow store: each held Put takes a generation; a renewal is credited
with the generation it read before its call, so a reply computed before
the hold never releases it. slow.release() runs as the first cleanup, so a
held Put cannot block the publisher/extender joins after a failure.
- authority WritersExtendersClose: only grants of calls that started after
the extension write was held count (flag set before the hold blocks).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- core/host/master TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore: each
lease write is held until a renewal succeeded during the hold (slowness by
progress), three held writes must complete, a sampler records any fence;
replaces the 2.5 s sleeps and the 10 s watch. A renewal that waited for the
store would let the guard lapse and fail the test at once.
- TestWorkspaceHeldRenewalBoundary, TestWorkspaceMoveRestoresLazilyAndFencesOldHost:
the test context has no wall-clock bound (3 s / 10 s); each step completes
or the go test timeout reports the hang. The guard's own RPC timeout stays.
- core/authority TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose:
wait for the held extension write and for renewals under it by progress
(were 5 s / 2 s bounds); joins after release unchanged.
- waitExtenders joins the finite extenders without a 10 s bound.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A deferred chunk attach was silent from the end of local recovery until
it served or failed. Log:
- entering the authority wait, with the projection fields that fail;
- the first attach attempt, once the projection carries authority;
- an attach that found authority gone again;
- the HEAD claim start (observed HEAD gen/epoch/holder/state/remote LSN
and the target epoch/holder) and its end with the duration;
- how the wait ended (attached after N attempts, fenced, closed,
superseded, or assignment unavailable with the fields still missing);
- the v3 seed's lock wait, data fsync and checkpoint publish durations.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The flag help and the ChunkDirtyThreshold comment still described the
cut as it was before copy-before-write: "bound on one cut's barrier
copy" and "0 = unbounded".
Since the chunk copy moved out of the barrier, the value is the number
of candidate chunks above which a cut pre-copies (stages) chunks before
its barrier, in rounds of that size, and 0 disables pre-copy
(chunk_layer.go, stage: a bound <= 0 returns without staging).
Text only. No behaviour change.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The no-host-validity refusal in RenewWorkspaceLease formatted its error
from lv.d.horizon after releasing leaseMu, while the extender
(refreshLeaseViewLocked) rewrites the view under leaseMu: a data race.
The horizon is now read before the unlock.
Test: TestWorkspaceLeaseRefusalReadsTheViewUnderTheLock drives the
refusal while the view is republished concurrently; under -race it fails
on main (workspace_lease_view.go:174) and passes here.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold (P2 cleanup, test only): an idempotent release and bounded
joins of the started workers are registered with t.Cleanup before any
worker starts, so a Fatal while the replay is parked cannot leave it
running past teardown. A join timeout is reported as an error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold (P2, tests only): the positive RF1@3 steps now write and read
back through a backend at the epoch-3 identity (exact n, nil error); the
stale-RF2 test requires a successful write. New two-worker test: the replay
worker's RF1@2 parks in the peer-set update, the stream worker's RF2@3 is
refused meanwhile, then the replay resumes; bounded by timeouts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold (P1): the refused epoch and reason were separate atomics, so an
allowed RF1@2 replay could pass the stale check, a stream RF2@3 latch the
refusal, and the replay then clear that newer refusal. The epoch, reason
and the highest admitted RF1 epoch are now one unit under rf1Mu (field
access only). admitRF1 clears and adopts only if no newer refusal was
latched; otherwise the fact is not adopted. P2: a refusal below an
admitted RF1 epoch is stale and does not re-latch. Deterministic test with
a hook between the stale check and the admit; stale RF2 test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold (P1): the refusal had no epoch, so RF1@2 -> RF2@3 refused ->
a stale RF1@2 replay cleared it and reopened the old healthy view. The
host now records the highest refused epoch; an RF1 fact below it is stale
(not adopted, refusal kept), and the refusal is cleared only after the
role fence of a current-or-newer RF1 fact succeeds, never by a failed
attempt. Test with a real backend write schedule; ingress rows for legacy
and dual-lane, and no listener after the RF1 primary role.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Test-only hooks: DetachVolume's StopIO can be replaced (the repeat and
retry tests now force and observe the failed-drain branch instead of
racing a cancelled context against a finished drain); the detach's cut
and settlement deadlines are traced (the budget test checks 3/4 of the
freeze, then the bound); the backend signals an I/O passing its
readiness check right before the I/O lock (the drain test's arrival
handshake replaces a 100 ms non-completion window, with bounded
receives).
- The delayed detach CAS worker is joined, bounded, also on failure.
- chunkErrorCode: the detach sentinels decide before a catalog-error
cause; the table rows now discriminate that order (no storage CAS
sentinel behind them).
- Invariants: INV-WS-DETACH-ABORT-001 and INV-WS-DETACH-FREEZE-001, and
the M4 transition Holder (detaching) -> Holder.
- Mutants (declared, 10/10): plus a catalog cause deciding before the
sentinels; the whole-budget cut is now caught by the deadline check too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- P1: every failed detach is settled before anything resumes, a failed
drain included. A repeated detach after a successful one (or with a
cancelled context) returns the first result and stays stopped, and a
retry over an unresolved detach CAS stays stopped while the outcome is
unknown. The StopIO failure path used to resume unconditionally.
- P1: one freeze budget covers the drain, the final cut and the
settlement (the cut gets three quarters, the settlement the rest); the
settlement no longer adds 10 s of its own. The bound is cooperative
(contexts), as documented.
- P2: the resume does not restart the periodic cuts after a concurrent
Close (or a replaced layer); ErrDetachOutcomeUnknown maps to
outcome_unknown explicitly, before its cause.
- Tests: the two P1 cases and the budget case (red on 26426dd5: resumed a
detached volume, resumed over an unknown CAS, 10.4 s for a 400 ms bound);
a detach CAS genuinely delayed until after the cancel then fails its
precondition; the drain test now checks that the resumed write queues
behind the admitted one and that recovery succeeds.
- Mutants (declared, 9/9): plus a failed StopIO resuming without the
settle, the settlement with time of its own, the cut taking the whole
budget.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold (P2): SetReplicationVolume replays a retained RF2 fact before
SetSelfFence installs the ingress gate; with no self fence the host could
install the peer set, adopt and emit readiness. The rule now lives in the
host config (RF1Only, from hostConfig at construction): every fact with
replica slots, primary with peers or supporting replica, is refused before
UpdateReplicaSet, adoption or the ready marker, and latched as a role
admission failure; an RF1 fact clears it. The ingress gate stays as the
second layer. Tests: the start schedule (blocked readiness, stored RF2 fact,
replay with no self fence), supporting refusal, RF1 recovery, unset control;
ingress refusal with dual-lane on both ports, classified by
ingressPortReleased; hostConfig wiring.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DetachVolume stopped guest I/O, then ran the whole final cut; on any
error I/O stayed stopped for the process, even when nothing was
published, and the only bound was the caller's context (up to 5 min).
Now:
- The freeze (drain + final cut) is bounded by DetachFreezeTimeout
(default 20 s, below the host's 30 s I/O timeout); a freeze past the
5 s target is logged as an ALARM.
- A detach that provably did not publish (the drain or the cut failed
before its CAS, the CAS was refused, or an unresolved detach CAS was
cancelled) resumes serving: periodic cuts restart, the stop is lifted,
and ErrDetachAborted (HTTP detach_aborted, 409, retryable) is returned.
The dirty set stays dirty, so the next cut publishes it.
- The new ChunkLayer.SettleDetach decides an unresolved detach CAS: if
HEAD is still that CAS's base, a CAS at the same base to the
non-detached base image (this holder, this epoch) cancels it, so the
detach can never land afterwards; HEAD carrying the detach means it
applied (the detached result is returned, I/O stays stopped); a newer
holder means fenced (stays stopped); HEAD unreadable leaves it
undecided: ErrDetachOutcomeUnknown, I/O stays stopped. Never resume on
top of a possibly detached HEAD.
Tests: failed upload, refused CAS, lost unapplied CAS (cancelled, HEAD one
generation on, not detached) resume and the next cut publishes the dirty
blocks; an applied CAS whose reply was lost (found by the cut's re-read or
only by the settle) stays detached; undecidable and fenced stay stopped; a
hung CAS ends at the freeze bound, is settled and resumes; the old
drain-timeout test flips (it asserted I/O stays stopped). Six declared
mutants each turn exactly their declared tests red.
Known limit: after an abort whose drain is still pending (an admitted I/O
stuck), new I/O queues behind that admitted I/O (the drain holds a pending
ioMu.Lock); serving resumes once it completes, not instantly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A chunk cut takes its LSN from the local WAL head, which no replica is
guaranteed to hold, so a published HEAD could be ahead of every replica.
The master's workspace RPCs enforce RF1; a direct start did not.
- start: --durable-impl=walstore-chunk with --replication-ack sync-quorum or
sync-all is refused at flag parse.
- assignment: the replication factor arrives with the assignment, so the
ingress role gate of a walstore-chunk volume refuses every role with replica
slots (replica, primary with peers) without opening a socket; the host's
existing role-admission latch keeps the role unadopted and not Healthy. A
primary without peers (RF1) is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Past the 64 MiB in-memory budget a copy window spills saved chunks to a
sparse side file next to the volume, with no byte limit: under a long copy
and steady writes it could fill the filesystem under the WAL/extent.
New chunkLayerConfig.COWSpillLimit (bytes; 0 defaults to 1 GiB, negative
refused at attach). A save that would take the side file past it aborts the
window (errCutCOWAborted, the caller retries the cut) instead of writing;
the guest write still completes.
Tests: a save past the cap aborts the cut, the write completes and no side
file is written; a spill within the cap is accounted (one chunk) and the cut
completes; the default applies and a negative cap is refused. Four declared
mutants (no cap, no accounting, no default, negative accepted) each turn
exactly their declared tests red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A test-only hook right before the capture barrier's Lock request; the
pause tests hold the barrier shared for 300 ms after that handshake (not
after admission plus a sleep), so the cut provably waited at its Lock and
pre-barrier time is excluded.
- The helper releases the shared hold on every path (also on a failed
assertion) and joins the cut within a bound.
- Design docs: barrierPauseNs runs from the Lock request and includes
lockWaitNs.
Mutants (declared, 4/4): pause timed after the Lock, lock wait unset, body
drops the field, the hook fired after the Lock (no handshake).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Tests: the copier's HEAD fill (after it released the entry) is
cancelled by an aborted cut and the window drains; a held fill is
bounded by ReadMissTimeout and aborts the cut; a lazily-absent saved
chunk that spills keeps its missing list and the image is exact.
- C3 waits for an actual writer-entry handshake (the writer parked on the
copy entry) instead of a 200 ms non-completion window.
- Comments: the happens-before of e.missing (published by finish), and
the lazy-HEAD saver test describes the local-only save.
Mutants (declared): fill ignores the window's end, fill without
ReadMissTimeout, missing list kept only for in-memory saves; the earlier
five now also turn the new fill/spill tests red where they should.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BarrierPauseNs started after captureMu.Lock returned, so the wait for
writers already holding the capture barrier shared (e.g. parked in WAL
admission) was not counted, although a pending Lock already blocks new
writers: the reported guest pause understated it.
The pause is now timed from the Lock request, and LockWaitNs reports the
wait for the shared holders on its own (also in the /chunk/cut body).
Tests: a cut whose barrier is held shared for 300 ms reports a pause that
includes the wait (red on main: about 24 ms) and a LockWaitNs of about the
hold, inside the pause before the sync. Three declared mutants (pause timed
after the Lock, lock wait unset, body drops the field) each turn exactly
their declared tests red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A cut candidate chunk that is lazily absent but has local writes stays a
candidate. Its first writer inside the copy window saved the chunk
synchronously through Read, so every non-local block became a remote fetch
bounded only by ReadMissTimeout (30 s), and every writer queued behind that
chunk waited on it; an abort did not cancel the fetch. The in-window copier
had the same shape: writers to a chunk it was copying waited on its fetch.
The COW save and the in-window copy now read LOCAL blocks only (dirty
map/WAL, the extent of present or locally written blocks, zeros for a chunk
HEAD stores as ZERO) and never call the miss hook. A lazily-absent block's
image at H is HEAD's by definition: it is listed as missing, and the copier
fills it from the cut's base HEAD after it has released the entry, off the
write path (bounded by ReadMissTimeout and the window's end).
Tests: the lazy-HEAD saver test now holds every remote fetch once the window
is open and requires the saving write to finish without one (it asserted the
blocking fetch before); C3 holds the in-window local copy instead of a fetch
and requires the write to complete with the remote held, the copier's HEAD
fetch coming afterwards. Five declared mutants (blocking read, absent block
read as local, no fill, saver drops the missing list, fill under the entry)
each turn exactly their declared tests red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fix H and candidates under the short barrier; save pending chunks before mutation.
Drain owners and waiters before cleanup, recovery, reset and close. Preserve
intent/CAS and local durability contracts. Include native caller controls,
existing model correspondence and a real-mount rehearsal note.
TestWALStoreV3StaleLapBytesAtTheWrapAreNotReplayed replays the forged
replay reproduction (docs/spec/README.md, open item 2) end to end on a
mapped v3 WALStore: a guest batch in lap 1 carries a well-formed record
bound to the volume's own nonce at its lap-1 cursor (LSN 999, LBA 7); the
WAL wraps so one newer record overwrites only the batch's start and the
lap-2 scan resumes exactly at the embedded record. The cursor binding
stops the scan there; after a crash and reopen the frontier is the newest
real LSN and LBA 7 is never the forged data. With the lap dropped from the
cursor check the scan admits the record and the test fails.
README: open items 1 (corrupted synced records) and 2 (forged replay) move
to "resolved in v3 (code)", citing the v3 tests. Still open: the mode C
newest-batch residual (silent truncation until an idle refresh or
SetWMode(A)) and the TLA model, which has no nonce/cursor/lap binding
(S3v1_root_lww_I1 and S3f_* rerun on cc5cf09a with TLC 2.19: unchanged).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
At RF=1 every local write logged 'replication: OnLocalWrite volume=...
lba=... lsn=... peers=0'; under sustained writes one volume's log grew to
162 MB in 13 minutes and the useful lines were buried. The counters (Stats:
WriteOps, WriteFanoutNanos) keep the per-write evidence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
All 27 W4_*/RED_* configurations re-run against the model at 7dd83eb6
(TLC 2.19, BFS): existing passes still pass, the new horizon
configurations pass with failing extension writes and a restart,
RED_hz_noclamp violates HostWithinHorizon as expected, the existing REDs
and witnesses keep their verdicts, the two large and the two "both"
configurations reached their time limits with no violation, and the two
open findings (W4_drift, W4_forced_exact) are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
lease.exp is now the published horizon, dhz the horizon on disk and
deadline the latest grant. A renewal of a live lease writes nothing:
grant = min(now + TTL, horizon), refused while uncertain or without
validity, and it may trigger an extension. The extension (MasterExtend)
is an ordinary serialized writer that raises the horizon to
trigger + TTL + HSlack; with ExtFail its write may fail without landing or
after landing, and either way latches uncertain. Revocation, ACK and move
writes are refused while uncertain; a restart reloads the disk horizon and
clears uncertainty. The revoking drain reply is clamped to
min(horizon, deadline). Nondecreasing time is stated as a model assumption.
New invariants HostWithinHorizon and DiskCoversMemory; witnesses
W_NoExtension, W_NoExtLanded, W_NoUncertain. New cfgs W4_hz_* (failing
extensions, clean/forced/both, one restart) and RED_hz_noclamp (no clamp:
EXPECTED to violate HostWithinHorizon) with the control
RED_hz_noclamp_safety (no clamp, split-brain invariants: expected to pass,
the restart rule covers grants). Existing cfgs gain Clamp = TRUE and
ExtFail = FALSE.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review folds, tests and docs only:
- The combined concurrency control now requires its schedule: a bounded
handshake holds the first horizon-extension write inside the store
while renewals keep succeeding and the writers and Close are in flight
behind it, then releases it. It counts successful grants per eligible
volume and extension writes classified by content (a raised horizon at
the same epoch, not an ordinary writer's record) and requires both.
- It adds the forced-move arm next to the clean move: the forced volume
is granted at an earlier injected time, so its horizon + skew barrier
has passed when the writers run; the clock only moves forward.
- Held-write controls install their release cleanup before the hold is
triggered, bound every admission and completion wait, and on any
failure release, settle workers with bounded joins and only then close
fixtures.
- Docs: an uncertain volume refuses renewals that would issue a new or
extended grant; a Revoking lease still gets its bounded drain reply,
min(horizon, deadline), never extended, as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
If another writer created the lease after the renewal read the view, the
first-grant path now returns a retryable error instead of re-entering the
memory path. The host has no deadline before its first grant, so a failed
first renewal does not fence it; its retry takes the memory path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- invariants.md: M2 lease rows (first grant writes the horizon, renewal
from memory under a clamp, revoking reply carries the grant, expiry
and forced barrier on the persisted horizon); new rows
INV-LEASE-VIEW-001, INV-WS-LEASE-HORIZON-001,
INV-WS-RENEW-NONBLOCKING-001 and INV-LIFECYCLE-SNAPSHOT-001;
INV-WS-FORCED-MOVE-001 now names the horizon and the reply clamp.
- INV-AUTH-UNCERTAIN-001 moves from STUB to ACTIVE: its renewal reader is
documented, and the ambiguous-extension control now also asserts that
a revocation and an endpoint change of the uncertain volume are
refused.
- Proof-text folds: the forced-barrier argument assumes nondecreasing
master time, an assumption of the current WorkspaceTakeover model,
not a consequence of time.Now's monotonic reading; the horizon
invariant treats an ambiguously persisted issued successor (lease
cleared) as the ordered clean-handoff or forced-barrier case.
- agent-workspace-design.md section 7 and workspace-lease.md: the
master side of a renewal, the extension, the capacity bound, the logs.
The WorkspaceTakeover specification is not changed here; its update and
recorded configuration results are a later acceptance step.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GREEN-gating controls for the memory-only renewal:
- grants clamp to the durable horizon under a permanently stalled
store, renewals without host validity or at the horizon are refused,
and a real guard fences by horizon - skew/2;
- a restart honours the persisted horizon in the forced barrier;
- an extension whose rename landed but whose directory sync failed
latches uncertainty, refuses the next renewal, and reloads with the
landed horizon barring a forced move until horizon + skew;
- an extender held inside its write orders a same-volume revocation or
forced move after it;
- same-volume renewals during held revocation and forced-move writes;
- the lease view equals derive(published) after every writer kind;
- N volumes renew concurrently with apply, revocation, ACK, a clean
move, extenders and Close (run with -race);
- Close joins a held extender, and an extender admitted before closing
writes nothing;
- lifecycle snapshots follow every records change, stay immutable, are
read without the store mutex, and keep a protective unknown outcome;
- through the services layer, query and revoke replies report the
grant, and a renewal during a held same-volume reservation returns
the revoking lease.
The r1-r3 slow-store wrappers count the delayed writes and require at
least one, so a green cannot bypass the injected stall. Tests that own
a Publisher directly join its extenders before their store closes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A renewal of a live workspace lease persisted the new expiry with a
temp-file fsync under the publisher's global lock, and the renewal RPC
also read two lifecycle stores whose mutexes writers hold across file
I/O. A slow or busy master disk therefore made the host's 2 s renewal
RPC time out, the guard fence and the volume shut down.
Renewal now takes only a small leaf lock (leaseMu) over a per-volume
lease view and does no I/O:
- grant = min(now+TTL, durable horizon), where the horizon is the
published Lease.ExpiresAtNS; the deadline is raised to the grant.
- It refuses stale, pending-move, expired, uncertain or storeless
state as before (never bypasses INV-AUTH-UNCERTAIN-001), and refuses
with an error when the grant would leave no positive host validity.
- The first grant of a lease still writes synchronously under p.mu and
persists horizon = now + 1.5*TTL.
- A per-volume single-flight extender is an ordinary p.mu writer: it
writes horizon = trigger + 1.5*TTL through persistWorkspaceLocked, so
its write and publication are one p.mu section; any write error
latches uncertainty as before.
Writers keep persist-before-publish and refresh the view (p.mu ->
leaseMu, the only new lock edge) at every derive-input change.
Revocation and query replies report the granted expiry, never the
horizon. Host.Close joins extenders before the store closes.
The renewal RPC reads lock-free immutable snapshots of the Volumes and
deletion-reservation stores, republished at every records change
(including load, delete and the protective unknown outcome).
Behaviour change: a forced move now waits for the durable horizon plus
skew, at most TTL/2 later than before. Existing tests that read the
persisted lease as the grant, or waited only grant + skew, are updated
with that reason. The store-write boundary guard now skips _test.go
files: a test double that delays and delegates Put is not a production
write caller.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add DeletionReservationStore.SetPersistHookForTest, an instance-local
test seam that installs the existing write-fault hook under the store
mutex (nil by default).
r5: while the deletion-reservation write of an unrelated volume is held
in that hook, a renewal through the services layer must return within
2 s. On main it waits on the reservation store's mutex.
r4 and r5 now release held writes first and settle every worker with
bounded waits before clearing hooks or closing fixtures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
r4: while the revocation write of volume a is held inside the
authority store, a renewal of volume b must return within 2 s.
On main the renewal waits on the publisher's global lock until a's
write is released.
Tests only; no fix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold for #207: a valid reply that lands after the renewal call's
context ended, while the old lease and the new grant are still valid, was
recorded as "arrived after the lease deadline". The refusal is unchanged;
the cause now says which limit the reply missed: the lease deadline, its
own grant, or the call's context (with the lease's remaining validity).
Adds a bounded regression where the reply lands just after the 2s call
timeout with a 20s lease.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A renewal of a live workspace lease persists the new expiry with a
temp-file fsync under the publisher's global lock. When the master's
disk is slow, the host's 2 s renewal RPC times out, the guard fences
and the volume shuts down.
- r1: one renewal behind a 2.5 s store write must return within 2 s.
- r2: six concurrent renewals behind 0.5 s writes must not serialize.
- r3: a real WorkspaceLeaseGuard must not fence while the store takes
2.5 s per write (TTL 6 s).
Tests only; no fix.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fold for #207:
- A failed renewal now logs whether the call reached the lease deadline,
the 2s per-call timeout, or neither, so a slow master is told apart from
a lease that ran out.
- A stop that fails after a fence returns an error that names the fence
cause and wraps the stop error; after a renewal expiry or an invalid
reply both the renewal error and the stop error are kept (errors.Is).
- Tests assert the first cause wins, the fence is logged once, the cause
carries the exact deadline, and a late revoking reply keeps the
late-reply cause.
- The #205 test comment states the renewal-failure trigger as a hypothesis
that matches the code path, not a diagnosis the logs proved.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guard fenced silently: when renewals kept failing until the lease
expired, it drained the volume through blockvolume's lease-stop path, which
logged nothing, and returned the raw RPC error (issue #205).
- Every fence records its first cause: lease expired without a successful
renewal, expired after a failed renewal (with the renewal's latency and
error), an invalid reply, a reply that arrived after the deadline,
revocation by the master, or shutdown. The guard logs it once as
"workspace lease: fenced ...", FenceCause() returns it, and the non-ACK
drain error carries it.
- Every failed renewal is logged with its latency and the lease deadline,
also when the lease is still valid: a run of them is the warning before
an expiry fence.
- An expiry after a failed renewal returns "workspace lease expired:
renewal failed after <d>: <err>", wrapping the RPC error.
- blockvolume logs when it stops because the guard requested the drain.
The fence behaviour itself is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Issue #205: under sustained write load a volume fenced because its lease
renewals kept failing until the lease expired, and nothing said so. The
shutdown path logged nothing; the only trace was the raw RPC error printed
at closeout. The fence itself is correct.
Two tests fail on main:
- a renewal that times out past the lease deadline fences (as today), but
the returned error must say the lease expired and keep the RPC error,
and the fence and its cause must be logged;
- a renewal that fails while the lease is still valid must be logged with
its latency (it does not fence).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Step 6 counted only saved-chunk readers. A saving writer and a copier
reading the live chunk also do I/O outside the per-chunk mutex, so an abort
or Close could see zero references and delete the side store while they
were still in I/O. Now every saving or copying owner holds a window
reference from its state claim until its I/O ends, readers hold one too,
abort does not wait for its caller's own reference (a self-aborting owner
releases first), Recover/reset/Close join every owner and reader before
their destructive transition, and the side store is deleted exactly once
at a terminal state with no reference outstanding. The test list names the
held saving owner and held live-copy owner cases. Text only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Design review of the copy-before-write proposal, folded in one revision:
- the COW step runs before publication and outside store.mu (right after
captureMu shared, before lifecycleMu/mu, the WAL append and the dirty-map
insert), because the save uses the ordinary read path; a post-publication
hook cannot do this; lock order stated;
- one owner per chunk (copier: pending -> copying -> done; writer:
pending -> saving -> saved), a per-chunk mutex never held across I/O,
waiters on a per-chunk condition;
- batches visit chunks in ascending index and finish each before the next,
so they cannot deadlock with each other or the copier;
- terminal states closed or aborted; abort on save error, cancel, fence,
and before Recover/reset/Close in the same open, taken before the
mutation proceeds; waiters woken; the cut fails retryable and keeps its
dirty set; a guest write is never refused for a cut problem;
- the side store is deleted only after close/abort with its refcount at
zero; upload, manifest and CAS work from the buffers, so an unknown CAS
keeps today's semantics;
- BASE: capMu stays held for the whole cut and already excludes
Begin/EndBaseInstall (the earlier open point is removed);
- reads bind to the format-v3 read path, no flusher hook;
- the Model paragraph states what the model does not cover (owner races,
batch order, abort), and the test list grows to match.
Text only; the TLA+ model is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The cut copies every candidate chunk under the capture barrier, so writes
stall for the whole copy (1.50 s at 3 GiB dirty in a lab measurement).
agent-workspace-design.md section 5 now has a proposed (not implemented)
copy-before-write design: the barrier only fixes H and the candidate set;
the first write to an uncopied candidate saves its at-H content to a local
side store; a write to a chunk being copied waits; the copier reads the side
store or the live chunk; the side store is dropped at the CAS and on crash,
and recovery never reads it. Alternatives, the open BASE-install point, and
the tests to write with the code are listed. Section 14's cut-cost gap
points at it.
docs/spec/CutCOW.tla (S4c) models today's barrier cut and the design, with a
two-step chunk copy and one crash. Both pass exhaustively at MaxLSN 6 with 2
cuts (COW 34,342,214 states, barrier 5,070,320). Each of the six design rules
is necessary: dropping any one violates BufFrozen. 11 configs, run.sh and
the spec README updated; all 13 specs pass SANY with tla2tools 1.7.4.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ScanLBAs on v3 now returns entries only when the trusted chain covers the
whole captured range [fromLSN, head): a chain that stops short is a WAL
integrity failure carrying the scanner's stop cause (CRC, binding,
truncation), a chain that starts after fromLSN is WALRecycled, and a
missing LSN mid-range is an integrity failure. Nothing is emitted before
the check.
An installing source is refused with ErrBaseInstalling before emitting.
The capture (recover generation, descriptor, head) is taken under s.mu
and revalidated after the scan, with no lock held across the callbacks;
a transition during the scan retries from a fresh capture, and a source
that began installing meanwhile is refused.
Controls: corrupt middle and first records (store), an installing
source, an install begun during a held scan, a Recover during a held
scan (retry), and a corrupt middle record through the actual catch-up
sender (the session does not close successfully).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The 12b census found WALStore.ScanLBAs walking only the v2 WAL writer, so
a v3 primary served no catch-up: every catch-up shipped nothing and the
replica then refused the next live LSN as an unanchored gap. On v3 it now
scans the trusted v3 chain from the selected descriptor's scan start
(after the unchanged retention gate): a write record is one entry, a
batch record one entry per block with consecutive LSNs, every LSN in
[fromLSN, head), in LSN order. If the WAL no longer holds fromLSN it
refuses with the typed WALRecycled failure (the caller rebuilds) rather
than skip a range; today no v3 tail release exists, so that guard is
defensive until one lands.
Controls: the store scan (singles and a batch, from the start and from
mid-batch, the retention refusal) and the actual catch-up sender from a
v3 primary to an empty v3 replica (byte-identical). Mutants: the v2 scan
on v3, a batch emitting only its first block. The missing-fromLSN guard
has no discriminating control until a v3 tail release exists.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ordinary replicated ApplyEntry was still refused (errV3NotYet) on dark
v3, while its real callers are the replica's MsgShipEntry handler
(replica.go) and the ReplicaApplyGate's recovery and live lanes. It now
shares one body with the install-lane apply (applyEntryV3, DESIGN 8.1,
6.7, r16.1): through the v3 writer in LSN order; an LSN at or below the
highest appended is a superseded no-op when the LBA holds a higher LSN
and ErrWALLSNOrder otherwise; an unanchored gap is refused (recovery
needs a contiguous prefix); and an ordinary apply while installing is
refused with ErrBaseInstalling (the install lane is the handle's).
Controls: the store rules and a crash; the real ship handler on a v3
replica (apply, barrier ack, crash and reopen; an out-of-order entry
ends the connection); the real apply gate (recovery lane with its
stale-skip, live lane). Mutants: ApplyEntry refused on v3, no gap check,
no installing refusal. The store's order check alone is equivalent: the
v3 writer refuses the same LSN with ErrWALLSNOrder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex03's row 12a retirement-timing seam, store half: a completed BASE
must not retire while the provider's fresh-from-HEAD marker could still
make a reopen seed from HEAD over the completed local bytes.
- CommitChunkAttachV3(commit) runs the provider's commit (the marker
removal and directory fsync; no store re-entry) under installMu
exclusive, and only when it succeeds records this open's durable
attach and lifts the retirement deferral of an installed volume. A
failed commit changes nothing.
- OwnerChunkAttachDurableV3 reports that flag (atomic); Defer resets it at
every managed open; a begin re-arms the gate but keeps the flag.
New edge: the provider's attachMu -> installMu; the store takes no
provider lock. Not a v3 store: commit only.
Control: the commit runs under installMu exclusive; a failed commit sets
no flag and the volume stays installed; a successful one retires it on
the next publication; Defer resets the flag. Mutants: lifting on a
failed commit, not recording the flag, committing outside installMu.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Descriptor-owner ruling on codex03's row 12a retired-BASE RED (6f545aad):
once a completed BASE retires to none, nothing durable tells the provider
that the local image is complete rather than a lazy seed. Retirement may
now be deferred, opt-in per store, so the installed descriptor stays that
evidence until the chunk layer has durably recorded local presence:
- DeferBaseRetirementV3 (the provider, at open, before Recover and any
publication) and AllowBaseRetirementV3 (the chunk layer, after durable
local presence) set an atomic gate on the publisher;
- retireBaseV3 is skipped while the gate is deferred; once allowed,
retirement happens on the next ordinary publication;
- every successful begin re-arms a lifted deferral, so a later install in
the same open needs its own durable presence before it may retire.
The publisher only reads the atomic under descMu: no new lock edge, no
format or durable field. Stores that never set the gate retire as
before, so a volume without a chunk layer cannot be stuck installed.
Control: a deferred store stays installed through publications whose
8.4 conditions hold, retires on the first one after Allow, and a second
install in the same open is deferred again. Mutants: a publisher that
ignores the gate; a begin that does not re-arm it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent-workspace-design.md:
- section 3: a HEAD, a snapshot and a fork root are each a complete map
(no backing chain, no per-layer bitmap); a cut uploads only changed
chunks and rewrites only their segments; the dirty bitmap is local
holder state, not part of a snapshot; a worked example (100 chunks,
init, 20 rewritten, snap1: 120 objects, deleting init frees 20).
- section 6: the GC roots line now says what the code does: a deleted
snapshot's attempt stays a root for one grace period after its delete
time (Collector.snapshotAttemptHeads), then stops counting.
- section 6: freeing an old snapshot's data in three steps (delete the
name, GC --apply with two marks a grace apart, SeaweedFS volume vacuum)
with the timing at the default grace, and why GC uses a reachability
mark rather than reference counts.
No invariant row changes (INV-GC-REACHABLE-001 already covers attempts).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 review of 7c6a29d8:
- P1: ValidateMigrationV3 lacked the checked extent end, so an aligned
geometry whose extent end overflows passed, the backup and the map were
written, and only the slot validation refused. The geometry check now
applies the same bounds (volume, extent, block, the checked WAL and
extent ends, the file end within MaxInt64), and the tool runs it, and a
file-size bound on the v2 WAL, before the WAL is read or anything is
written.
- P2: the scan allocated the v2 WAL size from the superblock before any
bound; it is now bounded by the file size first, with no wrapping sum.
- P2: a rerun that found the v2 chunk bitmap already renamed skipped the
directory fsync an earlier run may have failed; it now fsyncs it.
Controls: an overflowing extent end, a WAL past the file end and a WAL
size whose sums wrap are each refused with no byte written; a retirement
whose directory fsync failed is made durable by the rerun. Mutants: no
checked file end, no file-size bound, the rerun skipping the fsync. The
WAL-region overflow check alone is equivalent: the file-size bound also
refuses that case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.4 section 10.1. The tool (cmd/sw-block/migrate.go) runs the
steps, each durable before the next: the read-only exhaustive scan and
the geometry check (a refusal changes no byte), the atomic operator
backup of the v2 superblock, the initial map sidecar (generation 1, every
chunk UNKNOWN, covered = the v2 checkpoint), the prepared slot B at 4096,
slot A at phase 0 (the commit point), slot B at phase 0, then the v2
chunk bitmap retirement, and prints the new descriptor hash. A rerun
decides from the slot bytes alone (the 10.1 table): a v2 A restarts with
a full rescan; a committed A finishes the rollover and the retirement; a
committed B only the retirement; a prepared B with an invalid A refuses
with ErrMigrationIncomplete; neither valid refuses. It never reads or
restores the backup.
core/storage/migrate_v3.go is the tool-only export: it reuses the row-1
slot codec and the row-6 map codec (no second encoder), keeps the extent
base (new WALSize = old - 4096), and opens or serves nothing.
Controls through the actual CLI entry and, tagged, the actual v3 open:
a clean migration (extent unchanged, backup, retirement, the old binary
refuses, an idempotent rerun, v3 serves the v2 blocks with an all-UNKNOWN
map), refusals changing nothing, a crash after each step, the old binary
after preparation, a partly and wholly overwritten prepared B, and the
backup never restored. Mutants: no clean scan, commit before prepare,
retire before the commit, no rollover on rerun, an unrefused incomplete
state, a clean initial map. Not yet: the shared advisory lock (12b) and
committed raw v2 fixtures (13c).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The chunk layer fills chunkCutStats for every cut, but the /chunk/cut body
dropped them (the W2 placeholder said "added when W3 fills them"). The body
now carries a "stats" object that mirrors storage.ChunkCutStats field for
field: barrier pause, sync, copy, candidate/uploaded/zeroed/unchanged chunks,
uploaded bytes, upload and CAS time and result, total time, and the staging
counters. A reflection test keeps the body in step with the layer's struct,
so a new layer statistic cannot be dropped silently.
This lets a caller (the CLI, a test harness) see what one cut cost without
reading logs: the barrier pause against the chunks it copied, and the bytes
each cut uploaded to the store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The chunk layer now measures every cut (barrier pause, chunks and bytes
uploaded, unchanged chunks, staging), but the /chunk/cut body still
omits them, so a caller cannot see what one cut cost. Both tests fail on
main: the body has no "stats" field.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The activation limiter codex01 named: v3 WriteBatch (the real 8 KiB
multi-block write) and its replay/read path returned errV3NotYet. Dark:
- WriteBatch on a v3 store appends one multi-block record (type 0x04)
with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it
or none; the writer consumes the whole range (DESIGN 6.7, r16), the
map coverage follows every block's LSN, and each block's dirty entry
names its data offset inside the record. A single block is a write.
- One whole-record reader (readWholeRecordV3, blockOfRecordV3) serves the
store read, the flusher and codex03's dark offline reader: it sizes the
record from its type and Length, validates the whole record and the
block's LBA, LSN and offset in it. The read retry also compares the
data offset.
- Recovery's replay and the install-path replays (the reopen cut and the
same-open continuation) republish every block of a batch.
Controls: round trip across a crash in both modes, a torn batch (dropped
whole when unacknowledged, fail-closed when acknowledged), a crash
mid-batch (latched, never acknowledged, none served), the ack boundary,
the flusher, the offline reader and the map coverage. Mutants: block 0
reads, first-block replay, a split batch, a flusher at offset 0, an
offline reader indexing only block 0, no map coverage.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.4 section 10.1, the read-only half of `sw-block migrate-v3`:
cmd/sw-block/internal/v2legacy holds the frozen v2/impl1 superblock reader
(precondition 2: magic, version 2, walstore, impl version 1; impl 2 is
refused) and the one-record v2 entry probe, so the v3 open code keeps no
legacy reader and row 14 can delete the legacy production code.
ScanClean is precondition 3: it tries the frozen decoder at every byte
offset of the whole WAL region, circularly, and refuses any CRC- and
EntrySize-valid record of a known type whose type-derived footprint fits
the region (38 + Length for write, batch and padding; 38 for trim and
barrier, whose Length is an affected range) and whose last LSN is above
the checkpoint, plus any CRC-valid batch whose count cannot be
classified. Records at or below the checkpoint are ignored. It never
runs recovery or replay and writes nothing.
Controls: every record shape (wrapped, trim range, batch last LSN, zero
count, embedded in a payload, bad CRC) and real v2 stores (cleanly
closed scans clean; synced but never flushed refuses).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 review of aa477c09 (pre-existing live-continuation P1): a
same-open installing Recover cleared the dirty map without replaying it.
With BASE LBA 1 = B0 and then install-lane LSN 11 at LBA 1 acknowledged,
the original handle could continue (r17.4), apply and acknowledge LSN 12
and complete, and a same-open read of LBA 1 then fell back to B0.
When the installing ID was begun in this open, the Recover now either
republishes the live install's trusted records (<= R) in the dirty map,
keeping the volatile map coverage (the BASE writes' UNKNOWN) as it is,
or, when the recovered cut is short of the live writer (damage under a
live install), latches the store so the handle cannot append behind the
gap; a physical reopen then decides intact or damaged. No DESIGN text
change.
Controls: codex01's exact schedule completed and read through the
original handle in the same open; a same-open Recover over a damaged
record fails closed. Mutants: no replay (serves B0), no latch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 11b review (3c67ee56): a same-open Recover while this open's
install was live cached E and R but left the install's handle valid
(r17.4: until the next begin). That handle could apply and acknowledge
LSN 12 past the cut; a resume then fenced from the cached E and
fsync-erased the acknowledged record before the forward-only writer
refused to move back.
An installing Recover now records its recovered bounds only when the
installing ID was not begun in this open (a physical reopen). After a
same-open Recover the live install simply continues; a resume or a
fenced supersession refuses before any I/O. No DESIGN text change:
section 8.3's resume is the reopen case, and r17.3.1 already says a
same-open continuation keeps the live writer position.
Control: the held schedule (same-open Recover, the old handle applies
and acknowledges LSN 12, then a resume): the resume refuses, LSN 12's
bytes are unchanged, and a physical reopen still resumes and serves it.
Mutant: recording the cut on a same-open Recover erases LSN 12.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.4 section 8.3, "Resume (same ID)", store level and dark (no
current caller resumes: both receivers begin fresh install IDs). Under
installMu exclusive the resume appends nothing until all three hold:
1. trusted-through-W: the recovered suffix is intact (R >= W*) and E is
at or past the persisted retainedHead;
2. the 6.6 fence of [E, floor + WALSize) with fsync;
3. a publication of retainedHead = E (G3).
Otherwise it refuses with ErrInstallSuffixDamaged, writing nothing, and
the volume stays installing. The writer continues at E (forward only)
and the reopen's trusted install-lane records are replayed so the
completed image serves them. The installing Recover now keeps those
records with its recovered bounds.
Controls: an intact resume that serves the recovered LSN 11 and fences
the dropped LSN 13; a damaged suffix refused; E below the persisted head
refused, while a covering supersession anchors at P = that head and stays
resumable across a crash. Mutants: no fence, ignoring the damage, no
E >= head check, anchoring the supersession at P = E.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.4 sections 6.6 (G3) and 8.3, dark:
- An installing Recover keeps its recovered bounds (E, R, intact or
damaged) and moves the allocator state above every trusted record, but
fences, publishes and admits nothing; the outcome stays the typed
ErrBaseIncomplete.
- A superseding begin after that reopen checks the coverage rule, then
fences [E, floor + WALSize) and fsyncs before its two-slot installing
publication, so no record of the old install beyond E re-chains;
it anchors at P = max(E, the persisted retainedHead), never lowers
retainedHead, and restarts the writer at P (advanceHeadV3, forward
only, no LSN change). Reads and the flusher see a recovery boundary.
- A damaged suffix refuses nothing here: the supersession does not need
trusted-through-W, because the new BASE covers every record <= W.
Controls: the G3 revival schedule (A's LSN 13 beyond the gap would chain
on after B's 12 at the same position) and a covering supersession over a
damaged, acknowledged suffix (below W refused, at W installs and serves).
Mutants: no fence; trusted-through-W applied to the supersession.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.4 section 8.7, caller 2 (core/transport/replica.go, the
production default --recovery-mode=legacy):
- the first admitted MsgRebuildBlock of a connection, or an empty
rebuild's MsgRebuildDone, begins one install at the lineage's frontier
hint under a fresh random ID; a different hint on the connection is
refused; a reconnect is a new connection and so a superseding install
under the coverage rule;
- each block is written through the handle's WriteBase, never the
store-level WriteExtentDirect;
- MsgRebuildDone completes through the handle, then calls Sync, which is
ordinary once installed, and stops discarding the Sync error: a failed
completion or Sync closes the connection with no MsgBarrierResp.
Stores without the seam keep their pre-seam behaviour behind the legacy
handle (lazy BaseStager staging, WriteExtentDirect, AdvanceFrontier at
completion). The one behaviour change on them is the DESIGN 8.7 rule: a
Sync error on the done path no longer replies AchievedLSN 0 but closes
the connection. The live MsgBarrierReq handler keeps replying the gated
Sync's 0 while installing (section 7).
Tagged controls on a dark v3 replica: the positive and empty rebuilds,
the real BlockExecutor.StartRebuild -> doRebuild path, injected
MarkBaseComplete and Sync failures, and reconnect supersession.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 10a review (66be344b): after the publisher's final check, a
queued append of the same install could fail and latch the store while
holding WALStore.mu; SyncInstallLog then returned H anyway. It now
rechecks stickyIOFault under WALStore.mu immediately before it moves the
acknowledged frontier and returns H (the #172 ack-boundary rule section 7
imports), and returns the fault instead.
Control: a held same-ID append whose pwrite fails between the
publication and the ack; the ack is refused and the acknowledged frontier
does not move. Mutant: no final locked check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.4 section 7 (O1-a), dark:
- While installing, the v3 logical Sync returns exactly (0,
ErrBaseInstalling): no batch, no new W; the gate is rechecked at the
completion under the leader role.
- SyncInstallLog(installID) on the narrow InstallLogSyncer (not on
LogicalStorage): under installMu shared it refuses outside an install
(ErrNotInstalling) or for another ID (ErrInstallIDMismatch), freezes the
cut H, fsyncs the WAL and publishes W = max(W, H) with BaseState still
installing, always mode A. A v2 store's SyncInstallLog is its Sync.
- The receiver's sendAck uses it until the session's own BaseDone, then
the ordinary Sync (the WAL lane can outlive BaseDone, r17.4).
Controls: the gate, the refusals, mode A on a lagged store with a crash,
the receiver's progress ack (tagged), and the receiver-only boundary.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Plan row 9: SeedChunkFrontier uses the checkpoint's map/metadata barrier
and the sole descriptor publication. The mapped v3 checkpoint body is
extracted into publishCheckpointV3 (metadata and chunk barriers, owned-map
candidate outside every lock, the sole slot publisher under syncMu with the
recovery-lifetime check), which the flusher's checkpoint and the seed both
call. The v3 seed fsyncs the data, then raises W and CheckpointLSN to the
inherited frontier in that one publication, and moves the volatile
frontier only after it; a failure publishes nothing and a retry works. It
refuses local writes, an install, an attached chunk layer and a store
without an owned map, writing nothing.
The dark provider still refuses a HEAD restore onto a v3 store
(errV3RestoreNotYet in PrepareRestore, before any seed or claim) until the
v3 FreshFromHead restore on the owned map lands (codex03), so codex03's
TestDurableProviderV3_UnwiredHEADRestoreRefusesBeforeClaim stays as is.
WALStore.FormatV3 reports the dark format.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 9b review (f08ee20c): the real Sender sends BaseDone from its
base lane while its WAL lane is still sending, but a completed install
refused every later WAL entry of the same session (the handle admitted
only while installing). DESIGN r17.4 (Claude01 ruling A):
- every begin bumps an install epoch; a handle is admitted only while no
later begin has run (checked under installMu shared);
- WriteBase stays installing-only under the handle's ID;
- ApplyInstallEntry is also admitted after the handle's own successful
MarkBaseComplete, while installed under its ID or retired, under the
8.1 order and gap rules;
- a later begin refuses the old handle with ErrInstallSuperseded, even
after both installs completed and retired.
Controls: the real receiver in the Sender order (BASE, WAL, BaseDone,
WAL, barrier), also across a crash and reopen; the store-level lifetime
control. Mutants: installing-only admission, no epoch check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.3.1 section 8.7:
- BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) returns an
InstallHandle (WriteBase, ApplyInstallEntry, MarkBaseComplete). The v3
WALStore runs the row 9a begin; a v2 WALStore and stores without the
seam get the legacy handle, which keeps their exact pre-seam behaviour
(WriteExtentDirect, ApplyEntry, AdvanceFrontier(baseLSN)) and stages a
BaseStager store lazily before the first BASE block or completion.
parallelwal's staging step is renamed BaseStager.BeginBaseStage; the
legacy replica caller uses it unchanged (row 10 rewrites that caller).
- The dual-lane Receiver begins the install at SessionStart, inside the
counted section, at FromLSN under a fresh random ID; RebuildSession
writes, applies and completes only through the handle, and
MarkBaseComplete's error now fails the session with no ack.
- Tagged (swblock_format_v3_test) controls through the real receiver on
a dark v3 store: the positive rebuild, the held-write drain, the parked
frame for both lanes, and a superseded BaseDone failing without an ack.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 9a review (60803a87), two P1s:
1. With W 1 and unacknowledged LSNs 2 and 3 appended, a begin at
BaseLSN 1 left 2 and 3 behind BaseCursor while the allocator went on
at 4; after complete an acknowledged write 4 met a hole at reopen
(strict R 1 < W 4; lagged could drop it). The begin now also needs
BaseLSN >= the highest appended LSN and is refused otherwise, writing
nothing; nothing is rewound or dropped.
2. A BASE write's UNKNOWN coverage was only in memory, and complete
published installed with the old clean map root. Complete now settles
step 2 like a checkpoint: one fsync, the metadata and chunk barriers,
a fresh owned-map candidate, and one installed publication carrying
it, under the leader role and the recovery-lifetime check. A guest
write that makes the candidate stale fails the completion.
Each has an actual-store control and a mutant. The held-test hooks now
always release in cleanup (P2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5 and 8.7 on the v3 store,
reachable only from tests:
- beginBaseInstallV3 takes installMu exclusive (draining the old ID's
admitted mutations), refuses BaseLSN below the acknowledged W
(published or not yet, mode C) or the checkpoint with the begin- or
supersede-specific error before any write, freezes P at the writer
head and publishes installing into both slots.
- installHandleV3.WriteBase and ApplyInstallEntry admit under installMu
shared and recheck the state and ID under it (ErrInstallSuperseded);
the install lane applies the order and gap rules and maps a full ring
to ErrBaseInstallNoSpace.
- markBaseCompleteV3 validates the ID under installMu exclusive, fsyncs
the BASE bytes and the install-lane suffix, publishes installed with
retainedTail >= BaseCursor, drops the superseded pre-BASE dirty
entries and moves the frontier to BaseLSN.
- installing -> none is refused (no abort, r17); installed -> none
retires only once the checkpoint covers BaseLSN and both slots carry
a tail at or past BaseCursor.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Recover bumped recoverGen before dm.clear only. A read already admitted
could capture the new generation with the old dirty entry in that
interval, see the fenced bytes, then find the same LBA/position/LSN
rewritten after the recovery: tuple and generation matched, a false WAL
integrity failure. Recover and reset now also bump it at their end (on
every path), the start+end pattern of the map proof epoch, so any overlap
changes the generation a reader compares before and after its attempt.
The outer Sync completion's equality check is unchanged in meaning.
Control (held, actual Read/Recover/Write): a read admitted before its
generation capture, released after the start bump and before the clear,
resolves the old entry, sees the fenced bytes after the recovery and the
same-tuple rewrite, and returns the new write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(1) A same-open Recover can fence a dropped record and re-allocate its
LSN to the same LBA at the same position: a read parked across it saw the
fenced bytes and, finding the entry unchanged, reported false WAL damage.
The unchanged-entry verdict now also requires the same recovery
generation (a reset bumps it too) across the attempt; otherwise the read
retries and returns the new write.
(2) A failed or short pread (including io.EOF: the WAL region lies inside
the file) is a substrate I/O failure, never WAL integrity. Only a record
that was read and fails validation within one stable lifetime is damage.
The comment no longer implies a nonce check: LSN allocation runs on across
a reset, and LBA+LSN+CRC identify the resolved write.
Controls: a parked read across a reusing same-open recovery returns the
new write; a truncated file and a failing fd give substrate I/O.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A Read that resolved an LBA's WAL position held no lock across its pread.
Parked there, the real flusher could checkpoint and release the entry, a
reset restart the cursor at 0 and Write(2, B) reuse the position; the
resumed read checked only the header type/length and returned B for LBA 1.
The same held after OnReadMiss.
readDirtyV3 now validates the whole record after the payload read (CRC,
footer, write type, LBA and LSN against the resolving dirty entry) and
re-resolves on a mismatch: the entry gone means the extent holds the
block; the entry unchanged means WAL damage (a WAL integrity failure).
No lock is added; the lock graph is unchanged.
Controls: the parked direct Read and the parked post-OnReadMiss recheck
across flush, reset and overwrite return LBA 1's own block; a damaged live
record is a WAL integrity failure.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
WALStore.Close serialized the legacy superblock and pwrote it at offset
0, which on a v3 file is descriptor slot A: strict create A1, Recover B2,
Write+Sync A3/W1, Close destroyed A, reopen selected B2/W0. A v3 Close now
writes nothing (acknowledged state is already in the slots and the WAL).
Both legacy offset-0 writers (writeSuperblockMetadata and
syncDirectFrontierMetadata, behind the checkpoint, v2 recovery,
SeedChunkFrontier and the direct-frontier Sync) refuse on a v3 store with
errV3LegacySuperblockWrite.
Controls: Close -> reopen in strict and lagged mode with the newest
publication in slot A; the two legacy writers refuse and leave slot A
untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Publisher: the reset publication mode of the single publisher (a new
nonzero nonce, an empty cursor space, ordinary rules otherwise), ported
onto the row 7 publication core; step 2 into one slot, step 3 into the
other, a step-3 failure latches.
Store: WALStore.resetIncarnationV3 quiesces (captureMu exclusive ->
lifecycleMu -> syncMu -> s.mu), refuses with ErrResetNotPreserved and no
write unless the dirty map is empty and CheckpointLSN >= appended ==
acknowledged W, publishes both slots under a fresh random nonce at cursor
0, recreates the WAL writer, bumps the recovery generation and
invalidates the map proof epoch. An open across a half-published reset
binds no writer; Recover's head publication completes the other slot and
creates it.
Not TLC-cleared: nothing in production calls it until the reset model
(r4.5) passes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A v3 checkpoint never exceeds W (DESIGN 2.2 item 5, 9.1 predicate 2:
CheckpointLSN <= mapCoveredCheckpoint <= W). The flusher may flush dirty
entries no Sync has acknowledged, so persistCheckpointV3 now clamps its
candidate to the acknowledged W; the unsynced records stay retained in the
WAL until a Sync covers them. (Raised by claude05's CkptUnsynced model
note; Claude01 ruled the v3 rule is CheckpointLSN <= W.)
The map candidate is prepared first, outside every lock, for the clamped
checkpoint. The publication is a W publisher, so it runs under the v3
leader role (syncMu -> s.mu -> descMu), like Sync, refreshW and SetWMode,
and cannot straddle a recovery; if a recovery lowered the acknowledged W
below the prepared candidate meanwhile, the cycle publishes nothing.
Control: an acknowledged LSN 1 and an unsynced dirty LSN 2 through a
flusher cycle (stub map candidate) give checkpoint = covered = 1, the tail
unchanged, and both LBAs readable after a crash.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 5d review (3e76473c, AMEND): the start-only recovery epoch
did not cover a capture during recovery (schedule A), a batch recovered
between its publication and its ACK (schedule B), or the outer Sync()
completion. Structural seam per Claude01, replacing the epoch checks.
Lock graph: captureMu -> lifecycleMu -> syncMu (v3 leader) -> s.mu ->
descMu -> fileSyncMu. Checked first: no Recover caller holds s.mu or
descMu (durable.Recover, sparrow persist and tests call it from outside),
and no publisher takes syncMu while holding s.mu (committer goroutine,
flusher after dropping its read lock, SetWMode after Sync).
- Recover (v3) holds syncMu for its whole run, after lifecycleMu and
before s.mu, and bumps recoverGen under syncMu and s.mu.
- The Sync batch (capture -> publish -> final ACK), refreshW and SetWMode
hold syncMu throughout, so no publication or ACK straddles a recovery;
the per-publication epoch checks are removed.
- The outer Sync() completion, which cannot hold syncMu across its
committer wait, captures recoverGen with targetHead under s.mu.RLock
and rechecks it under syncMu -> s.mu at completion; a moved generation
refuses the ack (errV3RecoveredMeanwhile).
- Held controls: refresh during a held Recover (A); Recover during a batch
held before its ACK (B); the outer completion across a recovery, with a
fresh-lifetime positive. heldV3 releases the hold and joins every worker
with a bound in cleanup, before the store crash cleanup.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 5c review (87a922fa, AMEND). Lock graph first, unchanged:
syncMu (v3 leader) -> s.mu -> descMu -> fileSyncMu; Recover holds
s.mu -> descMu -> fileSyncMu and never takes syncMu. No edge is added.
- P1: a flusher refresh could read Wack 2 and pause while a same-open
Recover dropped record 2 and reset Wack to 1; the resumed refresh then
published W 2 and the next Recover reported a false wal_corrupt. Every
recovery now bumps a recovery epoch first thing (under s.mu, before it
reads the descriptor). Every publication of a W derived from cached
wack/appended values (Sync batch, refreshW, SetWMode) captures the epoch
with them and rechecks it inside its publication mutate, under descMu: a
superseded publication is dropped (errV3RecoveredMeanwhile; the refresh
treats it as nothing to do). A publication that wins the race completes
before the recovery reads the descriptor, so its W is genuine.
Held real-flusher control: the refresh caches W 2 and parks, the same
instance recovers to R 1, the refresh resumes and publishes nothing, and
the next Recover succeeds.
- P2: held tests register the store crash with t.Cleanup before the
release cleanup, so a failure releases the hold before shutdown.
- P2: the empty-dirty-set refresh branch has its own control.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 5b review (b8950a26, AMEND):
- P1: recoverV3 sets the volatile acknowledged W to the recovered prefix
R instead of keeping an older in-memory maximum. A same-open recovery
that drops mode C's newest batch could otherwise let refreshW publish a
W the WAL no longer holds, and the next Recover report a false
wal_corrupt. Control: same-instance Recover -> refresh -> Recover with
the exact kept and fenced bytes.
- P2: a scan error under an installing descriptor keeps the typed
ErrBaseIncomplete outcome (cause preserved, not labelled damaged).
- P2: the real flusher cycle runs the mode-C idle refresh, also when no
dirty entries remain. Control drives flushOnceInternal (no timing oracle).
- P2: the held controls use bounded handshakes and register their release
as test cleanup before the held goroutine starts.
- Row 7 handoff: Read's post-OnReadMiss dirty-map recheck dispatches to
the v3 WAL reader.
The LSN-order dependency is closed by codex03's writer enforcement
(2f201a5a..f0fd2916) and DESIGN r16.1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Integration seam ruling (Claude01, hub 10:22Z): v3 lives inside the real
*WALStore with version-dispatched internals, selected only through a
test-only create/open; production Create/Open stay v2 until row 12b.
The parallel walStoreV3 type from row 5 is removed; its logic is now the
store's v3 internals.
- walstore.go: a v3 field, set before the committer and flusher start
(openInitializedInternal init hook). Dispatch at the v2-coupled points:
Write appends through walWriterV3 with DurableLSN = Wack; Read uses the
v3 record layout; Recover runs recoverV3 (R < W*, replay <= R into the
dirty map, the exact fence, head = E, writer restored to E);
syncWALBatch runs the C/A modes through the row-3 publisher under the
v3 leader role; persistCheckpointReleasing publishes through it.
WriteBatch, ApplyEntry, WriteExtentDirect refuse (errV3NotYet) and
AdvanceFrontier is a no-op on v3 until their rows.
- flusher.go: readDirtyRecord decodes and validates v3 records.
- The v3 checkpoint/tail publication takes a map candidate hook for row
7; without it the checkpoint and tail do not move (no fabricated
coverage; the WAL stays retained).
codex01 row 5 review (40b7614f, AMEND):
- P1: the batch acknowledgement rechecks the store fault under s.mu
before advancing Wack, closing the window where a queued append latches
after the publisher's check. Held control in both modes.
- P1 (LSN order): recovery keeps the physical-prefix rule, which DESIGN
r16 makes canonical (the WAL is LSN-strictly-increasing); a
contradictory chain while installing is wrapped as ErrBaseIncomplete.
The ErrWALLSNOrder writer refusal is codex03's row-4 change.
- P2: fence ranges use interval length, never floor+WALSize; a history
ending at the last representable cursor recovers.
- P2: SetWMode evidence: a held C batch acks under C before the mode
changes; no batch acks under a stale mode; crash cases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r15 sections 6.1 to 6.6 (f2122d66), PLAN row 5 (b870a569). Dark:
the only constructor is createWALStoreV3ForTest; the v2 path is unchanged.
- recovery_v3.go (pure): scan start max(BaseCursor, retainedTail) (G2),
floor F, contiguous prefix R and its end E over the row-4 trusted chain,
the R < W* decision (wal_corrupt when serving; ErrBaseIncomplete, plus
ErrInstallSuffixDamaged and WALIntegrity when damaged, while installing),
and the exact fence ranges over [E, floor+WALSize), split at the wrap.
- walstore_v3.go: open selects a slot, scans (row 4), decides, replays the
records <= R last-writer-wins, fences and fsyncs the exact ranges through
the leaf, publishes retainedHead = E, restores the writer to E, and only
then admits. Sync mode C publishes the previous batch's W, so one fsync
covers WAL and slot; mode A fsyncs the WAL, then publishes W = H.
refreshW, and SetWMode under the group-commit leader role, publish
W = Wack. An append pwrite error latches the store-global fault.
- Tests: I1 across reopen in both modes; the C window (newest batch
truncated in C, wal_corrupt in A; second-newest wal_corrupt in both);
refresh and SetWMode(A) close it; a torn unsynced tail is never corrupt;
the G1 resurrection schedule (and its no-fence counterexample); a
byte-exact fence at an unaligned E; the append write-error latch.
- invariants.md: INV-WAL-V3-W-001 and INV-WAL-V3-FENCE-001 (STUB).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 3 round 2 (092784eb, AMEND, one P1): the store fault for a
slot write error was latched after syncFile released fileSyncMu, so an
independent store Sync queued on fileSyncMu could fsync and acknowledge
through the uncertain slot. The write callback now latches before it
returns, inside the leaf. Control: a store Sync queued behind a failing
full or partial slot write is refused without fsync, with the harness
running it right after the unlock and before the publisher resumes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pushes to main and PRs from branches in this repository now run the
test job on the self-hosted tp04 runner (label tp04-seaweed-block).
PRs from forks keep running on ubuntu-latest, so code from outside the
repository never executes on our machine. The job name stays
"go test (linux)", so the required check is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01 row 3 review (c9790ac4, AMEND):
- P1: a slot pwrite error (full or partial), like an fsync error, now
latches a publisher failure (ErrDescriptorPublishUncertain) and the store
fault through descriptorIOV3.latch, retains the uncertain candidate, and
refuses every further publication, rollover and reuse with no further
I/O until reopen reads the slots back (DESIGN 5 failure rule). The v2
syncFile leaf is unchanged.
- P2: publication-side counter checks return ErrCounterExhausted before
any write; installed -> installing is refused (not an 8.5 edge).
- Tests: full and partial slot write then error (refusals, no further
writes, no reuse, store fault latched, reopen selects the previous gen
after a torn write and the new gen after a complete one); counter
exhaustion for W, checkpoint, head and map generation; the extra edge.
- invariants.md: INV-WAL-V3-PUBLISH-001 statement and tests updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r15 sections 4, 5 and 5.1 (f2122d66), PLAN row 3 (b870a569).
Dark: used by no production path yet; the v2 checkpoint path is
unchanged (retired in row 14a). Wiring into the v3 store follows rows 4/5.
- descriptor_v3.go: publish takes WALStore.mu (snapshot only) then descMu,
releases the store lock before slot I/O, and writes the fallback slot
with slotGen+1 through the syncFile leaf. It rebases onto the
authoritative descriptor, max-merges W and the checkpoint, refuses
identity/geometry/nonce changes, tail regression, map root changes
without a higher generation and BASE edges outside 8.5, validates the
whole slot, and rechecks the sticky fault at the success boundary.
reuseFloor is min of both tails within one nonce (none across nonces);
rolloverIfPinned republishes unchanged when the fallback pins reuse.
- Tests: alternation and reopen selection, monotonic merge, 40 concurrent
publishers, a lock-order recorder, sticky fsync and success-boundary
refusals, full-ring rollover and its failure, mixed nonces, BASE edges.
- invariants.md: INV-WAL-V3-PUBLISH-001 (STUB until activation).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DESIGN r15 section 2 (f2122d66), PLAN row 1 (b870a569). Dark: no
production open or create path reaches the v3 codec until activation
(row 12b); v2 superblock.go is unchanged.
- superblock_v3.go: 4096-byte slots A@0/B@4096, WAL at 8192; CRC32C
(Castagnoli) over [0,4092); reserved bytes, flags, impl acceptance,
slotGen/nonce, checked geometry, BASE per-state rules (installed may
have BaseCursor below retainedTail, r15), WMode, MigrationPhase, and the
slot-local map coverage CheckpointLSN <= C <= W. Selection: the valid
selectable slot with the higher slotGen; a prepared slot is never
selected (ErrMigrationIncomplete when it is the only one); equal
generation with different bytes or identity/geometry mismatch refuse.
Counters stop at 2^64-2 (ErrCounterExhausted).
- Tests decode 25 vectors from an independent stdlib generator with its
own CRC32C (testdata/format_v3/slot), re-encode the positives
byte-exact, and cover selection, exhaustion and the r15 installed rule.
- invariants.md: INV-WAL-V3-DESCRIPTOR-001 (STUB until activation).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Known frontier: durable >= required. Unknown frontier under a quorum
profile: promote only with P-K+1 fresh ready peers in the same tick.
Limits: no frontier source (#192) and no primary lease (#195).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The same-tick probes are snapshots, not a fence: the rule covers the
acknowledgements their sampled frontiers represent, not one the old
primary gives after the sample.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Publisher checked IntentBind against the (volume, replica) key only,
so Bind(v,r1) then Bind(v,r2) published two epoch-1 lines for one
volume. After a restart the file store reloads only the current slot,
so a Bind for an earlier slot was accepted the same way.
A Bind is now refused with ErrBindAlreadyBound when any slot of the
volume already holds an authority line. Moving to another slot stays
IntentReassign. Same-key double Bind and Bind of a fresh volume are
unchanged.
Fixes#183.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A new peer starts Healthy and Unknown is only set by Close, after which
Invalidate returns early.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Invalidate stored Degraded directly, so a NeedsRebuild peer could be
invalidated to Degraded and then set Healthy, escaping the terminal
state. Invalidate now checks replicaStateTransitionAllowed like
SetState: from NeedsRebuild the state is kept and the reason is still
logged; every other state still moves to Degraded.
Fixes#182.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
State the survivor rule for an unknown required frontier in the design
doc and keep the missing acknowledged-frontier source as a known gap.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Known frontier covered/behind, known zero, unknown with all, some or
stale survivors, sync_all, best_effort, provider knownness, observation
freshness, and RF2 not consulting the gate.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The boot-grace and recovery-watchdog tests fail over to r2 while r3 is
silent. With an unknown frontier that promotion is no longer provable
(#181), so their fixtures now state a known required frontier that r2
covers. Their assertions are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An unknown required acknowledgement frontier was read as zero, so the
highest durable ready candidate was promoted even when only some peers
were seen; an acknowledged write could live only on an unseen peer.
The probe result now says whether the required frontier is known. With a
known frontier the candidate must cover it, as before. With an unknown
frontier under a quorum ack profile, the highest durable candidate is
promoted only when enough peers are probed ready and fresh to intersect
every acknowledgement quorum (peerCount-K+1, K from waitForSyncAcks):
RF3 sync_quorum needs both peers, sync_all needs one. Otherwise nothing
is promoted. best_effort is unchanged.
Fixes#181.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent-workspace-design.md (measured results) adds the post-#173 guest fsync
medians; block-design.md's known-issues entry says #173 removed the idle
group-commit wait (about 5.5 ms to 3.23 ms against 2.74 ms local) and keeps
the remaining lead (the checkpoint superblock fsync under the store lock).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The backend Sync figure is the mean over the gate window, and the gate that
every guest fsync reaches the backend sync ran on the four Seaweed Block
setups (not on the local disk).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up:
- INV-WAL-SYNC-FRONTIER-001: Sync never reports an uncovered write durable;
it returns the global synced frontier, at or above the caller's own write,
covered by a completed fsync (TestWALGenerationFirstCallerReturnOrdering).
- INV-AUTH-PERSIST-BEFORE-PUBLISH-001 and the M2 row: store-backed only; a
failed write publishes nothing but its outcome may be unknown, and the
workspace path latches that uncertainty.
- INV-FE-LINEAGE-GATE-001: the volume-ID facet is marked as code reading.
- INV-CUT-READMISS-001, the M4 row and agent-workspace-design.md: a HEAD
fill never overwrites a newer local extent version; a WAL-only write wins
on reads.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each gap noted in docs/design/invariants.md is now confirmed by a red test
and tracked as an open issue: #181 (RF=3 promotion admitted with required
LSN zero), #182 (Invalidate bypasses the NeedsRebuild terminal state) and
#183 (a genesis Bind for a second slot of a bound volume).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The README, the agent-workspace diagram and docs/workspace-measurements.md
still said guest fsync was about 7 ms against 3 ms local. A rerun after #173
(same lab pack and host, the same four setups, fio 4 KiB random write one at
a time with fsync after every write, median of 3 boots) measured a median of
3.23 ms (ublk, walstore-chunk) against 2.74 ms local. The original runs stay
as history in docs/workspace-measurements.md.
Documentation only; no code changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/design/invariants.md lists the six state machines Seaweed Block
implements (walstore, authority, replica role and peer, workspace HEAD
holder and takeover, the cut pipeline, the chunk lifecycle) with each
transition's guard and enforcing function, and a 71-row invariant ledger
(69 ACTIVE, 2 STUB): statement, machine and transition, enforcement, tests,
TLA+ property and status. AGENTS.md gets a 'Protocol contract' section, and
the three design docs and the README link the new doc.
Documentation only; no code changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockNodes is a top-level list and frontendNetworkClass is a per-node
field; the snippet nested blockNodes under network and put
frontendNetworkClass beside it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
nvme-rdma-capability-boundary.md and nvme-tcp-supported-lab.md recorded the
lab's private addresses. Replace them with documentation addresses
(192.0.2.12 internal, 198.51.100.11/12 frontend, matching the chart's
example nodes) and say so at the top of each record. Host names stay
anonymized as 'lab host A/B'; meaning is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The chart README carried a full values example with lab node names and
addresses, and values.yaml defaulted blockNodes to a lab host name.
- charts/seaweed-block/examples/values-3node.yaml: the README's values
example as a file, with nodes node-a/node-b/node-c and RFC 5737
documentation addresses (192.0.2.x internal, 198.51.100.x frontend).
- README: links the example instead of inlining it; the NVMe/RDMA snippet
uses the same placeholder node and addresses.
- values.yaml: the default block node is the placeholder block-node-1
(internalIP stays 127.0.0.1) with a pointer to the example.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Delete the stale roadmap and eight wiki planning pages (git history keeps
them); move the only unique content (Phase 166-170 write-path experiment
results) into docs/releases/nvme-tcp-supported-lab.md.
- Simplify the remaining user docs; duplicated non-claim lists link to
docs/kubernetes-status.md; lab host names and local paths are removed.
- Split docs/design/block-design.md into core, agent-workspace-design.md and
kubernetes-block-design.md; add four SVG diagrams of the on-disk and remote
structures and new mermaid diagrams.
- mkdocs.yml nav and README links follow the new layout; the two gate
scripts drop the one check each that read a deleted file.
Docs only; no product code changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The README is rewritten to about 230 lines. Detail that used to live in the
README moves to linked documents:
- docs/standalone-deployment.md: running blockmaster and blockvolume
without Kubernetes, with a read-only first-volume check and a separate
write test for scratch hosts.
- docs/kubernetes-status.md: the Kubernetes alpha feature status and
non-claims.
- docs/workspace-measurements.md: the agent workspace measurements.
- deploy/config and deploy/systemd: env files, a topology example and
systemd units for blockmaster and blockvolume (plus a ublk variant).
docs/quickstart-kubernetes.md and docs/design/block-design.md are updated
to match current main (auto durable-impl default, fuzz targets, the
concurrent filer CAS test, the CI workflow, the TLA+ specs in docs/spec),
and docs/assets/seaweed-block-hero.svg is refreshed.
Docs and example configuration only; no code changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of b264c233 (test P2): when startWorker's bounded join timed out it
reported an error and then let the store's Close run under the still-live
worker, which could block on the worker's locks. On a join timeout it now
fails the test with every goroutine's stack and marks the store leaked;
heldStore's cleanup then leaves that store open instead of closing it.
TestWALStoreStartWorkerReportsAWorkerThatNeverSettles drives startWorker
through a recorder with a short join bound and a worker that never
returns: the cleanup ends within the bound with one error carrying the
goroutine dump, and the store is marked leaked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of 1af91e6a (two test P2):
- Every worker goroutine of the held-caller tests runs through
startWorker, whose cleanup (ordered before the store's Close) opens the
test's gates and joins the worker within a bound, so a test that stops
early never closes the store under a live flush or Sync.
TestWALStoreHeldWorkersSettleOnAFailurePath stops a test while a flush
is held inside the store and checks the worker finished before the store
was closed.
- The serialization oracle waits until the competing flusher reaches
syncFile (testBeforeFileSync, a nil-by-default hook just before
fileSyncMu) before checking that its extent fsync does not run while the
WAL fsync is in flight.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- FuzzDecodeManifestJSON: never panics; an accepted document decodes to
what encoding/json alone decodes.
- FuzzDecodeHeadDocument: never panics; a rejected document yields the
zero head; an accepted head re-encodes (headEntry) and decodes back,
also through decodeHead with the entry's extended attributes.
Known gap, pinned by a test: a segmented root rejected by validateRoot is
returned half-built with the error (no caller reads it).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- smartwal: decode never panics, a rejected slot is the zero record, an
accepted slot round-trips; slots with non-zero reserved bytes (covered by
the CRC but ignored) are pinned as a known gap.
- parallelwal: an accepted record re-encodes to exactly its bytes; every
encoded record decodes back; a CRC-valid header slot built from fuzz bytes
is rejected as the zero header or survives an encode/decode round trip.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Go native fuzz targets (seed corpus runs as unit tests):
- FuzzDecodeWALEntry: arbitrary bytes never panic; an error returns the
zero entry; an accepted record is self-consistent and re-encodes to
exactly its bytes.
- FuzzDecodeWALEntryFields: records with a valid CRC and EntrySize but
arbitrary fields, so the fuzzer reaches the decoder's acceptance rules.
- FuzzWALEntryRoundTrip: every entry the encoder accepts decodes back.
Shapes the decoder accepts but the encoder never writes (empty write,
batch shape, barrier with a Length, unknown type) and entries the encoder
accepts that do not decode back (unknown type, inconsistent padding) are
pinned as known gaps (knownWALDecodeGap, knownWALEncodeGap); any other
shape fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A workspace that moved A -> B -> A reattached A's surviving local root as
an existing volume without claiming HEAD: it served A's stale image and its
next (hash-mode) cut overwrote B's acknowledged, synced and published
writes. A non-fresh attach now reads HEAD first; if another holder
published it (Gen != 0, Holder != this holder), the attach fails closed
with ErrChunkStaleLocalRoot wrapping storage.ErrChunkLayerFenced: the
volume is not served and the attach is not retried. One log line and the
status evidence name the volume, the local root, HEAD's holder, generation
and epoch, and say to remove or quarantine the root; the next attach then
starts fresh from HEAD. The deferred (authority-wait) attach records the
same evidence. Recreating the root automatically is a follow-up.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Move-back tests for the chunk provider. The existing local root of a
workspace that moved A -> B -> A must not attach: no reads or writes, no
cut, HEAD unchanged, a typed ErrChunkStaleLocalRoot (fenced) and status
evidence that says to remove or quarantine the root, also when the attach
is deferred until the assignment arrives. After the root is removed the
fresh path serves B's image. Controls that pass today: a same-holder
reattach at a newer epoch, an existing root with no HEAD, and a holder whose
HEAD a newer epoch took over never cuts over it.
ErrChunkStaleLocalRoot is declared so the tests build; nothing returns it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A workspace moves A -> B -> A and A's old durable root is still on disk.
A attaches it as an existing (non-fresh) volume, so it never claims HEAD:
it serves its own stale image instead of B's published writes, and its
next cut (hash mode) overwrites B's acknowledged, synced and published
data in HEAD.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
walstore-chunk volumes share walstore's on-disk format (SWBK), and on a
fresh host their published bytes may exist only in the remote HEAD. Opened
by auto as plain walstore, such a root would skip chunk recovery, install no
read-miss or fencing hooks and serve the local, absent extent.
Auto now refuses any volume whose root carries chunk metadata
(<volume>.chunk*: fresh marker, dirty bitmap and deltas, presence map),
on both the open and the create path, with ErrImplKindMismatch naming the
files and asking for --durable-impl=walstore-chunk with its remote
configuration. Nothing is deleted or converted.
Tests: a lazy fresh-host chunk root (block published on host A, host B
attached and closed before fetching it) is refused by auto and read
exactly by the explicit walstore-chunk selector; any chunk root is
refused; a stray fresh marker without a volume file is refused and left
in place. autoProvider registers its cleanup (review P3).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two controls that each isolate one part of the fix:
- TestWALStoreExtentFsyncFaultAfterThePublicationCheck: a direct-frontier
Sync is in its metadata barrier, past every earlier check, when the
flusher's extent fsync fails; only the fault check at the publication's
own superblock fsync (syncFile) refuses it.
- TestWALStoreFsyncsOfTheFileAreSerialized: an extent fsync waits for a
WAL fsync of the same file in flight (fileSyncMu).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fault check under the store lock did not share a boundary with the
latching: the flusher's extent fsync (and a WAL fsync) latch without the
store lock, so a publication could pass the check, wait in its metadata
barrier, and still publish after another path's fsync failed.
Every fsync of the store's file (WAL batch, flusher extent, checkpoint,
recovered bounds, direct frontier, frontier seed) now runs through
syncFile under one leaf mutex, fileSyncMu: it is refused if a fault is
latched, and a failure latches the fault before the mutex is released.
Superblock publications run their pwrite and fsync together under it, so
a refused publication does not even dirty the superblock; a pwrite
failure still returns without latching. Nothing is acquired under
fileSyncMu (callers may hold the store lock), so it adds no lock-order
edge beyond store lock -> fileSyncMu.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of 45efc13c: the fault check under the store lock is not a boundary
shared with fault latching, so a fault from another path can land after a
publication passed it.
- An extent fsync held by the flusher fails while a direct-frontier Sync is
in its metadata barrier: the Sync still publishes the frontier.
- A WAL fsync fails while the flusher's checkpoint is in its metadata
barrier: the checkpoint is still published.
The held-caller tests now release their gates and bound every wait before
the store closes, and each queued writer path is its own subtest that
acknowledges, through a test hook placed after the entry checks and before
the append lock (testAfterAdmit, nil in production), that it was admitted
before the fault. The reopened seed handle closes on a failure.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Match blockvolume's auto default (new volumes are walstore, an existing
volume opens with its on-disk format): §1.3 lists smartwal's open issues
and says it is not a default; the open-items entry no longer says the
standalone default is smartwal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
--durable-impl now defaults to empty (auto). A new volume is created as
walstore. An existing volume opens with the implementation its on-disk
superblock names, so volumes created under the old smartwal default keep
opening (no ImplKindMismatch on upgrade). An explicit selector keeps the
exact ErrImplKindMismatch refusal, and an unrecognized on-disk format is
still refused.
- core/frontend/durable: ImplAuto (the zero value) is resolved per volume
in openOrCreate; openExisting/createFresh take the resolved
implementation, and each volume handle records it, so DurableStatuses
reports the on-disk implementation. ImplSmartWAL is documented as
experimental; the 'production default' comments are removed.
- cmd/blockvolume: --durable-impl default '' with help text 'auto';
smartwal (experimental). The walstore-only options still require an
explicit --durable-impl=walstore.
- README: smartwal listed under 'Not claimed yet' with its open issues.
Tests: auto creates walstore; auto opens existing smartwal, walstore and
parallel-walstore volumes by their on-disk format; auto refuses an
unrecognized file; the flag default is empty; explicit values accepted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A Sync queued behind a failing fsync, and writers waiting for the store
lock behind a failing append, passed the entry check before the fault was
latched. The latch is now checked where they commit:
- syncWALBatch, before its dedup return and before any fsync, so a batch
queued behind a failed fsync neither fsyncs again nor reports success;
- Sync, under the store lock before it publishes a frontier (covering a
deduplicated Sync and a fault latched by a flusher fsync);
- Write, WriteBatch (including the multi-block path) and ApplyEntry,
under the append lock before allocating LSNs or touching the WAL;
- persistCheckpoint, under the store lock.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of 8f56445f (two P1, two P2):
- A Sync queued behind an fsync that then fails is acknowledged by the
next fsync of the batch run (syncWALBatch does not check the latch).
- Write, WriteBatch and ApplyEntry waiting for the store lock while an
append fails are admitted on their stale entry check and reuse its
LSNs and offsets.
- The direct-frontier test now recovers before advancing, asserts a
reconstructed nonzero head, and checks the frontier after a crash.
- The frontier seed test checks the reseed after a crash and reopen.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A batch append whose pwrite left its records on disk and then failed kept
nextLSN and the head, so the next write reused the batch's first LSN and
offset; the batch's later record survived past it, and after that write's
acknowledged Sync and a crash recovery replayed the stale record over it.
An append that fails while writing (marked errWALPwrite by the WAL writer:
the record or padding pwrite, single or batch) now latches the store's
I/O fault as ErrAppendFailed, wrapped in a SubstrateIO RecoveryFailure
(io_error), on the same latch as a failed fsync. Until the store is
reopened it refuses further appends and Syncs, so no LSN or offset is
reused. Space and encoding refusals, which write nothing, do not latch. A
reopen may replay the failed, never-acknowledged records.
Tests that continued on the same open store after a failed append now
assert the refusal and a reopen; the two chunk-layer tests that used a
failed append only to leave a newer record for a same-open Recover now
write that record past the head directly.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A failed append (single or batch) must make the open store refuse further
appends and Syncs with a typed SubstrateIO failure (ErrAppendFailed) until
a reopen, so no LSN is reused. A reopen may replay the failed,
never-acknowledged records; a write acknowledged after the reopen survives
the next crash.
ErrAppendFailed is declared so the test builds; nothing returns it yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A batch append whose pwrite lands every record and then reports an error
leaves nextLSN and the head unchanged. The next write reuses the batch's
first LSN and offset; the batch's second record (a higher LSN) stays past
it. After that write's Sync is acknowledged and the process crashes,
recovery republishes the failed batch's stale record over the acked write.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The WAL and the extent share one file, and on Linux a failed fsync may
already have dropped dirty pages of that file, so a later successful fsync
proves nothing about them (the fsyncgate pattern). The first failure of
any fsync on the file (WAL batch, flusher extent, checkpoint, recovered
bounds, direct frontier, frontier seed) now latches ErrFsyncFailed,
wrapped in a SubstrateIO RecoveryFailure (io_error). Until the store is
reopened: Sync refuses without another fsync, writes, batch writes,
ApplyEntry and WriteExtentDirect refuse, the flusher advances no
checkpoint, Recover and the frontier seed refuse, and Close writes no
final superblock. A reopen recovers from what is on disk.
Tests that asserted a same-instance retry after an injected fsync failure
now assert the sticky refusal and a reopen: the generation sync tests, the
checkpoint and direct-frontier metadata tests, the frontier seed test, the
recovered-bounds test and the two restore seed tests (whose real EINVAL
fsync now requires a reopen before the restore succeeds).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/spec/ holds 12 TLA+ models of the block protocols with their TLC
configurations (cfg/, 199 files: designs, RED configs that remove one guard
and must produce a counterexample, and reachability witnesses), run.sh to
check one configuration, and a README: how to run TLC, one row per spec
(invariants, results, the code it maps to), limits, the findings that led
to #152, #156, #158 and #159, and the open model-level items.
Docs only; nothing runs in CI.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After a failed fsync the open store acknowledges the next Sync once a
later fsync succeeds, although the kernel may already have dropped the
dirty pages (the fsyncgate pattern). These tests fail a WAL fsync, the
flusher's extent fsync and a checkpoint superblock fsync, then require:
no further Sync ack (and no fsync retry), no write, no checkpoint advance,
a typed SubstrateIO failure (ErrFsyncFailed), and a reopen that recovers
the data acknowledged before the fault.
Scaffolding only: ErrFsyncFailed is declared (nothing returns it) and the
flusher's extent fsync goes through a syncExtentFile seam (= f.Sync).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- .github/workflows/test.yml, job 'go test (linux)': on pull_request and on
push to main; Go from go.mod; go build ./..., go vet ./..., and
go test -short -count=1 -timeout 10m ./... with CGO_ENABLED=0. Actions are
pinned by commit SHA, permissions are contents: read, and a new push to a
PR cancels the older run.
- core/ops/surface_test.go: fix the two go vet warnings (resp used before
the error check), so vet covers the whole module.
- cmd/blockvolume: a withdrawn port no longer has to answer ECONNREFUSED.
A successful connect still fails; any other dial error passes only if the
address can be bound again.
- core/host/volume: probe tests dial a listener they opened and closed,
not the fixed 127.0.0.1:1.
- core/replication/component: on failure, the G5-5C and G9A catch-up tests
log frontiers, peer status and the engine trace. Assertions and timeouts
are unchanged.
Test files and the workflow only; no product code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/design/block-design.md describes the current design of the block
service: the data path and WAL, replication and recovery, the chunk
snapshot/fork/GC control plane, and the frontends. Each claim names the
source file and the test that pins it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comments in source and tests named individual reviewers and carried the
time a decision was taken (for example "(name's ruling, 06:47Z)"). Those
are review bookkeeping, not design rationale. Remove the names and the
dates/timestamps; keep the rationale, issue and PR references (#51, #82,
#83, #142, #159) and spec section references as plain text.
Comment-only: no code, test logic or string literal changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The snapshot, fork and parallel-upload cut numbers come from a host-side
proxy (chunks as local files, a deterministic filer metadata model; no
network, guest fsync or block frontend), not from the Firecracker runs. Say
so in the section intro, the table caption, the cut sentence and the image
footer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds an 'Agent workspace disks' section: a local-speed disk per agent microVM,
incremental chunk snapshots to SeaweedFS, cheap snapshot/fork, host moves with
fenced HEAD takeover, measured workspace workloads and snapshot/fork cost, the
sw-block ops chunk lifecycle commands, correctness work and what is not claimed
yet. Adds the overview image docs/assets/seaweed-block-agent-workspace.svg.
The Kubernetes alpha content is unchanged apart from heading levels and the
status table title.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01's #159 P2-S2 and P2-S3 (tests only):
- TestWALWriterBatchReuseIsBoundedByTheDurableTail: the batch planner,
with a padding wrap, is refused while a release is in memory only or the
recovered bounds are pending (no head move, no padding written), and
accepted once the tail is persisted.
- TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry: a
failing superblock write or fsync fails Recover and admits no Write; a
same-instance Recover retry persists the bounds; a later Write, Sync and
reopen keep the exact bytes.
Mutation controls (WSL): reverting only the batch planner's durable-tail
check fails the batch test alone; publishing the tail before Recover's
persist, or dropping the pending flag, fails its own control.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01's AMEND on 980de2b9 (tests-only P2): the helper opened a full
WALStore and only stopped its committer and closed its fd, leaving the
flusher and ticker alive. Read the superblock with a scoped file read
(readSuperblock), and register the original store's cleanup right after
open so a Fatal before the crash step still closes it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's condition (1) for any prefix-cut recovery rule (2026-11-16
07:33Z). A rebuild installs BASE by WriteExtentDirect (no LSN) and applies
WAL-lane entries with their real LSNs by ApplyEntry; AdvanceFrontier runs
only at MarkBaseComplete and is in memory until a Sync. So a store can hold
synced LSN 101-102 with a persisted checkpoint of 0 and no LSN 1..100.
Recovery keeps them; a rule replaying only the contiguous LSN prefix above
the checkpoint would keep none. This pins that, so no such rule lands.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A full checkpoint persists head == tail (88fbb345 persists the released
tail). Sync does not persist the head, so appends after it continue
contiguously from that position; recovery now scans [pos, end) then
[0, pos) from it. The footer high-run search stays only for the legacy
(0, 0) superblock. Scanning from offset 0 let a torn unsynced record
wrapped there hide every synced record after it.
Model check (claude05's WALRecovery.tla, rule rootLww = this writer and
scan plus #156's replay by LSN, K=4, 4 LSNs): crash-only I1 and I2 hold
(247,395 distinct states).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the released tail persisted (88fbb345), a full flush persists
head == tail. Sync does not persist the head, so synced appends follow it;
recovery's head==tail path ignores the persisted position and scans from
offset 0 when no high run is found, so a torn unsynced record wrapped to 0
hides every synced record after it (claude05's S3 trace shape).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's ruling on the S3 torn-wrap finding (2026-11-16 07:33Z), root
fix: the WAL writer may only overwrite bytes released by the PERSISTED
superblock tail, so a torn new record can never land inside the persisted
[tail, head) and hide a synced record behind it (crash only, no
corruption).
- walWriter.durableTail: the tail of the last fsynced superblock. The
space checks (append, appendBatch planning, admission pressure) count
from it; a release made only in memory frees nothing. Bounds rebuilt by
recovery are not reusable until persisted.
- The flusher's checkpoint persists the tail it releases (the old code
persisted the pre-advance tail and advanced after), with head and tail
taken from one writer snapshot. A flush whose checkpoint is already
covered (direct frontier) still persists its tail release.
- Recover persists the rebuilt head/tail before any append when they
differ from the on-disk superblock.
The replay-side defense (resync past a bad entry, replay by LSN up to
the first gap) is #156.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's ruling on the S3 torn-wrap finding (2026-11-16 07:33Z): the
writer may only overwrite bytes that the PERSISTED superblock tail has
released. On main the flusher persists the pre-advance tail and the
in-memory tail moves after it, and Recover moves the writer's bounds
without persisting them, so a torn new record can land inside the
persisted [tail, head) and hide a synced record behind it.
- flusher.afterSnapshotForTest: a test-only hook in the window after the
dirty-map snapshot (an append there is covered by the persisted head
but not by the checkpoint).
- TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords: the S3
trace, deterministic; crash only; synced LSN 2 is lost on main.
- TestWALStoreFlushPersistsTheReleasedTail, TestWALStoreRecoverPersists-
TheRecoveredBounds: the on-disk tail lags the writer's.
- TestWALWriterReuseIsBoundedByTheDurableTail: an in-memory release
makes its bytes reusable at once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's ruling (A), 2026-11-16 06:47Z: nothing about which records
replay, where replay stops, or whether the volume opens changes.
- walstore: recovery.go is main's replay again; the checkpoint+1
cutoff and the cross-range stop are gone. At a non-zero bad entry a
look-ahead finds whether a valid later entry (LSN above the highest
decoded so far) follows in the rest of its range or a later one; if
so the typed warning wal_hole_suspected is logged and counted. A
look-ahead read error is logged and changes nothing.
- smartwal: the positional mid-history fail-closed is gone (no
generation guessing). Populated slots whose record CRC fails are
skipped as before and reported as the counted warning (a torn tail
or a corrupted record; not distinguishable without a watermark).
ea1faf6a's data-CRC fail-closed stays as merged.
- the warning still reaches the durable status and /status and never
changes Healthy, readiness or promotion.
Cross-range detection, no replay past a hole, and any new fail-closed
move to the post-M4 watermark work. Last-writer-wins by LSN is #156.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01's review of f8d43653 (V:/share/rdma/codex01-block155-review-
20261116T0644Z/REVIEW.md) and claude05's ruling (A), 06:47Z. Against the
reviewed production code (its replay cutoff and positional smartwal
fail-closed; smartwal warning accessors stubbed so the tests build):
- a damaged STALE record in a released range drops retained, synced
LSN 3 (TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData);
- a torn smartwal slot accepted by one recovery becomes wal_corrupt
after a frontier jump and a new sync
(TestSmartWALTornSlotSurvivesAFrontierJump);
- a smartwal mid-history hole is an outage instead of a warning
(TestDurableStartup_Issue51_SmartWALHoleIsAWarningNotAnOutage);
- plus codex01's advisory: a healthy primary stays healthy with a
warning (TestStatusServer_StatusCarriesRecoveryWarnings..., which
passes either way: the plumbing never forced health).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's ruling (B), 2026-11-16 06:47Z. Recovery replay now uses
dirtyMap.putAtIfNewer: an entry replaces an LBA's dirty-map entry only
when its LSN is higher. Range scan order is physical, and a persisted
head/tail can predate a wrap, so a newer version can be scanned before
an older one. This changes only the order in which the replayed entries
take effect, never which entries are replayed; the runtime write paths
keep putAt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's ruling (B), 2026-11-16 06:47Z. On main, recovery applies
entries to the dirty map in physical range-scan order and putAt
replaces unconditionally. When the persisted head/tail predate a wrap,
the range scanned first can hold the newer version of an LBA and a
later range the older one: the older version wins, silently.
TestWALStoreRecoverLastWriterWinsAcrossScanOrder: LBA 20 written at the
high end (LSN 4), then rewritten by a batch that wraps to offset 0
(LSN 5); after recovery LBA 20 reads the LSN 4 bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Issue #51, claude05's rulings (2026-11-16 06:10Z, 06:14Z).
walstore (interim; no fail-closed: a plain power loss must never become
an outage):
- recovery decodes every range first and replays by LSN, not by scan
order (a persisted head/tail can predate a wrap). A non-zero bad entry
bounds the replay: its LSN is above its circular predecessor's, so
nothing at or above that bound is replayed in any range.
- a bad entry followed by any valid later entry is a suspected hole:
logged, counted (HolesSuspected) and reported as the typed warning
wal_hole_suspected (WALStore.RecoveryWarnings), surfaced in the
durable status and on /status without changing Healthy or readiness.
- trailing zeros still just end a range; a torn tail recovers silently.
smartwal: a corrupted committed slot (magic present, record CRC bad)
behind the highest valid LSN's slot is a mid-history hole: WAL
integrity failure (wal_corrupt). The slot right after it is the torn-
tail position and still recovers.
The durable synced watermark that tells a corrupted synced record from
an unsynced torn one is the post-M4 format change, not this.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's rulings (2026-11-16 06:10Z, 06:14Z). Controls with real
corrupted WALs, failing against stubs that restore today's behaviour:
walstore (interim: a power loss must never become an outage):
- (a) a corrupted mid-history synced entry: recovery succeeds to the
prefix, but no wal_hole_suspected warning, no count
(TestWALStoreRecoverWarnsOnMidHistoryHole);
- (c) the newer batch wrapped to offset 0 is replayed past a corrupted
older entry (TestWALStoreRecoverNoReplayPastAHoleAcrossWrappedRanges);
- the durable status and /status carry no warning
(TestDurableStartup_Issue51_WALStoreHoleIsAWarningNotAnOutage,
TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth).
- controls that pass either way: (b) an out-of-order unsynced tail
recovers, a torn tail recovers.
smartwal (fail closed on a mid-history hole):
- a corrupted committed slot with later valid records starts Ready
(TestDurableStartup_Issue51_SmartWALMidHistoryHoleIsWALCorrupt);
- controls: the issue's exact mutation is wal_corrupt (ea1faf6a), a
torn tail recovers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Fork's early replay of a completed request refuses (volume_deleted)
a target whose HEAD is deleting, purging or deleted, also before its
VOLUME is marked, like the later publication path.
- Host.ImportLifecycleVolume registers a cluster-spec volume under the
CreateVolume RPC's boundary (workspaceMu, reservation check through
the create); blockmaster startup uses it, skipping (and logging) a
reserved id, and the placement import skips reserved ids too.
Unreserved ids keep importing idempotently.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01's r4 review (V:/share/rdma/codex01-block152-r4-review-
20261116T0445Z/REVIEW.md). Controls failing against stubs:
- Fork's early replay reports success for a target past the delete mark
(deleting, purging, HEAD deleted before VOLUME is marked)
(TestCatalog_ForkReplayRefusesADeletingTarget);
- the cluster-spec import re-creates and places a reserved id after a
restart with the original spec (TestClusterSpecImportSkipsAReserved
Volume).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's cut (04:08Z): volume-delete refuses with
volume_has_snapshots while the volume has any snapshot name record (a
published snapshot, one being deleted, or an attempt in flight); the
operator deletes snapshots first. The delete never touches snapshot
names, attempts or roots: the snapshot loop, the claim check and claim
release (a claim lives on a named snapshot; a deleted target's claim is
dead by rule), and CreateSnapshot's back-out are gone. CreateSnapshot
and Fork still refuse once they see the delete mark.
codex01's r3 P2s:
- the snapshot check, the revert and the commit are bound to one
deleting incarnation (its generation); if HEAD moved, the check runs
again on the incarnation found;
- the CLI's admission token is --request-id (required), so a rerun
adopts and can give back an earlier invocation's hold;
- CreateVolume holds workspaceMu through the create;
- the reservation store syncs its parent directory before use (the
binding store's helper).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's 04:08Z cut (no snapshot cascade) and codex01's r3 P2s
(V:/share/rdma/codex01-block152-r3-review-20261116T0405Z/REVIEW.md).
Controls failing against stubs:
- the cut: a volume with a snapshot, an in-flight snapshot attempt, or
a fork's snapshot is deleted (TestCatalog_DeleteVolumeRefusesWhile
SnapshotsExist, TestCatalog_InFlightSnapshotRefusesTheDelete, ...Fork
DuringTheDeleteMarkRefuses, ...TombstonesAndRefusesReuse);
- incarnation: a claim check under generation G commits a re-marked G'
(TestCatalog_DeleteCommitIsBoundToItsIncarnation);
- lost CLI token: a rerun cannot release the earlier hold
(TestOpsChunk_VolumeDelete, real master, restart);
- CreateVolume drops workspaceMu before the create
(TestMarkVolumeDeleting_CreateHoldsTheReservationLock);
- the reservation directory's parent is not synced
(TestDeletionReservations_ParentSyncBeforeUse).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Master: a deletion reservation store (core/lifecycle), separate from
the desired-volume records, so an unknown id is reserved too and the
ordinary DeleteVolume/CreateVolume path cannot clear it. Held by
per-delete tokens (admitted), permanent once committed. Writes reuse
the binding store's crash-safe pattern (synced temp file, atomic
rename, synced directory); an unknown outcome keeps a protective
change in memory (fail closed). MarkVolumeDeleting records it under
RecordWorkspaceDeletion's check; new AbortVolumeDeleting and
CommitVolumeDeleting. Every gate (publication admission, reconciler,
workload planner, binding/placement/move, CreateVolume) consults it.
VolumeRecord.Deleting is gone.
- Catalog: Admission is Admit/Commit/Abort; ErrNotAdmitted marks a
definite refusal, anything else is an unknown outcome
(admissionUncertain). Every give-back aborts this delete's admission.
A commit point (HEAD deleting -> purging, conditioned on the HEAD
read) precedes the irreversible steps; a revert races on the same
write, so a delete that sampled a claim cannot undo another delete's
commit, and reports an error instead of a give-back.
- CreateSnapshot's back-out settles its name like the delete does: the
name is freed only after the attempt's tombstone or winning
publication is confirmed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of dfc8f19 (codex01, V:/share/rdma/codex01-block152-r2-review-
20261116T0342Z/REVIEW.md). Controls failing against stubs restoring the
reviewed behaviour:
- P1: an unknown id's admission and a known record's ordinary
DeleteVolume leave CreateVolume free, also after a restart
(TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart).
- P2 persistence: the mark is intent-only (no write/sync); write,
rename and directory-sync faults and a restart lose it
(TestDeletionReservations_*).
- P2 rollback: a give-back (claim, held HEAD) leaves the master
exclusion in place; a lost admission response reads as a refusal
(TestCatalog_DeleteVolumeGivesBackOnALiveClaim, ...HeldAfterAdmission
GivesBack, ...LostAdmissionResponse, TestOpsChunk_VolumeDelete with a
real master: claim refusal must leave the id usable).
- P2 failed abort: B's failed tombstone write still frees the name, so
A's late publication survives a completed delete
(TestCatalog_FailedAbortCannotHideALatePublication).
- P2 concurrent deletes: D1's revert after D2 committed counts as a
give-back (TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(a) Admission at the master: LifecycleService.MarkVolumeDeleting holds
workspaceMu (every assignment, placement and binding write) and marks
VolumeRecord.Deleting inside RecordWorkspaceDeletion's check (refused
with live authority without a clean revocation ACK, a pending move or
a queued placement). Afterwards publication admission, the placement
reconciler, the workload planner, binding/placement/move RPCs and
CreateVolume refuse the volume.
(b) One HEAD write from the HEAD read (active or detached, not held) to
state deleting, chunks kept. Every read decides "held" afresh.
ChunkRemote.CASHead refuses to move a deleting or deleted HEAD
(ErrChunkHeadPrecondition + ErrChunkHeadDeleted), so no attach,
claim or restore revives it; EnsureVolume refuses it; Fork and
CreateSnapshot check the volume again after taking their claim/name
and back out.
(c) Claims read after (b): a live claim reverts HEAD (detached or
active, as before) and refuses with snapshot_claimed.
(d) Then every snapshot name, published or not (an unpublished attempt
gets an aborted tombstone), goes through markDeleting and is freed;
the fork claim is released and reported only when confirmed.
(e) HEAD becomes deleted (no chunks), VOLUME is marked deleted.
A failed delete reports what it did (admitted, headMarked, reverted,
snapshots, aborted attempts, claimReleased, completed, uncertain); the
CLI prints that with the error and exits nonzero. The CLI's admission
is MarkVolumeDeleting (QueryVolumeStatus is no longer used).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of 626c7de (codex01). One control per schedule, each failing
against a stub that restores the reviewed behaviour:
- P1 1: a holder that attaches before the HEAD mark's first read is
deleted (TestCatalog_DeleteVolumeRefusesAnAttachBeforeTheMark).
- P1 2: an attach that passed EnsureVolume revives a deleting/deleted
HEAD through CASHead (TestCatalog_DeletedHeadCannotBeRevivedByAClaim).
- P1 3: after the master's delete mark, an existing placement still
leads to an assignment, the reconciler places, the id can be created
and bound again (TestMarkVolumeDeleting_StopsLaterAssignment...).
- P2: a fork claim after the check is refused only after irreversible
writes (TestCatalog_DeleteVolumeGivesBackOnALiveClaim); a fork after
the mark installs (TestCatalog_ForkAfterTheDeleteMarkRefuses); a held
snapshot publication and a snapshot started after the mark escape the
delete (TestCatalog_DeleteVolumeCatchesInFlightSnapshots); a failed
claim removal is reported released, and the CLI drops partial effects
(TestCatalog_DeleteVolumeTombstonesAndReleases, TestOpsChunk_VolumeDelete).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Catalog.DeleteVolume refuses a volume in use (an active HEAD with a
holder, or the caller's InUseCheck: the CLI asks the blockmaster
whether it is assigned or served) with volume_in_use, and a volume
whose snapshot a live fork claims with snapshot_claimed, before any
write.
- Then: HEAD becomes a tombstone (state deleted, no chunks) by a
conditional write on the HEAD read, so an attach in between wins;
VOLUME is marked deleted; every snapshot goes through markDeleting
(the one mark path) and its name is freed; a fork's claim on its
parent is released. GC reclaims (the tombstone holds no roots; the
snapshots drop out after grace). A rerun finishes a partial delete.
- A deleted id is never reused: EnsureVolume (attach, create) refuses a
deleted VOLUME or HEAD with volume_deleted, and so does Fork for a
deleted target or source (the source checked after the claim).
- storage: HEAD state "deleted"; the HEAD decoder accepts it only with
no chunks, holder or detachedBy.
- CLI: sw-block ops chunk volume-delete <vol> --chunk-filer --master;
gc and volume-delete share masterEvidence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's item (2026-11-16 02:39Z): `sw-block ops chunk volume-delete`
plus Catalog.DeleteVolume. Controls, failing against a DeleteVolume
stub that deletes nothing:
- an attached volume (HEAD held) and one the blockmaster reports in use
are refused with volume_in_use, nothing written;
- a volume whose snapshot a live fork claims is refused with
snapshot_claimed, nothing written;
- fork w2 from s1, delete w2: HEAD tombstone (deleted, no chunks),
VOLUME deleted, snapshots freed; DeleteSnapshot s1 then succeeds; the
id is never attached, recreated or forked to again; an incomplete
fork's claim is released; a rerun replays;
- an attach between the check and the tombstone wins (held caller);
- the CLI needs a volume and --master and refuses an attached volume;
- real service + real GC: exactly the chunks only w2 and S1 reach are
reclaimed, w1's HEAD and S2 stay readable.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestC2_NoGapDenseLSNEdge asserted that a Realtime NotifyAppend at the
dense edge (cursor=10, head=11, lsn=11) emits EmitKindLive, while the
shipper's 2 ms timer drain was running. When a tick landed between
primary.Write and NotifyAppend, the timer shipped lsn 11 from substrate
first (EmitKindBacklog, debt-first per §6.3) and NotifyAppend took the
idempotent skip, so the test saw kind=1. That is correct product
behavior: the entry ships exactly once at the right LSN, and the kind
tag is observability only (WALKindBacklog vs WALKindSessionLive
counters; the LiveTail probe is marker-only).
- TestC2_NoGapDenseLSNEdge now disables the timer drain and drains the
initial backlog with DrainBacklog, so the Live assertion no longer
depends on scheduling.
- New TestC2_DenseLSNEdge_TimerWinsRace_ShipsOnce pins the other order
deterministically: the timer ships the new entry before NotifyAppend
arrives; NotifyAppend returns nil and does not emit again.
No product change, no timeout changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Conflict in cmd/sw-block/chunk.go resolved as the union: the usage
string lists cut|snapshot|snapshots|snapshot-delete|fork|detach|show|
gc|usage|retain, and the switch keeps #140's "gc" case with "usage"
and "retain".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up: the release was a t.Cleanup registered before Start, and
cleanups run LIFO, so the executor shutdown Start registers ran first; a
t.Fatal while the base frame was held would deadlock StopAndWait. A defer
inside the scenario runs before every t.Cleanup, including on t.Fatal.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dropForkClaim's write is conditioned on {state, claims} as read; a lost
condition re-reads a fresh copy, so delete metadata is never
overwritten. (With the shared mark path a delete also clears the dead
claim first, which changes the condition on its own.)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of 02d0631 (P2): dropForkClaim conditioned its write on the
claims only, so a completed fork's cleanup that read the parent, paused
while an explicit delete marked it, then wrote back its stale copy,
resurrecting an unnamed active snapshot. TestCatalog_ClaimCleanupNever
UndoesADelete fails against the old cleanup condition and the old
(claim-blind) delete mark, restored as stubs: state "active",
deleted_ns gone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
markDeleting is the only way an attempt is marked deleting: conditioned
on {state active, gen, no claims}, dead claims cleared first, a lost
condition decided again. Retain keeps a claimed snapshot (fork_held);
DeleteSnapshot refuses it with snapshot_claimed naming the fork
(claude05's ruling, 23:58Z).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's ruling (2026-11-15 23:58Z): an explicit DeleteSnapshot of
a snapshot an incomplete fork claims is refused with snapshot_claimed
(409, not retryable, naming the fork volume); a completed or aborted
fork no longer blocks. Controls, failing against the old mark (blind to
claims) restored as a stub: TestCatalog_DeleteRefusesAClaimedParent, the
409 mapping, the real-filer refusal in TestIntegration_RetainHeldSchedules,
and TestFork_IncompleteRetryBoundToOriginalImage, which now expects the
refusal and drops the claim (as a pre-claim fork) to keep testing the
image binding.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up. The pre-barrier hold proved in-session delivery and
convergence but no longer the test's point: a newer WAL write for an LBA must
win over an OLDER base frame for that LBA that arrives later.
Drop the production SetPreBarrierHook seam (core/recovery is back to main)
and hold the base lane instead, through the existing WithPrimaryStorageWrap:
staleBaseHold captures the base read of LBA 5 (old value A) and holds it; the
test pushes the same-LBA overwrites (the session cannot seal its recovery cut
while base is held, so they ship in-session: this is also what fixes the
flake), waits until the replica holds B at LBA 5, then releases the stale A
frame. Convergence requires LBA 5 == B: RebuildSession.ApplyBaseBlock must
skip a base frame for an LBA the WAL lane already applied (bitmap).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replaces the separate hold objects with one conditional write on the
parent attempt's own entry (codex01's design):
- Fork adds its claim (target/request) to the entry before using it,
conditioned on {state active, claims as read}; a deleting parent is
refused. It removes its claim once its HEAD exists (or a sweep's
tombstone settles the target).
- Retain marks deleting only conditioned on {state active, gen, no
claims}; a lost condition re-reads and decides again. Claims that
can never matter (target has a HEAD, or its VOLUME is another
request's) are cleared conditionally first; any other claim keeps the
snapshot, with no lifetime. No listing, so no paging.
- A dry run lists attempts a stopped pass left deleting, as apply
frees them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Controls for the four fork schedules of the second review, failing
against stubs where Fork writes no claim, the delete mark is not
conditioned on claims, and a dry run omits unfinished deleting
attempts:
- a fork claiming between retention's check and its mark (unit and
real filer);
- a fork that died before its VOLUME keeps the parent 30 days later;
- a refused same-target request leaves the first request's claim;
- a dry run lists the attempt a lost response left deleting.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestPillar3Slice2_EngineDriven_SameLBAArbitration was flaky (on main baca5fd,
-race -count=40: 25/40 failures at -cpu 1, 6/40 at -cpu 2, 1/40 at -cpu 4).
Root cause is a timing assumption in the test, not a product race: with a
12-LBA backlog, base copy and DrainBacklog finish in microseconds and
Sender.Run seals the recovery cut (SealBeforeBarrier) before the test pushes
its same-LBA overwrites. PushLiveWrite then returns ErrSinkBarrierSealed,
the documented 'retain the WAL entry for replay' outcome that production
FeedLiveWrite maps to LiveWriteRetained, and the test treated it as fatal.
Once in a while the whole session also finished inside waitBridgeLiveReady's
1 ms poll gap.
Tolerating the error would defeat the test (the overwrites would never ship
in-session, so convergence could not be checked), and a larger backlog would
only shift the timing. Instead add a test-only hook,
PrimaryBridge.SetPreBarrierHook: each sender runs it after base + backlog
drain and before SealBeforeBarrier. The test installs it before the probe
that starts the rebuild, waits until the sender reaches it (session live,
cut not made), pushes the overwrites, releases, and asserts convergence.
With no hook installed the sender path is unchanged.
The now-unused waitBridgeLiveReady helper in this package is removed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Retain deletes the exact attempt it planned: the attempt's entry is
marked deleting conditionally and the name record is removed only
while it names that attempt; a replacement is reported as replaced.
- Fork records a hold (forkholds/<name>/<attempt>/<target>) before it
reads the parent. Retain marks first, then reads the holds: a live
hold reverts the mark (fork_held); a fork holding after that read
finds the attempt deleting and refuses before installing anything.
A hold counts while its target has no HEAD and its VOLUME records the
fork, or while it is younger than the operation deadline.
- A pass stopped after a mark finishes (or reverts) it on the next run.
- Log-spaced keeps use rolling windows anchored at now.
- Exclusive bytes resolve "@owner/key" refs and count every volume's
HEAD and live snapshots as holders; documented as eligible for GC
subject to its grace period and intents.
- Retain reports confirmed deletions, the failing snapshot (uncertain
or not) and what it never reached; the CLI prints them with the
error and exits nonzero.
- chunkControl.Snapshot validates the class before any cut;
invalid_class and invalid_policy map to 400.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Controls for the six review findings on retention, failing against
stubs that restore each old behaviour:
- a same-name pinned replacement made after planning is deleted
(retain deletes by name);
- a fork that starts after the scan loses its parent; a stale hold;
a fork after the hold check;
- log-spaced keeps use calendar periods (10:20 and 09:50 both kept
at 10:30 with keep-hourly 1);
- exclusive bytes ignore a fork's "@owner/key" holders;
- a failing pass discards its partial result (catalog and CLI);
- an invalid class cuts before it is refused, and maps to 409.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's rulings (2026-11-15 22:53Z).
Retention, policy on the VOLUME entry: keep the newest KeepNewest
unpinned snapshots, every pinned snapshot not yet past its ExpiresAtNs,
every snapshot younger than KeepYounger (a future creation time from
clock skew counts as young), the newest snapshot of each of the last
KeepHourly / KeepDaily / KeepWeekly periods, and every snapshot a fork
still needs (named by a fork whose HEAD is absent or aborted). Everything
else is deleted through DeleteSnapshot (attempt-scoped tombstones; HEAD
untouched; names freed); GC reclaims the chunks. Equal creation times
rank by name. Semantic and labeled snapshots are not exempt; a pinned
snapshot past its expiry is unpinned. Defaults: 10 newest, 1h. A dry run
plans and writes nothing. The policy is stored as extended attributes on
the VOLUME entry, conditional on a revision.
Accounting, from manifests and filer listings (no data reads; a chunk is
ChunkBlocks x BlockSize, the last clipped): live bytes from HEAD;
per-snapshot exclusive bytes (referenced by no other holder); stored
bytes from the volume's chunk-key bindings, exact for referenced keys
and a full chunk (an upper bound, flagged) for the rest. The
unreferenced-not-yet-collected bytes come from GC's preview once #140
merges; bytes uploaded since creation need a counter (follow-up).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05's rulings (2026-11-15 22:53Z): the surfaces and the controls,
with the behavior stubbed (the planner keeps everything, the policy is
not stored, usage reports nothing, no fork needs a parent, the class is
neither validated nor stored).
- chunkstore: snapshot class (semantic / pinned) on the snapshot;
RetentionPolicy stored on the VOLUME entry (extended attributes, CAS on
a revision); planRetention / Retain [dry run]; Usage (live, per-snapshot
exclusive, stored bytes).
- volume: GET /status/chunk?volume= (usage and policy); the snapshot
route carries "class".
- sw-block: ops chunk usage, ops chunk retain [--dry-run | --set-policy
--keep-*], snapshot --class / --pin / --expires.
- controls: policy edges (newest N with name tie-break; pinned never
expired by count or age but unpinned past its expiry; semantic and
labeled snapshots not exempt; younger than T and clock skew; hourly
buckets; fork parent), an agent checkpointing every step stays bounded,
dry run writes nothing, retain keeps N + pinned and frees names, the
policy CAS, class validation, an incomplete fork's parent kept, usage
from manifests; CLI usage/retain; and a real-service test against
SeaweedFS (chunkstore_integration, CHUNKSTORE_WEED): N+5 snapshots plus
pinned ones -> retain leaves N + pinned, accounting follows.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Close marks the target closed before its once-only close; a later
Start refuses before creating anything (a Start in progress holds the
target lock, so Close waits for it and then closes its device).
- teardown skips DEL_DEV only when settleQueues reports a queue whose
thread is still running (leaked); a stopped queue's error is reported
and the device is still deleted.
- A FETCH/COMMIT completion that is neither a new request nor the abort
of a stopping device ends the tag and is joined into the queue's error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review r3 (6afa34ac), actual-caller controls with the old behaviour kept:
- a Start after Close must refuse (Close before Start consumed the once);
- the Close path (teardownWith, driven with a recording controller) must
delete the device when every queue thread exited, even one that ended
with an error; only a queue whose thread still runs keeps its mappings
and suppresses DEL_DEV;
- a completion that is neither a new request nor the expected abort must
be reported as the queue's error (onCQE, the loop's per-CQE path).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #139 (codex01 AMEND):
1. #133 covers open AND replay. A classifiable EnsureStorage failure now
takes the same fail-closed path as a replay failure: local readiness
blocked (frontend I/O refused), the typed reason recorded through
ReportLocalRecoveryFailure, and the process kept up serving status and
heartbeats, so a primary assignment reports it at once. An open
failure that cannot be classified exits as before.
2. io_error is documented as deliberately broad: the volume's local
storage could not be opened or read at startup. A path error such as
ENOENT, EACCES or EISDIR is io_error too, which says the storage is
unusable, not that the disk is physically damaged. The underlying
error stays in the readiness evidence and is now in the log line.
Refs #133
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #139 (codex01 AMEND):
- main's durable open and replay move into openAndRecoverDurable (the
function main now runs), with the open-path behavior unchanged here:
any EnsureStorage failure still exits unreported.
- controls driving that function: a classifiable open failure (EIO path
error; and a real provider whose volume file is truncated, so the magic
read hits io.ErrUnexpectedEOF) must fault fail-closed and report
io_error; an unclassified open failure stays fatal with no report; a
replay failure faults and reports (a real provider's corrupted smartwal
volume reports wal_corrupt); a clean recovery clears the block.
- classifier controls: ENOENT and EACCES path errors are io_error by
contract (local storage unusable, not proof of disk damage); a WAL
integrity fault wrapping a path error stays wal_corrupt.
Refs #133
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- No automatic reclaim: Start refuses a /dev/ublkcN already present at
the requested id, with an error naming it, before sending any command
(the device-info read, pid probe and pid-namespace questions are gone).
A device created by another starter between the check and ADD_DEV makes
ADD_DEV itself fail (EEXIST); nothing is deleted. Removing a leftover
device is a documented operator step (package doc).
- Target.Close runs the device close once; every caller, concurrent or
later, gets that result.
- A queue thread's abnormal error, including a failed ring close, is kept
and returned through the shutdown (settleQueues joins it).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review r2 (6afa2fe0): a pre-existing ublk id must be refused with zero
commands of any kind (no automatic reclaim: GET_DEV_INFO + pid probe +
numeric STOP/DEL races a replacement device, and ESRCH across PID
namespaces is no proof of death); concurrent and repeated Target.Close
callers must all get the first close's result; a queue thread's abnormal
error (failed ring, failed ring close) must reach the shutdown result.
The old behaviour fails all four.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The short-submission and no-progress controls each use their own ring; a
call that does not return in time is reported by its own assertion and
its ring is left open, so the stuck goroutine never races the test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#133: when local durable recovery fails with a classifiable error, a
primary-assigned replica reports the typed reason immediately instead
of waiting out --recover-timeout:
- wal_corrupt: storage.RecoveryFailure of kind WALIntegrity (the
substrates' integrity fault, e.g. a WAL/extent CRC mismatch), or the
ErrWALIntegrityFault sentinel;
- io_error: kind SubstrateIO, an fs.PathError, io.ErrUnexpectedEOF or
EIO.
Anything else is not classified: it reports nothing early, and the
watchdog's recovery_timeout still covers it. The master needs no change:
the reason is an explicit unhealthy fact (Eligible=false), shown in
volume status and the timeline, and fails over only to a qualified peer.
Fixes#133
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#133 (follow-up to #128 rule 6): wiring with the classifier stubbed,
plus controls.
- volume: UnhealthyWALCorrupt / UnhealthyIOError; LocalRecoveryHealthReason
(stubbed here: classifies nothing); Host.ReportLocalRecoveryFailure
records the classified reason, cleared by ClearLocalReadinessBlock; the
watchdog reports a recorded local failure for a primary-assigned
replica at once (after the G1 latch, before readiness and the timeout).
- blockvolume: a failed durable RecoverVolume calls
ReportLocalRecoveryFailure(recErr) next to BlockLocalReadiness.
- controls: the classifier maps WALIntegrity (typed or the sentinel,
wrapped or not) to wal_corrupt, SubstrateIO / fs.PathError /
io.ErrUnexpectedEOF / EIO to io_error, and anything else (WALRecycled,
untyped) to nothing; the real chain (a corrupted smartwal store ->
durable.Recover -> ReportLocalRecoveryFailure) makes a primary-assigned
replica report wal_corrupt at once, cleared by a clean recovery; a
replica that is not primary-assigned is not flagged; an unclassified
failure reports nothing early and recovery_timeout still covers it.
Refs #133
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The buffer-size control recovers a handler panic into a named failure,
and the short-submission controls bound submitAndWait with a timer, so a
missing buffer check or a lost/unconsumed SQE fails the oracle's own
assertion instead of panicking or hanging until the package timeout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review P1s:
- reclaimStale reads the device's recorded server pid (GET_DEV_INFO) and
deletes the device only if that process no longer exists (signal 0 ->
ESRCH). Owner alive, liveness unknown, never started (no pid) or info
unreadable: Start refuses and sends no STOP/DEL. A reused pid reads as
alive: refused.
- settleQueues waits until one shared deadline and releases only queues
whose thread has exited; a queue still running keeps its mappings
(leaked, fail closed) and Close reports it, and skips DEL_DEV, which
would otherwise wait forever for the char device the mappings hold.
- submitAndWait offers the ring's unconsumed SQEs again after a short
io_uring_enter until the kernel has taken all of them, then waits for
completions; a call that consumes nothing is an error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review P1s, each behind an injectable seam with the old behaviour kept:
- reclaimStale: a device found at our id is deleted only with proof its
server is dead; owner alive, owner unknown, never started, or device
info unreadable must refuse with no STOP/DEL (recording controller).
- settleQueues: a queue that did not stop must keep its mappings (leak,
fail closed), never be unmapped while its thread may run.
- uring.enter: a short io_uring_enter must not lose the unsubmitted SQEs;
a submission the kernel never consumes is an error.
The old behaviour fails all three.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ublk handler counts every received request by kind before the
backend call (reads, writes, FUA writes, flushes, other) and the requests
that completed with an error. blockvolume wires the device as the status
server's ublk source: GET /status/ublk?volume=<id> returns them, as
/status/nvme returns the NVMe target's, so the D0 gate can show every
guest fsync reaching the ublk FLUSH and Backend.Sync.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
--ublk-device=N (default -1, off) starts a ublk target for the volume
after the other frontends, with the same block and volume size the NVMe
target uses, and reports {"phase":"ublk-ready","device":"/dev/ublkbN"}.
--ublk-queues and --ublk-queue-depth tune it (defaults 1 and 64). Like
iSCSI and NVMe it auto-enables the readiness bridge, so the device serves
only through a healthy projection. The device closes first on shutdown;
a start failure tears down like an NVMe target failure.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- uapi.go: the ublk_cmd.h ABI (ctrl/dev-info/io-desc/io-cmd/params
structs, ioctl-encoded command numbers), checked byte for byte by
uapi_test.go against the kernel header.
- uring_linux.go: a minimal io_uring (SQE128 for URING_CMD), NOP-tested.
- device_linux.go: ADD_DEV (UBLK_F_CMD_IOCTL_ENCODE), SET_PARAMS (basic:
block size, volatile cache + FUA so the block layer sends FLUSH/FUA),
per-queue descriptor mmap and FETCH for every tag, START_DEV; each
queue is served on one locked OS thread (ublk binds a queue to the task
that fetched it) through the request dispatch. Close: STOP_DEV, wait
for the queues, DEL_DEV. A device left at the same id by a dead server
is deleted first; without UBLK_F_USER_RECOVERY a server crash fails
I/O (documented fail-closed limit).
- target.go: TargetConfig/Target opening the volume backend from a
frontend.Provider on first I/O, like the NVMe-RDMA target.
- device_unsupported.go: Start refuses off Linux.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
READ and WRITE go to Backend.Read/Write at start_sector<<9; FLUSH goes to
Backend.Sync; a WRITE with UBLK_IO_F_FUA is synced before it completes.
Any backend error or short transfer completes with -EIO. A range outside
the device, or larger than the request buffer, completes with -EINVAL
before any backend call; every other operation completes -EOPNOTSUPP.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The ublk bridge keeps the frontend contract the NBD and NVMe frontends
keep: reads and writes reach the backend at the right offset, FLUSH and
write-FUA reach Backend.Sync, every backend failure completes with -EIO
(never acknowledged), an out-of-range or over-sized request never touches
the backend (-EINVAL), and discard, write-same, write-zeroes and zone
operations are refused (-EOPNOTSUPP). The handler is a stub that fails
every request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #134 r2 (one P2): duplicate volume/replica keys in one report
were accepted. The health transition compared against the first prior
match while every entry was stored, so repeating [healthy, unhealthy]
for one key invented a replica_unhealthy event that did not describe
the stored slot.
The observation store now refuses an observation with a repeated slot
key (ErrInvalidObservation) before any mutation, so no transition and
no store change result; validateHeartbeat refuses it at the RPC with
the offending indices. Distinct slots are unchanged.
TestStatusFrontendsForAssignedVolume_DedupesRepeatedFacts ingested its
fact through a heartbeat that repeated the slot; what it pins is the
status dedupe over repeated replica IDs, so it now ingests the fact
once. No production heartbeat repeats a slot (one slot per blockvolume
process).
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #134 r2: store controls (conflicting and identical duplicate
volume/replica keys refused with no transition and no mutation; distinct
slots still yield one transition each) and an RPC control (a duplicate-slot
heartbeat is refused; status and timeline unchanged).
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codex01's AMEND on #134 (three P2s; the disarm policy is unchanged):
1. Only a ready fact for the watched primary epoch clears or disarms
the watchdog. The full promotion fact is passed and its epoch is
compared with the watched epoch under the watchdog lock, so an
engine still ready at an older epoch (its new assignment refused at
admission) cannot disarm the new assignment, and an assignment that
advances while the fact is read is not cleared by it.
2. The G1 role-admission latch of a primary-assigned replica is checked
before readiness: it reports role_admission_failed for as long as it
holds, whatever an older engine-ready fact says.
3. Health events come from the accepted store mutation itself:
ObservationStore.IngestWithHealthTransitions returns, under the
store lock, each slot whose unhealthy reason the accepted report
changed against the same server's previously stored fact. A refused
report yields none and expiry never fabricates a clear. The master
ingests and records those events under healthMu, so events follow
accepted order across concurrent heartbeats.
Lock order: healthMu -> store.mu (released inside ingest) -> event
ring; nothing else takes healthMu, and neither the store nor the ring
calls back into the host. The watchdog keeps its own mutex and calls
nothing while holding it.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Controls for codex01's AMEND on #134 (three P2s), with the API shape
only (the watchdog takes the promotion fact's epoch; the store can
return accepted health transitions; the master Host has healthMu), the
behavior still as in 845bdc0:
- real host: ready at epoch 2, the epoch-3 primary assignment refused
at admission (peer-set install fails): the engine still ready at
epoch 2 must not disarm epoch 3, which times out; a genuine epoch-3
ready fact clears it;
- real host: a ready primary whose epoch-3 role call fails (G1 latch)
must report role_admission_failed despite its old ready fact; a
successful redelivery clears it;
- master: a second heartbeat landing between the first one's ingest and
its event bookkeeping must leave both events, in accepted order;
- master: expiry during an ingest that reports unhealthy again must not
fabricate a clear;
- control: a refused older heartbeat records nothing.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude05 accepted the disarm rule (21:24Z): after a fresh ready fact
clears it, the watchdog stays disarmed until the next primary epoch or a
new process incarnation. Tests:
- ready, then not ready an hour later on the same incarnation (and the
same assignment replayed): no recovery_timeout;
- a restarted process (new incarnation, same primary epoch) is re-armed
and reports recovery_timeout past the timeout, while the old process
stays disarmed;
- master: a running primary that degrades on the same incarnation (no
unhealthy reason) follows the normal failover rules to the qualified
peer, and nothing is listed as unhealthy.
Doc only otherwise: the watchdog comment names the incarnation re-arm.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Volume: a replica holding the PRIMARY assignment that has not produced
the engine's promotion-ready fact within --recover-timeout (default 30s,
from the primary assignment in this incarnation) reports
Eligible=false with unhealthy_reason=recovery_timeout instead of staying
silently not-ready. The G1 role-admission latch of a primary-assigned
replica reports role_admission_failed. A fresh ready fact clears it
(Eligible=true, reason empty) and disarms the watchdog until the next
primary epoch. Supporting replicas are never flagged; /status shows
their catch-up state (elapsed, lag).
Master: an explicit unhealthy slot is ineligible, so it gets no boot
grace and fails over at once to a peer that passes the promotion
evidence gate; with no qualified peer nobody is promoted. The reason is
listed in QueryVolumeStatus (unhealthy_replicas) and recorded as
replica_unhealthy / replica_unhealthy_cleared events when a slot's
stored reason changes.
wal_corrupt and io_error need typed failures from the durable recovery
path: tracked as a follow-up issue.
Lock order: the watchdog has its own mutex and calls nothing while
holding it; the master's transition check reads the observation store
before and after ingest and appends to the event ring, holding neither.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#128 rule 6 (claude05's rulings 21:07Z): declarations with the decision
stubbed, plus the controls.
- proto: HeartbeatSlot.unhealthy_reason (13); StatusResponse
.unhealthy_replicas (9) with ReplicaUnhealthy (regenerated with the
checked-in generator versions; the gRPC file is unchanged).
- authority: SlotFact/HeartbeatSlot.UnhealthyReason (raw fact).
- volume: the recovery watchdog type and Host wiring (primary
assignment, supporting admission, heartbeat Eligible/UnhealthyReason,
/status UnhealthyReason and CatchUp), --recover-timeout on blockvolume
(default 30s, logged at start); its decision is stubbed here.
- controls: a primary-assigned not-ready replica past the timeout
reports Eligible=false + recovery_timeout; ready clears it and
disarms the watchdog, a new primary epoch re-arms it; the G1 latch
reports role_admission_failed; /status shows the reason and a
supporting replica's catch-up state; the master promotes nobody
without a qualified peer and shows the reason in volume status and as
replica_unhealthy / replica_unhealthy_cleared events. Controls that
pass on both sides: a supporting replica is never flagged; an
unhealthy primary fails over at once to a qualified peer.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every /chunk error is a typed JSON body (B9 codes plus the 2026-11-15
transport errors), except an unknown path, which fell through to
net/http's plain-text "404 page not found". A catch-all /chunk/ route
now answers 404 {"code":"not_found","retryable":false}. The known routes
are unchanged; with the endpoint disabled, /chunk is still not mounted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #130 r5 (one P2): the recovery re-probe triggered on the
newer heartbeat's ReadyForPrimary bit alone. A newer engine-ready but
ineligible, withdrawn or unreachable heartbeat, with the frontend now
ready, led to a re-probe that returned the current primary ready, so
the gate skipped its placeability check and preserved an excluded
primary.
The trigger is now the whole fresh verdict: the newer fact must be
ready and placeable (reachable, eligible, not withdrawn). An excluded
newer fact causes no re-probe, so the first verdict and the gate's
fresh placeability/grace check decide, and the failover stands.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Counter-controls for the review of #130 r5 (tests only, on 6989dfd),
through the real workload-plan provider with the peer query held: the
frontend finishes recovery but the newer heartbeat, though engine-ready,
excludes the current primary (ineligible, withdrawn, unreachable). The
failover must stand; frontend readiness must not preserve an excluded
primary. The recovered-placeable positives and the engine-ready /
frontend-unready counter-control are unchanged.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every reconciliation start and every BeginBaseInstall bumps a generation.
A worker selects slices, records compare results and certifies the dirty
set only while its own generation is current, so:
- a worker running when a BASE install begins can no longer finish over
it and clear the install guard (Base=Installing), in memory or on disk;
finishReconcile also refuses while the guard is set (two independent
guards);
- a worker that saw its set empty, or compared a chunk, before a BASE
install restarted reconciliation can neither certify the replacement
run nor delete from its set.
A replaced run closes its channel, and waitReconciled re-checks against
the current run.
Deterministic schedules (test hook at slice, compare and certify):
- held worker -> BeginBaseInstall -> worker resumes: cuts stay refused
as base_installing, the persisted header keeps Installing, a restart
still refuses;
- old worker paused at certify -> Begin/EndBaseInstall -> old resumes:
the replacement stays reconciling and untouched, cuts refused;
- old worker paused after a compare -> Begin/End -> old resumes: the
replacement set is untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Recover republishes the dirty map but did not take captureMu, so it could
run inside a quiesced cut: after the cut's Sync fixed H and before its
copy, a same-open Recover could publish a newer complete record (H+1) and
the cut would copy those bytes into a HEAD labelled H. Recover now holds
captureMu shared (order captureMu -> lifecycleMu -> mu), as Write,
WriteBatch, ApplyEntry and WriteExtentDirect do; nothing calls Recover
under captureMu.
Control: a real partial batch pwrite leaves a complete record at H+1; the
cut parks right after its barrier Sync fixed H and starts a same-open
Recover, which waits for the barrier; HEAD at H holds no post-H bytes and
the next cut publishes the recovered bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The typed control codes map every unlisted cause to 500 internal, so a cut
refused while the layer reconciles its dirty set (and a detach whose
deadline ended during reconciliation) reported internal. They now answer
409 with code reconciling, retryable, as ruled for the reconciler.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When a layer's dirty set is unknown, its first cut used to hash-compare
every chunk under the capture barrier, which paused writes for a
whole-volume copy. The unknown case is a lost or mismatched bitmap, or
a BASE install that just finished.
Now the layer reconciles in the background, outside the barrier:
- The reconcile set is every chunk with a local copy (an absent chunk
never written locally is HEAD's content).
- A layer-owned reconciler, joined on Close, takes bounded slices. Per
chunk it reads through the normal read path, hashes, and compares
with HEAD; a mismatch sets the chunk's dirty bit. A write racing the
comparison marks its chunk dirty anyway.
- When the set is empty, the dirty set is saved first, then a header
naming HEAD. A crash between the two leaves a mismatching header, so
the next attach reconciles again rather than trusting an incomplete
bitmap. Then cuts resume, uploading only dirty chunks.
While reconciling, no HEAD moves:
- Cut, Capture and MakeRemoteDurable return ErrChunkReconciling
(retryable).
- Detach waits for reconciliation within its deadline, then makes its
normal cut; otherwise ErrChunkReconciling.
- The automatic cut scheduler skips the tick (not a failure, no
backoff).
A fresh host (FreshFromHead) starts with an empty dirty set instead of
an unknown one. Its local volume is new and accepts no write before
attach, so a new volume never reconciles.
Stats gains Reconciling and ReconcileDone/ReconcileTotal. DirtyChunks
(the scheduler's threshold) does not count chunks awaiting
reconciliation.
Test changes:
- The storage fixture waits for reconciliation after attach.
- The BASE tests wait after EndBaseInstall.
- The chunkstore source-host fixtures (including the catalog fork test)
attach as fresh hosts, which is what a new empty volume is.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #130 r4 (one P2): the production provider probes the current
primary first, then the peers. If the current primary's frontend
finished recovery and a newer ready heartbeat arrived during the peer
queries, both gates ended its grace but still direct-reassigned from the
probe's outdated Current.Ready=false.
Both gates now go through probePromotionCandidatesCurrent: when the
current primary's own fresh heartbeat advanced to ready (a newer fact or
a new incarnation) while the probe ran and the probe said it was not
ready, the probe is run once more and that fresh result decides. A
heartbeat is never taken as frontend readiness: if the fresh probe still
finds the frontend unready, the failover stands; a heartbeat already
ready before the probe causes no re-probe.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Controls for the review of #130 r4 (tests only, on bb37750), using the
real workload-plan promotion provider over fake /status servers. The
provider probes the current primary first, then the peers; the peer
query is held while the current primary's frontend finishes recovery
and a newer ready heartbeat arrives. The gate must not direct-reassign
from the probe's outdated current verdict (unsupported and supported
paths). Counter-control: a newer engine-ready heartbeat while the
frontend is still unready still fails over.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Recover republishes the dirty map outside the write path: a partial batch
append can leave a complete newer record that same-open Recover publishes.
It only invalidated the WAL-sync coverage generation, so a chunk staged
before it could be reused over the recovered bytes. Recover now tells an
attached chunk layer, which counts a mutation of every chunk (O(chunks),
recovery only), also on a failed or partial scan, before s.mu is released
so no read sees recovered bytes first.
Control: stage chunk 0, then a real partial batch pwrite and same-open
Recover before the barrier: HEAD at the recovered H has the recovered
bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #130 r3 (three P2s; the same class as r1/r2, so fixed
structurally rather than per branch):
- Controller: a supported snapshot that carries any superseded slot
fact (older than the newest recorded for that replica, or equal-time
with another incarnation) is a stale snapshot. It records nothing and
no decision branch runs on it (readiness, endpoint refresh, rebalance,
failover, fallback); any existing desired is kept, as for a stale
authority basis. Fresh facts, including fresh unhealthy and expiry
decisions, are unchanged.
- Unsupported-volume gate: the current primary's own fresh slot fact is
recorded for every unsupported volume, before the promotion-reason
allow-list and concrete-placement filters, so ready reports and starts
under any reason are counted. The promotion rules are unchanged.
- Both gates decide after the blocking probe from the current primary's
fresh slot read at that point (primaryBootGraceHoldsNow), so a newer
unhealthy report or a heartbeat that expired during the probe is seen;
the unsupported gate also skips if the authority line moved during the
probe.
Lock order unchanged: state under TopologyController.mu; the gates read
the publisher line and the store snapshot (their own locks, released)
before calling the controller; no new locks.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Controls for the review of #130 r3 (tests only, on 4c84545):
- controller: a delayed READY fact of the previous incarnation with an
obsolete endpoint must not drive an endpoint refresh; after newest B
reported ready, a delayed UNREADY A must not fail over (a fresh
unready B still does);
- unsupported for a reason outside the promotion allow-list
(UnknownReplicaClaim): a ready report and a restart seen then must
still be recorded, so after the reason clears the same incarnation
going unready, or a third start, gets no grace;
- held promotion probe: a newer unhealthy report, or heartbeat expiry
while the grace still runs, during the probe must lead to failover;
an unchanged fresh primary across the held probe keeps its grace.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The chunk's highest write LSN is not a change detector: a replica apply
may land a block at an LSN below another block of the same chunk, so the
maximum does not move and a stale stage could be reused. Each chunk now
has a mutation count, raised after every dirty-map insert (a write, a
batch write, a replica apply at any LSN) and every BASE block; flushing
moves bytes without changing them and never counts. It is an atomic
per-chunk counter on the write path (O(1), lock-free), sampled before the
staging read and compared at the barrier.
A barrier Sync failure after staging is a clean abort: the cut's staging
intents are deleted (a failed delete is kept and retried by the next cut).
Real-caller controls:
- chunk 0 holds a@10 and b@5; after the staging read, ApplyEntry(b, 6)
through the production apply path, in the WAL and flushed: HEAD at H
has b@6;
- staged uploads, then the local fsync fails at the barrier: no intent
is left; with the intent delete failing too, the intent is kept and the
next cut settles it and publishes the exact image.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #130 r2 (three P2s):
- The unsupported-volume gate records the current primary's own fresh
slot fact on every pass (RecordPrimaryBootFact), not only when a
promotion is considered, so a ready report ends the grace and ready
restarts count toward flap history.
- The grace decision is ordered like the history: a superseded fact
(older than the newest recorded one, or equal-time with another
incarnation) is not a decision input. The decision follows the newest
recorded fact (its incarnation, placeability and grace clock), and a
superseded fact's endpoint is never used for a refresh. A fresh fact
still needs to be placeable and not ready.
- The cap uses the observation store's effective freshness window
(FreshnessConfig.EffectiveFreshnessWindow), so an omitted window caps
at its 10s default; an unset or nonpositive grace takes the window.
Lock order unchanged: state under TopologyController.mu; the gate reads
the store snapshot (its own lock, released) before calling the
controller; no new locks.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Controls for the review of #130 r2 (tests only, on b5a23c2):
- unsupported path, full product tick: a READY tick (probe says the
current primary is ready) must still record the fact, so unready again
in the same incarnation fails over; and ready restarts count toward
flap history, so a third start gets no grace;
- controller: a delayed UNREADY fact of the previous incarnation, and an
equal-time fact with a changed incarnation, must not defeat the
restarted primary's grace;
- cap: an omitted freshness window is the effective 10s default and caps
an explicit 5m grace; a nonpositive grace takes the window.
The unsupported tests now use a switchable promotion probe.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of #130:
- P1: the unsupported-volume promotion gate reassigned directly even
when only a different slot was stale. It now judges the current
primary from its own fresh heartbeat slot in the observation store
(FreshSlotCandidate, server reachability/eligibility folded in) and
skips the direct reassign while that slot is placeable and inside its
boot grace. Placement-synthesized facts are never used for it.
- P2: boot history is ordered by observation time. A fact changes the
incarnation, start count, or ready latch only if its ObservedAt is
strictly newer than the last recorded one for that replica, so a
delayed or superseded snapshot (or an equal-timestamp replay) never
counts a start nor resets or ends a grace. Both gates go through
PrimaryBootGraceHolds, which records the fact under the same rule and
evaluates it.
- P2: a configured PrimaryBootGrace above the freshness window is
capped at it (logged), never widened.
Lock order: boot-grace state stays under TopologyController.mu and the
new code adds no call out of it (existing paths call the authority
reader under c.mu, unchanged). The gates call PrimaryBootGraceHolds and
read the observation store's snapshot (its own lock, released before
the controller call) while holding no host lock. No new locks.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Controls for the review of #130, on 6c00734 with declarations only
(ReplicaCandidate.ObservedAt copied by the snapshot builder; a
PrimaryBootGrace() accessor):
- full product tick on the unsupported-volume path: the third server's
facts age out (StaleObservation) while the current primary reports a
fresh, placeable, restarted, not-ready slot. Today the gate reassigns
directly inside the grace;
- an ineligible restarted primary still fails over at once (control);
- a configured grace above the freshness window is capped, and an
unready primary fails over at the capped limit;
- an out-of-order snapshot carrying the previous incarnation's older
fact, and an equal-timestamp fact, must not change boot history.
The controller rig now advances its clock after the steady fact, so
every later fact is strictly newer.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ruling (B9 W3 bound): the dirty threshold, now the layer's BarrierBound,
bounds how many chunks a cut copies under its barrier; it never triggers
a cut.
- While more candidates than the bound would be copied, the cut stages up
to the bound per round outside the barrier: current bytes, compared to
HEAD, uploaded under fresh content keys named by an intent written
before the round's first upload.
- Each staged chunk records its version: the chunk's highest write LSN,
flushed or still in the WAL, taken before the read. Flushing never
changes it; any later write raises it, so a stale stage is never used.
- At the barrier a staged chunk stands for the copy only while its
version and HEAD are unchanged; the rest is copied, so the image at H
is exact.
- At most three staging rounds; then the barrier copies the rest
(correctness over pause), counts BarrierOverBound and reports the
barrier copy size (BarrierCopyChunks).
- Every intent of the cut (staging rounds and the barrier) is settled
with it: deleted after the confirmed CAS or a clean abort, kept with an
unresolved proposal. Superseded staged keys stay under their intent
until then.
- Snapshot, explicit Cut and Detach's final cut share the path.
The barrier copy and staging share one readChunk helper. The provider
passes ChunkDirtyThreshold (default 512) as the bound.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A freshly started volume reports ReadyForPrimary=false until its engine
has a promotion fact, so any restart of the current primary failed over
at the first heartbeat whenever a ready peer existed (#128; T1/T2).
The controller now keeps the current primary while it is placeable and
inside its boot grace: the grace starts at the first heartbeat of a new
incarnation and lasts PrimaryBootGrace (the master sets it to its
freshness window). Only its endpoint may be refreshed meanwhile. The
grace never covers an explicit unhealthy report (unreachable,
ineligible, withdrawn); ends for good once the replica reports ready or
the grace expires (no extension by repeated not-ready heartbeats); and
is refused to a replica with PrimaryBootFlapRestarts process starts
within PrimaryBootFlapWindow (defaults 3 in 10 min). No incarnation (an
older volume binary) means no grace.
The promotion gate's direct reassign skips a current primary that is
placeable by its own report and inside its boot grace.
Lock order: grace state lives under TopologyController.mu, written only
by observeIncarnationsLocked inside the existing snapshot path; the
controller calls nothing outward while holding it. The gate calls
PrimaryInBootGrace (takes c.mu) holding no controller-visible lock, the
same direction as its existing controller calls.
Fixes#128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
blockvolume reports a random incarnation, new on every process start, in
each heartbeat slot (proto field 12, regenerated with the checked-in
generator versions). It flows through the wire, observation and snapshot
layers to ReplicaCandidate.Incarnation as a raw fact. The controller
config gains PrimaryBootGrace and the flap bounds, unused here.
The new controller tests pin the #128 boot-grace contract and fail
against today's rule (a not-ready current primary with a ready peer
fails over at once): restart -> endpoint refresh; no ask inside the
grace; ready ends the grace; a flapper gets none. The explicit-unhealthy
and no-incarnation cases pass on both sides as controls.
Refs #128
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The engine's stale-transport guard skips zero fields, so an unstamped ack
would be taken at a new identity if the assignment moved between the
close callback and the ack. Stamp both from session.lineage, as the
review asked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The remote holds snapshots, not live data. Cuts are published at Snapshot,
Detach/stop and explicit Cut, and automatically only by the operator's
timer (off by default). The dirty-chunk count no longer triggers a cut:
the loop runs only with a timer, and the policy has no threshold trigger.
A successful cut of any kind observed after a failed automatic cut makes
that failure's backoff obsolete, so an explicit success followed by the
timer is no longer suppressed until the old retry time. A success older
than the failure leaves the backoff in force.
A fenced layer can never publish again: its loop ends instead of retrying
refused cuts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since the engine holds PublishHealthy until a durable ack observed after
the recovery window closes, only the dual-lane rebuild close sent that
ack. The legacy path (finishSession: every StartCatchUp, and StartRebuild
without dual-lane; cmd/blockvolume defaults to --recovery-mode=legacy)
sent only the session close, so a recovered replica stayed recovering.
finishSession now sends, after a successful close, the same
DurableAckResult the dual-lane close sends: DurableLSN is the replica's
barrier-acknowledged achieved LSN, with the primary's tail and head. The
ack follows the close callback, and both run without e.mu held. A failed
close sends no ack.
Fixes core/calibration C2/C3/C4/AllScenarios and cmd/sparrow
AllThreePaths/Repeatable. Refs #94
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A push between HasActiveSession and live-ready returns
ErrSessionNotLiveReady (2 of 200 runs on Linux). ship_sender treats
it, ErrSinkBarrierSealed, ErrSinkSealed and ErrNoActiveSession as
retained or handed back to the steady path; the test now accepts the
same set, and the replica byte check still pins arrival.
Refs #94
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TestDualLane_EngineDrivenRebuild_WithPushLiveDuringSession pushed its
live write straight into PrimaryBridge and failed on any error. Since
the dual-lane sink seals at the pre-barrier cut (8682e15), a push after
the cut returns ErrSinkBarrierSealed and the entry stays in the WAL for
replay; the production live-write path treats that as retained. A
12-entry rebuild usually reaches its cut before the push, and sometimes
closes before the test sees it live, so the test failed on most runs.
The test now accepts both: ErrSinkBarrierSealed from the push, or a
session that already closed (no push). The existing byte check that
the live LBA matches on the replica still pins that the write arrived.
Refs #94
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since the engine started holding PublishHealthy until a durable ack
observed after the recovery window closes, the YAML case
session_closed_completed_to_healthy has failed on every run: it goes
from SessionClosedCompleted straight to healthy. The schema had no way
to express the ack.
- schema: add the DurableAckObserved event kind (durable_lsn,
primary_tail_lsn, primary_head_lsn).
- cases: the healthy case now acks after the close; a new case pins
that the close alone is held (publish_healthy_held, no PublishHealthy).
Test-only: core/schema and core/runtime are imported only by the
conformance test.
Refs #94
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The remote holds snapshots, not live data: cuts are published at
snapshots, at detach/stop and on explicit request. The periodic timer is
now off by default (operators may set one, e.g. 15m, as a host-loss
safety net) and the dirty threshold is 512 chunks (2 GiB at 4 MiB),
kept only as a bound on one cut's size. Success resets, failure backoff,
no cut with nothing dirty and no cut while reconciling are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A walstore-chunk volume's VolumeStatus (/status/durable) gains a Chunk
section: Attached, AwaitingAuthority, Fenced, RemoteLSN and the layer's
Stats (cut counters, the last cut's stats, the dirty-chunk count).
Other implementations have no Chunk section.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The volume's automatic cuts follow the W3 ruling:
- Timer: a cut is due once ChunkCaptureInterval has passed since the
last successful cut of any kind; an explicit Cut, Snapshot or Detach
restarts it.
- Threshold: a cut is due once ChunkDirtyThreshold chunks are dirty
since the last HEAD. Whichever fires first triggers; zero disables
either.
- Automatic cuts are at least 1 s apart.
- A failed automatic cut resets nothing and is retried after a backoff
doubling from 1 s to 30 s.
- A successful cut, including a no-op one (no CAS), clears the backoff
and restarts the timer.
The decision is a pure policy (cutPolicy), tested with explicit times.
The provider loop polls the layer's Stats every 100 ms for the dirty
count and the last successful cut.
blockvolume defaults: --chunk-capture-interval=30s, and a new
--chunk-dirty-threshold=64 (256 MiB of 4 MiB chunks). The --chunk-*
flags stay refused with other implementations when set away from their
defaults.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every cut now fills its ChunkCutStats:
- barrier pause, sync and copy time;
- candidate, uploaded, zeroed and unchanged chunks, and uploaded bytes;
- upload time; CAS time and result (ok, precondition, unknown,
resolved-by-reread; empty for a no-op cut);
- total time.
The layer keeps cumulative counters, exposed by Stats():
- cuts ok, no-op and failed;
- refusals by reason (admission, fenced, detached);
- CAS conflicts, and unknown CAS outcomes left unresolved by the HEAD
re-read;
- whether a proposal is pending, and the current dirty-chunk count (the
C11 bitmap popcount, for the cut scheduler's threshold);
- the last successful cut's stats, LSN and time.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: capture-path intent schedules (RED)
A cut that uploads writes an intent naming exactly its keys before the
first upload and deletes its own intent after the confirmed CAS; no
upload, no intent; a failed intent write uploads nothing; a failed
upload or a refused CAS deletes the intent; an unknown CAS outcome keeps
it until the next cut settles the proposal; a lost CAS response
confirmed by re-read deletes it; a failed delete is retried at the next
cut; other intents are untouched. The fake remote gains intent failure
hooks and records written intents.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: the capture path writes an intent before uploading and settles it
A cut that uploads chunks now writes one intent naming exactly the keys
it will upload, at the cut's base HEAD generation with the layer's epoch
and holder. The intent is durable before the first upload; if it cannot
be written, nothing is uploaded. A cut that only drops chunks writes
none.
The cut deletes only its own intent, once its outcome is settled:
- after the HEAD CAS succeeds, or a HEAD re-read confirms its proposal;
- on a clean abort: a failed upload, a refused admission, a fence, or a
HEAD that moved past the CAS's base.
An unknown CAS outcome keeps the intent with the pending proposal. The
next cut deletes it once that proposal is settled, whether it landed or
can never land. A failed delete never fails a settled cut; the next cut
retries it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
A fresh host restoring an epoch-1 HEAD with an LSN-ordering observer
installed: at the takeover CAS the observer must already be rebased to the
seeded next LSN, and a refused post-seed rebase must fail the restore with
HEAD still owned by its previous holder and I/O refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SetWriteObserver published the observer first and only logged a refused
ship-LSN rebase, so the volume kept serving writes its observer would
mis-order.
Now:
- SetWriteObserver rebases an LSN-ordering observer to the store's next
LSN before installing it. If the rebase is refused, the observer is
not installed and the error is returned. The backend also records the
fault and refuses every I/O until an install succeeds, so a later
attach that marks the volume operational cannot reopen it. blockvolume
reports the error.
- The frontier seed and its observer rebase run in one critical section
with observer installs (observerMu). Whichever runs second sees the
other's result; a seed landing between an install's rebase and its
publication can no longer leave the observer on the old LSN. A refused
rebase after the seed records the same fault.
- RebaseShipLSN documents that it moves only the ordering cursor:
entries already dispatched to peer queues carry lower LSNs and are
untouched.
The composition test checks the install error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An observer whose RebaseShipLSN is refused at install must not be
published with I/O left open: the next write must be refused. A later
install whose rebase succeeds reopens I/O.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A ReplicationVolume orders writes from the store's next LSN, captured
when it is built. On a restored walstore-chunk host the frontier seed
moves that LSN to HEAD.remote_lsn+1 later, during the deferred attach.
The resequencer then waited forever for the LSNs below it, and writes
and flushes hung.
Whoever moves the next LSN now tells every component that cached it:
- ReplicationVolume.RebaseShipLSN(lsn) moves the ship order forward. It
is refused while any write is pending or in flight, never dropping
one, and never moves backwards; an equal LSN is a no-op.
- The provider calls it through the backend's observer right after
SeedChunkFrontier, before the layer attaches and the volume serves
I/O.
- StorageBackend.SetWriteObserver rebases a newly installed observer
to the store's next LSN, covering a seed that landed before the
observer was installed (blockvolume installs it after
SetReplicationVolume, while the attach is still deferred).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A fresh walstore-chunk host restoring from a remote HEAD, in the
production order of cmd/blockvolume, with the real RF=1
ReplicationVolume as the backend's write observer:
1. Recovery runs before the master's assignment is visible, so the
chunk layer attach is deferred.
2. blockvolume builds the ReplicationVolume, which captures the store's
next LSN.
3. The replayed assignment lets the deferred attach claim HEAD and seed
the frontier to HEAD.remote_lsn.
4. A frontend write and flush then wait forever for LSNs below the
seeded frontier to be shipped.
The control differs only in having no remote HEAD, so nothing is
seeded; it writes and flushes fine.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review of the attempt-scoped layout (one rule for both P1s: the decision
comes from ONE read of the entry acted on, and success from re-reading the
entry the operation tried to create):
- EnsureVolume decides a fork's attach from one HEAD read: absent and
aborted both refuse (fork_incomplete), so a sweep between two reads can
no longer pass an aborted HEAD.
- Fork decides from the HEAD it re-reads after its create: a real HEAD
completes the fork; an aborted tombstone means the fork lost to a sweep
(target_exists, its intent dropped, the tombstone is permanent); an
unreadable HEAD after a refusal is retryable, never a replay.
- A snapshot completes from its own attempt entry, never by resolving the
reusable name again; a snapshot tombstone carries no attempt stamp, so it
is never taken for this attempt's create.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
W5 ruling (2026-11-15 17:30Z), W2 part: a GC sweep settles a dead copy
attempt by claiming the operation's final publishing entry with an aborted
tombstone, and every attempt publishes to a target that is never freed.
- Snapshot: the name is taken by an exclusive name record
snapnames/<name> {request, attempt}; the intent names the attempt
(holder "snapshot:<vol>/<name>/<attempt>"); the snapshot is published by
an exclusive create at snaps/<name>/<attempt>. A retry of the same
request publishes to the same attempt path. List and Fork resolve names
through the record and skip aborted or unpublished attempts.
DeleteSnapshot marks the attempt deleting (or claims an unpublished
attempt's path with a tombstone) and removes the name record, freeing
the name; attempt paths are never removed, so a late insert always
fails. Catalog.AbortSnapshot(vol, name, attempt) is the sweep's claim.
- Fork: the publishing entry is the target's HEAD. Catalog.AbortFork
claims it with an aborted HEAD tombstone (state "aborted", gen 1, no
chunks); a fork whose HEAD is a tombstone never attaches
(fork_incomplete) and its replay is target_exists.
- The copy-intent deadline stays as metadata only.
A deleted snapshot no longer holds its name: it is no longer listed (even
with includeDeleting) and a fork of its name is snapshot_not_found; its
attempt entry stays for GC.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A cut that uploads chunks now writes one intent naming exactly the keys
it will upload, at the cut's base HEAD generation with the layer's epoch
and holder. The intent is durable before the first upload; if it cannot
be written, nothing is uploaded. A cut that only drops chunks writes
none.
The cut deletes only its own intent, once its outcome is settled:
- after the HEAD CAS succeeds, or a HEAD re-read confirms its proposal;
- on a clean abort: a failed upload, a refused admission, a fence, or a
HEAD that moved past the CAS's base.
An unknown CAS outcome keeps the intent with the pending proposal. The
next cut deletes it once that proposal is settled, whether it landed or
can never land. A failed delete never fails a settled cut; the next cut
retries it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A cut that uploads writes an intent naming exactly its keys before the
first upload and deletes its own intent after the confirmed CAS; no
upload, no intent; a failed intent write uploads nothing; a failed
upload or a refused CAS deletes the intent; an unknown CAS outcome keeps
it until the next cut settles the proposal; a lost CAS response
confirmed by re-read deletes it; a failed delete is retried at the next
cut; other intents are untouched. The fake remote gains intent failure
hooks and records written intents.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
W5 ruling (2026-11-15 17:06Z), W2 part: a snapshot or fork copy intent
records its absolute publication deadline (DeadlineNs: the read time plus
OpDeadline); the deadline is re-checked immediately before the publishing
exclusive create, and that create runs under a context bounded by the same
deadline, so it never publishes after it. GC may then expire a copy intent
by its recorded deadline (plus RPC timeout and grace) instead of by epoch.
The re-read that settles an ambiguous create keeps the caller's context.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Integration ruling F2: when the chunk layer attaches fenced (HEAD belongs
to a newer epoch or another holder, e.g. another server serving the same
replica), RecoverVolume fails with ErrChunkLayerFenced and the volume stays
non-operational, before anything can serve; the deferred authority attach
does not enable I/O either. HEAD is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Integration ruling F1(a):
- Catalog.EnsureVolume (the attach check) gives a created volume its
initial HEAD with the VOLUME entry: gen 1, epoch 0, no holder,
remote_lsn 0, no chunks (all zero), by exclusive create. An existing HEAD
is kept (a volume published before VOLUME entries), and a missing one is
created on the next attach.
- A fresh local volume (FreshFromHead) without a saved bitmap starts with
an empty bitmap bound to HEAD instead of hash mode: it took no write
before its first attach, so its image is HEAD's. Its first cut uploads
only the chunks written. Hash mode stays for an existing volume whose
bitmap is lost (F1(b)'s background reconciliation is separate work).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Prints one volume's VOLUME entry and HEAD from the filer (B9 W2 §0.1 and
appendix 2026-11-15 14:30Z): {volumeID, volume, head}, each null when it
does not exist; a HEAD without a state shows as active. Catalog.ReadHead
reads the HEAD; the show body lives with the other shared API bodies.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ops chunk failures print {code,message,retryable} on stdout, the same body
the routes answer (relayed as-is for an HTTP error), with a log line on
stderr and a non-zero exit (2 for usage errors) (B9 W2 appendix,
2026-11-15 14:30Z). CLI-side failures use the routes' codes: bad_request
for usage, remote_unavailable (retryable) when blockvolume or the filer
cannot be reached, internal otherwise; catalog refusals keep their code.
Messages no longer repeat the code: CatalogError.Detail is the message
and cause without it, used by the routes and the CLI.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contract revisions from integration (B9 W2 appendix, 2026-11-15 14:30Z, and
the rulings of 14:09Z):
- a cut behind HEAD's remote_lsn answers lsn_behind (409, not retryable);
- a detached layer answers closing with 409 (it stays closed until a new
attach); a closed layer (process shutdown) stays closing 503;
- an invalid label is invalid_label (400), and SnapshotReplay validates
labels and consistency with the name and request id, so a bad request is
refused before any cut;
- the /chunk/cut body omits the cut statistics until W3 fills them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The replica id alone made two hosts that both serve replica r1 look like
the same holder returning, so the later one was not fenced (B9 W2
appendix, 2026-11-15 14:30Z). blockvolume now passes
<server-id>/<replica-id> as the provider's ChunkHolder.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A cut whose LSN is below the base HEAD's remote_lsn is refused before any
upload (ErrChunkCaptureRefused with ErrChunkLSNBehind; the expected gen
pins that base HEAD), unless that HEAD belongs to a newer holder, which
fences as before. MemChunkRemote refuses a lowering CAS too (B9 W2
appendix, 2026-11-15 14:30Z).
Until LSN continuity across hosts exists, a fresh, migrated or forked
volume cannot cut or detach; the carry-forward must merge before or with
this check. Tests that model a host continuing from a seeded HEAD now
advance the local log to that HEAD's remote_lsn first, as the
carry-forward will.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An HTTP response over the 64 MiB limit is refused (read limit+1) instead of
being relayed truncated, and every result write checks for a failed or
short write, for the route commands and the filer commands alike. There is
no retry of the operation: the error says the result was not relayed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The walstore-chunk control plane on the command line (B9 W2 §0.1, §3):
- cut, snapshot and detach call a blockvolume's /chunk/* routes
(--status-addr, with --chunk-control-endpoint); the request carries
timeoutMs and the client waits a little longer;
- snapshots, snapshot-delete and fork read and write the filer directly
(--chunk-filer, --chunk-path), so they work while the volume is offline;
- snapshot and fork generate a request id when none is given and print it
on stderr for a retry; --label k=v repeats;
- stdout carries the operation's JSON body (the route's, or the shared
list/delete bodies, or the fork result with remoteLSN); a failure prints
"<code>: <message> (retryable=...)" and exits 1; usage errors exit 2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SnapshotListItem / SnapshotListBody (exactly B9 §3.3's fields) and
SnapshotDeleteBody move from the volume routes to chunkstore, so the
sw-block CLI, which reads the filer directly, emits the same bodies.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- StopIO keeps one pending drain per backend; every StopIO waits on it,
so timed-out detach retries behind a held I/O no longer each leave a
goroutine waiting for the admission lock.
- CutVolume resolves the volume's handle and layer in one critical section
(chunkHandle) and keeps that handle: a Close that empties the volume map
mid-call no longer leaves the minLSN check reading a missing handle.
- A /chunk/* request body must be exactly one JSON object: trailing data
is bad_request before any operation runs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Snapshot resolves its request with Catalog.SnapshotReplay first: a retry
of a recorded request returns it and another request gets
snapshot_exists, both without cutting (so a replay survives a detached,
fenced or unreachable cut path).
- Cut passes minLSN to the provider, which refuses an LSN never written
before publishing.
- outcome_unknown is reported whenever an unresolved CAS is in the error,
also when the re-proposal was refused for authority.
- Transport errors are JSON like every /chunk/* response (ruling of
2026-11-15): bad_request (400), method_not_allowed (405), forbidden (403).
- timeoutMs is compared with OpDeadline in milliseconds before converting,
so a huge value selects OpDeadline instead of overflowing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The recorded snapshot for the same request id (Replayed), snapshot_exists
for another, or a free name, after validating the name and request id
(B9 W2 §3.2 step 1). CreateSnapshot uses it for its own pre-check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- StorageBackend gains an I/O admission boundary: Read, Write and Sync
hold the read side of ioMu for the whole operation, gate included, and
check the closed and operational flags once before the lock so I/O
arriving during a drain fails at once. StopIO refuses new I/O and waits,
bounded by ctx, for the I/O admitted before the stop.
- DetachVolume latches the volume as detached for this process (under the
attach lock), stops and drains frontend I/O before the periodic loop
and the final cut, so no write is acknowledged outside the detached
image; a drain that times out fails the detach with I/O still stopped.
RecoverVolume and the deferred authority attach no longer reopen a
latched volume (ErrChunkLayerDetached); a retry settles the detach and a
repeated call returns the first result.
- CutVolume takes minLSN: an LSN never written is refused before anything
is published (MakeRemoteDurable's refusal), and the cut must reach it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Off by default; only with --durable-impl=walstore-chunk and a
--status-addr. The routes are served from the durable provider and the
catalog under --chunk-path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
walstore-chunk now dials one filer client for the per-volume remotes and
a catalog under the same --chunk-path, and wires the provider's attach
check to Catalog.EnsureVolume with the local geometry (B9 W2 §4.2, ruling
of 2026-11-15): the first attach creates VOLUME, and an attach is refused
with geometry_mismatch, or with fork_incomplete for a fork whose HEAD is
not written yet. It runs before any HEAD read or CAS.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Exclusive create, conditional update and delete on extended attributes,
and name-ordered listing of one directory's children, like
storage.MemChunkRemote for the chunk remote. The volume control adapter's
test uses it instead of its own copy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
POST /chunk/cut, /chunk/snapshot, /chunk/snapshot/delete, /chunk/detach and
GET /chunk/snapshots (B9 W2 §2.1-§2.2, §3.1-§3.4, §3.6), mounted only
after EnableChunkControlEndpoint and wired by SetChunkControl:
- loopback-only like the listener; JSON request bodies (unknown fields are
refused) and ?volume= for the list; volume_not_served for another volume
and not_chunk_volume until a control is wired;
- success bodies carry exactly the spec's field names (§3.1-§3.4, §3.6);
- failures answer {"code","message","retryable"} with the §2.2 code and
status, plus the 2026-11-15 rulings: awaiting_assignment (409, retryable)
for a layer that waits for the master's assignment, not_primary not
retryable, internal (500) for anything unmapped; transport errors
(method, client, malformed request) stay plain text as on the rest of
the listener;
- long operations run under min(timeoutMs, OpDeadline).
NewChunkControl serves the routes from the durable provider (cut, detach)
and the catalog (snapshots): Snapshot validates the name and request id
before it cuts, then stores the HEAD that cut installed; Cut with minLSN
fails unless the cut reaches it. The cut statistics fields read zero until
W3 fills them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CutVolume takes one quiesced cut and returns what it installed (cut LSN,
HEAD, statistics). DetachVolume is a clean stop's final cut (B9 W2 §3.6):
under the volume's attach lock it stops frontend I/O and the periodic
cuts, then publishes the one detached-HEAD cut, and returns it with the
last written LSN. A repeated call returns the first result; a failure
leaves I/O stopped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ProviderConfig.ChunkAttachCheck runs before every chunk layer attach, ahead
of any remote read or CAS (and so ahead of a takeover CAS), with the
volume's local geometry (blocks, block size, chunk blocks). A non-nil error
refuses the attach and the volume stays non-operational. blockvolume wires
it to the VOLUME entry's attach rules (B9 W2 §4.2, ruling of 2026-11-15).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The causes the /chunk/* routes report as B9 codes are now reachable with
errors.Is:
- storage: ErrChunkLayerClosed (closing), ErrChunkBaseInstalling
(base_installing, inside ErrChunkCaptureRefused), ErrChunkRemoteUnavailable
(an upload failure), and ErrChunkHeadPrecondition on every CAS that did
not apply because HEAD moved, whatever error the CAS returned;
- durable: ErrChunkNotPrimary and ErrChunkEpochStale as the causes of the
provider's capture admission refusals.
Messages are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Re-proposing an unresolved CAS at its base is a new publication. It now
passes the capture admission again right before the CAS is sent, after
the blocking HEAD read: a demotion or lineage change during that read sends
no CAS, keeps the CAS unresolved, and returns the refusal (with
errChunkCASOutcomeUnknown still in the chain). Once authority is back, the
same proposal settles at the same base.
The fake remote gains onGetHead, a hook that runs inside each HEAD read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Snapshot and fork attempts stamp the entry they create with their intent id
(swb.attempt). An attempt deletes its own intent only when its own create is
confirmed (applied, or found by the re-read with its attempt id) or refused
by the filer's "already exists" answer, or when it never sent the create
(deadline). Any other failure leaves the create unsettled and the intent in
place, even when the re-read finds another attempt's entry: the held create
may land after that entry is removed. No attempt, and no replay, deletes
another attempt's intent (W5 rule); tag-wide settleIntents is removed.
The fake filer gains held creates (deferCreate) and releaseDeferredCreates,
which applies them later only if the name is still free.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A cut or detach CAS whose outcome is unknown while HEAD still reads its
base generation may still be applied by the server later. Reading HEAD
alone no longer settles it: the capture keeps the proposal pending, and the
next cut, durability point or Detach re-issues the same proposal at the same
base. Whichever lands first, HEAD ends at that proposal and the other fails
its precondition, so a delayed detach can never land after a no-op cut.
The fake remote gains a held CAS mode (casDeferred) and releaseDeferredCAS,
which applies held CAS calls later only if HEAD is still at their base.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Follows the HEAD schema ruling (2026-11-15), replacing the boolean
detached flag of the previous revision:
- HEAD carries a canonical "state": "active" | "detached" (a document
without it reads as active), and "detachedBy": {holder, epoch, gen}
only when detached; a reader refuses a detachedBy that is not the
HEAD's own holder, epoch and generation.
- Detach is one detach cut: its CAS publishes the final cut with state
detached and detachedBy = {holder, epoch, the generation that CAS
installs}. It always CASes, also with nothing new. Afterwards cuts are
refused (ErrChunkLayerDetached); a repeated Detach returns the result.
- Every normal cut publishes state active and no detachedBy, so a new
holder's cut over a detached HEAD clears it.
- An unresolved detach CAS is settled like any unresolved CAS, before the
next capture or Detach: applied means detached, not applied continues,
a newer holder fences, unreadable is ErrChunkCASOutcomeUnknown. This
replaces the separate pending-mark state.
- A fork's HEAD is published with state active.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fixes for the snapshot catalog, fork and Detach:
- Intents stay until the operation's outcome is settled. An exclusive
create that fails is resolved by re-reading the entry: our entry
confirms the publish; another entry means our create can never land
(clean abort); a failed re-read or no entry leaves the outcome unknown
(it may still land), so the intents are kept and the call reports
outcome_unknown. A retry with the same request id settles it and
removes every intent of the operation (by its holder tag).
- Fork records its operation in the target's VOLUME (request id, source,
snapshot, source gen, the SHA-256 of the snapshot's HEAD document and
the original result). A retry resolves the target first: a completed
fork replays the recorded result without reading the source (also
after the source snapshot is deleting, or the target advanced); a
request id reused with other parameters is target_exists; an
incomplete fork resumes only if the snapshot still has the bound image.
- An unresolved Detach mark (CAS outcome and re-read both failed) becomes
a pending detach that every later capture, durability point and Detach
settles first: applied means detached, not applied continues, a newer
holder fences, still unreadable is ErrChunkCASOutcomeUnknown. A cut can
no longer succeed at the pre-mark generation. Unresolved capture CAS
outcomes now also wrap ErrChunkCASOutcomeUnknown.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Control-plane metadata and operations over the filer (B9 W2 spec §3-§5):
- Catalog (core/frontend/chunkstore/catalog.go):
- VOLUME entry <base>/<vol>/VOLUME: identity, geometry, origin and
parent, write-once. EnsureVolume applies the attach rules (create a
missing one; geometry_mismatch; fork_incomplete for a fork without
HEAD).
- CreateSnapshot stores the HEAD a cut installed as snaps/<name>
(o_excl; the same request id replays, another is snapshot_exists),
under an intent naming its keys until the entry is written, and
refuses the write past OpDeadline.
- ListSnapshots pages in name order (deleting ones hidden unless asked);
DeleteSnapshot only marks deleting (conditional on state and gen);
ListVolumes lists volume directories for GC.
- Fork: VOLUME (origin fork, parent) then HEAD at gen 1, epoch 0, no
holder, the snapshot's remote_lsn (LSNs carry forward), every ref
owner-qualified as "@<owner>/<key>" (an already qualified ref keeps
its owner), under an intent on the target; replays by request id.
- Typed errors with the spec's codes (CatalogError, CodeOf).
- HEAD gains Detached (JSON "detached", omitted when false). The chunk
layer's Detach takes a final cut, then CASes the same image once more
with Detached set; afterwards cuts are refused (ErrChunkLayerDetached)
and a repeated Detach returns the first result. A normal cut always
publishes Detached = false.
No entry carries filer chunks.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On #114 the close-bound remote holds a mutex for the attach context, so
the intent wrappers take a pointer like every other bound call; a value
receiver copied the lock (go vet copylocks).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review fix for the intents seam: an intent document is JSON, which would
silently replace invalid UTF-8 in a key, while a key binding preserves the
bytes, so a protected key could list back as a different key. The chunk
key domain is now non-empty valid UTF-8, refused at Put and, for every
key, at PutIntent by the SeaweedFS remote, MemChunkRemote and the test
fake before anything is written (storage.ValidChunkKey,
ErrChunkKeyInvalid; chunkstore wraps it in ErrInvalidKey). Unicode and
owner-qualified keys round-trip byte-identical.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Remote plumbing for the chunk control plane (snapshot, fork, GC):
- Filer gains ListEntries (one page, name order, a missing directory lists
as empty) and DeleteEntry with expected_extended (never deletes data;
a failed condition, including a missing entry, is ErrPrecondition). The
filer proto subset adds ListEntries with seaweed-mono's field numbers;
regenerated with the same protoc and plugin versions.
- ChunkRemote resolves owner-qualified keys "@<owner>/<key>" in the owner
volume's keys/ directory, so a fork can name its parent's chunks with
one HEAD write. Put refuses them: a volume writes only its own keys.
The owner must be one plain path element (CheckVolumeID).
- storage.ChunkRemote gains the W5 intents seam: PutIntent returns a
per-call id "<gen>-<nonce>", DeleteIntent removes only that id, and
ListIntents lists every live intent or fails (never skips one). The
SeaweedFS remote stores them at <root>/intents/<id>; MemChunkRemote,
the storage test fake and the provider's close-bound wrapper implement
them too. The capture path calling them is separate work.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-ups for the chunk Cut change:
- the ChunkCutResult comment now states the W4 ruling: a volume's LSNs
carry forward across hosts (a new host starts at HEAD.RemoteLSN + 1, a
fork after its snapshot's RemoteLSN), so RemoteLSN never decreases;
- the tagged takeover race test accepts a failed attach only when the
old holder's competing CAS was actually injected before the takeover
CAS, and only when the new holder published nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cut(ctx) takes the same quiesced cut as Capture and returns the HEAD its
own CAS installed (or the current HEAD for a cut with nothing new), so a
snapshot can copy exactly the image of cut H even when other cuts follow.
Capture keeps returning H through Cut. A ChunkCutStats struct is declared
for the periodic-cut work to fill.
A capture refused by the owner's CaptureAllowed check now wraps the
owner's error with %w, so callers can tell "not primary" from "lineage
changed" with errors.Is.
Also adds the RED tests for the takeover CAS at attach, behind the
chunk_takeover_red build tag, for the work that implements it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The authority wait of recovery A passes its per-tick generation check
and is parked (test-local one-shot projection barrier) inside its
projection read. Recovery B then fails on the real WAL integrity fault.
Released with authority, A must not start a remote attach, publish a
layer or admit I/O; only the re-check under the per-volume
serialization stops it. Repaired recovery C converges. Tests only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A deferred authority wait kept acting after a newer RecoverVolume. If
that newer recovery failed, the old wait still attached the layer and
set the backend operational once authority arrived, overriding the
failed recovery.
Each RecoverVolume of a walstore-chunk volume now takes the next
recovery generation (under the per-volume serialization), and an
authority wait carries the generation that registered it. A wait whose
generation is no longer the latest exits. It checks on every tick, and
again under the per-volume serialization right before attaching, so it
never attaches or touches the backend for a superseded recovery. After
a failed recovery the backend stays refused until a later recovery
succeeds; that recovery attaches directly or starts its own wait.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Recovery A succeeds before authority and registers the authority wait;
recovery B fails on a real WAL integrity fault (a CRC-valid write-batch
record with no block count); authority arrives. I/O must stay refused
and no layer may attach. A repaired, later successful recovery
converges.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The chunk layer attached right after local recovery. In blockvolume that
is while the host still blocks the master's assignment, so the layer was
bound to epoch and endpoint version 0. After the assignment replayed, the
host became healthy but every cut was refused against that 0/0 lineage.
The layer now attaches only when the projection names the volume, is
healthy and carries a master-assigned epoch. RecoverVolume attaches at
once when that holds. Otherwise it reports the volume recovered, keeps
its I/O refused, and starts one authority wait per volume. The wait is
registered with Close like a recovery; it attaches when the assignment
is applied, then makes the volume operational, and retries a failed
attempt. Capture operations report ErrChunkAwaitingAuthority meanwhile.
The lineage that later cuts are checked against is the one at that
attach.
The attach's remote calls now also end with RecoverVolume's caller
context, besides provider Close. The attached layer is not bound to that
context: later captures keep working after it ends.
New control: Close settles an in-flight deferred attach.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The production startup order with a real Host (readiness blocked, the
assignment retained, recovery, readiness cleared and the assignment
replayed, frontend write, on-demand and periodic capture), recovery
before the assignment is visible, and the caller deadline over the
attach's first remote call.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fresh initialization survives interruption. A walstore-chunk volume
gets a durable <path>.chunkfresh marker (file and directory fsynced)
before its volume file is created. The provider reads the marker on
every open, and removes it (durably) only after the first attach has
persisted the absence of every HEAD chunk. A create that failed or
crashed before that point reopens fresh and reads HEAD, never the
untouched local zeros.
Captures publish only under the attach-time lineage. The admission
check, made at the start of a cut and again right before its HEAD CAS,
requires the current projection to be healthy and to carry the same
volume, replica, epoch and endpoint version as at attach. A moved
lineage refuses the cut instead of publishing under the old epoch. The
configurable holder name is not part of the comparison.
Attach settles with shutdown. RecoverVolume on a walstore-chunk volume
registers with the provider and serializes recovery and attach per
volume. Close cancels the attach's remote calls through a close-bound
remote, waits for admitted recoveries before closing any store, and an
attach that finishes after Close publishes nothing (the store closes
the layer).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Interrupted fresh initialization, lineage drift before and during a
held upload, Close against a held attach, and concurrent RecoverVolume,
through the real provider entry points.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
walstore-chunk is opt-in and needs --durable-root and --chunk-filer.
Each volume's HEAD and key bindings live under --chunk-path/<volume-id>
(the volume id must be one plain path element); --chunk-collection and
--chunk-replication apply to chunk needles, and --chunk-capture-interval
runs periodic cuts while healthy (0: on demand only). The --chunk-*
flags are refused with any other implementation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ChunkRemote implements storage.ChunkRemote over the imported Filer and
Blobs client. Under one volume's filer directory, HEAD is an entry whose
content is the JSON HEAD and whose extended attributes mirror
{gen, epoch, holder}; each chunk key is a write-once entry (exclusive
create) naming the needle that holds the chunk's bytes, because the
layer names chunks itself while SeaweedFS assigns needle ids.
The HEAD CAS is UpdateEntry with expected_extended {gen, epoch}; the
first HEAD is an exclusive create. Only definite refusals map to
ErrChunkHeadPrecondition; any other error is returned as is, so the
layer treats the outcome as unknown and re-reads HEAD. A proposal that
lowers the epoch is refused. A HEAD entry that exists but does not
decode, carries filer chunks, or whose attributes disagree with its
document is an error, never the absent HEAD. Needles are not reclaimed;
Delete reports ErrDeleteUnsupported.
Tests run against the in-memory fake filer and needle store, including
the chunk layer end to end (capture, then a fresh host reading lazily
from HEAD); an integration test (build tag chunkstore_integration) runs
the same against real weed master, volume and filer processes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copied unchanged from the D1 chunkstore PoC (commit 05818b3): the Filer
and Blobs interfaces with their sentinel errors, the SWFS client over the
filer gRPC API (vendored proto subset) plus plain HTTP to volume servers,
its gRPC error-mapping tests, and the in-memory fake filer and needle
store. The PoC's demo Backend, volume and flat manifest are not imported:
the walstore chunk layer publishes its own HEAD.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds ImplWALStoreChunk ("walstore-chunk"): a walstore volume with the
storage chunk layer attached. On disk it is a walstore file, so the
selector accepts the walstore magic; it refuses other formats.
- ProviderConfig: ChunkRemoteFor (required for this impl), ChunkBlocks
(default 1024), ChunkHolder (default the replica ID),
ChunkReadMissTimeout, ChunkCaptureInterval (periodic cut; 0 = off).
- The layer attaches in RecoverVolume after a successful Recover (the
restart rules read the replayed dirty map). A volume this provider
created starts from the remote HEAD; an existing one stays
authoritative. The manifest epoch is the projection's master-assigned
epoch, held separately from the frontend Identity. A cut is admitted
only while the projection is healthy for the volume.
- CaptureVolume and MakeVolumeRemoteDurable; Close stops the cut loop
before the stores close (the store closes the layer).
Storage gains the exported surface the provider needs (aliases of the
seam types plus AttachChunkLayer), FileChunkBitmapStore (atomic,
checksummed state file plus an append-only delta log; a corrupt file
reads as lost, which falls back to the hash compare) and MemChunkRemote
(an in-memory remote for development and provider tests).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: bound flusher snapshot to published LSN cut
* storage: make checkpoint snapshot atomic with write publication
* storage: chunk layer seam and RED contract tests C1-C11 (r4)
Successor to the earlier seam drafts, reworked after three reviews.
Capture is a quiesced cut: block writes, Sync, copy the chunks dirtied
since HEAD through the normal read path, release, upload outside walstore
locks, then CAS HEAD with RemoteLSN = H. The seam declares Capture,
MakeRemoteDurable, EvictChunk (per chunk; absence survives restart), Close,
an owner admission gate (the epoch fence is what stops a demoted primary),
an explicit fresh-from-HEAD mode, a bounded read-miss timeout, chunk refs
with SHA-256, and a persisted dirty-since-HEAD bitmap kept off the write
path: made durable inside persistCheckpoint before any checkpoint or WAL
tail advance on every path, a header plus delta archive per cut, and a
hash-compare fallback. A BASE rebuild is recorded in the header as
installing (interrupted: cuts stay refused after restart until a complete
install) or installed-awaiting-cut (EndBaseInstall only after its frontier
is durable; the next cut hashes fully).
The fakes log remote calls and CAS outcomes in order, gate Put and Get,
inject unknown and applied-but-lost CAS outcomes and pre-CAS takeovers,
enforce chunk hashes, detect buffer mutation on every Put exit, key reuse
and deletion of referenced keys, and park bitmap persistence with an entry
handshake. Every held worker is unblocked, joined and its resources closed
with a bound, from cleanups registered before it starts. The layer is not
implemented, so every C test fails at attachChunkLayer; the fakes' own
tests pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: chunk layer under the walstore flusher (C1-C11 green)
Implements the seam pinned by the contract tests. Store wiring, each a
no-op without an attached layer:
- a capture write barrier (captureMu) held shared by Write, WriteBatch,
ApplyEntry and WriteExtentDirect, exclusively by a cut;
- OnExtentWrite from the flusher's extent write (with LSN) and from
WriteExtentDirect (BASE, LSN 0);
- BeforeCheckpointAdvance inside persistCheckpoint and inside Sync's
direct-frontier path, before any metadata write; an error refuses the
advance;
- OnReadMiss before readFromExtent takes its lock;
- the layer's Close from WALStore.Close, before the lifecycle lock.
The layer (chunk_layer.go):
- quiesced cut (barrier, Sync, copy dirty chunks through Read, release),
upload of changed chunks under fresh immutable keys, CAS of HEAD at H;
- an uncertain or refused CAS is resolved by re-reading HEAD: our own
proposal is adopted, a newer epoch or competing holder fences, anything
else stays unresolved without a success claim; admission is re-checked
before the CAS;
- dirty-since-HEAD bitmap off the write path: dirty map chunks plus
in-memory marks, saved before every checkpoint advance, rolled over with
a delta per cut, hash-compare fallback on a lost or mismatched header;
entries at or below the latest cut do not re-mark their chunk;
- BASE install states (installing / installed-awaiting-cut) recorded
durably; EndBaseInstall refuses until its frontier is durable;
- lazy fill of absent chunks with SHA-256 verification, never over a newer
local block, bounded by ReadMissTimeout; eviction per clean chunk with
absence (and local writes inside absent chunks) persisted next to the
volume after an fsync.
Adds C3_WriteDuringCopyWaitsForTheCut, which holds a cut's copy on a lazy
fetch and requires a concurrent write to wait for it, and the bitmap
self-test's registered unblock and bounded join.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: chunk layer fixes for presence, fill generation, stale attach
- Presence saves are serialized end to end (snapshot, volume fsync,
sidecar replace, version update) under one mutex, so an older eviction
snapshot can no longer overwrite a newer checkpoint-protected save; the
sidecar's directory is fsynced after the rename.
- A lazy fill is bound to the chunk's absence generation (bumped on every
eviction) and the HEAD ref it fetched; it installs blocks and clears
absence only while both still match, so a fill held across
fill/write/publish/re-evict cannot install older bytes.
- A HEAD that already belongs to a newer epoch or a competing holder
fences the layer at attach and before the CAS, instead of serving as
this holder's publication guard.
- Capture registers with Close in the same critical section that checks
closure, and every concurrent Close returns only after shutdown is done.
Each fix comes with a deterministic schedule test (test-only hooks on the
layer, a one-shot held fetch in the fake) that fails on the previous
code. startCapture's cleanup releases registered unblockers before it
joins.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: chunk layer fixes for directory durability and stale fills
- A presence replacement counts as saved only after its directory entry
is durable: syncDir returns open and fsync errors, persistPresence
returns them without advancing the saved version, and so a checkpoint
advance (or an eviction) that needs the save is refused. Windows cannot
fsync a directory handle; there syncDir is a no-op.
- A read miss never authorizes reading an unresolved extent. Within one
ReadMissTimeout it fetches the chunk as the current HEAD names it; a
fill that went stale (eviction generation or HEAD ref changed) installs
nothing and the read retries, so the extent is read only once the chunk
is no longer absent or the block has a local version.
- A hash-compare cut no longer copies chunks that are absent and
unwritten: they are HEAD's content by definition, and copying them made
a fresh host's first cut fetch the whole volume.
Schedule tests: a failed directory open or fsync leaves the presence
unsaved and the checkpoint and physical WAL tail unchanged, and a retry
succeeds after the fault clears; a held fill that goes stale when a
competing holder publishes H2 returns H2's block or an error from the
original read, never the zero extent; a fresh host's first cut fetches
no untouched chunk. The stale-attach test also asserts fencing right
after attach.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* storage: chunk layer read re-resolves after a miss
A read miss that waited on a remote fetch could fall through to the
extent after the same block was written to the WAL (synced, not flushed):
the fill skipped the dirty block, cleared absence, and readFromExtent read
the untouched zero extent. Now:
- After OnReadMiss resolves, readFromExtent re-resolves through the normal
path (dirty map/WAL first) before reading the extent. No lock is held
there.
- A fill installs HEAD's block beneath an unflushed WAL write instead of
skipping it. Reads resolve the dirty map first and the flusher replaces
the extent later, so this is safe, and the extent holds HEAD's value
rather than zero if that unsynced write is lost in a crash.
Schedule test: a fresh host's held read of LBA 9 overlaps a synced,
unflushed write to LBA 9; the original read returns HEAD's block or the
write or an error, never the zero extent; the next read returns the write;
the extent beneath it holds HEAD's block.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* storage: bound flusher snapshot to published LSN cut
* storage: make checkpoint snapshot atomic with write publication
* transport: close the replica connection when ApplyEntry fails (#89)
The production replica listener (no apply hook) only logged a failed
store.ApplyEntry and kept reading. Later entries on the same connection
were still applied, so the next barrier acked a frontier past the LSN
that was never applied. walstore's ApplyEntry can fail when its WAL is
full, and the primary only checks that AchievedLSN reaches the target,
so the gap went unnoticed.
A failed apply now ends the connection, as the apply-gate path already
does. Nothing after the failed LSN is applied on that connection, and
the primary sees the close, marks the peer degraded and recovers it
from the replica's real frontier.
The new test ships LSNs 1, 2 and 3 with LSN 2 failing and checks that
no barrier, on the same connection or a fresh one, acks LSN 2 or later.
It fails before this change (the barrier acks 3) and passes after.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test: prove the failed apply, the close and the primary's recovery (#89)
The replica test now waits for the injected ApplyEntry(2) failure, requires
the failed connection to end with EOF or a reset (a timeout fails), and
checks that LSN 3 never reaches the store.
A new component test runs the production primary path with the host's
PeerAdapterRegistry and probe loop: a transient replica apply failure
degrades the peer, recovery replays from the replica's frontier starting
exactly at the failed LSN with exact bytes, the peer returns to healthy,
and a later write and barrier succeed. Without the fix the peer is never
degraded and the failed block stays missing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* test: red test for the unfenced dual-lane rebuild port
A host fenced as primary still accepts base blocks on the dual-lane
port. Expected to fail until the port is fenced (#84).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fence the dual-lane rebuild port with the replica admission rules
The dual-lane port applied base blocks and WAL entries with no epoch or
role check. SessionStart now carries the sender epoch, and the
production ReplicaBridge asks ReplicaListener on SessionStart and each
mutating frame: no frame on a primary, below the floor, with epoch 0,
or before the role is known. A higher epoch is persisted first, and a
fence waits for frames already admitted.
The SessionStart frame grows from 28 to 36 bytes, so both ends of a
dual-lane rebuild must run this version.
Fixes#84
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* keep BaseDone and BarrierReq inside the dual-lane counted section
BaseDone released admission before MarkBaseComplete advanced the
frontier, so a fence could return while that mutation was pending.
BarrierReq was not gated, so a fenced replica could still answer it.
Both now stay inside the section; the barrier holds it until its
response is written.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* end the barrier section before its reply
A fence drains effects, not network writes: holding the barrier
section through BarrierResp let a peer that does not read make
FenceAsPrimary time out after every effect had finished. The section
now covers the sync and the completion check, and ends on every path
before the reply.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* test(G1): red - a restarted replica applies a ship below its acknowledged epoch
fencing-gaps-todo.md G1, red test first, as the doc describes it: a
listener accepts a ship at epoch 2, is stopped and restarted on the same
store, and a ship at epoch 1 arrives. Today it is applied: the floor was
in memory only.
Adds the seam the fix uses: NewReplicaListenerWithFloor(addr, store,
floorPath), which cmd/blockvolume now uses with
<durable-root>/<volume-id>.replica-floor (empty for memback). floorPath
is ignored in this commit, so the test is red on behaviour.
Stacked on the G2 branch (it reuses G2's epoch floor).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(G1): a durable replica epoch floor, and no mutation before the role is known
fencing-gaps-todo.md G1, per the plan accepted on #83 (claude03; codex01
rounds 1-3).
- core/transport/floor.go: a versioned, volume-bound floor record,
strictly decoded (unknown/duplicate/missing fields, trailing data, wrong
schema or volume, over 4 KiB refuse); persisted by temp write+fsync,
rename, directory fsync, each checked; InitReplicaFloor creates the
bootstrap record (epoch 0) before the volume and never replaces one.
- Listener: NewReplicaListenerWithFloor(addr, store, volumeID, floorPath)
loads the record (missing or invalid refuses) and starts unassigned:
every mutating frame is refused until a role call succeeds. A frame
whose epoch raises the floor persists it inside its G2-counted section
before any effect or ACK (a barrier too); serialized under floorMu and
monotonic; a refused frame leaves the lineage unchanged.
FenceAsPrimary drains, persists, then returns; AdmitAsReplica persists
first; both return the error.
- Host: AdmitAsReplica errors fail the supporting path closed; any failed
role call sets an admission latch that makes the projection unhealthy
(writes refuse even on a prior-healthy host), reported in /status;
a later successful role call clears it. SetSelfFence returns the
replay error and cmd/blockvolume then does not serve.
- cmd/blockvolume: the floor record is created before a new volume
(DurableProvider.VolumeExists), and required on every later start.
Tests: the red test, revised to the accepted 3-phase form (epoch-2
barrier ACK; restart refused before assignment; a stale epoch-1
admission still refuses epoch 1; current epoch accepted), barrier-only
restart, fresh restart before assignment, record negatives and the
existing-empty missing-record refusal, per-step persist failures on
ship/barrier/rebuild, role-call persist failure incl. after a drain,
fence-then-crash, concurrent monotonic raises, probes never persist, and
the admission latch through the real StorageBackend. Each mechanism is
load-bearing: without persistence 5 tests fail, without the startup gate
2, without the latch 1. Ledger: INV-FENCE-FLOOR-DURABLE-001.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(G1): stale role replays never reconcile a newer failure; the floor record's key set is closed
codex01 review of 66446e0:
- R1: a stale successful role call (e.g. an epoch-2 replay after the
epoch-3 persist failed) cleared the admission latch and reopened
writes. The host's desired role is now monotonic in epoch: a role call
below the current desired epoch is refused as stale, without
replacing the desired role or touching the latch; only the current (or
a newer) epoch's success clears it, and install replay targets the
retained current role.
- R2: encoding/json struct decoding accepted case variants, so
{"epoch":7,"EPOCH":0} loaded as floor 0. The key check now runs before
decoding and accepts exactly schema, volume_id and epoch, case-sensitive,
none repeated.
Red (66446e0's floor.go and host.go) / green: codex01's two controls;
the stale-replay cases on the primary, supporting and install-replay
paths; uppercase keys, case-folded duplicates in both orders and a
case-folded schema key refuse; canonical epoch 0 stays valid. All 23
G1/G2 tests pass 3/3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* test(G2): red - a promoted host applies the deposed primary's ship
fencing-gaps-todo.md G2, red test first. A real ReplicaListener and the
real Host.applyFact primary path: ship at epoch 1 to listener B, master
promotes B to primary at epoch 2 (a self AssignmentFact), the old primary
ships at epoch 1 again. Today the ship is applied.
Adds the seam the fix uses: Host.SetSelfFence / fenceSelf call the
host's own listener on the primary path (after UpdateReplicaSet, before
OnAssignment) and on the supporting-replica path, and replay an already
adopted role when the listener is installed later (cmd/blockvolume wires
it before Serve). The listener's FenceAsPrimary / AdmitAsReplica are
no-ops in this commit, so the test is red on behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(G2): a new primary fences its own replica listener
fencing-gaps-todo.md G2. The replica listener gets an epoch floor and a
primary flag. FenceAsPrimary(e), called by the host on the primary path
before OnAssignment, sets the floor to at least e and refuses every
replication mutation; AdmitAsReplica(e), on the supporting-replica path,
re-admits replication but keeps the floor. acceptMutationLineage, the
single gate for ship, recovery lane start and rebuild block/done,
applies both. Probes are unchanged.
Green: TestG2_PromotedHostRefusesShipFromDeposedPrimary (real
Host.applyFact primary path + real listener) passes 3/3; new listener
tests: a primary refuses ship / recovery lane start / rebuild but answers
probes; the floor stays after AdmitAsReplica and never goes down.
Ledger: INV-FENCE-SELF-ON-PROMOTE-001.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style(G2): gofmt replica.go field alignment
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(G2): the fence drains replication mutations already past the gate
Review of cc884db (claude03 P2-1, codex01 P1): acceptMutationLineage
released r.mu before the store write, and FenceAsPrimary only flipped
flags, so a deposed-epoch ship or rebuild admitted just before promotion
was applied after the fence returned, while the host served as primary.
Each mutating frame (ship, recovery lane start, rebuild block, rebuild
done, barrier) is now counted under r.mu from before its gate check until
its storage effect is done; its ack is written after it is uncounted, so
the fence never waits on the network. FenceAsPrimary sets primary and the
floor (no new admissions), then waits for the count to reach zero, bounded
(10 s); on timeout it returns an error and the host fails closed: no
OnAssignment, as for an UpdateReplicaSet failure; master redelivers.
Lock order: Host.selfFenceMu -> ReplicaListener.mu, never the reverse;
r.mu is held only for gate state and the counter (Cond.Wait releases it),
never across storage or network calls.
Red (fence without the wait) / green: in-flight controls for ship (direct
and ApplyHook paths) and a rebuild base write fail, then pass 3/3; a
mutation stuck past the bound makes the fence report an error; the host
does not adopt primary when the fence fails.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* docs(protocol): track epoch/fencing gaps G1-G5
Opens a TODO for five fencing gaps found while reviewing the epoch
protocol at b1ff581. G1-G3 are confirmed by reading the code (replica
floor in memory only, new primary does not fence its own listener,
production promotion runs without a required ACK frontier). G4 is a
design decision (no primary lease). G5 needs a test first (caught-up
check has no epoch). Each item has the failure scenario, the proposed
fix, and the red test to write first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(protocol): record the G4 decision (option A, non-claim for alpha/beta)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
- helm-single-node-first-volume-chain: add an emit_provenance phase (product=block,
tested_ref/sha from the image, __block_writer_verified/__block_reader_verified/
__block_first_volume_ok) so the shared scripts/qa-assert.sh accepts the block
bundle the same way as s3/rdma/vfs.
- QA-RUNBOOK-block-current-v1.md: block QA SOP (standard gate / dirty-dev DEBUG /
deep runbook / post-run provenance assertion), block-specific.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
G1-G7 pass (contract review, schema-aware API boundary, delete-safety decision
semantics, cleanup_observed_at freshness, dry-run lifecycle-owner action,
multi-volume isolation, live operator-status status/events-only boundary).
Records the required carry-forward: a full live-apiserver/envtest lifecycle-owner
RBAC/admission gate is still needed before any finalizer mutation can ship.
- add QA sign-off
- add Phase 41 finished plan
- rewrite current-plan as Phase 42 (lifecycle-owner API/admission gate)
- roadmap: mark Phase 41 closed, Phase 42 active
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Package the Kubernetes alpha into a script-based Day-1 activation loop: activate the stack, create the first PVC-backed volume, verify writer/reader data, collect product-owned observation evidence, render a local read-only report, and clean up.
Includes multi-node-safe activation defaults, first-volume example automation, read-only ops report output, README/quickstart/release note updates, and review-driven hardening for fail-fast configuration, promotion evidence, inventory fail-closed behavior, and test guards.
Validated by Day-1 activation run 20260517-205252-04e9 and read-only report run 20260517-212358-bfba. Local targeted tests passed.
Add the light-use operations path for Seaweed Block alpha users.
This includes per-volume status bundles, cluster inventory, product-owned blockvolume lifecycle, durable restart/reattach evidence, same-node alpha placement checks, TestOps control data, and the supporting runner-native gates and QA close reports.
The next active plan is Basic Mounted Failover And Reattach MVP, which carries RF=2/RF=3 recovery work forward without claiming it closed in this milestone.
Adds the beta-hardening test and operations foundation for Seaweed Block, including runner-native protocol/beta gates, CSI lifecycle and durable restart coverage, iSCSI/NVMe protocol release gates, returned-replica evidence, read-only operations status reports, OS initiator compatibility gates, and fast iSCSI L2 durable restart/reconnect coverage.
Close the current protocol-readiness plan and move active work to V2 parity and hardening.
The release gate now covers iSCSI ALUA/failover, NVMe ANA/multipath/failover, CSI protocol selection, and the iSCSI compatibility soak. Test layering is documented so default Go tests stay unit/component scoped, local subprocess tests are opt-in, and Linux lab coverage remains in runner-native TestOps suites.
Replace the marketing-leaning prose with a terser, fact-first README:
status / why this exists / architecture / quick start / repo layout /
development / current limitations / license.
Drops abstract slogans and adjective stacks. Keeps every concrete
command, path, image reference, and limitation that was previously
documented. Net: 362 → 190 lines.
Add a stable Kubernetes app-demo entry point, registry image overrides, a quickstart guide, and copyable basic app PVC examples.
Validated on M02 k3s with writer pod -> same PVC -> reader pod checksum verification.
Adopt a more direct engineering tone (Why build this / The design / How it
compares / What works today / What's NOT claimed). Keeps the load-bearing
honesty bits intact: the four control/data separation invariants, the full
non-claims list, and the complete Quick Start including KUBECONFIG and the
second image import.
Strip T4a/T4b/T4c/T4d, G3+/G5-5/G5-5A/G5-5C/G6/G7-redo, P14/P15, and
"architect round-NN" prose from godoc and in-body comments across the
core/ tree. Preserve stable invariant identifiers (INV-* names) since
they're searchable across the codebase.
Files: core/engine/apply.go, core/host/master/services.go,
core/replication/component/cluster.go, core/replication/probe_loop.go,
core/storage/walstore.go, core/storage/walstore_recovery.go,
core/transport/executor.go, core/transport/replica.go.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pass scope: package doc, struct field docs, --help flag descriptions,
and inline comments. Removes G5-4 / G5-5C / G6 §1.A / G7-redo / G9A /
T2 / T3b / P15 / 'architect ruling' phase prefixes while preserving
the substantive technical content.
Per docs/overview.md: 'If a document is meant for external users,
avoid internal phase or gate labels. Historical design notes should
live in sw-block/design/, not in this public docs entry path.' --help
output and godoc summaries are user-facing surfaces and follow the
same rule.
No behavior change.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hardware-validated diagnosis of the scenario #5/#6 "engine retry/escalate
gap" QA flagged: the bridge's onStart/onClose lambdas in
NewBlockExecutorWithDualLane built SessionStartResult /
SessionCloseResult WITHOUT the ReplicaID field. The engine's
checkReplicaID dropped both events as `wrong_replica` ("event for ,
engine owns r2"), so Session.Phase stuck at Starting forever,
hasActiveSession returned true permanently, and every subsequent
post-completion StartRebuild dispatch was silently suppressed.
This explained QA's pattern: probe r2 success R=0 S=1 H>>0 → engine
correctly classifies as Decision=rebuild (verified by adapter trace
{decision rebuild (R < S)}) but emits zero commands because of the
phase-stuck guard. The peer's runtime state diverged from the engine's
session truth: peer.SetState(Healthy) fires on the executor callback
side (which never checks ReplicaID) but engine.Apply rejects.
Scenario #2 "succeeded" only because peer.SetState(Healthy) is enough
for the harness's wait_until_peer_healthy check; the engine's session
state was already broken at that point. Scenarios #5/#6 needed a
second rebuild and that's where the bug surfaced.
Hardware result post-fix:
G7 #2: dispatch=3s, complete=3s, total=6s — GREEN.
G7 #5: rebuild dispatches in 2s (was: never dispatched). New failure
is at byte-equal verify (498 mismatches over 5500 LBAs) — the
concurrent-writes-during-rebuild seam (T4 wire-fromLSN vs
shipper-anchor split) flagged in v3-rebuild-from-lsn-pin-
clarification §4. Out of scope of this fix.
Adapter diagnostic logs (`g7-debug:`) added in core/adapter/adapter.go
that pinpointed the bug — left in for QA verification of next run.
Will gate them or remove in a follow-up commit once stable.
Anchor: hardware trace g7-20260502T012553Z primary-fail.log line
"trace=[{event SessionStarted} {wrong_replica event for , engine
owns r2}]" — the empty ReplicaID being dropped.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hardware-validated fix for the silent rebuild stall on 40da4c8. Three
coordinated changes that close the gap between unit-test-green and
hardware-completing dual-lane rebuild:
1. **`startRebuildDualLane` — sentinel translation**
Caller passed `fromLSN=0` to the bridge, taken literally by
`WalShipper.StartSession(0)`. On a primary that's been running,
the WAL retention floor is at `checkpointLSN` (entries through
the checkpoint are durable in the extent and the WAL ring has
recycled past 0); `ScanLBAs(0)` immediately returns
`ErrWALRecycled`, the wal goroutine errors, sender exits before
barrier emission, hardware silently stalls.
Fix: pass `sessionFromLSN = targetLSN` (the snapshot pin). Base
lane covers the snapshot through the checkpoint, WAL drain has
nothing to ship at the pin (cursor==head), live writes during
the session flow via NotifyAppend on the steady-state path.
2. **`WalShipper.DrainBacklog` — cursor-caught-up shortcut**
At the dual-lane bootstrap with `cursor == fromLSN == targetLSN
== primary head`, the loop entered ScanLBAs and hit the recycle
gate. Add an early shortcut: if `cursor >= head` at iter start,
skip ScanLBAs and try the R1 transition directly.
3. **`RebuildSession.SeedWalApplied` + receiver wiring**
For a base-only rebuild (WAL drain ships nothing), `walApplied`
stayed at 0; `TryComplete`'s `walApplied >= targetLSN` conjunct
could never hold. Seed it with `fromLSN` at SessionStart so the
predicate satisfies after `MarkBaseComplete` + `WitnessBarrier`.
4. **`executor.go` dual-lane onClose — completion marker**
QA harness `wait_until_rebuild_complete` greps for
`executor: rebuild complete, sent N blocks (targetLSN=N)` —
emitted only by the legacy `doRebuild` path. Mirror it on the
dual-lane bridge's onClose callback so the harness recognizes
completion identically across modes.
Hardware result (G7 #2 — empty replica join, 1000 LBAs):
rebuild dispatched in 1s, completed in 1s after dispatch
(total 2s), 1000 LBAs byte-equal verified post-rebuild.
Markers fired: `barrier prepare ... WalLegOk=true` +
`barrier handshake ... match=true` + peer state
`catching_up → healthy`.
Known seam (out of scope, T4-during-live-writes):
When live writes arrive during the session, the receiver's T4
monotonic checker expects `lsn == appliedWalLSN+1` where
`appliedWalLSN` is seeded to `fromLSN`. Live writes get LSNs
starting at `fromLSN`, breaking T4. Resolving this requires
splitting the wire-fromLSN (T4 expectation) from the
shipper-anchor (DrainBacklog cursor) — separate work. The
hardware harness's scenario #5 (concurrent writes during
rebuild) hits an unrelated probe-loop dispatch issue first
and never gets to exercise this seam.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces the recover(a,b) sole completion gate (`walApplied >=
TargetLSN`) at both Tier-1 sites with the §IV.2.1 realizable conjunct
synthesized from existing observables (ProbeBarrierEligibility witness
+ baseDone + barrier round-trip). Per recover-semantics-adjustment-plan
§1, "session semantically complete" claim moves from replica-side
verdict to coordinator-owned authority on the primary.
Tier-1 sites updated:
RebuildSession.TryComplete (replica, layer-1):
baseDone ∧ walApplied >= targetLSN ∧ barrierWitnessed
PeerShipCoordinator.CanEmitSessionComplete (primary, system close):
phase != Idle ∧ baseDone ∧ achieved >= targetLSN
∧ (walLegOkWitnessed → walLegOkAtBarrier)
Mechanics:
- Receiver latches RebuildSession.WitnessBarrier() on frameBarrierReq
arrival, BEFORE TryComplete. BarrierReq arrival = primary attests
PrimaryWalLegOk under shipMu (§IV.2.1 disjunction).
- Sender records PrimaryWalLegOk witness via
Coordinator.RecordBarrierWalLegOk(walLegOk) immediately after the
ProbeBarrierEligibility snapshot, BEFORE writing frameBarrierReq.
- Bridging-sink path (no probe) leaves walLegOkWitnessed=false; the
conjunct collapses to legacy (back-compat preserved while §IV.2.1
probe wiring is dual-lane-only). Test coverage in
TestRecoverA_BridgingSinkPath_LegacyCollapse pins this.
A-class conformance stubs unskipped (recover_a_conformance_test.go):
A1 TestRecoverA_DebtZeroPath_BarrierEligible SKIP→GREEN
A2 TestRecoverA_LiveTailPath_BarrierEligible… SKIP→GREEN
A3 TestRecoverA_Disjunction_EitherPathSuffices SKIP→GREEN
A4 TestRecoverA_NeitherPath_NotEligible SKIP→GREEN
+ TestRecoverA_BridgingSinkPath_LegacyCollapse GREEN (new)
A4 binding: walLegOk=false witness → CanEmit refuses → sender returns
FailureContract on close. Wire-level emission gating (§IV.2.2 stronger
"MUST NOT be emitted") is the B-class barrierEmitFreeze wave — out of
scope. A-class pins the binding at the close gate.
C-class still SKIP (CheckpointCutSeq on wire, achieved-as-cut-witness).
Y kept as comparator pre-C-class (`achieved >= targetLSN` retained;
"Y as enumerator only" defers to C-class wave).
Whole-tree go test ./... -count=1 green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds Receiver.appliedWalLSN/recvFromLSN tracking and checkMonotonic /
enforceWalWireMonotonic per §IV.0 T4 (recover-semantics-adjustment-plan
§7 v3.28 substrate-mode carve-out).
Behavior:
- SessionStart seeds recvFromLSN=appliedWalLSN=FromLSN.
- Each frameWALEntry runs enforceWalWireMonotonic before ApplyWALEntry.
- RecoveryModeWALReplay: requires lsn == appliedWalLSN+1; gap returns
FailureContract; exact-duplicate / backward returns FailureProtocol.
- StateConvergence (smartwal ScanLBAs): skipped — frontier LSN may
legitimately repeat across many RecoveryEntry payloads.
Tests:
- TestReceiver_checkMonotonic_T4: forward / duplicate / gap / backward.
- TestReceiver_checkMonotonic_boundaryDup: lsn==FromLSN before any
apply is a Protocol failure (not a no-op).
Authored by architect; submitted on user request.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First behavioral wave of the recover(a) migration now that Gate G0 is
closed. OBSERVABILITY ONLY — no completion-predicate replacement,
no semantic change to BarrierReq emission gating. The recover(a,b)
band path stays GREEN as today; this commit adds the §IV.2.1
PrimaryWalLegOk observation tuple and Option B cutID counter so QA's
hardware oracle (§8.2.6) can wire round-trip grep in parallel with
A/B/C-class implementation.
Anti-discipline checks (§8.2.8) honored:
- All 5 marker fields per the §8.2.6 schema (no simplification).
- Conformance stubs in core/recovery/recover_a_conformance_test.go
remain SKIPPED — predicate replacement is the A-class wave.
Substrate changes:
WalShipper (core/transport/wal_shipper.go):
+ firstLiveEmitted atomic.Bool — set on first EmitKindLive emit
(fast-path or post-CASE-A residual); reset on StartSession.
Implements PrimaryLiveTail's per-session monotonic property.
+ ProbeBarrierEligibility() — single-shot snapshot under shipMu
returning (debtZero, liveTail, walLegOk, cursor, head). The
§IV.2(2) guard is simplified at this layer to "ever emitted
Live" — component-layer exercises the real guard.
RecoverySink (core/transport/recovery_sink_adapter.go):
+ ProbeBarrierEligibility delegate — duck-types the
barrierEligibilityProbe interface in core/recovery so the
dual-lane production path can populate marker logs.
PeerShipCoordinator (core/recovery/peer_ship_coordinator.go):
+ barrierAttempt counter on peerShipState — increments per
NextBarrierCut call within a session; resets to 0 at
StartSession (per architect Option B in plan §8.2.6).
+ NextBarrierCut(replicaID) (cutID, error) — first call per
session yields 1; pre-§IV.2.4 wire change this is a
coordinator-local sequence; post-C-class it becomes the
wire CheckpointCutSeq with no log-prefix change.
Sender.Run (core/recovery/sender.go):
+ barrierEligibilityProbe interface (optional, sink-side).
+ Two log lines per BarrierReq round-trip (5 fields each per
§8.2.6 schema):
replication: barrier prepare replica=<id> sessionID=<n>
cut=CCS:<cutID> PrimaryDebtZero=<bool> LiveTail=<bool>
WalLegOk=<bool> cursor=<n> head=<n>
replication: barrier handshake cut=CCS:<cutID>
achieved=<n> match=<bool>
Pre-C-class `match=true` unconditionally — the same cutID
flows from prepare to handshake by construction. Post-C-class
becomes the real wire-vs-engine compare.
+ Markers fire only on the dual-lane production path (sink
implements barrierEligibilityProbe); bridging-sink path
doesn't emit them — pre-§IV.2.1 markers are dual-lane-only
per the §8.2.6 hardware oracle scope.
Tests:
core/transport/probe_barrier_eligibility_test.go (new):
- FreshShipper_DebtZero — at construction, cursor==head==0,
walLegOk via debtZero.
- LiveEmitFlipsLiveTail — fast-path Live emit sets liveTail
monotonically.
- StartSessionResetsLiveTail — per-session monotonic reset
contract.
core/recovery/peer_ship_coordinator_test.go:
+ TestCoordinator_NextBarrierCut_MonotonicPerSession —
first-call-yields-1, monotonic increment, per-session reset
on StartSession-after-EndSession.
What this commit does NOT do (waiting for A-class wave):
- Replace `walApplied >= TargetLSN` predicate in TryComplete.
- Replace `achievedLSN >= targetLSN` in CanEmitSessionComplete.
- Replace Sender.Run's success-path FailureContract on
`achieved < target`.
- Add CheckpointCutSeq to BarrierReq/Resp wire payload.
- Un-skip conformance stubs.
Each of those is its own slice that turns ≥1 conformance stub
SKIP→GREEN as it lands.
Refs: recover-semantics-adjustment-plan.md §8.2 / §8.2.6
(Option B cutID); v3-recovery-algorithm-consensus.md §IV.2.1
(PrimaryDebtZero / LiveTail / WalLegOk); §I P8 (recover(a) vs
recover(a,b)). Companion to the QA→SW handoff commits 599f60e /
a08dea1 / faafa46.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Commit 3 of the QA→SW handoff (`recover-semantics-adjustment-plan.md`
§8.2.7 step 4). Adds 8 SKIPPED red-test anchors covering the three
G0-合同-unblockable categories from §8.2.5; D/E/F deferred until
G0-身份 + G0-wire close per the same section.
File: core/recovery/recover_a_conformance_test.go
Categories landed:
A. PrimaryWalLegOk disjunction (§IV.2.1) — 4 stubs:
- DebtZeroPath_BarrierEligible
- LiveTailPath_BarrierEligibleAfterEverEmittedLive
- Disjunction_EitherPathSuffices
- NeitherPath_NotEligible
B. Lock discipline at BarrierReq emission (§IV.2.2 barrierEmitFreeze)
— 2 stubs:
- BarrierReqUnderShipMu_NoInterleaveWithDriveEmits
(codifies the slice-2B Pillar2B race fix)
- BarrierImminentFlag_FreezesDriveEmits
(Option 3 from architect's lock-discipline trade-off)
C. AchievedLSN as cut-witness, not target-crossing (§IV.2.4)
— 2 stubs:
- AchievedLSN_PerCutWitness
- SuccessWith_AchievedLSN_BelowTarget
(codifies FS-4 reverse from §8.2.3 — Y as enumerator only)
Anti-discipline checks (§8.2.8) honored:
- Every t.Skip carries a reason citing §IV.2.1 / §IV.2.2 / §IV.2.4
+ the unblocking G0 sub-gate; no bare t.Skip.
- No production type imports (stubs only declare Skip; real test
bodies land alongside impl).
- D/E/F categories explicitly NOT included per §8.2.5.
Verified: go test runs the stubs as SKIP entries; commit 1's oracle
table tests still GREEN. The skip messages double as a TODO list
visible to anyone running `go test -v` against core/recovery.
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.5.
Companion to commit 1 (`599f60e` dual-oracle table) and commit 2
(`a08dea1` legacy header annotation).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Commit 2 of the QA→SW handoff (`recover-semantics-adjustment-plan.md`
§8.2.7 step 3). Header-only annotation pass on the 19 _test.go
files in seaweed_block that reference `targetLSN` or `walApplied`
as completion-authority terms (discovery: `grep -rlE
'targetLSN|walApplied' --include='*_test.go' core/`).
Each file gets a 2-line header right after the package decl,
verbatim per §8.2.4:
// Completion oracle: recover(a,b) band — NOT recover(a) closure.
// See sw-block/design/recover-semantics-adjustment-plan.md §8.1.
Six of the 19 are deeply primary.H-bound (assertions tied to
`replica.H == primary.H` or `achieved == primary.H`) and get an
extra `migrate-candidate` line per §8.2.4:
// migrate-candidate: depends on primary.H semantics, see §8.1 Tier-5 migration
The migrate-candidate set:
- core/transport/pillar2_assembled_test.go
- core/transport/pillar3_convergence_test.go
- core/transport/walshipper_pin_protection_test.go
- core/transport/transport_test.go
- core/transport/catchup_sender_test.go
- core/recovery/e2e_test.go
Anti-discipline checks (§8.2.8) honored:
- No assertion changes — header text only.
- migrate-candidate kept on its own line, not merged with the
standard 2-line annotation.
Note on count: §8.2.4 cited "~95 files" against the broader audit
pattern (TargetLSN/AchievedLSN/FrozenTarget/TryComplete). The
narrower §8.2.4 grep (targetLSN|walApplied) targets the actual
completion-authority surface and yields 19 files in the
seaweed_block tree. Build + tests clean post-annotation.
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2.4.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Commit 1 of the QA→SW handoff catalog (`recover-semantics-adjustment-
plan.md` §8.2.7 step 2). Pure-function spec-semantics test, no
production type imports — `RecoverState` + `BarrierWitness` are
test-local data shapes per §8.2.1 (anti-discipline check #3:
oracle test must NOT couple to core/* production types).
What this commit adds:
BandOracle (legacy recover(a,b)):
walApplied ≥ TargetLSN ∧ baseDone
RecoverAOracle (§IV.2.1):
baseDone ∧ PrimaryWalLegOk ∧ BarrierWitness with CutMatch
where PrimaryWalLegOk = (cursor==head) ∨ LiveClassEmitted
8-case counterexample table per §8.2.3:
- 4 sanity rows (both oracles agree)
- 4 CORE rows showing the dual-oracle independence:
FS-1, FS-2, FS-3: Band-true while RecoverA-false
(debt remaining, no barrier, cut mismatch)
FS-4 (reverse): Band-false while RecoverA-true
(Y as enumerator only — walApplied<Y
but LiveTail+barrier hold)
TestRecoverA_DualOracle_MutualIndependence:
Explicit pin that neither oracle implies the other. This is the
minimal expression of the dual-oracle motivation (plan §8.1):
keeping both green-by-each-side without forcing either's
completion authority on the other.
Test status: GREEN — table-driven, no production deps, no I/O.
Becomes the green-1 anchor of the §8.1 four-tier red-green ladder
that sw + QA will extend (commit 3 stubs are A/B/C skipped pending
G0 sub-gates).
Source: sw-block/design/recover-semantics-adjustment-plan.md §8.2
(QA-canonical handoff). The 8-case state vectors + oracle function
bodies are copied verbatim from §8.2.1 / §8.2.2 / §8.2.3 — sw-side
adjustments are gofmt + file-header convention only.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per architect's Path B ruling (2026-04-30), the four §13-era tests
that were skipped during slice-1 are re-authored to §6.3 contracts.
Three pass cleanly; one stays skipped pending deeper integration work.
TestWalShipper_R2_SaturationUnderSustainedLoad
(renamed from TestWalShipper_BacklogStaysBacklog_UnderLoad)
§13-era claim: "mode stays Backlog under saturation". Retired —
§6.3 single drive() collapse removes mode-as-dispatch. Re-authored
to the §6.3 saturation observability contract:
- Slow EmitFunc + pre-seeded substrate (lag ≥ threshold)
- Background writer extends head during scan
- OnSaturation fires single-shot per session
- cursor advances monotonically (INV-MONOTONIC-CURSOR)
- Eventually catches up after writer stops
10× stability locally clean (~5s per run with slow-emit).
TestDualLane_LiveWritesDuringSession_AtomicSeal
Pre-§6.3: per-pusher acceptedSet vs replica.Read; failed ~1/10
runs under §6.3 (concurrent CASE A scans race with producer).
Architect Path B: drop per-pusher cache; assert post-barrier
convergence on backlog + accepted-push LBA range. Cache-data
mismatch can no longer surface; the canonical truth at each
accepted LBA is primary.Read post-barrier.
15× stability locally clean.
TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity
Architect's "DisableTimerDrain + 串行 push" path B variant.
The race surfaced under §6.3 isn't frame-tear; it's a session-
bracket vs in-flight-emit race: drive() emits hold writeMu
briefly per frame, sender's BarrierReq writeMu acquire can
interleave between emits, and receiver may then read the
barrier and return before in-flight push frames arrive. This
is a real §6.3 semantic gap with concurrent push during a
session, NOT a §6.3 correctness bug — the §6.3 model doesn't
bracket per-push barriers (architect's "另开 ADR for per-push
barrier semantics"). Path B explicitly listed serialized
pushes as an acceptable shape: 128 sequential pushes preserve
high-pressure intent without the race.
15× stability locally clean.
TestT4a6_BestEffort_DisconnectThenReassign
STAYS SKIPPED with a more honest §6.3 + walstore-recycle note.
§6.3 auto-fill via substrate (Path B) requires substrate to
retain the entries the new shipper backfills. In this L2
integration test, the second batch's LSNs may be past the
walstore recycle floor by the time the post-reassign shipper
opens with cursor=0; ScanLBAs returns ErrWALRecycled, drive()
treats as transient (cursor stays 0), and CASE B fires with
lsn=61 cursor=0 → tail-gap error. The proper §6.3 contract
here is engine-driven rebuild on WAL-recycled signal, but
that path isn't wired through this test's UpdateReplicaSet
flow. Re-author requires either tuning walstore retention OR
wiring the rebuild-on-recycled escalation; both out of slice-2B
scope. Tracked in §11.9 follow-ups.
5× cross-package sweep (transport / recovery / replication /
replication/component / storage / storage/memorywal /
storage/smartwal) all green post-slice-2B.
Refs: architect Path B ruling 2026-04-30; v3-recovery-algorithm-
consensus.md §6.3 + §6.9 + §11.9. Companion to slice-1 b3826b2,
slice-2A 8672e63.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Architect ruling 2026-04-30: §6.3 normative tail-gap fail-closed
becomes the default. LegacyOutOfOrderEmit defaults to false in
DefaultWalShipperConfig; new code MUST NOT rely on log+drop-gap
behavior. The shipper does NOT silently emit input bytes for a
missing-LSN case; engine MUST escalate to rebuild.
Test migration to §6.3 fail-closed default (sequential cursor+1
LSNs, production-mirror pattern):
- dual_lane_p2d_profile_test: P2d wire-format dispatch tests
used arbitrary lsn=50/200 for distinctness. Changed to lsn=1
(cursor+1 fast-path); wire-format claims (SWRP preamble vs
frameWALEntry, kind tag) unchanged.
- recovery_sink_adapter_test: post-EndSession context-restore
tests used arbitrary lsn=100/9999. Changed to use
shipper.Cursor()+1 dynamic so fast-path fires; rule-2 context-
restore claim is independent of LSN value.
- walshipper_resident_test (3 phase tests): cross-session
NotifyAppends with lsn={1,2,3} mismatched cursor (StartSession
rewinds cursor to fromLSN=0). Changed to dynamic shipper.Cursor()
+1 per phase.
- ship_sender_test (StaleEpoch_SilentDrop): fresh-epoch sanity
Ship with lsn=2 → cursor=0 mismatch under §6.3. Changed to
lsn=1.
- wal_shipper_executor_test (AdvancesCursor): ships at lsn={10,
20, 15} testing cursor-advances claim. Re-authored to lsn={1, 2,
1 idempotent} — production-mirror dense sequence.
- wal_shipper_executor_test (RegistryStableConcurrent): pre-§6.3
used 8×25 concurrent Ships with random LSNs (header itself
flagged "concurrent Ship is NOT production"). Re-authored per
architect Path B ruling: sequential Ship from one goroutine
(with lossless cursor==maxLSN assertion as the §6.3 contract
permits) + concurrent WalShipperFor lookups (the registry-
stability claim). Concurrency stress preserved on the part that
survives §6.3.
5× consecutive cross-package sweep (transport / recovery /
replication / replication/component / storage / storage/memorywal /
storage/smartwal) all green. No flakes.
Production audit (cmd/blockvolume + cluster.go): both use
NewWalShipper → DefaultWalShipperConfig, now Legacy=false. Production
flow inserts NotifyAppend(lsn==cursor+1) per primary's WAL append
chain — fast-path fires, no tail-gap reachable. If a tail gap ever
surfaces under load (network drop / shipper bug), the engine sees
the error and escalates to rebuild — the explicit §6.3 contract.
Refs: architect ruling 2026-04-30 (Path B + Legacy=false default);
v3-recovery-algorithm-consensus.md §6.3 + §6.9 NEGATIVE-EQUITY.
Companion to slice-1 b3826b2.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Refactors WalShipper's dispatch from mode-dispatched (NotifyAppend +
drainOpportunity as separate entry points with mode-keyed bodies) to
the consensus §6.3 single drive(input) function. NotifyAppend +
drainOpportunity become thin wrappers that offer input{has:true,...}
or input{has:false} respectively.
Dispatch (drive holds shipMu for the whole call — single serializer
per peer):
Idle (mode == ModeIdle): drop everything.
Fast-path (in.has + in.lsn == cursor+1 + head <= in.lsn):
Tail-emit input bytes as EmitKindLive. Preserves Realtime hot
path observability — cursor monotonic + no debt + input is the
next LSN means input bytes are canonical-equivalent to substrate;
no scan needed.
CASE A (cursor < head, debt-first per §6.3):
Substrate is canonical. Scan from cursor, emit each entry as
EmitKindBacklog, advance cursor; loop until cursor == head OR
scan exits. Per consensus §13 alignment, this is BACKLOG-DRAIN
semantics even when invoked from a NotifyAppend caller —
"Realtime is reading substrate?" is a misread; the wire kind tag
is Backlog, the dispatch is debt-first. R1 transition runs at the
tail of CASE A under shipMu.
Idempotent skip (in.lsn <= cursor after CASE A): drop.
CASE B (caught up + fresh tail, in.lsn == cursor+1):
Tail-emit input as EmitKindLive.
Tail-gap (in.has + in.lsn > cursor+1 + cursor == head):
Per §6.3 / §6.9 NEGATIVE-EQUITY ban — input MUST NOT replace a
missing LSN. Default fail-closed; engine MUST escalate to
rebuild. LegacyOutOfOrderEmit=true (transitional, see below)
restores pre-§6.3 log+emit.
Config delta:
+ LegacyOutOfOrderEmit (DEPRECATED, transitional):
True restores pre-§6.3 "log + emit input on tail gap"
behavior. Slice-1 default = true (transitional bridge — zero
behavior change for existing callers); slice-2 will flip to
false (§6.3 normative). Documented in field doc + DefaultWal
ShipperConfig comment.
StrictRealtimeOrdering (existing): semantically subsumed by
§6.3 tail-gap fail-closed. Both strict and non-strict (with
Legacy=false) now fail-closed at tail-gap. Kept for production
wiring expressivity; field doc updated.
CONVENTION block at file top: this implementation tracks `cursor` as
LAST-EMITTED LSN; spec §6.3 uses `cursor` as NEXT-TO-EMIT. Translation
in code: spec.cursor == internal.cursor + 1; the check `lsn ==
cursor+1` is identical to spec's `lsn == cursor`. Documented inline
on drive() so reviewers don't flip the bit.
Test migration (3 tests skipped with §6.3-migration notes; will be
re-authored against the new model in a separate slice or removed if
their pre-§6.3 contract is fully retired):
- TestT4a6_BestEffort_DisconnectThenReassign: asserted that a
degraded peer + reassign does NOT silently catch up the
suppressed batch. §6.3 default is automatic substrate-fill on
reattach — pre-§6.3 "best-effort = no auto catch-up" contract is
superseded. Skipped.
- TestWalShipper_BacklogStaysBacklog_UnderLoad: asserted that
Backlog mode persists while writer outpaces drain. §6.3 single
drive() runs CASE A scan to completion under one shipMu acquire;
R1 fires when caught up; Backlog mode is no longer load-bearing
in dispatch. Skipped.
- TestDualLane_LiveWritesDuringSession_AtomicSeal +
TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity: concurrent
pushers race against each other's CASE A substrate scans; the
end replica state is byte-equal-primary post-barrier in the
common case, but the per-pusher acceptedSet vs replica-Read
direct comparison surfaces stragglar LBAs in ~1/10 runs. The
atomic-seal contract holds; the test shape needs re-authoring
to assert replica == primary (which is the same claim AtomicSeal
intended without per-pusher tracking). Skipped.
Updated test (re-authored against §6.3, kept passing):
- TestWalShipper_R2_LagSignalFires: pre-§6.3 the test could pump
1000 NotifyAppends in Backlog mode (lag-only) and observe lag
accumulate. Post-§6.3, NotifyAppend with lsn==cursor+1 takes
fast-path tail emit; cursor advances; lag stays at 0. The new
R2 test pre-seeds substrate (head advances without triggering
drive), then a single trigger NotifyAppend invokes drive() →
CASE A scan whose first emit's updateLag observes lag ≈ 1000 ≥
threshold 500 → OnSaturation fires single-shot. Same INV pinned;
different reach.
5× full cross-package sweep (transport / recovery / replication /
storage) all green — no flakes observed.
Out of scope (slice 2):
- Flip LegacyOutOfOrderEmit default to false (§6.3 normative).
- Migrate skipped tests to §6.3 contracts (or retire them).
- Address the concurrent-pusher race semantics surfaced in
AtomicSeal/Pillar2B at the design level — likely a per-LBA
write barrier on the dual-lane path is the right answer; needs
architect call.
- OpenWALScan stateful iterator (§12.4 #8).
Refs: v3-recovery-algorithm-consensus.md §6.3 send(input,debt) +
§6.9 HOPE-SHIPPER-MONOTONIC + §13 ModeRealtime alignment + §6.10
INV-RECV-* (receiver-side, already landed in 055fd46).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
smartwal isn't in core/storage/contract_test.go's implementation
matrix (intentional — the experimental subpackage stays
self-contained per its own test header), so the §6.10 BASE bypass
contract was unverified at the smartwal-named level after
055fd46. This test mirrors TestContract_WriteExtentDirect against
the smartwal substrate directly.
Asserts:
- WriteExtentDirect succeeds, Read returns bytes (smartwal reads
always pull from extent — the ring is not consulted)
- Frontier (H, nextLSN) NOT advanced (BASE has no LSN; ring NOT
touched)
- Subsequent ApplyEntry shadows correctly via writeAt's normal
extent overwrite + ring append
- Substrate-level: WriteExtentDirect after ApplyEntry IS allowed
to overwrite — pins that bitmap arbitration is the receiver's
job, not the substrate's. Prevents a future "let's silently
dedupe at substrate" change from quietly subverting §6.10.
Refs: v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE);
mini-plan §11.8 receipt for 055fd46; closes the smartwal coverage
gap noted in the SW status report.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
§6.10 BASE bypass (commit 055fd46) made base lane fast enough that
the original Pillar 2 C wire-abort test became race-prone:
sometimes the entire session — base + WAL + barrier round-trip —
completed before the test's "close every accepted conn" code path
fired, leading to Success=true when the test expected Success=false.
Reproduced as ~3/20 fail rate after the §6.10 change.
Switch the failure mechanism from "close conn mid-session" (timing-
dependent) to faulty-read substrate (deterministic): the same
faultyReadStorePillar2 used by Pillar 2 A. Read fails after 4
successful base-block reads → streamBase returns Substrate failure →
bridge onClose → OnSessionClose with Success=false. No wire timing
involved.
The semantic claim of the test is unchanged: prove that a session
which fails on the failure path triggers rule-2 emit-context restore.
Pre-session SnapshotEmitContext returns (nil, zero, SteadyMsgShip)
on a fresh replica; post-session snapshot must equal pre-session.
That assertion is preserved.
What's no longer in scope here:
- Mid-session network drop / replica crash specifically — this
test no longer claims to exercise that path. Future "real
network drop" coverage would need a controllable wire-fault
listener (test-infra follow-up); slice-1 deferred wire-tap
helper covers the same cost-of-test-infra slice.
Stability: 20 consecutive runs of TestPillar2C alone, 5 consecutive
full-transport-suite runs, all green post-fix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Implements consensus §6.10 (INV-RECV-BITMAP-CORE / INV-RECV-WAL-NAIVE):
BASE lane writes go directly to extent, bypassing the LSN-tracked WAL
apply path entirely. The receiver's per-session bitmap is the sole
arbiter of BASE-vs-WAL conflict at this LBA; substrate stale-skip is
irrelevant for BASE because BASE never enters the WAL.
Substrate contract delta (LogicalStorage):
+ WriteExtentDirect(lba uint32, data []byte) error
Writes one block's bytes to the substrate's extent. No LSN. No
frontier (R/S/H) advancement. Substrate stale-skip / WAL apply
machinery NOT invoked. Receiver pairs with AdvanceFrontier in
MarkBaseComplete to keep post-rebuild frontier reporting honest.
Implementations:
- BlockStore — write to in-memory blocks map; nextLSN/walHead
untouched.
- memorywal — append a record with LSN=0 sentinel; no
retention/nextLSN advance. Receiver bitmap
discipline keeps semantics correct (BASE only
reaches substrate when WAL hasn't touched LBA).
- WALStore — wraps existing private writeExtent; pwrites to
extent file, no WAL append, no dirty-map entry.
- smartwal.Store — pwrites directly to extent at lba's offset; ring
NOT touched, no LSN/frontier advance.
RebuildSession changes:
- ApplyBaseBlock now calls store.WriteExtentDirect(lba, data) instead
of store.ApplyEntry(lba, data, targetLSN). The targetLSN-as-base-LSN
POC compromise (which silently rode substrate stale-skip) is gone.
- MarkBaseComplete now calls store.AdvanceFrontier(targetLSN) — the
explicit frontier-advance that ApplyEntry's side effect previously
provided implicitly. Pre-§6.10, BASE applies bumped walHead per
LBA; now we make the bump explicit at base-done.
Contract test (TestContract_WriteExtentDirect): pins
- WriteExtentDirect succeeds and Read returns the bytes
- Frontier (H) and nextLSN MUST NOT advance (BASE has no LSN)
- Subsequent ApplyEntry at LSN > 0 shadows the BASE bytes
runs against BlockStore-mem / WALStore / MemoryWAL.
Refs: v3-recovery-algorithm-consensus.md §6.10 (INV-RECV-BITMAP-CORE,
INV-RECV-WAL-NAIVE); §6.3 cursor-monotonic sender invariant; mini-plan
§12 design-candidate doc-track.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Non-blocking improvements landed before slice-2:
1. AchievedLSN assertion. Was log-only; now asserts
res.AchievedLSN == post-session primary.H, which is
frozenTarget + len(overwrites) by construction. Tighter than
"achieved >= target" — catches a SessionLive frame that
silently didn't apply (achieved would lag) or barrier ack
drifting past the actually-shipped tail.
2. Convergence assertion now compares replica.Read(lba) against
primary.Read(lba) directly (replica == primary), not just
against the cached bRefs payload. Defence-in-depth: if a
future receiver bug diverges from primary in a way that
"happens to" still match the cache, the primary-direct
comparison catches it. bRefs check retained as test-internal
sanity that the live-write payload itself wasn't dropped.
3. Comment fix: "5× locally" → "10 consecutive runs" to match
what the stability check actually did.
4. Companion-SHA list in the file header now lists cf232f2
(this slice itself) alongside Phase 0 / C3 / Pillar 2
commits — easier blame.
10× consecutive runs deterministic post-polish; cross-package
sweep (transport / recovery / replication) all green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mini-plan §11.7 pillar 3 (receiver-side convergence): when the same
LBA is touched by both the backlog (WAL ≤ targetLSN) AND a live
write during the session (WAL > targetLSN flushed at seal), the
replica's final state matches the higher-LSN write. AtomicSeal and
Pillar 2 B both use disjoint LBA ranges (push window > base window),
so neither asserts the arbitration claim.
Single subtest in core/transport/pillar3_convergence_test.go:
TestPillar3Slice1_ReceiverConvergence_LiveOverwritesBacklog_SameLBAs
- Seed primary with 12 LBAs (LBA 0..11, pattern A_i). Sync,
primaryH=12.
- StartRebuild with frozenTarget=12.
- After OnSessionStart: live-overwrite LBA {3, 5, 7} with pattern
B_i (LSN 13/14/15 > frozenTarget → SessionLive path).
- After barrier: untouched LBAs (0,1,2,4,6,8,9,10,11) → seed A;
overwritten LBAs (3,5,7) → live B.
The discriminating assertion is on the overwritten LBAs: a receiver
without proper wire-ordering or apply-order arbitration could leave
those LBAs at A. Convergence to B for all three captures the
INV-PILLAR3-SAMELBA-CONVERGENCE invariant. Verified deterministic
across 10 consecutive runs.
In-scope (slice-1):
- Transport stack only (NewBlockExecutorWithDualLane + real
RecoverySink + runDualLaneListener + real receiver).
- Single arbitration assertion across multi-LBA seed + overwrites.
Out of scope (deferred):
- Full engine/cluster path (component.Cluster.DriveAssignment +
DriveProbeResult) — slice-2 territory.
- §IV T2 (architect-open at consensus §IV) — this slice asserts
barrier semantics under a frozen target only.
- RF > 1, long-duration soak.
- Wire-level frame tap with explicit LSN-monotonicity proof —
convergence here is asserted via post-barrier replica reads;
frame integrity remains transitive (any torn frame → receiver
decode fail → session.Success = false).
Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 3 (receiver
convergence). Companion to 11392ba / eb4071e / cc457c0 / ceac3bf.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mini-plan §11.7 pillar 2: same fault dimensions as C3 fault-injection,
but on the manager-assembled stack (BlockExecutor + PrimaryBridge +
real RecoverySink + recovery.Sender + resident WalShipper +
PeerShipCoordinator under unified replicaID). C3 used a spy
WalShipperSink and net.Pipe; this slice exercises the same robustness
through TCP + real receiver.
Three sibling tests in core/transport/pillar2_assembled_test.go:
A — TestPillar2A_BaseError_AssembledStack_FailReason
faultyReadStorePillar2 wraps the primary; Read fails after 4
successful base-block reads. Asserts: OnSessionClose Success=false
with FailReason wrapping the synthetic error; coord.Phase back to
Idle (EndSession defer ran); replica.R < primary.H (recovered
frontier never reached the target — barrier never fired).
B — TestPillar2B_LiveWrites_HighPressure_BarrierIntegrity
Sibling to TestDualLane_LiveWritesDuringSession_AtomicSeal with
different focus: larger backlog (300 entries) + more pushers
(16 × 8 = 128 attempts) for genuine writeMu contention; stricter
convergence (replica.H == primary.H exactly post-barrier — not
asserted by AtomicSeal). Frame integrity is asserted transitively
through Success=true: any torn frame would fail receiver decode.
Documents wire-tap as a future test-infra follow-up.
C — TestPillar2C_WireAbortMidSession_AssembledStack_RestoresEmitContext
Production-equivalent abort: peer drops connection mid-session
(network failure / replica crash) — startRebuildDualLane uses
context.Background, so wire close is the closest analog to C3's
ctx-cancel test. Snapshots the resident WalShipper's pre-session
emit context, aborts mid-session, asserts post-session snapshot
equals pre (rule-2 restore). Plus: OnSessionClose with FailReason,
coord.Phase=Idle.
What's intentionally out of scope:
- Wire-level frame tap with explicit decode + LSN-monotonicity
(current tests prove integrity transitively).
- Pillar 3 (receiver convergence with live writes during session,
bitmap/barrier interaction, T2 hardware soak).
- streamBase ctx-awareness (C3 #2B variant — separate follow-up).
Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 2; architect
sign-off "A+B+C 一个 commit"; Phase 0 unified replicaID (11392ba).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three table-shaped subtests covering the failure paths of Sender.Run's
BASE ∥ WAL goroutine pair (§6.8 #6 / P6 / G3). Companion to the
existing TestC3_BaseWalParallel_FramesInterleave (happy path /
overlap claim).
#1 BASE error → WAL exits via groupCtx.Done
Faulty store fails primaryStore.Read after N reads; streamBase
returns a Substrate failure; groupCancel from BASE goroutine
unblocks DrainBacklog parked on ctx; spy sink confirms
drainCtxErrSeen != nil; lifecycle counters StartSession=1,
EndSession=1; Run returns within 2s.
#3 Outer ctx cancel → both lanes wind down
Caller cancels parent ctx mid-session after WAL goroutine has
entered DrainBacklog. Run returns within 2s; coord.EndSession
defer fires (Phase back to Idle); sink.EndSession defer fires
exactly once; DrainBacklog observed ctx cancellation.
#2A WAL error → Run terminates (variant A — narrow)
Spy sink returns synthetic error from DrainBacklog. BASE
goroutine runs to completion (small store; streamBase is not
ctx-aware). Run returns the WAL failure with PhaseBacklog;
errors.Is unwraps to the synthetic; lifecycle counters correct.
NOT asserted: prompt BASE stop on WAL failure. streamBase has
no ctx-check today; variant B (future follow-up) would pair a
periodic groupCtx.Err() check inside streamBase's loop with a
strict prompt-stop assertion. Test header documents this.
Spy WalShipperSink: structural-typing match (no exported types added);
records StartSession / DrainBacklog / EndSession call counts; per-test
drainBehavior selects immediate / block-until-ctx / synthetic-error.
Refs: v3-recovery-wal-shipper-mini-plan.md §11.7 pillar 2 (dual-line
execution); architect-recommended scope #1 + #3 + #2A.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The component harness (cluster.go) constructed dual-lane executors
with rid="r-%d" while the engine driver in dual_lane_engine_test.go
sent AssignmentInfo / ProbeResult under "replica-%d". Pre-Phase-0-
Fix-#1 this silently diverged: bridge keyed coord.PinFloor under
"r-N", sink keyed WalShipper writeMu + post-emit RecordShipped under
"replica-N". The rebuild barrier completed despite the keying
mismatch (replica-driven BarrierResp), so the bug stayed invisible.
Now that startRebuildDualLane fail-closes on a mismatched non-empty
construction RID (commit 11392ba), this drift surfaces as a hard
error in TestDualLane_EngineDrivenRebuild_HappyPath / _WithPushLive
DuringSession. Aligning the harness to the engine driver's
"replica-%d" convention restores the invariant: construction RID ==
engine arg, coord/sink/bridge all keyed identically.
Test assertions that probed the stale "r-0" key (lines 110, 197, 251
region) updated to "replica-0".
Refs: INV-RID-UNIFIED-PER-SESSION (commit 11392ba);
v3-recovery-execution-institution.md Phase 0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
INV-RID-UNIFIED-PER-SESSION: the engine arg replicaID is the single
source of truth for keying coord / WalShipper / sink / bridge for a
recovery session. Pre-fix, startRebuildDualLane built the RecoverySink
with the engine arg but called bridge.StartRebuildSessionWithSink with
the construction-time dl.ReplicaID. If the two diverged, the post-emit
hook keyed coord.RecordShipped under arg while the bridge keyed
coord.PinFloor under dl.ReplicaID — the keys never reconciled, no
error fired, watchdog timed out long after.
Fix:
(a) Fail-closed assert at session entry: non-empty dl.ReplicaID must
equal recovery.ReplicaID(arg). Empty stays permissive (legacy /
test omission; arg flows through unchanged).
(b) Thread argRID through to bridge.StartRebuildSessionWithSink so
coord and sink key uniformly under arg from this point on.
Tests (core/transport/replicaid_unified_test.go):
- TestPhase0Fix1_DriftRejected_FailsClosedAtEntry: non-empty drift
returns error before any wire activity; coord.Phase Idle under
both IDs; OnSessionStart/Close never fire.
- TestPhase0Fix1_HappyPath_ArgEqualsConstructionID: aligned IDs,
full rebuild, frontier converges, coord returns to Idle.
- TestPhase0Fix1_EmptyConstructionRID_ArgFlowsThrough: empty
construction RID bypasses guard; arg keys both bridge and sink;
coord lifecycle observed under arg, never under empty key.
Refs: v3-recovery-execution-institution.md "Entity layering &
assembly contract" Phase 0; v3-recovery-wal-shipper-mini-plan §11.6.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Architect code-review caught comment/code mismatch: docstring above
drainOpportunity still said "Realtime mode: if cursor < head, scan
to fill the gap" — but the implementation correctly returns early
when mode != ModeBacklog (matches consensus §13 E-WALSHIPPER-DUAL-
MODE / mini-plan §11.2a / T4a no-replay carve-out).
Risk this doc-debt prevented: future contributor reads the stale
comment, "fixes" the function to scan in Realtime, re-introduces
the silent-divergence bug C2 closed (Realtime substrate scan would
replay dead-window writes when peer comes back online).
Comment now states the dual-mode contract explicitly with a
DO-NOT-ADD-A-REALTIME-BRANCH warning citing §13 / T4a / CHK-
WALSHIPPER-TIMER-DRAIN's ModeBacklog scope.
No code logic change.
go test all four packages — PASS.
Architect review (offline against §6.8 / §IV / §V) flagged two
correctness gaps in C1+C2+C3:
1. NotifyAppend Realtime missing the §6.8 #9 sequence invariant
(lsn == cursor + 1). Without it, a caller that drops a
notification or races would silently emit out-of-order LSNs
leaving permanent gaps on replica (T4a no-replay carve-out
means no self-healing in Realtime).
2. drainOpportunity TOCTOU: mode/cursor read under shipMu, then
shipMu released before head.Head(). A concurrent NotifyAppend
(Backlog lag-only) could shift state between the unlock and
the head read.
Also two architect-derived doc tightenings:
3. DisableTimerDrain inline doc now states production MUST leave
false (§6.8 #4 forbids primary-idle starvation); test-only
invariant: shipper MUST NOT linger in cursor < head without
alternative drain source.
4. walShipperEntry.writeMu lock hierarchy doc: shipMu → writeMu,
never reverse.
Fixes:
- WalShipperConfig.StrictRealtimeOrdering (default false): tier
selector per architect's "production fail-close vs minimum log
+ monitor" guidance. Default mode logs WALSHIPPER-OUT-OF-ORDER
warning + emits anyway (preserves pre-guard test compatibility);
strict mode returns explicit error (production opt-in once
engine drives rebuild-on-gap).
- drainOpportunity now reads mode + cursor + head under one
shipMu hold (consistent snapshot), then releases for the heavy
ScanLBAs call. Eliminates the TOCTOU window.
Tests:
+ TestC1_Realtime_OutOfOrder_StrictFailsClosed — strict mode
rejects lsn != cursor+1 with explicit error. Banned regression
anchor: the old `if lsn > cursor + 1 ... drain` check (the
dense-edge counterexample architect flagged).
- Existing tests preserved by non-strict default mode. Engine-
driven dual-lane PushLiveWrite test + T4a6 reassign test now
log warning during the brief race window but emit + pass.
Existing test renamed:
- TestC1_WriteMu_NoInterleave → TestC1_WriteMu_FramesWellFormed
(concurrent-NotifyAppend was unrealistic; production callers
serialize per-replica via volume.mu; real concurrent-writer
coverage lives in TestDualLane_LiveWritesDuringSession_AtomicSeal).
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component}
— all PASS.
Production migration path (separate work):
- Engine wires StrictRealtimeOrdering=true once peer churn /
UpdateReplicaSet drives rebuild-on-gap (re-anchors WalShipper
cursor for the new endpoint).
- Fix replicaID consistency in startRebuildDualLane (engine
replicaID vs dl.ReplicaID — currently sink uses one, bridge
coord uses the other).
Architect review of C1+C2+C3 (offline against §6.8 / §IV / §V) flagged
two doc gaps that should be inline in the code, not just PR descriptions:
1. DisableTimerDrain (wal_shipper.go WalShipperConfig):
- PRODUCTION MUST leave false. §6.8 #4 is MUST: "primary-idle
starvation forbidden". Setting true in production violates
architect contract.
- Test-only invariant: shipper MUST NOT linger in cursor < head
without alternative drain source. Today's only users are R2
saturation tests (scope-bounded).
2. Lock hierarchy (executor.go walShipperEntry.writeMu):
- shipMu → writeMu (always; reversal risks deadlock).
- WalShipper holds shipMu; calls EmitFunc under it; EmitFunc
acquires writeMu.
- recovery.Sender.writeFrame acquires only writeMu (does not
hold shipMu). Order is consistent: shipMu outermost when both
in play.
No code logic change; documentation tightening so future readers
can verify §6.8 mechanical SINGLE-SERIALIZER without re-deriving
from grep.
go test all four packages — PASS.
Architect §6.8 #6 BASE ∥ WAL WALL-CLOCK OVERLAP: extent/base bulk
SHOULD overlap WAL drain where product permits (reduces wall-clock
pin exposure). Pre-C3 Sender.Run ran streamBase fully before
sink.DrainBacklog — strictly serial.
Sender.Run now spawns two goroutines:
Base goroutine: streamBase → frameBaseDone → coord.MarkBaseDone
WAL goroutine: sink.StartSession → sink.DrainBacklog
Both share writeMu via C1 (sink's WriteMu() duck-typing). Frame
integrity preserved by mutex-bounded interleaving on the wire —
two writers never interleave bytes within a single frame. Wall-
clock benefit comes from CPU/IO overlap (substrate scans, encoding,
small base-block writes).
Coordination:
- groupCtx with cancel; first failing goroutine cancels to
unblock the other (in particular DrainBacklog observes ctx).
- Both error channels collected; first non-nil error returned.
- Barrier writes after both goroutines complete (errgroup-Wait
pattern via two channels).
Note on physical reality: shared writeMu means base waits on slow
WAL writes (and vice versa). This is correct serialization. Hard
SLO on base under bursty WAL would need a separate credit channel
(out of scope §6.8 #6 strict reading; see consensus §6.8 note).
Test:
+ TestC3_BaseWalParallel_FramesInterleave — receiver-side capture
parses sender's wire stream into a frame sequence; asserts at
least one frameWALEntry appears BEFORE the last frameBaseBlock
in that sequence (interleaved progress, not strictly base-
then-WAL). Verified: firstWAL index << lastBase index.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS.
C1+C2+C3 close §6.8 nine MUSTs:
✓ #1 SINGLE-SERIALIZER (C1: shared writeMu)
✓ #2 ONE TAPE (single shipMu + cursor; substrate is canonical)
✓ #3 PRIORITY (C2: drain in cursor order during Backlog)
✓ #4 TIMER (C2: self-driving Backlog drain)
✓ #5 FRAMING ≠ SECOND TAPE (P2d: profile selects encoder, not tape)
✓ #6 BASE ∥ WAL (C3: errgroup goroutines)
✓ #7 R1 (existing: assertCaughtUpAndEnableTailShipLocked)
✓ #8 R2 (existing: OnSaturation single-shot per session)
✓ #9 send(·,·) consistency (C2: NotifyAppend + drain dispatch)
Architect review of ad7bc74 against §6.8 / consensus v3.8 nine
MUSTs: two correctness fixes — concurrency safety (writer race) +
accounting (missing RecordShipped on WalShipper-routed path).
§6.8 #1 SINGLE-SERIALIZER (mechanical):
walShipperEntry adds writeMu sync.Mutex.
EmitFunc holds it during conn.Write.
recovery.WalShipperSink gains optional duck-typed sub-interface
`interface{ WriteMu() *sync.Mutex }`. transport.RecoverySink
implements it via e.WalShipperWriteMu(replicaID).
recovery.Sender.NewSenderWithSink: duck-types the sink; if WriteMu()
present, sender.sharedWriter = sink.WriteMu(). writeFrame uses
sharedWriter when set, falling back to its own writerMu otherwise.
Result: in dual-lane sessions, Sender.writeFrame (SessionStart /
BaseBlock / BaseDone / BarrierReq) AND EmitFunc (frameWALEntry)
serialize on the same per-replica entry mutex. No more interleaved
header/payload from two concurrent writers on the same conn.
Steady (Ship) path uses entry's own writeMu uncontended (only Ship
writes the legacy port).
Accounting (post-emit RecordShipped):
walShipperEntry adds postEmit func(lsn uint64). EmitFunc fires
outside writeMu after a successful conn.Write.
WalShipperSink gains optional sub-interface
`interface{ SetPostEmitHook(func(lsn uint64)) }`.
RecoverySink implements via e.SetWalShipperPostEmitHook.
recovery.Sender.Run: at session start (after defers), checks if
sink supports SetPostEmitHook; if so, installs
func(lsn) { coord.RecordShipped(replicaID, lsn) } and clears
via defer at session end.
Result: each successful WalShipper-routed emit (Backlog scan or
Live NotifyAppend) advances coord.shipCursor in lockstep with
emit. Pre-C1 the dual-lane path silently left shipCursor at
fromLSN; future code that depends on the cursor (BacklogDrained,
TryAdvanceToSteadyLive, observability) was latent-broken.
Tests:
+ TestC1_WriteMu_SharedAcrossSenderAndWalShipper — sink.WriteMu()
and executor.WalShipperWriteMu return same mutex address.
+ TestC1_WriteMu_NoInterleave — concurrent NotifyAppend emits
parse cleanly as a sequence of well-formed recovery frames
(no header/payload interleave detected).
+ TestC1_PostEmitHook_AdvancesShipCursor — full dual-lane rebuild
completes cleanly; replica frontier reaches primaryH; coord
returns to Idle. Exercises the post-emit hook on every shipped
LSN without panic / hook misuse.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS, no regressions.
Companion: sw-block design mini-plan §11.2 / §11.3 (commit 058305225
on seaweedfs/feature/sw-block).
Pins the user-stated architectural invariant:
Steady: WalShipper handles NotifyAppend (recv) + emit (peer).
Recovery session: pin floor PROTECTED at fromLSN so substrate WAL
retention can't recycle entries the session still needs.
Pin advances via FEEDBACK: replica BaseBatchAck → recovery.Sender
readerLoop → coord.SetPinFloor → pin advances; substrate may
now recycle below the new floor.
Session end: pin released.
Tests:
+ TestPin_ProtectedDuringSession_AdvancesViaFeedback_ReleasedOnEnd —
full single-replica lifecycle:
1. coord.StartSession → pin = fromLSN
2. RecoverySink.StartSession → WalShipper Backlog;
pin still = fromLSN (shipper mode change must NOT move pin)
3. coord.SetPinFloor(replica, ackLSN, S) — simulates
readerLoop's BaseBatchAck translation; pin advances
4. Out-of-order lower-LSN ack: pin must NOT regress
5. RecoverySink.EndSession → shipper Realtime;
pin survives (sink.EndSession is shipper-side, doesn't
release coord pin)
6. coord.EndSession → pin released to 0
+ TestPin_MultiSession_MinPinAcrossActiveSessions — cluster-wide
invariant: WAL retention gated by min pin across all active
sessions. Slow replica's pin floors the whole cluster; fast
replicas advancing past it don't unlock recycling. After all
sessions end, anyActive=false and no floor is enforced.
Together these confirm the user's architecture: WalShipper-side
mode transitions and coord-side pin lifecycle are orthogonal —
sink.EndSession ≠ session-pin-release; only coord.EndSession
releases. Production callers (recovery.Sender.Run defer) call BOTH
on every exit path, which is what the existing wiring already does.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 2 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pins the algorithmic invariant the user named in §10 framing:
WalShipper 常驻; recovery 时是 Backlog; 追平后仍在同一实例上变成
Realtime, 再接 steady 的 NotifyAppend.
One resident WalShipper per (volume, replicaID); steady ship and
recovery sessions share the SAME instance; mode transitions are
internal to the shipper; the recovery session is just a bracket
(StartSession / EndSession) around it.
Tests:
+ TestWalShipper_Resident_SameInstanceAcrossSessions —
INV-SINGLE: WalShipperFor returns the same instance during
and after multiple consecutive RecoverySink-bracketed sessions
on the same replica.
+ TestWalShipper_Resident_ModeTransitionsAcrossSessions —
pins the cycle: Realtime → (StartSession) → Backlog →
(DrainBacklog R1) → Realtime → (EndSession) → Realtime,
repeatable across consecutive sessions.
+ TestWalShipper_Resident_SteadyShipBetweenSessions — full
timeline: steady NotifyAppend → recovery session 1 → steady
NotifyAppend → recovery session 2 → steady NotifyAppend.
Recording EmitFunc captures all emits; verifies the three
steady-phase emits use steady lineage (rule 2 holds across
multiple bracket cycles).
+ TestWalShipper_Resident_NotifyAppendDuringSession_BacklogMode —
while a session holds the shipper in Backlog mode, concurrent
steady NotifyAppend calls are lag-only (no emit). After
EndSession, post-session NotifyAppend emits normally under
restored steady context. Pins the mode-decision boundary.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 4 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three failure-mode tests pinning clean teardown across the full
StartRebuild → bridge → Sender → wire stack:
+ TestDualLane_ReplicaListenerStopped_BeforeRebuild — listener
closed before dial; StartRebuild surfaces the dial error
synchronously; coordinator never advances past Idle (session
never registered).
+ TestDualLane_ReplicaListenerStopped_MidSession — listener
accepts and immediately closes the conn (no Receiver behind it);
Sender's first writeFrame fails with Wire failure; OnSessionClose
fires Success=false; coordinator returns to Idle via Sender.Run's
deferred coord.EndSession; PrimaryBridge's senders entry torn
down (subsequent PushLiveWrite returns "no active session").
+ TestDualLane_SubsequentRebuild_AfterFailure_Succeeds — regression:
after a failed rebuild teardown, a fresh rebuild on the same
replica with a healthy listener succeeds end-to-end. Verifies
registry / coordinator state is genuinely cleaned, not just
dead-but-still-occupying-slots.
This pins the deferred-EndSession contract at the integration level:
no matter how Sender.Run exits (success, wire error, ctx cancel),
both sink.EndSession and coord.EndSession fire — observable as
PrimaryBridge sender-map cleanup + coordinator Idle.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 3 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes the test gap the recovery package's e2e_test.go disclaimed at
the dual-lane (cross-process-shape) level: live writes pushed via
PrimaryBridge.PushLiveWrite during an active dual-lane rebuild
session, exercising senderBacklogSink.flushAndSeal's atomic-seal
boundary on the real TCP wire.
Tests:
+ TestDualLane_LiveWritesDuringSession_AtomicSeal — full chain:
StartRebuild → engine→adapter→executor (dual-lane) → bridge →
Sender.Run → streamBacklog (100 backlog LBAs) + flushAndSeal +
barrier; concurrently 8 workers × 5 = 40 pushers via
bridge.PushLiveWrite. Asserts the atomic-seal contract:
every push that returned nil MUST be byte-equal on replica.
Verified: 40/40 pushes accepted, all on replica.
+ TestDualLane_LiveWritesDuringSession_AchievedLSN — sanity
lower bound: achievedLSN >= frozenTarget after backlog drain.
+ TestDualLane_PushLiveWrite_NoSession_Errors — bridge guard:
PushLiveWrite without an active session returns an explicit
"no active session for replica" error.
Substrate: memorywal on primary so live writes get LSN > frozenTarget
and streamBacklog filters them for flushAndSeal to ship as
WALKindSessionLive (BlockStore's walHead-synthesized LSN would have
collapsed all backlog entries past targetLSN under concurrent
primary.Write). Replica stays BlockStore.
This is G7 §2 #4 (concurrent writes during rebuild) in scope as the
architect ratified — the dual-lane bridging path now has end-to-end
coverage of that scenario, independent of P2d.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (no regressions; 3 new tests).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two parallel-safe wiring helpers that don't lock in the dual-lane
wire-body format (P2d still architect-gated) but unblock the
production wiring sequence so the format swap, when it lands, is
mechanical.
transport.BlockExecutor.SnapshotEmitContext(replicaID):
- Accessor that returns the per-replica WalShipper's current
(emitConn, emitLineage) under emitCtxMu — same lock discipline
as production EmitFunc.
- Honest signal when no entry exists: returns (nil, zero) so
callers can pass through to NewRecoverySink as the steady-
restore values without a special case.
- Canonical caller pattern (P2d-post): snapshot BEFORE
constructing RecoverySink → pass to NewRecoverySink as the
steady context → EndSession's rule-2 restore lands the right
values.
recovery.PrimaryBridge.StartRebuildSessionWithSink(...):
- New entry point that accepts an external WalShipperSink (e.g.,
transport.RecoverySink wrapping the per-replica WalShipper).
- Existing StartRebuildSession unchanged — continues to use the
bridging senderBacklogSink path (legacy compatible).
- Internal startRebuildSessionLocked is shared between the two
public methods; switches between NewSenderWithBacklogRelay and
NewSenderWithSink based on whether sink is nil.
- Fail-closed: nil sink → explicit error (callers that want the
bridging path call StartRebuildSession explicitly).
Tests:
+ TestSnapshotEmitContext_NoEntry_ReturnsZero
+ TestSnapshotEmitContext_AfterUpdate_ReturnsCurrent
+ TestSnapshotEmitContext_ThenRecoverySink_RestoresCaptured —
end-to-end of the canonical wiring pattern: snapshot → build
sink with snapshotted steady → run session → assert restored
context matches snapshot.
+ TestPrimaryBridge_StartRebuildSessionWithSink_NilRejected
+ TestPrimaryBridge_StartRebuildSessionWithSink_InvokesSinkLifecycle —
sink receives StartSession + DrainBacklog + EndSession in order
when invoked through the bridge's public surface.
+ TestPrimaryBridge_StartRebuildSession_StillUsesBridgingSink —
regression: legacy entry point still installs senderBacklogSink.
go test ./core/recovery/ ./core/transport/ ./core/replication/{,component} —
all PASS (incl. existing test suite, no regressions).
Production enable still requires P2d (wire body format / applier
owner / replay source). These helpers are "ready but not switched
on" — calling StartRebuildSessionWithSink today would produce a
wire-format mismatch on the dual-lane port (executor's EmitFunc
encodes MsgShipEntry; recovery.Receiver decodes frameWALEntry).
The §10 decision request on seaweedfs/feature/sw-block resolves
that.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three doc-only follow-ups from architect code review of 845c810
(non-blocking; no logic changes):
1. NewRecoverySink — explicit caller obligations:
- Defer EndSession at the StartSession call site so a
StartSession error path still restores steady context
(recovery.Sender.Run already does this; production callers
using NewRecoverySink directly must too).
- nil sessionConn = programmer error (Realtime emits would have
nowhere to go). nil steadyConn = honest only when no steady
ship was in flight; next steady emit fails closed at EmitFunc.
2. installRecordingShipper (test helper) — TEST-ONLY /
single-goroutine note. The entry.shipper assignment bypasses
walShipperMu deliberately; production paths take that mutex.
Don't lift the pattern into production or concurrent tests
without re-introducing the lock.
Test suite unchanged; go test ./core/transport/ -run TestRecoverySink
still PASS (6/6).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pre-decision parallel work for P2d (per architect ratification): the
transport-side adapter that satisfies recovery.WalShipperSink by
duck typing, plus integration tests that pin architect P1 review
rules 1+2. No wire-format branching — the adapter inherits whatever
EmitFunc executor.WalShipperFor wired in. P2d resolves MsgShipEntry
vs frameWALEntry; this adapter survives that decision either
unchanged (if "unify on MsgShipEntry") or via swap of the underlying
shipper construction (if "use frameWALEntry on dual-lane port" or
envelope tag).
RecoverySink:
- NewRecoverySink(executor, replicaID, sessionConn/Lineage,
steadyConn/Lineage)
- StartSession: updateWalShipperEmitContext(session) BEFORE
WalShipper.StartSession (rule 1)
- DrainBacklog / NotifyAppend: thin delegate
- EndSession: WalShipper.EndSession FIRST, then
updateWalShipperEmitContext(steady) (rule 2)
Tests (lifecycle ordering only — no wire decode):
+ TestRecoverySink_StartSession_InstallsSessionContext —
direct post-condition, white-box check on entry.emitConn /
emitLineage after StartSession returns.
+ TestRecoverySink_DrainBacklogEmits_UseSessionContext —
rule 1 indirect: install recording EmitFunc; assert every
backlog drain emit captures session context. Stale context
would surface immediately on the first drain emit.
+ TestRecoverySink_EndSession_RestoresSteadyContext —
rule 2 direct: post-EndSession entry context == steady.
+ TestRecoverySink_NotifyAppendAfterEndSession_UsesSteadyContext —
rule 2 indirect: post-EndSession Realtime emit captures
steady context at emit time.
+ TestRecoverySink_FullLifecycle — combined ordering across
StartSession → DrainBacklog → EndSession → post-session
NotifyAppend; each phase's emits use the expected context.
+ TestRecoverySink_SatisfiesWalShipperSink — compile-time
duck-type check via locally re-declared interface (no
recovery import to keep cycle-free option open).
Recording EmitFunc strategy: replace per-replica WalShipperEntry's
shipper with a fresh one whose EmitFunc reads emitConn/emitLineage
under emitCtxMu (same lock discipline as production) and records
into a slice. This captures the at-emit-time context — the only
honest evidence of rule-1 / rule-2 ordering without coupling to
wire format.
go test ./core/transport/ ./core/recovery/ ./core/replication/{,component} —
all PASS (incl. existing test suite, no regressions).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Buffer state moves into senderBacklogSink (sinkMu / queue / sealed
fields, flushAndSeal method); Sender no longer owns any live-write
scaffolding. Sender.Run flow becomes:
StartSession → BaseLane → BaseDone → sink.StartSession →
sink.DrainBacklog → barrier → return
DrainBacklog (in the bridging sink) does scan + flushAndSeal +
seal atomically — sender.Run barriers as soon as it returns.
There is no engine "go barrier" signal anymore; the previous
sender.Close / closeCh / FinishLiveWrites pattern is gone.
Atomic-seal contract migrates from sender.drainAndSeal (queueMu)
to senderBacklogSink.flushAndSeal (sinkMu): NotifyAppend that lands
before the seal lock is captured + shipped; pushes after see
"sink sealed" error. EndSession is the defer-safety net (idempotent
seal so post-Run NotifyAppend still gets explicit error).
Deleted from Sender:
- Close(), closeCh, closeOnce
- queueMu, liveQueue, sealed, walItem
- drainAndSeal, bufferLiveWriteLocked
- PhaseAwaitClose
Deleted from PrimaryBridge:
- FinishLiveWrites (engine→sender "go barrier" signal no longer
needed — barrier auto-fires after DrainBacklog)
Updated:
- transport/rebuild_sender.go: drop FinishLiveWrites call
- sender.Run defer: just sink.EndSession + coord.EndSession
- failure.go: remove PhaseAwaitClose
Tests rewritten per architect rule 3 (delete scaffolding once e2e
cases that inject mid-session writes pass barrier convergence
through the new path):
e2e_test.go:
- 5 sender.Close() calls removed
- TestE2E_RebuildWithLiveWritesDuringSession: push live writes
BEFORE sender.Run starts — sink buffers under sinkMu until
flushAndSeal ships them
- TestE2E_KindCountsPinsBacklogVsLive: substrate switched to
memorywal (preserves write-time LSN) so push-before-Run
preserves LSN > frozenTarget filter discipline; BlockStore's
walHead-synthesized LSN would have shifted under push-before
- TestE2E_PushLiveWriteAtomicSeal: race window is now between
pushers and sink's flushAndSeal seal point; contract holds
integration_stub_test.go:
- TestIntegrationStub_LifecycleCallbacks: drop FinishLiveWrites
- TestIntegrationStub_CtxCancelUnblocksSender: skipped — no
idle wait window to cancel into post-B-2
- TestIntegrationStub_FailureTypedOnCancellation: skipped —
same reason
sender_walshipper_sink_test.go:
- TestSenderBacklogSink_NotifyAppend_BuffersForFlushAndSeal:
white-box accessor now reads sink's queue (was sender's)
- var _ WalShipperSink = &senderBacklogSink{} (pointer receiver)
- TestSender_WithSink_DelegationOrder: drop sender.Close;
Run barriers autonomously after DrainBacklog returns
Verified: all recovery (incl. 5 e2e) + transport + replication +
replication/component tests PASS. Net deletion: -175 lines.
Note: dual-lane frameWALEntry vs MsgShipEntry alignment remains
P2d. The bridging senderBacklogSink stays as the in-package sink
until then; once a real transport.WalShipper sink replaces it,
the buffer + flushAndSeal scaffolding here goes too.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add NotifyAppend(lba, lsn, data) error to WalShipperSink interface.
Sender.PushLiveWrite now routes through s.sink.NotifyAppend instead
of touching liveQueue directly — the sink owns buffering / ordering
discipline.
Bridging path (senderBacklogSink) implements NotifyAppend by
buffering into the sender's liveQueue under queueMu — production
discipline (architect rule 2). streamBacklog is one-shot ScanLBAs;
direct wire emit during the scan would interleave LSNs and break
the receiver's monotonic-LSN check, so the buffer + ordered
drainAndSeal flush stays as the safety net until P2d aligns the
dual-lane wire format.
When P2d swaps in a real transport.WalShipper sink, NotifyAppend
will route to WalShipper.NotifyAppend (Backlog mode lag-tracking;
Realtime direct ship under shipMu) — at that point the queueMu /
liveQueue / drainAndSeal scaffolding can be deleted (slice B-2).
Tests:
+ TestSender_PushLiveWrite_RoutesViaSinkNotifyAppend — RED→GREEN,
pins the routing contract (incl. error propagation from sink).
+ TestSenderBacklogSink_NotifyAppend_BuffersForDrainAndSeal — pins
the bridging-path buffer discipline.
recordingSink in tests gains NotifyAppend + snapshotNotifyAppend.
Verified:
- go test ./core/recovery/ — all PASS, including 5 e2e tests
(PushLiveWriteAtomicSeal exercises mid-session writes and
barrier convergence end-to-end).
- go test ./core/transport/ ./core/replication/{,component} — all PASS.
Note: dual-lane frameWALEntry vs MsgShipEntry alignment remains P2d;
backlog relay continues as the bridging sink until then.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Slice A (mechanical, dead-code removal):
- NewSenderWithSink panics on nil sink (was: silent promote to legacy)
- NewSender → private newSender (only used by sink-installing
constructors as builder)
- Run() drops the `if s.sink != nil { ... } else { legacy }` split;
sink path is unconditional. INV-NO-DOUBLE-LIVE at recovery layer
is now a structural guarantee (one emit path, not a runtime check)
- TryAdvanceToSteadyLive call site removed (kickoff Q3 collapsed
Phase enum to {Idle, Active}; barrier-ack is the completion
signal)
Kept for slice B per architect framing:
- Close, drainAndSeal, liveQueue, sealed, closeCh, queueMu, walItem
- PushLiveWrite (still feeds session-lane tails until live writes
route through WalShipper.NotifyAppend)
- streamBacklog (called by senderBacklogSink.DrainBacklog)
Tests:
+ TestNewSenderWithSink_NilSinkPanics — locks sink-mandatory contract
- TestSender_NoSink_FallsBackToLegacyBehavior — replaced by panic test
go test ./core/recovery/ ./core/transport/ — all PASS.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sender's WAL pump now flows through a sink in P2b too — but via a
backlog-relay adapter that keeps the same frameWALEntry wire
behavior as legacy streamBacklog. This keeps the receiver path
(decoder + RebuildSession.ApplyWALEntry on dual-lane port) untouched.
Real rewind / transport.WalShipper integration is P2d (which also
wires the dual-lane / receiver decoding alignment).
Why a relay-not-real-WalShipper for P2b:
Recovery's receiver consumes frameWALEntry on the dual-lane port.
transport.WalShipper writes MsgShipEntry on the executor's legacy
port. Plugging transport.WalShipper directly into recovery.Sender
in P2b would mean wire-format mismatch + receiver dispatch break.
The intentional shim is `senderBacklogSink` (DrainBacklog →
streamBacklog) — sink-shape API, same wire bytes.
Changes:
sender.go:
+ senderBacklogSink — adapts streamBacklog() to WalShipperSink:
StartSession / EndSession are no-ops (real rewind stays in
transport.WalShipper for P2d); DrainBacklog calls the existing
streamBacklog() in-place.
+ NewSenderWithBacklogRelay(primary, coord, conn, replicaID) —
constructs sender with senderBacklogSink{s: s}. Used by all
existing e2e + integration callers in P2b.
Sink-mode Run() flow: after sink.DrainBacklog returns nil, the
legacy `<-closeCh` wait + drainAndSeal still run so
PushLiveWrite session-lane entries (the existing test
scenario that injects post-target writes) keep converging.
P2c can move session-live into NotifyAppend once transport
WalShipper is wired.
NewSenderWithSink doc updated to reflect the closeCh + drainAndSeal
retention until P2c.
e2e_test.go:
All NewSender(...) → NewSenderWithBacklogRelay(...). No assertion
changes; same e2e shape, sink-mode path now exercised end-to-end.
integration_stub.go:
PrimaryBridge uses NewSenderWithBacklogRelay so the
bridge-shaped lifecycle (StartRebuildSession + PushLiveWrite +
FinishLiveWrites) still works through the sink branch.
sender_walshipper_sink_test.go:
+ TestSender_WithSink_DelegationOrder: spawns a goroutine that
`sender.Close()` after `<-sink.drainCalledCh` so sink-mode
Run unblocks past the closeCh wait and reaches sink.EndSession +
barrier path (otherwise drainCalledCh never fires).
+ TestNewSenderWithBacklogRelay_installsRelaySink: smoke test
that the new constructor installs senderBacklogSink and the
type satisfies WalShipperSink (compile-time check).
Lint fix: remove sync/atomic copy from earlier scaffolding.
Header comments clarified for P2 stage progression.
Test sweep:
go test ./core/recovery/... → all PASS (legacy path + sink path
both exercised; e2e tests now run via the relay sink).
go test ./core/transport/... → all PASS (no transport changes
in P2b).
go test ./core/replication/... ./core/replication/component/...
→ all PASS.
Roadmap note (architect-aware):
P2c — make sink required; delete legacy NewSender pump (streamBacklog
+ closeCh + drainAndSeal + PushLiveWrite + liveQueue + sealed
+ queueMu + walItem + Close). Sink-mode Run is already the
future shape; legacy path is deletable when no caller relies
on Close + drainAndSeal.
P2d — wire transport.WalShipper into recovery.Sender by aligning
wire format (dual-lane vs legacy port) at receiver decoding.
Then NewSenderWithBacklogRelay can be retired in favor of
NewSenderWithSink(real walShipperAdapter). Transport-layer
integration tests for architect rules 1+2 (updateContext
before StartSession; restore after EndSession) land here.
Per v3-recovery-wal-shipper-mini-plan.md §3 P2 — "Drain API wired
from recovery.Sender; delete/disable recovery/sender duplicate
pump". P2a is the smallest green-on-merge step: introduce the
sink, make Sender accept it as OPTIONAL, branch Run() based on
presence. P2b/c migrate existing tests + delete legacy pump.
Architect 2026-04-29 P1 review ratification: "Proceed with P2 TDD
as you outlined, and keep these two integration rules explicit
in tests:
1. updateWalShipperEmitContext(replicaID, sessionConn,
sessionLineage) before StartSession.
2. After EndSession, restore whatever lineage conn Ship will
use, or the next steady emit will use stale recovery
lineage on the wire."
Rules 1 + 2 are caller obligations and live in transport (P2d).
P2a establishes the SINK interface contract that those rules
plug into.
WalShipperSink interface (core/recovery/sender.go):
type WalShipperSink interface {
StartSession(fromLSN uint64) error
DrainBacklog(ctx context.Context) error
EndSession()
}
Lives in core/recovery to avoid import cycle (transport
imports recovery for ReplicaID etc.). transport.WalShipper
satisfies it via duck typing.
Boundary docstring spells out architect rules 1+2 as caller
obligations; Sender does not enforce them.
Sender constructor:
NewSender(...) — legacy path (sink == nil; Run uses
streamBacklog/closeCh/drainAndSeal).
P2c removes this path.
NewSenderWithSink(..., sink) — sink-mode path (Run delegates).
Defensive: nil sink promotes to
NewSender so behavior is predictable.
Run() branching:
if s.sink != nil:
defer s.sink.EndSession() // always-cleanup defer FIRST so
// it fires on every exit path
// (success, StartSession err,
// DrainBacklog err, barrier err).
s.sink.StartSession(fromLSN)
s.sink.DrainBacklog(ctx)
// skip TryAdvanceToSteadyLive (kickoff Q3 collapse:
// {Idle, Active}; barrier-ack is the only completion signal)
else:
// LEGACY: streamBacklog → closeCh wait → drainAndSeal →
// TryAdvanceToSteadyLive (P2c removes)
Failure mapping for sink errors:
sink.StartSession err → FailureContract @ PhaseBacklog
sink.DrainBacklog err (ctx) → FailureCancelled @ PhaseBacklog
sink.DrainBacklog err (other) → FailureSubstrate @ PhaseBacklog
Test (TDD, sender_walshipper_sink_test.go):
TestSender_WithSink_DelegationOrder
- recordingSink mock captures call order
- Run sender (with deliberately non-converging setup so test
doesn't depend on barrier success)
- Assert: sink.callOrder = [StartSession, DrainBacklog, EndSession]
- Assert: startCalls/drainCalls/endCalls all 1 (always-cleanup)
- Assert: fromLSN argument forwarded to sink.StartSession
Other sink-test scaffolds (NoSink_FallsBackToLegacy,
WithSink_DelegatesStartSession, WithSink_EndSessionAlwaysCalled,
WithSink_StartSessionFailureAborts, WithSink_NoStreamBacklog
Reachable) marked t.Skip — they will be filled in as P2b/c
delete the legacy path and provide the e2e harness for sink-
driven WAL pump.
Test infrastructure:
recordingSink — mock with mutex-guarded call log; also has
shipDuringDrain hook + drainBlocksUntil channel
for P2b's e2e tests where the sink does pump
WAL via the test wire.
Test deadlock fix (caught during impl):
receiver returning error didn't close replicaConn → sender's
readerLoop blocks forever reading. Fixed by closing replicaConn
immediately after receiver.Run returns in the test goroutine.
Documented in test comments.
Test sweep:
go test ./core/recovery/ -run "TestSender_WithSink_DelegationOrder"
→ PASS (0.00s).
go test ./core/recovery/ ./core/transport/ -count=1
→ all PASS (no regression on legacy path, including existing
e2e tests that still use NewSender / sender.Close /
PushLiveWrite — those keep working in P2a).
Next:
P2b — migrate existing e2e tests (TestE2E_RebuildHappyPath etc.)
to NewSenderWithSink + a real walShipper / passthrough
sink. Required before P2c.
P2c — make sink required; delete streamBacklog, drainAndSeal,
PushLiveWrite, liveQueue, sealed, closeCh, queueMu,
walItem, Close.
P2d — transport-layer integration tests for architect rules
1 (updateContext before StartSession) and 2 (restore
after EndSession). Wire BlockExecutor.startRebuildDualLane
to call updateWalShipperEmitContext + walShipper.StartSession.
Architect P1 review (2026-04-29 of commit 0d3e379) found 4 items.
This commit fixes#1, #2, #3 + adds #4 doc note. All required before
P2's recovery.Sender wiring trusts the same EmitFunc for backlog
emit.
#1 (P2 SHOWSTOPPER): encoding seam moved INTO EmitFunc.
Before: Ship() pre-encoded payload via EncodeShipEntry, passed
encoded bytes as `data` to NotifyAppend. EmitFunc just did
`WriteMsg(conn, MsgShipEntry, data)`.
Hidden bug for P2: when DrainBacklog calls `s.emit(e.LBA, e.LSN,
e.Data)` with e.Data = raw substrate bytes from ScanLBAs, NOT
pre-encoded ShipEntry, EmitFunc would WriteMsg garbage. Replica's
MsgShipEntry handler would fail decode. Architect: "wiring
recovery to this same EmitFunc without encoding in or before emit
will ship garbage on rebuild/catch-up".
After: EmitFunc owns EncodeShipEntry. WalShipper hands raw
`(lba, lsn, data)` tuples; EmitFunc encodes per-call using
walShipperEntry.emitLineage. Both steady (Ship) and backlog
(P2 DrainBacklog) feed the SAME EmitFunc shape — one encoding
seam, one wire frame type.
Implementation:
- walShipperEntry adds emitLineage RecoveryLineage field.
- WalShipperFor's EmitFunc reads lineage from entry under
emitCtxMu, calls EncodeShipEntry inside.
- updateWalShipperConn renamed to updateWalShipperEmitContext;
now sets BOTH conn AND lineage atomically.
- Ship() passes RAW data (block bytes), NOT pre-encoded payload.
Future P2: recovery.Sender's session-installer calls
updateWalShipperEmitContext with session lineage before
walShipper.StartSession. After session ends, restores steady
lineage. SAME EmitFunc handles both flows.
#2: TestBlockExecutor_StableUnderConcurrent_Ship test scope
clarified.
Architect: "cursor == maxLSN does not prove no lost emits — if
goroutines finish out of LSN order, Realtime's idempotent-skip
drops lowers while cursor still ends at maxLSN".
Renamed: TestBlockExecutor_WalShipperRegistry_StableUnderConcurrent_Ship
Test now explicitly pins:
- INV-SINGLE registry stability under concurrent Ship load.
- cursor advanced from 0 (some Ship landed).
- cursor ≤ maxLSN (sanity bound).
And explicitly does NOT pin:
- "all 200 LSNs reach the wire" — that's lossless-emit
semantics, requires production-mirror serialized Ship pattern
(held under volume.mu in production via OnLocalWrite).
Belongs to P2 e2e where serialized Ship matches production.
Comment block at top of test calls out architect P1 review #2
as the rationale.
#3: ordering invariant for updateWalShipperEmitContext documented.
Architect: "every code path that can emit must refresh conn
context the same way Ship does (or centralize 'resolve conn
then notify')".
Added explicit invariant doc on updateWalShipperEmitContext:
"every code path that ends in an emit (steady Ship, future
recovery-session backlog DrainBacklog, future Activate) MUST
refresh this context BEFORE the call that may emit. Otherwise
EmitFunc emits with stale lineage / nil conn".
#4: registry lifecycle TODO documented.
Architect: "walShippers is never torn down when a peer goes
away with new session/conn semantics. Probably fine for MVP;
watch replica churn / InvalidateSession".
Added doc note: walShippers entries are never torn down today;
P3+ may add Forget(replicaID) hook for replica churn / lineage
invalidation / executor reuse. Out of scope for MVP since
current call sites construct one BlockExecutor per
(volume, replica) lifecycle.
Test sweep:
go test ./core/transport/ -count=1 → all PASS (including the
renamed test with weaker but honest assertions).
Wider sweep (transport + recovery + storage + replication +
replication/component): all PASS.
Net effect: P2 (recovery.Sender thin) can now plug DrainBacklog
into the SAME walShipper that Ship() uses, with EmitFunc handling
encoding for both. The "5th time wrong pump" risk is materially
lower.
Per v3-recovery-wal-shipper-mini-plan.md §3 P1, with TDD discipline
(tests first, impl drives by failing tests):
Tests written first (wal_shipper_executor_test.go, RED phase):
TestBlockExecutor_WalShipperRegistry_GetOrCreate
spec §3 INV-SINGLE — WalShipperFor idempotent get-or-create;
different replicaIDs get distinct instances; concurrent calls
for same replicaID linearize through walShipperMu.
TestBlockExecutor_Ship_AdvancesWalShipperCursor
Ship() delegates to per-replica WalShipper. Observable via
cursor advancing per Ship call. Idempotent Ship with lsn ≤
cursor (NotifyAppend's idempotent-skip path) does NOT regress
cursor.
TestBlockExecutor_WalShipperFor_StableUnderConcurrent_Ship
Strong INV-SINGLE under load — 8 writer goroutines × 25 Ships
each (200 distinct LSNs) all funnel through the same shipper
instance; cursor reaches max LSN.
3a coverage (architect 2026-04-29 ratification): "仅 Ship 只走
WalShipper (mock transport)". Mock here is net.Pipe with
io.Copy(io.Discard, replicaConn) — Ship's wire writes succeed,
test asserts on cursor advancement (the delegation observable).
3b deferred per architect to nightly: "Sender + Ship integration
冒烟" (cross-component INV-NO-DOUBLE-LIVE). Will be added when
P2 wires recovery.Sender to call walShipper.StartSession /
DrainBacklog (replacing its own streamUntilHead).
Implementation (driven by failing tests):
core/transport/executor.go:
+ walShipperMu sync.Mutex
+ walShippers map[string]*walShipperEntry
+ walShipperEntry struct { shipper *WalShipper; emit conn ctx }
+ WalShipperFor(replicaID) *WalShipper — get-or-create; on
create, the EmitFunc closes over entry.emitConn (mu-guarded
pointer that Ship updates per-call)
+ updateWalShipperConn(replicaID, conn) — Ship's per-call
hook to set the conn the EmitFunc will use
core/transport/ship_sender.go:
Modified Ship():
- Lineage validation + epoch fence + lazy dial: UNCHANGED.
- After conn resolved + payload encoded: delegate to
WalShipperFor + updateWalShipperConn + NotifyAppend.
- The walShipper's EmitFunc does the WriteMsg under shipMu
(INV-NO-DOUBLE-LIVE at the wire path).
No behavior change for callers: Ship's signature, return
semantics (silent-drop on stale epoch, error on dial/write
failure, nil on success) all preserved.
Architectural notes:
- WalShipper.Activate(0) at first WalShipperFor — Realtime mode
immediate. First Ship's lsn > 0 emits cleanly.
- emitConn is mutable per-Ship: caller's session conn may change
over time (lazy dial, session re-attach). EmitFunc reads under
entry.emitCtxMu so mutations are visible.
- Idempotent NotifyAppend (lsn <= cursor) returns nil silently;
Ship caller can't distinguish from successful emit. Acceptable
for fire-and-forget contract.
Test sweep (TDD GREEN):
go test ./core/transport/ -run "TestBlockExecutor_(WalShipper|Ship_)"
→ 3 PASS, 0 FAIL.
Wider sweep:
go test ./core/transport/ ./core/recovery/ ./core/storage/...
./core/replication/component/ ./core/replication/
→ all PASS — no regression in existing executor / recovery /
storage / replication tests.
LOC delta:
+ executor.go ~70 LOC (registry struct + WalShipperFor +
updateWalShipperConn)
~ ship_sender.go ~10 LOC change (delegate via NotifyAppend)
+ wal_shipper_executor_test.go ~250 LOC (3 tests)
Next: P2 — recovery.Sender drops streamUntilHead/PushLiveWrite/
drainAndSeal; calls walShipper.StartSession + DrainBacklog
instead. TDD again, write tests first against the new
"recovery.Sender does NOT own WAL pump" contract.
Architect 2026-04-29 P0 review: signed off, two doc-vs-impl mismatches
to fix + one dead-code cleanup. All comment / dead-field changes; zero
behavior change.
(1) EmitFunc docstring (line ~46-48):
Was: "Returning an error transitions WalShipper to Backlog (or
stays Backlog if already there) and aborts the current emit"
Reality: NotifyAppend in Realtime returns the error AS-IS;
mode does not flip; cursor is NOT advanced for the failed
emit. Degraded decision belongs to executor/engine.
Fix: docstring now accurately describes propagate-and-don't-flip
semantic. Prevents next reader from "fixing" wal_shipper.go
to flip to Backlog on emit error (which would be wrong per
spec — degraded is upstream's call).
(2) sessionActive struct field comment (line ~154-155):
Was: "EndSession returns to Idle"
Reality: EndSession sets sessionActive=false + mode=Realtime
(NOT Idle). Mode goes to Idle ONLY at NewWalShipper ctor;
no API path returns to Idle from non-Idle once Activate
or StartSession has run.
Fix: docstring describes actual transition; flags Idle as
ctor-only state.
(3) stopBacklog field — dead code:
Was: chan struct{} created in StartSession, closed in
EndSession, but no goroutine ever reads from it.
DrainBacklog uses ctx for cancellation; stopBacklog is
unreferenced.
Fix: deleted the field + StartSession's make + EndSession's
close. Architect option was "comment as P2-reserved OR
delete"; deleted to match architect's "dead code is worse
than missing code" principle. If P2 (or any future
backlog-goroutine refactor) needs it, it'll be added then.
R2 test concurrency note (architect 2026-04-29):
`OnSaturation` callback uses `t.Errorf` from non-test goroutine.
P0 stress (count=20, multiple 1-second runs) is clean; future
hardening could use channel + main-goroutine assert. NOT
required for P0 merge per architect; logging here so reviewer
knows it's a known soft spot.
Test sweep:
go test ./core/transport/ -run "TestWalShipper_" -count=1 → all
PASS (10 PASS + 1 SKIP for RegistrySingleton P1 placeholder).
Memories saved (cross-conversation rules from this round):
feedback_lsn_from_allocator_not_boundaries.md — never derive
"LSN of this Write" from Boundaries(); use Write's return.
feedback_tdd_when_spec_locked.md — when spec is normative, write
conformance tests FIRST against spec § references; impl-first
is the pattern that caused 3 recovery-component rewrites.
Next: P1 — BlockExecutor registry + Ship delegate. TDD again.
Per architect 2026-04-29 review of g7-redo/wal-shipper-impl:
Q1a (INV-SUBSET fromLSN+1 anchoring):
TestWalShipper_DeliveredEqualsCursor — replaced "expected LSN 1..head"
with explicit `fromLSN+1, ..., head` derivation. fromLSN=0 still in
this case (so first emit IS LSN 1) but assertion is now general:
future variants with fromLSN > 0 work without rewriting test logic.
Q1b (CursorMonotonic seed/fromLSN alignment):
Earlier seed (LSN 1..5) + fromLSN=10 had `head < fromLSN` — an edge
that exposes R1 bugs but doesn't pin INV-MONOTONIC-CURSOR cleanly.
Changed seed to LSN 1..15 so head=15 ≥ fromLSN=10, giving DrainBacklog
a real range (10, 15] to ship. Assertions strengthened: post-drain
cursor==head, idempotent NotifyAppend with lsn<cursor doesn't regress.
Q1c (BacklogStaysBacklog_UnderLoad err loosening):
Spec §5.3 normative content is "R1 must not fake-Realtime under
saturation"; whether DrainBacklog returns nil or non-nil at ctx
deadline is impl choice. Removed strict `drainErr != nil` Fatal,
removed errors.Is check; primary contracts (mode != Realtime AND
cursor < head) stay as Errorf. drainErr now logged as observation.
Q3 (R1_DoubleCheckRejectsRace fixedHeadSource):
Replaced HeadSourceFromStorage + sleep-until-cursor≥8 heuristic
with explicit fixedHeadSource control. Substrate Write happens
BEFORE head bump (atomicity: any scan after the bump sees LSN 11
in substrate). NotifyAppend after bump covers race-lost-the-window
branch (R1 already flipped → realtime emit).
Q4 (R2 single-shot per session — already correct):
Test asserts `fired ≤ 1` per session. Architect ratified per-session
single-shot; cross-session re-fire works because StartSession
resets saturationFired flag. Spec §6 line for "default per-session
at most once; cross-session can re-fire" is architect's edit
(separate from this commit).
TEST BUG FOUND DURING `go test` (architect-prompted "fix-then-code"):
6 sites used `lsn, _, _ := primary.Boundaries()` which captures R
(syncedLSN, FIRST return value), not H. memorywal.Boundaries returns
`(R, S, H)`; only Sync() advances R, so concurrent NotifyAppend after
Write got stale lsn=preSyncedLSN, hit the idempotent-skip path
(`lsn <= cursor`), and live writes during session vanished.
Fixed by using primary.Write's RETURNED lsn directly:
- Old: _, _ = primary.Write(lba, data)
lsn, _, _ := primary.Boundaries()
- New: lsn, _ := primary.Write(lba, data)
6 fix sites: R1_NoGapAtTransition (line 396), NoDoubleLive (566),
R2_LagSignalFires (627), R2_NoSpuriousSignal (669),
BacklogToRealtime_Happy (717), BacklogStaysBacklog_UnderLoad (786).
Two tests went from RED → GREEN purely via this test bugfix:
- TestWalShipper_R1_NoGapAtTransition: was cursor=102 want 200;
now cursor=200 == finalHead, all 200 LSN in emit log.
- TestWalShipper_BacklogToRealtime_Happy: was emit count=10 want
11; now 11 emits (10 backlog + 1 realtime LSN 11).
Other tests passed coincidentally because their assertions don't
depend on the lsn parameter to NotifyAppend being correct (e.g.,
R2 tests count fired hooks, not exact LSN sequences).
IMPLEMENTATION (wal_shipper.go) is unchanged — no behavior bug
surfaced. Tests had the bug; spec-driven discipline still worked
(failing tests forced inspection that found the test bug, not a
silent green-on-bad-impl).
Test results:
go test ./core/transport/ -run "TestWalShipper_" -count=1 → all
PASS (10 PASS + 1 SKIP for RegistrySingleton P1 placeholder)
go test ... -run "R1_NoGap|R1_DoubleCheck|NoDoubleLive" -count=20
→ no flake under stress (architect Q3 alternate gate; -race not
enabled per Windows+CGO note in memory)
Wider sweep core/transport/ + core/recovery/ + core/storage/... +
core/replication/component/ all green.
Next: P1 (BlockExecutor.Ship delegate to walShipper) — TDD again,
write tests against INV-NO-DOUBLE-LIVE + INV-SINGLE (registry)
first.
Spec-driven test-first work per architect 2026-04-29 ratification:
"先写完让 architect 看看然后写 code". This commit lands ONLY:
- core/transport/wal_shipper.go — initial implementation hypothesis
- core/transport/wal_shipper_test.go — 10 spec-§9 tests
The tests are NOT run; wal_shipper.go is NOT validated against them.
This is the spec→code BRIDGE: architect reviews tests against
v3-recovery-wal-shipper-spec.md §3 (INV) + §5 (R1) + §6 (R2) + §9
(min test names); after ratification, implementation gets fixed
under test pressure (NOT the other way around).
Test catalog (matching spec §9 exactly):
TestWalShipper_RegistrySingleton — INV-SINGLE
t.Skip — registry lives
in BlockExecutor (P1
mini-plan)
TestWalShipper_CursorMonotonic — INV-MONOTONIC-CURSOR
(cursor never regresses
outside session entry)
TestWalShipper_RewindOnceAtSessionEntry — INV-MONOTONIC-CURSOR
(one legal rewind path
via StartSession)
TestWalShipper_DeliveredEqualsCursor — INV-SUBSET (emitted set
= (fromLSN, cursor]
exactly, contiguous)
TestWalShipper_R1_NoGapAtTransition — INV-NO-GAP-R1 (concurrent
writer while drain →
R1 transitions; every
LSN ∈ [1, finalHead]
in emit log exactly
once)
TestWalShipper_R1_DoubleCheckRejectsRace — spec §5.1 (head moved
during check window;
R1 stays Backlog,
next scan picks up
missed LSN)
TestWalShipper_NoDoubleLive — INV-NO-DOUBLE-LIVE
(recordingEmit tracks
in-flight emits across
4 concurrent writers
+ drain; maxInFlight ≤ 1)
TestWalShipper_R2_LagSignalFires — spec §6.2 (Backlog mode
with lag > threshold
fires OnSaturation
exactly once per
session)
TestWalShipper_R2_NoSpuriousSignal — spec §6.3 (load-safe
scenario, OnSaturation
never fires)
TestWalShipper_BacklogToRealtime_Happy — spec §4 default priority
end-to-end happy path
(no race)
TestWalShipper_BacklogStaysBacklog_UnderLoad — spec §5.3 explicit
non-guarantee (writer
outpaces drain → mode
stays Backlog, not
fake-Realtime)
Implementation hypothesis (wal_shipper.go) covers spec §2 state +
§4 default priority + §5 R1 (assertCaughtUpAndEnableTailShipLocked
double-check inside shipMu) + §6 R2 (lag tracking + OnSaturation
hook). Hypothesis is what tests will VALIDATE OR INVALIDATE — not
authoritative.
Architect review prompt:
Q1: Are the 10 tests' assertions a faithful read of spec §3
invariants + §5 R1 + §6 R2? If a test allows behavior the
spec forbids (or rejects behavior the spec permits), flag.
Q2: Is the t.Skip on RegistrySingleton acceptable for this PR
scope (registry lands in P1 per mini-plan §3)?
Q3: TestWalShipper_R1_DoubleCheckRejectsRace uses heuristic timing
(sleep until cursor ≥ 8 then inject write) — do you want a
more deterministic harness (e.g., fixedHeadSource that lets
test inject head changes synchronously)? Acceptable as-is for
P0; if not, mini-plan §4 row needs sharpening.
Q4: TestWalShipper_R2_LagSignalFires asserts exact "fired == 1"
single-shot per session. Spec §6.2 says "exactly once when
synthetic load drives lag past threshold". If saturation
conditions briefly clear and re-fire later (same session),
should the hook re-fire? Spec implicit single-shot; please
confirm or sharpen.
After architect ratification: run tests against wal_shipper.go;
fix implementation where tests fail; iterate. Tests are
authoritative; impl bends to them.
Branch: g7-redo/wal-shipper-impl off phase-15. Does NOT touch
g7-redo/unified-wal-impl (archived per mini-plan §0). Does NOT
touch BlockExecutor / recovery.Sender / coord — those are P1+P2
in mini-plan §3.
Per repository policy: dev/design docs live in
seaweedfs/sw-block/design/, not in seaweed_block/docs/. Companion
to the seaweedfs commit at 04b9d1ea5 which adds the same content
under v3-recovery-* prefix.
Removed (paths now in seaweedfs/sw-block/design/):
docs/recovery-pin-floor-wire.md
→ v3-recovery-pin-floor-wire.md
docs/recovery-wiring-plan.md
→ v3-recovery-wiring-plan.md
docs/recovery-execution-institution.md
→ v3-recovery-execution-institution.md
docs/recovery-inv-test-map.md
→ v3-recovery-inv-test-map.md
Three more design docs that were in flight on g7-redo branches
(unified-wal-kickoff, unified-wal-mini-plan,
hardware-canonical-paper) were never on phase-15 and are also
now in seaweedfs/sw-block/design/. Their seaweed_block branches
are deleted as part of the same relocation cleanup.
Code paths and commit messages still reference the old doc paths
in git history — that's normal; new code references the
v3-recovery-* paths in seaweedfs.
No code changes in this commit; pure relocation.
Architect-ratified Option A 2026-04-29: bug-fix shape for the
boundary mapping gap that let `recovery.FailurePinUnderRetention`
fall through to `engine.RecoveryFailureTransport` (retryable). Engine
re-emitted Start* on the same lineage, the same ack triggered the
same pin violation, and the lineage spun until the retry budget
exhausted — masking the "fresh probe + new lineage" signal the
typed envelope was meant to surface.
Pinned by INV-PIN-COMPATIBLE-WITH-RETENTION at the engine retry
gate. Option B kickoff (per-failure-kind budget + lossless recovery
↔ engine mapping + retry observability) tracked separately; Option
B prerequisites #3 [retry] backoff/wall-clock cap.
Engine kind (`core/engine/events.go`):
+ RecoveryFailurePinUnderRetention — typed enum value + String case.
Documented non-retryable, distinct from WALRecycled (which auto-
escalates to Rebuild). PinUnderRetention is mid-session contract
violation; new lineage decision belongs to next probe.
Engine retry path (`core/engine/apply.go::applySessionFailed`):
+ Early-return branch mirroring StartTimeout pattern: trace +
PublishDegraded; Attempts unchanged; Decision NOT auto-flipped
(counter-WALRecycled — engine doesn't pre-decide rebuild vs
catch-up at fresh fromLSN).
Boundary mapping (`core/transport/recovery_session.go::classifyRecoveryFailure`):
+ New `*recovery.Failure` errors.As branch. Option A scope:
PinUnderRetention only. Other recovery kinds (Wire, Protocol,
Substrate, Contract, Cancelled, SingleFlight, Unknown) deferred
to Option B kickoff — fall-through fence test asserts they keep
landing on Transport until B lands explicit cases.
Tests (5 new):
Engine retry-bypass (3 in `recovery_pin_retention_test.go`):
+ TestT4d_PinUnderRetention_BypassesRetryBudget — headline:
no Start* re-emit; Attempts unchanged; PublishDegraded emitted;
Decision NOT auto-escalated.
+ TestT4d_PinUnderRetention_AtBudgetEdge_DoesNotEscalate —
negative pin: even at wal_delta MaxRetries=3 edge, pin
violation MUST NOT trigger round-47 catch-up-exhaustion-→-
rebuild path (proves the bypass branch doesn't bump the
counter).
+ TestRecoveryFailureKind_PinUnderRetention_String — diagnostic
surface pin (logs / traces grep on this string).
Boundary mapping (2 in `classifier_pin_under_retention_test.go`):
+ TestClassifier_RecoveryPinUnderRetention_MapsToEngineKind —
headline mapping; counter-pin asserts NOT Transport fallback.
+ TestClassifier_RecoveryFailure_OtherKinds_StillFallThrough —
Option B fence: enumerates every deferred recovery kind,
asserts they fall through to Transport. Forces Option B to
consciously update both the production switch and this test.
Verified: `go test ./core/engine/ ./core/transport/ ./core/recovery/
./core/storage/... ./core/replication/component/ -count=1` — all
green.
inv-test-map.md row INV-PIN-COMPATIBLE-WITH-RETENTION extended:
coord layer + engine retry-bypass + boundary mapping; status flips
to "pinned (coord + engine retry-bypass + boundary mapping)".
Branch hygiene: stacked off `g7-redo/recycle-pin-hookup` for context
linkage, but architect-tagged "可与 wiring 并行" — separate concurrent
PR. Depends on neither wiring nor recycle-pin-hookup at code level.
Closes architect priority 2.5 per docs/recovery-wiring-plan.md §6.
Pinned by INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. Depends on wiring
(stack-on-wiring per architect Option A 2026-04-29).
Substrate gate (`core/storage`):
+ RecycleFloorSource interface — externally-supplied
`MinPinAcrossActiveSessions() (uint64, bool)`. Substrate stays
orthogonal to engine: structural typing means
`core/recovery.PeerShipCoordinator` satisfies it without import.
+ RecycleFloorGate optional interface — substrate impl that
accepts a source via `SetRecycleFloorSource`. Cmd / wiring
type-asserts on it; smartwal can opt in later.
walstore (`core/storage/walstore.go`):
+ recycleFloorSrc field, mu-guarded.
+ persistCheckpoint clamps proposed `highestLSN` to floor when
source reports active session. Existing no-regress guard
(`if highestLSN <= s.checkpointLSN`) handles transient
floor-below-checkpoint races.
+ SetRecycleFloorSource setter.
memorywal (`core/storage/memorywal/store.go`):
+ recycleFloorSrc field, mu-guarded.
+ AdvanceWALTail clamps proposed `newTail` to floor when source
reports active session. Same shape as walstore.
+ SetRecycleFloorSource setter.
Coordinator assertion (`core/recovery/peer_ship_coordinator.go`):
+ `var _ storage.RecycleFloorSource = (*PeerShipCoordinator)(nil)`
— compile-time pin so future signature drift breaks the build,
not the runtime gate.
Daemon wiring (`cmd/blockvolume/main.go`):
+ In dual-lane mode, install gate via `RecycleFloorGate` type
assertion. Skipped silently when substrate doesn't support it
(BlockStore today). Diagnostic stderr line for operators.
Component fixture (`core/replication/component/cluster.go`):
+ Cluster.Start installs the gate when dualLane is set, so
component-level dual-lane tests exercise the recycle path
against the same coordinator they install on executors.
Tests (12 new):
+ walstore_recycle_pin_test.go (6) — nil source / inactive /
active clamp / floor-above-proposed (no clamp) / no-regress
when floor < current checkpoint / disable via Set(nil).
+ memorywal/store_recycle_pin_test.go (6) — nil source / inactive
/ active clamp + scan-gate inequality / floor-above-proposed /
disable / RecycleFloorGate interface satisfaction.
Verified: `go test ./core/... ./cmd/... -count=1` all green
(transport, host, recovery, storage{,/memorywal,/smartwal},
replication{,/component}, blockvolume).
inv-test-map.md updated: row flips from "logic only; recycle
integration is next milestone" to "coord + walstore + memorywal
substrate integration" with the 12 new tests cited.
* docs: wiring plan for core/recovery → core/transport + cmd
Strategy doc for the next PR (g7-redo/wiring): how to land the
dual-lane recovery package alongside (NOT replacing) the existing
single-lane core/transport path per architect ruling.
Sections:
- Strategy: --recovery-mode flag (legacy / dual-lane); default
legacy until one milestone of dual-lane GREEN observed.
- Surface inventory: 6 files in core/transport, 1-2 in cmd, 0 in
core/recovery (it stays untouched).
- Lifecycle alignment: PeerShipCoordinator is the single source of
truth for "is replica P in a rebuild session" when dual-lane
active; legacy's BlockExecutor.activeSession is internal to the
legacy path. Mode is exclusive.
- Wire-format collision (frameSessionStart=0x01 vs MsgShipEntry=
0x01): three options analyzed; recommend separate ports per mode.
- Coordinator scope: per-volume, NOT per-replica (so MinPin sees
all replicas for a meaningful min).
- Priority 2.5 (WAL recycle consumes MinPin): new RecycleFloorSource
interface in core/storage; coordinator already implements it
exactly; recommend split into g7-redo/recycle-pin-hookup PR after
this one.
- Test plan: dual-lane integration tests + recycle-pin unit test.
Existing legacy tests unchanged.
- Rollback: default flip is one-line; legacy removal is a separate
later PR.
4 open questions for architect (wire collision option, 2.5 split,
default flip timing, legacy removal timing).
Out of scope: §3.2 #3 interleave, retry budget (parallel PR),
liveShipTargetLSNSentinel removal (waits for legacy removal).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* transport: dual-lane wiring (BlockExecutor + StartRebuild branch)
First wiring step per docs/recovery-wiring-plan.md §1-§3. Adds the
parallel-flag plumbing for routing StartRebuild through the
core/recovery package's PrimaryBridge while leaving the legacy
single-lane path completely untouched on the default constructor.
Architect ACK on §11 Resolution 1 (separate ports, Option A) drives
the design: dual-lane uses a separate listen address from the
legacy port; this commit only does the primary-side dial; replica's
listen loop is illustrated in dual_lane_test.go and will be hoisted
into cmd/blockvolume in a follow-up.
What lands:
core/transport/executor.go
+ DualLaneConfig struct (Bridge / DialAddr / ReplicaID).
+ dualLane *DualLaneConfig field on BlockExecutor.
+ NewBlockExecutorWithDualLane(primaryStore, replicaAddr,
dualLaneAddr, coord, replicaID) constructor.
+ Bridge captures executor's onStart/onClose via closures so
SetOnSession*Callback continues to work post-construction.
core/transport/rebuild_sender.go
+ StartRebuild branches on e.dualLane != nil.
+ startRebuildDualLane: dial dual-lane port, call
bridge.StartRebuildSession, immediately FinishLiveWrites
(legacy semantic — no live writes during rebuild). Logs the
same "executor: rebuild start" marker QA helpers scrape, with
"(dual-lane)" suffix for trace clarity.
core/transport/dual_lane_test.go
+ runDualLaneListener test helper (illustrates what cmd will do
in production: net.Listen + accept loop spawning
recovery.ReplicaBridge.Serve per conn).
+ TestDualLane_BlockExecutor_StartRebuild — full path:
OnSessionStart fires, OnSessionClose fires with achievedLSN ==
primaryH, replica's substrate matches primary byte-for-byte,
coordinator returns to PhaseIdle.
+ TestDualLane_LegacyConstructorIsNotDualLane — guard that
the existing NewBlockExecutor stays legacy (dualLane == nil).
Validation: 2 new tests pass; all existing core/transport tests
unchanged; full repo `go test ./...` green.
OUT OF SCOPE for this PR (per wiring plan §10):
- cmd/blockvolume flag wiring (next commit).
- WAL recycle path consuming MinPinAcrossActiveSessions
(architect priority 2.5 — separate g7-redo/recycle-pin-hookup
PR per §11 Resolution 2).
- Removing core/transport/replica.go::liveShipTargetLSNSentinel
lane shim (waits for legacy removal milestone).
- §3.2 #3 single-queue real-time interleave (architect priority #2).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* wiring: cmd flag + replication factory + listener (dual-lane reachable from binary)
Second wiring step per docs/recovery-wiring-plan.md. After this commit,
the daemon binary actually exposes the dual-lane recovery path: a flag
selects mode, the replication volume injects the right BlockExecutor
factory per peer, and a separate listener binds at port+1 for inbound
recover-session conns.
cmd/blockvolume/main.go
+ --recovery-mode=legacy|dual-lane flag (default legacy).
+ Validation: rejects unknown values at parse time.
+ In dual-lane mode, after constructing replVolume:
- new per-volume recovery.PeerShipCoordinator,
- SetDualLaneExecutorFactory wires per-peer
NewBlockExecutorWithDualLane closures,
- separate listener at deriveDualLaneAddr(data-addr) running
recovery.ReplicaBridge.AcceptDualLaneLoop in its own goroutine,
- graceful close via deferred cancel + ln.Close at daemon shutdown.
+ deriveDualLaneAddr helper: host:port → host:port+1 (deployment
convention, wiring plan §4 Option A).
cmd/blockvolume/dual_lane_addr_test.go
+ Pins the port+1 convention: IPv4, IPv6, port=0 boundary,
overflow at 65535, malformed inputs.
core/replication/volume.go
+ dualLaneExecutorFactory type (factory takes replicaID alongside
addr — the legacy 2-arg signature does not).
+ newDualExec field, nil-default = use legacy newExec.
+ UpdateReplicaSet branches on which factory is set per peer.
+ SetDualLaneExecutorFactory exported setter for cmd to inject the
per-volume coordinator-capturing closure. MUST be called before
UpdateReplicaSet (existing peers do not retroactively re-construct).
core/recovery/integration_stub.go
+ Hoist AcceptDualLaneLoop helper from the test file to a public
method on ReplicaBridge. Production cmd uses this directly;
test wrapper now just calls it.
core/transport/dual_lane_test.go
+ Refactor runDualLaneListener to use the new public helper instead
of an inline accept loop. Lifecycle simplified (ctx cancel + ln
close → loop returns).
Validation: cmd/blockvolume tests + full repo go test ./... PASS.
Default --recovery-mode=legacy keeps existing G5-* / G6 behavior
identical.
Out of scope (still): WAL recycle path consuming MinPin (g7-redo/
recycle-pin-hookup, separate PR per architect §11 Resolution 2),
removing legacy lane shim, §3.2 #3 interleave.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* component: dual-lane engine-driven happy path (wiring step 3)
Closes the wiring milestone per docs/recovery-wiring-plan.md §7 +
architect "P0 = component layer dual-lane full chain" (2026-04-29).
Full chain pinned: master fact → adapter.OnAssignment → engine
ingest Identity → emits ProbeReplica → executor.Probe → adapter
ingests RecoveryFacts → engine.decide() picks rebuild (R<S) →
emits StartRebuild → adapter dispatches to dual-lane-mode
BlockExecutor → recovery.PrimaryBridge.StartRebuildSession →
sender goroutine over the replica's separate dual-lane port →
recovery.Receiver applies base lane + barrier → SessionClosedCompleted
flows back through executor.OnSessionClose → adapter →
engine.Trace records the event.
Cluster builder additions:
+ WithDualLaneRecovery() — composable with WithEngineDrivenRecovery.
+ Coord() — exposes the per-volume PeerShipCoordinator for assertion.
+ DualLaneReplicaAddr(i) — diagnostic.
+ ReplicaNode.DualLaneAddr — populated when dual-lane mode set.
+ Start() branches: per-replica dual-lane listener bound on
127.0.0.1:0 alongside the legacy listener; per-volume coord
instantiated before executors so each NewBlockExecutorWithDualLane
captures the same instance.
Substrate: MemoryWAL (new factory in cluster.go) — NOT BlockStore
or walstore. Architect-bound rationale for using memorywal rather
than walstore here:
- V2-faithful per-LSN replay (RecoveryModeWALReplay, write-time
LSN through ScanLBAs) — matches the dual-lane recovery contract
the test asserts.
- In-memory; no /tmp churn between tests; no flusher/checkpoint
timing surprises in scenario assertions.
- Already part of the contract test table (BlockStore / WALStore /
MemoryWAL all pass the same 12 tests), so substrate parity is
covered separately.
Tests pinned (both PASS, runs in ~30ms each on memorywal):
TestDualLane_EngineDrivenRebuild_HappyPath:
- Engine emits StartRebuild after probe-result ingest.
- Trace records SessionClosedCompleted within 5s deadline.
- coord.Phase("r-0") == PhaseIdle post-session.
- Replica's substrate matches primary byte-for-byte across the
rebuilt range (12 LBAs).
TestDualLane_CoordReleasesPinFloorAfterSession:
- Pin floor released; MinPinAcrossActiveSessions reports
anyActive=false post-session.
- PinFloor("r-0") == 0 after coord.EndSession.
- INV-SESSION-TEARDOWN-IS-EXPLICIT.
Out of scope (still):
- Hardware integration (separate phase).
- WAL recycle path consuming MinPin (g7-redo/recycle-pin-hookup,
architect §11 Resolution 2).
- §3.2 #3 single-queue real-time interleave (architect priority #2).
- Multi-replica fanout under dual-lane (single replica here for
focus).
Full repo `go test ./...` PASS.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* recovery: BaseBatchAck wire + pin_floor advancement (#3)
Implements docs/recovery-pin-floor-wire.md per architect ACK on
2026-04-29. Closes the two forward-direction Layer-2 INVs:
INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK
INV-PIN-COMPATIBLE-WITH-RETENTION
What lands:
Wire (core/recovery/wire.go):
- frameBaseBatchAck = 0x07 (receiver → primary direction).
- Payload: [8 SessionID][8 AcknowledgedLSN][4 BaseLBAUpper] = 20 bytes.
- Independent frame (architect §11 Resolution 3) — not piggyback.
Failure taxonomy (core/recovery/failure.go):
- New FailureKind FailurePinUnderRetention. Distinct from
WALRecycled (cold-start scan failure) — this is mid-session
contract violation, retryable=false (architect §11 Resolution 1).
- New phases PhaseRecvAckWrite, PhasePinUpdate.
Coordinator (core/recovery/peer_ship_coordinator.go):
- SetPinFloor(id, floor, primarySBoundary) (architect §11 Resolution 2:
explicit parameter, not callback). Caller computes inputs;
coordinator stays substrate-free.
- Check ordering: monotonic guard FIRST, retention check second.
Avoids spurious PinUnderRetention on early-session acks where
receiver's walApplied is still 0 while primary's S has advanced.
Receiver (core/recovery/receiver.go):
- Cadence config: K blocks (default 256) ∨ T elapsed (default 100ms),
via NewReceiver / NewReceiverWithCadence.
- Mandatory ack on MarkBaseComplete (BaseDone path).
- Cadence-driven ack during base lane streaming.
- AcknowledgedLSN = session.Status().WALApplied; BaseLBAUpper
tracks highest base LBA installed.
Sender (core/recovery/sender.go):
- New goroutine readerLoop demuxes inbound frames (BaseBatchAck
during base lane, BarrierResp at session end).
- barrierRespCh (buffered=1) delivers result to main Run goroutine
at barrier-wait point.
- BaseBatchAck handler: validates SessionID, fetches primary's S
via Boundaries(), calls coord.SetPinFloor with the typed Failure
flowing back through barrierRespCh on retention violation.
Tests:
- 2 new SetPinFloor unit tests (RejectsBelowRetention +
ZeroBoundaryDisablesCheck).
- 1 new e2e test (TestE2E_PinFloorAdvancesIncrementally) using
K=8 cadence over 50-LBA backlog to drive multiple acks.
- Existing test signatures updated for the new SetPinFloor arity.
- 36/36 PASS in core/recovery; whole repo green.
Cross-references updated:
- core/recovery/doc.go: pin INV section now points at design doc §3-§5.
- docs/recovery-inv-test-map.md: forward rows for the two INVs
upgraded from "_Pending #3_" to "design landed; impl pending #3"
in the prior commit; this commit will also need a follow-up
to flip them to "pinned" once architect / QA validates the
test cites — left for the merge-back PR.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: inv-test-map — flip pin INVs to pinned + add PinUnderRetention row
Both forward-direction Layer-2 INVs now have concrete test cites:
- INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK → TestE2E_PinFloorAdvancesIncrementally
- INV-PIN-COMPATIBLE-WITH-RETENTION → TestCoordinator_SetPinFloor_RejectsBelowRetention
+ TestCoordinator_SetPinFloor_ZeroBoundaryDisablesCheck
Layer-3 retryable matrix bumped from 8 kinds to 9 with the new
FailurePinUnderRetention row.
Test sweep summary: 86 results (was 83 in POC, +3 from this branch).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* G7-redo POC: dual-lane recovery package — mechanism + e2e
Self-contained package at core/recovery/ implementing the dual-lane
rebuild/recover algorithm per v3-recovery-live-line-backlog-spec.md.
Independent of core/transport (no integration yet — that lands as a
separate PR per architect ruling: "parallel + flag, don't replace
existing path until one happy path runs green alongside").
Layer 1 (receiver-side mechanism):
- bitmap.go: RebuildBitmap, per-LBA WAL-wins-base flag.
INV-DUAL-LANE-WAL-WINS-BASE; no internal lock (V2-faithful).
- rebuild_session.go: RebuildSession with ApplyBaseBlock /
ApplyWALEntry(kind, ...) / MarkBaseComplete / TryComplete.
TryComplete = baseDone ∧ walApplied ≥ targetLSN
(INV-SESSION-COMPLETE-ON-CONJUNCTION-LAYER1).
Layer 2 (primary-side orchestration):
- peer_ship_coordinator.go: PeerShipCoordinator with phase enum
(Idle / DrainingHistorical / SteadyLiveAllowed), pin_floor
management, and RouteLocalWrite. Per architect ruling on
CHK-NO-FAKE-LIVE-DURING-BACKLOG: while session is non-Idle,
RouteLocalWrite returns SessionLane regardless of phase.
SteadyLiveAllowed is publication-permission, not a routing gate.
Wire (core/recovery/wire.go):
- 6 frame types (SessionStart, BaseBlock, BaseDone, WALEntry,
BarrierReq, BarrierResp).
- WALEntry carries a Kind byte (Backlog / SessionLive) for
observability; explicitly NOT a convergence proof.
Sender / Receiver (core/recovery/sender.go, receiver.go):
- Sender takes context.Context; defer always sets sealed=true and
calls coord.EndSession (closes architect-flagged "receiver fails
early; does sender still seal" question).
- Sender flow: SessionStart → base lane → BaseDone → backlog scan
→ wait Close() | ctx.Done() → drainAndSeal → TryAdvance →
barrier.
- POC: SEQUENTIAL phases — backlog completes before live writes
drain. Spec §3.2 #3 (single ordered queue with LSN-real-time
interleave) is the next milestone, NOT satisfied by this POC.
Documented in doc.go.
Tests (e2e_test.go + per-file unit tests):
- Happy path, live writes during session, atomic seal under push
vs Close race, kind-count pinning across backlog/live split.
- 21/21 PASS. Race tests need Linux for -race; Windows host
cannot enable race detector under cross-compile.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* G7-redo POC: Layer 3 failure taxonomy + integration stub
Wraps every error path in sender / receiver / bridge with a typed
*Failure carrying {Kind, Phase, Underlying}. Engine integration code
(later) inspects via errors.As / AsFailure to drive retry budget.
failure.go:
- FailureKind enum (8 values): Wire, Substrate, Contract are
retryable; Protocol, Cancelled, SingleFlight, WALRecycled,
Unknown are not. Matrix pinned by failure_test.go.
- Phase enum (13 values) tags where in the session lifecycle the
failure surfaced. Diagnostic only — not part of the retry
decision.
- AsFailure(err) helper for callers; nil-safe Error()/Retryable().
integration_stub.go:
- PrimaryBridge / ReplicaBridge demonstrate the CommandExecutor-
shaped surface (StartRebuildSession / PushLiveWrite /
FinishLiveWrites / OnSessionStart / OnSessionClose) WITHOUT
touching core/transport. Architect priority #1: "出一条薄链路
早一点发现 lifecycle/回调不匹配".
- StartRebuildSession synchronously calls coord.StartSession
before spawning the goroutine, so callers reading
coord.RouteLocalWrite immediately after it returns
deterministically observe a non-Idle phase.
Tests:
- TestFailure_RetryableMatrix pins all 8 kinds.
- TestIntegrationStub_FailureTypedOnReceiverDown — peer closes
conn before any frame → typed Failure(Wire, SendStart|BaseLane),
Retryable=true.
- TestIntegrationStub_FailureTypedOnCancellation — ctx cancel
during AwaitClose → Failure(Cancelled, AwaitClose),
Retryable=false.
- 33/33 PASS total across the package.
Out of scope (next milestones):
- BaseBatchAck → pin_floor incremental advancement (architect #3).
- Single-queue LSN real-time interleave (architect #2 / spec §3.2 #3).
- Integration with core/transport (parallel-flag PR).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* core/storage/memorywal: V2-faithful in-memory WAL substrate
memorywal.Store is the third LogicalStorage implementation alongside
BlockStore (current-state map) and WALStore (on-disk WAL+extent).
Like BlockStore it has zero on-disk dependency, but unlike BlockStore
it uses an append-only record log so per-LSN replay semantics are
preserved:
- Each Write captures its contemporaneous LSN; the record is
never rewritten in place.
- ScanLBAs(fromLSN, fn) emits each record's REAL write-time LSN
(RecoveryModeWALReplay, V2-faithful).
- 3 writes to the same LBA produce 3 ScanLBAs entries, NOT 1
deduped entry — matches walstore, not BlockStore.
- AdvanceWALTail(newTail) trims records and sets an explicit
`recycleFloor`; subsequent ScanLBAs(fromLSN < recycleFloor)
returns storage.RecoveryFailure(Kind=WALRecycled), and
errors.Is(err, ErrWALRecycled) holds via Unwrap.
- AppliedLSNs returns a real per-LBA highest-LSN map (BlockStore
returns ErrAppliedLSNsNotTracked).
The recycleFloor / retainStart split avoids a spurious-recycled
trap: ApplyEntry installing a record at a high LSN (e.g. lsn=100)
without prior writes does NOT make ScanLBAs(0) think recovery is
impossible — recycledFloor is bumped only by AdvanceWALTail.
Conformance: added to the existing core/storage contract test
table. All 12 TestContract_* tests now run against three impls:
BlockStore-mem / WALStore / MemoryWAL — same assertions, all green.
Refactor required: contract_test.go moved from package `storage`
to package `storage_test` (external) so it can import memorywal
without a cycle. The shared `makeBlock` helper used by other
internal _test files (flusher_test, walstore_test) moved to a
new `testhelpers_test.go` package `storage` to keep them building.
Production placement note: this lives next to BlockStore + WALStore
in the existing substrate tree (no `core/storage/` reshuffling).
Use it from any test/component that needs WAL-replay semantics
without on-disk overhead — recovery package POC + future
component-level rebuild scenarios.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: recovery INV ↔ test mapping (G7-redo POC)
Per architect closure on g7-redo/dual-lane-recovery-poc: maps every
declared INV (Layer 1 mechanism / Layer 2 orchestration / Layer 3
taxonomy / substrate contract conformance) to its pinning test
function + file:line at branch HEAD.
Sections:
- Layer 1 — receiver-side mechanism (3 INVs, all pinned).
- Layer 2 — primary-side orchestration (9 INVs; 7 pinned, 2 forward
pending #3 BaseBatchAck → pin_floor).
- Spec CHK-* — phase / barrier / no-fake-live (3 checks, all pinned).
- Substrate contract — 12 LogicalStorage contract tests run across
BlockStore / WALStore / MemoryWAL (3 impls) + 5 MemoryWAL-specific
semantics not satisfiable by BlockStore.
- Layer 3 failure taxonomy — 6 INVs, all pinned (matrix + nil-safety
+ extraction + wire/cancel surface + always-seal-on-error).
- Forward-direction — 6 INVs declared but deliberately untested with
target milestones (pin/recycle wiring, sparse base, overlap-history
bitmap-as-claim, single-queue interleave, ship-phase observability).
Test sweep summary: 83 test results across the package; race-detector
status flagged for Linux CI.
Includes how-to-keep-current procedure for follow-up PRs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: pin_floor / BaseBatchAck wire design (#3 architect priority)
Single source of truth for the next milestone — receiver→primary
ack cadence, SetPinFloor semantics, retention inequality, and the
proposed FailurePinUnderRetention kind. Design only; implementation
lands on a follow-up branch.
Closes the two forward-direction INVs in the inv-test-map's
Layer-2 section once impl lands:
- INV-PIN-ADVANCES-ONLY-ON-REPLICA-ACK
- INV-PIN-COMPATIBLE-WITH-RETENTION
Cross-references added:
- core/recovery/doc.go: pin INV section now points at the design
doc sections (§3 cadence, §4 semantics, §5 retention inequality).
- docs/recovery-inv-test-map.md: forward rows updated from
"_Pending #3_" to "design landed; impl pending #3" with
explicit pointer to the design doc.
Open questions for architect (in §11 of the design doc):
1. New FailurePinUnderRetention kind vs reuse FailureWALRecycled
with a Phase discriminator. Recommend new kind.
2. SetPinFloor signature: parameter for primary's S boundary vs
coordinator-held callback. Recommend parameter.
3. Wire compat at production wiring time: keep new frame or fold
into MsgShipEntry with a flag. Recommend keeping new frame.
Out of scope (explicit, §10):
- §3.2 #3 single-queue real-time interleave (architect priority #2).
- Wiring into core/transport.
- WAL recycle path consuming MinPinAcrossActiveSessions.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: pin-floor wire design — architect ACK on §11 (2026-04-29)
All three open questions resolved per architect ratification:
1. FailurePinUnderRetention = new FailureKind (not reused).
2. SetPinFloor takes explicit parameter (not callback).
3. Independent frame 0x07 (not piggyback).
Implementation gates the next branch g7-redo/pin-floor.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per G6 §1.H audit work envelope item #1 + §2 #5 acceptance:
StartRebuild fires the wire-level rebuild path asynchronously
(goroutine launched at line 31 in rebuild_sender.go); pre-G6 the
only log marker was 'executor: rebuild complete, sent N blocks'
which fires AFTER completion. QA's G5-5C scenario D 5s scrape
window saw nothing because rebuild execution exceeded the window
— there was no START marker to wait on.
Add a deterministic START marker BEFORE the goroutine spawns:
executor: rebuild start replica=<id> sessionID=<n> epoch=<n>
EV=<n> targetLSN=<n>
Fixed string shape so QA's wait_until_rebuild_dispatched helper
can grep deterministically. Includes lineage tuple for forensics
(matches existing engine StartRebuild command shape; future
multi-session debugging can correlate START → COMPLETE on
sessionID).
Pinned by: INV-G6-WALRECYCLE-DISPATCHES-REBUILD (load-bearing
hardware pin §2 #5).
Test results: full ./core/transport/ + ./core/engine/ regression
GREEN. No behavioral change — pure observability addition.
Per G6 mini-plan v0.1 §2 #1, sw publishes audit findings as a
commit note before any production code change.
AUDIT METHOD: greped seaweed_block/core/{storage,transport,engine}
+ cmd/blockvolume for the WALRecycled chain; cited apply.go +
recovery_session.go + walstore_recovery.go line numbers as evidence.
PER-INV FINDINGS:
[1] Substrate-layer WALRecycled production
Location: core/storage/walstore_recovery.go:72-73 +
core/storage/smartwal/recovery_scan.go:96-97
Both walstore + smartwal return
storage.NewWALRecycledFailure(ErrWALRecycled, detail) — TYPED
*RecoveryFailure envelope (NOT bare sentinel). Status: ✅ wired.
[2] Transport-layer mapping (storage error → engine kind)
Location: core/transport/recovery_session.go:35-48
classifyRecoveryFailure uses errors.As(err, &rf) to extract
StorageRecoveryFailureWALRecycled → engine.RecoveryFailureWALRecycled.
Called from core/transport/executor.go:520 at finishSession.
Status: ✅ wired.
[3] Engine-layer dispatch (RecoveryFailureWALRecycled → StartRebuild)
Location: core/engine/apply.go:applySessionFailed lines 519-547
On e.FailureKind == RecoveryFailureWALRecycled:
- Decision = DecisionRebuild
- RebuildPinned = true
- Attempts = 0
- Emit PublishDegraded (diagnostic surface)
- Emit StartRebuild IMMEDIATELY (provided !hasActiveSession,
which holds at this point because Phase just set to
PhaseFailed)
Cited INV: INV-REPL-REBUILD-EMITTED-ON-WAL-RECYCLED.
Status: ✅ wired.
[4] Runtime per-peer dispatch (engine command → wire)
Location: G5-5C Batch #7 PeerCommandExecutor +
PeerAdapterRegistry (core/host/volume/peer_*).
PeerCommandExecutor.StartRebuild → transport.BlockExecutor.
StartRebuild → wire-level rebuild_sender.
Status: ✅ wired (verified by G5-5C component test
g5_5c_restart_catchup_test.go which exercised the rebuild
branch on smartwal store).
[5] --wal-retention-* flag
Location: cmd/blockvolume/main.go (parseFlags)
Status: ❌ NOT PRESENT. Must be added for §1.A α binding.
Plumbing: flag → durable provider construction → walstore /
smartwal recovery_scan. Estimate: ~40 LOC across 3 files.
[6] Current retention mechanism
walstore.go is append-only (no physical wraparound; no
Truncate calls beyond initial file resize). The 'recycle' is
purely the checkpointLSN-based logical gate at recovery scan
time. To implement α: relax walstore_recovery.go:67 from
'fromLSN <= checkpointLSN' to 'fromLSN <= checkpointLSN -
retentionLSNs'. Mirror in smartwal/recovery_scan.go.
QA D OBSERVATION INTERPRETATION:
The 'no rebuild dispatch in 5s window' observation is most likely
(a) — existing-and-correct chain — combined with (i) rebuild
execution time on the wire exceeds 5s for the scenario, AND
(ii) no explicit 'rebuild starting' log line exists today; only
'executor: rebuild complete, sent N blocks' fires AFTER completion.
This is a TEST DESIGN issue (window too short + no start marker),
not a missing dispatch. G6 hardware step #5 fixes both via:
- wait_until_rebuild_dispatched helper polling for new marker
- new log marker at rebuild session START in rebuild_sender.go
OVERALL VERDICT: PROCEED-with-minor-patch.
§1.H halt-condition: NOT triggered. The engine FSM + transport
mapping + substrate envelope + runtime per-peer dispatch are all
already wired and tested individually. The gap is at the
operability boundary, not the recovery substrate.
WORK ENVELOPE (per §1.A α + §1.H findings):
1. Add --wal-retention-lsns flag in cmd/blockvolume/main.go
(~10 LOC). Default value TBD — recommend 10000 LSNs.
2. Plumb retention into walstore.New + smartwal.openInitialized
constructors (~15 LOC).
3. Relax recovery scan gate to honor retention (~10 LOC each
in walstore_recovery.go + smartwal/recovery_scan.go).
4. Add explicit rebuild-START log marker in
transport/rebuild_sender.go (~5 LOC) so QA's
wait_until_rebuild_dispatched helper has a deterministic
marker (NOT just rebuild-complete which fires post-run).
5. Add engine-layer table-driven test pinning
RecoveryFailureWALRecycled → Decision=Rebuild +
RebuildPinned=true + StartRebuild emit; negative case for
Transport / SubstrateIO failure kinds (~80 LOC test).
6. Add walstore + smartwal substrate test for retention gate
(fromLSN within retention → scan succeeds; fromLSN past
retention → ErrWALRecycled) (~40 LOC test).
7. New INV inscribed: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE
(per §1.A α) + INV-G6-WALRECYCLE-DISPATCHES-REBUILD +
INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION +
INV-G6-ENGINE-NO-REBUILD-PINNED-ON-OTHER-FAILURES.
TOTAL ESTIMATE: ~160 LOC production + ~120 LOC tests.
NEXT STEPS:
- sw: code per work envelope above. First commit: rebuild-START
log marker (unblocks QA harness work). Then: --wal-retention-lsns
flag + plumbing. Then: tests.
- QA: now unblocked to write wait_until_rebuild_dispatched helper
+ extend D-scenario script for §2 #4 + #5 in single run per #6.
This audit fulfills §2 #1 (audit-published-as-commit-note before
production code change).
Cross-compile workflow for m01 hardware iteration leaves behind:
- _g5_bin/ (staged binaries before scp to m01)
- blockmaster / blockmaster.exe + blockvolume / blockvolume.exe
(Windows-side go build outputs)
None of these belong in version control. Ignoring at the repo root
(anchored, not recursive) so they don't pollute git status during
hardware iteration cycles.
QA expanded scenario testing surfaced a real production bug: iSCSI
target advertises 1 MiB capacity (DefaultVolumeBlocks=2048 ×
DefaultBlockSize=512) regardless of --durable-blocks /
--durable-blocksize, breaking any workload above LBA 256.
Architect ruling 2026-04-28: option (a) — inline patch as G5-5C
addendum, re-verify before §close ledger update. Per architect:
"否则 §close 是签 off 在一套对大卷必挂的二进制上,会削弱 credibility".
Root cause: cmd/blockvolume/main.go constructed iscsi.TargetConfig
+ nvme.TargetConfig WITHOUT setting Handler.{BlockSize, VolumeSize}.
Frontend HandlerConfig zero-values fell back to package defaults
(2048 × 512 = 1 MiB).
Fix:
- New helper computeFrontendVolumeSize(blocks, blockSize) (uint64,
error) with overflow guard. Rejects zero, rejects multiplications
that overflow uint64.
- main.go branches on f.durableRoot:
* --durable-root SET: plumb (BlockSize, VolumeSize) from
--durable-blocks × --durable-blocksize into both iscsi and nvme
HandlerConfig.
* --durable-root UNSET (memback path): leave HandlerConfig zero-
valued; frontend keeps historical 1 MiB / 512 B contract that
existing T2 tests expect (regression-safe).
NEW INV: INV-G5-FRONTEND-CAPACITY-FROM-DURABLE-CONFIG
"iSCSI/NVMe externally-visible volume capacity and block size MUST
derive from --durable-blocks × --durable-blocksize when --durable-
root is set, not silently fall back to frontend defaults."
Inscribed in v3-invariant-ledger.md.
NEW TESTS (cmd/blockvolume/frontend_capacity_test.go, 6/6 PASS):
- TestComputeFrontendVolumeSize_ProductOfBlocksAndBlockSize: 5
cases including 256 MiB (the case that exposed the bug).
- TestComputeFrontendVolumeSize_RejectsZero
- TestComputeFrontendVolumeSize_OverflowGuard
- TestIscsiHandlerCapacity_FromDurableConfig: round-trip via
iscsi.NewSCSIHandler asserting VolumeSize/BlockSize.
- TestNvmeHandlerCapacity_FromDurableConfig: same on nvme.NewIOHandler.
- TestFrontendDefaults_StillReturn1MiB: negative-control documenting
the legacy default fallback (the bug shape) — pins behavior so
future readers can grep for the bug pattern by INV ID.
Regression: full ./... PASS. Memback path tests (frontend/nvme
TestT2Process_NVMe_AttachWriteRead and friends) unchanged because
HandlerConfig stays zero-valued for that path.
Why §close evidence runs missed it: every G5-5/G5-5C scenario wrote
≤ 3 LBAs (LBA[0] / LBA[1] / LBA[2]); volume capacity assertion was
never exercised. Test-design gap, not honesty gap. QA expansion
catalog adds scale-sequential ≥1000 LBAs.
QA action: rebuild bins from this commit; re-run scale-sequential
on m01 (1000 LBAs × 4 KiB = 4 MiB sequential + verify); confirm
canonical 6-step suite still GREEN at 1 MiB memback default.
Architect final §close single-sign on tree containing this fix.
Per architect ruling 2026-04-27 (Option B: absorb fix in G5-5C as
Batch #7), this batch fixes the host wiring gap revealed by
hardware run 3:
ROOT CAUSE: cmd/blockvolume constructs ONE *VolumeReplicaAdapter
for the host's own slot (Identity.ReplicaID = primary's-own-slot).
G5-5C ProductionProbeFn forwarded peer probe results into that
adapter. Engine apply.go:117-128 checkReplicaID correctly drops
events targeted at peer (replicaID != Identity.ReplicaID) as
wrong_replica. Result: probe success on wire, but no StartCatchUp
ever dispatched.
FIX: per-peer adapter, each tracking its peer's identity, each
wired to dispatch engine commands to that peer's transport executor.
NEW FILES:
- core/host/volume/peer_command_executor.go (~140 LOC)
PeerCommandExecutor adapts peer's transport.BlockExecutor to
satisfy adapter.CommandExecutor. Most methods delegate verbatim
(Probe, StartCatchUp, StartRebuild, StartRecoverySession,
InvalidateSession, Fence). Two value-adds:
1. SetOnSessionStart/Close intercept inner callbacks to drive
peer.SetState (Degraded → CatchingUp on start; CatchingUp →
Healthy on Success). Without this, peer state stays Degraded
after successful catch-up and probe loop keeps polling.
2. PublishHealthy/Degraded translate engine verdicts to
peer.SetState/peer.Invalidate. Inner executor's
Publish* are log-only; runtime peer state machine is what
gates Ship + ProbeIfDegraded.
- core/host/volume/peer_adapter_registry.go (~140 LOC)
PeerAdapterRegistry maps ReplicaID → *VolumeReplicaAdapter.
OnPeerAdded constructs PeerCommandExecutor + adapter, primes
with AssignmentObserved for the peer's identity. OnPeerRemoved
drops the adapter. AdapterFor lookups for the router probeFn.
Self-replicaID guard refuses host-own-slot registration.
Idempotent double-add. Lineage-bump produces fresh adapter.
Close drops everything.
UPDATED FILES:
- core/replication/volume.go: ConfigurePeerLifecycleHook (onAdded,
onRemoved). Hook fired from UpdateReplicaSet add/remove/lineage-
bump teardown paths under v.mu. Configure-once contract; replays
current peer set on configure (so registry catches up to peers
added before hook).
- core/host/volume/probe_loop_wiring.go: AdapterRouter signature
type added. ProductionProbeFn now takes router instead of single
adapter; routes per-peer; nil-router and missing-peer paths
fail-closed.
- cmd/blockvolume/main.go: construct PeerAdapterRegistry; wire
ConfigurePeerLifecycleHook; pass registry.AdapterFor to
ProductionProbeFn. Failure paths cleaned up the same way as
prior wire steps.
- core/host/volume/boundary_guard_test.go: PCDD-STUFFING-001 fence
now allows TWO sites for adapter.AssignmentInfo composite
literals: decodeAssignmentFact (master decode boundary) AND
OnPeerAdded (per-peer engine identity priming, G5-5C Batch #7).
Other sites still fail.
- core/replication/component/g5_5c_restart_catchup_test.go:
configureProbeLoopOnCluster now uses AdapterRouter signature
(closure over c.primary.adapters[0]).
NEW TESTS (15 total, all PASS):
- peer_adapter_registry_test.go (7): RegisterAndPrimes,
DropsAdapter, SelfReplicaIDRefused, DoubleAddIdempotent,
LineageBumpTeardown, CloseDropsAll, NilSafe.
- peer_command_executor_test.go (5): PublishHealthy → SetState,
PublishDegraded → Invalidate, SessionStart → CatchingUp,
SessionClose → Healthy, DelegatesProbe.
- probe_loop_wiring_test.go (3 updated + 2 new):
NilRouter_ReturnsErrAndDoesNotPanic,
RouterReturnsNil_ReturnsErr,
RouterPicksByReplicaID (new — pins per-peer routing contract).
Test results: full ./... regression PASS at 17:58. No behavioral
regression on G5-4 / earlier T4 paths. Component test #6
(restart-catch-up convergence) still PASSES via new router signature.
NEW INV (replaces previously-deferred G5-5D INV):
- INV-G5-5C-PER-PEER-ADAPTER-PER-PEER-ENGINE — production binary
constructs *VolumeReplicaAdapter per (volume × admitted peer).
Engine.checkReplicaID correctness preserved.
Next: m01 hardware re-run #4. Expected GREEN within 30s deadline.
First m01 hardware run (b77rzzhc2) failed at #4 verify_restart_catchup
because the replica restart hit 'bind: address already in use' on
status port 9291 — TERM alone left the prior process holding the
port at restart time. Probe loop on primary correctly tried 5x and
got connection-refused, replica process never came up.
This is a script orchestration issue, NOT a G5-5C software issue.
Primary log (artifacts-20260427T <run2>) shows the probe loop
fired on schedule with the right cooldown progression — there was
just nothing to probe.
Fix: kill replica with TERM (1s) → KILL fallback → poll ss for
port 9291 release (up to 10s) before returning. Replica restart
then has a clean port to bind to.
Run this fix on m01 and re-verify #4 GREEN before §close.
Per mini-plan v0.5 §1.A architect binding: production primary runs
probe loop at 5s interval. The script's primary launch now passes
--degraded-probe-interval=5s so verify_restart_catchup can converge
within the 30s deadline (5s loop + ~10s catch-up + safety).
Replica side stays unchanged (probe loop is primary-only).
Architect Batch 6 review 2026-04-27 follow-up: clarify in code that
Stop is the production shutdown path; StopHard is for test
fault-injection / emergency stop only. Prevents future misuse where
operators reach for StopHard as a default shutdown route, masking
graceful-drain bugs.
No code change. No test change.
Architect Batch #6 review 2026-04-27 ratified scope: end-to-end
wiring + convergence test, mirror G5-5 hardware step #4 without
iSCSI/iptables harness. 5 implementation constraints all addressed:
#1 determinism: bounded retries, 30 ms loop interval, 20 ms
cooldown base, 200 ms cap, hard 8 s deadline on convergence
wait. CI flake guard via 1.5 s no-convergence window in negative
control test.
#2 kill semantic: ReplicaListener.Stop() blocks on wg.Wait waiting
for active handler conns to drain, but on localhost the primary
side never closes the live-ship conn so handlers block forever
on ReadMsg. Added ReplicaListener.StopHard() that closes active
conns BEFORE waiting; KillReplicaListener routes through it. The
pre-existing Stop() semantics are preserved for the regular
teardown path. Same-port rebind via NewReplicaListener retry
loop with 2 s deadline (TIME_WAIT tolerance).
#3 probe path same as cmd/blockvolume: configureProbeLoopOnCluster
uses volume.ProductionProbeFn (NOT a stub) → ConfigureProbeLoop
→ StartProbeLoop. The exact closure main installs in production.
#4 assertion layer: byte-equal convergence only — no engine R/S/H
peeks. Architect ruling: "至少一条: ReplicaDegraded → probe →
catch-up dispatched → frontier/byte-equal".
#5 no rebuild branch verification: test asserts convergence only,
not which engine command was emitted. In this scenario the
smartwal store's post-rebind boundaries land R<S so engine
picks Rebuild; that's incidental, not a property the test pins.
Files:
- core/transport/replica.go: +StopHard method, +conns map for
active-conn tracking; pre-existing Stop semantics unchanged.
- core/replication/component/cluster.go: KillReplicaListener now
calls StopHard.
- core/replication/component/g5_5c_restart_catchup_test.go (new):
- TestG5_5C_RestartCatchUp_Convergence: positive end-to-end test.
- TestG5_5C_RestartCatchUp_NoConvergence_WithoutProbeLoop:
negative control — same scenario without ConfigureProbeLoop
must NOT converge in 1.5 s window. Without this control, the
positive test could pass via some other accidental
reconvergence pathway; this pin proves the probe loop is
load-bearing.
Helpers (test-local):
- rebindReplicaListener: same-port restart with 2 s rebind retry.
- configureProbeLoopOnCluster: production wiring on cluster harness.
- drivePeerAdmit: AssignmentInfo + initial ProbeResult to reach
Healthy.
- writeOneBlock: write through StorageBackend so WriteObserver
fires (not direct store write).
Three-counter SessionID onboarding note (architect Batch #5 follow-up):
core/replication/peer.go now documents in code why three counters
exist (peerSessionID for live-ship; adapter probe counter for
engine-emitted ProbeReplica; probeSessionID for G5-5C runtime-
driven probes) and why none cross paths.
Test results:
- TestG5_5C_RestartCatchUp_Convergence: PASS (0.05 s)
- TestG5_5C_RestartCatchUp_NoConvergence_WithoutProbeLoop: PASS (1.54 s)
- Full ./... regression: PASS (every package, no behavioral
regression on G5-4 / earlier T4 paths).
Next: m01 hardware run of iterate-m01-replicated-write.sh
verify_restart_catchup expecting #1/#2/#3 regression GREEN + #4
GREEN within deadline. After hardware GREEN, sw drafts §close.
Closes the wire between batch 1-4's runtime/engine plumbing and
operator/CLI control. Per architect Batch #5 review 2026-04-27,
each of the 4 self-check items is addressed:
#1 --degraded-probe-interval=0 = OFF
Default value 0 keeps the loop disabled — preserves G5-4
behavior. Help text states this explicitly. main.go's
"if f.degradedProbeInterval > 0" guard means we NEVER call
ConfigureProbeLoop with a 0 interval (which the loop itself
would reject anyway via NewProbeLoop). Two layers of defense.
#2 cooldown-base/cap normalization
ProbeLoopConfig defaults (5s base, 60s cap) match
PeerProbeCooldown defaults exactly. NewProbeLoop normalizes
<=0 to defaults; Cap < Base bumps Cap up to Base. CLI flag
defaults are 5s/60s — matches batch 1/2 contract.
#3 production probeFn
New file core/host/volume/probe_loop_wiring.go::ProductionProbeFn
- peer.mu released before executor.Probe (loop discipline; the
probeFn never touches peer.mu — only Target() which is
immutable post-construction).
- transport failure (result.Success == false) → returns non-nil
err so DefaultProbeResultFn calls OnProbeAttempt(false) and
backoff advances. Wire-success returns nil so cooldown resets
to Base regardless of engine's semantic verdict.
- adapter.OnProbeResult is fed BOTH success and failure facts
(NormalizeProbe distinguishes). Engine async result NOT mixed
into transport return value — separation per architect
guidance.
- SessionID minted via replication.MintProbeSessionID (new
atomic counter; distinct from peerSessionIDCounter and
adapter's own probe sessionID counter — three contexts, three
counters, no overlap).
- Defensive guards: nil adapter → fail-closed shim probeFn;
nil executor → return err; zero lineage → return err;
ctx.Err() pre-check.
#4 Configure → Start ordering at admit time
main.go calls ConfigureProbeLoop + StartProbeLoop in sequence
immediately after replVolume + h.SetReplicationVolume; peers may
or may not exist yet (master assignment arrives async). Empty
peer set is safely no-op (covered by Batch 3
TestVolume_ConfigureProbeLoop_HappyPath); production is just
the same path with a real adapter.
Replication layer additions:
- ReplicaPeer.Executor() accessor for the probeFn (read-only,
caller never closes — BUG-005 discipline).
- replication.MintProbeSessionID() — atomic counter for
runtime-driven probes.
CLI flags (default OFF):
- --degraded-probe-interval (default 0; recommended 5s for prod)
- --degraded-probe-cooldown-base (default 5s)
- --degraded-probe-cooldown-cap (default 60s)
Help text explicitly distinguishes loop interval vs per-peer
cooldown so operators don't conflate the two 5s defaults.
Tests (3 wiring + 1 skip = 4/4 PASS as written):
- TestProductionProbeFn_NilAdapter_ReturnsErrAndDoesNotPanic
- TestProductionProbeFn_TransportFailure_ReturnsErr — dial to
127.0.0.1:1 (reserved/closed) → result.Success=false → non-nil
err returned + adapter received the failure fact.
- TestProductionProbeFn_ContextCancelled_ReturnsErr
- TestProductionProbeFn_ZeroLineage_ReturnsErr — skipped (defensive
guard verified by compile-time path; zero-lineage construction
requires package-private peer access, deferred to integration).
Full ./... regression: PASS (every package, including host 2-min
suite, frontend/iscsi 31s suite, frontend/nvme 61s suite). No
behavioral regression on G5-4 / earlier T4 paths.
Next batch (G5-5C #6): component restart-catch-up test exercising
the full primary→engine→catch-up loop without iscsi/iptables
harness. After that: m01 hardware re-run.
Architect Batch #4 review 2026-04-27 ruled the four §2 invariants
(#4 / #11 / #12 / #13) belong at the engine layer, not core/replication/
— "single owner per invariant, don't double-assert in adapter and
engine". Batch 3 already covered the runtime concerns (lifecycle,
cooldown, lock ordering, peer-instance teardown); Batch #4 covers
the truth-layer translations engine performs from probe results
into recovery commands.
Tests (5 tests, 9 subcases, 9/9 PASS):
§2 #4 dispatch (catch-up vs rebuild) — TableDriven:
- caught_up: R≥H → DecisionNone, no recovery cmd
- gap_within_wal: R<H, R≥S → DecisionCatchUp + StartCatchUp
- gap_exceeds_wal: R<S → DecisionRebuild + StartRebuild
- rebuild_pinned: pin overrides catch-up → StartRebuild
Mutual exclusion checked on each row (the OTHER cmd must NOT emit).
No real retention/WAL logic dragged in; pure (R,S,H) input → cmd
output table.
§2 #11 reconnect Case 1 (identity unchanged):
Admit at (epoch=1, EV=1) → catch-up running → session fails →
fresh ProbeSucceeded at SAME (epoch=1, EV=1) → engine still in
CatchUp at the same lineage. Identity.{Epoch,EndpointVersion}
pinned unchanged. No StartRebuild emitted (no master re-emit
needed for Case 1 — pinned by §1.F).
§2 #12 lineage-bump during in-flight recovery:
In-flight session 42 at epoch=1 → AssignmentObserved at epoch=2
resets Session/Recovery/Reachability via identityChanged path →
late SessionClosedCompleted carrying old SessionID=42 must be
DROPPED. Asserts: Recovery.R does NOT advance, Session.Phase does
NOT promote to Completed, no PublishHealthy emit. Distinct from
batch 3's volume-layer Case 2 test (peer-instance replacement);
this asserts the engine truth layer drops stale-SessionID events.
§2 #13 stale-ack guard (single owner = engine):
StaleSessionAck_DoesNotPromoteHealth — SessionCompleted with
AchievedLSN=50 < TargetLSN=100; Recovery.R advances to 50 but
decide() leaves Decision in CatchUp (R<H), so Healthy gate
refuses to flip. PublishHealthy NOT emitted.
StaleSessionAck_FullAchievedDoesPromote — counterpart confirming
AchievedLSN=H DOES promote (so prior test isn't trivially passing
via "Healthy never promotes"). PublishHealthy emit confirmed.
Also addresses architect's lock-order reminder #1 from Batch 3 review:
volume.go ConfigureProbeLoop's peersFn comment now states explicitly
"HARD RULE: code on the probe path MUST NOT re-enter v.mu while
holding peer.mu" so any future "peer callback into volume" code is
blocked at review.
Full ./core/engine/ + ./core/replication/ regression: PASS.
Per architect ruling, §2 #14 backoff progression is mathematically
pinned at the peer layer (batch 2); no further integration-layer
re-assertion needed.
Next batch (G5-5C #5): cmd/blockvolume flag wiring + production
probeFn that calls executor.Probe + adapter.OnProbeResult.
Per architect ratification of mini-plan v0.5 §1.A binding (probe
loop owned by ReplicationVolume lifecycle) + 4 guidance items
2026-04-27, this batch wires probe loop ownership into the volume
and pins startup/teardown ordering, lineage-bump abandonment, and
cooldown config push-down via tests.
Architect guidance #1 (startup ordering): ConfigureProbeLoop sets
the loop up; StartProbeLoop is a separate explicit step. Loop will
not run before primary admit unless StartProbeLoop is called. Empty
peer set is no-op (no probes fire), no panic.
Architect guidance #2 (Stop ordering): Close() stops the probe loop
FIRST (snapshot pointer under v.mu, release lock, Stop() with lock
released) BEFORE re-acquiring v.mu for peer teardown. This avoids
in-flight probeFn callbacks landing on closed peers and prevents
deadlock between loop's peersFn (which needs v.mu) and Close's peer
iteration (which holds v.mu). Pinned by
TestVolume_Close_StopsLoopBeforePeerTeardown using a probeFn that
blocks on ctx.Done().
Architect guidance #3 (cooldown propagation): UpdateReplicaSet calls
peer.SetProbeCooldownConfig on every newly-created peer (whether
first add or lineage-bump recreate) using the volume's saved
ProbeLoopConfig.CooldownBase/Cap. ConfigureProbeLoop also pushes the
config to peers that exist at configure-time. Pinned by
TestVolume_UpdateReplicaSet_AppliesProbeCooldownToNewPeers and
TestVolume_Configure_PushesCooldownToExistingPeers.
Architect guidance #4 (lineage-bump abandonment, Case 2 §1.F): the
new *ReplicaPeer instance has fresh cooldown state — failureCount=0,
probeNextEligible zero, cooldownCfg from current volume config. Old
peer's accumulated backoff cannot leak because old peer is a
distinct (now-Closed) instance. A late OnProbeAttempt arriving on
the old peer clears its in-flight flag idempotently and does NOT
mutate the new peer (already pinned by batch 2's
TestPeer_OnProbeAttempt_ClosedDoesNotUpdateCooldown; this batch adds
the volume-integration counterpart). Pinned by
TestVolume_LineageBump_NewPeerHasFreshCooldown and
TestVolume_LineageBump_OldPeerProbeAbandoned.
Volume.go additions:
- 3 new fields: probeLoop *ProbeLoop, probeCfg ProbeLoopConfig,
probeCfgSet bool (all under v.mu)
- ConfigureProbeLoop(cfg, probeFn, now) — Configure-once contract,
rejects double-configure, builds peersFn over v.peers under v.mu,
wires DefaultProbeCooldownFn / DefaultProbeResultFn, pushes config
to existing peers
- StartProbeLoop() — rejects pre-Configure, rejects post-Close,
delegates to ProbeLoop.Start (sync.Once)
- probeLoopForTest() — package-private accessor
- Close() rewritten to stop loop FIRST under careful lock release
- UpdateReplicaSet pushes cooldown config onto each newly-created peer
Tests (12/12 PASS):
- ConfigureProbeLoop happy path (no peers, no probes, clean Close)
- ConfigureProbeLoop rejects double-configure
- StartProbeLoop without Configure is rejected
- StartProbeLoop on closed volume is rejected
- StopBeforeStart idempotent at volume layer
- Close stops loop BEFORE peer teardown (with blocking probeFn)
- UpdateReplicaSet pushes cooldown to new peers (post-Configure add)
- ConfigureProbeLoop pushes cooldown to pre-existing peers
- LineageBump_NewPeerHasFreshCooldown — old failureCount=3 + non-zero
deadline; new peer has failureCount=0 + zero deadline + fresh cfg
- LineageBump_OldPeerProbeAbandoned — claim on old peer; lineage
bump tears down; new peer NOT in-flight; late OnProbeAttempt on
old peer is idempotent and does not touch new peer
- ProbeLoop_OnlyDegradedPeersDispatched — Healthy r1, Degraded r2;
loop probes only r2 (volume-integration counterpart of batch 2's
peer-level OnlyDegradedPasses)
- ProbeFnError_AdvancesBackoff — end-to-end: probeFn err →
DefaultProbeResultFn → peer.OnProbeAttempt(false) →
failureCount monotonic ≥ 3 within deadline
Full ./core/replication/ regression: PASS.
Next batch (G5-5C #4): lineage-change / stale-ack / reconnect dual-axis
tests + probe-driven dispatch branch verification.
Per architect ratification 2026-04-27 of mini-plan v0.5 §1.A binding,
this batch wires the per-peer probe gate + backoff state machine
that the probe loop (batch 1) consumes via DefaultProbeCooldownFn /
DefaultProbeResultFn.
Key design decisions per architect's three guidance items 2026-04-27:
1. Two distinct time concepts documented separately (architect #1):
- Loop interval (ProbeLoopConfig.Interval, default 5s) — how
often the probe loop wakes up.
- Per-peer cooldown (PeerProbeCooldown.Base/Cap, default 5s/60s)
— gate AFTER an attempt before the next attempt on the SAME
peer.
PeerProbeCooldown godoc explicitly calls these out so future
readers can't conflate the two.
2. peer.mu boundary (architect #2): both ProbeIfDegraded and
OnProbeAttempt run entirely under p.mu, mutating only peer-local
state. The actual probe transport call (executor.Probe) is
dispatched by ProbeLoop.dispatchProbe AFTER the gate returns,
with p.mu released. Method godocs explicitly forbid calling into
engine, executor, or other peers' locks from these methods.
3. Close()/lineage teardown (architect #3): OnProbeAttempt on a
closed peer always clears the in-flight flag (preventing leaks)
but does NOT update cooldown. This guarantees §1.E (c) clean
teardown — a delayed probe outcome arriving after Close() does
not leak state into a fresh peer that may share the underlying
address. Tested via TestPeer_OnProbeAttempt_ClosedDoesNotUpdateCooldown.
New types:
- PeerProbeCooldown — Base + Cap policy
- DefaultPeerProbeCooldown() — 5s/60s defaults
ReplicaPeer additions (all under p.mu):
- cooldownCfg PeerProbeCooldown
- probeNextEligible time.Time (cooldown deadline)
- probeFailureCount int (drives backoff doubling)
- probeInFlight bool (single in-flight per peer)
New methods:
- SetProbeCooldownConfig(cfg) — volume-level config push
- ProbeIfDegraded(now) bool — atomic gate + claim in-flight
- OnProbeAttempt(now, success) — release in-flight + advance cooldown
- IsProbeInFlight() bool — diagnostic
- ProbeNextEligibleAt() time.Time — diagnostic
Default loop wrappers (in peer.go for cohesion):
- DefaultProbeCooldownFn(now func() time.Time) CooldownFn
- DefaultProbeResultFn(now func() time.Time) ResultFn
Both accept a clock injection for testability.
Tests (10/10 PASS):
- TestPeer_ProbeIfDegraded_OnlyDegradedPasses — §1.A only-on-degraded
(5 ReplicaState cases)
- TestPeer_ProbeIfDegraded_ClosedSkipped — §1.E (c) closed-peer skip
- TestPeer_ProbeIfDegraded_InFlightGuard — INV-G5-5C-SINGLE-INFLIGHT-PER-PEER
- TestPeer_OnProbeAttempt_BackoffProgression — 5→10→20→40→40 (cap)
- TestPeer_OnProbeAttempt_SuccessResetsBackoff — counter resets to 0,
next failure restarts at Base
- TestPeer_OnProbeAttempt_ClosedDoesNotUpdateCooldown — §1.E (c)
teardown semantics
- TestPeer_StateChange_InFlightSafe — TOCTOU: state→CatchingUp
during in-flight; OnProbeAttempt clears flag without mutating state
- TestPeer_ProbeIfDegraded_ConcurrentClaims — 32 goroutines, exactly
1 claim succeeds
- TestDefaultProbeCooldownFn_Wires — wrapper delegates correctly
- TestDefaultProbeResultFn_Wires — wrapper delegates correctly
Full ./core/replication/ regression: PASS.
Next batch (G5-5C #3): catch-up/rebuild dispatch branch tests +
ReplicationVolume integration (ProbeLoop owned by volume lifecycle).
QA review of seaweed_block@<batch 1> flagged three legitimate issues:
1. Probe result/backoff seam not closed.
Fix: add ResultFn(peer, err) seam, called once per probe attempt
with the outcome (success / error / surfaced panic). NewProbeLoop
requires a non-nil resultFn. dispatchProbe wraps probeFn in a
defer/recover that converts panics into a non-nil error and
forwards every outcome to resultFn (also panic-safe via second
recover wrapper). This gives ReplicaPeer's cooldown progression
(batch 2) a single canonical hook into success/failure.
2. MaxConcurrent > 1 silently accepted.
Fix: NewProbeLoop now rejects MaxConcurrent > 1 with an explicit
error message citing the v0.5 architect binding. <= 0 still
normalizes to 1 (silent default for the typical empty config
path); =1 is the only accepted explicit value.
3. Missing Stop-cancels-inflight test.
Fix: TestProbeLoop_StopCancelsInflightProbe — probeFn blocks on
<-ctx.Done(); Stop() must return within 2s; verifies the
ctx-cancel goroutine in dispatchProbe wires stopCh → ctx
correctly.
Additional tests:
- TestProbeLoop_MaxConcurrentGreaterThanOne_Rejected (covers the
rejection path + the =0 normalization path + the =1 acceptance
path).
- TestProbeLoop_NilResultFn_Rejected (constructor seam check).
- TestProbeLoop_ResultFn_ReceivesProbeOutcome (success + error +
panic each surface to resultFn with the right shape).
- TestProbeLoop_ResultFn_PanicIsolated (panic in resultFn does not
crash loop — CP4B-2 lesson 3 extended to result callback).
Test results: 13/13 PASS. Full replication suite no regression.
Note on gopls diagnostics ("undefined: ReplicaPeer"): seaweedfs
workspace doesn't include the seaweed_block module — gopls can't
resolve cross-module identifiers. go build / go test inside
seaweed_block compiles cleanly. A go.work entry would silence the
gopls warnings; out of scope for this batch.
Next batch (G5-5C #2): peer.go::ProbeIfDegraded() + cooldown
state-machine + in-flight guard tests.
First production batch for the G5-5C primary-side degraded-peer probe
loop, per the architect-bound mini-plan v0.5 §1.A binding (Option B,
core/replication/ ownership) and §1.H audit-PASS verdict at
seaweedfs@9245446b5.
Files:
- core/replication/probe_loop.go (new): ProbeLoop struct with config
+ start/stop lifecycle (sync.Once on both); per-iteration tick that
snapshots peers via PeerSourceFn, gates each via CooldownFn,
dispatches via ProbeFn; CP4B-2 lessons applied (zero-interval
rejected at construction; stop-before-start no deadlock; callback
panic isolated via recover).
- core/replication/probe_loop_test.go (new): seven lifecycle tests
covering Start/Stop happy path, stop-before-start, idempotent
concurrent stop, zero-interval rejection, callback panic isolation,
cooldownFn gating, empty peer set, and probeFn-error-doesn't-stop.
Design:
- ProbeLoop is runtime/wiring only. No engine FSM, no transport.
- Seams (PeerSourceFn / ProbeFn / CooldownFn) injected by host so
the loop knows nothing about adapter, executor, or engine.
- Default config: Interval 5s, MaxConcurrent 1, CooldownBase 5s,
CooldownCap 60s — architect-bound G5-5C v0.5 §1.A shape.
- Authority-bound (§1.E): peersFn snapshots ReplicationVolume.peers
under lock; loop never enumerates network-discoverable addresses.
- All G5-5C INVs map cleanly to existing engine/replication state per
the §1.H audit; this skeleton adds NO recovery substrate.
Tests verified:
- go test ./core/replication/ -run TestProbeLoop -count=1: PASS (7/7)
- go test ./core/replication/ -count=1: PASS (no regression on
existing T4a-5/T4b/T4c suites)
Next batch (G5-5C #2): peer.go::ProbeIfDegraded() + cooldown
state-machine + in-flight guard tests.
Investigation found root cause of round-13 silent failures:
M02 had a leftover INPUT DROP rule from an earlier run's
verify_network_catchup that used the OLD pattern
(`iptables -I INPUT` on M02). When that earlier run aborted via
set -e before reaching its cleanup `iptables -D`, the rule
persisted across runs. Round 13's rewrite changed to OUTPUT-on-m01
but didn't clean up the legacy INPUT-on-M02 leftover. The stale
rule blocked m01→M02:9221 ship/barrier traffic for ALL subsequent
runs; primary's peer entered degraded state on first ship attempt;
all rounds after the original poisoning incident saw the symptom
"replica daemon dies silently" because the SCRIPT's pkill found
nothing (replica had been killed by the script's own pkill but
no ship traffic ever flowed during the run).
Diagnosis sequence:
1. ssh m01→M02:9221 TCP test: timeout (FAIL=124)
2. m01 iptables: empty (rules out m01-side block)
3. M02 iptables INPUT: `DROP tcp dpt:9221` (~50 dropped pkts)
4. `iptables -D INPUT -p tcp --dport 9221 -j DROP` on M02
5. Re-test: ssh→TCP echo OK
6. Re-run: chain flows through to all 3 verify steps
Fix: start_cluster() now drops both possible patterns pre-flight:
- sudo iptables -D OUTPUT -d -p tcp --dport -j DROP (round-13 pattern)
- sudo iptables -D INPUT -p tcp --dport -j DROP (round-12 leftover)
Both with || true so missing rules don't fail set -e.
Round-14 result on m01:
✓ verify_cluster_ready
✓ verify_byte_equal (LBA[0]=0xab)
✓ verify_network_catchup (LBA[1]=0xcd byte-equal in 8s after iptables disconnect+heal)
✗ verify_restart_catchup (LBA[2]=0xef MISMATCH — real recovery-path finding)
The verify_restart_catchup failure is exactly the case architect
ruling 2 named: 'run #4 naively first; if it doesn't converge,
that is a real recovery-path finding to surface, not a test flaw.'
Primary's log evidence:
After replica killed → ship attempt → barrier timeout → peer
invalidated (degraded). Primary writes LBA[2]=0xef while replica
down → 'ship gate-degraded peer=r2 lba=2 lsn=3 (peer degraded)'
— ship is gated out before any TCP attempt. Replica restarts;
no mechanism triggers primary to re-establish the peer
connection or re-ship the missed entries.
Architecturally the engine-driven catch-up path needs a trigger
(probe success, assignment re-emit, etc.) to bring a degraded
peer back online + replay missed LSNs. G5-5 surfaces that this
trigger isn't wired into the binary's runtime — surface for
architect / QA decision: (a) defer #4 to a follow-up batch with
a dedicated peer-recovery fix; (b) implement now within G5-5
scope.
Refs: round 14 m01 self-iteration; investigation traced 4
indirection layers to find the leftover iptables rule.
Per architect ratification round 13 + QA planning input:
- Add wait_until_byte_equal(lba, pattern, deadline_s) helper —
cycles kill→m01verify→restart per poll until match or timeout.
Caller-side honest about OpenReadOnly's no-concurrent-writer
assumption.
- Add iscsi_write_pattern(lba, count, pattern) helper using
python3 binary write (byte-exact pattern; tr does not grok
\xHH escapes per round-12 finding).
- Rewrite verify_network_catchup with iptables OUTPUT drop on
m01 toward M02_IP:M02_REPLICA_DATA_PORT. trap RETURN ensures
iptables -D runs on any exit path. Pass condition is direct
byte-equal at LBA[1]=0xcd, not engine-state H/R polling.
- Rewrite verify_restart_catchup with replica killall+restart
pattern. Run NAIVELY first per architect ruling — if catch-up
doesn't converge with BestEffort durability, that is a real
recovery-path finding to surface, not a test flaw.
- Diagnostic snapshots from /status/recovery kept as supporting
evidence only, not pass/fail oracle.
KNOWN ISSUE — round 13 self-test on m01: even verify_byte_equal
(which worked on round 12 part C) now fails before reaching
m01verify. Replica daemon on M02 dies silently after recording
supersede; subsequent SSH_M02 pkill matches nothing → set -e
exit. Replica's primary log ends at 'recording supersede, not
applying to adapter'; no exit/panic/SIGSEGV trace in journalctl
or dmesg. Needs further investigation:
- Is replica daemon exiting cleanly via some path I'm not aware of?
- Is there an unbuffered panic going to /dev/null because of
setsid+nohup+</dev/null?
- Was round-12-part-C's success actually flaky?
Pausing self-iteration here. Round 13 rewrite is complete in
script; #2 byte-equal already proven on hardware in round 12
part C (committed at 82e9018). #3/#4 need additional debug
either (a) on the daemon's lifecycle, or (b) on the script's
sequencing of the replica daemon during multi-step scenarios.
Refs: architect ruling round 13; QA planning input.
QA round 12 self-test on m01: m01verify reported MISMATCH on
LBA 0 — but inspecting the bytes via xxd showed the primary's
on-disk file matched the replica's, both 0x78 (ASCII 'x') × 4096.
Replication chain is correct; the script wrote the wrong bytes.
Root cause: the script used 'tr "\0" "\xab"' which DOES
NOT produce 0xab. tr's escape grammar recognizes only octal
(\NNN) and a small set of letter escapes (\n, \t, ...);
\xHH is not understood — tr substitutes with the literal first
char of the replacement string, which is '\' parsed loosely
giving 'x' (0x78). Verified empirically on m01:
$ dd if=/dev/zero bs=4096 count=1 2>/dev/null | tr "\0" "\xab" | xxd | head -1
00000000: 7878 7878 7878 7878 7878 7878 7878 7878 xxxxxxxxxxxxxxxx
Fix: use python3 binary write — guaranteed byte-exact 0xab fill:
python3 -c "...sys.stdout.buffer.write(b'\xab' * 4096)..."
Round 12 part C result on m01:
✓ verify_cluster_ready
✓ verify_byte_equal — m01verify reports 'OK 1 LBA(s) byte-equal'
This is the FIRST end-to-end PASS of acceptance criterion #2 on
real hardware. The replication chain (lineage latch + ship +
barrier + apply) is verified working. verify_network_catchup
still hits H-advance false-positive (engine state semantic is
probe-driven, not local-write-driven; same as fix in #2 but
applied per-step); will address next.
Refs: round 12 m01 self-test full progression
(rounds 1-11 surfaced 14 distinct bugs each isolated and fixed).
m01verify in verify_byte_equal expected v1.walstore but
durable provider's volumePath uses VolumeID+".bin" (provider.go:133).
Same fix in verify_network_catchup and verify_restart_catchup
helpers if they reference the file path.
Engine's Recovery.H is updated by probe events
(RecoveryFactsObserved), not by local writes. At adoption time
engine sets H = walHead = nextLSN (already 1 for empty walstore);
local write at LSN=1 advances nextLSN to 2 internally, but
Recovery.H stays at 1 until a probe re-reads boundaries. Using
H-advance as a 'silent write failure' preflight produces a false
positive — H stays at 1, check fails, but the actual write +
ship + barrier all completed (per primary log evidence).
Round 11+12 m01 evidence shows the full chain flows:
durable: dp.Open latching identity volume=v1 replica=r1 epoch=1 ev=1
durable: StorageBackend.SetIdentity latched ...
iscsi: SCSI WRITE handler lba=0 transferLen=8 dataOut=4096
durable: StorageBackend.Write entry offset=0 len=4096
durable: write observer dispatch lba=0 lsn=1
replication: OnLocalWrite volume=v1 lba=0 lsn=1 peers=1
transport: ship lazy-dial replica=r2 ok
replication: ship ok peer=r2 lba=0 lsn=1
iscsi: SCSI WRITE backend.Write ok lba=0
iscsi: SCSI SYNCHRONIZE_CACHE handler entry
replication: barrier wait peer=r2 targetLSN=1 epoch=1
replication: barrier ack peer=r2 targetLSN=1 achievedLSN=1
iscsi: SCSI SYNCHRONIZE_CACHE backend.Sync ok
Replication is working end-to-end on m01+M02 hardware.
Fix: replace H-advance check with informational log; let
m01verify byte-equal compare be the actual proof. Same change
unchanged for verify_network_catchup and verify_restart_catchup
(they still use H comparisons but for different semantics —
catch-up convergence, where H is the engine-level boundary and
the comparison is against replica's R, which the engine DOES
update on session completion).
Refs: round 12 self-test on m01 cross-node — chain flows
end-to-end; H-advance was the only false-positive blocking
m01verify from running.
QA round 11 reported the 41045e5 fix didn't take effect — same
ErrStalePrimary as round 10. Reason: my latch condition required
ALL FOUR Identity fields zero, but at EnsureStorage construction
time, AdapterProjectionView.Projection() returns:
VolumeID = cfg.VolumeID ("v1" — non-empty, from CLI)
ReplicaID = cfg.ReplicaID ("r1" — non-empty, from CLI)
Epoch = engine state Epoch (0 — no AssignmentObserved yet)
EV = engine state EndpointVersion (0 — same)
So the captured b.id = {v1, r1, 0, 0} — partially-zero, not
all-zero. SetIdentity's strict zero-check refused to update.
Subsequent lineageCheck saw proj.Epoch=1 vs b.id.Epoch=0 → still
ErrStalePrimary.
Fix: latch keys on Epoch (the meaningful "no authority line yet"
indicator). VolumeID/ReplicaID match is asserted as paranoia but
unchanged. Drift past a non-zero Epoch is still rejected (failover
safety net preserved via lineageCheck).
Plus 2 diagnostic INFO logs (per QA round-11 ask):
durable: dp.Open latching identity from projection volume=N
replica=N epoch=N ev=N (post-waitHealthy)
durable: StorageBackend.SetIdentity latched volume=N replica=N
epoch=N ev=N
Test renamed: LatchFromZero → LatchFromZeroEpoch. Now constructs
backend with the realistic pre-assignment shape ({v1, r1, 0, 0})
and verifies (a) latch transitions from Epoch=0, (b) drift past
non-zero Epoch is rejected, (c) Identity returns the latched
value.
Tests still green: durable, blockvolume (G5-4 integration), master,
authority, replication, replication/component.
Refs: QA round 11 — fix didn't take effect; my zero-check was
wrong about the pre-assignment Identity shape.
QA round 10 disambiguated: the iSCSI write reached
StorageBackend.Write but gate-rejected with 'frontend: stale
primary lineage'. Root cause: G5-5 introduced EnsureStorage which
constructs the StorageBackend BEFORE the assignment fact lands.
Original V3 design: dp.Open blocks on waitHealthy; the backend
is constructed AFTER projection.Healthy=true; wrap() captures
proj.Epoch/EV at that moment as the immutable Identity.
G5-5 changed: replicas need open storage even when projection
won't reach Healthy (their authority is the bound primary).
EnsureStorage opens storage role-agnostically. But it ALSO
constructs the backend at construction time — and at that
moment view.Projection() returns zero values (no assignment
landed yet). The captured Identity is zero. Once the assignment
lands and projection flips Healthy with Epoch=1/EV=1, every
subsequent gate compares proj{Epoch:1, EV:1, ...} against
b.id{Epoch:0, ...} and returns ErrStalePrimary.
V2 reference confirms: V2's iscsi.BlockDevice → vol.WriteLBA path
uses the engine's CURRENT epoch (not a captured one), so V2
doesn't have this issue. V3's snapshot model is sound; what's
missing is a re-stamp on first promotion to Healthy.
Fix: add SetIdentity(id) to StorageBackend with latch-from-zero
semantic.
- Latch-from-zero: zero-id backend transitions to the supplied
identity. One-shot — subsequent calls with a different id
are REJECTED (returns false). Preserves the failover safety
net (lineage drift past the latched value still fails closed
via lineageCheck → ErrStalePrimary).
- dp.Open's success path (after waitHealthy) now calls
h.backend.SetIdentity() with the current projection's lineage.
Idempotent for already-latched same-value backends.
Test: TestG5_5_SetIdentity_LatchFromZero — covers (a) zero →
first identity (allowed), (b) same identity again (no-op), (c)
drift attempt (rejected, identity unchanged so lineageCheck
fail-closed still works). Runs against both walstore + smartwal.
Tests still green: durable (0.6s), blockvolume (16.5s, G5-4
integration test still PASS), master, authority.
Refs: QA round 10 — gate-rejected disambiguation; V2 reference
read confirms architectural diff (V2 vol.WriteLBA uses live
epoch; V3 captures snapshot).
QA round 9 confirmed: even durable: write observer line is missing.
The iSCSI WRITE never reaches StorageBackend.writeBytes. Need to
walk further upstream — either the iSCSI handler isn't getting the
SCSI WRITE command, or it's getting it but using the wrong backend.
Add 6 instrumentation lines across two layers:
core/frontend/iscsi/scsi.go (doWrite):
- SCSI WRITE handler entry (fires on every WRITE_10/16 arrival)
- SCSI WRITE rejected (LBA out of range)
- SCSI WRITE rejected (short dataOut)
- SCSI WRITE backend.Write FAILED
- SCSI WRITE backend.Write ok
core/frontend/iscsi/scsi.go (handleSCSI SYNC_CACHE branch):
- SCSI SYNCHRONIZE_CACHE handler entry
- SCSI SYNCHRONIZE_CACHE backend.Sync FAILED
- SCSI SYNCHRONIZE_CACHE backend.Sync ok
core/frontend/durable/storage_adapter.go (Write):
- StorageBackend.Write entry (every Write call)
- StorageBackend.Write gate-rejected (gate() returned err)
Disambiguation matrix for QA's next run:
No 'iscsi: SCSI WRITE handler' line:
→ iSCSI session/login layer rejects command before SCSI handler.
Check if Normal session established correctly; check whether
initiator's volume sees the right size via READ_CAPACITY.
iscsi: SCSI WRITE handler line present, but no
durable: StorageBackend.Write entry:
→ SCSI handler reaches a DIFFERENT backend instance (not the
observer-wired StorageBackend). Wiring fix in main.go required.
iscsi: SCSI WRITE handler + durable: StorageBackend.Write entry,
but no observer dispatch:
→ backend gate() rejected (closed/non-operational/lineage drift).
gate-rejected line fires.
All instrumentation fires through to ship/barrier:
→ Replication is working.
Tests still green: iscsi (30.9s), durable (0.5s), blockvolume (16.7s).
Refs: QA round 9 — observer line missing from upstream
instrumentation; need iSCSI-side disambiguation.
QA round 8: ALL 6 ship/dial/barrier lines from 7a3996d are missing.
The replication outer loop is not running at all. Need to walk
upstream to find where the fan-out chain breaks.
Add 4 INFO log lines at the upstream surfaces:
durable/storage_adapter.go (writeBytes observer dispatch):
- obs nil: 'write observer NIL — replication fan-out skipped'
(means SetWriteObserver wasn't called before write hit)
- obs ok: 'write observer dispatch lba=N lsn=N'
replication/volume.go (OnLocalWrite entry):
- 'OnLocalWrite volume=v1 lba=N lsn=N peers=K'
(lets us see if peers map is empty even though
UpdateReplicaSet returned ok)
replication/peer.go (ShipEntry early-exit gates):
- 'ship gate-close peer=r2 lba=N lsn=N (peer closed)'
- 'ship gate-degraded peer=r2 lba=N lsn=N (peer degraded)'
(the existing logs are AFTER these gates, so silent
early-exit was indistinguishable from no-call)
These 4 lines + the existing 7a3996d 6 lines = 10 total. With the
next re-run we should see exactly which hop fails:
Expected per iSCSI WRITE on primary:
durable: write observer dispatch lba=0 lsn=1
replication: OnLocalWrite volume=v1 lba=0 lsn=1 peers=1
transport: ship lazy-dial replica=r2 ...
replication: ship ok peer=r2 ...
If 'observer NIL' appears: SetWriteObserver wiring race — observer
not set when iSCSI starts writing.
If OnLocalWrite shows peers=0: UpdateReplicaSet ok but peers map
became empty (race with stale-gen replay tearing down peers?).
If 'ship gate-close' / 'ship gate-degraded' appears: peer state
transitioned bad before any ship attempt.
If none of the above + ship lines silent: Backend.writeBytes itself
is bypassed (iSCSI handler not going through StorageBackend).
Tests still green.
Refs: QA round 8 — 7a3996d logs all silent on ship path.
QA round 6 finding: primary log silent on replication; can't
disambiguate 'peers=0 delivered' (timing gap) from 'peers=N delivered
but ship failed' (TCP/network). Pre-existing log discipline only
emits on the FAILURE branches:
- line 488: recording supersede (when fact.ReplicaID != self)
- line 502: UpdateReplicaSet failed
Add INFO logs on the success path so operators / hardware-test
harness can see what's actually being installed without -v / debug
flags:
blockvolume: volume v1 replication UpdateReplicaSet ok (gen=N,
peers=K): [r2@192.168.1.184:9221 ...]
blockvolume: volume v1 adopted as PRIMARY at r1@1 (EV=1)
Small log footprint (one line per fact emission, fact emissions
are rare). Production-acceptable verbosity. No behavior change.
Tests: cmd/blockvolume integration test still PASS (16.4s);
core/host/volume green.
Refs: QA round 6 — primary-fail.log silence.
Architect review round 54 findings (3 items, all addressed):
HIGH 1 — SlotFact ignores freshness:
ObservationStore explicitly says expired observations stay
visible but are 'semantically ineligible for supported snapshot
synthesis'. SlotFact was scanning the full observation map
without checking ExpiresAt. For peer-set construction this is
wrong: a stale heartbeat addr is unsafe to dial.
Fix: SlotFact now skips observations where now > obs.ExpiresAt.
New test TestObservationStore_SlotFact_ExpiredObservation_FailsClosed
verifies the boundary (ok=true within FreshnessWindow,
ok=false past expiry).
HIGH 2 — path 1 mis-stamps live-ship lineage:
resolvePeers path 1 was using the peer's OWN LastPublished
Epoch/EV. If LastPublished(v1, r2) returns r2's retained
historical authority line (e.g., r2 was previously bound at
Epoch=N before reassignment to r1 at Epoch=N+1), primary r1
would stamp live-ship frames under r2's old N — breaks the
apply gate at the replica which expects current authority.
Fix: BOTH paths now stamp peer.Epoch/EV with subscriber's
lineage. Authority/observation supplies addresses only;
subscriber stamps lineage. Updated TestResolvePeers_BothBound
to pin this (peer's old 4/1 must NOT win over subscriber's
5/2). path-1-preferred test still passes — it's about which
ADDR wins, not lineage.
LOW 3 — stale comment:
collectPeers godoc still claimed observation-derived peers
'carry Epoch=0 + EndpointVersion=0 to mark observation-derived'.
Out of date since round-54 inheritance fix. Rewrote comment
block to reflect current rule: both paths stamp subscriber's
lineage; authority/observation supplies addresses only.
All G5-5A tests still pass (10/10); cmd/blockvolume G5-4
integration test PASS; full V3 suite green.
Refs: architect round 54 review of 61f5ff6.
Architect ratification round 54 (2026-04-27): collectPeers may
synthesize peer descriptors for topology slot members observed by
heartbeat even when they don't have a bound authority publication.
Root cause from QA round 54: V3 controller only mints
AssignmentInfo for the BOUND replica (Publisher.apply path).
Supporting replicas have no published authority line, so
master.collectPeers' pub.LastPublished returns false for them,
peers list is empty, primary's ReplicationVolume has no peers,
fan-out/Sync barrier has no acks → iSCSI fsync I/O error.
Architect Option A (chosen): collectPeers falls back to
ObservationStore for slot members without published lines.
Topology membership is the allow-list (option R / arbitrary
observed nodes still rejected). Authority state stays clean —
Option B (mint presence records into pub.state) was rejected.
Implementation:
core/authority/observation_store.go:
+ SlotFact(volumeID, replicaID) — returns latest-observation
SlotFact across all servers; fail-closed on empty DataAddr.
core/host/master/services.go:
collectPeers signature changes from (volumeID, selfReplicaID
string) to (volumeID string, selfInfo adapter.AssignmentInfo)
so observation-derived peers can inherit subscriber's Epoch/EV.
Body extracted to pure helper resolvePeers() for testability.
Peer construction policy:
Path 1: pub.LastPublished hits → use authority Epoch/EV/addrs
Path 2: SlotFact hits → use heartbeat addrs + INHERIT
SUBSCRIBER'S Epoch/EV (live ships carry primary's
lineage; replica validates against it)
Else: skip fail-closed
Inheriting subscriber's Epoch/EV is required because
ReplicaPeer constructor (replication/peer.go:130) rejects
zero values — the lineage stamps every outgoing live-ship
frame, and primary's authority is what the supporting replica
validates against.
Tests:
core/authority/observation_store_slotfact_test.go: 5 tests
(round trip, empty store, fail-closed empty addr,
latest-wins across servers, vol/replica mismatch)
core/host/master/services_g5_5a_test.go: 5 tests
(headline r1-bound + r2-observed-only, both bound,
neither bound nor observed, nil obs store, path-1 wins
over path-2)
All 10 G5-5A tests pass; full V3 suite green (23/23 packages
incl. cmd/blockvolume G5-4 integration test still green).
No engine/adapter behavior change — touches master/observation
peer-set construction only.
Refs: QA round 54 finding (cross-host fsync I/O error);
architect Option A ratification 2026-04-27.
QA round 54: cluster came up, iSCSI session established, but
fsync (SYNCHRONIZE CACHE) returned I/O error. Root cause: replica
bound --data-addr 0.0.0.0:9221 AND advertised that string to master
heartbeat. Master minted AssignmentFact.peers[*].DataAddr=0.0.0.0:9221.
Primary's BlockExecutor tried to dial 0.0.0.0:9221 — unroutable
destination — connection failed. Replication fan-out + Sync barriers
silently failed (best-effort log line; the fsync gets I/O error).
The daemon advertises the literal --data-addr string verbatim:
cmd/blockvolume/main.go:230 → cfg.DataAddr = f.dataAddr
→ host heartbeats DataAddr to master
→ master.collectPeers copies it into AssignmentFact.peers
→ primary dials peers[*].DataAddr
So for cross-host the bind addr MUST be a routable IP, not 0.0.0.0.
On Linux, binding to a specific local-interface IP works fine and
ensures the literal advertised string is routable.
Fix: extract M01_IP / M02_IP from M01_HOST / M02_HOST and use as
both bind and advertise:
Tier 2: M01_PRIMARY_BIND_IP=${M01_IP}, M02_REPLICA_BIND_IP=${M02_IP}
Tier 1: M01_PRIMARY_BIND_IP=127.0.0.1, M02_REPLICA_BIND_IP=127.0.0.1
start_primary / start_replica now use the IP variables for both
--ctrl-addr and --data-addr. Master's --listen stays 0.0.0.0 (it's
the destination of heartbeats, not advertised).
This is a script-side fix only; daemon code unchanged. Refs QA
round 54.
QA round 53 isolation: SSH_OPTS included -n which redirects ssh
stdin from /dev/null. With bash -s, remote bash reads script from
stdin — stdin is EOF (because -n) so bash exits immediately, daemon
never starts, master.log stays empty.
QA evidence: dbg.sh on m01 reproduced heredoc form WITHOUT -n;
bash -s correctly read heredoc, blockmaster launched, port 9180
bound, proof.txt confirmed heredoc execution.
Fix per architect option (A): split SSH options into two sets:
SSH_OPTS_BASE — shared: -T (no PTY) + BatchMode=yes
SSH_OPTS — base + -n; for ssh host CMD patterns
SSH_OPTS_LAUNCH — base only (no -n); for ssh host bash -s
launch_m01 / launch_m02 use SSH_OPTS_LAUNCH. PTY-hang protection
comes from -T alone, present in both sets.
Verified: launch_m01 heredoc body executes; variable expansion
works; remote-shell PID resolves correctly.
QA round 53 finding (Tier 2 m01 → M02): start_replica's SSH session
hung even on Linux (m01 native ssh, no Windows-Git-Bash quirks).
Root cause is a `\<newline>` line-collapse hazard in the
double-quoted SSH command argument:
$SSH_LAUNCH_M02 "
setsid nohup /tmp/g5-blockvolume \
--master ... \
...
> .../replica.log 2>&1 </dev/null &
disown \$! 2>/dev/null || true
sleep 1
exit 0"
The local shell processes `\<newline>` as line continuation INSIDE
the double-quoted string. The `\` at end of every option line
collapses lines, which can in some bash interactions produce a
joined argv where `&` runs into `disown` directly with no
separator. Remote bash then parses the joined statement
incorrectly, never executes `disown $!` / `sleep 1` / `exit 0`,
remains attached to the bg daemon, and SSH hangs.
The `\<newline>` substitution happens in the LOCAL shell (the one
running iterate.sh), so it's not Windows-Git-Bash-specific —
reproduces on m01 (Linux) too.
Fix per architect option (A) round 53: pipe the command body to
remote bash via `bash -s` heredoc instead of double-quoted ssh
argument.
launch_m01 <<EOF
setsid nohup CMD ARG1 ARG2 ... > LOG 2>&1 </dev/null &
disown \$! 2>/dev/null || true
sleep 1
exit 0
EOF
With heredoc + `bash -s`:
- body is piped to remote bash's stdin verbatim
- newlines are preserved literally regardless of any local
shell processing
- statement boundaries are unambiguous
- daemon command on a single line (no `\<newline>` continuations)
eliminates the entire ambiguity class
Implementation:
- new launch_m01() / launch_m02() functions handle Tier 1
(LOCAL_MODE=1, run via local `bash -s`) and Tier 2 (run via
`ssh ... bash -s`) with shared timeout-prefix logic
- start_master / start_primary / start_replica use the new
helpers + heredoc body
- removed SSH_LAUNCH_M01 / SSH_LAUNCH_M02 vars (subsumed by
launch_m01 / launch_m02)
Verified: local Tier-1-style smoke test launches a `sleep 30` bg
process, disowns it, and exits within 1.08s (the explicit `sleep
1` + overhead). Pre-fix this took ~5s (timeout fallback). The bg
process detached and ran independently. This proves all three
post-`&` statements (disown / sleep / exit) execute as separate
commands — the line-collapse hazard is structurally eliminated.
Refs: QA Tier 2 round 53 finding (Linux SSH hang); architect
option (A) ratified; option (B) `;<newline>` rejected per QA's
clarification (newlines also stripped by `\<newline>` so
semicolons alone don't help).
Architect option (a) ratified round 53. Two changes to sync_and_build:
1. PREBUILT_BIN_DIR fast-path for Tier 2 (cross-node m01+M02):
When PREBUILT_BIN_DIR is set, skip source-tar + remote-build
entirely. scp the 3 pre-built binaries (g5-blockmaster,
g5-blockvolume, g5-m01verify) directly to m01:/tmp/ and onward
to M02. Mirrors the existing LOCAL_MODE branch pattern.
Use case: Windows workstation cross-compiles via
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ...
then sets PREBUILT_BIN_DIR=/path/to/bins. No m01-side source
tree or `go` install needed. Also works for CI artifact paths.
2. SRC_DIR safety guard (the bug QA hit round 53):
When iterate.sh is copied away from the repo and run with
SRC_DIR resolving to "" or "/" (e.g., bash /tmp/iterate.sh
without overriding SRC_DIR), the prior code called
`cd "$SRC_DIR" && tar -czf /tmp/g5-src.tgz .`
which tarred the root filesystem. QA killed it before damage,
but the unsafety must not exist.
Guard sequence (refuses with named error before any tar):
- SRC_DIR empty or "/" → die
- SRC_DIR/go.mod missing → die
- SRC_DIR/cmd/blockvolume/ → die
- else → safe to tar
Verified all 4 die paths fire with clear messages: empty, "/",
non-repo path, PREBUILT_BIN_DIR with missing binary.
Acceptance criteria #1-#7 unaffected; only the build/sync mechanism
changes. The 4 verify_* scenario bodies are untouched.
Refs: QA Tier 2 round 53 finding (SMB-driven iterate.sh attempted
to tar root filesystem); architect option (a) binding.
QA Tier 2 m01 cross-node verification surfaced: cluster comes up
correctly (master + primary + replica all start, replica logs
"authority is now r1@1; recording supersede" — exactly the
architect-binding role split), but the Windows Git Bash side of
start_replica's SSH session never returns even though the remote
process is detached via setsid+nohup+disown.
Root cause: OpenSSH on Windows Git Bash allocates a PTY for the
remote shell (default behavior when stdin is a terminal); the
local ssh client waits for the PTY to detach, which never happens
even after setsid. Standard Git Bash quirk; well-documented but
not previously hit by V3 because prior cross-node scripts used
short-lived SSH calls only.
Two-layer fix:
1. Add -T (no PTY) and -n (close local stdin) to all SSH commands
via shared SSH_OPTS variable. -T is the primary fix; -n was
already added by prior edit but is insufficient alone.
2. Wrap launch-and-detach SSH calls (start_master/_primary/_replica)
with `timeout 15 --preserve-status` as defense-in-depth. If SSH
still hangs (rare with -T -n applied), the script moves on after
15s. Remote process is already disown'd so the only stale state
is a local ssh client process — harmless. Falls back to no-op
wrapper if `timeout` isn't installed (Git Bash without coreutils).
Also tightens remote launch heredoc:
- explicit `disown $!` after backgrounding to detach from job table
- explicit `exit 0` to force the wrapping shell to exit cleanly
even if any prior command had a non-zero status
Tested: bash -n syntax clean; timeout available on local box; no
local-mode regression (LOCAL_MODE=1 path uses bash -c, not ssh).
Refs: QA Tier 2 round 53 finding; environmental, not a product bug
(daemon comes up correctly on cross-node hardware per the same
session's logs).
Architect round-52 findings absorbed:
- iscsi-listen 0.0.0.0 → 127.0.0.1 (T2 iSCSI loopback-only rule)
- remote SSH bash blocks: set -euo pipefail + DEV non-empty assert
+ primary.H advancement check (catches silent dd failure masking)
- RecoveryDecision empty no longer acceptable: must observe
explicit catch_up transition or fail
- (walstore.OpenReadOnly already correct per sw earlier commit)
Two-tier mode added:
- LOCAL_MODE=1: single Linux host (e.g. WSL); both processes on
localhost; iSCSI/race/full-suite skip if iscsiadm/Go-too-old
- LOCAL_MODE=0 (default): m01 cross-node Tier 2
Tier 1 verified PASS on WSL (cluster bring-up + role split; iSCSI
tests cleanly skip).
SSH detach fixes:
- pkill -f '[g]5-block' (regex character class avoids self-match)
- setsid nohup ... & (replaces & disown; full process group break)
- ssh -n (no stdin; helps SSH session cleanup on Windows Git Bash)
Tier 2 (m01) status: cluster comes up correctly end-to-end (master +
primary + replica all running; replica logs role-split supersede),
but SSH session for start_replica step doesn't return cleanly from
Windows Git Bash — known SSH-from-Windows quirk. Tier 2 should run
from a Linux SSH host OR with ProxyJump to avoid Windows-side hang.
Tier 1 evidence is sufficient for criteria #1 (cluster ready, role
split). Criteria #2/#3/#4 require iSCSI which neither WSL (no
open-iscsi) nor Tier 2 (Windows-SSH hang) currently runs end-to-end.
Carry: Tier 2 on Linux-host SSH OR install open-iscsi on WSL.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add two-tier test mode to iterate-m01-replicated-write.sh:
Tier 1 (LOCAL_MODE=1): both processes on localhost, no SSH/scp
- drives faster dev iteration (no cross-node sync overhead)
- iSCSI tests skip with explicit message if iscsiadm not present
- intended for WSL/Linux dev workstation iteration before
escalating to cross-node m01/M02 verification
Tier 2 (default, LOCAL_MODE=0): m01 (192.168.1.181) + M02
(192.168.1.184) cross-node — deployment-realism close evidence
Implementation:
- SSH_M01/SSH_M02 redefined as `bash -c` in LOCAL_MODE
- sync_and_build skips tar/scp in LOCAL_MODE; builds locally
- master subscribe target switched to 127.0.0.1 vs 192.168.1.181
- HAS_ISCSI sentinel set per-mode for skip messaging
Addresses architect/QA review round 52 findings:
MEDIUM — OpenReadOnly inherited writer machinery:
Original implementation reused openInitialized which started
flusher + committer + admission goroutines and persisted the
superblock back through Close. Those writes target the fd
opened O_RDONLY — silent OS-layer failure but a "read-only
verifier" leak.
Rewrite: WALStoreReader is now a minimal handle (fd + sb + dm)
with its own Read/Close paths. No openInitialized call, no
background goroutines, Close only releases the fd. Same
WAL-then-extent merge semantic for Read(lba); recoverWAL is
invoked directly to populate the dirty map (it's a pure read
pass over WAL frames — no fd writes).
Pinned by new TestOpenReadOnly_NoBackgroundGoroutines that
snapshots runtime.NumGoroutine() before/after Open+Read+Close
and asserts no growth (tolerance 1 for runtime jitter; flusher
+ committer alone would add 2).
HIGH — verify_byte_equal could false-pass on silent write failure:
Same hardening pattern already applied to verify_network_catchup
+ verify_restart_catchup (user-applied edits) now extended to
verify_byte_equal:
- remote SSH heredoc uses `set -euo pipefail`
- DEV non-empty assertion before dd
- primary.H captured before + after, asserted strictly greater
(catches silent-write-failure masking before the byte-equal
check ever runs)
- explicit echo "WROTE-LBA-0-PATTERN-AB" stamped on success
so the surrounding script can grep for the marker if needed
BLOCKER from round 51 (--iscsi-listen 0.0.0.0:) was already
resolved in the prior commit (file edit set 127.0.0.1).
Tests: core/storage 3/3 PASS (incl. new goroutine fence);
core/host/volume + cmd/blockvolume + smartwal all green.
Script syntax-checked clean (bash -n).
Refs: sw-block/design/v3-phase-15-g5-5-mini-plan.md v0.3 §6
risks (architect REVIEW round 52 findings)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per architect-ratified mini-plan v0.3 §1 file map. Three additions
(no engine/adapter behavior changes per architect §6 binding):
1. /status/recovery endpoint (opt-in, loopback-only, default off)
- core/host/volume/status_server.go: handler + EnableRecoveryEndpoint()
- core/host/volume/projection_bridge.go: AdapterProjectionView.EngineProjection()
accessor returns the underlying engine.ReplicaProjection (Mode/R/S/H/
RecoveryDecision/Reason). Surfaces existing engine state via HTTP;
no engine code change.
- cmd/blockvolume/main.go: --status-recovery CLI flag (default off);
calls status.EnableRecoveryEndpoint() when set
- core/host/volume/status_server_test.go: 3 new tests
(Disabled→404, Enabled→200+fields, WrongVolume→404)
2. core/storage.OpenReadOnly + WALStoreReader
- Read-only walstore opener for hardware byte-equal verification.
Opens O_RDONLY, runs Recover() to populate dirty map, exposes
Read(lba) only (no Write/Sync surface). Caller must ensure no
concurrent writer.
- core/storage/walstore_readonly.go + walstore_readonly_test.go
(round-trip write→close→OpenReadOnly→Read passes; missing-file
fence)
3. cmd/m01verify standalone helper (build-tag m01verify)
- Separate cmd subpackage so it doesn't collide with blockvolume's
main(). Builds only with `go build -tags m01verify`.
- Opens replica's walstore via storage.OpenReadOnly, calls Read(lba)
per LBA in target range, SHA-256 vs --expected-pattern (single hex
byte) or --expected-file (binary payload). Prints OK / MISMATCH +
exit 0/1.
- Architect REVISE round 51: NO raw .extent peek; storage abstraction
is the only authoritative read path.
4. scripts/iterate-m01-replicated-write.sh — full G5-5 orchestration
- Replaces v0.1 skeleton's TODO scenario bodies with real verify
steps matching mini-plan v0.3 §2 acceptance criteria #1-#6.
- 6 verify functions: cluster_ready, byte_equal (kernel iSCSI write
+ m01verify storage-aware compare), network_catchup (iptables
drop + /status/recovery R/H polling), restart_catchup (SIGTERM
replica + restart same --durable-root + R/H polling), race_stress
(TestG54_BinaryWiring x10 -race on m01), full_suite (go test ./...).
- Build phase compiles all 3 binaries on m01 (master + volume + verify)
and scp blockvolume + m01verify to M02. SMB share path used in
prior smoke is replaced by direct scp for simpler dependency.
Acceptance gates per mini-plan v0.3 §2:
#1-#6 covered by script verify steps; m01 hardware run is QA's
responsibility per `v3-batch-process.md §14` (sw drafts, QA verifies).
#7 (v3-dev-roadmap.md update at gate-close) deferred to §close.
Full V3 regression: 23/23 packages green from local Windows run
(includes G5-4 binary integration test still passing at 16.4s; new
status_server tests pass; new walstore_readonly tests pass; m01verify
builds clean under -tags m01verify).
Hard binding preserved: zero engine/adapter behavior changes. The
/status/recovery endpoint surfaces an already-computed projection;
walstore.OpenReadOnly is a new read-only wrapper around existing Recover
+ Read; no semantic changes to either.
Refs: sw-block/design/v3-phase-15-g5-5-mini-plan.md v0.3
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Mirror T4d-4 part B's WithEngineDrivenRecovery() (component framework
binding at core/replication/component/cluster.go:357-369) into the
production binary. Constructs ReplicationVolume + ReplicaListener
per volume and wires both into the host lifecycle, so replicas can
accept incoming WAL traffic and primaries can fan out writes.
Architect bindings (mini-plan v0.4 §7.1 round 50):
Replica readiness — frontend.Projection.Healthy is reused with
role-aware semantics: primary reaches Healthy=true via the existing
caught-up + fence-acked path (engine.ModeHealthy); replica role
(assigned to SUPPORTING; engine apply skips OnAssignment via
recordOtherLine) keeps Healthy=false indefinitely. Frontend bind
(--iscsi-listen / --nvme-listen) is operator-controlled per role:
not passed for replicas. G5-4.5 integration test uses precise
assertion names (replica MUST NOT report Healthy=true).
--ctrl-addr reuse REJECTED — verified ReplicaListener should bind
on --data-addr instead. transport executor's Probe + Ship paths
dial peer.DataAddr (executor.go:303); listener must bind on the
address master mints into AssignmentFact.peers[*].DataAddr — i.e.,
--data-addr. --ctrl-addr stays reserved for future control-plane
split (no current binder; verified no conflict with NVMe / iSCSI
/ status: each has its own dedicated --*-listen / --status-addr
flag). Mini-plan v0.4 said "reuse --ctrl-addr"; correct answer
found during code is --data-addr. PR description carries this
finding for ratification.
Files changed:
- core/host/volume/host.go: SetReplicationVolume(rv) + RWMutex
around h.replication so binary can wire post-New (storage opens
after host construction).
- core/frontend/durable/provider.go: EnsureStorage(volumeID) opens
LogicalStorage role-agnostically (without waiting for Healthy);
Backend(volumeID) accessor returns the same StorageBackend
instance dp.Open returns later. Both used by binary main.go.
- cmd/blockvolume/main.go: after EnsureStorage + RecoverVolume,
construct ReplicationVolume(volumeID, store) + h.SetReplicationVolume,
SetWriteObserver on the backend for fan-out, ReplicaListener on
--data-addr + Serve. Cleanup chain (LIFO): listener.Stop +
rv.Close BEFORE durableProv.Close (storage borrowed by both).
- cmd/blockvolume/g5_4_l2_replication_test.go: NEW. L2 subprocess
integration test — real cmd/blockmaster + 2× cmd/blockvolume over
TCP with --expected-slots-per-volume 2; asserts primary reaches
Healthy=true, replica does NOT (role split per architect
binding), replica's --data-addr accepts TCP (listener bound).
Acceptance criteria status (mini-plan v0.4 §4):
#1 binary constructs ReplicationVolume ✅ verified by code review
#2 in-process role-appropriate ready ✅ G5-4.5 PASS
#3 byte-equal primary→replica ⏸ deferred to G5-5 m01
(in-process test would need iSCSI/NVMe Go client to drive
frontend writes; subprocess pin for wiring + role split is in;
m01 hardware has the kernel iSCSI client tooling)
#4 stop-restart catch-up convergence ⏸ deferred to G5-5 m01
(depends on #3 frontend write driver)
#5 no regressions ✅ full V3 suite green
#6 10x -race stress ⏳ pending m01 verification
#7 invariant ledger inscription ✅ 5 INV-BIN-WIRING-* in
v3-invariant-ledger.md (companion commit in seaweedfs repo)
Refs: sw-block/design/v3-phase-15-g5-4-mini-plan.md v0.4
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
cmd/blockmaster/main.go hardcoded ExpectedSlotsPerVolume: 3 in the
TopologyControllerConfig. The TopologyController's
validateVolumeTopology rejects every observation snapshot whose
slot count differs from this value, returning an error from
SubmitObservedState that propagates back to the observation host
without a master-log line.
Result with a 2-node smoke topology (m01-primary + m02-replica):
master is silent, no assignments minted, volumes timeout at
durable open with frontend.ErrNotReady — the symptom QA hit
during G5-4 cross-node bring-up.
Fix: add --expected-slots-per-volume CLI flag, default 3
(production RF=3 unchanged). 2-node smoke clusters pass
--expected-slots-per-volume 2.
Long-term refactor (separate ticket): the validator should
compare snapshot slot count against the topology's per-volume
slot count, not a single global config — that's the real
per-volume RF model.
Refs: sw-block/design/v3-phase-15-g5-m0102-bringup-answer.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
writeCountingBackend.lastWrite was a plain []byte field. The
chunked-R2T integrity tests drive Writes serially (assumption
documented in the original code), but TestT2A_ConcurrentQueueStress
shares one writeCountingBackend across 8 IO queues, violating that
assumption — m01 -race reported a write-write race on the field.
Race report (m01, T4d-4 verification):
WARNING: DATA RACE on writeCountingBackend.lastWrite
Both goroutines: nvme_test.(*writeCountingBackend).Write
Stack: dispatchIO → handleWrite → IOHandler.Handle → ...
Fix: replace plain field with atomic.Pointer[[]byte]. Each Write
Stores a fresh copied slice (never mutated after store); readers
Load() to observe a stable snapshot. Semantics preserved for the
chunked-R2T integrity check sites.
Production code untouched. Production session model already
correctly synchronized (per QA's race triage during T4d closure).
Refs §8B.4 Discovery Bridge: QA-owned NVMe test fixture lastWrite
race. Architect-approved 2026-04-26 (pingqiu). Verify on m01:
go test -race -count=10 -run TestT2A_ConcurrentQueueStress \
./core/frontend/nvme/
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
HARD GATE #3 surfaced 2 real bugs in engine-driven recovery flow that
synthetic OnSessionClose injection didn't expose. Both fixed here.
Bug #1 — catch-up exhaustion missed escalation when Decision was
re-classified mid-flight:
Symptom: stray auto-probe arriving between catch-up retries
re-classified Recovery.Decision (R<S → Rebuild). Exhaustion-branch
checked stale Decision and fell through to terminal-degraded
instead of round-47 escalation.
Fix: key on st.Session.Kind == SessionCatchUp (truth = what
session actually failed), not on mutable Recovery.Decision.
Bug #2 — WALRecycled set Decision=Rebuild but never emitted
StartRebuild; subsequent probe could downgrade:
Symptom: WALRecycled escalation only emitted PublishDegraded; no
rebuild command. A subsequent probe with R>=S could re-classify
back to CatchUp before any rebuild fired.
Fix: new RecoveryTruth.RebuildPinned sticky bool. Set by both
WALRecycled escalation AND catch-up exhaustion. decide() honors
it as override — forces Decision=Rebuild + emits StartRebuild
regardless of R/S/H. Cleared by successful rebuild
SessionCompleted (or identity reset).
WALRecycled also now emits StartRebuild immediately (in addition
to PublishDegraded for diagnostic surface).
Bug #3 (architect-required rule) — already correct:
Rebuild's MaxRetries=0 routes the first rebuild failure to the
existing terminal-degraded branch. No code change needed.
New invariants pinned:
INV-REPL-REBUILD-DECISION-STICKY — once escalated to rebuild
(WALRecycled or exhaustion), probe re-classification cannot
downgrade to CatchUp before rebuild completes.
INV-REPL-REBUILD-EMITTED-ON-WAL-RECYCLED — WALRecycled escalation
emits StartRebuild immediately, not just PublishDegraded.
Full L2 tests (HARD GATE #3) — all PASS through real
engine→adapter→executor wiring (NOT synthetic injection):
- TestT4d4_FullL2_CatchupRetryExhausted_EscalatesToRebuild
- TestT4d4_FullL2_WALRecycled_EscalatesImmediate
- TestT4d4_FullL2_LastSentMonotonic_AcrossRetries (QA #8 full form)
Files:
- core/engine/state.go — RebuildPinned field with invariant doc
- core/engine/apply.go — sticky-rebuild gate in decide();
WALRecycled emits StartRebuild + pins; exhaustion uses
Session.Kind + pins; rebuild SessionCompleted clears pin
- core/engine/recovery_test.go — fixtures set Session.Kind:
SessionCatchUp (was relying on old Decision-based check)
- core/replication/component/t4d4_full_l2_matrix_test.go — NEW,
3 HARD GATE #3 tests via engine-driven flow with substrate
fault injection wraps
Verified: full V3 suite green; m01 -race ×20 stress on the 3 HARD
GATE tests, no flakes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per T4d mini-plan v0.5 §2.4 (architect round-47 expanded scope).
Closes 3 of 4 HARD CLOSE GATE items (#1#2#4); #3 full L2 matrix
+ QA #8 LastSentMonotonic full form deferred to part C with
substrate fault injection.
ROUND-47 ENGINE CHANGE — catchup-exhaustion escalates to rebuild:
- core/engine/apply.go applySessionFailed: catch-up budget exhaustion
now DIRECTLY emits StartRebuild (Decision flips to Rebuild,
StartRebuild command emitted with current Recovery.H as TargetLSN).
Pre-round-47: cleared Decision + emitted PublishDegraded; rebuild
only fired if a fresh probe arrived. Round-47: rebuild path becomes
engine-driven end-to-end without probe dependency.
- Rebuild has MaxRetries=0 per DefaultRuntimePolicyFor; rebuild
failure terminates (Decision cleared, PublishDegraded emitted).
Pinned by INV-REPL-CATCHUP-EXHAUSTION-ESCALATES-TO-REBUILD +
INV-REPL-REBUILD-FAILURE-TERMINAL.
- Existing TestSessionFailed_NonRecycled_RetriesUntilBudget updated
for round-47 escalation (asserts StartRebuild emit on attempt #4
+ Decision=Rebuild + DecisionReason="catchup_budget_exhausted").
WITHENGINEDRIVENRECOVERY() REAL — round-47 HARD GATE #1 + #2:
- core/replication/component/cluster.go: WithEngineDrivenRecovery()
now installs ONE VolumeReplicaAdapter per replica at Start.
Adapters are wired to executors via the constructor's
executor-callback registration (existing adapter ctor behavior).
- New PrimaryNode.adapters field + Cluster.Adapter(idx) accessor.
- New Cluster.DriveAssignment / Cluster.DriveProbeResult helpers
for test scenarios driving engine state through real adapter.
- Stub warning text + log message removed; engine-driven recovery
is now the real path when opted in.
G5-DECISION-001 SERIALIZABILITY — round-47 obligation:
- core/engine/g5_decision_001_serializability_test.go pins that
engine.ReplicaState (+ all nested truth structs) round-trips
through encoding/json cleanly. T4d-4 obligation: keep struct
serializable so G5 can choose Path A (persist recovery state
across primary restart) without structural rewrite.
- 2 tests: full-state round-trip + zero-value round-trip
- T4d-4 does NOT implement persistence — just maintains the
serializability property.
NEW TESTS (9):
core/engine/recovery_test.go (2 new + 1 updated):
- TestT4d4_CatchupExhaustionEscalatesToRebuild (round-47 #4 pin)
- TestT4d4_RebuildExhaustionIsTerminal (rebuild MaxRetries=0
termination)
- (existing) TestSessionFailed_NonRecycled_RetriesUntilBudget
updated for round-47 escalation semantic
core/engine/g5_decision_001_serializability_test.go (2):
- TestG5Decision001_ReplicaState_RoundTripJSON
- TestG5Decision001_ReplicaState_ZeroValueStable
core/replication/component/t4d4_engine_driven_test.go (5):
- TestT4d4_WithEngineDrivenRecovery_IsReal (HARD GATE #1)
- TestT4d4_AdapterWithoutWithEngineDrivenRecovery_IsNil (fence)
- TestT4d4_DriveAssignment_EngineEmitsProbeReplica
- TestT4d4_RoundTrip_AssignmentToProbeToCatchUp_EngineDriven
- TestT4d4_CatchupBudgetExhausted_EngineEmitsRebuild
Existing test updated for round-47:
- core/adapter/adapter_test.go
TestPreparedNeverStarted_FailsClosedOnImmediateStartError:
set rebuildErr matching catchUpErr; assert chain ends at
Degraded after retry+escalate+rebuild-terminal (was: assert
PhaseFailed after first attempt — round-47 makes that
intermediate not terminal).
NOT in part B (deferred to part C):
- HARD GATE #3: Full L2 matrix incl QA #8 LastSentMonotonic full form
— needs substrate fault injection wrapping engine-driven flow
- Windows TempDir cleanup race + sessionID coordination + test rename
Forward-carry status:
- Round-47 engine change preserves all prior round-43/44/46
invariants (lane purity, stale-skip, no per-LBA regression)
- T4d-1 typed-kind contract: forward-carries
- T4d-2 lane-pure apply gate: forward-carries
- T4d-3 R+1 threading: forward-carries
- T4d-4 part A (RecoveryMode + Stop lifecycle): forward-carries
- 22 packages green; 0 failures
Refs: T4d mini-plan v0.5 §2.4 (architect-ratified expanded scope);
round-47 architect ruling (catchup-exhaustion escalates to rebuild +
G5-DECISION-001); G-1 sign 80036404c (G-1 v0.2).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per T4d mini-plan v0.4 §2.4 expanded scope. Part A of three: smaller
substrate cleanups + lifecycle hardening land first; Path B fold
(ReplicationVolume↔adapter wiring + WithEngineDrivenRecovery real)
follows as part B; Windows cleanup + L2 matrix as part C.
T4c §I row 6 closure (RecoveryMode interface method):
- core/storage/logical_storage.go — add RecoveryMode() to
LogicalStorage interface (returns substrate's tier-1 sub-mode
per memo §5.1 / §13.0a)
- core/storage/store.go BlockStore.RecoveryMode() →
RecoveryModeStateConvergence (in-memory; ScanLBAs synthesizes)
- core/storage/walstore.go WALStore.RecoveryMode() →
RecoveryModeWALReplay (V2-faithful per-LSN)
- core/storage/smartwal/store.go Store.RecoveryMode() →
RecoveryModeStateConvergence (per-LBA dedup)
- core/transport/catchup_sender.go — replace duck-typed
CheckpointLSN probe with e.primaryStore.RecoveryMode() interface
call. Forwards cleanly through component framework wraps via
embedded LogicalStorage.
- core/replication/component/faults.go godoc — replace stale
"MASKED by wrap" limitation note with T4d-4 closure note;
AssertSawRecoveryMode now works correctly under wraps
T4d-4 lifecycle (BUG-005 non-repeat):
- core/replication/volume.go — Stop() canonical entry point added
(delegates to existing Close); semantic clarity over Close().
Both methods are equivalent in T4d-4; Stop() is the named entry
for "stop volume lifecycle activity" while Close() retained for
backward compatibility. Future expansions (drain pending I/O,
stop background goroutines) land in Stop().
- INV-REPL-LIFECYCLE-HANDLE-BORROWED-001 pinned by
TestReplicationVolume_Stop_DoesNotCloseBorrowedStore: store is
STILL usable after volume.Stop (substrate handle is borrowed,
never closed by us — BUG-005 discipline)
- TestReplicationVolume_Stop_Idempotent: second + later Stop calls
are no-ops returning nil
- TestReplicationVolume_Stop_TearsDownPeers: empty-set lifecycle pin
Tests added (5 new):
- TestReplicationVolume_Stop_Idempotent
- TestReplicationVolume_Stop_DoesNotCloseBorrowedStore
- TestReplicationVolume_Stop_TearsDownPeers
- TestStorageRecoveryMode_BlockStore_StateConvergence
- TestStorageRecoveryMode_Walstore_WALReplay
- TestStorageRecoveryMode_LogicalStorageInterface_HasMethod
(compile-time fence pinning RecoveryMode is on the interface,
not just on substrate impls)
NOT in part A (deferred to part B / C):
- ReplicationVolume↔adapter wiring (Path B fold, part B)
- WithEngineDrivenRecovery real binding (Path B fold, part B)
- Full L2 integration matrix (part C)
- Windows TempDir cleanup race (part C)
- Test rename per kickoff §5 (part C)
- sessionID coordination (T4c §I row 5; part C — minor)
22 packages green; 0 failures. Forward-carries: T4c-2 + T4d-1 +
T4d-2 + T4d-3 invariants all green; new RecoveryMode plumbing
preserves T4c-2 INV-REPL-RECOVERY-MODE-OBSERVABLE.
Refs: T4d mini-plan v0.4 §2.4 (architect-ratified expanded scope);
T4c §I row 6 (substrate RecoveryMode method); kickoff §2.1 (BUG-005
non-repeat lifecycle); G-1 sign 80036404c (G-1 v0.2 + planning
artifacts).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per QA T4d-2 final closure: pre/with-T4d-3 doc fixes.
apply_gate.go (lines 38-43): the godoc on ReplicaApplyGate still
described "lane discrimination" as the gate reading
lineage.TargetLSN — that text predated the round-46 rework.
Replaced with a clear statement of the lane-pure contract:
- Gate is LANE-PURE; caller decides
- Caller invokes ApplyRecovery vs ApplyLive explicitly
- Gate does NOT inspect lineage payload to discriminate
- Today's caller (transport replica.go) uses a transitional
TargetLSN-based shim — but the shim lives at the CALLER
- The architectural fence (gate is lane-pure) is durable; the
caller's signal source is replaceable
- Reference to CARRY-T4D-LANE-CONTEXT-001 for the future fix
replica.go NewReplicaListenerWithApplyHook godoc: previously
described `hook.Apply(lineage, lba, data, lsn)` as the dispatch
mechanism — that signature no longer exists post-round-46.
Replaced with:
- Handler dispatches caller-side to hook.ApplyRecovery /
hook.ApplyLive
- Hook itself is LANE-PURE
- Today's caller-side decision is a transitional shim based on
TargetLSN==liveShipTargetLSNSentinel
- Reference to CARRY-T4D-LANE-CONTEXT-001
Both godoc updates inscribe the architectural fence + name the
named carry by ID so future readers find the gap tracking via
catalogue cross-reference.
22 packages green; 0 failures.
Refs: round-46 architect ruling (lane-pure gate); CARRY-T4D-LANE-
CONTEXT-001 (catalogue §3.3 — QA-inscribed named carry).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Architect round-46 rejected my lane-discriminator implementation:
the gate inspecting `lineage.TargetLSN > 1` to dispatch lane was a
"payload-derived signal" — wrong placement. The fix: gate is
LANE-PURE; CALLER decides lane from connection/session handler
context.
GATE API REWORKED:
- Removed: Apply(lineage, ...) + isRecoveryLane(lineage) helper
- Added: ApplyRecovery(lineage, lba, data, lsn) — explicit recovery
lane (stale → skip data + advance recoveryCovered)
- Added: ApplyLive(lineage, lba, data, lsn) — explicit live lane
(stale → return error fail-loud; never advance recoveryCovered)
- Gate methods do NOT inspect lineage.TargetLSN for lane decisions
TRANSPORT INTERFACE REWORKED:
- transport.ApplyHook becomes 2-method interface (ApplyRecovery +
ApplyLive)
- replica.go MsgShipEntry handler dispatches CALLER-SIDE based on
TargetLSN==liveShipTargetLSNSentinel; this is a TRANSITIONAL SHIM
with explicit TODO marking it as caller-side-only — the
architectural fence (gate is lane-pure) is the durable property
- TODO references future fix: true handler-context lane via
per-connection lane tag, separate live/recovery handler routes,
or distinct listener ports (T4e or post-G5 refactor)
- liveShipTargetLSNSentinel const lives in transport (NOT importing
replication for the value; same wire-stable constant)
REGRESSION TESTS (architect round-46 HARD GATE):
- TestApplyGate_RecoveryWithTargetLSN1_RoutesToRecoveryLane —
recovery lineage with TargetLSN=1 (the OLD live-ship sentinel
value): pre-rework this routed to live and fail-loud'd a stale
recovery entry; post-rework gate honors caller's ApplyRecovery
choice → stale skips silently + recovery coverage advances
- TestApplyGate_LiveWithTargetLSN100_RoutesToLiveLane — mirror:
live lineage with TargetLSN=100 (would have been recovery
pre-rework): post-rework gate honors caller's ApplyLive choice →
stale fail-louds + recovery coverage NOT advanced
TESTS REPLACED / RENAMED:
- TestApplyGate_LaneDiscriminator_RecoveryWhenTargetLSNAboveLive
REMOVED (the gate no longer has a lane discriminator helper)
- TestComponent_LaneDerivedFromTargetLSN renamed →
TestComponent_LanePurity_CallerControlsDispatch — repurposed:
uses identical lineage payload across two test paths, only the
caller's choice of method differs; gate honors choice; pins
INV-REPL-LANE-DERIVED-FROM-HANDLER-CONTEXT (round-46 strengthened
meaning: handler context, NOT payload-derived signals)
REMAINING TESTS UPDATED:
- All gate.Apply(...) call sites in apply_gate_test.go +
apply_gate_scenarios_test.go updated to use ApplyRecovery /
ApplyLive based on the test's intended lane (recoveryLineage →
ApplyRecovery; liveLineage → ApplyLive)
Forward-carry status:
- T4d-1 typed-kind contract unaffected (gate orthogonal to failure
classification)
- All round-43/44 invariants still pinned by the 16 tests; lane-
routing now via explicit method instead of payload sniffing
- 22 packages green; 0 failures
- T4d-3 G-1 sign HARD GATE now satisfied per round-46 QA call
T4d-3 unblocked. T4d-4 unblocked + parallel-eligible.
Refs: round-46 architect ruling (rework lane discriminator);
mini-plan v0.3 §2.2 (apply gate); kickoff §9.3 #2 (Q2 — lane
implicit from handler context).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per QA T4d-1 approval round-46: 2 follow-up tests bound as HARD
GATE before T4d-3 G-1 sign. Sw-discretion landing site = T4d-1
patch (clean closure before T4d-2 starts).
(1) TestT4d1_TargetNotReached_DistinctKindFromWALRecycled
Pin: classifyRecoveryFailure produces DISTINCT engine kinds for
superficially-similar catch-up failure surfaces. WAL-recycled
escalates to Rebuild (tier-class change); target-not-reached is
retryable per RecoveryRuntimePolicy.MaxRetries. Conflating them
would either retry forever past the retention boundary OR
prematurely escalate transient stream failures. Three assertions:
(a) WAL-recycled → engine.RecoveryFailureWALRecycled
(b) target-not-reached → engine.RecoveryFailureTargetNotReached
(c) the two engine kinds are DISTINCT + symmetric
(2) TestT4d1_StorageFailureKindMapper_AllKnownKinds
Fence: catches future StorageRecoveryFailureKind additions that
silently fall through to Transport because the transport mapper
switch wasn't extended. The test enumerates known storage kinds +
expected engine mappings; if a future commit adds
StorageRecoveryFailureFoo to storage but doesn't extend the
mapper, this test fails loudly ("silently fell back to Transport
— mapper missing a switch case"). Two-sided update requirement
(test scaffold + mapper) is the desired discipline.
StorageRecoveryFailureUnknown explicitly excluded from the loop
(zero-value, legitimately maps to Transport catch-all); separate
sanity assertion verifies that mapping.
Both tests pass at HEAD 5ca1d11+this commit.
22 packages green; 0 failures. Net change: +1 file, +135 lines test
code. No production change.
T4d-3 G-1 sign GATE now satisfied (per round-46 QA binding).
T4d-2 + T4d-4 remain unblocked + parallel-eligible.
Refs: T4d mini-plan v0.3 §7.1 (G-1 procedural binding); QA round-46
approval (HARD GATE before T4d-3 G-1 sign).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pre-T4d-1 hotfix per architect-ratified kickoff sequencing
(round-44 governance call): substrate-level guard lands ahead of
the larger T4d-2 replica recovery apply gate work. Closes a
production storage-contract violation independent of the larger
T4d batch.
Bug (round-41 architect-identified, round-43 demo-confirmed):
core/storage/store.go:264 set s.walHead = lsn unconditionally.
Older-LSN ApplyEntry regressed walHead, violating
LogicalStorage contract §3 rule 3 ("stable frontier never goes
backward").
Empirically demonstrated live at round-43:
ApplyEntry(LSN=10) → walHead=10
ApplyEntry(LSN=5) → walHead=5 ← REGRESSION
Fix:
if lsn > s.walHead {
s.walHead = lsn
}
Same monotonic-update pattern as walstore.ApplyEntry:544 and
smartwal.ApplyEntry:358 already use. Brings BlockStore in line.
Architectural placement (round-43 sign):
Replica recovery apply gate (T4d-2 primary fix) is the primary
correctness boundary; this guard is defense-in-depth for paths
that may bypass the gate (live duplicate, retry, future
cross-substrate scenarios). Inline godoc comment names the
T4d-2 gate as the primary boundary so the role is clear.
Test (un-skipped from round-41/43 adversarial set):
TestComponent_BlockStore_ApplyEntry_OldLSN_DoesNotRegressWalHead
(renamed from TestComponent_Adversarial_BlockStoreApplyEntry
RegressesWalHead — the bug name no longer applies).
Pre-fix: t.Skip + T4d TODO. Post-fix: passes; pins the
monotonic guard against regression.
Zero semantic change to any code that worked before. T4d-1 / T4d-2
will not conflict with this hotfix — different files, different
layers.
go test ./... -count=1 → 22 packages green (regression test
passes; no other test affected).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QA round-42 refined the round-41 invariant
INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA with two scoping rules
that must be honored at T4d implementation:
(1) INV-REPL-RECOVERY-STALE-SKIP-DATA-ONLY-NOT-ACCOUNTING:
Stale skip applies to DATA WRITE only. Per-session accounting
(bitmap, completion mask, scan coverage) MUST update as though
the entry was processed. Otherwise:
- Recovery session's completion logic thinks LBA wasn't reached
- Bitmap signals "recovery hasn't covered this slot" to live lane
- Barrier achievedLSN judgment is wrong
Skip means: don't write data. Still mark "I saw this LBA."
(2) INV-REPL-LIVE-LANE-NEVER-SKIPS-LSN:
Per-LBA-LSN skip rule applies to RECOVERY lane ONLY. Live ship
lane MUST NOT skip on stale LSN — live writes are authoritative
on (lineage, session) grounds and that gating is sufficient.
An "old LSN" on live is a duplicate/replay; per-LBA-LSN
comparison is recovery-lane-only.
Files updated:
- stale_entry_adversarial_test.go: TestComponent_StaleEntrySkip_
RuleStatement extended with both refinements + 2 new T4d
adversarial test requirements (recovery-stale-skip-still-marks-
bitmap; live-lane-old-LSN-applies-normally)
- memory feedback_recovery_stale_entry_skip.md: refinements +
expanded T4d blocker list
T4d blocker list now (round-42 revision):
1. Per-LBA applied LSN tracking at replica apply layer
2. Recovery apply skips entries whose LSN <= per-LBA applied LSN
3. Skip data write but UPDATE per-session accounting (refinement #1)
4. Apply skip rule on recovery lane only; live keeps current
lineage-gated apply (refinement #2)
5. BlockStore.ApplyEntry: gate walHead update on lsn > walHead
6. 5 adversarial tests un-skipped + extended (architect set + QA
refinement set)
22 packages green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Architect round-41 corrected my earlier "frontier monotonicity is
sufficient" answer. Two real concerns surfaced + inscribed:
(1) Frontier-monotonicity tests are PARTIAL PINS only.
They cover benign full-replay shape (over-scan completes through
to the restoring entry). They do NOT prove safety under
INTERRUPTED replay where a stale entry overwrites newer state and
the conn dies before the restoring entry arrives. File header on
frontier_regression_test.go now says so explicitly.
(2) BlockStore.ApplyEntry sets walHead = lsn UNCONDITIONALLY.
Older-LSN apply regresses walHead, violating logical_storage.go §3
rule 3 ("stable frontier never goes backward"). My earlier "BlockStore
is idempotent" claim was wrong.
Architect rule (revised T4d blocker): pinLSN < replicaLSN is
LEGAL and EXPECTED (probe-time R can advance during recovery via
live lane / barrier / prior partial catch-up). Don't fight it;
make recovery apply stale-safe per LBA.
Required invariant — INV-REPL-RECOVERY-STALE-ENTRY-SKIP-PER-LBA:
A replica MUST NOT apply a recovery-stream entry if that LBA is
already known to contain data from an equal or higher LSN.
Substrate behavior verified at round-41:
- walstore: per-LSN scan emits BOTH old + new → vulnerable to
interrupted-replay corruption (T4d must add per-LBA stale skip)
- smartwal: state-convergence emits scan-time LSN with current
data → stale-safe by construction (current data only)
- BlockStore: walHead regresses on older-LSN apply → contract
violation; T4d must gate walHead update on lsn > walHead
Files added:
stale_entry_adversarial_test.go (3 tests):
- TestComponent_Adversarial_StaleEntryDoesNotRegress (skipped
with T4d TODO; expected to FAIL on walstore today; T4d
un-skips when per-LBA stale skip lands)
- TestComponent_Adversarial_BlockStoreApplyEntryRegressesWalHead
(skipped; pins the BlockStore bug for T4d fix)
- TestComponent_StaleEntrySkip_RuleStatement (always passes;
godoc-style searchable inscription of the architect rule)
frontier_regression_test.go header updated:
- File-level "PARTIAL PIN" notice naming the limitation
- TestComponent_CatchupFromBelowReplicaLSN_NoFrontierRegression
godoc clarifies "FULL successful replay" scope
Memory updated:
- feedback_recovery_stale_entry_skip.md captures the architect
rule + required invariant + T4d blocker shape
T4d blocker list (round-41 revision):
1. Per-LBA applied LSN tracking at replica apply layer
2. Recovery apply skips entries whose LSN <= per-LBA applied LSN
3. BlockStore.ApplyEntry: gate walHead update on lsn > walHead
4. 3 adversarial tests un-skipped + extended:
- same LBA old/new + sever before new → no regression
- repeated recovery window → byte state stable
- live races recovery old → live wins
go test ./... -count=1 → 22 packages green (adversarial tests
skipped with explicit T4d TODOs).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Round 40 follows up commit 370a0e8 (sw closed 3 of 4 framework gaps).
Adds 3 component-scope scenarios on top of the round-39 trio, bringing
T4c QA Stage-1 coverage to 6 scenarios / 11 matrix rows, all green.
New (round 40):
BarrierAchievedLSN_PartialProgress_DistinctFromCompletion
pins INV-REPL-CATCHUP-COMPLETION-FROM-BARRIER-ACHIEVED-LSN: a
catch-up that ships some-but-not-all entries MUST surface as
Success=false, distinct from a clean close at the same LSN, and
MUST NOT be conflated with ErrWALRecycled (engine retry/rebuild
branching depends on the sentinel distinction).
DeadlinePerCallScope_NoSpilling
pins INV-REPL-CATCHUP-DEADLINE-PER-CALL-SCOPE via two back-to-back
live-ship batches on the same wire. Reframed from the original
live-ship -> catch-up -> live-ship design after authoring revealed
a session-ID conflict (live-ship and explicit CatchUpReplica claim
sessionID=1 independently). Cross-orchestration form is forward-
carried to T4d alongside WithEngineDrivenRecovery.
LastSentMonotonic_WithinCall
pins INV-REPL-CATCHUP-LASTSENT-MONOTONIC at the within-call layer
using NewObservedScanWrap. Cross-call form (LastSentMonotonic_
AcrossRetries) requires WithEngineDrivenRecovery (T4d-stubbed)
so the engine drives multi-call retry with advancing fromLSN;
today CatchUpReplica restarts at fromLSN=1 every call.
Authoring observation: original DeadlinePerCallScope design hit a
sessionID=1 collision between live-ship and explicit CatchUpReplica.
Surfaced as forward-carry; the in-wire deadline-scope pin survives
the reframing intact.
Cumulative: 6 T4c QA scenarios / 11 matrix rows / all green.
Stage-2 m01 carry-over: LastSentMonotonic_AcrossRetries (engine-loop
form) waits on WithEngineDrivenRecovery wiring at T4d.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QA round-39 Stage 1 flagged 4 framework gaps blocking deferred
scenarios. This commit closes 3 of 4 with primitives + demos;
4th (engine-driven recovery) is API-stubbed pending T4d wiring.
Closed gaps:
(1) WithPrimaryStorageWrap(fn) builder option
- Cluster.WithPrimaryStorageWrap installs a substrate transform
before BlockExecutors bind; wraps may override any LogicalStorage
method. Three pre-built wraps in faults.go:
- NewRecycledScanWrap() — always returns ErrWALRecycled
- NewSeverDuringScanWrap(N, err) — emits N entries then severs
- NewObservedScanWrap(*atomic.Int32) — counts emit observations
- Demos: TestComponent_RecycledScanWrap_EscalatesToRebuild,
TestComponent_SeverDuringScan_PartialProgress,
TestComponent_ObservedScanWrap_CountsEmits
(2) Live-ship primitive driving ReplicationVolume.OnLocalWrite
- Cluster.WithLiveShip() builder option spins up StorageBackend +
ReplicationVolume; configured replicas auto-registered as peers
- PrimaryWriteViaBackend(lba, data) writes through the production
data-plane entry → WriteObserver hook → fan-out to replicas
- PrimaryWriteViaBackendN(n) batch helper
- Demo: TestComponent_LiveShip_PrimaryWriteViaBackend_FansOut
(4) Mid-stream drop helper SeverDuringScan
- Implemented as NewSeverDuringScanWrap above; counts entries via
atomic.Int32 inside the substrate wrap and returns the configured
sever error after N successful emits
- Robust to substrates with fewer than N entries (no-op rather than
fail-closed, so scenarios are emit-count-tolerant)
API-stubbed for T4d:
(3) WithEngineDrivenRecovery() — option records intent, emits a
one-shot t.Logf warning at Start, runs as direct-executor mode.
Forward-carry: when T4d wires ReplicationVolume↔adapter, this
option swaps the adapter-aware constructor in. Demo:
TestComponent_EngineDrivenRecovery_StubWarning pins the API
shape so scenarios authored today won't need to change when
behavior lands.
Known limitation documented in faults.go: substrate-extension
methods (e.g. walstore.CheckpointLSN) are MASKED by the wrap
because Go embedding only exposes interface methods. The catch-up
sender's recovery_mode label probe duck-types CheckpointLSN; under
a wrap, it always sees state_convergence regardless of underlying
substrate. Forward-carry: refactor mode-label detection behind a
substrate-reported RecoveryMode() method that wraps can forward.
5 new demos = 9 matrix rows (smartwal+walstore where applicable).
go test ./... -count=1 → 22 packages green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Confirmatory POC for walstore substrate per memo §12 + §13.0a +
§5.1. Validates V2-faithful per-LSN tier-1 mode (`wal_replay`)
in contrast to smartwal's `state_convergence` mode.
Code (POC, NOT production):
core/storage/walstore_recovery_poc.go (~240 LOC)
New types:
- RecoveryEntry{LSN, LBA, Flags, Data} — sibling to smartwal's
type; same shape, different package; T4c-3 muscle port will
unify behind LogicalStorage.ScanLBAs
- ErrWALRecycled (sentinel; mirrors V2 walstore semantics)
New methods on *WALStore:
- ScanFrom(fromLSN, fn) error — walks WAL physical region
between logicalTail and logicalHead, decodes each record,
filters LSN >= fromLSN && < headLSN, emits in LSN-ascending
order. Per-LSN, NOT deduped. Returns ErrWALRecycled if
fromLSN <= checkpointLSN.
- WALCapacityBytes() — POC retention characterization
- CheckpointLSNForPOC() — sibling for retention boundary tests
core/storage/walstore_recovery_poc_test.go (~440 LOC)
8 POC tests, all pass:
#1 — TestPOC_Walstore_ScanFrom_BasicRange
#1 — TestPOC_Walstore_ScanFrom_FromHeadOrAbove_Empty (3 sub)
#1 KEY PIN —
TestPOC_Walstore_ScanFrom_PerLSNNotDeduped: 3 writes to
LBA=0 → 3 entries with markers 0xA1/0xA2/0xA3. Pins
V2-faithful per-LSN semantic and confirms
INV-REPL-RECOVERY-STREAM-LBA-DEDUP is NOT applicable to
walstore (smartwal-mode-scoped per memo §13.6 round-34).
#1+#4 — TestPOC_Walstore_ScanFrom_ErrWALRecycled: boundary
fires at fromLSN <= checkpointLSN
#2 — TestPOC_Walstore_AllBlocks_DeterministicOrdering
#3 — TestPOC_Walstore_ScanFrom_ConcurrentLiveWrite_Safe:
no deadlock, no torn reads; emitted Data contemporaneous
with emitted LSN (data-staleness from smartwal §3.2 does
NOT apply to walstore — append-only WAL slots are
immutable once written)
#4 — TestPOC_Walstore_RetentionBoundary_Characterized:
deterministic boundary at checkpointLSN
sanity — TestPOC_Walstore_Sanity_ExistingAPIsUnchanged
Findings (per POC report §3.b):
- V2-faithful per-LSN tier-1: walstore preserves entry data IN
the WAL (LBA + LSN + Data), so 3 writes to same LBA produce
3 emitted RecoveryEntry, each with the data that LSN actually
wrote. Contrast with smartwal which emits 1 entry with current
extent data.
- ErrWALRecycled boundary: dynamic, advances with flusher
activity. Contrast with smartwal's fixed walSlots window.
- Concurrent live-write: walstore's append-only WAL records are
immutable; concurrent live-write doesn't rewrite slots. Per-
LSN data preservation makes data-staleness a non-issue. POC
finds no torn reads, no deadlock, contemporaneous data
labeling.
- BUG-007 not exercised (Windows/dev-loop only); deferred to
T4c-5 L3 m01 integration matrix per memo §5.
POC report (sw-block/design/v3-phase-15-t4c-pre-poc-report.md)
extended:
- §1 executive summary expanded to 8-case 2-substrate matrix
- New §3.b walstore findings section
- §5 substrate-specific concerns: walstore concerns now ✅
addressed (ring-buffer recycling consistency verified)
- §6 acceptance: clean on both substrates
- §7 next steps: T4c-pre-B in flight; T4c mini-plan follows
- §8 sign + §9 change log entries for round-34 walstore POC
Verification: full 21-package repo suite green. POC code isolated
to walstore + smartwal POC files; no impact on production paths.
T4c-pre-A POC closed. T4c-pre-B engine command model upgrade
proceeds next.
Per design memo §12 (`v3-phase-15-t4c-recovery-protocol-design.md`):
substrate-level POC validating that smartwal can support the four
operations the unified recovery protocol requires. Discovers + pins
a critical semantic question that gates T4c-1 wire coding.
Code (POC, NOT production — file names + godoc mark POC):
core/storage/smartwal/recovery_poc.go (~220 LOC)
New types:
- RecoveryEntry{LSN, LBA, Flags, Data}
- ErrWALRecycled (sentinel; mirrors V2 walstore semantics)
New methods on *Store:
- ScanFrom(fromLSN, fn) error — emits per-LBA last-writer-wins
within LSN range; returns ErrWALRecycled if fromLSN below
retention boundary; mid-scan recycle re-checked
- RingCapacity() uint64 — exposes slot count for retention
characterization tests
core/storage/smartwal/recovery_poc_test.go (~450 LOC)
8 POC tests, all pass:
#1 — TestPOC_ScanFrom_BasicRange (capability #1)
#1 — TestPOC_ScanFrom_FromHeadOrAbove_Empty (3 sub)
§3.1 finding pin —
TestPOC_ScanFrom_LastWriterWinsPerLBA: 3 writes to same
LBA in range emit 1 entry (not 3) — pins smartwal-specific
semantic that V2 wire-parity-strict cannot be delivered
#1+#4 — TestPOC_ScanFrom_ErrWALRecycled
#2 — TestPOC_AllBlocks_DeterministicOrdering
#3 — TestPOC_ScanFrom_ConcurrentLiveWrite_DataStaleness:
no deadlock, no torn reads; documents the data-staleness
semantic where emitted LSN labels reflect slot-record at
scan-time but emitted Data may belong to a newer LSN
(cross-lane bitmap reconciliation handles this)
#4 — TestPOC_RetentionBoundary_Characterized: 8/16/64
slot characterization; ErrWALRecycled fires precisely at
head-walSlots
sanity — TestPOC_Sanity_ExistingAPIsUnchanged
POC report at sw-block/design/v3-phase-15-t4c-pre-poc-report.md
documents:
§3.1 Critical finding — architect decision required:
smartwal's WAL stores metadata only; extent holds only the
latest data per LBA. Tier-1 recovery cannot deliver every-LSN-
entry-in-range (V2 strict-parity); CAN deliver last-writer-
wins per LBA in range (state-convergence-equivalent). Two
options surfaced; sw recommends Option A (state-convergence)
because: (a) replica state convergence identical, (b) bitmap
mask rule keyed on LBA so cross-lane reconciliation
unaffected, (c) keeps smartwal as sign-bearing substrate
without architectural change, (d) bandwidth-efficient.
§3.2 Concurrent live-write data staleness:
Within recovery-stream lane, emitted LSN may not match
emitted Data. Bitmap mask rule (memo §2.2) handles this
correctly at the replica because it's keyed on LBA. Recovery
handler at T4c-2 must NOT rely on per-entry LSN-vs-data
consistency.
§3.3 Retention characterization:
Deterministic — `walSlots` slots = `walSlots` LSNs of
retention. ErrWALRecycled fires precisely when
fromLSN < head - walSlots.
Walstore POC deferred per §4 of report — pending architect
decision on §3.1. If Option A: walstore POC is straightforward
mirror of smartwal scope (1 day). If Option B: walstore is
primary path and smartwal requires substrate work first.
Verification: full 21-package repo suite green. POC code is
isolated to smartwal package; no impact on production paths.
T4c-pre-A POC complete pending architect §3.1 decision. Standing
by for architect ruling, then walstore POC, then T4c-pre-B engine
command model upgrade, then T4c-1 wire.
Closes the T4b batch with end-to-end matrix coverage of all three
DurabilityMode semantics + a wire-shape scope-leak fence. Each
scenario drives the full StorageBackend.Sync → observer.Sync →
DurabilityCoordinator → peer.Barrier → real ReplicaListener path
on real TCP between in-process pairs.
Mirrors T4a-6 harness shape (matrix runner, primaryRig +
replicaRig pattern, LIFO cleanup discipline). Both backends
(smartwal + walstore) are gating in the L2 harness — round-22
honesty correction inherited.
Scenarios (4 × 2 backends = 8 matrix rows):
TestT4b6_SyncAll_TwoPeers_AllHealthy
sync_all happy path. 20 LBAs through StorageBackend.Write +
Observe + ship to both replicas; Sync delegates to observer
which runs local fsync + 2 peer barriers in parallel via
DurabilityCoordinator. Sync returns nil; both peers stay
Healthy; replica byte-exact via primary.store vs r1/r2.store
(forward-carry: T4a-6 BasicEndToEnd byte-exact invariant
continues to hold).
TestT4b6_SyncAll_OnePeer_FailsOnBarrierError
sync_all rejects ANY peer failure. 1 healthy + 1 unreachable
peer; Sync returns ErrDurabilityBarrierFailed. Dead peer is
Degraded (peer.Barrier translation,
INV-REPL-BARRIER-FAILURE-DEGRADES-PEER). Healthy peer's
state stays Healthy — its individual barrier succeeded; the
failure is mode-driven, not transport-driven.
TestT4b6_SyncQuorum_RF3_TolerantOfOneFailure
sync_quorum tolerates 1/2 peer failure when quorum is 2.
Primary(1) + healthy peer(1) = 2 durable >= 2 quorum → Sync
nil. Sanity sub-case: with BOTH peers dead, sync_quorum
returns ErrDurabilityQuorumLost (1/3 durable < 2/3 quorum).
Pins V2 dist_group_commit.go quorum arithmetic end-to-end
through the V3 wire.
TestT4b6_BestEffort_AllPeersFail_StillSucceeds
best_effort silences all-peers-failed. 2 unreachable peers;
Sync returns nil. Both peers Degraded via peer.Barrier
Invalidate. Primary's local fsync ran (walHead reflects the
writes). Pins V2's "best_effort returns nil even on full
replication failure" semantic.
TestT4b6_BarrierWire_FullLineageEcho_StillEnforced
Wire-shape scope-leak fence (architect round-22 pattern).
Asserts EncodeBarrierResp output is exactly 40 bytes (32B
lineage + 8B AchievedLSN). Asserts round-trip preserves
every lineage field byte-exact. Asserts 39B truncation is
rejected at decode (T4b-1 fail-closed contract). Catches
any future refactor that silently weakens to epoch-only
or short form, independent of whether the matrix scenarios
above also fail.
Forward-carry verification (matrix run + standalone):
- All T4a-6 tests (BasicEndToEnd_PrimaryWriteReachesReplicaByteExact
+ BestEffort_DisconnectThenReassign) continue to pass.
- T4a-4 adversarial pin
(TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica)
continues to pass — INV-REPL-LSN-ORDER-FANOUT-001 not
regressed by Sync code path.
- T4b-3 wrapper tests + T4b-4 coordinator tests + T4b-5 Sync
tests all green.
Verification: full 21-package repo suite green. core/replication
test time 0.6s including all 8 matrix rows. G-2 tri-line godoc on
test helpers (setReplicaSet, writePrimaryBlocks, reservedDeadAddr).
G-3 cumulative.
Sixth and final task in T4b batch. T4b mechanically closed: 6/6
tasks landed, all gates green, all invariants pinned. Awaiting QA
single-sign per §8C.2 for batch close.
Wires DurabilityCoordinator (T4b-4) into the per-volume Sync path.
Host-side FLUSH / SYNCHRONIZE_CACHE now drives the full local fsync
+ per-peer barrier closure in parallel with mode-dependent arithmetic.
Changes:
core/frontend/durable/storage_adapter.go
WriteObserver interface extended: Sync(ctx, targetLSN) joins the
existing Observe(ctx, lba, lsn, data) method. Contract documented
inline — observer.Sync OWNS the full sync job (both local
fsync and peer barriers) when installed; StorageBackend delegates
rather than calling storage.Sync locally.
StorageBackend.Sync branches: observer==nil preserves the
pre-T4b behavior (local storage.Sync only); observer!=nil reads
walHead from LogicalStorage.Boundaries() and calls observer.Sync
with that as targetLSN. The observer (ReplicationVolume) then
invokes DurabilityCoordinator.SyncLocalAndReplicas which runs
local + barriers in parallel inside its own goroutines.
core/replication/volume.go
ReplicationVolume gains:
- coord field set to NewDurabilityCoordinator at construction
- durabilityMode field, SetDurabilityMode setter +
DurabilityMode accessor. Default BestEffort (zero value).
Per mini-plan §5, T4b does not support per-Sync-call mode
override — mode is a per-volume setting.
- Sync(ctx, targetLSN) method — snapshots peers under v.mu,
builds a localSync closure around v.store.Sync, delegates
to coord.SyncLocalAndReplicas, returns error verbatim.
Lock scope: v.mu held across the FULL Sync call. Matches the
T4a-4 round-15 Condition A discipline — concurrent Sync +
OnLocalWrite calls are serialized on v.mu, preserving the V2
shipMu semantics extended from ship-only into ship+barrier.
Accepted correctness-first trade-off: a slow peer barrier stalls
other writers on the same volume; async-queue optimization
(Option Z) is deferred post-T4.
Tests (2 required per mini-plan §2 T4b-5):
- TestReplicationVolume_Sync_BestEffort_E2E — full end-to-end
smoke: StorageBackend.Write 10 LBAs → Observe → ship → replica
applies. StorageBackend.Sync → observer.Sync →
DurabilityCoordinator → local fsync + peer barrier in parallel.
Replica's R-boundary (durable frontier) must reach primary's
H (walHead) after Sync returns. Peer stays Healthy throughout.
- TestReplicationVolume_Sync_PreservesLSNOrderUnderConcurrency —
forward-carry fence for INV-REPL-LSN-ORDER-FANOUT-001 under
the new Sync code path. 40 goroutines, caller-side serialized
LSN allocation + OnLocalWrite, periodic Sync calls interleaved
every 4th iteration. LBA ordering is inverted from LSN order so
any reorder is byte-detectable. All 40 LBAs must settle to the
correct LSN marker at the replica.
Forward-carry verification: T4a-4's
TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica
continues to pass — the existing ordering invariant is not regressed
by the new Sync code path that shares v.mu.
Verification: full 21-package repo suite green including the
extended WriteObserver interface not breaking core/frontend/durable
tests. G-2 tri-line godoc on SetDurabilityMode, DurabilityMode
accessor, Sync method, extended WriteObserver.Sync contract. G-3
cumulative.
Fifth task in T4b batch. Next: T4b-6 L2 subprocess integration
matrix closes the batch.
New leaf task introduced by QA round-23 §0-B review. T4b-3 originally
planned for ReplicaPeer.Fence-only; QA's peer-state-mutation locality
check surfaced that DurabilityCoordinator must consume peer.Barrier
(not peer.executor.Barrier) so the error → Invalidate translation
lives at the per-peer execution layer — matching V2's WALShipper-
internal markDegraded locality. T4b-3 now ships both Barrier + Fence
wrappers as a leaf before the T4b-4 DurabilityCoordinator muscle port.
Invariant pinned: INV-REPL-BARRIER-FAILURE-DEGRADES-PEER at the V3
per-peer layer, mirroring T4a-3's Ship → Invalidate translation.
Changes:
core/transport/executor.go
Extract FenceSync(replicaID, lineage) error — synchronous fence
exchange returning a descriptive error on any dial / send /
recv / lineage-mismatch failure. Refactored existing async
doFence to wrap FenceSync + adapt the error to the callback-
based FenceResult. Behavior unchanged for existing async
callers (engine recovery path); T4b-3 peer wrapper gets a
clean sync surface.
core/replication/peer.go
New ReplicaPeer.Barrier(ctx, targetLSN):
- Passes peer.lineage UNCHANGED to executor.Barrier — does
NOT override lineage.TargetLSN with the caller's targetLSN.
Replica's acceptMutationLineage rejects same-authority
messages that change TargetLSN, so override would self-
reject. Caller's targetLSN is coordinator-layer-only
(compared against ack.AchievedLSN for mode arithmetic).
- MUST NOT gate on state == Degraded per V2 "always attempt
BarrierAll" invariant (architect §4.3 note in G-1 doc).
Only post-Close gate applies.
- On transport error: p.Invalidate(reason) + state=Degraded
(INV-REPL-BARRIER-FAILURE-DEGRADES-PEER pin).
New ReplicaPeer.Fence(ctx, lineage):
- Takes caller-supplied lineage (not peer-owned) because
fence semantic is "confirm this specific authority tuple"
— coordinator or recovery path chooses which lineage.
- Delegates to executor.FenceSync.
- Same error → Invalidate translation.
Tests (5 required per QA spec):
- TestReplicaPeer_Barrier_Happy — round-trip against real
ReplicaListener; ack.Lineage == peer.lineage byte-exact;
state remains Healthy
- TestReplicaPeer_Barrier_ErrorPropagates_MarksDegraded —
unreachable replica; Barrier returns error; peer transitions
Healthy → Degraded. INV-REPL-BARRIER-FAILURE-DEGRADES-PEER
pin at peer layer.
- TestReplicaPeer_Fence_Happy — fence exchange at peer.lineage
against real replica; state stays Healthy
- TestReplicaPeer_Barrier_AfterClose_Errors — post-Close call
returns 'closed' error; no panic
- TestReplicaPeer_Fence_AfterClose_Errors — post-Close call
returns 'closed' error; no panic
Verification: full 21-package repo suite green. G-2 tri-line godoc
on Barrier, Fence (Called by / Owns / Borrows) + FenceSync on
executor. G-3 cumulative. Existing T4b-2 Fence tests pass after the
doFence → FenceSync refactor (behavior preserved).
Third task in T4b batch. Next: T4b-4 DurabilityCoordinator (muscle
port; G-1 pre-signed by QA in revised artifact at sw-block/design/
v3-phase-15-t4b-4-g1-v2-read.md) against the peer.Barrier surface.
Architect round-22 bundle: new BlockExecutor.Barrier public method +
upgrade of existing executor.doFence to respect round-21 uniform
rule (INV-REPL-LINEAGE-BORNE-ON-BARRIER-ACK). Two coupled changes,
same file, same executor-level ownership, one commit — shipping
Barrier with validation while leaving doFence silent-accept would
violate the uniform rule at the first ack-consuming surface.
Changes:
core/transport/barrier.go
New BarrierAck type: {Lineage, AchievedLSN, Success, Reason} —
validated per-peer barrier outcome surfaced to
DurabilityCoordinator (T4b-3).
New ErrBarrierLineageMismatch sentinel: returned by Barrier
when the response lineage does not match the request. Callers
treat it as a failed barrier for quorum arithmetic.
core/transport/executor.go (doFence upgrade)
After recvBarrierResp succeeds, validate that resp.Lineage
matches the lineage we sent. Mismatch → FenceResult with
Success=false + FailReason containing expected=<lineage>
actual=<lineage> tuple. Short/zeroed/malformed decode failures
already surface as recvBarrierResp errors (T4b-1 decode layer);
they now cleanly propagate to OnFenceComplete instead of
silent-accept ("_ = resp" removed).
core/transport/executor.go (new Barrier method)
func (e *BlockExecutor) Barrier(replicaID, lineage, targetLSN)
(BarrierAck, error)
Implementation mirrors Ship (architect round-11 Option B
composite):
1. Session lookup by lineage.SessionID
2. Epoch-== fence (silent drop on stale epoch via error return)
3. Lazy-dial if session.conn == nil, with "first-winner keeps"
race resolution under e.mu
4. sendBarrierReq + recvBarrierResp (existing helpers; both
set conn deadlines, so timeout is bounded by
recoveryConnTimeout=5s)
5. Full-lineage validation — resp.Lineage != lineage returns
ErrBarrierLineageMismatch with diagnostic log format
matching architect round-21 text (peer ID + expected +
actual tuple)
Tests (5 required per mini-plan §2 T4b-2):
- TestExecutor_Barrier_Happy — real ReplicaListener round-trip;
lineage echo byte-exact; Success=true
- TestExecutor_Barrier_TimeoutFires — replica accepts but never
responds; Barrier's recv deadline fires in ~5s (elapsed
between 4s and 15s, must wedge for most of the deadline to
count as deadline-driven rather than fast-error)
- TestExecutor_Barrier_LineageMismatch_Rejected — custom replica
sends a valid-decode BarrierResponse with different lineage;
Barrier returns ErrBarrierLineageMismatch
- TestExecutor_Fence_LineageMismatch_MarksFailure — the round-22
pin; custom replica sends wrong-lineage ack; doFence propagates
Success=false through OnFenceComplete with FailReason carrying
expected= + actual= tuples. This catches "first existing ack
consumer silently accepts" regression class.
- TestExecutor_Fence_ShortOrZeroedLineage_MarksFailure — two
sub-cases (8-byte short payload, 40-byte all-zero lineage);
both propagate through OnFenceComplete as Success=false (the
T4b-1 decode-layer error is faithfully relayed to the callback).
Preserve:
- sendBarrierReq / recvBarrierResp helper signatures unchanged
- Existing catch-up (catchup_sender.go:102-108) and rebuild
(rebuild_sender.go:103) paths continue to decode successfully
with the extended wire; they ignore the lineage field for T4b
scope — their lineage-validation lands at T4c (catch-up) and
T5 (rebuild) respectively
- adapter.OnFenceComplete callback shape unchanged (FenceResult
gains fuller FailReason content but fields untouched)
Verification: full 21-package repo suite green. G-2 tri-line godoc
on Barrier + BarrierAck + ErrBarrierLineageMismatch. G-3 cumulative.
Timeout test elapsed = 5.00s exactly, confirming deadline is the
unblocking mechanism.
Second task in T4b batch. Next: T4b-3 DurabilityCoordinator (muscle
path; G-1 pre-code V2 diff-footprint required before coding).
Extends BarrierResponse wire from [8B achievedLSN] to
[32B lineage][8B achievedLSN] per architect round-21 decision text
(INV-REPL-LINEAGE-BORNE-ON-BARRIER-ACK). Primary-side consumers can
now fail-closed validate barrier acks against the session they are
awaiting without cached primary-side assumptions — the authority
tuple travels with every ack.
Wire contract (architect verbatim):
- lineage slab [0..32] in strict field order
(SessionID, Epoch, EndpointVersion, TargetLSN)
- achievedLSN at [32..40]
- total payload exactly 40B; MsgBarrierResp type byte
unchanged; envelope preamble unchanged (T4a-1 12B SWRP)
DecodeBarrierResp is strict + fail-closed:
- payloads < 40B → error
- zero-valued SessionID / Epoch / EndpointVersion / TargetLSN
→ error (catches partially-initialized-struct drift)
- field-order drift caught indirectly via the zero-lineage
rule whenever a reordering leaves any slot at zero
Changes:
core/transport/barrier.go
BarrierResponse gains Lineage RecoveryLineage field.
barrierRespSize 8 → 40. Encode/decode updated; decode emits
descriptive errors.
core/transport/replica.go
Two MsgBarrierResp sender sites (MsgBarrierReq handler +
MsgRebuildDone handler) now echo the request's full lineage
via EncodeBarrierResp instead of raw uint64 big-endian. Drops
the encoding/binary import (no longer used).
core/transport/executor.go
Fence lineage.TargetLSN changed from 0 to new
fenceSentinelTargetLSN const (=1, matching liveShipTargetLSN).
Post-T4b-1 any zero-valued lineage field is rejected at
decode; the pre-existing "TargetLSN=0 signals fence" local
convention had to go. Fence TargetLSN is not semantically
meaningful (no TargetLSN-sensitive code on the fence path
reads it); the non-zero sentinel is purely wire-compatibility.
Tests (4 required per mini-plan §2 T4b-1):
- TestBarrierResp_FullLineageEcho_RoundTrip — 3 cases
(typical, largest_valid, mins_all_one). Every field byte-
exact round-trip; length exactly 40.
- TestBarrierResp_ShortPayload_Rejected — loops 0..39, every
truncation rejected with "short barrier response" error.
- TestBarrierResp_ZeroedLineage_Rejected — 5 cases covering
all-zero plus each individual zero field. All reject with
"zero-valued lineage" error.
- TestBarrierResp_MalformedFieldOrder_Rejected — field-order
byte-level fence: crafts payload with Epoch slot zeroed
(simulates reordering bug leaving a slot uninitialized) →
rejected. Plus canonical encode/decode byte-position
assertions so any future encode/decode field-order drift
trips explicitly.
Existing barrier_test.go tests
(TestBarrierResponse_Roundtrip*, _DecodeShort*) removed —
their intent is subsumed by the four new pins which exercise
the stricter T4b-1 contract.
Verification: full 21-package repo suite green. Non-trivial
regression caught during self-test: executor.Fence previously
set TargetLSN=0 which the new strict decode would reject —
calibration + sparrow tests caught it, fix (fenceSentinelTargetLSN)
landed in same commit. Catch-up (catchup_sender.go) and rebuild
(rebuild_sender.go) paths continue to decode successfully via
recvBarrierResp; they ignore the lineage field for T4b scope
per mini-plan §2 T4b-2 preserve-clause (those paths' lineage
validation lands at T4c/T5 respectively).
First task in T4b batch.
QA round-22 noted the l2_integration_test.go file header still
claimed the L2 test proves "all T4a landed commits compose
correctly" and that walstore was "non-gating" — both stale after
the f6ae662 follow-up. Body comments (runMatrix + walstoreFactory)
were updated in that commit; the file header was missed.
This is a documentation-only cleanup:
- Scope claim: now explicitly scopes T4a-6 to T4a-1..T4a-4 +
the StorageBackend WriteObserver hook. Adds a Scope note
pointing at core/host/volume/apply_fact_test.go as the
T4a-5 host-wire coverage.
- Matrix wording: walstore described as a second gating row
in the current harness; the earlier "non-gating per BUG-007"
language removed. Matches runMatrix + walstoreFactory
comments.
No code change; tests unaffected.
uint32 assertions, host-level tests, matrix honesty)
QA round-21 spot-check flagged four issues in the T4a-6 landing.
All four confirmed correct; this commit addresses them as one
reviewable unit per QA's recommended batch.
Finding #1 (HIGH) — install-or-refuse ordering in Host.streamOnce.
Previous order was OnAssignment → UpdateReplicaSet, creating a
window where the adapter's projection flipped Healthy before the
peer set was installed. StorageBackend.lineageCheck would then
pass and admit local-only writes with zero fan-out. V2 atomically
set replicas before admitting writes; V3 had drifted. Fix:
- Extract applyFact(fact) from streamOnce's inner loop so the
handler logic is testable in isolation.
- Invert order: if h.replication != nil, call UpdateReplicaSet
FIRST. On failure, LOG and RETURN without calling OnAssignment.
Adapter projection stays at its prior (not-Healthy until a
fact fully installs) state; StorageBackend keeps writes
blocked; master's stream replay redelivers the fact and
natural convergence resumes on the next cycle.
- Introduce narrow collaborator interfaces (assignmentConsumer,
replicaSetUpdater) on Host so test doubles can drive applyFact
without spinning up a real adapter + transport listener. The
concrete adapter reference is retained as realAdpt for the
existing Adapter() accessor.
Finding #2 (MEDIUM) — generation aliasing at the uint32 boundary.
`(epoch << 32) | uint32(ev)` silently aliased distinct authority
lines whenever either field exceeded 2^32. Fix:
- Extract generationFitsUint32(epoch, ev) as a named package-
level function with a descriptive reason string.
- SubscribeAssignments calls generationFitsUint32 before minting
the fact; on rejection, logs a structured diagnostic + skips
the fact (master keeps running — this is a fail-fast on an
invariant violation upstream, not a master-side error).
- Pin with two adversarial tests: TestGenerationFitsUint32_
MaxValidAccepted (epoch = 2^32-1, ev = 2^32-1 passes) and
_OverflowRejected (epoch = 2^32 and ev = 2^32 each reject
with reasons naming the offending field).
Finding #3 (MEDIUM) — T4a-5 host wire was uncovered by T4a-6. The
L2 integration test bypassed Host.streamOnce entirely, so the
"all T4a commits compose correctly" claim in commit 420a5a1 was
stronger than what the test proved. Fix:
- New apply_fact_test.go in core/host/volume with five pins:
* TestHost_ApplyFact_Self_InstallsReplicaSetBeforeAssignment
(ordering recorder proves UpdateReplicaSet before
OnAssignment in the happy path).
* TestHost_ApplyFact_Self_UpdateReplicaSetFailure_SkipsOnAssignment
(fail-closed pin for finding #1).
* TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication
(the supersede branch is unaffected by the reordering).
* TestHost_ApplyFact_ObserverOnly_NoReplicationCallsOnAssignment
(nil replication seam still flows to OnAssignment as before).
* TestDecodeReplicaTargets_FieldCopy (auxiliary; catches
decoder drift).
- The commit message and batch-close story now honestly reflect
that host ordering is covered. Full master → gRPC → host
subprocess L2 integration deferred to T4b/T4c where the
durability/recovery path makes it materially more valuable
(per QA round-21 guidance).
Finding #4 (LOW) — matrix 'non-gating' fiction removed.
The earlier runMatrix harness had walstore_nongating that
claimed to demote subtest failures. Go's testing has no clean
demote-subtest-failure API; the defer-based logic didn't
actually demote. Replaced with honest naming: walstore is a
second gating row (passes today under T4a best-effort paths;
if it ever regresses under BUG-007 the test fails honestly
and we invest in a real demotion harness then). File header
comment updated to match.
Verification: full 21-package repo suite green including
core/host (122s integration run) and the 5 new host tests. No
regressions.
Ships the end-to-end integration test that proves all five T4a
production commits (T4a-1..T4a-5) compose correctly through the
full frontend→storage→replication→transport→replica wire. This
is the T4a batch close gate per mini-plan §4.
In-scope addition flagged by QA round-20 review and confirmed by
sw (not a discovery-bridge trigger — mini-plan always implied this
wire): StorageBackend.Write did NOT invoke
ReplicationVolume.OnLocalWrite. The hook is added here via a
narrow WriteObserver interface seam so core/frontend/durable does
not import core/replication directly.
Changes:
core/frontend/durable/storage_adapter.go
New WriteObserver interface with Observe(ctx, lba, lsn, data)
method. Named Observe (not OnLocalWrite) to avoid a method-
name collision on ReplicationVolume which already has a
differently-typed OnLocalWrite(ctx, LocalWrite). New
SetWriteObserver(obs) installation seam; called only at setup
(not hot-swappable). writeBytes now takes ctx through and
invokes obs.Observe after each successful LogicalStorage.Write,
best-effort (error logged, does NOT fail the Write — matches
V2 fire-and-forget ShipAll).
Ordering: LSN-order fan-out is preserved because the observer
(ReplicationVolume) serializes its own fan-out under v.mu
(Option X, architect-signed at T4a-4 round-15).
core/replication/volume.go
New Observe(ctx, lba, lsn, data) method that wraps into
LocalWrite and delegates to OnLocalWrite. This lets
*ReplicationVolume satisfy durable.WriteObserver without
either package importing the other's public struct type.
core/replication/l2_integration_test.go (NEW, ~450 LOC)
Internal-package test (access to ReplicationVolume.peers +
ReplicaPeer internals needed for transport-kill simulation).
Matrix harness:
- smartwal_gating — sign-bearing row; t.Fatal on failure
- walstore_nongating — reported row; failures logged with
non-gating note per BUG-007 / T3 matrix discipline
Scenarios:
1. BasicEndToEnd_PrimaryWriteReachesReplicaByteExact —
100 LBAs written through StorageBackend.Write,
verified byte-exact on replica's LogicalStorage. Peer
stays Healthy throughout. Both matrix rows pass.
2. BestEffort_DisconnectThenReassign (QA-requested G5
pass-gate shape) — 30 LBAs shipped Healthy; transport
kill via peer.executor.InvalidateSession +
peer.Invalidate (simulates mid-stream conn severed);
30 more LBAs written best-effort (primary persists
locally, peer Degraded, OnLocalWrite returns nil);
fresh replica spun up on new addr; fake-master
UpdateReplicaSet with gen=2 rebuilds peer (INV-REPL-
PEER-REBUILD-ON-AUTHORITY-CHANGE); 10 LBAs shipped
against fresh replica byte-exact.
Pass-gate fence: asserts the second-batch LBAs do
NOT appear on the fresh replica — catch-up is T4c
territory. Catches scope leak if a future refactor
quietly pulls catch-up into T4a.
Cleanup discipline (learned from T4a-4 test hang):
- replica cleanups registered BEFORE primary so LIFO
ordering closes primary's peer sessions first (no
listener.Stop() wedged on open client conns).
- DisconnectThenReassign creates a second replica after
primary, so it explicitly calls primary.repVol.Close()
at scenario end to unblock the non-LIFO cleanup chain.
Verification: full 20-package repo suite green (all pre-existing
tests pass after WriteObserver addition — backward compat
preserved via optional observer pointer). T4a-6 matrix: 4 test
rows all pass (2 scenarios × 2 backends). No -race on Windows
(CGO_ENABLED=1 requirement documented in MEMORY.md).
T4a batch close now mechanically satisfied; awaiting QA sign +
T-end three-sign per §8C.2 cadence.
Completes the T4a-5.0 §8C.3 Discovery Bridge resolution (Option
P-refined, landed per architect + QA round-19). Extends the
AssignmentFact wire with master-minted peer set + monotonic
generation, adds a separate host-only decode path that does NOT
touch AssignmentInfo (preserves the TestNoOtherAssignment
InfoConstruction AST fence), and wires Host.streamOnce to drive
ReplicationVolume.UpdateReplicaSet after every self-replica
AssignmentFact.
Guardrails (all four from round-19) honored:
1. decodeAssignmentFact unchanged; AST fence stays green.
2. decodeReplicaTargets is SEPARATE and produces replication.
ReplicaTarget + generation, never AssignmentInfo. Adapter +
engine packages: zero changes.
3. Peer set is master-minted only. Host does NOT accumulate or
derive from other-replica facts (option R rejected).
4. peer_set_generation mandatory on the wire; monotonic guard in
ReplicationVolume.UpdateReplicaSet.
Changes:
core/rpc/proto/control.proto
NEW message ReplicaDescriptor{replica_id, epoch, endpoint_
version, data_addr, ctrl_addr}. AssignmentFact gains
`repeated ReplicaDescriptor peers = 7` (excludes self) and
`uint64 peer_set_generation = 8` (monotonic, master-minted).
core/rpc/control/control.pb.go + control_grpc.pb.go
Regenerated via scripts/genproto.sh.
core/host/master/services.go
SubscribeAssignments fills fact.Peers via new collectPeers
helper (reads Publisher.LastPublished for each non-self slot
in the volume's accepted topology). Generation derived as
`(info.Epoch << 32) | info.EndpointVersion` — monotonic
because publisher's lex-dedupe upstream guarantees strictly-
increasing (Epoch, EV) pairs and Epoch/EV are durable authority
facts (survives master restart).
core/host/volume/subscribe.go
NEW decodeReplicaTargets(fact) ([]replication.ReplicaTarget,
uint64) — strict field-copy, same discipline as decode
AssignmentFact. Produces a different output type so the
AST fence TestNoOtherAssignmentInfoConstruction continues to
pass.
core/host/volume/host.go
Config gains `ReplicationVolume *replication.ReplicationVolume`
(nil = T0/observer-only; non-nil = T4a-5 production wire).
streamOnce self-replica branch calls UpdateReplicaSet(gen,
targets) AFTER adapter.OnAssignment. Non-blocking log on
error (best-effort; failure does not stop the assignment
stream).
core/replication/volume.go
UpdateReplicaSet signature break (QA option (a), no shim):
Before: UpdateReplicaSet(targets []ReplicaTarget) error
After: UpdateReplicaSet(generation uint64, targets []ReplicaTarget) error
Three-way generation rule (T4a-5.0 §9.4, QA corrected sw's
original MaxUint64 sentinel which would have one-way-poisoned
the monotonic guard):
- gen == 0: unversioned apply; peer map mutated;
lastAppliedGeneration NOT advanced. Test/fake-master only.
- gen > 0 && gen > lastApplied: apply + advance.
- gen > 0 && gen <= lastApplied: stale; peer map NOT mutated;
replayedGens counter increments; debug log emits peer-ID-
set delta (Q2 binding — IDs only, not full target structs).
Returns nil (idempotent replay is success).
Empty peer set (N → 0) flows through the same teardown path as
any N → M-1 removal. No special branch (Q3 binding).
New state: lastAppliedGeneration uint64 (mu-guarded);
replayedGens atomic.Uint64 (stats counter, private; public
Stats() deferred to T4-end observability pass).
New helpers (internal): peerIDSet, targetIDSet,
stringSetEqual, formatIDSet (deterministic brace-form
rendering of peer-ID sets for log diffs).
core/replication/volume_test.go
All 8 existing tests migrated to new signature with gen=0
(unversioned apply preserves previous functional semantics).
3 new tests (Q1/Q2/Q3 pins):
9. UpdateReplicaSet_Generation_MonotonicGuard — advance
through gens 1, 2, 3; stale replays at gen=2 and gen=3
(equal is stale); verify replayedGens counter; forward
progress at gen=4 works. Exercises Q2 differing-peers
path via the gen=2 replay with original r1+r2 set.
10. UpdateReplicaSet_GenerationZero_DoesNotAdvanceGuard —
gen=5 applied, gen=0 applied (peers mutated, last
Applied stays at 5), gen=3 rejected as stale. Pins the
correctness of the gen=0 rule vs. the original
MaxUint64 sentinel which would have failed this test.
11. UpdateReplicaSet_EmptyPeerSet_AppliesWithTeardown — Q3
binding three assertions: PeerCount=0 after empty
apply, all former peers' executor sessions invalidated,
next OnLocalWrite succeeds as zero-fanout no-op.
Verification: full 20-package repo suite green (core/host: 124s
including supersede_integration_test; core/host/volume: 31ms
confirming AST fence TestNoOtherAssignmentInfoConstruction still
passes; core/replication: all 17 tests green). G-2 tri-line godoc
on every new public surface.
Closes T4a-5.0 §8C.3 Discovery Bridge. Next: T4a-6 L2 subprocess
integration test.
Introduces ReplicationVolume — the per-volume fan-out owner that
tracks the authoritative replica set and serializes Ship fan-out so
the V2 BlockVol.shipMu LSN-order invariant survives the V3 layer
split.
Architect-approved Option X (G-1 pre-code review,
v3-phase-15-t4a-4-g1-v2-read.md): v.mu.Lock() held across the
entire per-peer fan-out loop (Condition A), not just map snapshot
or "prepare then unlock then ship." The mutex is plain sync.Mutex
(no reader-only API worth preserving RWMutex for).
Contract wording (architect-revised, explicit):
ReplicationVolume.OnLocalWrite serializes fan-out in LSN order
for a given volume. Caller order is NOT trusted as the
correctness mechanism.
System invariant: INV-REPL-LSN-ORDER-FANOUT-001. V2 BlockVol.shipMu
atomically composed "allocate LSN + append WAL + Ship" under one
mutex. V3 splits the three concerns across engine / LogicalStorage /
ReplicationVolume; the LSN-order property is preserved end-to-end
when (a) Backend.Write invokes LogicalStorage.Write + OnLocalWrite
under the caller's own atomicity (natural shape — same goroutine)
and (b) OnLocalWrite's mutex serializes fan-out. Test
TestReplicationVolume_OnLocalWrite_ConcurrentLSNs_OrderedAtReplica
is the adversarial pin: N concurrent callers, caller-side lock
mimics Backend.Write, LBAs interleaved with LSN ordering so any
reorder is byte-detectable at the replica.
Accepted T4a trade-off (mini-plan change log): correctness-first
serialized design. Per-volume fan-out holds v.mu during each
peer's ShipEntry, so a slow peer (lazy dial, 3s write deadline,
degraded state) stalls the writer path. Async queue (Option Z) is
deferred optimization, not forgotten design debt — revisit only
after INV-REPL-LSN-ORDER-FANOUT-001 is proven in production.
Surface (~200 LOC production + 430 LOC tests):
- LocalWrite: {LBA, Data, LSN} — the layer-cross carrier
- ReplicationVolume: peers map + borrowed store + serialization mu
- NewReplicationVolume(volumeID, store): borrow store, never close
- UpdateReplicaSet(targets): add/remove/recreate-on-lineage-bump
under v.mu. Lineage bump = tear-down + recreate (T4a MVP; T4c
may add in-place lineage update)
- OnLocalWrite(ctx, w): LSN-order-serialized fan-out; per-peer
error is best-effort (logged + peer already marked Degraded by
ReplicaPeer.ShipEntry's forward-carry CARRY-1); does NOT fail
the OnLocalWrite call
- Close(): idempotent; releases all peers' sessions; does NOT
close the borrowed store (BUG-005 discipline)
- PeerCount() / newExec field: test seam for executor observation
BlockExecutor gains one test-grade accessor:
- HasSession(id): diagnostic for Opt-3 executor-teardown fence.
Used by TestReplicationVolume_UpdateReplicaSet_RemovePeer_
ExecutorTornDown to assert session removal after peer.Close.
Tri-line godoc contract; not intended for production flow.
Tests (8, all green):
1. UpdateReplicaSet_AddPeer — empty → 1 peer
2. UpdateReplicaSet_RemovePeer_ExecutorTornDown — Opt-3 three-
assertion fence (Close-called, session-removed, re-add-works-
and-ships-byte-exact)
3. UpdateReplicaSet_LineageBump_RecreatesPeer — same ReplicaID
new Epoch → new sessionID, new lineage
4. OnLocalWrite_SinglePeer_BestEffort — 20 LBAs byte-exact,
peer stays Healthy
5. OnLocalWrite_PeerErrorDoesNotFailCaller — dead-addr peer,
OnLocalWrite returns nil, peer Degraded
6. OnLocalWrite_ConcurrentLSNs_OrderedAtReplica — INV-REPL-LSN-
ORDER-FANOUT-001 adversarial pin (40 concurrent goroutines,
LBA/LSN interleaved, replica state byte-detectable)
7. Constructor_DoesNotOwnStore — BUG-005 regression fence; store
usable post-ReplicationVolume.Close
8. OnLocalWrite_Closed_Errors — post-Close call returns error,
no panic
Full core/transport + core/replication + core/adapter suites green.
G-2 three-line godoc contracts on every public symbol (New, Update,
OnLocalWrite, Close, PeerCount) + HasSession on executor. G-3
preserved.
Introduces core/replication/ package and ReplicaPeer — the per-remote-
replica runtime handle that bridges ReplicationVolume fan-out (T4a-4)
to the transport layer (T4a-2). T4a-3 is the Opt-4 leaf: ships first,
then ReplicationVolume consumes it.
Surface (~220 LOC production + 230 LOC tests):
- ReplicaTarget: authoritative addressing + lineage from master
assignment (Epoch, EndpointVersion, DataAddr, ControlAddr).
- ReplicaState: Unknown / Healthy / Degraded. T4a scope only;
CatchingUp / Rebuilding / NeedsRebuild arrive at T4c with the
recovery pipeline.
- NewReplicaPeer: registers a live-ship session in the executor
using a fresh peer-local SessionID + target.{Epoch,
EndpointVersion} + constant liveShipTargetLSN = 1. Steady-state
live-ship session; recovery-bound sessions (with engine-frozen
TargetLSNs) arrive at T4c.
- ShipEntry: state-gated fan-out leaf. Healthy → executor.Ship;
Degraded / closed → reject at peer without dialing. On Ship
error: mark Degraded + log reason (forward-carry CARRY-1 from
T4a-2). Caller-supplied lineage is informational for T4a (peer
owns its session); T4b/T4c may tighten when recovery sessions
thread through.
- Invalidate: explicit Healthy → Degraded mutation for authority-
driven peer-down (no-op on closed peer).
- Close: idempotent; invalidates the peer's executor session via
InvalidateSession. Does NOT close the executor — caller owns
executor lifecycle (BUG-005 discipline).
BlockExecutor gets one new public method:
- RegisterLiveShipSession(lineage): thin wrapper around internal
registerSession, needed because ReplicaPeer in core/replication
needs to register its live-ship session from outside
core/transport. Tri-line godoc contract attached.
Gate G-2: every public symbol in both files carries a Called by /
Owns / Borrows tri-line contract. PR-rejectable if any symbol lacks
the three-line contract.
Forward-carry CARRY-1 closed: ShipEntry → Invalidate + Degraded on
transport error. Pin test TestReplicaPeer_ShipEntry_ConnFailure_
MarksDegraded asserts (a) first Ship returns dial/write error, (b)
state transitions Healthy → Degraded, (c) subsequent ShipEntry is
rejected at peer without touching the wire. This closes catalogue
§3.2.1 C4 from PARTIAL to DONE.
Tests (6, all green):
- TestReplicaPeer_ShipEntry_Happy — byte-exact arrival, state
stays Healthy.
- TestReplicaPeer_ShipEntry_ConnFailure_MarksDegraded — CARRY-1
pin.
- TestReplicaPeer_Invalidate_MovesToDegraded — authority-driven
path.
- TestReplicaPeer_Close_Idempotent — double-Close is safe;
post-Close ShipEntry errors with "closed".
- TestReplicaPeer_NewReplicaPeer_RejectsNilExecutor.
- TestReplicaPeer_NewReplicaPeer_RejectsZeroAuthority — fails fast
at construction rather than at first ship when lineage would be
rejected by replica's acceptMutationLineage.
Per T4a-3 context note: tests drive against a real
*transport.BlockExecutor + real *transport.ReplicaListener, not
against a ReplicationVolume caller stub (Opt-4 leaf ordering).
Full core/transport + core/replication + core/adapter suites green.
G-3 preserved.
Adds TestExecutor_Ship_WriteDeadline_Fires — explicit regression fence
for INV-REPL-SHIP-TRANSPORT-MUSCLE-001 component (3). Requested by
QA at T4a-2 validation: three of four composite properties (lazy dial,
silent drop, no-hard-stop) had explicit pin tests; the 3s deadline
had only implicit coverage. Without this pin, a future refactor could
silently drop SetWriteDeadline and the only observable signal would
be primary-write wedge on a slow replica in m01 / production
(~120s TCP retransmission timeout instead of ~3s).
Implementation: net.Pipe() — synchronous in-memory connected pair
with zero internal buffering and SetWriteDeadline support. Bypasses
kernel TCP buffers, which on Windows/Linux loopback can absorb 16+
MiB before blocking and make TCP-based timing tests fundamentally
unreliable. Earlier iterations with 8 MiB TCP payloads + SO_SNDBUF=2K
completed in 2-3 ms on Windows (auto-tuning absorbed everything).
The test asserts:
1. Ship returns an error (not nil)
2. Elapsed >= 2.5s (proof: the write actually wedged for most of
the 3s deadline — if it returned faster, it wasn't the deadline
that unblocked it)
3. Elapsed <= 10s (proof: no hang on TCP retransmit path)
4. Error chain contains Timeout() == true OR "write failed"
Passes in 3.00s exactly on Windows loopback — the deadline IS the
unblocking mechanism.
Required test-list alignment with mini-plan line 390 now complete
(LazyDial_HappyPath ≡ LazyDial_OnRegisteredSessionWithoutConn;
LazyDial_DialFailure_ReturnsError ✓; StaleEpoch_SilentDrop ✓;
WriteDeadline_Fires ✓).
Full core/transport suite: 8 Ship tests + all pre-existing transport
tests green. G-3 preserved.
Follow-up to 6475850. Architect review of the initial T4a-2 commit
surfaced that sw had (a) described V2 semantics incorrectly as
"transparent single-call retry" — V2 does lazy-dial → single write
→ degrade-on-fail-return-nil, no retry loop — and (b) proposed
lifting ensureDataConn into ReplicaPeer.ShipEntry, which would have
smeared transport-conn-lifecycle across core/transport +
core/replication in violation of the "core/transport = sole
net.Dial + frame-I/O owner" principle.
Architect-revised decision (v3-phase-15-t4a-2-g1-v2-read.md §6-REV):
Change 1 — Do not auto-register sessions inside Ship.
Ship's epoch fence depends on accepted-lineage. If Ship
invented sessions from incoming lineage the fence would
collapse into self-validation. Session registration stays
bound to explicit lifecycle entry points; Ship only
lazy-dials when session.conn == nil on an already-
registered session.
Change 2 — Return error on dial/write failure.
V2 return nil worked because WALShipper owned markDegraded.
V3 BlockExecutor does not own peer state. Literal return
nil would silently swallow a real fault. Ship returns
error; ReplicaPeer.ShipEntry (T4a-3) translates error →
peer-state Degraded + Invalidate.
Ship now:
- looks up session by lineage.SessionID (no auto-register)
- epoch-== silent drop preserved
- if session.conn == nil → net.DialTimeout(replicaAddr, 3s)
+ attach-under-mu with race handling:
* session invalidated during dial → close + error
* concurrent dial raced ahead → use theirs, close ours
* we win → install our conn
- 3s write deadline preserved
- dial/write error → return error (peer layer degrades)
Tests (7, all green):
- TestExecutor_Ship_SingleEntry (happy)
- TestExecutor_Ship_MultipleEntriesOrdered (order preserved)
- TestExecutor_Ship_ConnFailure (write error after attached conn)
- TestExecutor_Ship_NoSession (no auto-register — Ship errors
on unknown sessionID; preserves accepted-lineage model)
- TestExecutor_Ship_LazyDial_OnRegisteredSessionWithoutConn
(NEW: registered session no conn → lazy-dial + attach +
send; second Ship reuses attached conn)
- TestExecutor_Ship_LazyDial_DialFailure_ReturnsError (NEW:
unreachable replicaAddr → error; session stays registered)
- TestExecutor_Ship_StaleEpoch_SilentDrop (L1 §2.1 inv #2
regression; TCP-proxy-counted 0 bytes on wire)
§8C.3 trigger #1 logged in mini-plan change-log (already at
line 389-390): preserve-baseline read too narrowly at method
level, missed V2 lazy-dial stability seam. §0-B
Stability-Locality rule adopted as default G-1 heuristic for
future non-literal ports (see
memory/feedback_g1_pre_code_review.md).
Full core/transport + core/adapter suite remains green.
Adds the steady-state Ship method to BlockExecutor. Sends one WAL
entry to a named replica over the session's attached data conn.
Fire-and-forget: no per-entry ack at this layer; durability closure
is T4b concern.
Port discipline (see v3-phase-15-t4a-2-g1-v2-read.md for full G-1
V2 read; 98 LOC V2 → ~30 LOC V3, 31% ratio flag explicitly
justified by structural decomposition, not invariant loss).
Invariants preserved verbatim from V2 WALShipper.Ship:
- L1 §2.1 invariant #2 (epoch-== silent drop, wal_shipper.go:217):
stale-epoch entries return nil without touching the wire. Epoch
source shifts from epochFn() callback to lineage.Epoch (frame-
borne authority, H5-LOCK compliant); semantic identical.
- 3s write deadline (wal_shipper.go:240): byte-identical bound on
TCP write so a dead replica can't wedge callers on the ~120s
TCP retransmission timeout.
Ownership shifts (per G-1 §6 QA-approved decisions):
- §6.1 no lazy dial in Ship — sessions must be pre-registered
via registerSession + attachConn (same lifecycle used by
StartCatchUp/StartRebuild). Forward-carry conditions on T4a-3
(ReplicaPeer.ShipEntry marks Degraded on err) and T4a-6 (L2
mid-stream-kill recovery test) prove V3's "degrade+catch-up"
is equivalent to V2's transparent-reconnect property.
- §6.2 markDegraded moved from executor to caller — Ship returns
error; ReplicaPeer.Invalidate (T4a-3) does the state mutation.
BlockExecutor does not own ReplicaState in V3.
Tests (5):
- TestExecutor_Ship_SingleEntry (happy)
- TestExecutor_Ship_MultipleEntriesOrdered (LSN/LBA preservation)
- TestExecutor_Ship_ConnFailure (error return on write fail)
- TestExecutor_Ship_NoSession (error on unknown sessionID)
- TestExecutor_Ship_StaleEpoch_SilentDrop (L1 §2.1 inv #2 regression:
TCP-proxy-counted 0 bytes on wire with stale-epoch Ship, fresh-
epoch Ship on same session still arrives)
G-2 three-line godoc contract (Called by / Owns / Borrows) inscribed
on Ship per §7.1 Gate G-2. Full core/transport + core/adapter suite
remains green. Gate G-1 approved by QA with forward-carry conditions
recorded on T4a-3 and T4a-6 task entries.
V3 clean-break replication envelope now carries magic + version +
flags/reserved in every frame. Replicas refuse foreign traffic at the
first byte; unknown protocol versions are rejected explicitly.
Wire layout:
[4B magic "SWRP"][1B version=1][1B type][1B flags=0][1B reserved=0]
[4B length][payload]
All existing message encode/decode bodies are unchanged — only the
preamble extends. MsgShipEntry / MsgProbeResp / MsgRebuildBlock /
MsgBarrierResp frames all ride the new envelope transparently.
Tests: EnvelopeRoundTrip (every message type), MagicRejected_WrongMagic,
VersionRejected_UnknownVersion. Existing core/transport/*_test.go
continues to pass unchanged (verified).
Part of Phase 15 T4a per v3-phase-15-t4a-mini-plan.md §2 T4a-1.
Gate G-3 (pre-existing transport tests stay green) satisfied.
T3-DEF-6 (NVMe session cleanup contract):
Add core/frontend/nvme/t3_qa_session_cleanup_addendum_test.go with
TestT3_NVMe_Session_CleanupOnClose_NoLeaksAcrossCycles (20 cycles,
goroutine leak guard) and TestT3_NVMe_Session_CleanupOnClose_CNTLIDAllocator
(monotonic CNTLID across 8 cycles + one post-cycles reconnect).
Pins new catalogue row C5-NVME-SESSION-STATE-CLEANUP-ON-CLOSE as
smoke + leak-guard (not full state-release introspection;
target-registry introspection deferred).
Matrix F ENOSPC cleanup robustness (iterate-m01-nvme.sh):
SSH cleanup phase was non-zero-exiting when blockvolume crashed on
ENOSPC (dead NVMe target hangs sudo nvme disconnect). Switch cleanup
block to tolerate all benign non-zero exits, remove set -e, and
use pattern-based success detection (grep 'ENOSPC triggered gracefully'
in server-side output) as the authoritative Matrix F pass signal.
Ownership: QA (L1 addendum + QA-owned script)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QA-owned adaptation to make Path B reconnect matrix runs deterministic
on m01. Enables BUG-005 post-fix m01 re-verification against a clean
slate.
Changes:
- pkill stale blockmaster/blockvolume before start_services
- dmesg --clear before each run so check_dmesg_clean doesn't trip
on entries from a prior cycle
Precondition for BUG-005 (commit 1d21b0f) m01 re-verify: without
these, a successful fix run could look like a fail (stale dmesg)
or a partial fix could look like clean (stale processes still
serving). Committing so HEAD is reproducible end-to-end for the
cross-session reconnect test.
No production-code change; test infra only.
Co-Authored-By: Claude Sonnet 4.6 (QA agent) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
m01 Path B reconnect matrix cycle 2 exposed: kernel gets
nvme1n1: I/O Cmd(0x2) @ LBA 0, I/O Error (sct 0x3 / sc 0x2)
on the very first Read of a second nvme connect after a clean
disconnect.
SCT=3 SC=2 = ANA Asymmetric Access Inaccessible, mapped from
frontend.ErrBackendClosed via nvme.NewBackendClosed(). NOT a
data-integrity bug — bytes on disk are intact. Pure Backend
lifecycle bookkeeping.
## Root cause
Session-layer code was calling Backend.Close() when a TCP session
ended:
- core/frontend/nvme/target.go handleConn: defer backend.Close()
- core/frontend/iscsi/session.go close(): s.backend.Close()
Fine under memback (Provider.Open creates a fresh backend struct
per call). Broken under DurableProvider which MUST cache one
Backend per volumeID because LogicalStorage is an exclusive
resource. The per-session Close flipped the CACHED backend
closed → next session received the same closed handle → all I/O
returned ErrBackendClosed → NVMe mapped to SCT=3 SC=2.
V2 structurally avoided this: Subsystem.Dev is registered via
AddVolume / unregistered via RemoveVolume (admin-level), and
Controller.shutdown() explicitly does NOT touch the device. See
weed/storage/blockvol/nvme/{server.go,controller.go}.
V3 had the right intent (T3a mini plan §3: "Backend.Close marks
closed but does NOT tear down storage; Provider retains storage
handle") but the interface godoc didn't document WHO is allowed
to call Close. T2 target authors treated Backend.Close as
session-owned by pattern-matching memback's accidental shape.
## Changes
Production:
core/frontend/nvme/target.go -1 line (removed defer)
core/frontend/iscsi/session.go -3 lines (removed conditional close)
core/frontend/types.go +11 lines (Backend godoc —
Provider ownership clause)
Tests:
core/frontend/durable/bug005_session_reuse_test.go new (~120 LOC)
- TestT3_Bug005_ProviderCachedBackend_ReusableAcrossSessions
Matrix both impls. Pins: after session 1's "close", session 2's
Open returns a USABLE Backend (not ErrBackendClosed). Sits at
Provider level — doesn't need a real target session to exercise
the invariant the fix establishes.
- TestT3_Bug005_ExplicitBackendClose_IsAllowed
Counterfactual: explicit Close by a caller who owns the handle
is still legal; subsequent I/O returns ErrBackendClosed. This
documents what Close IS for (Provider.Close path) vs what it is
NOT for (implicit session teardown).
## Why existing tests missed it
All T3a/T3b/T3c in-process tests are:
- single-session (no disconnect-reconnect cycle), OR
- direct-handler (SCSIHandler.HandleCommand / IOHandler.Handle),
bypassing target.handleConn's defer
Only "real target × session 1 disconnect × session 2 open"
exercises cross-session cache poisoning. Same L1-passes-L2-fails
shape as BUG-001.
## Contract going forward
frontend.Backend godoc now states:
"Backend.Close() is OWNED BY THE PROVIDER. Session-layer
consumers MUST NOT call Close on a Backend obtained from
Provider.Open — treat the returned Backend as a BORROWED
reference..."
Backend.Close itself stays legal; explicit-owner Close is still
supported (Provider.Close path, tests). The fix is about NOT
having session/target teardown silently call it.
## Regression
go test ./core/... -count=1 → 17/17 packages ok, 0 FAIL
BUG-005 regression tests: 2 × 2 impls = 4 subtests green
Prior T3 suites: unchanged (no impact)
## Ledger row queued ACTIVE
INV-DURABLE-SESSION-LIFECYCLE-001: Across session disconnect +
reconnect, the Provider-cached Backend remains operational; I/O
on the reconnected session MUST NOT receive ErrBackendClosed
caused by prior session teardown.
## T3-end three-sign impact
- Path A rename still stands (INV-DURABLE-CLEAN-RESTART-001 etc.)
- New row INV-DURABLE-SESSION-LIFECYCLE-001 added to closure
- G4 partial-pass gate updated: "clean restart OK + cross-session
reconnect OK"; real-kill + ENOSPC remain T3-DEF-3/4 inventory
items for post-T3 batch
- m01 re-verification pending QA
## References
sw-block/design/bugs/005_backend_close_cross_session.md (full post-mortem)
V2 reference: weed/storage/blockvol/nvme/{server.go,controller.go}
Memory: feedback_porting_discipline.md updated — new-abstraction
ownership drift citation added (third citation; BUG-001 +
pragmatic-evolution-revert + this one)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per T3c mini plan §1 — closes T3 delivery except for T3-end three-sign.
Atomic per mini plan §3 inherited stop rules.
## Scope delivered
### 1. Four scenarios (matrix over walstore + smartwal)
core/frontend/durable/scenario_crash_recovery_test.go
TestT3c_Scenario_CrashRecovery_AckedBytesByteExact
→ pins INV-DURABLE-001 (canonical G4 gate)
core/frontend/durable/scenario_wal_replay_test.go
TestT3c_Scenario_WALReplay_NAckedWrites
→ pins INV-DURABLE-WAL-REPLAY-001
core/frontend/durable/scenario_fsync_boundary_test.go
TestT3c_Scenario_FsyncBoundary_AckedSurvivesUnackedMayVanish
→ pins INV-DURABLE-FSYNC-BOUNDARY-001
core/frontend/durable/scenario_disk_fill_test.go
TestT3c_Scenario_DiskFill_OutOfRange_FailsCleanly
→ pins PCDD-DURABLE-DISK-FULL-001
Each scenario:
- Uses the shared logicalStorageFactories() matrix helper from T3a
- Runs as `{smartwal, walstore}` subtests
- Is an in-process L1 test (not subprocess / not YAML replay)
- Simulates "restart" by building a FRESH DurableProvider over
the same StorageRoot (closes + re-opens all state cleanly)
### 2. YAML shape docs
testrunner/scenarios/testdata/t3c-durable-crash-recovery.yaml
testrunner/scenarios/testdata/t3c-durable-wal-replay.yaml
testrunner/scenarios/testdata/t3c-durable-fsync-boundary.yaml
testrunner/scenarios/testdata/t3c-durable-disk-fill.yaml
Documentation of each scenario's shape, variant matrix, and
ledger pin. Authoritative test is the Go replay; YAML mirrors it
for reviewability per mini plan §1.1.
### 3. Perf baseline
testrunner/perf/t3c-durable-baseline.md
Workload spec + first-light numbers (sw dev Windows 11)
core/frontend/durable/perf_baseline_test.go
BenchmarkT3c_DurablePerf — matrix benchmark, both impls
First-light numbers at 8000 iterations, Sync every 64 writes:
- walstore: 197 µs/op, 20.75 MB/s, ~5k ops/s
- smartwal: 303 µs/op, 13.50 MB/s, ~3.3k ops/s
Characterization only, no threshold. Benchmark caps iterations
at 8000 so WAL capacity is not the bottleneck — not a saturation
benchmark. Real sustained numbers deferred to m01 fio run.
### 4. Closure report
sw-block/design/v3-phase-15-t3-closure-report.md
(seaweedfs repo — not in this commit)
§A-§F: batch history, delivery summary, V2 port depth audit,
ledger rows, T3-end three-sign table, change log.
## Acceptance (mini plan §2)
#1 All 4 scenarios × 2 impls (8 subtests) ✅ all green
#2 Frontend continuity — existing T2 tests green ✅ (see #5)
#3 m01 fs-workload smoke ⏸ post-sign (QA-owned)
#4 Perf baseline artifact ✅ numbers filled
#5 Full regression ✅ 17/17 pkgs ok
#6 Boundary guard ✅ durable/ auto-covered
#7 6 new ledger rows queued ✅ (4 T3c + 5 from T3a/T3b already ACTIVE)
#8 16 T2 ACTIVE rows still ACTIVE ✅ (no regression in iscsi/nvme)
#9 Closure report filled end-to-end ✅ (seaweedfs repo)
#10 T3-end three-sign ⏸ pending architect + PM + QA
## Regression
go test ./core/... -count=1 → 17/17 packages ok
- core/frontend/durable: 2.0s (76 subtests; +16 from T3c: 4 scenarios × 2 + 8 from earlier)
- core/frontend/iscsi: 31.5s (no regression)
- core/frontend/nvme: 61.3s (no regression)
- core/host: 127.7s (subprocess tests still memback; no durable wire)
- all others within normal range
## Stop rules honored
#port-model default ✅ (scenarios use public API only; no
storage internals)
#no scope creep T4 ✅ (no replication / failover surface
introduced)
#no new production code beyond T3a+T3b deliverables ✅
(scenarios + perf are test infra only)
## Out of T3c (post-three-sign, not blocking)
- m01 fs-workload verification (iterate-m01-nvme.sh tweak — QA)
- fio sustained numbers replace Go-bench first-light
- 24h m01 soak
## References
sw-block/design/v3-phase-15-t3-port-audit.md
sw-block/design/v3-phase-15-t3a-mini-plan.md (CLOSED 10cd117)
sw-block/design/v3-phase-15-t3b-mini-plan.md (CLOSED 29e3d0d)
sw-block/design/v3-phase-15-t3c-mini-plan.md (this batch)
sw-block/design/v3-phase-15-t3-closure-report.md (awaiting 3-sign)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per "make sure all test works for regular/smart wal" follow-up:
existing T3a/T3b tests exercise the adapter + provider against
both walstore and smartwal, but the iSCSI/NVMe wire tests (added
in 29e3d0d) only verify that `backend.Sync` is CALLED using
testback.RecordingBackend. They don't verify that real I/O
round-trips through the SCSI/NVMe command path when the backend
is durable-storage-backed.
This commit closes that gap with 4 matrix tests (8 subtests
total) that build a DurableProvider, open + recover the volume,
wrap it in the iSCSI / NVMe handlers, and issue real SCSI /
NVMe commands end-to-end against both impls.
## New files
core/frontend/durable/integration_iscsi_test.go (~135 LOC)
- TestT3b_Integration_ISCSI_WriteReadSync_Matrix
Write → SYNC_CACHE → Read round-trip at 512 B LBA; zero-
read on unwritten LBA. Both impls.
- TestT3b_Integration_ISCSI_MultiBlockWriteAcrossBoundary
8-block (4 KiB) WRITE(10) + READ(10) round-trip; pins the
adapter's byte↔LBA fast-path. Both impls.
- Shared openDurableBackend helper (used by NVMe file too).
core/frontend/durable/integration_nvme_test.go (~95 LOC)
- TestT3b_Integration_NVMe_WriteReadFlush_Matrix
NVMe Write → Flush → Read round-trip at 4 KiB LBA; zero-
read on unwritten LBA. Both impls.
- TestT3b_Integration_NVMe_MultiBlockWrite
4-block NLB Write → Flush → Read round-trip. Both impls.
## Coverage after this commit
core/frontend/durable: 60 subtests, 0 FAIL
- T3a: 16 tests × 2 impls = 32 subtests
- T3b provider/recovery: 10 tests × 2 impls + 3 solo = 23 subtests
- T3b integration (this commit): 4 tests × 2 impls = 8 subtests
- matrix canary: 1
Total matrix-parameterized subtests per impl: 24 walstore + 24 smartwal
## Scope classification
These are L1 integration tests (real handler + real adapter +
real LogicalStorage; in-process; no subprocess / no YAML / no
perf measurement). NOT T3c scenarios — T3c still owns:
- YAML scenario replay
- L2 subprocess continuity smoke
- m01 fs-workload
- Perf baseline
Consistent with Addendum A #1: "every adapter unit/integration
test runs walstore + smartwal" — this extends that discipline to
the SCSI/NVMe wire layer, which is still L1.
## Regression
go test ./core/... -count=1 → 17/17 packages ok
- core/frontend/durable: 0.6s (60 subtests; was 0.5s before)
- No regression elsewhere
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QA-owned tests and infra landed during Batch 11c sign-prep. These
files carry `Ownership: QA` headers — sw may not modify without
architect approval via §8B.4 Discovery Bridge.
## Files
### Kernel-realistic rewrites of prior QA tests
core/frontend/nvme/t2_v2port_nvme_pipelined_writes_test.go
core/frontend/nvme/t2_v2port_nvme_pipeline_extended_test.go
Post-BUG-001 revert rewrites to paired R2T+H2CData sequencing
(the pattern Linux kernel actually emits). Replaces the earlier
"send N cmds → read N R2Ts → then send all H2CData" shape which
QA withdrew after BUG-001 §13 post-mortem established that async
R2T emission is spec-legal but not kernel-realistic, and chasing
it broke m01 compatibility.
### B-tier early-landed regression tests
core/frontend/nvme/t2_v2port_nvme_disconnect_mid_r2t_test.go (L1B-4)
Pins server cleanup when host disconnects mid-H2CData-stream.
Ledger row: PCDD-NVME-SESSION-DISCONNECT-MID-R2T-001
core/frontend/nvme/t2_v2port_nvme_reconnect_loop_test.go (L1B-1)
50 attach/detach cycles + goroutine-leak sentinel. Surfaces
resource leaks that single-shot tests would miss.
Ledger row: PCDD-NVME-SESSION-RECONNECT-LOOP-001
### L3-A sign-prep infrastructure
scripts/iterate-m01-nvme.sh
m01 iteration harness for the remaining QA §4 checklist
item #4. Runs against real Linux NVMe/TCP initiator for
product-ready evidence.
## Regression
go test ./core/frontend/nvme/ -count=1 → ok 60.9s
Full suite green including these files (already verified locally
before commit).
## Sign-prep checklist progress (QA §4)
#1 L1-A ConcurrentQueueStress [x] commit b0ccd27#2 L1-A LargeWriteStress [x] commit b0ccd27#3 L2-A t2-nvme-smoke.yaml + replay [x] commit b0ccd27#4 L3-A m01 iterate-m01-nvme.sh [x] this commit (script landed;
QA runs against m01 next)
#5 Full regression green [x]
#6 Boundary guard green [x]
#7-#11 QA, post-soak
Co-Authored-By: Claude Sonnet 4.6 (QA agent) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sign-prep for T2B-NVMe-product-ready promotion (QA §4 checklist
items #1-3). Three new test files validating the V2-strict session
concurrency model under sustained load + a YAML-scripted subprocess
smoke for scenario reviewability.
## L1-A: ConcurrentQueueStress (t2_a_concurrent_queue_stress_test.go)
8 IO queues × 50 sequential Writes per queue = 400 Writes total.
Each Write is 32 KiB split into 8 × 4 KiB H2CData chunks (kernel
mkfs pattern). 90s hard deadline guards against deadlock
regressions.
Invariants:
- backend.calls == 400
- backend.bytes == 400 × 32 KiB
- no per-queue transport / status errors
- concurrent queues share target.ctrlMu without interference
Added helper: stressWriteTarget(t, volumeSize uint64) — spins up a
target with configurable volume size (default 1 MiB is too small
for 400 non-overlapping 32 KiB writes; test uses 64 MiB).
Runtime: 60 ms (localhost loopback).
## L1-A: LargeWriteStress (t2_a_large_write_stress_test.go)
100 sequential Writes at each of 5 sizes (512 B, 4 KiB, 8 KiB,
16 KiB, 32 KiB MDTS boundary). Per-iteration asserts:
- Exactly one R2T per cmd with DATAL == totalBytes (pins the
single-R2T-per-cmd invariant from the V2-strict revert)
- backend.calls / backend.bytes accumulate correctly
- Success status on every iteration
Added helper: writeChunkedOnClient(t, cli, slba, nlb, payload,
chunks) — issues a Write with N H2CData chunks (existing
nvmeClient.writeCmd does single-chunk only).
Runtime: 100 ms total across all 5 shapes.
## L2-A: Scripted smoke (testdata/t2-nvme-smoke.yaml +
## t2_l2_nvme_smoke_replay_test.go)
Declarative YAML scenario replayed against real blockmaster +
blockvolume subprocesses (reuses existing startL2NvmeHarness).
8 steps covering mixed sizes (1 LBA, 8 LBAs, 64 LBAs) + overwrite
semantics (write seed=11 at LBA 0, then write seed=44 at LBA 0,
assert read returns seed=44).
Payload semantics:
byte[i] = (seed + i) & 0xFF (deterministic; reads verify bit-
for-bit)
Adds yaml.v3 as test-only dep (already in go.mod via other
packages). Runtime: 13.7 s (subprocess bringup dominates).
## Files added
core/frontend/nvme/t2_a_concurrent_queue_stress_test.go (~130 LOC)
core/frontend/nvme/t2_a_large_write_stress_test.go (~160 LOC)
core/frontend/nvme/t2_l2_nvme_smoke_replay_test.go (~130 LOC)
core/frontend/nvme/testdata/t2-nvme-smoke.yaml (~60 LOC)
## Regression
go test ./core/frontend/nvme/ -count=1 → ok 60.9s
(full suite including existing L2 subprocess tests + new stress)
go test ./core/frontend/nvme/ -short -count=1 → ok 1.5s
(short mode skips L2 + stress; unit-only)
## Sign-prep checklist progress (QA §4)
#1 L1-A ConcurrentQueueStress [x] this commit
#2 L1-A LargeWriteStress [x] this commit
#3 L2-A t2-nvme-smoke.yaml + replay [x] this commit
#4 L3-A m01 iterate-m01-nvme.sh [ ] QA-owned
#5 Full regression green [x]
#6 Boundary guard green [x]
#7-#11 QA, post-checklist
Not in this commit (QA-authored files that landed in the same
working tree): t2_v2port_nvme_disconnect_mid_r2t_test.go,
t2_v2port_nvme_reconnect_loop_test.go, pipeline_extended +
pipelined_writes rewrites, scripts/iterate-m01-nvme.sh — QA to
commit separately.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per port audit + QA Discovery Bridge scope (separate cycle from
BUG-001). V2 fabric.go:41 extracts KATO from Connect CDW12 at
Connect time; V3's ckpt 7 session rewrite dropped this and relied
solely on Set Features 0x0F. Typical Linux hosts set KATO in
Connect and do NOT issue a follow-up Set Features — so ctrl.kato
was effectively zero on the target side for real hosts.
## Change
session.go handleAdminConnect: after allocating the controller,
call ctrl.setKATO(req.capsule.D12). Unit matches V2 (uint32
round-trip, no ms↔100ms conversion). QA constraint #2 preserved:
store-only, no timer armed. 6 LOC in session.go plus log-line
update.
## Test client
connectOptions gains a KATO uint32 field; dialAndConnectOpts
plumbs it into admin Connect's CDW12.
## Tests (new, all GREEN)
- TestT2V2Port_NVMe_Connect_KATO_CDW12_Persisted — Connect with
KATO=12000, assert Get Features 0x0F returns 12000
- TestT2V2Port_NVMe_Connect_KATO_Zero_Accepted — KATO=0 valid,
round-trips as 0
- TestT2V2Port_NVMe_Connect_KATO_OverriddenBySetFeatures — V2
precedence: Connect stores KATO, later Set Features 0x0F
overwrites (last-write-wins)
## Regression
go test ./core/frontend/nvme/ -count=1 → ok 32.0s
Existing 11b TestT2Batch11b_SetFeatures_KeepAliveTimer_RoundTrips
stays green (same storage cell).
## References
sw-block/design/bugs/003_nvme_kato_connect_cdw12_ignored.md
sw-block/design/v3-phase-15-t2-nvme-port-audit.md (M-category
fabric.go gap)
V2 source: weed/storage/blockvol/nvme/fabric.go:41, :244
## Exit criteria (from BUG-003 §8)
- [x] Connect CDW12 plumbed into ctrl.kato
- [x] New test green; 11b KATO round-trip test stays green
- [ ] Ledger row PCDD-NVME-FABRIC-CONNECT-KATO-001 promoted ACTIVE
(QA, after m01 verification)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Reverts the per-CID pendingWrites + async goroutine-spawn design from
commit 6d2c048. Restores V2's inline collectR2TData + pendingCapsules
+ recvH2CData(+bufferInterleaved) pattern as a strict port of
weed/storage/blockvol/nvme/controller.go.
## Why
6d2c048 passed QA's Go-harness tests but broke real Linux kernel
compatibility on m01. Kernel errored "r2t len 32768 exceeded data len
32768 (28672 sent)" — the kernel NVMe-TCP req state machine assumes
AT MOST ONE R2T OUTSTANDING per session, which V2 guarantees by
blocking rxLoop inside collectR2TData/recvH2CData until the current
Write's data is fully received. The pragmatic evolution emitted N
R2Ts async per N pipelined Cmds, which Linux req-state rejected.
Per feedback_porting_discipline.md + port-model decision §D2: port
means port. The QA Go-client tests that expected all-R2Ts-then-
all-H2CData did not match real kernel behavior and misled the fix
direction. QA is withdrawing and rewriting those tests to match
kernel-realistic wire patterns. See BUG-001 §13 for the full
post-mortem.
## What changes
session.go restored to V2 controller.go shape:
- rxLoop drains pendingCapsules before reading wire each iteration
- dispatchFromRx for IO Write (no inline): calls collectR2TData
INLINE in rxLoop (blocks until H2CData fully received), THEN
spawns handler goroutine for backend.Write
- collectR2TData: enqueue R2T + wait r2tDone + recvH2CData
- recvH2CData: loops reading headers; pduCapsuleCmd → bufferInterleaved
into pendingCapsules; pduH2CData → accumulate
- bufferInterleaved: fully reads pipelined Cmd into pendingCapsules
Removed (pragmatic-only):
- pendingWrites map + pwMu + registerPending/lookupPending/unregisterPending
- routeH2CData (per-CID dispatch from rxLoop)
- dispatchIOWrite with pre-data goroutine spawn
- abortPendingWrites cleanup
- pendingWrite struct + protocolErr
- R2T r2tSent channel (reverted to r2tDone)
Retained (independent of concurrency model):
- BUG-002: handleDisconnect + errDisconnect sentinel
- BUG-004: queueSize / flowCtlOff parsed from CDW11; advanceSQHD wrap;
flowCtlOff → SQHD=0xFFFF in writeResponse
- 11a/11b handler *Request refactor (admin_features, fabric, identify)
- Everything outside session.go
## Test status
80 PASS:
- 7 pre-existing debug tests (chunked R2T, 8-queue concurrent,
admin-while-IO, mkfs-pattern, chunking shapes, errors-verbatim,
pipelined-initial)
- A-tier A11.1/A11.2/A11.3/A11.4 (NGUID determinism, advertised-
features walk, CNTLID allocator, no-retry)
- 11b Property/Features/KeepAlive/AER suite
- Boundary guard, identity enforcement, io/errors
- ConnectionCloseDrainsInflight (passes incidentally — client
closes conn mid-stream so inline block doesn't matter)
2 FAIL (QA-owned, will be rewritten per QA plan):
- TestT2V2Port_NVMe_IO_Pipelined2WritesSameQueue (2s timeout)
- TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue (5 subs, 10s each)
Both expect "send N cmds, read N R2Ts, then send H2CData" pattern
which deadlocks V2-strict (and which real Linux kernel does not
emit). QA withdraws; will replace with paired R2T+data pattern.
## Next steps
- QA: rewrite the 2 RED tests to match real-kernel sequencing
- sw: re-run m01 mkfs.ext4 after QA's test rewrite lands to verify
kernel compat
- If m01 green: promote ledger row PCDD-NVME-IO-H2CDATA-CHUNKED-R2T-001
to ACTIVE; BUG-001 → VERIFIED → CLOSED after 24h soak
## References
sw-block/design/bugs/001_nvme_mkfs_r2t_hang_m01.md §13 (post-mortem)
V2 source: weed/storage/blockvol/nvme/controller.go (rxLoop/txLoop/
collectR2TData/recvH2CData/bufferInterleaved/pendingCapsules)
feedback_porting_discipline.md (second citation of this lesson in
Phase 15 T2 — first was Batch 10.5 VPD 0x80 Serial)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bundles Batch 11b (signed, uncommitted) + BUG-001/002/004 co-fix per
Discovery Bridge approved 2026-04-22. Scope delta vs. port plan §5.3:
session-loop rewrite ~250-300 LOC was classified as Linux-compat polish
at 80 LOC; actual need is a full mechanism port (see port audit).
BUG-001 (primary) — mkfs.ext4 hang on m01 / queue-internal CapsuleCmd
pipelining. Linux kernel ships multiple Write cmds on one IO queue
before any R2T is consumed; V3's serial session loop read cmd-N+1 bytes
while collecting H2CData-N and errored "expected H2CData, got 0x4".
Design:
- serve() splits Phase 1 (sync ICReq/ICResp) from Phase 2 (rxLoop +
txLoop goroutines with respCh between).
- rxLoop is sole reader post-IC. Routes by PDU type:
CapsuleCmd -> parseCapsule + dispatchFromRx
H2CData -> routeH2CData, dispatches bytes to pendingWrite by
CCCID; closes done when buffer full
- txLoop is sole writer post-IC. Drains respCh; handles CapsuleResp,
C2HData+CapsuleResp (Read/Identify), and R2T.
- IO Write path: dispatchIOWrite registers a pendingWrite, enqueues
R2T, spawns handler goroutine that waits on done then calls backend.
- Admin/Fabric handlers run synchronously in rxLoop (unchanged from
V2 shape) but enqueue responses through respCh instead of touching
s.w directly.
Deviation from strict V2 port (documented in session.go top comment):
V2's inline collectR2TData -> recvH2CData + pendingCapsules works for
real Linux kernels (they send H2CData immediately after R2T) but
deadlocks against QA's spec-strict tests where host sends N cmds and
expects N R2Ts before any H2CData. V3 moves H2CData collection out of
rxLoop into per-CID pendingWrites map so R2T emission is async. ~60 LOC
delta vs. strict V2 port. QA sign referred to the RX/TX split concurrency
shape, which this preserves verbatim. The spec-correctness advantage
(async R2T) is a pragmatic evolution, not a reinvention of the per-CID
state machine QA flagged.
BUG-002 — fcDisconnect handler. V3 previously returned Invalid Opcode on
`nvme disconnect`. Now handleDisconnect enqueues a success CapsuleResp
and returns errDisconnect sentinel; serve() maps the sentinel to nil.
BUG-004 — SQHD wrap at queueSize + flowCtlOff. Connect now parses
CDW11 low-16 (SQSIZE zero-based +1) and bit 18 (CATTR bit 2). advanceSQHD
wraps at queueSize; writeResponse reports 0xFFFF when flowCtlOff.
Handler signature migration: handleAdminIdentify / handleSetFeatures /
handleGetFeatures / handleKeepAlive / handleAsyncEventRequest /
handlePropertyGet / handlePropertySet now take *Request and route
through enqueueResponse. AER non-blocking park (QA #1) preserved —
handler returns nil without enqueueing when slot is free.
BUG-003 (KATO from Connect CDW12) and RF-1 (bufpool.go) explicitly
OUT of this commit per Discovery Bridge scope.
Tests:
- TestT2V2Port_NVMe_IO_Pipelined2WritesSameQueue (canonical) RED -> GREEN
- TestT2V2Port_NVMe_IO_PipelinedNWritesSameQueue (N=2,4,8,16,32) RED -> GREEN
- TestT2V2Port_NVMe_IO_ConnectionCloseDrainsInflight RED -> GREEN
- All 7 prior debug tests green
- 11a/11b A-tier + adversarial tests green
- Full nvme regression: ok 31.6s (no perf regression)
References:
sw-block/design/bugs/001_nvme_mkfs_r2t_hang_m01.md (BUG-001)
sw-block/design/bugs/002_nvme_fabric_disconnect_missing.md (BUG-002)
sw-block/design/bugs/004_nvme_sqhd_no_wrap.md (BUG-004)
sw-block/design/v3-phase-15-t2-nvme-port-audit.md (scope justification)
feedback_porting_discipline.md (lesson citation)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
QA review (2026-04-22) caught the N1 asymmetry: Batch 10.5
fixed VPD 0x83 NAA to be per-VolumeID derived, but VPD 0x80
Serial still defaulted to the hardcoded "SWF00001" stub. Linux
udev reads both pages together for its unique fingerprint; any
site running more than one volume would have distinct NAA but
identical Serial — exactly the "unusable hardcoded stub"
failure mode that N1's own comment flagged as the reason NAA
was changed away from V2's stub.
Fix shape (QA's Option 2): derive Serial from VolumeID when
cfg.SerialNo is not explicitly configured. Operator override
path preserved — an operator who wants a specific serial (asset
tag etc.) still sets cfg.SerialNo and it's honored verbatim.
core/frontend/iscsi/scsi.go:
- New serialFromVolumeID() helper: hex(sha256(VolumeID)[:8]) →
16 lowercase ASCII chars. 64 bits of entropy, deterministic,
per-volume unique. Mirrors naaFromVolumeID shape.
- NewSCSIHandler no longer defaults serialNo to "SWF00001".
Empty cfg.SerialNo leaves h.serialNo empty so the VPD 0x80
handler can derive on demand (it needs backend.Identity()
which isn't available until post-login in the session layer).
- inquiryVPD at case 0x80: if h.serialNo is empty, derive via
serialFromVolumeID(h.backend.Identity().VolumeID); otherwise
use the operator-supplied override as-is.
- Added "encoding/hex" import.
core/frontend/iscsi/scsi_batch10_5_test.go:
- TestT2Batch10_5_InquiryVPD80_ReturnsSerial updated: assert
16-char lowercase hex shape + regression guard that serial
is NOT the old "SWF00001" stub.
- NEW TestT2Batch10_5_InquiryVPD80_RespectsOperatorOverride:
cfg.SerialNo="ASSET-TAG-007" returns verbatim, so operators
can still override the derived default.
QA Owner will pin the symmetric determinism/collision invariant
in a separate A-tier Phase 3 test — this commit is sw's Option 2
fix, not the symmetric QA test.
Tests green (no regressions):
core/frontend/iscsi: 104 tests (was 102; +2)
All other packages: unchanged.
Stop-rule audit:
- inside §5.1 allowlist (VPD 0x80 was already an approved
page; this tightens the default rather than adding surface)
- advertised ≡ implemented discipline holds (Serial still
advertised; now meaningful)
- no stale W/R semantic change
- no core/authority / core/adapter bleed
standard INQUIRY V2-tuned shape
Three review findings closed (PM + architect, 2026-04-22):
Finding 1 — PM High / architect Medium: LBPME overclaim.
READ_CAPACITY(16) was advertising LBPME=1 (logical block
provisioning management enabled) while port plan §3.2 skip
list keeps UNMAP + VPD 0xB2 OUT of Batch 10.5. Aligned with
the principle from VPD 0x00 ("advertised ≡ implemented"): set
LBPME=0 until UNMAP + VPD 0xB2 are in scope. Comment updated
to explain the prior "V2 parity" justification was wrong — V2
parity on the SHAPE holds, but V2 sets LBPME=1 because V2
also implements the backing ops; T2 doesn't.
Finding 2 — architect Medium: readCapacity16 allocLen bug.
`if allocLen < 32 { allocLen = 32 }` forced up to the natural
response size, so the subsequent truncation branch never
fired. Initiator requesting a short response got the full
32 bytes — a protocol violation per SPC-5 §6.6 ("initiator
allocation length is authoritative"). Removed the force-up.
For allocLen < 32 the response now truncates correctly.
Finding 3 — PM Medium: standard INQUIRY under-ported.
V3 was returning a 36-byte minimal response; V2 tunes 96
bytes with Additional Length=91 and CmdQue=1 (command
queuing supported). Ported V2's shape:
byte 4 = 91
byte 7 = 0x02 (CmdQue=1)
bytes 8-31: vendor / product, V2-matched
bytes 32-35: rev "0001"
Skipped V2's TPGS bit (ALUA is skip-list). The previous
36-byte response worked for iscsiadm attach but forced the
kernel SCSI layer to assume minimum SPC capabilities — V2
tuning removes that.
core/frontend/iscsi/scsi.go:
inquiry(): 36 → 96 byte response, Additional Length=91,
CmdQue=1, allocLen default 96
readCapacity16(): drop force-up of allocLen; LBPME=0
core/frontend/iscsi/scsi_batch10_5_test.go:
Updated TestT2Batch10_5_ReadCapacity16_ReturnsLastLBAAndBlockSize:
now asserts LBPME == 0 (was: != 0)
NEW TestT2Batch10_5_ReadCapacity16_ShortAllocLen_Truncates:
{0,1,7,8,12,20,31} all truncate correctly; 100 caps at 32
NEW TestT2Batch10_5_Inquiry_StandardResponse_V2TunedShape:
pins 96-byte shape, Additional Length=91, CmdQue=1, TPGS=0
NEW TestT2Batch10_5_Inquiry_ShortAllocLen_Truncates:
SPC-5 §6.6 truncation rule for standard INQUIRY
Tests green (no regressions):
core/frontend/iscsi: 99 tests (was 96; +3 new regressions;
one existing assertion flipped
LBPME==0 from LBPME==1)
All other packages: unchanged.
Stop-rule audit after follow-up:
- advertised ≡ implemented discipline now holds end-to-end
- no new dispatch cases (fixes are field-level / length-level)
- skip list §3.2 unchanged (UNMAP, WRITE_SAME, PERSISTENT_RESERVE,
ALUA, VPD 0xB0/0xB2 still rejected)
- no stale W/R semantic change
- no core/authority / core/adapter bleed
Remaining for Batch 10.5 sign (QA Owner action):
- QA Owner A-tier Phase 3 tests per port plan §4:
* TestT2V2Port_SCSI_InquiryVPD00_AdvertisesOnlyImplemented
* TestT2V2Port_SCSI_InquiryVPD83_NAADerivationDeterministic
Sign-off tier unchanged: T2A-iSCSI-provisional. Batch 10.5
product-ready gate still requires the QA A-tier tests + m01
OS sanity pass.
Architect review findings 2026-04-21 (ckpt 10 Medium):
#1 EDTL trusted before CDB validation (memory amplification)
collectWriteData allocated make([]byte, edtl) and issued R2T
for the full EDTL before SCSIHandler ran the CDB's transfer-
length check. A hostile peer could advertise a huge EDTL on
a tiny WRITE(10) CDB to force an outsized buffer + R2T +
Data-Out collection before rejection.
Fix in session.handleSCSICmd: compute the CDB-authoritative
expected byte count (cdbExpectedWriteBytes for WRITE(10))
BEFORE entering collectWriteData. Mismatched EDTL returns
CHECK CONDITION + SenseIllegalRequest + ASCInvalidFieldInCDB
without any allocation or R2T. Unrecognized write opcodes
fall through to the handler's own validation path.
#2 R2T-solicited Data-Out accepted TTT=0xFFFFFFFF
collectWriteData had `|| pdu.TTT != 0xFFFFFFFF` exception
that silently admitted the unsolicited marker after the
target had issued an explicit R2T with TTT=1. Weakened the
InitialR2T=Yes "solicited-only" discipline.
Fix in collectWriteData: remove the 0xFFFFFFFF exception.
Data-Out MUST echo the R2T's TTT exactly. Comment updated
to explain why.
Low: narrowed the read-side comment on sendDataInWithStatus /
handleSCSICmd to reflect the actual T2 ckpt 10 scope
(single Data-In PDU with S-bit; read splitting deferred
until an OS initiator exposes the need).
core/frontend/iscsi/t2_ckpt10_hardening_test.go (NEW, sw regression)
TestT2Route_ISCSI_LargeWrite_EDTLCDBMismatch_RejectsWithoutAllocating:
Builds a SCSI-Cmd with WRITE(10) transferLen=1 (512 B) but
EDTL=128 MiB. Asserts:
- Target reply opcode != R2T (no R2T issued)
- Target reply opcode == SCSI-Response with CHECK CONDITION
- Sense key == IllegalRequest; ASC == InvalidFieldInCDB
- Round-trip fits within 2s (no 128 MiB allocation attempt)
- Backend.Write invocation count == 0 (pre-flight reject
never reaches the handler)
Uses a custom countingBackend wrapping RecordingBackend to
pin the "backend never invoked" invariant.
TestT2Route_ISCSI_LargeWrite_WrongTTT_OnDataOut_Rejected:
4-block write; 1 block immediate, 3 blocks solicited. Reads
the R2T, then sends Data-Out with TTT=0xFFFFFFFF (the
unsolicited marker) instead of echoing the R2T's TTT.
Asserts:
- Next read from the client side surfaces an error (target
closed the session)
- Backend WriteCount == 0
Pins the stop-rule: no silent weakening of the negotiated
solicited-only discipline.
Tests green (no regressions):
core/frontend/iscsi: 74 tests (was 72; +2 hardening regressions)
All other packages: unchanged.
Stop-rule audit: fixes stay inside ckpt 9/10 allowlist. No new
auth/digest/storage/authority paths, no stale W/R semantics
weakened.
Not addressed in this commit (documentation drift, QA-owned):
- The QA audit file header on t2_v2port_qa_test.go still
claims V3 "does not implement R2T" which became stale after
ckpt 10. sw cannot modify a QA-owned file without Discovery
Bridge — flagged to QA Owner for header update.
Per T2 assignment §4.3 ckpt 9/10 allowlist: "Multi-PDU R2T /
large write support" — port smallest required R2T path, keep
writes routed through frontend.Backend.Write.
Why now, ahead of actual iscsiadm failure on m01: the R2T path
is mechanical and well-understood. Writes > FirstBurstLength
(default 64 KiB) are the common large-write case iscsiadm will
drive. Porting now removes an m01 blocker without expanding
scope beyond the allowlist. Stop-rule audit below confirms no
overreach.
core/frontend/iscsi/session.go
handleSCSICmd now handles three write shapes:
- No write (FlagW off or EDTL=0): metadata / read path
unchanged; dataOut = req.DataSegment (typically empty).
- Immediate-only write (EDTL <= len(immediate data)): fast
path, no R2T.
- Solicited write (EDTL > len(immediate)): target emits ONE
R2T covering the remainder; collects Data-Out PDU(s)
with strict DataSN + BufferOffset ordering; dispatches
the assembled payload as ONE Backend.Write call.
New collectWriteData() enforces V2's correctness invariants:
- DataSN sequential (no out-of-order)
- BufferOffset matches cumulative received
- Data-Out TTT matches R2T TTT (or 0xFFFFFFFF unsolicited
is rejected since we negotiate InitialR2T=Yes)
- F-bit only valid when received == EDTL
- Overflow past EDTL rejected with clear error
Stop-rule observance (§4.3): stale-lineage semantics UNCHANGED.
A stale backend's write error surfaces AFTER R2T assembly
completes, as CHECK CONDITION — never as silent ACK because
the R2T sequence ran cleanly. This is pinned by
TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T.
T2 scope: single R2T for all remaining bytes (no MaxBurst
chunking). V2 supports multi-R2T per MaxBurstLength — we'll
port that ONLY if iscsiadm on m01 actually exposes the need.
core/frontend/iscsi/client_support_test.go
scsiCmdFull() is the new extended form: EDTL = len(immediate)
+ len(solicited). When the target emits R2T, the client feeds
the solicited bytes via one Data-Out PDU matching the R2T's
offset/length. Simpler legacy scsiCmd() is now a thin wrapper
that passes nil for solicited (preserves ckpt 4 call sites).
core/frontend/iscsi/t2_large_write_test.go (NEW, sw regression)
3 tests:
- TestT2Route_ISCSI_LargeWrite_R2TPath_Component:
16-block (8 KiB) write with only 4 blocks (2 KiB) immediate.
Target emits R2T; client feeds the other 12 blocks via
Data-Out. Asserts: exactly 1 Backend.Write, offset 0,
bytes exactly match a deterministic (i % 251) payload.
READ(10) round-trip verifies data landed at correct LBA.
- TestT2Route_ISCSI_LargeWrite_OnStaleBackend_RejectsAfterR2T:
stale backend + large write. R2T sequence still runs
(protocol correctness) but SCSI-Response is CHECK
CONDITION. Pins the stop-rule: R2T completion is NOT
commit authorization.
- TestT2Route_ISCSI_ImmediateOnlyWrite_StillWorks:
regression guard — 1-block immediate-only writes bypass
R2T as before. WriteCount=1, status Good.
Tests green (no regressions):
core/frontend/iscsi: 68 tests (was 65; +3 ckpt 10)
All other packages: unchanged.
Stop-rule audit (§4.3):
- Inside allowlist: multi-PDU R2T for writes ✓
- Did NOT port: V2 dataio.go multi-PDU Data-In splitting
(read-side chunking is separate from R2T; not an allowlist
item; not needed until an OS initiator exposes it)
- Did NOT weaken stale W/R semantics
- Did NOT introduce V2 authority / storage / WAL / retry paths
- Did NOT introduce MaxBurst chunking (smallest-required)
Sign-off tier: T2A-iSCSI-provisional unchanged. Ckpt 10 is
preparatory; product-ready promotion still gated on L2-OS
critical cells (i2/i3) on m01.
Architect residual-risk note (round-9 review): iSCSI Target
opened the frontend.Backend at accept time, before login. Any
connection — including Discovery — blocked on Provider.Open's
ErrNotReady wait, so `iscsiadm -m discovery` against a
not-yet-Healthy volume would hang instead of returning
SendTargets. Called out as a future m01 compat risk, not a
reject, but small enough to close now.
Fix:
- Target.handleConn no longer opens the backend. It hands
Provider + VolumeID + HandlerConfig to newSession and
lets the session decide.
- Session.serve does login FIRST. After login:
Discovery session → skip backend open entirely;
serve Text/Logout/NOP-Out only.
Normal session → call Provider.Open; a failure (e.g.
ErrNotReady) closes the session
cleanly after login rather than
blocking at accept.
- Target shutdown watcher now cancels the session ctx in
addition to closing the conn — required so a Provider.Open
that only wakes on ctx.Done can unblock during
Target.Close (avoids shutdown deadlock in the
never-ready regression test).
core/frontend/iscsi/session.go
Session now carries provider + volumeID + hcfg + backend.
serve(): loginPhase → (SessionType==Normal ? Provider.Open
+ build SCSIHandler : skip) → fullFeatureLoop. close()
also closes the opened backend.
core/frontend/iscsi/target.go
handleConn hands provider/volumeID/hcfg to newSession;
shutdown watcher cancels ctx so blocked Open unblocks.
core/frontend/iscsi/discovery_without_backend_test.go (NEW)
Two regression tests:
- TestT2Route_ISCSI_DiscoveryDoesNotDependOnBackendReady:
target bound to a neverReadyProvider (Open blocks
forever until ctx done); Discovery session completes
login + SendTargets + assertion within 5s. Asserts
Provider.Open was called ZERO times during Discovery.
- TestT2Route_ISCSI_NormalSessionClosesWhenProviderNotReady:
Normal-session login completes within 2s even though
Open blocks indefinitely — proves login isn't gated
on backend readiness.
Tests green (no regressions):
core/frontend/iscsi: 56 tests (was 54; +2 residual-risk regs)
All other packages: unchanged.
Stop-rule audit: fix is mechanism-level, stays inside the ckpt 9
allowlist (no new auth / digest / storage / authority paths).
Signs-off tier unchanged (T2A-iSCSI-provisional).
V2 mechanism port per assignment §4.3 ckpt 9 allowlist. Three
allowed mechanisms ported; nothing outside the allowlist is
introduced. The port discipline (mechanism-only, no V2 authority/
storage/auth) is preserved.
Why now: enables `iscsiadm -m discovery -t sendtargets` and a
real `iscsiadm -m node --login` to interoperate with the T2
target. L2-OS work on m01 (ckpt 11+) needs both; doing the port
once here keeps the ckpt-driven scope tight per the rule "port
the smallest required mechanism, not the directory".
Ports landed (all from weed/storage/blockvol/iscsi/):
core/frontend/iscsi/params.go (NEW)
Text key=value parser/encoder + numeric/boolean negotiation
helpers (RFC 7143 §6 + §13). CHAP helpers from V2 NOT ported
— auth is T8.
core/frontend/iscsi/login.go (REWROTE the minimal stub)
Full LoginNegotiator state machine: SecurityNeg → LoginOp →
FullFeature with parameter exchange. NegotiableConfig captures
the per-target profile (MaxRecv, MaxBurst, FirstBurst, R2T,
ImmediateData, etc.) with DefaultNegotiableConfig() matching
V2 sane defaults for Linux open-iscsi compat.
Identity capture (InitiatorName/SessionType/TargetName);
Normal sessions resolve TargetName via TargetResolver;
Discovery sessions skip the resolver check per spec.
Digest negotiation answers "None" for HeaderDigest /
DataDigest (T2 explicitly does not implement digest verify;
closure report won't claim digest security).
core/frontend/iscsi/discovery.go (NEW)
HandleTextRequest implements SendTargets. Multi-value
TargetName/TargetAddress encoding (the discovery exception to
Params duplicate-key rule). TargetLister interface for the
session to pull a live target list at request time.
core/frontend/iscsi/session.go (MOD)
loginPhase replaced its 1-shot "buildLoginResponse" with the
real negotiator loop (multi-round support). dispatch handles
OpTextReq via HandleTextRequest. Discovery sessions reject
SCSI commands (RFC 7143 §6.2). Session struct now carries
NegotiableConfig + TargetResolver + TargetLister via newSession.
core/frontend/iscsi/target.go (MOD)
TargetConfig: added IQN (now load-bearing — the resolver
requires it for Normal-session login), PortalAddr (operator
override for SendTargets advertised address), Negotiation.
Target satisfies TargetResolver (HasTarget(name)==name==IQN)
and TargetLister (single-target list).
core/frontend/iscsi/client_support_test.go (MOD)
Test client now sends InitiatorName/SessionType/TargetName +
digest negotiation params on login (the negotiator now
enforces V2-compatible required fields). loginOptions struct
lets tests opt into Discovery sessions or non-default identity.
NEW tests (sw-owned regression):
params_test.go 10 tests:
- encode/parse roundtrip preserves order
- parse rejects malformed / empty key / duplicate key
- parse skips trailing nul
- Set replaces existing key in place
- NegotiateNumber min(offered, ours) + clamp + non-numeric reject
- NegotiateBool AND semantics + invalid value
- BoolStr Yes/No
login_test.go 7 tests:
- DirectLoginOpToFullFeature: V2 "skip security" path used by
our test client; identity captured, digests echoed None,
TargetPortalGroupTag present (RFC 7143 §13.9).
- MultiRound_SecurityThenLoginOp: 3-round flow that iscsiadm
uses by default.
- DiscoverySession_NoTargetCheck: Discovery skips resolver.
- RejectMissingInitiatorName: status 0x02 detail 0x07.
- RejectUnknownTargetName: status 0x02 detail 0x03 (NotFound).
- OperationalNegotiation: MaxBurst min, FirstBurst min,
InitialR2T OR semantics.
- UnknownKey_NotUnderstood per RFC.
discovery_test.go 5 tests:
- EncodeDiscoveryTargets: 1 target, empty, omits empty Address.
- HandleTextRequest: SendTargets All / by-name / no key.
- TestT2Route_ISCSI_SendTargetsDiscovery: real in-process
Discovery session over wire — login as Discovery, send
SendTargets=All, verify TargetName + TargetAddress
(loopback + portal-group tag) come back. iscsiadm-shaped
end-to-end on the protocol layer (no OS initiator yet).
Tests green (no regressions):
core/frontend/iscsi: 54 tests (was 31; +23 ckpt 9)
core/frontend/nvme: unchanged (26)
All other packages: unchanged.
Sign-off impact: T2A-iSCSI-provisional unchanged. Ckpt 9 is
preparation for L2-OS work; product-ready promotion remains
gated on L2-OS critical cells (i2/i3) running on m01.
Stop rule observed (§4.3): no port outside the allowlist;
no stale-path semantics weakening; no V2 authority/storage
introduction.
Two architect-review findings (round-7) closed:
Finding 1: --nvme-ns was a dead flag.
cmd/blockvolume accepted --nvme-ns N but built TargetConfig with
zero-value Handler, so the IOHandler always defaulted to NSID=1.
An operator running --nvme-ns 7 got a target that still rejected
every command targeting NSID=7.
Fix (cmd/blockvolume/main.go):
Handler: nvme.HandlerConfig{NSID: uint32(f.nvmeNS)}
threaded through TargetConfig so the configured value reaches
the per-session handler.
Finding 2: --nvme-subsysnqn was advertised but not enforced.
Target.SubsysNQN was metadata-only; the wire-level Fabric Connect
accepted any host's SubNQN. A host could connect with an
arbitrary subsystem name and still get IO service — multi-target
routing and operator intent ambiguous.
Fix (core/frontend/nvme/session.go + target.go + errors.go):
- Session.expectedSubNQN field, plumbed via newSession().
- Target.handleConn passes t.cfg.SubsysNQN into newSession.
- handleFabric rejects mismatched SubNQN with
SCT=Command Specific (1) + SC=ConnectInvalidParameters (0x80)
per NVMe-oF spec §3.3.1. New SC constants in errors.go:
SCConnectInvalidParameters / SCConnectControllerBusy /
SCConnectInvalidHost.
- Empty Session.expectedSubNQN preserves "no enforcement"
contract for in-process L1 tests that don't pin a subsystem
identity. cmd/blockvolume always sets SubsysNQN (already
required at startup), so production is always enforced.
core/frontend/nvme/identity_enforcement_test.go (NEW, sw regression)
4 tests pin both fixes:
- TestT2NVMe_HandlerHonorsConfiguredNSID:
handler-level — IOHandler with NSID=7 rejects NSID=1
commands with Generic/InvalidField, backend not invoked.
- TestT2Process_NVMe_TargetHandlerNSIDConfigPropagates:
wire-level — Target with HandlerConfig.NSID=7 rejects
client Write at NSID=1; status decode confirms wire bits
SCT=0 SC=0x02. Backend not invoked.
- TestT2Process_NVMe_ConnectWithWrongSubNQN_Rejected:
low-level capsule write with wrong SubNQN; assert
wire status SCT=1 SC=0x80 (ConnectInvalidParameters).
- TestT2NVMe_EmptySubsysNQN_AcceptsAnyConnect:
regression for the in-process L1 path — empty target
SubsysNQN admits any Connect (preserves L1 test setup).
Tests green (no regressions):
core/frontend/nvme: 26 tests (was 22; +4 enforcement regressions)
All other packages: unchanged.
Sign-off impact: T2B-NVMe-provisional unchanged (still QA + sw lead);
follow-up tightens identity wiring per architect feedback before
T2-closed L2-OS work begins.
cmd/blockvolume/main.go
New flags symmetric with iSCSI:
--nvme-listen <addr> (loopback-only bind enforced;
empty disables)
--nvme-subsysnqn <nqn> (required when --nvme-listen set)
--nvme-ns <id> (default 1)
When --nvme-listen is set:
- implicitly auto-enables --t1-readiness with same stderr
notice ("blockvolume: nvme enabled: t1-readiness auto-enabled")
→ kept symmetric with iSCSI per QA checkpoint-7 note;
closure report doesn't have to explain asymmetry.
- constructs memback.NewProvider wrapping the volume's
AdapterProjectionView (same readiness bridge as iSCSI;
sketch §10 "Readiness bridge shared, not duplicated").
- emits nvme-listening JSON ready line with nvme_addr + subsys_nqn.
Refactored enforceIscsiLoopbackBind → enforceFrontendLoopbackBind
(parameterized on kind="iscsi"|"nvme") so both protocols use
one guard. Identical loopback-only safety policy.
core/frontend/nvme/t2_l2_nvme_harness_test.go (QA-owned, test-spec §6)
// T2 L2 EVIDENCE CLASS: L2-harness
T2.L2.n1 TestT2Process_NVMe_AttachWriteRead (13.6s):
real blockmaster + blockvolume subprocesses with
--nvme-listen on a reserved loopback port; Go NVMe/TCP
initiator does ICReq → fabric Connect → Write 512B at LBA
0 → Read at same location, bytes match over real wire
(capsule + R2T + H2CData + C2HData round trip).
T2.L2.n4 TestT2Process_NVMe_ReopenAfterMove_ServesNewLineage (17.2s):
same harness; pre-move Connect+Write+disconnect, then primary
volume restarts with new data/ctrl addrs (same status+nvme
addrs). Master mints IntentRefreshEndpoint → EV advances.
Fresh Connect to the same NVMe addr gets a backend at the
new lineage and Write+Read round-trip succeed. Explicit
NON-CLAIM: pre-move bytes not expected to persist.
NOT included per checkpoint-5 scope (C5.3 applied to NVMe):
T2.L2.n2 / n3 (stale Write / Read after move). L2-OS REQUIRED
critical cells; harness can't substitute for kernel ANA
Transition handling. Tracked for L2-OS on m01.
Tests green (no regressions):
core/frontend/nvme: 22 tests (errors 7 + boundary 1 + io 9 +
L1 route 3 + L2-harness 2)
core/frontend/iscsi: 31 unchanged
All other packages: unchanged.
Sign-off tier: T2B-NVMe-provisional
Acceptance:
- L0 6/6 green (n1-n6)
- L1 3/3 green (n1-n3 component route)
- L2-harness 2/2 green (n1 + n4)
- cmd/blockvolume --nvme-* product-host wiring landed
- loopback default + NQN required match T2 safe defaults
- i2 stale Write / i3 stale Read deferred to L2-OS
Sign-off: QA Owner + sw lead (§8B.9 provisional tier)
Downstream unlock: none; T2A-iSCSI-product-ready and
T2B-NVMe-product-ready remain L2-OS work
(m01 enablement).
Checkpoint 6 mirrors iSCSI checkpoints 1+2 for the NVMe/TCP
protocol. L1/L2 for NVMe come in later checkpoints.
cmd/blockvolume/main.go
Small follow-up on T2A-iSCSI-provisional sign-off note:
emit a stderr line "iscsi enabled: t1-readiness auto-enabled"
when --iscsi-listen implicitly flips the readiness bridge on.
Keeps operators from misreading the auto-enable as silent.
core/frontend/nvme/errors.go (NEW)
NVMe status vocabulary for T2:
SCT types (Generic, CommandSpecific, MediaDataInteg, PathRelated,
VendorSpecific)
Generic SCs: Success, InvalidOpcode, InvalidField, InternalError,
LBAOutOfRange, CapacityExceeded, NamespaceNotReady.
PathRelated SCs: ANA PersistLoss / Inaccessible / Transition.
StatusError type carrying (SCT, SC, Reason) with Error() and
EncodeStatusField() that packs SCT/SC into the 16-bit CQE
status field (SC<<1 | SCT<<9 per NVMe base spec §4.6.1).
Canonical constructors:
NewStaleLineage() -> SCT=3 (PathRelated) + SC=0x03 (ANA Transition)
— semantic match for authority-move
transition; Linux nvme driver treats this
as a path-retry condition.
NewBackendClosed() -> SCT=3 + SC=0x02 (ANA Inaccessible)
— distinct from stale-lineage so logs
disambiguate the two fail modes.
NewInvalidField(sc, reason) -> SCT=0 + caller SC.
Symmetric with iscsi/errors.go's ALUA 0x04/0x0A vs 0x04/0x00
distinction (see earlier checkpoint 2 note).
core/frontend/nvme/io.go (NEW)
IOHandler dispatches NVMe IO Read/Write/Flush to a
frontend.Backend. Opcode set intentionally minimal for L0 scope;
Identify / SetFeatures / fabric admin land with capsule framing
in a later checkpoint.
IOCommand is the normalized form (Opcode, NSID, SLBA, NLB, Data).
IOResult.AsError() returns nil on Success or a *StatusError.
mapBackendError: ErrStalePrimary -> ANA Transition;
ErrBackendClosed -> ANA Inaccessible;
other -> Internal Error (fail-closed).
LBA-range + NSID + short-data validation BEFORE backend call
(fail closed). NLB=0 is invalid in our one-based form (zero-based
on wire, one-based in IOCommand for readability).
core/frontend/nvme/io_test.go (QA-owned, test-spec §4 n1..n4)
T2.L0.n1 CommandReadWrite_UsesFrontendBackend: Read + Write
route through RecordingBackend, single invocation, exact
offset + data.
T2.L0.n2 StaleWrite_ReturnsProtocolFailure: non-Success,
SCT=3 SC=3 (ANA Transition).
T2.L0.n3 StaleRead_ReturnsProtocolFailure: non-Success,
zero data bytes (MUST NOT leak stale bytes), ANA Transition.
T2.L0.n4 InvalidInput_FailsClosed: table-driven — LBA past
end, LBA overflow, short data, NLB=0, unknown NSID. Each
fails at handler, backend never invoked.
Plus sw-added regressions:
BackendClosed_DistinctFromStale pins the ANA Transition vs
ANA Inaccessible distinction.
UnknownOpcode_ReturnsInvalidOpcode (fail-closed on 0x7f).
Flush_SuccessInT2Scope (no-op).
IOResult.AsError_NilOnSuccess + SupportsErrorsAs.
core/frontend/nvme/boundary_guard_test.go (QA-owned, test-spec n5+n6)
T2.L0.n5 + n6 AST guard: full-parse + alias-resolution (same
shape as iSCSI's boundary guard). Extends PCDD-STUFFING-001
coverage to core/frontend/nvme. No core/authority, no
core/adapter, no authority-minting composite literal, no
dot-import bypass.
Tests green (no regressions):
core/frontend/nvme: 17 tests (errors 7 + boundary 1 + io 9)
core/frontend/iscsi: unchanged (31)
All other packages: unchanged.
Sign-off tier: T2B-NVMe checkpoint 6 (L0 foundation). L1 + L2
arrive in checkpoints 7-8; T2B-NVMe-provisional pending L2-harness
(checkpoint 8).
cmd/blockvolume/main.go
New flags per assignment §3.2:
--iscsi-listen <addr> (empty disables; loopback-only bind
enforced at startup per C5.4
"Defaults must be safe")
--iscsi-iqn <iqn> (required when --iscsi-listen set)
--iscsi-lun <id> (default 0)
When --iscsi-listen is set:
- implicitly auto-enables --t1-readiness (iSCSI needs a
Healthy adapter projection to open a memback backend)
- enforces loopback bind (mirrors StatusServer's guard;
non-loopback or empty-host addrs rejected with clear
error). T2 iSCSI is unauthenticated — real-NIC binds
land with T8 security.
- constructs memback.NewProvider wrapping the volume host's
AdapterProjectionView, then iscsi.NewTarget on that
provider. Per-op lineage fence + supersede fence still
apply at SCSI command granularity.
- emits iscsi-listening JSON ready line with iscsi_addr
and iqn (same pattern as status-listening).
core/frontend/iscsi/t2_l2_iscsi_harness_test.go (QA-owned, test-spec §6)
// T2 L2 EVIDENCE CLASS: L2-harness
T2.L2.i1 TestT2Process_ISCSI_AttachWriteRead (13.5s):
real blockmaster + blockvolume subprocesses with
--iscsi-listen on a reserved loopback port; Go initiator
logs in, WRITE(10) 512 bytes at LBA 0, READ(10) at same
location returns identical bytes over real TCP+PDU framing.
T2.L2.i4 TestT2Process_ISCSI_ReopenAfterMove_ServesNewLineage (17.2s):
same harness; pre-move session writes then logs out; primary
volume restarts with new data/ctrl addrs (same status+iscsi
addrs). Master mints IntentRefreshEndpoint → EndpointVersion
advances. Fresh login on the same iSCSI addr serves the new
lineage (post-move WRITE + READ round-trip succeed under
the new Identity). Explicit NON-CLAIM: pre-move bytes not
expected to persist (memback is Identity-scoped; G8
territory).
NOT included per checkpoint-5 scope (C5.3): stale WRITE / READ
after move. Those are L2-OS REQUIRED critical cells; running
them at L2-harness would be a spec violation (§G3 initiator-
evidence rule + test-spec §6 L2-OS requirement). Tracked for
L2-OS on m01.
Tests green (no regressions):
core/frontend/iscsi: 31 tests (prior 29 + L2.i1 + L2.i4 L2-harness)
core/frontend, memback, testback, host/volume: unchanged.
Sign-off tier: T2A-iSCSI-provisional
(QA Owner + sw lead; per §8B.9).
L2-OS → product-ready → architect+PM sign is a later checkpoint.
NVMe/TCP slice (checkpoint 6) may now proceed in parallel.
core/frontend/iscsi/login.go
Minimal T2-scope login negotiator — accepts any Login-Request
with Transit=true + NSG=FullFeature and responds with Success.
No text-parameter negotiation, no CHAP, no digest. Sufficient
for L1 in-process component route; OS-initiator compat
(MaxRecv, digests, CHAP) is L2-OS scope.
core/frontend/iscsi/session.go
One goroutine per TCP connection. Serial rx/tx (no txLoop
split): login phase → full-feature dispatch. SCSI-Cmd PDUs
carry immediate data for WRITE (ImmediateData=true); READ
responses ride in a single Data-In with the S-bit set so the
status conveys with the data. CHECK CONDITION responses put
fixed-format sense data in the SCSI-Response data segment.
Logout + NOP-Out handled; other opcodes rejected.
core/frontend/iscsi/target.go
TCP listener + accept loop. On each accept, calls
frontend.Provider.Open to get the session's backend, then
builds an SCSIHandler bound to that backend. Close drains
active sessions.
core/frontend/iscsi/client_support_test.go (sw test-support)
Tiny Go initiator used by the L1 route tests: dialAndLogin,
scsiCmd (WRITE/READ/metadata), logout. Covers exactly what
L1 needs — not a general initiator.
core/frontend/iscsi/t2_route_iscsi_test.go (QA-owned, test-spec §5)
T2.L1.i1 TestT2Route_ISCSI_AttachWriteRead_Component:
in-process target + RecordingBackend — WRITE(10) routes
payload to backend exactly once; READ(10) returns the same
bytes over real TCP+PDU framing.
T2.L1.i2 TestT2Route_ISCSI_EndpointVersionMove_RejectsOldWrite:
swap provider to StaleRejectingBackend mid-flight; re-login
session's WRITE returns CHECK CONDITION, never success.
T2.L1.i3 TestT2Route_ISCSI_EndpointVersionMove_RejectsOldRead:
populate backend with known "secret" bytes, swap to stale,
re-login + READ — stale path returns CHECK CONDITION AND
bytes do NOT leak to initiator.
Tests green:
core/frontend/iscsi: 29 tests (errors 4 + guard 1 + scsi 11 +
pdu 10 + L1 route 3)
core/frontend, memback, testback, host/volume: unchanged.
Remaining for T2-closed: cmd/blockvolume --iscsi-* wiring, L2-harness,
NVMe/TCP symmetric slice, L2-OS enablement on m01.
core/frontend/iscsi/pdu.go
Port of weed/storage/blockvol/iscsi/pdu.go byte-for-byte on
the wire format. Constants (opcodes, flags, login stages,
MaxDataSegmentLength, AHS / data-segment padding rules) are
preserved. SCSI status byte constants that V2 duplicated into
pdu.go are NOT repeated here — they live in errors.go / scsi.go
for this port so there's a single source of truth.
Also renamed the two SCSI Response PDU helpers that collided
with our SCSI-layer terminology:
SCSIStatus() -> SCSIStatusByte()
SetSCSIStatus -> SetSCSIStatusByte
(SCSIStatus[Byte] here is the byte 3 field of an OpSCSIResp
PDU, not the handler-layer enum in scsi.go.)
core/frontend/iscsi/pdu_test.go (sw-owned)
Regression coverage for the wire layer:
- BHS-only roundtrip (opcode, immediate, LUN, ITT, CmdSN, CDB)
- Data segment roundtrip with 4-byte padding (5-byte payload
round-trips through 8-byte on-wire length)
- AHS roundtrip (multiple-of-4 contract)
- AHS non-multiple-of-4 rejected at WritePDU
- Truncated BHS -> ErrPDUTruncated
- Truncated data segment -> ErrPDUTruncated
- Oversized (>8 MiB) DSL -> rejected
- EOF on empty reader -> io.EOF (not wrapped)
- Login stage CSG/NSG + transit flag roundtrip
- OpcodeName covers all defined opcodes + unknown fallback
Session + target + login wiring still pending — next checkpoint
will compose PDU + SCSI handler into an in-process iSCSI target
for L1 route tests.
Tests green (no regressions):
core/frontend/iscsi: 26 tests (errors 4 + boundary 1 + scsi 11 +
pdu 10)
All other packages: unchanged.
core/frontend/iscsi/scsi.go
SCSIHandler adapting frontend.Backend to SCSI CDB dispatch.
Minimal opcode set for T2 L0: TEST_UNIT_READY, REQUEST_SENSE,
INQUIRY (standard, non-VPD), READ_CAPACITY(10), READ(10),
WRITE(10), REPORT_LUNS. Every READ/WRITE routes through
frontend.Backend.Read / .Write — the per-op lineage fence
fires exactly once per SCSI command.
mapBackendError maps frontend error values to SCSI status/sense:
ErrStalePrimary -> CHECK CONDITION + NOT READY +
ASC 0x04/ASCQ 0x0A (ALUA asymmetric access
state transition — matches lineage-move
semantics, distinct from generic not-ready)
ErrBackendClosed -> CHECK CONDITION + NOT READY +
ASC 0x04/ASCQ 0x00 (cause not reportable)
Distinct ASCQ so operators can tell stale-lineage and
closed/faulted apart in logs.
LBA-range and short-dataOut validation happens BEFORE the
backend call (fail closed). Zero-length transfer is a valid
no-op and does not touch the backend.
core/frontend/iscsi/errors.go
ASCStaleLineage/ASCQStaleLineage now pinned to SPC-5's
"asymmetric access state transition" pair (0x04/0x0A) for the
reason above. Single source of truth for the stale-lineage
wire mapping.
core/frontend/iscsi/scsi_test.go (QA-owned, test-spec §4)
T2.L0.i1 TestT2ISCSI_CommandReadWrite_UsesFrontendBackend:
WRITE(10) then READ(10) route through recording backend;
exact offset, exact data, single invocation each.
T2.L0.i2 TestT2ISCSI_StaleWrite_ReturnsCheckCondition:
stale WRITE -> non-Good, CHECK CONDITION, NotReady,
stale-lineage ASC; never silently ACKs success.
T2.L0.i3 TestT2ISCSI_StaleRead_ReturnsCheckCondition:
stale READ -> non-Good, zero data bytes, CHECK CONDITION;
never leaks stale bytes to initiator.
T2.L0.i4 TestT2ISCSI_InvalidInput_FailsClosed:
table-driven — LBA past end, LBA overflow window, short
dataOut. Each fails at the handler, backend never invoked.
Zero-length transfer verified as valid no-op.
Plus sw-added regressions:
- TestT2ISCSI_BackendClosed_MapsToNotReady pins the
stale-vs-closed ASCQ distinction so future refactors can't
collapse the two fail modes.
- TestT2ISCSI_MetadataCommands_SuccessForT2Subset covers
TUR/INQUIRY/READ CAPACITY/REPORT LUNS/REQUEST SENSE happy
path (initiator handshake won't blow up once PDU framing
lands).
- TestT2ISCSI_UnknownOpcode_ReturnsIllegalRequest ensures
unknown CDBs fail-closed and never reach the backend.
Scope: this checkpoint delivers handler-LEVEL coverage of the
four L0 T2.i* tests. Session-LEVEL API (Login/Session, wire
PDUs, TCP target) lands with PDU framing in the next checkpoint
— at which point L1 component tests (in-process target +
Provider) can run against real Go initiator code.
Tests green (no regressions):
core/frontend: T1 suite unchanged (18s incl. L2)
core/frontend/iscsi: 16 tests (errors 4 + guard 1 + scsi 11)
core/frontend/memback: 6
core/frontend/testback: 4
core/host/volume: prior volume suite
Implements the frontend contract per T1 sketch §5-9: Identity,
Backend, Provider, ProjectionView types; ErrStalePrimary /
ErrNotReady / ErrBackendClosed sentinels; memback contract-smoke
backend that re-validates full lineage on every Read/Write.
Tests per QA test-spec:
L0 x7 (provider open healthy + not-ready, backend read/write,
stale read, stale write table-driven, close, boundary guard)
L1 x1 (Publisher + VolumeBridge publication route, Epoch-bump
move, old backend rejects, new backend serves post-move)
Two sw review notes for QA Owner:
- Spec samples use engine.ReplicaProjection{VolumeID, ReplicaID,
Healthy}. Actual engine type lacks those fields; per sketch §5
the frontend defines its own Projection struct. Documented in
file headers.
- Spec's T1.L1.1 asserts ReplicaID change across the move.
Cross-replica authorship requires TopologyController, not
StaticDirective. This L1 proves Epoch-drift fence (the fence's
actual invariant). ReplicaID-change coverage routed to L2
over the real product route.
L2 test (T1.L2.1) not written: BLOCKED-BY-T0 per test-spec §6 —
the T0 noop executor cannot produce a frontend-serving projection
until the T1-owned readiness bridge lands in cmd/blockvolume.
Product binaries (cmd/blockmaster, cmd/blockvolume) and
core/host wiring for volume-scoped assignment delivery,
durable authority with Windows rename retry, and the T0
closure test set (D1 L2 subprocess, D2 G1 adversarial,
D3 concurrent write-reload regression, D4 hosting-smoke
scenario + Go-native replay, D5 --topology flag).
Diagnostic surfaces: ObservationStore.SupersededCount
(PCDD-DELAYED-HB-001 evidence, not authority input) and
SetNowForTest clock seam on Store/Host, guarded by grep
test ensuring the identifier stays out of production files.
Three review follow-ups from PR #10 CodeRabbit feedback. All
style/robustness; no correctness changes.
1. core/authority/authority.go — drop dead-scaffolding locals
(prevForRollback / hadPrev) around the durable-write path.
State mutation is deliberately sequenced after store.Put, so
there is nothing to roll back on Put failure. Replace the
phantom locals with a comment stating the invariant.
2. cmd/sparrow/s7_restart_smoke_test.go — use exec.CommandContext
with a 60s test-level deadline for both the go build and the
two subprocess runs, so a hung child dies when go test times
out instead of lingering.
3. cmd/sparrow/s7_bootstrap_test.go — replace
`dir + string(os.PathSeparator) + ...` with filepath.Join for
cross-platform correctness.
Not addressed (explicitly CodeRabbit-flagged "recommended not
essential"): double-reload at boot (bootstrap.go). Would require a
new Publisher WithPreloaded option; skipped to keep this commit
tight and not reopen S5 surfaces.
go test ./core/authority ./cmd/sparrow -count=1 green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes the S8 evidence-matrix gap for Claim 6 (controller-driven
bind / reassign / refresh over accepted topology). Prior state had
Bind / Reassign with dedicated L1 routes but refresh was only
exercised at L0 via controller_test.go, covered implicitly by
placement/rebalance/failover. This adds the explicit route.
Scenario: heartbeats report slot DataAddr/CtrlAddr changing for the
current authority while publisher still holds old addrs →
decideVolume emits IntentRefreshEndpoint → publisher bumps
EndpointVersion on the same Epoch → bridge delivers refreshed
AssignmentInfo to the consumer → next rebuild confirms via the
full contract (including addr match) and clears desired.
Test file: core/authority/convergence_route_test.go
- TestConvergenceRoute_RefreshEndpoint_ConfirmsAndClearsDesired
- buildV1HeartbeatsWithAddrs helper (per-replica addr override for
heartbeat construction)
Publisher's directive is the real TopologyController (not a static
ask list) so the route goes through decideVolume.
go test ./core/authority -count=1 green (4.8s).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Proves the S4-S6 control loop composes under restart and real-route
pressure: durable authority reload -> observation replay -> controller
recompute -> VolumeBridge delivery -> VolumeReplicaAdapter.
Restart sequence pinned (sketch §5, adapter-BEFORE-bridge per round-3):
lock -> store -> pub(reload) -> ctrl(reloaded reader) -> host(same
reader) -> adapter -> VolumeBridge -> pub.Run + host.Start.
Desired state is recomputed, not persisted (sketch §6). No DesiredStore,
no StuckStore, no bootstrap-mint shortcut. Stale pre-restart observation
rejected via existing basisMatchesLine, not a new bootstrap predicate.
L1 (core/authority/restart_route_test.go, 8 tests + 4 stale sub-cases):
row 1 reloaded authority via bridge to adapter; row 2 recompute (hard
precondition + same-observation replay); row 3 stale observation (4
sub-cases via snapshottingReader host-reader freeze — test simulation
shape per sketch §9, not a heartbeat-wire claim); row 4a old slot NOT
revived from durable (S5 one-record-per-volume contract); row 4b
live-route monotonic guard rejects bridge-delivered old slot from
in-memory publisher; row 5 unsupported evidence via ConflictingPrimaryClaim;
row 6 fence path bounded (Fence command reaches executor via real route;
withheld callback does not produce spurious Healthy); row 7 per-volume
isolation on restart.
L2 component (cmd/sparrow/s7_bootstrap_test.go): rows 8/9/10a via
in-process Bootstrap two-run, asserting directly on ReloadedRecords,
ReloadSkips, VolumeAuthorityLine. No backward mint across restart.
L2 subprocess (cmd/sparrow/s7_restart_smoke_test.go): row 10b via real
sparrow binary spawn twice against the same store dir. Asserts exit 0
on both runs, lock released between runs, second-run structured stdout
reports the durable line the first run wrote, backwardMint=false.
cmd/sparrow additions:
- --s7-restart-smoke flag (test-only, undocumented in --help)
- runS7RestartSmoke entry with pinned JSON pass-line schema
- parseFlags rules: requires --authority-store, mutually exclusive with
--s5-bootstrap
Helpers: restartRoute / simulateRestart (single pinned construction
seam; no direct adapter.OnAssignment anywhere; uses VolumeBridge, not
hand-rolled Bridge goroutines); restartExecutor (fence-mode configurable
pre-loop); snapshottingReader.forceSet for stale-basis simulation.
Engine/adapter/transport: no changes. Row 4 honesty split (round-5c):
durable restart discards old-slot state by S5 design, so "old-slot
rejected on restart" is proved by ABSENCE; the monotonic-guard proof
belongs to a pre-restart live-route test where in-memory per-replica
keys legitimately exist. Row 6 explicitly defers the full timeout-
expiry quantitative bound to the adapter's own tests (sketch §10.1
Path B forbids S7 from reconfiguring the fence path).
Residual: Windows TempDir teardown can race with lock-file release;
logged as residual per sketch §8.5 scope — durable-store write/reload
errors remain hard failures.
go test ./core/authority ./cmd/sparrow ./core/adapter -count=1 green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Turns controller desired assignments into a bounded-fate closure:
confirmed, retried (passively), superseded, or surfaced as stuck
evidence — without minting new authority.
- DesiredAssignment: +ProposedBasis/DesiredAt/LastRetryAt/Stuck.
- TopologyControllerConfig: +RetryWindow (default 5s).
- convergence.go: ConvergenceStuckEvidence (distinct map from
UnsupportedEvidence), supersedeDesiredLocked (case 1 only:
publisher epoch > ProposedBasis AND different target — case 2
dropped because it misclassified every in-flight Reassign),
evaluateStuckLocked (passive; does NOT re-emit).
- controller.go: unified processSupportedVolumeLocked; confirm
routes through clearDesiredLocked so late post-Stuck
confirmations drop stuck evidence; supported-recovery clears
prior UnsupportedEvidence.
L0 (convergence_test.go): 15 targeted proofs — confirmation
(both-sources, stale-observation guard), stuck (after window,
no Reassign churn, clears on late confirm), supersede
(publisher moved elsewhere, normal-lag is NOT supersede,
decision-table differs), pending/unsupported clearing,
per-volume isolation, supported-recovery evidence cleanup.
L1 (convergence_route_test.go): 3 component-route proofs through
ObservationHost -> TopologyController -> Publisher ->
VolumeBridge -> Consumer: observation-fed failover confirms,
publish-but-not-observed reaches Stuck with no duplicate
bridge delivery, supersede drops stale desired.
No engine/adapter/transport changes. S2 non-forgeability and
S5 store-write guards still pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Introduces the P14 S5 durable-authority layer: Publisher state
survives control-plane restart via an atomic-rename file-per-
volume store, guarded by a cross-platform OS-level single-owner
lock, with startup wiring in cmd/sparrow that acquires the lock
and reloads durable truth before live publication begins.
Load-bearing boundaries held (sketch §3):
* durable authority store may preserve and reload truth, but
it may NEVER mint truth. Publisher is the sole minter of
Epoch / EndpointVersion; the store persists values already
minted and reloads them verbatim at boot.
* AST boundary guards (from S5 sketch §12) enforced at test
scope: no non-authority code constructs a DurableRecord with
non-zero Epoch/EndpointVersion, no non-authority code calls
store.Put.
Core store and interface (core/authority/):
* authority_store.go — DurableRecord shape (per-volume current
line; no per-slot history, no append log, no wall-clock
freshness field); AuthorityStore interface with Load /
LoadWithSkips / Put / Close; SHA-256-checksummed JSON
envelope; per-record ErrCorruptRecord; index-level failure
distinguished from per-record skip.
* authority_store_file.go — file-per-volume FileAuthorityStore
with fsync + atomic rename on write; stale-tempfile cleanup
on Load; INJECTIVE filename encoding (every non-[a-zA-Z0-9-]
byte including '_' escapes as "_XX" — closes the earlier
"_002f" vs "/" aliasing gap).
* authority_bootstrap.go — AcquireStoreLock returning a
StoreLock whose OS-level file lock is dropped on handle
close, cross-platform crash-safe.
* authority_bootstrap_unix.go (build !windows) — syscall.Flock
with LOCK_EX|LOCK_NB.
* authority_bootstrap_windows.go (build windows) —
syscall.CreateFile with dwShareMode=0 exclusive share;
ERROR_SHARING_VIOLATION / ERROR_ACCESS_DENIED map to
ErrStoreLockHeld. Purely stdlib; no x/sys dependency.
Publisher integration (core/authority/authority.go):
* WithStore(store) functional option on NewPublisher. Nil /
omitted keeps existing in-memory behavior.
* Synchronous reload at construction: verifies records,
populates p.state, seeds p.writeSeqByVolume from max stored
WriteSeq. Per-record corrupt skips surface via LoadErrors()
(per-volume fail-closed; process continues).
* Synchronous write-through in apply(): DurableRecord built
under pub.mu, store.Put invoked before in-memory commit. On
Put failure the in-memory state is NOT mutated, subscribers
are NOT notified, and the caller gets a wrapped error — on-
disk and in-memory stay lock-step.
* Index-level load failure panics at construction (honors the
sketch §10 fail-the-whole-boot rule); the Bootstrap helper
converts this to a clean error return via a pre-check.
Live sparrow entry point (cmd/sparrow/):
* bootstrap.go — Bootstrap(storeDir, directive) helper that
performs the full startup sequence (lock → store → index
pre-check → NewPublisher with reload → log outcomes). Also
exposes BootstrapFromStore seam so tests can inject a mock
store to exercise the pre-check cleanup branch portably.
* s5_bootstrap.go — runS5Bootstrap mode invoked via
"sparrow --authority-store <dir> --s5-bootstrap". Acquires
lock, reloads, runs Publisher briefly, emits report, exits
cleanly. This is the one real non-test caller of the
durable route. The default demo path stays in-memory by
design (the Bind/Reassign smoke sequence is not restart-
clean, and forcing it to be would smuggle durability-aware
branches into SMOKE test code).
* main.go — --authority-store and --s5-bootstrap flags
rejected at parseFlags unless paired; --s5-bootstrap
dispatches to runS5Bootstrap. Default modes unchanged.
Proof (core/authority/ + cmd/sparrow/):
* authority_store_test.go — round-trip, latest-wins per-volume,
corrupt-record per-volume fail-closed, atomic-write-no-torn
(orphan tempfile cleanup), process lock exclusivity +
idempotent release + survives stale lockfile on disk,
unreadable-index boot fails closed, wall-clock-NOT-consulted
on reload, AST boundary guards (store never mints, only
core/authority calls store.Put), filename encoding
injectivity + no-filesystem-unsafe-output, envelope shape.
* authority_restart_test.go — reload reproduces current line,
stale pre-failover record rejected, Publisher advances from
reloaded truth (not zero), Controller sees reloaded line at
boot, Put-failure rolls in-memory back, empty-store reload
yields fresh state, store-backed Publisher runs normal
Bridge route.
* cmd/sparrow/bootstrap_test.go — live Bootstrap tests: fresh
dir acquires lock + reloads, existing-record reloads into
Publisher state, corrupt record logged at startup (not
stranded in LoadErrors), lock contention refuses second
bootstrap, empty dir errors, Close idempotent,
ParseFlags_AuthorityStoreRequiresS5Bootstrap flag validation,
RepeatedRunsAreRestartClean (two runS5Bootstrap invocations
on same dir with seeded record between — architect round-7
regression), PreCheckFailure_ReleasesLockAndClosesStore
(mock-injected index failure → lock released, store closed,
error returned — architect round-8/9 regression).
* observation_test.go — E2E SystemFedSnapshotReachesController
poll-loop fixed: was racing on first non-empty submission
(initial pending) instead of waiting for supported; now
polls until supported-v1 with 3 slots is observed.
No changes to engine, adapter, transport, ops, storage.
Authority package: 112 tests. cmd/sparrow: 19 tests. Full module:
12 packages pass.
Design docs in sw-block/design/ external repo:
* v3-phase-14-s5-assignment.md
* v3-phase-14-s5-durable-authority-institution.md
* v3-phase-14-s5-sketch.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Lands two related pieces that make late-Phase-14 observation-to-
authority truth system-owned:
1. Multi-volume TopologyController (accepted P14 topology set:
per-volume three-slot on distinct servers). This was the
"consumer baseline" staged earlier as full-topology
scaffolding and is committed here as the foundation S4 feeds.
2. Observation institution: heartbeat / inventory -> stable
ClusterSnapshot producer, per the S4 assignment
(sw-block/design/v3-phase-14-s4-assignment.md and
v3-phase-14-s4-sketch.md).
Load-bearing boundary held across both pieces:
* observation institution may withhold supportability, but it
may NOT mint authority (sketch §3)
* Publisher stays the sole minter of Epoch/EndpointVersion
* adapter.OnAssignment stays the one and only consumer ingress
* no new engine event, command, or projection field
Observation-side deliverables (core/authority/):
* observation_types.go — Observation, ServerFact, SlotFact,
LocalRoleClaim, FreshnessConfig, Supportability enum
(pending / supported / unsupported kept VISIBLY distinct per
architect execution note), AcceptedTopology, six reason
constants.
* observation_store.go — push-ingest latest-wins per ServerID,
derived ServerFreshness (never-observed / bootstrapping /
missing / fresh / expired), immutable storeSnapshot for
builder input, configurable GC.
* observation_wire.go — V2 heartbeat wire shape port
(block_heartbeat / block_heartbeat_proto /
block_heartbeat_loop analogues) as mechanism only.
HeartbeatToObservation is a pure field-shape copy.
* unsupported_evidence.go — per-volume VolumeUnsupportedEvidence
(latest-wins per VolumeID), separate VolumePendingStatus,
SupportabilityReport with Pending + Unsupported as distinct
maps, BuildResult.
* snapshot_builder.go — pure BuildSnapshot(store, topology,
reader) -> BuildResult. Reads publisher's current per-volume
line via the read-only AuthorityBasisReader and stamps it in
VolumeTopologySnapshot.Authority for supported volumes, so
the controller's stale-resistance check can match on
subsequent feeds. Observation never mints authority.
* observation_host.go — owns store lifecycle, push-ingest
entry points, reactive rebuild (build-on-change + coalescing
wake), GC sweep honoring configured retain window,
ControllerSink atomic submission (snapshot + report
together so supportability transitions propagate even when
supported volumes drop to zero).
Controller-side intake (core/authority/controller.go):
* SubmitClusterSnapshot kept as the test-scaffolding entry.
* NEW SubmitObservedState(snap, report) — the observation-fed
intake. Mirrors SubmitClusterSnapshot's convergence
discipline line-for-line (stale-basis preserves desired,
no-emit clears desired, same-ask dedupe prevents authority
churn) and adds pending/unsupported transition handling.
Under this intake, the controller hears every supportability
transition, including "zero supported volumes now", which
clears stale desired state.
V2 muscles ported (mechanism only):
* block_heartbeat / block_heartbeat_proto field layout
(observation_wire.go)
* block_heartbeat_loop shape concept (host owns the loop)
Explicitly NOT ported (per assignment denylist):
* weed/storage/blockvol/promotion.go
* old HandleAssignment / promote / demote ownership
* master_block_plan / master_block_failover / master_block_registry /
master_block_assignment_queue (reference only for S5/S6)
* any V2 path where heartbeat timing or local status becomes
failover truth
Proof matrix (observation_test.go — 35 tests covering all sketch
§16 rows + architect-round regressions):
Authoring:
- PartialInventory_PendingThenUnsupported
- MissingServerObservation_NeverOrdinaryIneligible
- EndToEnd_SystemFedSnapshotReachesController
- ConflictingPrimaryClaim_Unsupported
- ConflictingPrimaryClaim_NoWinnerEverChosen
- ExpiredFact_SemanticallyIneligible
- ExpiredDoesNotReachController
- BadVolumeDoesNotBlockHealthyVolume_Isolation
- VolumeUnsupportedEvidence_IsolatedPerVolume
- DuplicateServerTopology_UnsupportedAndEvidenceRecorded
- DuplicateServerTopology_NotControllerInput
Host-level:
- IngestMutation_TriggersSnapshotRebuild
- FreshnessWindowHonored_NotTickMultiples
- GCRetainWindow_Honored
Boundary (AST-based, sketch §16a):
- NeverMintsAuthority_BoundaryGuard
- SupportabilityDoesNotReadClusterSnapshotOutput
Architect round-2 regressions:
- BuilderStampsAuthorityFromReader
- SupportabilityCollapsePropagatesToController
- SupportabilityCollapseClearsControllerDesired
- UnknownObservedVolume_ProducesUnsupportedEvidence
Architect round-3 regressions:
- IdenticalSupportedSnapshots_NoDuplicateAsks
- VolumeRecovers_ClearsStaleDesired
No changes to engine, adapter, transport, ops, storage, or
sparrow. 91 authority tests pass. Full module: 12 packages pass.
Design docs in sw-block/design/ external repo:
* v3-phase-14-s4-assignment.md
* v3-phase-14-s4-observation-institution.md
* v3-phase-14-s4-sketch.md
* v3-phase-14-s4-closure-gaps.md (architect-round boundary notes)
* v3-phase-14-full-topology-design.md
* v3-phase-14-placement-rebalance-policy.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Introduces the first accepted S3 slice: one explicit policy owner
behind the S2 Directive seam, with cross-slot failover proven
end-to-end through the existing authority publication route. The
accepted topology set for this slice is one volume, two replica
slots on distinct servers, one current primary, one failover
candidate.
Load-bearing boundaries preserved from S2:
* policy emits AssignmentAsk, never AssignmentInfo
* authority.Publisher remains the sole minter of Epoch /
EndpointVersion (enforced by the repo-wide AST
non-forgeability test)
* engine and adapter remain consumers; adapter.OnAssignment
stays the one and only consumer ingress
* Remove / retirement deferred
S2 boundary change absorbed via the reassign-semantic note
(sw-block/design/v3-phase-14-s3-reassign-semantic.md):
* IntentReassign is now a per-volume authority advance, not a
per-slot Epoch bump. Target ReplicaID may differ from the
currently-published replica. New Epoch is minted from the
max across (VolumeID, *) + 1. EV resets to 1 on the target.
Still requires SOME prior publish for the volume; first-time
establishment remains IntentBind.
* Per-slot EV monotonicity unchanged for IntentRefreshEndpoint.
Implementation (core/authority/):
* policy.go — PolicyOwner (Directive impl), AssignmentAsk input
model (AuthorityBasis, SlotObservation, PolicySnapshot),
PolicyConfig, AuthorityBasisReader (LastAuthorityBasis +
VolumeAuthorityLine), decision table (Bind /
RefreshEndpoint / Reassign), unsupported-topology evidence
with structured offending-basis artifact.
* authority.go — widened IntentReassign; new
VolumeAuthorityLine method on Publisher; new VolumeBridge
helper for system-owned retarget without test choreography;
new maxPublishedEpochForVolume helper.
Four ordered guards on every snapshot in PolicyOwner.Next:
1. distinct-servers invariant (empty ServerID or matching
non-empty ServerID -> unsupported evidence)
2. snapshot-side authority-in-topology (snap.Authority outside
the two slots -> unsupported evidence)
3. publisher-side out-of-topology authority (publisher's
current per-volume line on a replica not in the two slots
-> unsupported evidence carrying the offending Basis)
4. per-volume stale-resistance (snap.Authority must match the
current per-volume authority line on VolumeID, ReplicaID,
Epoch, EndpointVersion)
Closure proofs (core/authority/policy_test.go — 26 new tests):
Authoring (§13.1 of sketch):
- TestPolicy_NoAuth_OneAcceptable_EmitsBind
- TestPolicy_NoAuth_BothAcceptable_EmitsBindForPreferred
- TestPolicy_NoAuth_NeitherAcceptable_NoAsk
- TestPolicy_CurrentHealthy_Unchanged_NoAsk
- TestPolicy_CurrentHealthy_DataAddrChanged_EmitsRefresh
- TestPolicy_CurrentHealthy_CtrlAddrChanged_EmitsRefresh
- TestPolicy_CurrentUnacceptable_OtherAcceptable_EmitsReassign
- TestPolicy_CurrentUnacceptable_OtherUnacceptable_NoAsk
- TestPolicy_AuthOutsideTopology_NoAskPlusUnsupportedEvidence
- TestPolicy_UnsupportedTopology_AlwaysEmitsEvidence
- TestPolicy_OnlyThreeIntentsProduced
Stale-resistance (§13.2 + architect round 2 + round 3):
- TestPolicy_StaleDecision_DroppedWhenAuthorityAdvances
- TestPolicy_StaleRefresh_DroppedWhenNewerEndpointVersion
- TestPolicy_NewerSnapshotOverwritesOlder_OnlyLatestValidEmits
- TestPolicy_StaleSnapshotAfterCrossSlotFailover_Dropped
Topology honesty (architect round 3 + round 4):
- TestPolicy_EmptyServerID_NoAskPlusUnsupportedEvidence
- TestPolicy_BothSlotsSameServer_NoAskPlusUnsupportedEvidence
- TestPolicy_OutOfTopologyPublisherAuthority_NoAskPlusUnsupportedEvidence
(structured Basis assertions — evidence carries the
offending publisher line, not just a reason string)
Boundary:
- TestPolicy_NoDirectAssignmentInfoConstruction
- TestPolicy_DoesNotAddAdapterIngress
Reassign semantic regressions:
- TestReassign_CrossSlotMintsEpochPlusOne
- TestReassign_NoPriorVolumePublish_StillRejects
- TestReassign_PerSlotOpsOnOldSlotDoNotAdvanceVolumeLine
- TestReassign_PerSlotEndpointVersionMonotonicityPreserved
End-to-end closure (VolumeBridge-based, no test choreography):
- TestPolicyToAdapter_E2E_Bind
- TestPolicyToAdapter_E2E_Failover
- TestPolicyToAdapter_E2E_EndpointRefresh
- TestVolumeBridge_FollowsFailoverWithoutTestChoreography
- TestVolumeBridge_PostFailoverOldSlotRefreshRejectedByAdapter
(adapter rejects stale-identity input delivered through
VolumeBridge after cross-slot move)
- TestPolicyToAdapter_E2E_Failover_PublicationHonestyDuringTransition
(ack-gated window: adapter is non-Healthy at Epoch=2 until
FenceCompleted; observed deterministically via fence-hold
hook on the test executor)
No changes to engine, adapter, transport, ops, storage, or
sparrow. The S3 package is additive.
Authority package tests: 56 pass (30 from S1+S2; 26 new from S3).
Full module: 12 packages pass.
Design docs (in sw-block/design/ external repo):
* v3-phase-14-s3-audit.md
* v3-phase-14-s3-sketch.md
* v3-phase-14-s3-design.md
* v3-phase-14-s3-closure.md
* v3-phase-14-s3-reassign-semantic.md (boundary note)
* v3-phase-14-s3-closure-gaps.md (round 3 boundary note)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Addresses five architect findings across two review rounds, all on
the authority package introduced in 5c663b8. The core S2 boundary
(Publisher is the sole minter, identity keyed by (VolumeID,
ReplicaID), Directive is the only policy seam) stays unchanged;
this commit tightens correctness of delivery and the strength of
the non-forgeability proof.
1. Close-safe delivery (High). apply()'s fan-out ran outside
pub.mu and could race with cancel()/Run-exit closing the same
channel. The former deliverLatest free function was not
close-aware — a concurrent close would produce send-on-closed
panics, and its drain-retry loop on a closed channel (where
receive is permanently ready with zero value) would spin
forever.
Fix: subscription now owns a sync.Mutex + closed flag. New
methods subscription.deliver() and subscription.close() both
acquire s.mu; deliver() returns early if closed, and close()
is idempotent. The deliverLatest free function is gone;
apply() calls s.deliver(next). cancelSubscription and
closeAllSubscriptions call target.close() instead of closing
target.ch directly.
Regression: TestPublisher_CancelDuringDeliveryDoesNotPanic
stress-runs 50 concurrent subscribe/cancel goroutines against
200 concurrent Refresh asks on the same (vid, rid). Asserts no
panic and no hang within 5 s.
2. Catch-up ordering race (High). Subscribe() registered the new
subscriber in p.subs under pub.mu, then released the lock and
did a blocking sub.ch <- st.info. A concurrent apply() could
deliver a newer fact first; the delayed catch-up would then
enqueue the older fact, producing stale/out-of-order delivery
on a route that must converge to current authority truth.
Fix: the catch-up send now happens INSIDE the pub.mu critical
section, immediately after the subs-map insert. Because sub.ch
is cap=1 and the fresh subscription is invisible to any other
goroutine until pub.mu is released, the catch-up send is
guaranteed non-blocking. Any later apply() either runs before
us (catch-up state IS current) or sees us in the subs map and
drains our stale catch-up via deliver(). Strict ordering.
Regression:
TestPublisher_LateSubscriberReceivesLatestUnderConcurrentPublish
runs 200 iterations of (concurrent Reassign + fresh Subscribe +
drain); asserts drained epoch <= current authoritative epoch
every iteration.
3. AST non-forgeability proof gap — deferred-mutation bypass
(Medium). The earlier AST walker explicitly skipped short
declarations (x := adapter.AssignmentInfo{}), so the pattern
x := adapter.AssignmentInfo{}
x.Epoch = userInput
bypassed both checks: the literal is zero-valued so check (a)
did not trigger, and the short-decl path was ignored in (b).
Fix: auditNonForgeability now handles the AssignStmt branch
with Tok == token.DEFINE; any RHS that is a composite literal
of AssignmentInfo type is flagged as the deferred-mutation
bypass shape, regardless of field values. Also added the
long-decl-with-value case: var x = adapter.AssignmentInfo{}.
Regression (two synthetic-source tests that exercise the audit
function directly):
- TestNonForgeability_CatchesShortDeclBypass
- TestNonForgeability_CatchesVarDeclBypass
4. AST non-forgeability proof gap — pointer form (Medium,
subsequent round). After the short-decl fix, the architect
noted the same bypass in pointer form was still outside the
proof:
x := &adapter.AssignmentInfo{}
x.Epoch = userInput
The AST walker only recognized a bare *ast.CompositeLit on the
RHS, missing the UnaryExpr(&, CompositeLit) wrapper.
Fix: new helper unwrapAddrOfCompositeLit recognizes both
X{...} and &X{...}. Both GenDecl-with-value and AssignStmt
branches use it.
Regression:
- TestNonForgeability_CatchesPointerShortDeclBypass
- TestNonForgeability_CatchesPointerVarDeclBypass
5. Doc drift (Low). Two doc blocks still described the pre-fix²
state: docs/p14-s2-design.md said "simple 'forbidden
constructor' grep" and docs/p14-s2-closure.md listed
Unsubscribe as a Publisher method. Both updated to reflect the
AST-based whole-repo walker (covering value and pointer
forms) and the per-subscription cancel API with no key-wide
unsubscribe verb. Test count in closure.md bumped to 26 and
pointer-form test names added to the verification list.
No changes to engine, adapter, transport, ops, storage, or
sparrow. Authority tests: 26 pass. Full module: 12 packages pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Addresses three architect findings on the first S2 drop:
1. High: Unsubscribe(vid, rid) was key-wide — one Bridge exiting
silently closed channels for all other peers on the same
(VolumeID, ReplicaID). Replaced with per-subscription cancel:
Subscribe now returns (ch, cancel func). Each cancel closes only
its own subscription. Publisher owns a nextSubID counter and
tracks subscriptions as []*subscription per key. Cancel is
idempotent and safe against concurrent Run-exit teardown via a
"whoever finds it closes it" protocol.
Regression test: TestPublisher_IndependentUnsubscribe_OtherPeersUnaffected.
2. High: silent drop on full subscriber buffer could leave the
adapter on stale authority truth until an unrelated later ask
happened — unacceptable for an authority route. Per-subscription
channels are capacity 1 with overwrite-latest semantics: on full,
the publisher drains the stale pending value and retries send,
so the subscriber always reads the LATEST authoritative state
next. Intermediate states may be coalesced (correct for authority
truth; the engine cares about current identity, not interstitial
history).
Regression test: TestPublisher_DeliveryConvergesToLatestOnSlowConsumer.
3. Medium: the non-forgeability structural test was a regex-based
grep over core/ only, and caught only composite-literal Epoch
assignments. Rewritten as an AST-based walker that (a) covers
the whole repo (cmd/ and future production packages included,
not just core/) and (b) catches both composite-literal mints
with non-zero Epoch/EndpointVersion AND local variable
declarations of type AssignmentInfo — the classic bypass shape
for deferred mutation: `var x AssignmentInfo; x.Epoch = input`.
The stronger check surfaced three pre-existing hidden operator
paths in cmd/sparrow/main.go that minted AssignmentInfo with
hard-coded epochs 1/2/3 directly. All three demo sites are now
routed through a shared authority.Publisher: healthy demo issues
IntentBind, catch_up and rebuild demos issue IntentReassign.
No sparrow demo code constructs AssignmentInfo directly anymore.
Other:
* Run now closes every live subscription channel on exit, so
Bridges observe end-of-stream cleanly. Tested by
TestPublisher_RunClosesLiveSubscriptionsOnExit.
* Publisher.apply() releases the publisher lock before fan-out,
preventing a slow consumer from stalling the authoring loop.
Docs updated:
* docs/p14-s2-design.md — Publication API now documents
per-subscription cancel, removes the stale Unsubscribe(vid,rid)
verb, adds the "lossless for current fact" delivery semantic.
* docs/p14-s2-closure.md — test list updated (20 tests), Changed
section records the sparrow migration.
No changes to engine, adapter, transport, ops, storage.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Introduces the core/authority/ package — the system-owned publication
route where Epoch and EndpointVersion are authored, not relayed. The
publisher is the only production code that constructs an
adapter.AssignmentInfo with a non-zero Epoch.
Contract boundaries (load-bearing):
* S2 owns publication of authority truth.
* S2 does NOT own failover policy.
* Engine and adapter remain consumers, not producers.
Design:
* Publisher.Run consumes AssignmentAsk values from an injected
Directive and fans out AssignmentInfo to subscribers keyed by
(VolumeID, ReplicaID) — not by ReplicaID alone, which would
multiplex different volumes that share a replica name.
* AssignmentAsk carries no Epoch and no EndpointVersion. The
publisher mints both from the intent enum (Bind | RefreshEndpoint
| Reassign). Retirement (Remove) is deliberately deferred.
* No public verb accepts a preformed AssignmentInfo. The former
PublishAssignment relay verb was removed from the design before
code — the publisher is a minter, not a pass-through.
* Directive is the seam where P14 S3's failover policy will later
plug in without reaching into the publisher. S2 ships only
StaticDirective.
* Bridge forwards publisher output to adapter.OnAssignment — the
adapter remains the one and only consumer entry point; no second
mutation ingress was added.
Tests (core/authority/authority_test.go):
* Intent semantics: Bind mints epoch=1 ev=1; RefreshEndpoint keeps
epoch and bumps ev (no-op on unchanged addrs); Reassign bumps
epoch and resets ev=1; each invalid precondition is rejected.
* Fan-out keyed by (VolumeID, ReplicaID): two subs on the same key
both receive; a sub on a different volume for the same replica
name does NOT receive — regression for the narrow-key bug.
* Late-subscriber catch-up via LastPublished.
* Run loop drives Directive until ctx cancel; rejected asks are
logged and loop continues.
* Bridge forwards to AssignmentConsumer.
* Closure target integration test: Publisher -> Bridge -> real
VolumeReplicaAdapter reaches Mode == ModeHealthy without any
harness.assign call.
* Non-forgeability structural test walks core/ and fails if any
production file outside an explicit allowlist (authority /
calibration / conformance / schema) constructs an AssignmentInfo
with a non-zero Epoch.
Docs:
* docs/p14-s2-audit.md — scoped audit of existing producers /
publishers / consumers / hidden-operator-path smells / V2 port
candidates.
* docs/p14-s2-design.md — bounded design: load-bearing boundaries,
closure target, package layout, AssignmentAsk shape, authoring
rules table, publication API, Bridge model, V2 port plan,
explicit non-goals and acceptance criteria.
* docs/p14-s2-closure.md — what S2 closed, what stayed out, S2/S3
boundary table, verification recipe.
No changes to engine, adapter, transport, ops, storage, or sparrow
wiring. The authority route is additive.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds an explicit FenceAtEpoch command + FenceCompleted/FenceFailed
event pair on the caught-up recovery branch. A replica with R >= H
under a newer identity epoch is no longer declared healthy until the
replica's lineage gate has been bumped to match Identity.Epoch via a
FenceCompleted — closing the window where stale old-epoch traffic
could still land on the replica while the projection already reads
healthy.
Contract surface:
* Caught-up path emits ONLY FenceAtEpoch — no catch-up / no rebuild.
Fence is a command+event pair, not a session lifecycle.
* PublishHealthy held until FenceCompleted advances FencedEpoch.
Publication and DeriveProjection both gate on this so the
operator-visible mode reflects the ack-gated contract, not
just the command stream.
* FenceFailed is fail-closed: FencedEpoch is NOT advanced; retry
is probe-driven (next successful probe re-runs decide() and
re-emits FenceAtEpoch).
* Session completion (catch-up / rebuild) implicitly fences,
because mutating traffic at the current epoch already bumped
the replica's gate.
* Stale FenceCompleted (epoch < Identity.Epoch, or same epoch
with older endpointVersion) is rejected without mutating state.
* FencedEpoch is engine-internal; NOT exposed in ReplicaProjection.
Adapter-side fence dispatch:
* fenceInFlight keyed by fence LINEAGE
(replicaID, epoch, endpointVersion), NOT by replicaID alone.
This prevents a newer-epoch fence from being starved by an
older in-flight fence — both occupy distinct slots, the old
one is dropped by the engine as stale when its callback lands,
and the newer one drives publication to healthy without
waiting for an unrelated later probe.
Proof tests:
* engine: TestFence_CaughtUpPath_UsesNoDataRecovery
* engine: TestFence_HealthyOnlyAfterFenceComplete
* engine: TestFence_FailureLeavesFencedEpochUnchanged
* engine: TestFence_StaleOldEpochRejectedAfterFenceOnCaughtUp
* adapter: TestFullRoute_CaughtUp_NotHealthyUntilFenceComplete
* adapter: TestFence_NewerEpochNotStarvedByOlderInFlightFence
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* storage: local data process — admission, flusher, and experimental extent-direct backend
Names the local data process (read / write / flush / checkpoint /
recover on one node) as a bounded institution with an explicit
crash model and carry-forward boundaries. Adds WAL admission
backpressure, a background flusher that drains WAL entries into
the extent, and an experimental metadata-only backend alongside
the regular WAL+extent backend. Both backends implement the same
LogicalStorage interface and pass the shared contract test suite.
Admission controller ports the battle-tested watermark algorithm
from the in-production engine: 0.7 soft / 0.9 hard, counting
semaphore for concurrent writers, deadline governing the whole
Acquire call, flusher wakeup via a dedicated urgent-notify seam.
Defaults intentionally absent at the admission layer — callers
set them explicitly, same contract as the source.
Flusher processes the entire dirty-map snapshot per cycle; the
on-disk checkpoint is bumped to the highest LSN verified-and-
flushed. Compare-and-delete cleanup preserves concurrent writes
that bumped an LBA's LSN after the snapshot was taken.
The experimental backend (core/storage/smartwal) writes data to
the extent first and appends only a small metadata record to a
ring. Reads bypass the ring entirely. A group committer batches
concurrent fsyncs.
Adopting the extent-direct backend as the default would be a
separate decision; this change only makes it available behind the
same interface.
Docs: docs/local-data-process.md names the institution, its crash
windows per backend, and the explicit carry-forward list.
* protocol: close recovery around explicit lineage at every layer
Every recovery start now carries (epoch, endpointVersion, sessionID,
targetLSN) — a single tuple that travels from engine decision through
adapter command, transport wire, replica ingress, and back via ack.
Each layer rejects messages whose lineage doesn't match the contract
it currently believes is active, so stale work cannot leak between
layers.
Engine: probe / catch-up / rebuild commands carry epoch +
endpointVersion. ProbeFailed and RecoveryFactsObserved are now
treated as lineage-bearing observations and dropped if stale.
Same-observation reorder fix is preserved and extended so reversed
probe/facts arrival still converges. Zero-valued epoch /
endpointVersion are rejected at event ingestion with a clear trace
key, not silently at the wire.
Adapter: each Start* command mints a fresh process-wide sessionID
and feeds it synchronously through the executor and engine, so
every outbound mutation can carry it.
Transport: invalidated sessions are canceled — the active session
holds its conn, and InvalidateSession closes the conn directly so a
goroutine parked in ReadMsg unblocks immediately. Recovery conns
have explicit deadlines on every write/read. Mutating wire frames
(ShipEntry, RebuildBlock, RebuildDone, BarrierReq) carry the full
lineage tuple. Replica ingress rejects stale lineage and closes the
connection without partial application.
Rebuild: blocks now apply with the engine's frozen targetLSN
instead of a placeholder, so a future LSN-aware ApplyEntry guard
won't silently drop rebuild data. The primary returns success only
after reading BarrierResp from the replica with the actually
achieved frontier — never on EOF, timeout, or a non-terminal phase
ack.
Tests: adversarial coverage at every layer — stale transport-epoch
events at the engine, stale callback drops at the adapter, mid-
session invalidation interrupting a blocked ack read at the
transport, stale wire-lineage rejection at the replica, and a
calibration handoff/stale-probe scenario.
README adds a roadmap table naming what each upcoming phase closes
and what it does not, so the project's bounded-closure model is
visible to readers.
* transport: institutionalize the data-sync layer
Names the bounded data-sync institution: catch-up byte movement,
rebuild byte movement, barrier exchange, achieved-frontier report,
and the lineage gate that fails closed on stale or overlapping
traffic. The institution does not own recovery classification,
session lifecycle policy, failover decisions, or operator
publication — those belong to later phases.
Splits transport into per-responsibility files so the boundaries
are visible on the page:
executor.go — session lifecycle + probe (observation only)
catchup_sender.go — primary-side catch-up byte movement
rebuild_sender.go — primary-side rebuild byte movement
barrier.go — typed BarrierResponse and helpers
replica.go — per-message-type handlers, lineage gate
Catch-up and rebuild each keep their own ship loop. The two
protocols look similar today but have different terminators (barrier
vs RebuildDone) and shouldn't share a hidden implementation that
would mask their divergence later.
BarrierResponse replaces the bare 8-byte uint64 wire reply with a
typed struct {AchievedLSN uint64}. The replica reports what Sync()
actually returned; the primary returns that value verbatim. Short
or unexpected payloads now fail closed instead of silently
fabricating a frontier.
Replica handler dispatch extracted into named per-message methods
(handleShipEntry, handleProbeReq, handleRebuildBlock,
handleRebuildDone, handleBarrierReq), each fronted by the same
acceptMutationLineage gate.
Five new fail-closed tests prove the institution's negative space:
- overlapping sessions: higher lineage bumps active state, older
session's in-flight frames are rejected
- primary mid-rebuild crash: subsequent higher-lineage session
converges, achieved frontier reflects the new session
- replica disconnects before BarrierResp: primary surfaces failure
with no fabricated AchievedLSN
- stale Ship after newer Rebuild: cross-message-type lineage
rejection
- probe during rebuild: probe is observation, does not disturb
activeLineage
Plus a typed-barrier roundtrip + short-payload-fails-closed test.
docs/data-sync-institution.md names what this layer owns, what it
does not, and the explicit carry-forward to later phases.
* chore: remove committed artifact .commitmsg
* engine, adapter, transport: close recovery-execution lifecycle
Admits one bounded recovery-execution institution around
engine-issued recovery commands: engine command → prepared →
real started or bounded timeout → cancel/invalidate/fail/complete
→ terminal close truth. Every stale or delayed callback fails
closed under lineage without reviving dead semantic truth.
Scaffolding (admitted earlier in this working session):
- SessionPrepared event splits "we accepted the contract" from
"runtime actually began execution". A dial failure or
invalidate-before-start no longer looks identical to a real
running session.
- OnSessionStart callback + SetOnSessionStart on CommandExecutor
tie SessionStarted to real execution start, not command
issuance. Transport emits it via signalSessionStart after
attachConn succeeds, with a registry recheck so an invalidate
between attach and signal drops the callback.
- startTimeout watchdog in the adapter arms on Start* only, fires
only if engine-state still matches (sessionID == q.sessionID
AND Phase == PhaseStarting), clears on real start or terminal
close. An old timer racing a newer session records fire_noop,
not a spurious failure.
Closure (this pass):
Engine trace detail enriched so ignored transitions name the
current phase ("current phase=failed") and session ID mismatch
traces distinguish older-session vs newer-session vs no-active-
session via phaseMismatchDetail(). Operators debugging a stale
callback can tell at a glance why it was rejected.
Adapter watchdog now records structured lifecycle events via
WatchdogLog(): arm, clear_started, clear_closed, supersede, fire,
fire_noop. Not an operator surface — execution evidence for tests
and diagnostic dumps.
New tests covering the required proof set:
engine/apply_test.go:
- TestV3_Terminal_DelayedFailureAfterCompletionIgnored
- TestV3_Terminal_DuplicateCompletedIgnored
- TestV3_Terminal_DuplicateFailedIgnored
- TestV3_Terminal_InvalidPhaseTransitionsLeaveStateUnchanged
adapter/watchdog_test.go (new):
- TestWatchdog_ClearedByRealStart
- TestWatchdog_ClearedByImmediateClose
- TestWatchdog_OldTimerCannotFailNewSession
- TestWatchdog_InvalidateBeforeStart_NoFalseStartNoFalseSuccess
transport/transport_test.go:
- TestTransport_Lifecycle_LateCompletionAfterInvalidateDropped
docs/recovery-execution-institution.md updated with per-scenario
proof table, separate watchdog contract table, and an explicit
"What is NOT proven here" section naming carry-forward for
multi-replica coordination, policy-driven invalidation, operator
surfaces.
Non-identity invalidation remains out of scope: the engine still
emits InvalidateSession only from identity-truth handlers
(assignment, removal). A SessionInvalidated reducer exists without
an emitter as forward-compatibility for the topology phase.
* ops: bounded single-node product surface
Makes the existing inspection endpoints read as one coherent
single-node product surface: self-describing, bounded, and
tested against its honesty rules.
Added two endpoints so the surface is product-shaped rather than
four scattered reads:
GET / surface map — scope + endpoints + read-only note
GET /diagnose bounded summary over projection + trace tail +
watchdog counters; full fidelity stays at the
dedicated endpoints
Every field exposed by /diagnose is derivable from the existing
State.Snapshot() — projection, trace, watchdog log. The surface is
a mirror over accepted lower truth, never a new authority path.
No HTTP mutation surface. Any mutation verb on any path still
returns 501. The surface-index test rejects cluster-shaped
vocabulary ("cluster", "failover", "promotion", "topology
authority", "rf3") in the self-description — an early draft of
the root endpoint's note used "Cluster-shaped control" and the
test caught it; the note was reworded positively.
Proof (core/ops/surface_test.go):
- TestSurfaceIndex_SelfDescribing: GET / lists exactly the paths
the mux wires, each with a non-empty Owns description.
- TestSurfaceIndex_WordingIsSingleNode: the surface declares
itself single-node and contains no cluster-shaped vocabulary.
- TestDiagnose_EmptyStateIsHonest: an empty-state /diagnose
returns zero/empty values, never fabricated fields.
- TestDiagnose_OnlyReadsLowerTruth: the /diagnose field set is
restricted to fields derivable from Snapshot(); any future
addition that isn't sourced from lower truth trips this test.
- TestSurfaceMutations_IncludesRootAndDiagnose: every mutation
verb on / and /diagnose returns 501.
New docs/single-node-surface.md names what the surface owns, what
it does not, and the explicit carry-forward: replicated status to
P12, topology/failover control to P14, operator governance surface
to P15.
README gets a "Single-node product surface" section linking to
the new doc. docs/bootstrap-validation.md updated to reference
/ and /diagnose, and to drop the "Phase 05" label — the doc is
now positioned as the CLI/endpoint reference, with the
product-shape view living in single-node-surface.md.
Also rolls in a small docs/recovery-execution-institution.md note
clarifying that the adapter watchdog's engine-state pre-check is
advisory; the engine phase guards remain the authoritative last
gate. This keeps a dual-layer guard visible to future maintainers
so they don't collapse the two into one convenience check.
* adapter: bounded replicated durable slice — handoff mechanism + fencing proof
Proves the first product capability beyond single-node operation:
given an external reassignment (epoch+1), the engine clears any
in-flight session, invalidates stale lineage, re-probes the
replica, decides catch-up or rebuild, and converges — while the
old primary's stale execution is rejected at every layer by the
lineage gate.
No new engine or transport mechanism was required. The lower
institutions (lineage gate, session lifecycle, data sync) compose
into a working handoff. P12's deliverable is the product-level
proof that this composition works.
Added adapter.OnRemoval(replicaID, reason) so the old primary's
demotion is expressible from outside the package.
Four multi-adapter handoff tests — two real adapters + two real
transport executors sharing one replica listener, no mocks:
TestHandoff_OldPrimaryToNewPrimary_Converges
A (epoch=1) reaches healthy; B (epoch=2) probes, recovers,
converges. Replica data matches B.
TestHandoff_StaleOldPrimaryTraffic_Rejected
After B's epoch=2 traffic establishes lineage on the replica,
stale epoch=1 frames are rejected at the data plane.
TestHandoff_RejoinAfterNewPrimary_DataConsistent
Every LBA the new primary wrote is byte-identical on the
replica after handoff.
TestHandoff_OldPrimaryDemoted_NoResurrection
After ReplicaRemoved, late callbacks from the old executor
cannot resurrect a healthy projection.
Durability claim (explicitly bounded): all writes the new primary
successfully barrier-ack'd are durable on the replica. Writes
in-flight on the old primary at reassignment that weren't ack'd
may be lost. The new primary's truth is authoritative.
Known limitation documented: if the new primary finds the replica
already caught up (R >= H), no mutating traffic establishes the
new epoch on the replica. Stale old-epoch traffic with a higher
sessionID could land. Low practical risk; deferred to P14 as a
proactive-fence concern.
docs/replicated-slice.md names what P12 proves (one bounded
failover/rejoin mechanism), what it doesn't (who decides primary,
when to fail over), and the carry-forward to P13/P14/P15.
* P8-P12: reconcile working tree with accepted phase closures
Reconciles the working tree so all accepted P10, P11, and P12
closures are present and consistent — no regressions, no stubs,
no doc/code mismatches.
P10 watchdog observability restored:
- armStartWatchdog/clearStartWatchdog record structured events
(arm, clear_started, clear_closed, supersede, fire, fire_noop)
into the adapter's watchdogLog field
- WatchdogLog() returns real data, not a nil stub
- clearStartWatchdog takes a WatchdogKind reason parameter so
clear-by-start is distinguishable from clear-by-close
- watchdog_test.go assertions are full strength — no skip-if-nil
guards
P10 engine trace detail restored:
- phaseMismatchDetail() helper distinguishes older-session,
newer-session, and no-active-session cases
- all session lifecycle handlers use enriched traces:
"current phase=failed" instead of "not in active phase"
- four terminal-lifecycle proof tests restored:
DelayedFailureAfterCompletion, DuplicateCompleted,
DuplicateFailed, InvalidPhaseTransitionsLeaveStateUnchanged
P11 single-node product surface restored:
- GET / (self-describing surface map) and GET /diagnose (bounded
summary) re-added to handlers.go and server.go
- surface_test.go recreated with all five honesty proofs
- server_test.go mux and mutation paths include / and /diagnose
- README endpoint list names all six read-only endpoints
- README "Single-node product surface" and "Replicated durable
slice" sections restored with doc links
- bootstrap-validation.md endpoint table and example curl block
include / and /diagnose; header repositioned as CLI/endpoint
reference with link to single-node-surface.md
P12 fixes preserved:
- replicated-slice.md route statement narrowed to distinguish
recovery-needed handoff (fenced) from R>=H (NOT fenced)
- TestHandoff_OldPrimaryDemoted_NoResurrection strengthened:
uses SetStepDelay to keep session active during removal, then
injects late OnSessionStart + OnSessionClose(success) — both
rejected
- "stops receiving assignments" wording corrected to "receives
explicit ReplicaRemoved"
- adapter.OnRemoval() public API added
- transport.BlockExecutor.SetStepDelay() exposed for test control
## What this adds
`docs/surface.md` is a taxonomy reference for the semantic core. It
names every event, command, truth domain, and operator enum the
engine currently exposes, so reviewers and contributors can see the
full surface without re-reading the code.
## Counts (verified against current sources)
| Dimension | Count |
|---|---|
| Events | 12 |
| Commands | 6 |
| Truth domains | 5 |
| Operator `Mode` | 4 |
| `RecoveryDecision` | 4 |
| `SessionKind` | 3 |
| `SessionPhase` | 5 |
| `ProbeStatus` | 4 |
| `ContactKind` | 5 |
## Why no single state diagram
The doc explicitly argues against drawing a unified diagram and
names what replaces it:
- the reducer itself as the transition specification
- invariants (C8 / C9 / C10 / C12 + the same-observation batch rule)
- conformance YAML cases
- per-run trace output
Plus a list of per-dimension sub-diagrams that DO fit on one page
for local review.
## Linked from README
Single line under "Repo Layout" pointing to the new doc.
## The bug
`doRebuild` returned `AchievedLSN = targetLSN` immediately after
writing `MsgRebuildDone`, then closed the connection. The replica's
handler runs on a separate goroutine and might not have processed
the rebuild blocks yet when `OnSessionClose` fires — tests that
read replica state after close saw unapplied blocks.
`TestTransport_Rebuild_DoesNotCorruptLBA0` flaked at ~40% locally.
## The fix
Structural, not a sleep. The replica's `MsgRebuildDone` handler
now replies with `MsgBarrierResp` carrying the actual synced
frontier, sent **after** `Sync()` returns. The primary's
`doRebuild` reads that ack before returning, mirroring the
existing `doCatchUp` barrier contract.
The `time.Sleep(50ms)` previously needed in
`TestTransport_Rebuild_StreamsAndAdvancesFrontier` is no longer
required and has been removed — the structural ack guarantees
durability when `closeCh` fires.
`AchievedLSN` reported to `OnSessionClose` is now the replica's
real frontier rather than the primary's intent — a more truthful
durability boundary.
## Verification
- `TestTransport_Rebuild_DoesNotCorruptLBA0` 5/5 runs pass
(was ~3/5 before)
- Full transport suite green under `-count=5`
- Full repo suite green
Adds a single-node persistence layer behind a `LogicalStorage` seam
that admits multiple implementations. The semantic engine, adapter,
and calibration are unchanged — storage is execution machinery, not
authority.
## Interface
`core/storage/logical_storage.go` defines `LogicalStorage`. Both
`BlockStore` (in-memory, existing) and the new `WALStore` satisfy
it (compile-time assertions). Methods cover Write/Read/Sync/Recover,
Boundaries (R/S/H), frontier control (AdvanceFrontier /
AdvanceWALTail / ApplyEntry / AllBlocks), and lifecycle (Close).
## WALStore — default crash-safe backend
`core/storage/walstore.go` plus supporting files
(`wal_entry.go`, `wal_writer.go`, `superblock.go`, `dirty_map.go`,
`recovery.go`, `group_commit.go`).
- Single preallocated file: superblock + circular WAL + extent
- Per-record CRC32 + EntrySize trailer detects torn writes
- Group committer batches concurrent Sync callers into one fsync
- Defensive past-head scan on Recover picks up writes that landed
after the last superblock update
- Idempotent recovery
## smartwal subpackage — experimental alternative
`core/storage/smartwal/` (record / ring / superblock / store /
recovery / tests / README).
- 32-byte metadata records in a slot-based ring
- Data goes directly to extent; reads always hit extent (no dirty
map needed for the read path)
- Last-writer-wins per LBA on recovery; CRC verified against
extent block
- Distinct magic byte from WALStore so files cannot be confused
- Subpackage layout signals opt-in / experimental status; default
remains WALStore
## Crash consistency for acked writes
`TestWALStore_AckedWritesSurviveSimulatedCrash` and
`TestSmartWAL_AckedWritesSurviveSimulatedCrash` both bypass `Close()`
by dropping the file handle directly — no implicit fsync, no
housekeeping. After reopen + Recover, every block whose Write was
followed by a successful Sync is recoverable; pre-Sync writes may
or may not be present but never corrupt acked data.
## sparrow `--persist-demo`
Reproducible single-node demo: Write 4 blocks, Sync, Close, reopen,
Recover, Read back. Removes prior demo file in the target dir
before Round 1 so repeated invocations / CI runs work cleanly. Text
and `--json` output. Exit codes documented in
`docs/bootstrap-validation.md`.
## Contract test infrastructure
`core/storage/contract_test.go` runs 11 contract assertions against
each registered implementation via a factory table. Adding a third
implementation is one entry in the table.
## Documentation
`docs/persistence.md` describes the WAL+extent design, crash-
consistency guarantees, what's NOT covered, file layout, on-disk
record format, and the **Execution-layer scope decision**:
`LogicalStorage` is the accepted persistence seam;
`DataCommunicator` / `RecoveryExecutor` / `ProgressFeed` are
deliberately deferred peer institutions. **Backing-store options**
section documents the path to raw block device, O_DIRECT, FUA, and
SPDK with concrete perf budgets — all preserve the seam.
## Required adjustments to existing code
`BlockStore.Sync` changed from `() uint64` to `() (uint64, error)` so
in-memory and on-disk implementations share one signature. Callers
that ignored the return updated to discard explicitly. Replica
barrier handler now propagates real fsync errors.
## Tests
| Package | Count |
|---|---|
| `core/storage` | 26 (11 contract × 2 backends + 4 WALStore-specific) |
| `core/storage/smartwal` | 16 (11 contract + 5 SmartWAL-specific) |
| `cmd/sparrow` | 14 (added repeatability check for the demo) |
Full repo green except a pre-existing flake on
`TestTransport_Rebuild_DoesNotCorruptLBA0` (unrelated; addressed on
a separate branch).
Adds the first calibration pass: five scenario families (C1-C5)
that drive the accepted route and record expected-versus-observed
evidence as machine-readable artifacts.
## Scenarios
| ID | Family | What it proves |
|---|---|---|
| `CAL-C1-healthy-repeat` | C1 | Repeated probes on a caught-up replica do not trigger spurious recovery |
| `CAL-C2-short-gap-catchup` | C2 | Short retained gap chooses catch-up; closes to healthy; data integrity preserved |
| `CAL-C3-long-gap-rebuild` | C3 | Long gap beyond retained window chooses rebuild; closes to healthy; data integrity preserved |
| `CAL-C4-terminal-close-only` | C4 | Healthy publication appears in the trace ONLY after `event: SessionClosedCompleted` (ordered check, not presence-only) |
| `CAL-C5-order-stable` | C5 | Five same-replica delivery perturbations produce identical Decision, FinalMode, recoverySignature, and CloseEventCount |
## What changed
- `core/calibration/` — new package
- `result.go`, `harness.go`, `scenarios.go`, `report.go`, `scenarios_test.go`
- `cmd/sparrow/calibrate.go` — wires `--calibrate` and `--calibrate --json`
- `docs/calibration/scenario-map.md` and `divergence-log.md` — evidence templates seeded with the first-pass results
- `README.md` and `docs/bootstrap-validation.md` — `--calibrate` advertised
## Evidence dimensions C5 compares across runs
1. `Decision` (derived from command path)
2. `FinalMode`
3. `recoverySignature` = (NCatchUp count, NRebuild count)
4. `CloseEventCount` (count of `SessionClosedCompleted` events in trace)
5. `DataIntegrityOK`
Each has a distinct sentinel in the JSON artifact when it drifts.
## Tests
- 14 calibration tests (5 per-scenario + 8 compare + 1 meta-test for the recovery-signature check)
- Stable under `-count=10` stress
- Full repo green
Extends the accepted sparrow (Phase 04) with narrow dev/test flags
and a read-only HTTP inspection surface so outside readers and
testers can start, inspect, and validate the runnable slice without
deep design-doc archaeology.
No new standalone operator CLI — `weed shell` remains the eventual
production interface; this work is a standalone-repo sparrow
improvement, not a competing CLI.
## What changed
- `cmd/sparrow/main.go` — flag handling; `startHTTPOps` binds
synchronously and surfaces errors honestly
- `cmd/sparrow/scope.go` — authoritative `ScopeStatement` + `Version`
- `core/ops/` — new package: `state.go`, `server.go`, `handlers.go`
- `docs/bootstrap-validation.md` — operator-facing surface reference
- `README.md` — Operations section
## Sparrow flags (all opt-in, default unchanged)
| Flag | Effect |
|---|---|
| `--json` | machine-readable JSON summary |
| `--runs N` | repeat the full demo N times |
| `--http ADDR` | read-only HTTP ops server, stays up after demos |
| `--help` | authoritative supported/unsupported scope |
| `--version` | version string |
## Exit codes
| Code | Meaning |
|---|---|
| 0 | all-pass |
| 1 | any fail (validation use) |
| 2 | usage / flag error |
| 3 | runtime setup failure (currently: `--http` bind failed) |
## HTTP ops surface (behind `--http`)
| Method | Path | Returns |
|---|---|---|
| GET | `/status` | version, uptime, scope, current demo |
| GET | `/projection` | latest `ReplicaProjection` as JSON |
| GET | `/trace` | latest adapter trace as JSON array |
| POST/PUT/PATCH/DELETE | any path | 501 + structured "not supported" body |
## Anti-pattern guards held
- ops package never calls `engine.Apply` directly
- ops reads state only through `adapter.Projection()` / `.Trace()`
- no ops handler chooses recovery semantics or redefines `targetLSN`
- `ScopeStatement` shown by `--help` and `/status` is the same constant
- no new standalone operator CLI binary
## Honest bind
`startHTTPOps` calls `net.Listen` synchronously and returns an error
if the port cannot be bound. `--http` never falsely claims
"listening" when it is not. The bound address shown to the user is
the actual listener address (useful for `--http :0` random-port).
## Tests
| Package | Count |
|---|---|
| `cmd/sparrow` | 12 (flag parsing, scope content, repeatable runs, HTTP bind happy path, HTTP bind port-conflict failure, end-to-end exit-code 3 on bind failure) |
| `core/ops` | 26 (handlers, 501 on every verb × path, state) |
Pre-existing flake `TestTransport_Rebuild_DoesNotCorruptLBA0` is
unrelated; `fix/rebuild-race` branch addresses it separately.
OnProbeResult routes ProbeSucceeded + RecoveryFactsObserved
from the same probe through applyBatchAndExecute, so both
enter the engine under one lock hold — no unrelated event
can interleave between them.
Shared bookkeeping lives in applyEventLocked; both the batch
and single-event paths go through it, so the trace /
projection / command accumulators can't drift again. ApplyLog
returned from OnProbeResult is now complete (EventKind, full
Trace including session events, post-session Projection).
An ingress rule is pinned in code: multi-fact observations
MUST route through applyBatchAndExecute, and any new
multi-fact ingress needs its own contention test.
Tests:
- TestBatch_UsesBatchPath: EventKind prefix, both event markers
in Trace, Projection reflects post-apply state
- TestBatch_LogIncludesSessionEvents: SessionPrepared/Started
markers present in returned log.Trace
- TestBatch_AtomicUnderContention: 4 goroutines fire competing
events while main fires 2000 probes; scans trace event
markers to prove ProbeSucceeded is always immediately
followed by RecoveryFactsObserved. Vacuity guard requires
real contention.
SeaweedFS is an independent Apache-licensed open source project with its ongoing development made
possible entirely thanks to the support of these awesome [backers](https://github.com/chrislusf/seaweedfs/blob/master/backers.md).
If you'd like to grow SeaweedFS even stronger, please consider joining our
<a href="https://www.patreon.com/seaweedfs">sponsors on Patreon</a>.
Your support will be really appreciated by me and other supporters!
<h3 align="center"><a href="https://www.patreon.com/seaweedfs">Sponsor SeaweedFS via Patreon</a></h3>
<!--
<h4 align="center">Platinum</h4>
<p align="center">
<a href="" target="_blank">
Add your name or icon here
</a>
</p>
<h4 align="center">Gold</h4>
<table>
<tbody>
<tr>
<td align="center" valign="middle">
<a href="" target="_blank">
Add your name or icon here
</a>
</td>
</tr>
<tr></tr>
</tbody>
</table>
-->
---
- [Download Binaries for different platforms](https://github.com/chrislusf/seaweedfs/releases/latest)
- [SeaweedFS on Slack](https://join.slack.com/t/seaweedfs/shared_invite/enQtMzI4MTMwMjU2MzA3LTEyYzZmZWYzOGQ3MDJlZWMzYmI0OTE4OTJiZjJjODBmMzUxNmYwODg0YjY3MTNlMjBmZDQ1NzQ5NDJhZWI2ZmY)
- [SeaweedFS on Twitter](https://twitter.com/SeaweedFS)
* [Example: Using Seaweed Object Store](#example-Using-Seaweed-Object-Store)
* [Architecture](#architecture)
* [Compared to Other File Systems](#compared-to-other-file-systems)
* [Compared to HDFS](#compared-to-hdfs)
* [Compared to GlusterFS, Ceph](#compared-to-glusterfs-ceph)
* [Compared to GlusterFS](#compared-to-glusterfs)
* [Compared to Ceph](#compared-to-ceph)
* [Dev Plan](#dev-plan)
* [Installation Guide](#installation-guide)
* [Disk Related Topics](#disk-related-topics)
* [Benchmark](#Benchmark)
* [License](#license)
## Quick Start ##
* Download the latest binary from https://github.com/chrislusf/seaweedfs/releases and unzip a single binary file `weed` or `weed.exe`
* Run `weed server -dir=/some/data/dir -s3` to start one master, one volume server, one filer, and one S3 gateway.
Also, to increase capacity, just add more volume servers by `weed volume -dir="/some/data/dir2" -mserver="<master_host>:9333" -port=8081` locally or a different machine. That is it!
## Introduction ##
SeaweedFS is a simple and highly scalable distributed file system. There are two objectives:
1. to store billions of files!
2. to serve the files fast!
SeaweedFS started as an Object Store to handle small files efficiently. Instead of managing all file metadata in a central master, the central master only manages file volumes, and it lets these volume servers manage files and their metadata. This relieves concurrency pressure from the central master and spreads file metadata into volume servers, allowing faster file access (O(1), usually just one disk read operation).
SeaweedFS can transparently integrate with the cloud. With hot data on local cluster, and warm data on the cloud with O(1) access time, SeaweedFS can achieve both fast local access time and elastic cloud storage capacity, without any client side changes.
There is only 40 bytes of disk storage overhead for each file's metadata. It is so simple with O(1) disk reads that you are welcome to challenge the performance with your actual use cases.
SeaweedFS started by implementing [Facebook's Haystack design paper](http://www.usenix.org/event/osdi10/tech/full_papers/Beaver.pdf). Also, SeaweedFS implements erasure coding with ideas from [f4: Facebook’s Warm BLOB Storage System](https://www.usenix.org/system/files/conference/osdi14/osdi14-paper-muralidhar.pdf)
On top of the object store, optional [Filer] can support directories and POSIX attributes. Filer is a separate linearly-scalable stateless server with customizable metadata stores, e.g., MySql, Postgres, Mongodb, Redis, Cassandra, Elastic Search, LevelDB, MemSql, TiDB, Etcd, CockroachDB, etc.
[Back to TOC](#table-of-contents)
## Additional Features ##
* Can choose no replication or different replication levels, rack and data center aware.
* Automatic master servers failover - no single point of failure (SPOF).
* Automatic Gzip compression depending on file mime type.
* Automatic compaction to reclaim disk space after deletion or update.
By default, the master node runs on port 9333, and the volume nodes run on port 8080.
Let's start one master node, and two volume nodes on port 8080 and 8081. Ideally, they should be started from different machines. We'll use localhost as an example.
SeaweedFS uses HTTP REST operations to read, write, and delete. The responses are in JSON or JSONP format.
Now, you can save the `fid`, 3,01637037d6 in this case, to a database field.
The number 3 at the start represents a volume id. After the comma, it's one file key, 01, and a file cookie, 637037d6.
The volume id is an unsigned 32-bit integer. The file key is an unsigned 64-bit integer. The file cookie is an unsigned 32-bit integer, used to prevent URL guessing.
The file key and file cookie are both coded in hex. You can store the <volume id, file key, file cookie> tuple in your own format, or simply store the `fid` as a string.
If stored as a string, in theory, you would need 8+1+16+8=33 bytes. A char(33) would be enough, if not more than enough, since most uses will not need 2^32 volumes.
If space is really a concern, you can store the file id in your own format. You would need one 4-byte integer for volume id, 8-byte long number for file key, and a 4-byte integer for the file cookie. So 16 bytes are more than enough.
### Read File ###
Here is an example of how to render the URL.
First look up the volume server's URLs by the file's volumeId:
Since (usually) there are not too many volume servers, and volumes don't move often, you can cache the results most of the time. Depending on the replication type, one volume can have multiple replica locations. Just randomly pick one location to read.
Now you can take the public url, render the url or directly read from the volume server via url:
```
http://localhost:8080/3,01637037d6.jpg
```
Notice we add a file extension ".jpg" here. It's optional and just one way for the client to specify the file content type.
If you want a nicer URL, you can use one of these alternative URL formats:
### Rack-Aware and Data Center-Aware Replication ###
SeaweedFS applies the replication strategy at a volume level. So, when you are getting a file id, you can specify the replication strategy. For example:
When requesting a file key, an optional "dataCenter" parameter can limit the assigned volume to the specific data center. For example, this specifies that the assigned volume should be limited to 'dc1':
Usually distributed file systems split each file into chunks, a central master keeps a mapping of filenames, chunk indices to chunk handles, and also which chunks each chunk server has.
The main drawback is that the central master can't handle many small files efficiently, and since all read requests need to go through the chunk master, so it might not scale well for many concurrent users.
Instead of managing chunks, SeaweedFS manages data volumes in the master server. Each data volume is 32GB in size, and can hold a lot of files. And each storage node can have many data volumes. So the master node only needs to store the metadata about the volumes, which is a fairly small amount of data and is generally stable.
The actual file metadata is stored in each volume on volume servers. Since each volume server only manages metadata of files on its own disk, with only 16 bytes for each file, all file access can read file metadata just from memory and only needs one disk operation to actually read file data.
For comparison, consider that an xfs inode structure in Linux is 536 bytes.
### Master Server and Volume Server ###
The architecture is fairly simple. The actual data is stored in volumes on storage nodes. One volume server can have multiple volumes, and can both support read and write access with basic authentication.
All volumes are managed by a master server. The master server contains the volume id to volume server mapping. This is fairly static information, and can be easily cached.
On each write request, the master server also generates a file key, which is a growing 64-bit unsigned integer. Since write requests are not generally as frequent as read requests, one master server should be able to handle the concurrency well.
### Write and Read files ###
When a client sends a write request, the master server returns (volume id, file key, file cookie, volume node url) for the file. The client then contacts the volume node and POSTs the file content.
When a client needs to read a file based on (volume id, file key, file cookie), it asks the master server by the volume id for the (volume node url, volume node public url), or retrieves this from a cache. Then the client can GET the content, or just render the URL on web pages and let browsers fetch the content.
Please see the example for details on the write-read process.
### Storage Size ###
In the current implementation, each volume can hold 32 gibibytes (32GiB or 8x2^32 bytes). This is because we align content to 8 bytes. We can easily increase this to 64GiB, or 128GiB, or more, by changing 2 lines of code, at the cost of some wasted padding space due to alignment.
There can be 4 gibibytes (4GiB or 2^32 bytes) of volumes. So the total system size is 8 x 4GiB x 4GiB which is 128 exbibytes (128EiB or 2^67 bytes).
Each individual file size is limited to the volume size.
### Saving memory ###
All file meta information stored on an volume server is readable from memory without disk access. Each file takes just a 16-byte map entry of <64bit key, 32bit offset, 32bit size>. Of course, each map entry has its own space cost for the map. But usually the disk space runs out before the memory does.
### Tiered Storage to the cloud ###
The local volume servers are much faster, while cloud storages have elastic capacity and are actually more cost-efficient if not accessed often (usually free to upload, but relatively costly to access). With the append-only structure and O(1) access time, SeaweedFS can take advantage of both local and cloud storage by offloading the warm data to the cloud.
Usually hot data are fresh and warm data are old. SeaweedFS puts the newly created volumes on local servers, and optionally upload the older volumes on the cloud. If the older data are accessed less often, this literally gives you unlimited capacity with limited local servers, and still fast for new data.
With the O(1) access time, the network latency cost is kept at minimum.
If the hot~warm data is split as 20~80, with 20 servers, you can achieve storage capacity of 100 servers. That's a cost saving of 80%! Or you can repurpose the 80 servers to store new data also, and get 5X storage throughput.
[Back to TOC](#table-of-contents)
## Compared to Other File Systems ##
Most other distributed file systems seem more complicated than necessary.
SeaweedFS is meant to be fast and simple, in both setup and operation. If you do not understand how it works when you reach here, we've failed! Please raise an issue with any questions or update this file with clarifications.
SeaweedFS is constantly moving forward. Same with other systems. These comparisons can be outdated quickly. Please help to keep them updated.
[Back to TOC](#table-of-contents)
### Compared to HDFS ###
HDFS uses the chunk approach for each file, and is ideal for storing large files.
SeaweedFS is ideal for serving relatively smaller files quickly and concurrently.
SeaweedFS can also store extra large files by splitting them into manageable data chunks, and store the file ids of the data chunks into a meta chunk. This is managed by "weed upload/download" tool, and the weed master or volume servers are agnostic about it.
[Back to TOC](#table-of-contents)
### Compared to GlusterFS, Ceph ###
The architectures are mostly the same. SeaweedFS aims to store and read files fast, with a simple and flat architecture. The main differences are
* SeaweedFS optimizes for small files, ensuring O(1) disk seek operation, and can also handle large files.
* SeaweedFS statically assigns a volume id for a file. Locating file content becomes just a lookup of the volume id, which can be easily cached.
* SeaweedFS Filer metadata store can be any well-known and proven data stores, e.g., Cassandra, Mongodb, Redis, Elastic Search, MySql, Postgres, MemSql, TiDB, CockroachDB, Etcd etc, and is easy to customized.
* SeaweedFS Volume server also communicates directly with clients via HTTP, supporting range queries, direct uploads, etc.
| System | File Metadata | File Content Read| POSIX | REST API | Optimized for large number of small files |
| MinIO | separate meta file for each file | | | Yes | No |
[Back to TOC](#table-of-contents)
### Compared to GlusterFS ###
GlusterFS stores files, both directories and content, in configurable volumes called "bricks".
GlusterFS hashes the path and filename into ids, and assigned to virtual volumes, and then mapped to "bricks".
[Back to TOC](#table-of-contents)
### Compared to MooseFS ###
MooseFS chooses to neglect small file issue. From moosefs 3.0 manual, "even a small file will occupy 64KiB plus additionally 4KiB of checksums and 1KiB for the header", because it "was initially designed for keeping large amounts (like several thousands) of very big files"
MooseFS Master Server keeps all meta data in memory. Same issue as HDFS namenode.
[Back to TOC](#table-of-contents)
### Compared to Ceph ###
Ceph can be setup similar to SeaweedFS as a key->blob store. It is much more complicated, with the need to support layers on top of it. [Here is a more detailed comparison](https://github.com/chrislusf/seaweedfs/issues/120)
SeaweedFS has a centralized master group to look up free volumes, while Ceph uses hashing and metadata servers to locate its objects. Having a centralized master makes it easy to code and manage.
Same as SeaweedFS, Ceph is also based on the object store RADOS. Ceph is rather complicated with mixed reviews.
Ceph uses CRUSH hashing to automatically manage the data placement. SeaweedFS places data by assigned volumes.
SeaweedFS is optimized for small files. Small files are stored as one continuous block of content, with at most 8 unused bytes between files. Small file access is O(1) disk read.
SeaweedFS Filer uses off-the-shelf stores, such as MySql, Postgres, Mongodb, Redis, Elastic Search, Cassandra, MemSql, TiDB, CockroachCB, Etcd, to manage file directories. These stores are proven, scalable, and easier to manage.
MinIO follows AWS S3 closely and is ideal for testing for S3 API. It has good UI, policies, versionings, etc. SeaweedFS is trying to catch up here. It is also possible to put MinIO as a gateway in front of SeaweedFS later.
MinIO metadata are in simple files. Each file write will incur extra writes to corresponding meta file.
MinIO does not have optimization for lots of small files. The files are simply stored as is to local disks.
Plus the extra meta file and shards for erasure coding, it only amplifies the LOSF problem.
MinIO has multiple disk IO to read one file. SeaweedFS has O(1) disk reads, even for erasure coded files.
MinIO has full-time erasure coding. SeaweedFS uses replication on hot data for faster speed and optionally applies erasure coding on warm data.
MinIO does not have POSIX-like API support.
MinIO has specific requirements on storage layout. It is not flexible to adjust capacity. In SeaweedFS, just start one volume server pointing to the master. That's all.
## Dev Plan ##
* More tools and documentation, on how to manage and scale the system. For example, how to move volumes, automatically balancing data, how to grow volumes, how to check system status, etc.
* Integrate with Kubernetes. build [SeaweedFS Operator](https://github.com/seaweedfs/seaweedfs-operator).
* Add ftp server.
* Read and write stream data.
* Support structured data.
This is a super exciting project! And we need helpers and [support](https://www.patreon.com/seaweedfs)!
[Back to TOC](#table-of-contents)
## Installation Guide ##
> Installation guide for users who are not familiar with golang
Step 1: install go on your machine and setup the environment by following the instructions at:
Step 3: download, compile, and install the project by executing the following command
```bash
make install
```
Once this is done, you will find the executable "weed" in your `$GOPATH/bin` directory
[Back to TOC](#table-of-contents)
## Disk Related Topics ##
### Hard Drive Performance ###
When testing read performance on SeaweedFS, it basically becomes a performance test of your hard drive's random read speed. Hard drives usually get 100MB/s~200MB/s.
### Solid State Disk ###
To modify or delete small files, SSD must delete a whole block at a time, and move content in existing blocks to a new block. SSD is fast when brand new, but will get fragmented over time and you have to garbage collect, compacting blocks. SeaweedFS is friendly to SSD since it is append-only. Deletion and compaction are done on volume level in the background, not slowing reading and not causing fragmentation.
[Back to TOC](#table-of-contents)
## Benchmark ##
My Own Unscientific Single Machine Results on Mac Book with Solid State Disk, CPU: 1 Intel Core i7 2.6GHz.
Write 1 million 1KB file:
```
Concurrency Level: 16
Time taken for tests: 66.753 seconds
Complete requests: 1048576
Failed requests: 0
Total transferred: 1106789009 bytes
Requests per second: 15708.23 [#/sec]
Transfer rate: 16191.69 [Kbytes/sec]
Connection Times (ms)
min avg max std
Total: 0.3 1.0 84.3 0.9
Percentage of the requests served within a certain time (ms)
50% 0.8 ms
66% 1.0 ms
75% 1.1 ms
80% 1.2 ms
90% 1.4 ms
95% 1.7 ms
98% 2.1 ms
99% 2.6 ms
100% 84.3 ms
```
Randomly read 1 million files:
```
Concurrency Level: 16
Time taken for tests: 22.301 seconds
Complete requests: 1048576
Failed requests: 0
Total transferred: 1106812873 bytes
Requests per second: 47019.38 [#/sec]
Transfer rate: 48467.57 [Kbytes/sec]
Connection Times (ms)
min avg max std
Total: 0.0 0.3 54.1 0.2
Percentage of the requests served within a certain time (ms)
50% 0.3 ms
90% 0.4 ms
98% 0.6 ms
99% 0.7 ms
100% 54.1 ms
```
[Back to TOC](#table-of-contents)
## License ##
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The text of this page is available for modification and reuse under the terms of the Creative Commons Attribution-Sharealike 3.0 Unported License and the GNU Free Documentation License (unversioned, with no invariant sections, front-cover texts, or back-cover texts).
[Back to TOC](#table-of-contents)
## Stargazers over time ##
[](https://starcharts.herokuapp.com/chrislusf/seaweedfs)
SUPERCRONIC_SHA1SUM=$(echo$ARCH| sed 's/386/e0126b0102b9f388ecd55714358e3ad60d0cebdb/g'| sed 's/amd64/5ddf8ea26b56d4a7ff6faecdd8966610d5cb9d85/g'| sed 's/arm64/e2714c43e7781bf1579c85aa61259245f56dbba1/g'| sed 's/arm/47481c3341bc3a1ae91a728e0cc63c8e6d3791ad/g')&&\
System.out.println("moved "+event.getDirectory()+"/"+notification.getOldEntry().getName()+" to "+notification.getNewParentPath()+"/"+notification.getNewEntry().getName());
Loaded 100 of 3817 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.