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>