Files
seaweedfs/seaweed-block/cmd/sparrow/s5_bootstrap.go
T
wzcheng99andClaude Opus 4.7 47eb1f6f8d P14 S5: durable authority institution + live sparrow bootstrap
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>
2026-04-19 18:48:25 -07:00

84 lines
2.6 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
)
// runS5Bootstrap is the live, non-test entrypoint exercising the
// P14 S5 durable authority bootstrap path. This is the minimum
// real call site that satisfies architect round-5:
//
// 1. AcquireStoreLock — single-owner OS lock on the store dir
// 2. NewFileAuthorityStore — open file-per-volume backend
// 3. NewPublisher(..., WithStore(store)) — reload synchronously
// 4. log LoadErrors() at startup so reload-corruption is visible
//
// The mode is intentionally narrow: it proves the durable route
// is wired end-to-end under a real flag, and produces machine-
// readable output so CI (or a real operator) can verify the
// reload count and skip list.
//
// Without --authority-store, sparrow continues to run in-memory
// (existing behavior preserved). With --authority-store AND
// --s5-bootstrap, sparrow performs the durable bootstrap and
// exits 0 on success. Running twice in a row against the same
// store directory exercises the reload path.
func runS5Bootstrap(opts options) int {
if opts.authorityStore == "" {
fmt.Fprintln(os.Stderr, "sparrow: --s5-bootstrap requires --authority-store <dir>")
return 2
}
directive := authority.NewStaticDirective(nil)
boot, err := Bootstrap(opts.authorityStore, directive)
if err != nil {
fmt.Fprintln(os.Stderr, "sparrow:", err)
return 1
}
defer func() {
if cerr := boot.Close(); cerr != nil {
log.Printf("sparrow: close durable bootstrap: %v", cerr)
}
}()
// Let the Publisher's Run goroutine start so the bootstrapped
// state is observably "live" — not just constructed. A short
// context cancel returns promptly; the bootstrap's own logs
// already recorded the reload outcome.
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
go func() { _ = boot.Publisher.Run(ctx) }()
<-ctx.Done()
if opts.json {
report := map[string]any{
"store": opts.authorityStore,
"reloaded_records": boot.ReloadedRecords,
"reload_skip_count": len(boot.ReloadSkips),
"reload_skip_reasons": summarizeSkips(boot.ReloadSkips),
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(report)
} else {
fmt.Printf("sparrow s5-bootstrap: store=%q reloaded=%d skips=%d\n",
opts.authorityStore, boot.ReloadedRecords, len(boot.ReloadSkips))
}
return 0
}
func summarizeSkips(skips []error) []string {
out := make([]string, 0, len(skips))
for _, e := range skips {
out = append(out, e.Error())
}
return out
}