calibration: first scenario pass (C1-C5)

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
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-04-14 12:13:27 -07:00
1 parent bdc4845014
commit aff28bc936
12 files changed
+1636 -5

No files matched your search

+21
View File
@@ -151,6 +151,8 @@ go run ./cmd/sparrow --help # authoritative scope statement
go run ./cmd/sparrow --json # machine-readable output for CI
go run ./cmd/sparrow --runs 10 # repeat the full demo N times
go run ./cmd/sparrow --http :9090 # add read-only HTTP inspection
go run ./cmd/sparrow --calibrate # Phase 06 calibration pass (C1-C5)
go run ./cmd/sparrow --calibrate --json # machine-readable calibration Report
```
HTTP endpoints (read-only): `/status`, `/projection`, `/trace`. Every
@@ -161,6 +163,25 @@ for the complete list of supported flags, endpoints, and exit codes.
This binary is a development and validation entry point only. The
production operations surface is `weed shell` after integration.
## Calibration
Phase 06 adds a small calibration set that drives the accepted route
through five scenario families (C1-C5) and records expected-versus-
observed evidence. Run it with:
```bash
go run ./cmd/sparrow --calibrate # text report
go run ./cmd/sparrow --calibrate --json # machine-readable Report
```
Evidence artifacts:
- [docs/calibration/scenario-map.md](docs/calibration/scenario-map.md)
- [docs/calibration/divergence-log.md](docs/calibration/divergence-log.md)
If a case diverges, record it in `divergence-log.md` before changing
the route or the expectations.
## Design Rules
The current implementation is intentionally shaped around a few strict rules:
+74
View File
@@ -0,0 +1,74 @@
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/seaweedfs/seaweed-block/core/calibration"
)
// runCalibration executes the Phase 06 first calibration pass and
// emits the Report. Text mode prints a per-scenario PASS/FAIL line
// plus the summary; --json emits the full machine-readable artifact
// suitable for piping into docs/calibration/ evidence review.
//
// Exit codes follow the sparrow contract:
// 0 all scenarios passed
// 1 one or more scenarios diverged or errored
//
// This is deliberately an addition to the sparrow binary rather than a
// new CLI — per v3-operations-design.md §1.3 and
// v3-phase-06-checklist.md §4 S1, Phase 06 reuses the accepted Phase 05
// bootstrap entry path.
func runCalibration(opts options) int {
report := calibration.Runner{}.Run(calibration.AllScenarios())
if opts.json {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(report)
} else {
fmt.Println("=== V3 Phase 06 Calibration ===")
fmt.Println()
for _, r := range report.Results {
status := "PASS"
if !r.Pass {
status = "FAIL"
}
fmt.Printf(" [%s] %-28s %s — %s\n", r.Family, r.ID, status, r.Intent)
if !r.Pass {
printDivergenceText(r)
}
}
fmt.Println()
fmt.Printf("=== Summary: %d/%d passed, %d diverged, %d errored ===\n",
report.Summary.Passed, report.Summary.Total,
report.Summary.Diverged, report.Summary.Errors)
if !report.Summary.AllPassed {
fmt.Println()
fmt.Println("Record each divergence in docs/calibration/divergence-log.md")
fmt.Println("before changing the route or the expectations.")
}
}
if report.Summary.AllPassed {
return 0
}
return 1
}
func printDivergenceText(r calibration.Result) {
if r.Error != "" {
fmt.Printf(" error: %s\n", r.Error)
return
}
fmt.Printf(" expected: decision=%s final_mode=%s includes=%v excludes=%v\n",
r.Expected.Decision, r.Expected.FinalMode,
r.Expected.CommandPathIncludes, r.Expected.CommandPathExcludes)
fmt.Printf(" observed: decision=%s final_mode=%s command_path=%v\n",
r.Observed.Decision, r.Observed.FinalMode, r.Observed.CommandPath)
if r.Divergence != nil {
fmt.Printf(" divergence: %+v\n", *r.Divergence)
}
}
+9 -3
View File
@@ -52,9 +52,10 @@ import (
// options captures parsed command-line flags.
type options struct {
json bool
runs int
httpAddr string
json bool
runs int
httpAddr string
calibrate bool
}
func main() {
@@ -79,6 +80,10 @@ func main() {
os.Exit(2)
}
if opts.calibrate {
os.Exit(runCalibration(opts))
}
code := runSparrow(opts)
os.Exit(code)
}
@@ -89,6 +94,7 @@ func parseFlags(args []string) (options, error) {
fs.BoolVar(&opts.json, "json", false, "emit machine-readable JSON")
fs.IntVar(&opts.runs, "runs", 1, "repeat the demo N times")
fs.StringVar(&opts.httpAddr, "http", "", "optional HTTP ops listen address (e.g. :9090)")
fs.BoolVar(&opts.calibrate, "calibrate", false, "run the Phase 06 calibration pass instead of the demo")
if err := fs.Parse(args); err != nil {
return opts, err
}
+3 -2
View File
@@ -4,15 +4,16 @@ package main
// statement. Shown by `sparrow --help` and echoed by the optional
// HTTP /status endpoint so no interface ever overclaims what the
// semantic core actually owns.
const ScopeStatement = `seaweed-block sparrow, Phase 05 runnable slice.
const ScopeStatement = `seaweed-block sparrow, runnable slice with Phase 05 ops and Phase 06 calibration.
Supported:
- run the three canonical demos (healthy, catch-up, rebuild)
- repeatable validation via --runs N
- machine-readable output via --json
- optional read-only HTTP inspection surface via --http ADDR
- Phase 06 calibration pass via --calibrate (C1 through C5)
Not supported (Phase 05 boundary; errors surface explicitly):
Not supported (errors surface explicitly):
- persistence or crash recovery (storage is in-memory)
- master service / dynamic assignment
- any mutation via the HTTP ops surface
+139
View File
@@ -0,0 +1,139 @@
package calibration
import (
"fmt"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/storage"
"github.com/seaweedfs/seaweed-block/core/transport"
)
// harness holds the shared scaffolding each scenario builds on top of:
// a primary store, a replica store, a replica listener, a block executor
// wired to the listener, and a V3 adapter wrapped around that executor.
//
// This is the SAME scaffolding the sparrow demo uses — scenarios do not
// short-circuit to the engine directly. That preserves the "accepted
// route" guarantee Phase 06 promises.
type harness struct {
primaryStore *storage.BlockStore
replicaStore *storage.BlockStore
listener *transport.ReplicaListener
executor *transport.BlockExecutor
adapter *adapter.VolumeReplicaAdapter
}
func newHarness() (*harness, error) {
primary := storage.NewBlockStore(256, 4096)
replica := storage.NewBlockStore(256, 4096)
ln, err := transport.NewReplicaListener("127.0.0.1:0", replica)
if err != nil {
return nil, fmt.Errorf("replica listener: %w", err)
}
ln.Serve()
exec := transport.NewBlockExecutor(primary, ln.Addr(), 1)
a := adapter.NewVolumeReplicaAdapter(exec)
return &harness{
primaryStore: primary,
replicaStore: replica,
listener: ln,
executor: exec,
adapter: a,
}, nil
}
// close tears down the transport. Safe to call in a defer.
func (h *harness) close() {
if h.listener != nil {
h.listener.Stop()
}
}
// writeBlocks writes N blocks to the primary with deterministic content
// (LBA i gets data[0]=byte(i+1)). Used by C2/C3/C5 setups.
func (h *harness) writeBlocks(n uint32) {
for i := uint32(0); i < n; i++ {
data := make([]byte, 4096)
data[0] = byte(i + 1)
h.primaryStore.Write(i, data)
}
h.primaryStore.Sync()
}
// mirrorToReplica copies the primary's current blocks into the replica
// and marks the replica's synced frontier at the primary's head. Used
// by C1 setup where the replica is already caught up.
func (h *harness) mirrorToReplica() {
blocks := h.primaryStore.AllBlocks()
_, _, pH := h.primaryStore.Boundaries()
for lba, data := range blocks {
_ = h.replicaStore.ApplyEntry(lba, data, pH)
}
h.replicaStore.Sync()
}
// advanceWALPastReplica moves the primary's WAL tail past the replica's
// frontier so the engine classifies the gap as long (R < S) and chooses
// rebuild. Used by C3 setup.
func (h *harness) advanceWALPastReplica() {
h.primaryStore.AdvanceWALTail(h.primaryStore.NextLSN())
}
// assign sends a fresh AssignmentInfo through the adapter. Triggers the
// auto-probe.
func (h *harness) assign(epoch, endpointVersion uint64) {
h.adapter.OnAssignment(adapter.AssignmentInfo{
VolumeID: "vol1", ReplicaID: "r1",
Epoch: epoch, EndpointVersion: endpointVersion,
DataAddr: h.listener.Addr(), CtrlAddr: h.listener.Addr(),
})
}
// waitForDecisionFinal polls the adapter's projection until:
// - mode becomes healthy (success path), OR
// - a timeout elapses (evidence of a stuck decision).
//
// Returns the final projection regardless of outcome so the caller
// can report observed state honestly even on timeout.
func (h *harness) waitForDecisionFinal(timeout time.Duration) engine.ReplicaProjection {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
p := h.adapter.Projection()
if p.Mode == engine.ModeHealthy {
return p
}
time.Sleep(20 * time.Millisecond)
}
return h.adapter.Projection()
}
// commandLog returns the adapter's accumulated command log as a slice of
// command-kind strings. This is the ground truth for command-path
// assertions — it contains what actually ran, not what we planned.
func (h *harness) commandLog() []string {
return h.adapter.CommandLog()
}
// dataMatches returns true iff every LBA that exists on the primary is
// byte-identical on the replica. Used for C2/C3 data-integrity evidence.
func (h *harness) dataMatches() bool {
primary := h.primaryStore.AllBlocks()
for lba, want := range primary {
got, err := h.replicaStore.Read(lba)
if err != nil {
return false
}
if len(got) != len(want) {
return false
}
for i := range want {
if got[i] != want[i] {
return false
}
}
}
return true
}
+40
View File
@@ -0,0 +1,40 @@
package calibration
// Report is the machine-readable artifact this package emits. It is the
// one canonical shape consumed by docs/calibration/ and by tester
// evidence review. Keeping the fields minimal and stable matters more
// than being rich — scenario-map.md and divergence-log.md both reference
// this shape.
type Report struct {
Summary Summary `json:"summary"`
Results []Result `json:"results"`
}
type Summary struct {
Total int `json:"total"`
Passed int `json:"passed"`
Failed int `json:"failed"`
Diverged int `json:"diverged"`
Errors int `json:"errors"`
AllPassed bool `json:"all_passed"`
}
func newReport(results []Result) Report {
s := Summary{}
for _, r := range results {
s.Total++
if r.Error != "" {
s.Errors++
}
if r.Pass {
s.Passed++
} else {
s.Failed++
if r.Divergence != nil && r.Error == "" {
s.Diverged++
}
}
}
s.AllPassed = s.Failed == 0
return Report{Summary: s, Results: results}
}
+126
View File
@@ -0,0 +1,126 @@
// Package calibration implements the Phase 06 calibration pass: a small
// set of scenarios (C1-C5) that drive the accepted V3 route and record
// expected versus observed outcomes. Evidence produced here feeds the
// docs/calibration/scenario-map.md and docs/calibration/divergence-log.md
// artifacts. The package MUST NOT redefine semantics; it only observes
// and compares.
//
// Inherited fixed boundaries (from v3-phase-06-checklist.md §1):
//
// - all scenarios run through the accepted adapter/transport/storage route
// - no scenario calls engine.Apply directly
// - no scenario rewrites frozen targetLSN
// - same-observation batch ingress at the adapter boundary is preserved
// - mismatches are recorded as divergences, never hidden by expectation tweaks
package calibration
// Family is the scenario family label, one of C1-C5.
type Family string
const (
FamilyC1 Family = "C1" // healthy remains healthy
FamilyC2 Family = "C2" // short gap -> catch_up
FamilyC3 Family = "C3" // long gap -> rebuild
FamilyC4 Family = "C4" // terminal truth only from session close
FamilyC5 Family = "C5" // timing/order perturbation stable
)
// Expected captures what a scenario claims the V3 route should produce.
// Kept narrow on purpose: command-path inclusion/exclusion plus final
// mode is enough for the first calibration pass. Richer expectations
// can be added only when a divergence shows they are missing.
type Expected struct {
Decision string `json:"decision"`
CommandPathIncludes []string `json:"command_path_includes,omitempty"`
CommandPathExcludes []string `json:"command_path_excludes,omitempty"`
FinalMode string `json:"final_mode"`
TerminalFromClose bool `json:"terminal_from_close"`
DataIntegrityExpected bool `json:"data_integrity_expected,omitempty"`
}
// Observed captures what actually happened when the scenario ran.
// These fields are filled by the harness — never by the scenario itself.
// A scenario that edited Observed to make Expected match would be a
// classic hide-the-divergence anti-pattern.
type Observed struct {
Decision string `json:"decision"`
CommandPath []string `json:"command_path"`
CloseEventCount int `json:"close_event_count"` // count of "event: SessionClosedCompleted" in trace
FinalMode string `json:"final_mode"`
TerminalFromClose bool `json:"terminal_from_close"`
DataIntegrityOK bool `json:"data_integrity_ok"`
}
// Result is one scenario's complete record: metadata, the two snapshots,
// pass/fail, and — if they differ — a machine-readable divergence note.
type Result struct {
ID string `json:"id"`
Family Family `json:"family"`
Intent string `json:"intent"`
Expected Expected `json:"expected"`
Observed Observed `json:"observed"`
Pass bool `json:"pass"`
Divergence *Mismatch `json:"divergence,omitempty"`
Error string `json:"error,omitempty"`
}
// Mismatch enumerates the dimensions on which expected and observed
// diverged. Multiple can be true for one scenario.
type Mismatch struct {
Decision bool `json:"decision_diff,omitempty"`
CommandPath bool `json:"command_path_diff,omitempty"`
FinalMode bool `json:"final_mode_diff,omitempty"`
TerminalFromClose bool `json:"terminal_from_close_diff,omitempty"`
DataIntegrity bool `json:"data_integrity_diff,omitempty"`
}
// Compare derives pass/fail and a Mismatch from Expected vs Observed.
// Pure function — the harness calls this after the scenario runs.
func Compare(exp Expected, obs Observed) (pass bool, m *Mismatch) {
var d Mismatch
any := false
if exp.Decision != "" && exp.Decision != obs.Decision {
d.Decision = true
any = true
}
if !pathSatisfies(obs.CommandPath, exp.CommandPathIncludes, exp.CommandPathExcludes) {
d.CommandPath = true
any = true
}
if exp.FinalMode != "" && exp.FinalMode != obs.FinalMode {
d.FinalMode = true
any = true
}
if exp.TerminalFromClose && !obs.TerminalFromClose {
d.TerminalFromClose = true
any = true
}
if exp.DataIntegrityExpected && !obs.DataIntegrityOK {
d.DataIntegrity = true
any = true
}
if !any {
return true, nil
}
return false, &d
}
func pathSatisfies(path, includes, excludes []string) bool {
have := make(map[string]bool, len(path))
for _, c := range path {
have[c] = true
}
for _, inc := range includes {
if !have[inc] {
return false
}
}
for _, exc := range excludes {
if have[exc] {
return false
}
}
return true
}
+611
View File
@@ -0,0 +1,611 @@
package calibration
import (
"strings"
"time"
"github.com/seaweedfs/seaweed-block/core/adapter"
"github.com/seaweedfs/seaweed-block/core/engine"
)
// Scenario is one calibration case. Run sets up the required state,
// exercises the accepted V3 route, and returns Observed — the
// ground-truth record of what happened. Expected is a pure-data
// declaration returned by Expect, so Compare() can produce the
// pass/fail and divergence without the scenario having any chance
// to tweak expectations after observation.
type Scenario interface {
ID() string
Family() Family
Intent() string
Expect() Expected
Run() (Observed, error)
}
// AllScenarios returns the first calibration pass exactly as seeded in
// sw-block/design/docs/calibration/scenario-map.md. Order matters only
// for repeatability of the JSON artifact.
func AllScenarios() []Scenario {
return []Scenario{
&scenarioC1Healthy{},
&scenarioC2ShortGap{},
&scenarioC3LongGap{},
&scenarioC4TerminalClose{},
&scenarioC5OrderStable{},
}
}
// --- C1 ---
type scenarioC1Healthy struct{}
func (*scenarioC1Healthy) ID() string { return "CAL-C1-healthy-repeat" }
func (*scenarioC1Healthy) Family() Family { return FamilyC1 }
func (*scenarioC1Healthy) Intent() string {
return "repeated observation on caught-up replica stays healthy"
}
func (*scenarioC1Healthy) Expect() Expected {
return Expected{
Decision: "none",
CommandPathExcludes: []string{"StartCatchUp", "StartRebuild"},
FinalMode: string(engine.ModeHealthy),
}
}
func (*scenarioC1Healthy) Run() (Observed, error) {
h, err := newHarness()
if err != nil {
return Observed{}, err
}
defer h.close()
h.writeBlocks(10)
h.mirrorToReplica()
h.assign(1, 1)
p := h.waitForDecisionFinal(3 * time.Second)
if p.Mode != engine.ModeHealthy {
// Precondition for the repetition proof failed; return what we
// have so the comparison reports the violation honestly.
return observed(h, p), nil
}
// The actual C1 claim: repeated observation on a caught-up replica
// stays healthy — no recovery is ever triggered. After reaching
// healthy, fire N probe results with the same R/S/H facts and
// assert no StartCatchUp / StartRebuild ever appears.
//
// Snapshot command count BEFORE the repetition; after the loop,
// the per-command totals must be unchanged for recovery kinds.
const repetitions = 5
_, _, pH := h.primaryStore.Boundaries()
rR, rS, _ := h.replicaStore.Boundaries()
for i := 0; i < repetitions; i++ {
h.adapter.OnProbeResult(adapter.ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1,
TransportEpoch: 1,
ReplicaFlushedLSN: rR,
PrimaryTailLSN: rS,
PrimaryHeadLSN: pH,
})
// Tiny spacing between probes to exercise the path repeatedly,
// not to sleep-through-a-race.
time.Sleep(5 * time.Millisecond)
}
// Re-read final projection after the repetition — if any probe had
// triggered recovery, mode would flip away from healthy.
p = h.adapter.Projection()
return observed(h, p), nil
}
// --- C2 ---
type scenarioC2ShortGap struct{}
func (*scenarioC2ShortGap) ID() string { return "CAL-C2-short-gap-catchup" }
func (*scenarioC2ShortGap) Family() Family { return FamilyC2 }
func (*scenarioC2ShortGap) Intent() string {
return "short retained gap chooses catch-up; closes to healthy"
}
func (*scenarioC2ShortGap) Expect() Expected {
return Expected{
Decision: "catch_up",
CommandPathIncludes: []string{"StartCatchUp"},
CommandPathExcludes: []string{"StartRebuild"},
FinalMode: string(engine.ModeHealthy),
TerminalFromClose: true,
DataIntegrityExpected: true,
}
}
func (*scenarioC2ShortGap) Run() (Observed, error) {
h, err := newHarness()
if err != nil {
return Observed{}, err
}
defer h.close()
// Primary has 10 blocks; replica starts empty. WAL tail is at 1
// (from first write), so R=0, S=1, H=10 and R < S would be rebuild.
// For catch_up we need R >= S, so mirror enough to pass the S
// boundary without reaching H.
h.writeBlocks(10)
// Copy 3 blocks to replica with an LSN that advances its frontier
// past S but well below H — classic catch_up territory.
_, _, pH := h.primaryStore.Boundaries()
for i := uint32(0); i < 3; i++ {
data, _ := h.primaryStore.Read(i)
_ = h.replicaStore.ApplyEntry(i, data, pH/2)
}
h.replicaStore.Sync()
h.assign(1, 1)
p := h.waitForDecisionFinal(5 * time.Second)
return observed(h, p), nil
}
// --- C3 ---
type scenarioC3LongGap struct{}
func (*scenarioC3LongGap) ID() string { return "CAL-C3-long-gap-rebuild" }
func (*scenarioC3LongGap) Family() Family { return FamilyC3 }
func (*scenarioC3LongGap) Intent() string {
return "long gap beyond retained window chooses rebuild; closes to healthy"
}
func (*scenarioC3LongGap) Expect() Expected {
return Expected{
Decision: "rebuild",
CommandPathIncludes: []string{"StartRebuild"},
CommandPathExcludes: []string{"StartCatchUp"},
FinalMode: string(engine.ModeHealthy),
TerminalFromClose: true,
DataIntegrityExpected: true,
}
}
func (*scenarioC3LongGap) Run() (Observed, error) {
h, err := newHarness()
if err != nil {
return Observed{}, err
}
defer h.close()
h.writeBlocks(10)
// Move WAL tail past the current head so R < S holds for any
// replica that has not yet reached the new tail. Replica is empty
// (R=0), so the engine must classify this as long-gap rebuild.
h.advanceWALPastReplica()
h.assign(1, 1)
p := h.waitForDecisionFinal(5 * time.Second)
return observed(h, p), nil
}
// --- C4 ---
// scenarioC4TerminalClose proves that terminal truth (final mode healthy)
// only appears AFTER SessionClosedCompleted in the trace. The test runs
// a normal catch-up scenario end-to-end and then scans the trace: if
// healthy publication preceded the session close event, that would be a
// terminal-truth anti-pattern. Phase 05 engine structurally disallows
// this, so the evidence we collect is order-of-trace-events.
type scenarioC4TerminalClose struct{}
func (*scenarioC4TerminalClose) ID() string { return "CAL-C4-terminal-close-only" }
func (*scenarioC4TerminalClose) Family() Family { return FamilyC4 }
func (*scenarioC4TerminalClose) Intent() string {
return "final healthy appears only after SessionClosedCompleted; progress alone does not count"
}
func (*scenarioC4TerminalClose) Expect() Expected {
return Expected{
Decision: "catch_up",
CommandPathIncludes: []string{"StartCatchUp"},
FinalMode: string(engine.ModeHealthy),
TerminalFromClose: true,
}
}
func (*scenarioC4TerminalClose) Run() (Observed, error) {
h, err := newHarness()
if err != nil {
return Observed{}, err
}
defer h.close()
// Same setup as C2: short gap → catch_up → close → healthy.
h.writeBlocks(10)
_, _, pH := h.primaryStore.Boundaries()
for i := uint32(0); i < 3; i++ {
data, _ := h.primaryStore.Read(i)
_ = h.replicaStore.ApplyEntry(i, data, pH/2)
}
h.replicaStore.Sync()
h.assign(1, 1)
p := h.waitForDecisionFinal(5 * time.Second)
obs := observed(h, p)
// Overwrite TerminalFromClose with a trace-order check — this is
// the specific C4 evidence question, and the trace carries the
// authoritative answer.
obs.TerminalFromClose = terminalOnlyAfterClose(h.adapter.Trace())
return obs, nil
}
// terminalOnlyAfterClose proves that a recovery-path scenario reached
// terminal healthy only through a session-close event, not through
// progress or transport success alone.
//
// Evidence (in trace ORDER, not just presence):
//
// 1. "event: SessionClosedCompleted" MUST appear at some index K.
// 2. "decision: none (R >= H)" — the ONLY engine path to Publication.
// Healthy = true on a recovery path — MUST appear at index >= K.
// The reducer sets Recovery.Decision to None only when R >= H,
// and R only advances to H via applySessionCompleted. Any
// "decision: none (R >= H)" at index < K would mean healthy was
// declared before close processed — the C4 violation.
// 3. At least one such decision MUST appear. A run that never
// reached healthy must not vacuously pass this check.
//
// A buggy route that published healthy early AND then later emitted
// the close markers would be caught by rule 2 — its pre-close
// "decision: none (R >= H)" would land before SessionClosedCompleted.
func terminalOnlyAfterClose(trace []engine.TraceEntry) bool {
closeIdx := -1
for i, te := range trace {
if te.Step == "event" && te.Detail == "SessionClosedCompleted" {
closeIdx = i
break
}
}
if closeIdx < 0 {
return false // rule 1 — scenario never closed
}
// Scan the whole trace for the healthy-transition decision. Any
// occurrence before closeIdx is a violation. Require at least one
// occurrence at or after closeIdx.
healthyAfterClose := false
for i, te := range trace {
if te.Step == "decision" && strings.HasPrefix(te.Detail, "none (R >= H)") {
if i < closeIdx {
return false // rule 2 — healthy claimed before close
}
healthyAfterClose = true
}
}
return healthyAfterClose // rule 3
}
// --- C5 ---
// scenarioC5OrderStable runs the short-gap case N times with a tiny
// pre-assignment sleep that varies per iteration. Every run must choose
// the same decision and reach the same final mode. The decision string
// recorded in Observed is from the first run; subsequent runs compare
// to it. Any divergence across runs marks the scenario as failed with
// CommandPath mismatch carrying the run where it happened.
type scenarioC5OrderStable struct{}
func (*scenarioC5OrderStable) ID() string { return "CAL-C5-order-stable" }
func (*scenarioC5OrderStable) Family() Family { return FamilyC5 }
func (*scenarioC5OrderStable) Intent() string {
return "same facts under small timing/order perturbation still choose the same decision"
}
func (*scenarioC5OrderStable) Expect() Expected {
return Expected{
Decision: "catch_up",
CommandPathIncludes: []string{"StartCatchUp"},
FinalMode: string(engine.ModeHealthy),
DataIntegrityExpected: true,
}
}
// perturbation is one of the concrete interleaving patterns C5 runs.
// Each produces the SAME underlying facts on the SAME replica (r1)
// but delivers events to the adapter in a different order, timing, or
// concurrency shape.
//
// Every perturbation must preserve "same facts" honestly:
//
// 1. No wrong-replica events (checkReplicaID's pre-identity accept
// path would turn them into real cross-replica side effects).
// 2. No post-assignment probes with pre-captured facts. Those carry
// STALE R/S/H values; once the engine has converged (R=H), an
// incoming fact with R<H is correctly interpreted as new truth
// and triggers a legitimate re-recovery. That's not an A1/A4
// leak — it's the engine doing its job. Including such events
// in a "same facts" perturbation is self-sabotage.
//
// Remaining valid perturbations vary goroutine scheduling, pre-assign
// event arrival, and assignment idempotence — the kinds of delivery
// variation an A1/A4 leak would surface on.
type perturbation int
const (
pertBaseline perturbation = iota // assign + wait
pertPreAssignProbe // one valid pre-assign probe, wiped when identity arrives
pertPreAssignStorm // 8 concurrent pre-assign probes, then assign
pertRepeatAssign // assign twice with identical epoch/endpointVersion (idempotent)
pertStaggeredAssign // 5 concurrent assigns with identical identity, then wait
)
func (*scenarioC5OrderStable) Run() (Observed, error) {
perturbations := []perturbation{
pertBaseline,
pertPreAssignProbe,
pertPreAssignStorm,
pertRepeatAssign,
pertStaggeredAssign,
}
var first Observed
var firstSig recoverySignature
sameDecision := true
sameFinalMode := true
sameRecoverySig := true
sameCloseCount := true
dataOK := true
for i, p := range perturbations {
h, err := newHarness()
if err != nil {
return Observed{}, err
}
// Identical facts across every run — only the delivery shape
// varies. Short-gap setup: R ~= H/2, S = 1, H = 10.
h.writeBlocks(10)
_, _, pH := h.primaryStore.Boundaries()
for j := uint32(0); j < 3; j++ {
data, _ := h.primaryStore.Read(j)
_ = h.replicaStore.ApplyEntry(j, data, pH/2)
}
h.replicaStore.Sync()
applyPerturbation(h, p)
proj := h.waitForDecisionFinal(5 * time.Second)
obs := observed(h, proj)
sig := extractRecoverySignature(obs.CommandPath)
if i == 0 {
first = obs
firstSig = sig
} else {
if obs.Decision != first.Decision {
sameDecision = false
}
if obs.FinalMode != first.FinalMode {
sameFinalMode = false
}
if sig != firstSig {
sameRecoverySig = false
}
if obs.CloseEventCount != first.CloseEventCount {
sameCloseCount = false
}
if !obs.DataIntegrityOK {
dataOK = false
}
}
h.close()
}
out := first
if !sameDecision {
out.Decision = "DIVERGED_ACROSS_RUNS"
}
if !sameFinalMode {
out.FinalMode = "DIVERGED_ACROSS_RUNS"
}
if !sameRecoverySig {
// Pollute the command path marker so the reader cannot miss
// that the recovery signature drifted. The baseline first-run
// path is preserved alongside the marker so divergence-log
// authors can still see what the first run looked like.
out.CommandPath = append([]string{"DIVERGED_ACROSS_RUNS_RECOVERY_SIG"}, first.CommandPath...)
}
if !sameCloseCount {
// Set CloseEventCount to a negative sentinel so the JSON
// artifact makes the drift unambiguous. Negative is never a
// legitimate count, so tester review cannot miss it.
out.CloseEventCount = -1
}
out.DataIntegrityOK = out.DataIntegrityOK && dataOK
return out, nil
}
// recoverySignature is the decision-relevant fingerprint of a command
// path — counts of each recovery command kind. Two runs with the same
// facts must produce the same signature even if their non-recovery
// command noise (duplicate PublishHealthy from repeat probes, etc.)
// differs. Comparing full command sequences would false-diverge on
// idempotent re-probes; comparing signatures catches the real A1/A4
// anti-pattern leak.
type recoverySignature struct {
NCatchUp int
NRebuild int
}
func extractRecoverySignature(path []string) recoverySignature {
var sig recoverySignature
for _, c := range path {
switch c {
case "StartCatchUp":
sig.NCatchUp++
case "StartRebuild":
sig.NRebuild++
}
}
return sig
}
// applyPerturbation drives the adapter under one of the C5 event
// orderings. Facts stay the same (same replica r1, same initial
// R/S/H); only the delivery shape — timing, ordering, concurrency,
// assignment idempotence — varies.
//
// All post-assignment probe variations are deliberately omitted: a
// probe fired with pre-captured facts after the engine has converged
// would deliver STALE R to the engine and legitimately trigger
// re-recovery. Treating that as a C5 failure would conflate engine
// correctness with A1/A4. Treating it as a C5 success would require
// gating the engine's fact-processing, which is a route change that
// belongs outside Phase 06.
func applyPerturbation(h *harness, p perturbation) {
_, _, pH := h.primaryStore.Boundaries()
rR, rS, _ := h.replicaStore.Boundaries()
sameFactsProbe := adapter.ProbeResult{
ReplicaID: "r1", Success: true,
EndpointVersion: 1,
TransportEpoch: 1,
ReplicaFlushedLSN: rR,
PrimaryTailLSN: rS,
PrimaryHeadLSN: pH,
}
switch p {
case pertBaseline:
h.assign(1, 1)
case pertPreAssignProbe:
// One valid pre-assign probe. Engine accepts via the
// pre-identity acceptance path; identity then lands and
// resets Reachability/Recovery, so pre-assign state is
// wiped. Final decision must match baseline.
h.adapter.OnProbeResult(sameFactsProbe)
h.assign(1, 1)
case pertPreAssignStorm:
// 8 concurrent pre-assign probes. Same net effect as
// pertPreAssignProbe but with real mutex contention across
// the adapter boundary before identity.
for i := 0; i < 8; i++ {
go h.adapter.OnProbeResult(sameFactsProbe)
}
h.assign(1, 1)
case pertRepeatAssign:
// Two identical assignments in sequence. The second's
// epoch/endpointVersion match the first, so the engine's
// monotonic identity check accepts without bumping
// identity — a true idempotent re-assign.
h.assign(1, 1)
h.assign(1, 1)
case pertStaggeredAssign:
// 5 concurrent identical assignments. Same endpoint/epoch;
// engine must handle concurrent idempotent re-assignment
// without producing divergent recovery signatures.
for i := 0; i < 5; i++ {
go h.assign(1, 1)
}
}
}
// --- shared ---
// observed builds the Observed record from a harness post-run. Central
// so every scenario captures the same fields the same way — scenarios
// never hand-tune Observed outside this function.
//
// Decision is derived from the command log rather than the final
// projection. After a successful recovery run the engine resets
// RecoveryDecision to "none", but the calibration question is "what
// did the engine CHOOSE to do for this setup?" — and that choice is
// visible in which Start* command was emitted. Reading the final
// projection instead would reduce every successful recovery to
// Decision="none", making the catch_up-vs-rebuild distinction
// invisible and falsely diverging from Expected.Decision.
func observed(h *harness, final engine.ReplicaProjection) Observed {
cmds := h.commandLog()
trace := h.adapter.Trace()
return Observed{
Decision: decisionFromCommandPath(cmds),
CommandPath: cmds,
CloseEventCount: countCloseEvents(trace),
FinalMode: string(final.Mode),
TerminalFromClose: terminalOnlyAfterClose(trace),
DataIntegrityOK: h.dataMatches(),
}
}
// countCloseEvents returns the number of SessionClosedCompleted events
// in the adapter trace. This is the truthful "session close" count
// (previously a field named SessionCloseCount in fact counted
// PublishHealthy commands, which was misleading).
func countCloseEvents(trace []engine.TraceEntry) int {
n := 0
for _, te := range trace {
if te.Step == "event" && te.Detail == "SessionClosedCompleted" {
n++
}
}
return n
}
// decisionFromCommandPath reports which recovery class the engine
// actually picked, regardless of where the projection has since
// settled. If StartRebuild appears, the engine chose rebuild.
// If StartCatchUp appears (and no rebuild), it chose catch_up.
// If neither, no recovery was needed — decision was none.
func decisionFromCommandPath(cmds []string) string {
hasRebuild := false
hasCatchUp := false
for _, c := range cmds {
if c == "StartRebuild" {
hasRebuild = true
}
if c == "StartCatchUp" {
hasCatchUp = true
}
}
switch {
case hasRebuild:
return "rebuild"
case hasCatchUp:
return "catch_up"
default:
return "none"
}
}
// Runner is the small driver that executes a set of scenarios and
// produces one Result per scenario. It is deliberately not parallel:
// the calibration signal is clearer when runs are sequential and a
// shared transport listener per harness is simpler to reason about.
type Runner struct{}
// Run executes every scenario in order, one after another, and returns
// a Report. Any error from a single scenario is recorded on its Result
// but does not stop the remaining scenarios.
func (Runner) Run(scenarios []Scenario) Report {
results := make([]Result, 0, len(scenarios))
for _, s := range scenarios {
r := Result{
ID: s.ID(),
Family: s.Family(),
Intent: s.Intent(),
Expected: s.Expect(),
}
obs, err := s.Run()
if err != nil {
r.Error = err.Error()
r.Pass = false
r.Divergence = &Mismatch{}
} else {
r.Observed = obs
r.Pass, r.Divergence = Compare(r.Expected, r.Observed)
}
results = append(results, r)
}
return newReport(results)
}
// Suppress the "adapter imported and not used" linter warning if
// scenarios ever temporarily drop all adapter references during
// development. The adapter IS used via harness; this is a defensive
// import anchor.
var _ = adapter.AssignmentInfo{}
@@ -0,0 +1,241 @@
package calibration
import (
"encoding/json"
"testing"
)
// TestAllScenarios_PassEndToEnd is the headline Phase 06 test: every
// scenario in the first calibration set runs green through the accepted
// V3 route. If this fails, a real calibration divergence has been found
// and belongs in docs/calibration/divergence-log.md — not in a test
// loosening.
func TestAllScenarios_PassEndToEnd(t *testing.T) {
report := Runner{}.Run(AllScenarios())
// Emit the JSON report to t.Logf so CI output carries the evidence.
buf, _ := json.MarshalIndent(report, "", " ")
t.Logf("Phase 06 calibration report:\n%s", buf)
if !report.Summary.AllPassed {
t.Fatalf("calibration failed: %d/%d passed, %d diverged, %d errored",
report.Summary.Passed, report.Summary.Total,
report.Summary.Diverged, report.Summary.Errors)
}
}
// TestC1_HealthyNoRecovery asserts the C1 claim in isolation so a
// failure points directly at family C1 without searching through the
// joint report.
func TestC1_HealthyNoRecovery(t *testing.T) {
obs, err := (&scenarioC1Healthy{}).Run()
if err != nil {
t.Fatal(err)
}
for _, c := range obs.CommandPath {
if c == "StartCatchUp" || c == "StartRebuild" {
t.Fatalf("C1: expected no recovery commands, got %v", obs.CommandPath)
}
}
if obs.FinalMode != "healthy" {
t.Fatalf("C1: final mode %q, want healthy", obs.FinalMode)
}
}
func TestC2_ShortGapCatchUp(t *testing.T) {
obs, err := (&scenarioC2ShortGap{}).Run()
if err != nil {
t.Fatal(err)
}
sawCatchUp := false
for _, c := range obs.CommandPath {
if c == "StartRebuild" {
t.Fatalf("C2: rebuild must not fire for short gap, got %v", obs.CommandPath)
}
if c == "StartCatchUp" {
sawCatchUp = true
}
}
if !sawCatchUp {
t.Fatalf("C2: StartCatchUp missing from %v", obs.CommandPath)
}
if obs.FinalMode != "healthy" {
t.Fatalf("C2: final mode %q, want healthy", obs.FinalMode)
}
if !obs.DataIntegrityOK {
t.Fatal("C2: data integrity check failed")
}
}
func TestC3_LongGapRebuild(t *testing.T) {
obs, err := (&scenarioC3LongGap{}).Run()
if err != nil {
t.Fatal(err)
}
sawRebuild := false
for _, c := range obs.CommandPath {
if c == "StartCatchUp" {
t.Fatalf("C3: catch-up must not fire for long gap, got %v", obs.CommandPath)
}
if c == "StartRebuild" {
sawRebuild = true
}
}
if !sawRebuild {
t.Fatalf("C3: StartRebuild missing from %v", obs.CommandPath)
}
if obs.FinalMode != "healthy" {
t.Fatalf("C3: final mode %q, want healthy", obs.FinalMode)
}
if !obs.DataIntegrityOK {
t.Fatal("C3: data integrity check failed")
}
}
func TestC4_TerminalOnlyFromSessionClose(t *testing.T) {
obs, err := (&scenarioC4TerminalClose{}).Run()
if err != nil {
t.Fatal(err)
}
if !obs.TerminalFromClose {
t.Fatalf("C4: terminal truth not attributable to session close; "+
"command path=%v final=%q", obs.CommandPath, obs.FinalMode)
}
if obs.FinalMode != "healthy" {
t.Fatalf("C4: final mode %q, want healthy", obs.FinalMode)
}
}
func TestC5_OrderStableAcrossRuns(t *testing.T) {
obs, err := (&scenarioC5OrderStable{}).Run()
if err != nil {
t.Fatal(err)
}
if obs.Decision == "DIVERGED_ACROSS_RUNS" {
t.Fatal("C5: decision varied across perturbed runs — A1/A4 leak")
}
if obs.FinalMode == "DIVERGED_ACROSS_RUNS" {
t.Fatal("C5: final mode varied across perturbed runs — A1/A4 leak")
}
// Recovery-signature divergence is signaled by a sentinel element
// prepended to CommandPath. The scenario run must not hit this.
if len(obs.CommandPath) > 0 && obs.CommandPath[0] == "DIVERGED_ACROSS_RUNS_RECOVERY_SIG" {
t.Fatalf("C5: recovery signature drifted across runs; first-run path=%v", obs.CommandPath[1:])
}
// CloseEventCount sentinel: negative is used to flag cross-run
// drift in the number of SessionClosedCompleted events. A legit
// count is always >= 0.
if obs.CloseEventCount < 0 {
t.Fatalf("C5: close-event count drifted across runs (sentinel %d)", obs.CloseEventCount)
}
if obs.Decision != "catch_up" {
t.Fatalf("C5: expected catch_up, got %q", obs.Decision)
}
// For the short-gap catch-up scenario, exactly one close event
// per run is the expected count. Lock this in so a future
// refactor that silently changes the close shape is caught.
if obs.CloseEventCount != 1 {
t.Fatalf("C5: expected CloseEventCount=1 (one catch-up session per run), got %d",
obs.CloseEventCount)
}
}
// TestC5_RecoverySignatureCheckActuallyWorks is a meta-test for the
// cross-run compare logic. We construct two divergent paths (one with
// extra StartRebuild) and verify extractRecoverySignature catches it.
// This guards against a future refactor silently dropping the compare.
func TestC5_RecoverySignatureCheckActuallyWorks(t *testing.T) {
pathA := []string{"ProbeReplica", "StartCatchUp", "PublishHealthy"}
pathB := []string{"ProbeReplica", "StartCatchUp", "StartRebuild", "PublishHealthy"}
pathDupCatchUp := []string{"ProbeReplica", "StartCatchUp", "StartCatchUp", "PublishHealthy"}
sigA := extractRecoverySignature(pathA)
sigB := extractRecoverySignature(pathB)
sigDup := extractRecoverySignature(pathDupCatchUp)
if sigA == sigB {
t.Fatal("extractRecoverySignature: A and B should differ (B has extra StartRebuild)")
}
if sigA == sigDup {
t.Fatal("extractRecoverySignature: A and Dup should differ (Dup has extra StartCatchUp)")
}
if sigA.NCatchUp != 1 || sigA.NRebuild != 0 {
t.Fatalf("sigA unexpected: %+v", sigA)
}
if sigDup.NCatchUp != 2 {
t.Fatalf("sigDup should count both catch-ups: %+v", sigDup)
}
}
func TestCompare_PassWhenEverythingMatches(t *testing.T) {
exp := Expected{
Decision: "catch_up",
CommandPathIncludes: []string{"StartCatchUp"},
CommandPathExcludes: []string{"StartRebuild"},
FinalMode: "healthy",
}
obs := Observed{
Decision: "catch_up",
CommandPath: []string{"Probe", "StartCatchUp", "PublishHealthy"},
FinalMode: "healthy",
}
pass, m := Compare(exp, obs)
if !pass {
t.Fatalf("expected pass, got mismatch %+v", m)
}
if m != nil {
t.Fatalf("expected nil mismatch on pass, got %+v", m)
}
}
func TestCompare_FailsOnEachMismatchDimension(t *testing.T) {
base := Expected{
Decision: "catch_up",
CommandPathIncludes: []string{"StartCatchUp"},
CommandPathExcludes: []string{"StartRebuild"},
FinalMode: "healthy",
TerminalFromClose: true,
DataIntegrityExpected: true,
}
cases := []struct {
name string
obs Observed
fieldOK func(*Mismatch) bool
}{
{
"decision", Observed{Decision: "rebuild", CommandPath: []string{"StartCatchUp"}, FinalMode: "healthy", TerminalFromClose: true, DataIntegrityOK: true},
func(m *Mismatch) bool { return m.Decision },
},
{
"command_path_missing_include", Observed{Decision: "catch_up", CommandPath: []string{"Probe"}, FinalMode: "healthy", TerminalFromClose: true, DataIntegrityOK: true},
func(m *Mismatch) bool { return m.CommandPath },
},
{
"command_path_has_excluded", Observed{Decision: "catch_up", CommandPath: []string{"StartCatchUp", "StartRebuild"}, FinalMode: "healthy", TerminalFromClose: true, DataIntegrityOK: true},
func(m *Mismatch) bool { return m.CommandPath },
},
{
"final_mode", Observed{Decision: "catch_up", CommandPath: []string{"StartCatchUp"}, FinalMode: "degraded", TerminalFromClose: true, DataIntegrityOK: true},
func(m *Mismatch) bool { return m.FinalMode },
},
{
"terminal_from_close", Observed{Decision: "catch_up", CommandPath: []string{"StartCatchUp"}, FinalMode: "healthy", TerminalFromClose: false, DataIntegrityOK: true},
func(m *Mismatch) bool { return m.TerminalFromClose },
},
{
"data_integrity", Observed{Decision: "catch_up", CommandPath: []string{"StartCatchUp"}, FinalMode: "healthy", TerminalFromClose: true, DataIntegrityOK: false},
func(m *Mismatch) bool { return m.DataIntegrity },
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
pass, m := Compare(base, c.obs)
if pass {
t.Fatalf("expected fail, got pass")
}
if m == nil || !c.fieldOK(m) {
t.Fatalf("expected %s flag set in mismatch, got %+v", c.name, m)
}
})
}
}
@@ -15,6 +15,8 @@ design, the production interface is `weed shell` after integration.
| Repeatable validation | `go run ./cmd/sparrow --runs 10 --json` |
| Machine-readable output for CI | `go run ./cmd/sparrow --json` |
| Optional read-only HTTP inspection | `go run ./cmd/sparrow --http :9090` |
| Phase 06 calibration pass | `go run ./cmd/sparrow --calibrate` |
| Calibration report as JSON (for tester review) | `go run ./cmd/sparrow --calibrate --json` |
## Not supported in Phase 05
@@ -0,0 +1,207 @@
# V3 Calibration Divergence Log
Date: 2026-04-14
Status: no divergences recorded on first pass
This file records all expected-versus-observed mismatches discovered
during Phase 06 calibration. It is seeded from the template in
`sw-block/design/docs/calibration/divergence-log.md`.
## Usage
A divergence is any case where:
1. expected semantic decision differs from observed decision
2. expected command path differs from observed command path
3. expected terminal-close behavior differs from observed closure
4. final state or final data differs from expectation
Do not hide a mismatch by broadening the expectation first.
Record the divergence here, then decide whether to fix or carry it forward.
## Status Labels
Use one of:
1. `open`
2. `investigating`
3. `fixed`
4. `accepted-carry-forward`
## Entry Template
Copy this block for each divergence:
```md
## DIV-XXX
- Scenario ID:
- Scenario family:
- Detected in run / artifact:
- Status:
### Expected
- semantic decision:
- command path:
- terminal close:
- final state / data:
### Observed
- semantic decision:
- command path:
- terminal close:
- final state / data:
### Classification
- semantic / route / terminal-close / data / other:
- anti-pattern pressure involved (`A1`, `A4`, `A7`, other):
### Notes
- short explanation:
- next action:
```
## Current Divergences
No route-level calibration divergences recorded.
First pass on 2026-04-14 ran all five scenarios
(`CAL-C1-healthy-repeat`, `CAL-C2-short-gap-catchup`,
`CAL-C3-long-gap-rebuild`, `CAL-C4-terminal-close-only`,
`CAL-C5-order-stable`) through `sparrow --calibrate` and through
`core/calibration/scenarios_test.go`. All five came back `pass`
with no expected-versus-observed mismatch on the accepted route.
### Harness evidence-attribution issues found and fixed on first pass
These are not route divergences; they are cases where the scenario
claimed stronger evidence than it actually checked. Architect review
on 2026-04-14 caught all three. Recorded here to make the history
honest and to serve as template for future evidence-strength
discipline.
**H-001 (`CAL-C4-terminal-close-only`) — healthy-only-after-close
was presence-only, not order.** The original check asserted that
`SessionClosedCompleted` and `session_completed` both appeared in
the trace, but never verified that no healthy-transition decision
appeared BEFORE them. A buggy route that published healthy early
and then later emitted close markers would still pass. Fixed by
scanning trace in order: any `decision: none (R >= H)` before the
close event is a violation, and at least one must appear at/after
close for the proof to be non-vacuous.
**H-002 (`CAL-C5-order-stable`) — perturbation was a sleep, not an
ordering change.** The original C5 delayed the start of each run by
0-8 ms but then ran the exact same deterministic sequence. This did
not stress A1 or A4 meaningfully. Fixed by replacing the sleep with
five distinct event-ordering patterns: baseline, early duplicate
probes, concurrent wrong-replica storm, mixed valid+stale, and storm
of valid same-fact probes. All five must produce the same decision
and final mode.
**H-003 (`CAL-C1-healthy-repeat`) — scenario did not actually
repeat observation.** The original C1 performed a single
assignment + single wait, then reported "repeated observation stays
healthy". Fixed by firing 5 additional `OnProbeResult` calls with
the same facts after reaching healthy, then re-reading the
projection to confirm mode stayed healthy and no new recovery
commands appeared.
**H-004 (`CAL-C5-order-stable`) — full command path was not
compared; only `Decision` and `FinalMode` were.** The original C5
loop compared three fields across runs but never looked at
`Observed.CommandPath`, and the report reused the first run's path
verbatim. A run whose command log drifted (e.g., extra `StartCatchUp`
from stale-fact re-probes) would pass silently. Fixed by adding a
`recoverySignature` comparison: counts of `StartCatchUp` and
`StartRebuild` must be identical across runs. A signature mismatch
prepends `DIVERGED_ACROSS_RUNS_RECOVERY_SIG` to the reported
CommandPath so divergence is visible in the artifact.
**H-005 (`CAL-C5-order-stable`) — wrong-replica perturbations had
real side effects.** The original C5 included two patterns that
fired `ProbeFailed` events for a different `ReplicaID` ("r-other"),
documented as "rejected by engine `checkReplicaID`". That comment
was wrong: `checkReplicaID` at `apply.go:108-111` accepts events for
ANY replica when `st.Identity.ReplicaID == ""` (pre-identity path).
Those events reached `applyProbeFailed` and emitted real
`PublishDegraded{r-other}` commands, observable in executor logs as
`publish degraded for r-other`. That contaminated the command-path
comparison and contradicted the "same facts under reordering" claim.
Fixed by dropping all wrong-replica perturbations. The remaining
five perturbations are all same-replica: baseline, pre-assign probe,
pre-assign concurrent storm, repeat assign, staggered concurrent
assign. Each one preserves facts while varying delivery.
After this fix a real engine observation was exposed: any
post-convergence probe firing with pre-captured (now stale) facts
triggers the engine to re-enter `catch_up` via a legitimate
`RecoveryFactsObserved → decide()` path. The re-emit is guarded by
`!hasActiveSession(st)` in `decide()` (apply.go:287) but fires once
the first catch-up has completed and the session is in
`PhaseCompleted`. This is not an A1/A4 leak — it's the engine
correctly processing newly-arriving facts. Including such probes in
a "same facts" perturbation set would force C5 to either pass
vacuously or misattribute a legitimate re-recovery as a violation.
Perturbation set narrowed accordingly.
**H-006 — `Observed.SessionCloseCount` was counting
`PublishHealthy`.** The field named `SessionCloseCount` was derived
from `countCommand(cmds, "PublishHealthy")`, which counts healthy
publications, not session-close events. Renamed to
`CloseEventCount` and re-derived from the adapter trace's
`event: SessionClosedCompleted` entries. The JSON artifact field
`close_event_count` now matches its name.
**H-007 (`CAL-C5-order-stable`) — doc claimed identical
`close_event_count` across runs; code did not enforce it.** After
H-006 corrected the field's meaning, the scenario map was updated to
claim "identical close-event count across runs" but the cross-run
compare loop in `scenarioC5OrderStable.Run` did not compare the new
field. A drift in CloseEventCount would have passed silently. Fixed
by extending the compare loop: when counts differ across runs,
`Observed.CloseEventCount` is set to `-1` as a sentinel (a legitimate
count is always >= 0), so the JSON artifact and the per-scenario
test both surface the drift. The scenario test also pins the
expected steady-state count to 1 (one catch-up session per run for
the short-gap setup), so any future refactor that changes session
emission shape is caught.
### Harness decision (retained from prior note)
`Observed.Decision` is derived from the command log
(`StartCatchUp` / `StartRebuild` markers), not from the final
projection. After successful recovery the engine resets
`RecoveryDecision` to `"none"`, which would collapse every
successful recovery to `"none"` and falsely diverge every
`catch_up`/`rebuild` case. The command-log view captures what the
engine actually chose. Not a route mismatch.
Add entries below this line as soon as the first calibration
route divergence appears.
## Recording Rules
When adding a divergence:
1. create the entry immediately
2. link the matching scenario id from `scenario-map.md`
3. classify the mismatch before proposing the fix
4. keep the original expected/observed wording even after the fix lands
## Closure Rule
A divergence may be marked `fixed` only when:
1. the underlying mismatch is corrected
2. the affected calibration case is rerun
3. the new evidence artifact is linked in the entry
A divergence may be marked `accepted-carry-forward` only when:
1. architect and tester agree it is outside the current calibration closure bar
2. the carry-forward reason is written explicitly
@@ -0,0 +1,163 @@
# V3 Calibration Scenario Map
Date: 2026-04-14
Status: first-pass wired, all scenarios green on 2026-04-14
This file is the working map for the Phase 06 first calibration pass,
seeded from `sw-block/design/docs/calibration/scenario-map.md` in the
planning repo. The authoritative test artifact is the JSON Report
emitted by `go run ./cmd/sparrow --calibrate --json`.
## Usage
For each scenario, record:
1. stable scenario id
2. scenario family (`C1` to `C5`)
3. one-sentence intent
4. expected semantic decision
5. expected command path
6. expected terminal close result
7. final-state/data expectation
8. evidence artifact location
9. current status
Do not delete rows when a case changes. Update status and add notes instead.
## Status Labels
Use one of:
1. `planned`
2. `wired`
3. `running`
4. `passed`
5. `diverged`
6. `accepted-carry-forward`
## First Calibration Set
| Scenario ID | Family | Intent | Expected Decision | Expected Command Path | Expected Terminal Close | Final State / Data Expectation | Evidence Artifact | Status | Notes |
|---|---|---|---|---|---|---|---|---|---|
| `CAL-C1-healthy-repeat` | `C1` | Repeated observation on caught-up replica stays healthy | `none` | no `StartCatchUp`, no `StartRebuild` before OR after 5 extra probe cycles | not required | final mode `healthy` after 5 additional same-fact probes | `core/calibration/scenarios_test.go::TestC1_HealthyNoRecovery` + `sparrow --calibrate --json` | `passed` | proves stable healthy absorbs repeated observation without triggering recovery |
| `CAL-C2-short-gap-catchup` | `C2` | Short retained gap chooses catch-up | `catch_up` | `StartCatchUp` yes, `StartRebuild` no | session close success | final mode `healthy`; replica data matches primary | `TestC2_ShortGapCatchUp` + `--calibrate --json` | `passed` | first calibration for short-gap route |
| `CAL-C3-long-gap-rebuild` | `C3` | Long gap beyond retained window chooses rebuild | `rebuild` | `StartRebuild` yes, `StartCatchUp` no | session close success | final mode `healthy`; rebuilt data matches primary | `TestC3_LongGapRebuild` + `--calibrate --json` | `passed` | first calibration for long-gap route |
| `CAL-C4-terminal-close-only` | `C4` | Progress alone does not count as terminal success | `catch_up` | `StartCatchUp` yes | ordered trace check: `decision: none (R >= H)` appears AFTER `event: SessionClosedCompleted` and at least once | final mode `healthy` only via close | `TestC4_TerminalOnlyFromSessionClose` + `--calibrate --json` | `passed` | ordered evidence, not just presence; catches a route that publishes healthy early then emits close markers late |
| `CAL-C5-order-stable` | `C5` | Same facts under 5 same-replica delivery perturbations keep identical recovery signature | `catch_up` across all runs | identical `(NCatchUp, NRebuild)` recovery signature across runs | identical close-event count across runs | identical final mode and data integrity across runs | `TestC5_OrderStableAcrossRuns` + `--calibrate --json` | `passed` | five patterns: baseline, pre-assign probe, pre-assign storm (8 concurrent), repeat assign, staggered assign (5 concurrent); A1/A4 pressure within the limits of the "same facts" boundary |
## C4 Evidence Shape
The C4 check is in trace ORDER, not presence:
1. `event: SessionClosedCompleted` appears at some index K.
2. `decision: none (R >= H)` — the ONLY engine path to Publication.Healthy — appears at index ≥ K. No occurrence before K is permitted; such an occurrence would prove healthy was declared before close processing.
3. At least one such decision must appear, otherwise the run never reached healthy and the proof is vacuous.
A buggy route that published healthy early and then later emitted the close markers still fails rule 2 deterministically.
## C5 Perturbation Patterns
Each C5 run uses identical facts (same R/S/H on both stores, same
identity) but varies delivery shape. All perturbations are
same-replica on purpose; wrong-replica events would land through
`checkReplicaID`'s pre-identity acceptance path and emit real
`PublishDegraded{r-other}` commands, which would contaminate the
comparison.
Post-assignment probes with pre-captured facts are also deliberately
omitted: after the engine converges, an incoming probe with the
original R (now stale) correctly triggers re-recovery — that's engine
correctness, not an A1/A4 leak, and including it would force C5 to
either pass vacuously or misattribute an engine change.
| Run | Pattern | What it stresses |
|---|---|---|
| 0 | baseline (assign + wait) | reference decision, signature, final mode |
| 1 | one valid pre-assign probe | pre-identity event acceptance and reset on identity arrival |
| 2 | 8 concurrent pre-assign probes | adapter-mutex contention under real concurrency before identity |
| 3 | two identical assignments in sequence | engine's monotonic identity check on equal-value re-assign |
| 4 | 5 concurrent identical assignments | concurrent idempotent re-assignment without signature drift |
All five runs must produce identical `Decision`, `FinalMode`,
`DataIntegrityOK`, AND `recoverySignature` (counts of `StartCatchUp`
and `StartRebuild` commands). Divergence on any of these is signaled
explicitly in the report — `Decision` or `FinalMode` flips to
`DIVERGED_ACROSS_RUNS`, or `CommandPath` gets a
`DIVERGED_ACROSS_RUNS_RECOVERY_SIG` sentinel element prepended.
Verified green under `-count=10` stress as of 2026-04-14.
## Evidence: Decision Attribution
The harness derives `Observed.Decision` from the command log, not from
the final projection. After a successful recovery the engine resets
`RecoveryDecision` to `none`; the calibration question is what the
engine chose to do, which is visible in whether `StartCatchUp` or
`StartRebuild` was emitted. Reading the final projection instead
would collapse every recovery to `none` and silently make the catch-up
vs rebuild distinction disappear. This is recorded here because it
is a real choice, not an accident.
## Anti-Pattern Evidence Map
First-pass coverage of the anti-patterns Phase 06 must calibrate:
| Anti-pattern | Primary scenario | Evidence strength | Status |
|---|---|---|---|
| `A1` (heartbeat timing defines recovery) | `CAL-C5-order-stable` | 5 same-replica delivery patterns with real concurrent goroutine contention; same `Decision` + `FinalMode` + `recoverySignature` across all | first-pass covered within the "same facts" boundary; real-topology/real-heartbeat pressure belongs to later phases |
| `A4` (event ordering defines semantics) | `CAL-C5-order-stable` | same 5 patterns include pre-assign events, concurrent assigns, and idempotent re-delivery; identical recovery signature across all | first-pass covered within the "same facts" boundary |
| `A3` (ack/progress defines terminal success) | `CAL-C4-terminal-close-only` | ordered trace check: `decision: none (R >= H)` only appears after `event: SessionClosedCompleted` | first-pass covered |
| `A7` (transport mechanics leak into engine) | `CAL-C1`-`CAL-C4` all go through real transport; no transport-shaped divergence observed | structural, not adversarial | first-pass supported; a dedicated adversarial A7 scenario (injected transport failure, concurrent shutdown, etc.) remains an open next-step if a divergence suggests one |
Evidence honesty notes:
- `A1`/`A4` coverage is bounded by the "same facts" constraint. Probes that arrive post-convergence with pre-captured (now stale) facts are NOT part of this set, because the engine legitimately re-enters recovery when fact-carrying events refresh R/S/H. That is engine correctness, not an A1/A4 leak, and including it would either loosen the pass criterion to vacuity or misattribute engine behavior.
- `A7` evidence remains structural (all C1-C4 use the real transport stack end-to-end) rather than adversarial. A future calibration that injects transport failures mid-session would strengthen this.
## Notes By Family
### C1
Focus:
1. no unnecessary recovery session
2. repeated probe/observe cycle remains semantically stable
### C2
Focus:
1. retained-window short gap remains `catch_up`
2. no silent widening into `rebuild`
### C3
Focus:
1. beyond-window long gap remains `rebuild`
2. no accidental downgrade into `catch_up`
### C4
Focus:
1. terminal truth still comes only from explicit session close
2. progress and transport success do not redefine final truth
### C5
Focus:
1. same facts still mean same decision
2. timing/order variation does not become hidden semantic input
## Update Rule
When a scenario changes state:
1. update the `Status` column
2. fill `Evidence Artifact`
3. add a short note if expectation changed or divergence appeared
If expected and observed results differ, also create or update the
matching entry in `divergence-log.md`.