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>
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>