From de673d8af88912a83cc31ff7550a69afbeb98e77 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 17:43:36 +0100 Subject: [PATCH 01/12] feat(recordlog): move the record log port to its consumers The record log port now lives in internal/recordlog, as ADR-0091 decides: the Log port, its Reader and Stats, the Holding state whose zero value is unknown, the segment and manifest types, and the port's refusals. The package imports no file-system package. internal/segmentlog is the segments kind behind it: Open and Inspect take a recordlog.Config, refuse the zero kind, and read lines back through the directory handle the writer holds, failing the log on any mismatch. internal/trailfile names the kind in one place and reads export, cursors and reindex through the Reader; an unknown holding state is an error, never free. trail segments prints from Stats and says unknown where another process cannot see the writer's bounds. Conformance cases 10 to 13 join the port's suite, each with its negative control. Signed-off-by: Konrad Karauda --- cmd/guardana-gateway/collect_bound_test.go | 5 +- cmd/guardana-gateway/segments.go | 46 ++-- cmd/guardana-gateway/segments_test.go | 68 +++++ internal/docscheck/ports_test.go | 12 +- internal/recordlog/deps_test.go | 100 +++++++ internal/recordlog/doc.go | 5 + internal/recordlog/errors.go | 39 +++ internal/recordlog/port.go | 179 ++++++++++++ internal/recordlog/port_test.go | 76 ++++++ internal/recordlog/segment.go | 116 ++++++++ internal/segmentlog/conformance_test.go | 127 ++++++--- internal/segmentlog/crash_test.go | 12 +- internal/segmentlog/doc.go | 6 +- internal/segmentlog/durable_test.go | 18 +- internal/segmentlog/errors.go | 40 ++- internal/segmentlog/helpers_test.go | 33 ++- internal/segmentlog/holds.go | 107 ++++++++ internal/segmentlog/manifest.go | 8 +- internal/segmentlog/manifest_test.go | 4 +- internal/segmentlog/port.go | 254 +++++++----------- internal/segmentlog/port_test.go | 236 ++++++++++++++++ internal/segmentlog/segments.go | 23 +- internal/segmentlog/segments_test.go | 23 +- internal/segmentlog/view.go | 187 ++++++++----- internal/segmentlog/view_test.go | 62 ++--- internal/segmentlog/write.go | 7 +- internal/trailfile/held.go | 108 +------- internal/trailfile/kind.go | 28 ++ internal/trailfile/log.go | 44 ++- internal/trailfile/log_holding_test.go | 61 +++++ internal/trailfile/log_test.go | 3 +- internal/trailfile/segments.go | 100 ++++--- scripts/ports.txt | 2 +- ...ers-as-the-log-did-when-it-was-opened.json | 18 ++ ...ad-back-of-another-line-fails-the-log.json | 17 ++ ...past-the-retained-lines-fails-the-log.json | 13 + ...-writer-holds-the-log-until-it-closes.json | 17 ++ 37 files changed, 1624 insertions(+), 580 deletions(-) create mode 100644 cmd/guardana-gateway/segments_test.go create mode 100644 internal/recordlog/deps_test.go create mode 100644 internal/recordlog/doc.go create mode 100644 internal/recordlog/errors.go create mode 100644 internal/recordlog/port.go create mode 100644 internal/recordlog/port_test.go create mode 100644 internal/recordlog/segment.go create mode 100644 internal/segmentlog/holds.go create mode 100644 internal/segmentlog/port_test.go create mode 100644 internal/trailfile/kind.go create mode 100644 internal/trailfile/log_holding_test.go create mode 100644 testdata/ports/record-log/10-a-reader-answers-as-the-log-did-when-it-was-opened.json create mode 100644 testdata/ports/record-log/11-a-read-back-of-another-line-fails-the-log.json create mode 100644 testdata/ports/record-log/12-a-read-back-past-the-retained-lines-fails-the-log.json create mode 100644 testdata/ports/record-log/13-a-writer-holds-the-log-until-it-closes.json diff --git a/cmd/guardana-gateway/collect_bound_test.go b/cmd/guardana-gateway/collect_bound_test.go index b1839e39e..926af35e2 100644 --- a/cmd/guardana-gateway/collect_bound_test.go +++ b/cmd/guardana-gateway/collect_bound_test.go @@ -15,7 +15,6 @@ import ( "github.com/guardana/control/adapters/otel" controlv1 "github.com/guardana/control/api/gen/go/guardana/control/v1" - "github.com/guardana/control/internal/evidence" "github.com/guardana/control/internal/segmentlog" "github.com/guardana/control/internal/trailfile" ) @@ -202,7 +201,7 @@ func TestPruneRemovesSealedSegmentsAndLeavesTheirTombstones(t *testing.T) { if _, err := os.Stat(filepath.Join(dir, "segment-00000002.jsonl")); err != nil { t.Errorf("the segment after the pruned one is gone: %v", err) } - v, err := segmentlog.Inspect(dir, evidence.MaxLineBytes) + v, err := trailfile.InspectLog(dir) if err != nil { t.Fatal(err) } @@ -261,7 +260,7 @@ func TestPruneCountsSegmentsFromTheDroppedOnes(t *testing.T) { if _, err := os.Stat(filepath.Join(dir, "segment-00000003.jsonl")); err != nil { t.Errorf("prune through 2 removed segment 3's file: %v", err) } - v, err := segmentlog.Inspect(dir, evidence.MaxLineBytes) + v, err := trailfile.InspectLog(dir) if err != nil { t.Fatal(err) } diff --git a/cmd/guardana-gateway/segments.go b/cmd/guardana-gateway/segments.go index 9702129ea..bc5ec94b4 100644 --- a/cmd/guardana-gateway/segments.go +++ b/cmd/guardana-gateway/segments.go @@ -11,58 +11,56 @@ import ( "strings" "time" - "github.com/guardana/control/internal/evidence" - "github.com/guardana/control/internal/segmentlog" + "github.com/guardana/control/internal/recordlog" "github.com/guardana/control/internal/trailfile" ) const pruneForm = "--through " -// trailSegments prints what the manifest of a directory of segments names: -// the counts of sealed, pruned and dropped segments against the most a -// manifest holds, then one line per segment and one for the live segment, -// each with the key a cursor names it by, reading and writing nothing else. -// It exits 1 when the directory is no log this build reads. +// trailSegments prints what the log in a directory of segments holds: its +// statistics, the counts of sealed, pruned and dropped segments against the +// most a manifest holds, then one line per segment and one for the live +// segment, each with the key a cursor names it by, reading and writing +// nothing else. It exits 1 when the directory is no log this build reads, or +// whether a collector holds it is unknown. func trailSegments(dir string, stdout, stderr io.Writer) int { - v, err := segmentlog.Inspect(dir, evidence.MaxLineBytes) + v, err := trailfile.InspectLog(dir) if err != nil { return fail(stderr, "trail segments", err) } - held, err := v.Held() + held, err := v.Holding().Held() if err != nil { return fail(stderr, "trail segments", err) } - m := v.Manifest() + m, st := v.Manifest(), v.Stats() collector := "none" if held { collector = "holds it" } - sealed := 0 - for _, s := range m.Segments { - if s.State == segmentlog.StateSealed { - sealed++ - } - } var b strings.Builder - fmt.Fprintf(&b, "tenant=%s project=%s retained_bytes=%d collector=%s\n", shown(m.Tenant), shown(m.Project), m.Retained, collector) - fmt.Fprintf(&b, "segments sealed=%d pruned=%d dropped=%d most=%d\n", sealed, len(m.Segments)-sealed, m.Dropped, - segmentlog.MaxSegments) + fmt.Fprintf(&b, "tenant=%s project=%s retained_bytes=%d collector=%s\n", shown(m.Tenant), shown(m.Project), st.Retained, collector) + fmt.Fprintf(&b, "segments sealed=%d pruned=%d dropped=%d most=%d\n", st.Sealed, st.Pruned, st.Dropped, + st.Bounds.MaxSegments) + // The byte bounds and the budget's refusals are the collector's, which a + // reader in another process does not see. + fmt.Fprintf(&b, "kind=%s max_line_bytes=%d segment_bytes=unknown max_bytes=unknown budget_refusals=unknown\n", st.Kind, + st.Bounds.MaxLineBytes) for _, s := range m.Segments { - k := segmentlog.SegmentKey(s.Seq, s.First) + k := recordlog.SegmentKey(s.Seq, s.First) fmt.Fprintf(&b, "segment=%d state=%s lines=%d bytes=%d key=%s sealed_at=%s", s.Seq, s.State, s.Lines, s.Bytes, hex.EncodeToString(k[:]), s.SealedAt.Format(time.RFC3339)) - if s.State == segmentlog.StatePruned { + if s.State == recordlog.StatePruned { b.WriteString(" pruned_at=" + s.PrunedAt.Format(time.RFC3339)) } b.WriteString("\n") } key := "none" if m.Live.Lines > 0 { - k := segmentlog.SegmentKey(m.Live.Seq, m.Live.First) + k := recordlog.SegmentKey(m.Live.Seq, m.Live.First) key = hex.EncodeToString(k[:]) } fmt.Fprintf(&b, "segment=%d state=live lines=%d bytes=%d key=%s tail_bytes=%d\n", m.Live.Seq, m.Live.Lines, - m.Live.Bytes, key, v.Tail()) + m.Live.Bytes, key, m.Tail) if _, err := io.WriteString(stdout, b.String()); err != nil { return fail(stderr, "trail segments", errors.Join(errors.New("writing to standard output"), err)) } @@ -90,7 +88,7 @@ func declarePrune(flags *flag.FlagSet) commandFunc { // before its file is unlinked. A collector holding the log is refused, so it // is stopped first. func prune(dir string, through int, stdout, stderr io.Writer) int { - v, err := segmentlog.Inspect(dir, evidence.MaxLineBytes) + v, err := trailfile.InspectLog(dir) if err != nil { return fail(stderr, "prune", err) } diff --git a/cmd/guardana-gateway/segments_test.go b/cmd/guardana-gateway/segments_test.go new file mode 100644 index 000000000..89e4a79fa --- /dev/null +++ b/cmd/guardana-gateway/segments_test.go @@ -0,0 +1,68 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + controlv1 "github.com/guardana/control/api/gen/go/guardana/control/v1" + "github.com/guardana/control/internal/segmentlog" + "github.com/guardana/control/internal/trailfile" +) + +// TestTrailSegmentsPrintsTheLogsStats: the counts and the bounds a reader +// knows are printed, and those only the collector knows say unknown; a log +// whose holding cannot be asked exits 1 and prints nothing. +func TestTrailSegmentsPrintsTheLogsStats(t *testing.T) { + dir := prunedLog(t) + status, stdout, stderr := trailCommand(t, "segments", dir) + for _, want := range []string{ + "segments sealed=1 pruned=1 dropped=0 most=10000\n", + "kind=segments max_line_bytes=786432 segment_bytes=unknown max_bytes=unknown budget_refusals=unknown\n", + "collector=none\n", + } { + if !strings.Contains(stdout, want) { + t.Errorf("trail segments printed\n%s\nwithout %q", stdout, want) + } + } + if status != exitOK || stderr != "" { + t.Fatalf("trail segments: %d, %q", status, stderr) + } + + lock := filepath.Join(dir, segmentlog.LockName) + if err := os.Remove(lock); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(lock, 0o700); err != nil { + t.Fatal(err) + } + status, stdout, stderr = trailCommand(t, "segments", dir) + if status != exitFail || stdout != "" || !strings.Contains(stderr, "unknown") { + t.Errorf("trail segments with the holding unknown: %d, %q, %q; want exit %d naming it unknown", status, stdout, stderr, exitFail) + } +} + +// prunedLog is a closed log of three segments, the first pruned, the second +// sealed and the third live. +func prunedLog(t *testing.T) string { + t.Helper() + dir := filepath.Join(t.TempDir(), "log") + l, err := trailfile.OpenLog(trailfile.LogConfig{Dir: dir, Tenant: "t1", Project: "p1", SegmentBytes: 1, MaxBytes: 1 << 20}) + if err != nil { + t.Fatal(err) + } + for _, ev := range trailOf("a", kProposed, kDecided, kStarted) { + if err := l.Append(context.Background(), []*controlv1.Event{ev}); err != nil { + t.Fatal(err) + } + } + if err := l.Prune(1); err != nil { + t.Fatal(err) + } + if err := l.Close(); err != nil { + t.Fatal(err) + } + return dir +} diff --git a/internal/docscheck/ports_test.go b/internal/docscheck/ports_test.go index 2ce0436ca..31070d9ed 100644 --- a/internal/docscheck/ports_test.go +++ b/internal/docscheck/ports_test.go @@ -415,7 +415,7 @@ func TestPortsListEveryPortWhole(t *testing.T) { } var problems []string found := documentedPorts(repoFS(t), goFiles, &problems) - for _, iface := range []string{"internal/trust.Roster", "internal/operators.Authenticator", "internal/operators.Authorizer", "internal/segmentlog.RecordLog", "internal/gateway.ApprovalAuthority"} { + for _, iface := range []string{"internal/trust.Roster", "internal/operators.Authenticator", "internal/operators.Authorizer", "internal/recordlog.Log", "internal/gateway.ApprovalAuthority"} { if !slices.Contains(found, iface) { t.Errorf("%s is not documented as a port, so the documented side would check nothing: found %q", iface, found) } @@ -549,14 +549,14 @@ func TestPortProblemsRefuseEachPlantedDefect(t *testing.T) { replaceIn(t, s, portsFile, trustLine, strings.Replace(trustLine, " file ", " ", 1)) }, "none of them empty"}, "the interface is a struct": {func(s fstest.MapFS) { - addLine(s, "record-log internal/segmentlog.Config segments testdata/ports/record-log none") - }, "is a type of internal/segmentlog that is not an interface"}, + addLine(s, "record-log internal/recordlog.Config segments testdata/ports/record-log none") + }, "is a type of internal/recordlog that is not an interface"}, "the interface is unexported": {func(s fstest.MapFS) { - addLine(s, "record-log internal/segmentlog.recordLog segments testdata/ports/record-log none") + addLine(s, "record-log internal/recordlog.reader segments testdata/ports/record-log none") }, "does not name an exported type"}, "the package declares no such type": {func(s fstest.MapFS) { - addLine(s, "record-log internal/segmentlog.Journal segments testdata/ports/record-log none") - }, "is not a type declared in internal/segmentlog"}, + addLine(s, "record-log internal/recordlog.Journal segments testdata/ports/record-log none") + }, "is not a type declared in internal/recordlog"}, "the conformance directory is absent": {func(s fstest.MapFS) { removeUnder(s, "testdata/ports/record-log") }, "conformance directory testdata/ports/record-log is absent"}, diff --git a/internal/recordlog/deps_test.go b/internal/recordlog/deps_test.go new file mode 100644 index 000000000..813401df9 --- /dev/null +++ b/internal/recordlog/deps_test.go @@ -0,0 +1,100 @@ +package recordlog + +import ( + "go/parser" + "go/token" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + + "github.com/guardana/control/internal/brand" +) + +// kindTree is the kind a port package must not reach. +const kindTree = "/internal/segmentlog" + +// refusedImports are the packages that would hand a consumer files: the port +// names no file-system type. +var refusedImports = []string{"os", "io/fs", "io/ioutil", "path/filepath", "syscall", "golang.org/x/sys/unix"} + +// TestThePortImportsNoFileSystemTypes: no Go file of the package, whatever +// its build constraints, imports a package of file-system types or the kind. +func TestThePortImportsNoFileSystemTypes(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + read := 0 + for _, name := range files { + if strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(token.NewFileSet(), name, nil, parser.ImportsOnly) + if err != nil { + t.Fatal(err) + } + read++ + for _, spec := range f.Imports { + path, err := strconv.Unquote(spec.Path.Value) + if err != nil { + t.Fatal(err) + } + if refusedImport(path) { + t.Errorf("%s imports %s", name, path) + } + } + } + // A glob that found only tests examined nothing, and would pass. + if read < 3 { + t.Fatalf("read the imports of %d production file(s); the package has more", read) + } +} + +func refusedImport(path string) bool { + return slices.Contains(refusedImports, path) || path == brand.ModulePath+kindTree || + strings.HasPrefix(path, brand.ModulePath+kindTree+"/") +} + +// TestThePortReachesNoKind: no package the port depends on, on this platform +// or on windows, is the kind. +func TestThePortReachesNoKind(t *testing.T) { + for _, goos := range []string{"linux", "darwin", "windows"} { + cmd := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}}", ".") + cmd.Env = append(os.Environ(), "GOOS="+goos) + out, err := cmd.Output() + if err != nil { + t.Fatalf("GOOS=%s go list -deps: %v", goos, err) + } + deps := strings.Fields(string(out)) + // A listing that does not reach the package itself examined some + // other package, and would pass whatever it found. + if !slices.Contains(deps, brand.ModulePath+"/internal/recordlog") { + t.Fatalf("GOOS=%s: go list -deps reached %d package(s), not this one; nothing was examined", goos, len(deps)) + } + for _, dep := range deps { + if dep == brand.ModulePath+kindTree || strings.HasPrefix(dep, brand.ModulePath+kindTree+"/") { + t.Errorf("GOOS=%s: the port reaches %s", goos, dep) + } + } + } +} + +// TestTheImportCheckRefusesEachPackage: each refused package and the kind are +// refused, and the packages the port does import are not, so the check above +// can fail. +func TestTheImportCheckRefusesEachPackage(t *testing.T) { + for _, path := range append(slices.Clone(refusedImports), brand.ModulePath+kindTree, brand.ModulePath+kindTree+"/x") { + if !refusedImport(path) { + t.Errorf("%s is not refused", path) + } + } + for _, path := range []string{"io", "context", "time", "crypto/sha256", brand.ModulePath + "/internal/brand", "osx"} { + if refusedImport(path) { + t.Errorf("%s is refused", path) + } + } +} diff --git a/internal/recordlog/doc.go b/internal/recordlog/doc.go new file mode 100644 index 000000000..f01c78dc9 --- /dev/null +++ b/internal/recordlog/doc.go @@ -0,0 +1,5 @@ +// Package recordlog declares the record log port: whole lines kept in +// numbered segments, written through Log and read through Reader. It names +// no kind's files or handles, so a kind, such as internal/segmentlog's +// segments, implements both and brings no reader of its own to a consumer. +package recordlog diff --git a/internal/recordlog/errors.go b/internal/recordlog/errors.go new file mode 100644 index 000000000..051f7a791 --- /dev/null +++ b/internal/recordlog/errors.go @@ -0,0 +1,39 @@ +package recordlog + +// Error is a refusal a consumer of the port matches with errors.Is, whatever +// the kind. They are constants, so no other code in the binary can reassign +// one and turn a refusal into a pass. +type Error string + +// Error returns the refusal's text. +func (e Error) Error() string { return string(e) } + +const ( + // ErrKind is a kind the opener does not know, the zero Kind included. + ErrKind Error = "recordlog: unknown kind" + // ErrConfig is a configuration no log opens with. + ErrConfig Error = "recordlog: the configuration is refused" + // ErrBinding is a log bound to another tenant or project. + ErrBinding Error = "recordlog: the log is bound to another tenant or project" + // ErrBudget is an append the log's byte bound refuses, or any append to a + // log opened with no bound. + ErrBudget Error = "recordlog: the log is at its byte bound; an operator prunes sealed segments" + // ErrFull is a seal past the most segments the log names. + ErrFull Error = "recordlog: the log names the most segments it may" + // ErrLines is an append that is not whole lines. + ErrLines Error = "recordlog: an append is whole lines, each ending in a newline" + // ErrPrune is a prune that names no sealed segment, or the live one, and + // an open of a segment that is neither sealed nor live. + ErrPrune Error = "recordlog: a prune names sealed segments only" + // ErrClosed is a call on a log that is closed. + ErrClosed Error = "recordlog: the log is closed" + // ErrFailed is a call on a log a seal or a prune left part way, whose live + // segment changed under it, or whose read-back found a line other than it + // wrote: until it is opened again the log takes nothing more. + ErrFailed Error = "recordlog: a seal or a prune stopped part way, or a segment changed; open the log again" + // ErrMoved is a segment that a seal or a prune moved between the read of + // the log and the open of the segment. + ErrMoved Error = "recordlog: the segment moved while it was opened" + // ErrHoldingUnknown is a holding state of unknown asked as held or free. + ErrHoldingUnknown Error = "recordlog: whether a writer holds the log is unknown" +) diff --git a/internal/recordlog/port.go b/internal/recordlog/port.go new file mode 100644 index 000000000..1dec0bccc --- /dev/null +++ b/internal/recordlog/port.go @@ -0,0 +1,179 @@ +package recordlog + +import ( + "context" + "crypto/sha256" + "io" + "strconv" + "time" + + "github.com/guardana/control/internal/brand" +) + +// Kind is how a log keeps its segments. The zero Kind names none, and every +// opener refuses it. +type Kind string + +// KindSegments keeps a log as a directory of segment files and a manifest +// naming each one. +const KindSegments Kind = "segments" + +// Digest is the SHA-256 of one line, its newline included. +type Digest [sha256.Size]byte + +// Bounds bound a log. SegmentBytes bounds a live segment before it is sealed +// and MaxBytes the bytes of every segment not pruned: both zero refuses every +// append, otherwise MaxBytes is at least twice SegmentBytes. MaxLineBytes +// bounds a line before its newline, from 1. MaxSegments bounds the segments, +// sealed and pruned, the log names; zero is the kind's own bound. +type Bounds struct { + SegmentBytes, MaxBytes int64 + MaxLineBytes, MaxSegments int +} + +// Config is what a log opens with, to write or to read. +type Config struct { + Kind Kind + // Location is where the log is: for KindSegments, a directory. + Location string + // Tenant and Project bind the log: a new log records them, and an + // existing one bound to another is refused. + Tenant, Project string + // LogID names the log in its manifest; empty writes no name. + LogID string + Bounds Bounds + // Visit, when set, is handed every whole line the log holds at open, + // sealed segments first and in order; an error refuses the open. + Visit func(line []byte) error + // Now dates seals and prunes. + Now func() time.Time +} + +// Span is one line a log wrote: its offset over the lines of the segments not +// pruned, read in order, its length, its newline included, and its digest. +type Span struct { + Offset, Size int64 + Sum Digest +} + +// Log is the record log port: it keeps whole lines in segments. Append +// returns nil only once the lines are durable. Every method of a log that is +// closed, or that has failed, refuses. +type Log interface { + // Append writes whole lines to the live segment, sealing it first when + // they would take it past its byte bound, and refuses them with + // ErrBudget when they would take the log past its own. + Append(ctx context.Context, lines []byte) error + // Seal seals the live segment; a live segment with no line stays. + Seal() error + // Prune prunes the sealed segments numbered through, and every one + // before it, keeping what each held as its tombstone. + Prune(through int) error + // Locate answers what the segment SegmentKey names is now. Its zero + // value is StateUnknown. + Locate(key Digest) SegmentAnswer + // Manifest is the log as it is now. + Manifest() Manifest + // Holds reads back each span where the log wrote it and refuses unless + // every one holds a line of its digest. Any mismatch, and any read that + // fails, fails the log with ErrFailed. + Holds(ctx context.Context, spans []Span) error + // Stats is what the log counts now. + Stats() Stats + Close() error +} + +// Holding is whether a writer holds a log. Its zero value is HoldingUnknown, +// which is never free. +type Holding uint8 + +const ( + // HoldingUnknown is a holding the reader could not learn. + HoldingUnknown Holding = iota + // HoldingHeld is a log a writer holds. + HoldingHeld + // HoldingFree is a log no writer holds. + HoldingFree +) + +// String names the holding state. +func (h Holding) String() string { + switch h { + case HoldingHeld: + return "held" + case HoldingFree: + return "free" + default: + return "unknown" + } +} + +// Held answers whether a writer holds the log: true when held, false when +// free, and ErrHoldingUnknown for any other state. +func (h Holding) Held() (bool, error) { + switch h { + case HoldingHeld: + return true, nil + case HoldingFree: + return false, nil + default: + return false, ErrHoldingUnknown + } +} + +// Content is one segment's lines as opened, read at offsets up to its Size. +type Content interface { + io.ReaderAt + io.Closer + // Size is the bytes a reader takes, those the segment held when opened. + Size() int64 +} + +// Reader reads a log as it was when the reader was opened, holding no lock and +// writing nothing; a writer may seal or prune meanwhile, and an open of a +// segment that moved since is ErrMoved. +type Reader interface { + // Manifest is the log as the reader found it. + Manifest() Manifest + // Locate answers for the segment SegmentKey names. + Locate(key Digest) SegmentAnswer + // First is the first segment not pruned: the first sealed one, or the + // live one when every sealed one was pruned. + First() SegmentAnswer + // After is the segment that follows seq, sealed, pruned or live; its + // state is StateUnknown when there is none. + After(seq int) SegmentAnswer + // Open opens a sealed or the live segment. One that is neither is + // ErrPrune, and one a seal or a prune moved since is ErrMoved. + Open(s Segment) (Content, error) + // Holding asks now whether a writer holds the log. + Holding() Holding + // Stats is what the reader found. A reader counts no refusal of a + // writer, and knows the byte bounds only as its own Config gave them. + Stats() Stats +} + +// Stats is what a log counts: its kind, the segments sealed, pruned with a +// tombstone, and dropped with theirs, the bytes of the segments not pruned, +// its bounds, and the appends its byte bound refused. +type Stats struct { + Kind Kind + Sealed, Pruned, Dropped int + Retained int64 + Bounds Bounds + BudgetRefusals uint64 +} + +// keyPrefix starts what a segment's key is the SHA-256 of. It is the format +// name of the segments manifest, so the keys stay those cursors already name. +const keyPrefix = brand.OTelNamespace + ".segments/" + +// SegmentKey is what names segment seq whose first line has the digest first +// to a reader: the SHA-256 of the segments manifest's format name, "/", seq +// in decimal, "/" and the 32 bytes of first. A segment keeps its key when it +// is sealed, and no two segments of one log have one, as no number is given +// twice. +func SegmentKey(seq int, first Digest) Digest { + b := append(strconv.AppendInt([]byte(keyPrefix), int64(seq), 10), '/') + return sha256.Sum256(append(b, first[:]...)) +} diff --git a/internal/recordlog/port_test.go b/internal/recordlog/port_test.go new file mode 100644 index 000000000..583748bc2 --- /dev/null +++ b/internal/recordlog/port_test.go @@ -0,0 +1,76 @@ +package recordlog + +import ( + "crypto/sha256" + "errors" + "testing" + + "github.com/guardana/control/internal/brand" +) + +// TestAHoldingOfUnknownIsNeverFree: only the held and the free state answer +// without an error; the zero value, and any value outside the three, is +// ErrHoldingUnknown and never reads as free. +func TestAHoldingOfUnknownIsNeverFree(t *testing.T) { + var zero Holding + for _, h := range []Holding{zero, HoldingUnknown, Holding(3), Holding(255)} { + held, err := h.Held() + if !errors.Is(err, ErrHoldingUnknown) || held { + t.Errorf("holding %d (%s) = %v, %v; want ErrHoldingUnknown", h, h, held, err) + } + if h.String() != "unknown" { + t.Errorf("holding %d is named %q", h, h) + } + } + if held, err := HoldingHeld.Held(); err != nil || !held { + t.Errorf("HoldingHeld = %v, %v; want held", held, err) + } + if held, err := HoldingFree.Held(); err != nil || held { + t.Errorf("HoldingFree = %v, %v; want free", held, err) + } +} + +// TestAnAnswerNamesASegmentOnlyWhenItKnowsOne: the zero answer and one found +// of no state are unknown, name no segment and say why; one found names its +// segment and its state. +func TestAnAnswerNamesASegmentOnlyWhenItKnowsOne(t *testing.T) { + seg := Segment{Seq: 2, State: StateSealed, Lines: 1, Bytes: 4, File: "two"} + for name, a := range map[string]SegmentAnswer{ + "zero": {}, "not found": NotFound("gone"), "found of no state": Found(Segment{Seq: 2, File: "two"}), + } { + if a.State() != StateUnknown || a.Segment() != (Segment{}) || a.Cause() == "" { + t.Errorf("%s: state %s, segment %+v, cause %q", name, a.State(), a.Segment(), a.Cause()) + } + } + if a := Found(seg); a.State() != StateSealed || a.Segment() != seg { + t.Errorf("found: %s, %+v", a.State(), a.Segment()) + } + if NotFound("gone").Cause() != "gone" { + t.Error("a cause given is not the one said") + } +} + +// TestASegmentKeyIsItsNumberAndFirstLine: the key is the SHA-256 of the +// segments format name, the number and the first line's digest, as cursors +// already name segments. +func TestASegmentKeyIsItsNumberAndFirstLine(t *testing.T) { + first := Digest(sha256.Sum256([]byte("aaa\n"))) + want := sha256.Sum256(append([]byte(brand.OTelNamespace+".segments/12/"), first[:]...)) + if got := SegmentKey(12, first); got != want { + t.Errorf("SegmentKey(12, aaa) = %x, want %x", got, want) + } + if SegmentKey(1, first) == SegmentKey(11, first) || SegmentKey(1, first) == SegmentKey(1, Digest{}) { + t.Error("two segments share a key") + } +} + +// TestManifestCountsSealedAndPrunedApart: the counts take the state of each +// segment named, and nothing of the live one. +func TestManifestCountsSealedAndPrunedApart(t *testing.T) { + m := Manifest{Dropped: 4, Live: Segment{State: StateLive, Lines: 3}, Segments: []Segment{ + {State: StatePruned}, {State: StatePruned}, {State: StateSealed}, {State: StateSealed}, {State: StateSealed}, + }} + if sealed, pruned := m.Counts(); sealed != 3 || pruned != 2 { + t.Errorf("Counts = %d sealed, %d pruned; want 3 and 2", sealed, pruned) + } +} diff --git a/internal/recordlog/segment.go b/internal/recordlog/segment.go new file mode 100644 index 000000000..79a7017e2 --- /dev/null +++ b/internal/recordlog/segment.go @@ -0,0 +1,116 @@ +package recordlog + +import "time" + +// State is what a segment is. +type State uint8 + +const ( + // StateUnknown is a segment the log does not name, or names more than + // once. It is the zero value. + StateUnknown State = iota + // StateLive is the segment appends go to. + StateLive + // StateSealed is a segment no append changes. + StateSealed + // StatePruned is a sealed segment an operator removed; its tombstone + // keeps what it held. + StatePruned +) + +// String names the state as a manifest spells it. +func (s State) String() string { + switch s { + case StateLive: + return "live" + case StateSealed: + return "sealed" + case StatePruned: + return "pruned" + default: + return "unknown" + } +} + +// Segment is what a log knows of one segment. +type Segment struct { + // Seq numbers the segment from 1, in the order it was sealed, and is + // never given again. + Seq int + State State + // Lines and Bytes are its whole lines and their bytes; First and Last the + // digests of its first and last line. + Lines, Bytes int64 + First, Last Digest + // SealedAt and PrunedAt date the seal and the prune; the live segment + // has neither. + SealedAt, PrunedAt time.Time + // File is the name the kind keeps the segment under, empty once pruned. + File string +} + +// Manifest is a log at one moment. +type Manifest struct { + Tenant, Project string + // Dropped is how many of the first segments were pruned and their + // tombstones dropped, to keep the log within its MaxSegments; Segments + // are the sealed and pruned segments after them, by Seq. Live is the live + // segment, with no line when Live.Lines is 0. + Dropped int + Segments []Segment + Live Segment + // Retained is the bytes of every segment not pruned, the live one's whole + // lines included. + Retained int64 + // Tail is the bytes after the live segment's last newline when a reader + // read it; a writer cuts them when it opens, so its own Tail is 0. + Tail int64 +} + +// Counts is how many of the segments m names are sealed and how many pruned +// with a tombstone. +func (m Manifest) Counts() (sealed, pruned int) { + for _, s := range m.Segments { + switch s.State { + case StateSealed: + sealed++ + case StatePruned: + pruned++ + } + } + return sealed, pruned +} + +// SegmentAnswer is what a locate found. Its zero value is StateUnknown. +type SegmentAnswer struct { + state State + cause string + seg Segment +} + +// Found is the answer naming s, of s's state. +func Found(s Segment) SegmentAnswer { return SegmentAnswer{state: s.State, seg: s} } + +// NotFound is an answer of StateUnknown, saying why. +func NotFound(cause string) SegmentAnswer { return SegmentAnswer{cause: cause} } + +// State is the segment's state, StateUnknown when no segment the log names +// has the key. +func (a SegmentAnswer) State() State { return a.state } + +// Cause says why the answer is StateUnknown. +func (a SegmentAnswer) Cause() string { + if a.state == StateUnknown && a.cause == "" { + return "nothing was located" + } + return a.cause +} + +// Segment is what the log knows of the segment, for an answer that is not +// StateUnknown. +func (a SegmentAnswer) Segment() Segment { + if a.state == StateUnknown { + return Segment{} + } + return a.seg +} diff --git a/internal/segmentlog/conformance_test.go b/internal/segmentlog/conformance_test.go index edeb27df1..1edad39a1 100644 --- a/internal/segmentlog/conformance_test.go +++ b/internal/segmentlog/conformance_test.go @@ -8,14 +8,27 @@ import ( "os" "path/filepath" "testing" + + "github.com/guardana/control/internal/recordlog" ) -// conformanceDir holds the RecordLog port's cases, each rule with a negative -// control that a kind must also pass. +// conformanceDir holds the record log port's cases, each rule with a +// negative control that a kind must also pass. const conformanceDir = "../../testdata/ports/record-log" +// opener is how a kind opens the port's two sides from one configuration. +type opener struct { + log func(recordlog.Config) (recordlog.Log, error) + read func(recordlog.Config) (recordlog.Reader, error) +} + // kinds are every kind the conformance cases run against. -var kinds = []string{KindSegments} +var kinds = map[recordlog.Kind]opener{ + recordlog.KindSegments: { + log: func(cfg recordlog.Config) (recordlog.Log, error) { return Open(cfg, Options{OpenLive: openTestLive}) }, + read: Inspect, + }, +} type conformanceCase struct { Rule string `json:"rule"` @@ -26,23 +39,35 @@ type conformanceCase struct { } // step is one call and what it must answer: an append of lines, or of raw -// bytes, a seal, a prune, a reopen, a reopen with other bounds, a locate of -// the segment of a number that a line begins, or the bytes retained. +// bytes, a seal, a prune, a close, a reopen, a reopen with other bounds, a +// read-back of lines at their offsets, a locate of the segment of a number +// that a line begins, the bytes retained, or whether a writer holds the log. +// A locate or a retained step with reader set asks a Reader opened then. type step struct { - Append []string `json:"append"` - Raw *string `json:"raw"` - Seal bool `json:"seal"` - Prune int `json:"prune"` - Reopen bool `json:"reopen"` - Bounds []int64 `json:"bounds"` - Locate string `json:"locate"` - Seq int `json:"seq"` - State string `json:"state"` - Retained *int64 `json:"retained"` - Want string `json:"want"` + Append []string `json:"append"` + Raw *string `json:"raw"` + Seal bool `json:"seal"` + Prune int `json:"prune"` + Close bool `json:"close"` + Reopen bool `json:"reopen"` + Bounds []int64 `json:"bounds"` + Holds []spanStep `json:"holds"` + Reader bool `json:"reader"` + Locate string `json:"locate"` + Seq int `json:"seq"` + State string `json:"state"` + Retained *int64 `json:"retained"` + Holding string `json:"holding"` + Want string `json:"want"` } -var wanted = map[string]error{"": nil, "budget": ErrBudget, "prune": ErrPrune, "lines": ErrLines} +// spanStep is a line read back at an offset over the lines retained. +type spanStep struct { + Line string `json:"line"` + Offset int64 `json:"offset"` +} + +var wanted = map[string]error{"": nil, "budget": ErrBudget, "prune": ErrPrune, "lines": ErrLines, "failed": ErrFailed} // TestEveryKindPassesTheConformanceCases runs every case and its negative // control against every kind. A case with no negative control, or one that @@ -66,19 +91,20 @@ func TestEveryKindPassesTheConformanceCases(t *testing.T) { if c.Rule == "" || len(c.Steps) == 0 || len(c.NegativeControl) == 0 { t.Fatalf("%s: a case names its rule, its steps and its negative control", path) } - for _, kind := range kinds { - t.Run(kind+"/"+filepath.Base(path), func(t *testing.T) { - runSteps(t, kind, c, c.Steps) - runSteps(t, kind, c, c.NegativeControl) + for kind, open := range kinds { + t.Run(string(kind)+"/"+filepath.Base(path), func(t *testing.T) { + runSteps(t, kind, open, c, c.Steps) + runSteps(t, kind, open, c, c.NegativeControl) }) } } } -func runSteps(t *testing.T, kind string, c conformanceCase, steps []step) { +func runSteps(t *testing.T, kind recordlog.Kind, open opener, c conformanceCase, steps []step) { t.Helper() - r := &runner{t: t, cfg: config(logDir(t), c.SegmentBytes, c.MaxBytes)} - r.cfg.Kind = kind + r := &runner{t: t, kind: open, cfg: recordlog.Config{Kind: kind, Location: logDir(t), Tenant: "t1", Project: "p1", + Bounds: recordlog.Bounds{SegmentBytes: c.SegmentBytes, MaxBytes: c.MaxBytes, MaxLineBytes: 1 << 10}, + Now: clockAt(1_800_000_000)}} r.open() defer func() { _ = r.l.Close() }() for i, s := range steps { @@ -94,22 +120,23 @@ func runSteps(t *testing.T, kind string, c conformanceCase, steps []step) { // runner is one kind's log under the steps of a case. type runner struct { - t *testing.T - cfg Config - l RecordLog + t *testing.T + kind opener + cfg recordlog.Config + l recordlog.Log } func (r *runner) open() { r.t.Helper() - l, err := Open(r.cfg) + l, err := r.kind.log(r.cfg) if err != nil { r.t.Fatal(err) } r.l = l } -// apply takes one step and returns what its call answered; a locate and a -// retained step check their own answer. +// apply takes one step and returns what its call answered; a step that asks +// checks its own answer. func (r *runner) apply(i int, s step) error { r.t.Helper() switch { @@ -121,6 +148,10 @@ func (r *runner) apply(i int, s step) error { return r.l.Seal() case s.Prune != 0: return r.l.Prune(s.Prune) + case s.Holds != nil: + return r.l.Holds(context.Background(), spans(s.Holds)) + case s.Close: + return r.l.Close() case s.Reopen || s.Bounds != nil: r.reopen(s.Bounds) default: @@ -129,11 +160,19 @@ func (r *runner) apply(i int, s step) error { return nil } +func spans(steps []spanStep) []recordlog.Span { + out := make([]recordlog.Span, 0, len(steps)) + for _, s := range steps { + out = append(out, recordlog.Span{Offset: s.Offset, Size: int64(len(s.Line)) + 1, Sum: sum(s.Line)}) + } + return out +} + // reopen closes the log and opens it again, with other bounds when given. func (r *runner) reopen(bounds []int64) { r.t.Helper() if bounds != nil { - r.cfg.SegmentBytes, r.cfg.MaxBytes = bounds[0], bounds[1] + r.cfg.Bounds.SegmentBytes, r.cfg.Bounds.MaxBytes = bounds[0], bounds[1] } if err := r.l.Close(); err != nil { r.t.Fatal(err) @@ -141,19 +180,39 @@ func (r *runner) reopen(bounds []int64) { r.open() } -// check takes a step that asks what the log answers. +// answerer is what the port's two sides both answer. +type answerer interface { + Locate(key recordlog.Digest) recordlog.SegmentAnswer + Manifest() recordlog.Manifest +} + +// check takes a step that asks what the log, or a reader of it, answers. func (r *runner) check(i int, s step) { r.t.Helper() + var a answerer = r.l + if s.Reader || s.Holding != "" { + reader, err := r.kind.read(r.cfg) + if err != nil { + r.t.Fatalf("step %d: opening a reader: %v", i, err) + } + if s.Holding != "" { + if got := reader.Holding().String(); got != s.Holding { + r.t.Errorf("step %d: the log is %s, want %s", i, got, s.Holding) + } + return + } + a = reader + } switch { case s.Locate != "": if s.Seq < 1 { r.t.Fatalf("step %d locates no segment number", i) } - if got := r.l.Locate(SegmentKey(s.Seq, sum(s.Locate))).State().String(); got != s.State { + if got := a.Locate(recordlog.SegmentKey(s.Seq, sum(s.Locate))).State().String(); got != s.State { r.t.Errorf("step %d: %s of segment %d is located %s, want %s", i, s.Locate, s.Seq, got, s.State) } case s.Retained != nil: - if got := r.l.Manifest().Retained; got != *s.Retained { + if got := a.Manifest().Retained; got != *s.Retained { r.t.Errorf("step %d: %d bytes retained, want %d", i, got, *s.Retained) } default: diff --git a/internal/segmentlog/crash_test.go b/internal/segmentlog/crash_test.go index 76a760f39..23c5b7979 100644 --- a/internal/segmentlog/crash_test.go +++ b/internal/segmentlog/crash_test.go @@ -56,7 +56,7 @@ func (c *crashing) ops() fsOps { // crashOpen opens the log as a process that stops before its step at. It // returns the log when the open came through, and whether the crash came. -func crashOpen(t *testing.T, cfg Config, at int) (*segments, bool) { +func crashOpen(t *testing.T, cfg settings, at int) (*segments, bool) { t.Helper() c := &crashing{at: at} l, err := openWith(cfg, c.ops()) @@ -73,7 +73,7 @@ func crashOpen(t *testing.T, cfg Config, at int) (*segments, bool) { // recovered opens the log after a crash, first as a process that crashes // again at each step its open takes in turn, then as one that does not, and // returns what that last open visited and the log. -func recovered(t *testing.T, cfg Config) ([]string, *segments) { +func recovered(t *testing.T, cfg settings) ([]string, *segments) { t.Helper() for at := 1; ; at++ { l, crashed := crashOpen(t, cfg, at) @@ -90,7 +90,7 @@ func recovered(t *testing.T, cfg Config) ([]string, *segments) { // manifest replace changed nothing and leaves the log taking appends; one // stopped later leaves it refusing them. It reports whether the crash came // before the seal ended. -func sealCrashes(t *testing.T, cfg Config, at int) bool { +func sealCrashes(t *testing.T, cfg settings, at int) bool { t.Helper() l, _ := crashOpen(t, cfg, 1<<30) mustAppend(t, l, "aaa", "bbb") @@ -132,7 +132,7 @@ func TestACrashAtEverySealStepIsCompletedOrNeverBegun(t *testing.T) { // sealRecovered checks the log a seal crashed at step at left: the two lines // once each, live or sealed, and the next append taken. -func sealRecovered(t *testing.T, cfg Config, at int) { +func sealRecovered(t *testing.T, cfg settings, at int) { t.Helper() seen, l := recovered(t, cfg) if !slices.Equal(seen, []string{"aaa", "bbb"}) { @@ -158,7 +158,7 @@ func sealRecovered(t *testing.T, cfg Config, at int) { // pruneCrashes is the log a crash at step at of a prune leaves: two sealed // segments and a live one, then a prune of both sealed ones that stops // there. -func pruneCrashes(t *testing.T, cfg Config, at int) bool { +func pruneCrashes(t *testing.T, cfg settings, at int) bool { t.Helper() l, _ := crashOpen(t, cfg, 1<<30) mustAppend(t, l, "aaa", "bbb") @@ -264,7 +264,7 @@ func (f *failingReplace) ops() fsOps { } // openFailingReplace opens a new log whose manifest replace fails when armed. -func openFailingReplace(t *testing.T) (*segments, *failingReplace, Config) { +func openFailingReplace(t *testing.T) (*segments, *failingReplace, settings) { t.Helper() cfg := config(logDir(t), 8, 64) f := &failingReplace{} diff --git a/internal/segmentlog/doc.go b/internal/segmentlog/doc.go index ab96e94de..77e6330dc 100644 --- a/internal/segmentlog/doc.go +++ b/internal/segmentlog/doc.go @@ -1,6 +1,6 @@ -// Package segmentlog is the RecordLog port, where evidence lines are kept, -// and its default kind, segments: a directory of segment files and a -// manifest that names each one, sealed or pruned. +// Package segmentlog is the segments kind of the record log port of +// internal/recordlog: a directory of segment files and a manifest that names +// each one, sealed or pruned. Open is the port's Log, Inspect its Reader. // // Appends go to one live segment. At its byte bound the live segment is // sealed: the manifest names it first, then it is renamed, so a crash between diff --git a/internal/segmentlog/durable_test.go b/internal/segmentlog/durable_test.go index 3a4845a49..58ae8448b 100644 --- a/internal/segmentlog/durable_test.go +++ b/internal/segmentlog/durable_test.go @@ -62,7 +62,7 @@ func TestAParentTheGroupOrOthersMayWriteIsRefused(t *testing.T) { func TestAStickyParentTheGroupOrOthersMayWriteTakesALog(t *testing.T) { for _, mode := range []fs.FileMode{0o777 | fs.ModeSticky, 0o770 | fs.ModeSticky} { dir := filepath.Join(parentOfMode(t, mode), "log") - l, err := Open(config(dir, 8, 64)) + l, err := openKind(config(dir, 8, 64)) if err != nil { t.Errorf("a parent of mode %v: %v", mode, err) continue @@ -110,7 +110,7 @@ func TestARootOwnedParentIsJudgedAsThisAccounts(t *testing.T) { func refusedIn(t *testing.T, parent, what string) { t.Helper() dir := filepath.Join(parent, "log") - if l, err := Open(config(dir, 8, 64)); !errors.Is(err, ErrDirectory) { + if l, err := openKind(config(dir, 8, 64)); !errors.Is(err, ErrDirectory) { t.Errorf("%s: %v, want ErrDirectory", what, err) if l != nil { _ = l.Close() @@ -146,7 +146,7 @@ func TestAParentOfAnotherAccountIsRefused(t *testing.T) { } refusedIn(t, parent, "a parent of another account") ownerWanted = saved - l, err := Open(config(filepath.Join(parent, "log"), 8, 64)) + l, err := openKind(config(filepath.Join(parent, "log"), 8, 64)) if err != nil { t.Fatalf("a parent the group and others may only read: %v", err) } @@ -171,7 +171,7 @@ func TestAManifestThatIsALinkIsRefused(t *testing.T) { _ = l.Close() } } - if _, err := Inspect(cfg.Dir, 1<<10); !errors.Is(err, ErrManifest) { + if _, err := inspectAt(cfg.Dir, 1<<10); !errors.Is(err, ErrManifest) { t.Errorf("a view of a manifest that is a link = %v, want ErrManifest", err) } } @@ -217,7 +217,7 @@ func TestAViewReadAcrossASealIsMoved(t *testing.T) { t.Error(err) } } - if v, err := Inspect(dir, 1<<10); !errors.Is(err, ErrMoved) { + if v, err := inspectAt(dir, 1<<10); !errors.Is(err, ErrMoved) { var m Manifest if v != nil { m = v.Manifest() @@ -225,7 +225,7 @@ func TestAViewReadAcrossASealIsMoved(t *testing.T) { t.Errorf("a view across a seal = %v, naming %d sealed segment(s) and %d live line(s); want ErrMoved", err, len(m.Segments), m.Live.Lines) } - v, err := Inspect(dir, 1<<10) + v, err := inspectAt(dir, 1<<10) if err != nil || len(v.Manifest().Segments) != 2 { t.Fatalf("the view after the seal: %v", err) } @@ -248,7 +248,7 @@ func TestASealAndANewLiveFileBetweenTheReadsAreMoved(t *testing.T) { } writeIn(t, dir, LiveName, "") } - if v, err := Inspect(dir, 1<<10); !errors.Is(err, ErrMoved) { + if v, err := inspectAt(dir, 1<<10); !errors.Is(err, ErrMoved) { var m Manifest if v != nil { m = v.Manifest() @@ -304,7 +304,7 @@ func TestADirectoryNamedThroughALinkAndDotDotIsTheOneJudged(t *testing.T) { if err := os.Symlink(filepath.Join(shared, "x"), filepath.Join(parent, "l")); err != nil { t.Fatal(err) } - l, err := Open(config(parent+"/l/../trail", 8, 64)) + l, err := openKind(config(parent+"/l/../trail", 8, 64)) if err != nil { t.Fatalf("a log named through l/..: %v", err) } @@ -328,7 +328,7 @@ func TestADirectoryThatIsALinkIsRefused(t *testing.T) { if err := os.Symlink("real", filepath.Join(parent, "log")); err != nil { t.Fatal(err) } - if l, err := Open(config(filepath.Join(parent, "log"), 8, 64)); !errors.Is(err, ErrDirectory) { + if l, err := openKind(config(filepath.Join(parent, "log"), 8, 64)); !errors.Is(err, ErrDirectory) { t.Errorf("a log directory that is a link = %v, want ErrDirectory", err) if l != nil { _ = l.Close() diff --git a/internal/segmentlog/errors.go b/internal/segmentlog/errors.go index 4c42ff8e2..22d5fe29f 100644 --- a/internal/segmentlog/errors.go +++ b/internal/segmentlog/errors.go @@ -1,5 +1,7 @@ package segmentlog +import "github.com/guardana/control/internal/recordlog" + // Error is a refusal by this package, matched with errors.Is. They are // constants, so no other code in the binary can reassign one and turn a // refusal into a pass. @@ -9,10 +11,6 @@ type Error string func (e Error) Error() string { return string(e) } const ( - // ErrKind is a kind this build does not know. - ErrKind Error = "segmentlog: unknown kind" - // ErrConfig is a configuration no log opens with. - ErrConfig Error = "segmentlog: the configuration is refused" // ErrNoPermissionBits is a platform that keeps no permission bits, so // the directory cannot be checked. ErrNoPermissionBits Error = "segmentlog: this platform keeps no permission bits to check" @@ -30,30 +28,24 @@ const ( // ErrVersion is a manifest of a format or version this build does not // read. ErrVersion Error = "segmentlog: the manifest's format or version is not one this build reads" - // ErrBinding is a log bound to another tenant or project. - ErrBinding Error = "segmentlog: the log is bound to another tenant or project" - // ErrBudget is an append the log's byte bound refuses, or any append to a - // log opened with no bound. - ErrBudget Error = "segmentlog: the log is at its byte bound; an operator prunes sealed segments" - // ErrFull is a seal past the most segments a manifest names. - ErrFull Error = "segmentlog: the manifest names the most segments it may" - // ErrLines is an append that is not whole lines. - ErrLines Error = "segmentlog: an append is whole lines, each ending in a newline" - // ErrPrune is a prune that names no sealed segment, or the live one. - ErrPrune Error = "segmentlog: a prune names sealed segments only" // ErrClock is a prune whose clock stands before the seal of a segment it // would prune, a date the manifest cannot hold. ErrClock Error = "segmentlog: the clock stands before a segment's seal" - // ErrClosed is a call on a log that is closed. - ErrClosed Error = "segmentlog: the log is closed" - // ErrFailed is a call on a log a seal or a prune left part way, or whose - // live file changed under it: the next open completes the step or counts - // the file again, and until then the log takes nothing more. - ErrFailed Error = "segmentlog: a seal or a prune stopped part way, or the live file changed; open the log again" // ErrLiveChanged is a failed append after which the live file no longer // holds what the log counted, so the log fails. ErrLiveChanged Error = "segmentlog: the live file no longer holds what the log counted" - // ErrMoved is a segment that a seal or a prune moved between reading the - // manifest and opening the file. - ErrMoved Error = "segmentlog: the segment moved while it was opened" +) + +// The port's refusals, as this kind returns them. +const ( + ErrKind = recordlog.ErrKind + ErrConfig = recordlog.ErrConfig + ErrBinding = recordlog.ErrBinding + ErrBudget = recordlog.ErrBudget + ErrFull = recordlog.ErrFull + ErrLines = recordlog.ErrLines + ErrPrune = recordlog.ErrPrune + ErrClosed = recordlog.ErrClosed + ErrFailed = recordlog.ErrFailed + ErrMoved = recordlog.ErrMoved ) diff --git a/internal/segmentlog/helpers_test.go b/internal/segmentlog/helpers_test.go index 0ff613e3f..02211bec6 100644 --- a/internal/segmentlog/helpers_test.go +++ b/internal/segmentlog/helpers_test.go @@ -11,6 +11,8 @@ import ( "sort" "testing" "time" + + "github.com/guardana/control/internal/recordlog" ) // testLive is the plainest live file: appends synced at the end, and what @@ -46,17 +48,36 @@ func (l testLive) Close() error { return l.f.Close() } // clockAt is a clock that stands at one second. func clockAt(sec int64) func() time.Time { return func() time.Time { return time.Unix(sec, 0) } } -func config(dir string, segmentBytes, maxBytes int64) Config { - return Config{Kind: KindSegments, Dir: dir, Tenant: "t1", Project: "p1", SegmentBytes: segmentBytes, +func config(dir string, segmentBytes, maxBytes int64) settings { + return settings{Kind: recordlog.KindSegments, Dir: dir, Tenant: "t1", Project: "p1", SegmentBytes: segmentBytes, MaxBytes: maxBytes, MaxLineBytes: 1 << 10, OpenLive: openTestLive, Now: clockAt(1_800_000_000)} } +// openKind opens the log cfg names through the port's opener, as a consumer +// does. +func openKind(cfg settings) (recordlog.Log, error) { + return Open(recordlog.Config{Kind: cfg.Kind, Location: cfg.Dir, Tenant: cfg.Tenant, Project: cfg.Project, + LogID: cfg.LogID, Bounds: recordlog.Bounds{SegmentBytes: cfg.SegmentBytes, MaxBytes: cfg.MaxBytes, + MaxLineBytes: cfg.MaxLineBytes, MaxSegments: cfg.MaxSegments}, Visit: cfg.Visit, Now: cfg.Now}, + Options{OpenLive: cfg.OpenLive}) +} + +// inspectAt opens the log in dir to read through the port's opener. +func inspectAt(dir string, maxLineBytes int) (*view, error) { + r, err := Inspect(recordlog.Config{Kind: recordlog.KindSegments, Location: dir, + Bounds: recordlog.Bounds{MaxLineBytes: maxLineBytes}}) + if err != nil { + return nil, err + } + return r.(*view), nil +} + func logDir(t *testing.T) string { t.Helper() return filepath.Join(t.TempDir(), "log") } -func openLog(t *testing.T, cfg Config) *segments { +func openLog(t *testing.T, cfg settings) *segments { t.Helper() l, err := openSegments(cfg) if err != nil { @@ -66,7 +87,7 @@ func openLog(t *testing.T, cfg Config) *segments { return l } -func mustAppend(t *testing.T, l RecordLog, lines ...string) { +func mustAppend(t *testing.T, l recordlog.Log, lines ...string) { t.Helper() if err := l.Append(context.Background(), []byte(joinLines(lines...))); err != nil { t.Fatalf("Append(%q) = %v", lines, err) @@ -86,10 +107,10 @@ func joinLines(lines ...string) string { func sum(line string) Digest { return sha256.Sum256([]byte(line + "\n")) } // key is what names segment seq beginning with line. -func key(seq int, line string) Digest { return SegmentKey(seq, sum(line)) } +func key(seq int, line string) Digest { return recordlog.SegmentKey(seq, sum(line)) } // visited opens the log with a visitor and returns what it was handed. -func visited(t *testing.T, cfg Config) ([]string, *segments) { +func visited(t *testing.T, cfg settings) ([]string, *segments) { t.Helper() var seen []string cfg.Visit = func(line []byte) error { diff --git a/internal/segmentlog/holds.go b/internal/segmentlog/holds.go new file mode 100644 index 000000000..2dee12d0d --- /dev/null +++ b/internal/segmentlog/holds.go @@ -0,0 +1,107 @@ +package segmentlog + +import ( + "context" + "crypto/sha256" + "fmt" + "os" + + "github.com/guardana/control/internal/recordlog" +) + +// Holds reads back each span where the log wrote it, through the directory +// the log holds, reading no more than those lines. A span no segment not +// pruned holds whole, a file that is not the regular file the log wrote, a +// read that fails and a line of another digest each fail the log. +func (l *segments) Holds(ctx context.Context, spans []recordlog.Span) error { + l.mu.Lock() + defer l.mu.Unlock() + if err := l.usable(); err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + if err := l.readBack(spans); err != nil { + return l.fail(fmt.Errorf("a line the log wrote is no longer as it was written: %w", err)) + } + return nil +} + +func (l *segments) readBack(spans []recordlog.Span) error { + opened := map[string]*os.File{} + defer func() { + for _, f := range opened { + _ = f.Close() + } + }() + for _, sp := range spans { + name, offset, err := l.spanAt(sp) + if err != nil { + return err + } + f, ok := opened[name] + if !ok { + if f, err = openJudged(l.root, name, os.O_RDONLY); err != nil { + return err + } + opened[name] = f + } + line := make([]byte, sp.Size) + if _, err := f.ReadAt(line, offset); err != nil { + return fmt.Errorf("%s at offset %d: %w", name, offset, err) + } + if sha256.Sum256(line) != sp.Sum { + return fmt.Errorf("%s at offset %d holds another line", name, offset) + } + } + return nil +} + +// spanAt is the file of the segment holding the line at sp, and the line's +// offset in it. Offsets count the sealed segments not pruned, in order, then +// the live one. +func (l *segments) spanAt(sp recordlog.Span) (string, int64, error) { + if sp.Offset < 0 || sp.Size < 1 || sp.Size > int64(l.cfg.MaxLineBytes)+1 { + return "", 0, fmt.Errorf("a span of %d bytes at offset %d is no line of this log", sp.Size, sp.Offset) + } + var start int64 + for _, s := range l.segs { + if s.State != StateSealed { + continue + } + if sp.Offset+sp.Size <= start+s.Bytes { + return within(s.File, sp, start) + } + start += s.Bytes + } + if sp.Offset+sp.Size <= start+l.live.bytes { + return within(LiveName, sp, start) + } + return "", 0, fmt.Errorf("no segment holds the line at offset %d", sp.Offset) +} + +// within is sp's offset in the segment name, which begins at start; a span +// that begins in an earlier segment is in none. +func within(name string, sp recordlog.Span, start int64) (string, int64, error) { + if sp.Offset < start { + return "", 0, fmt.Errorf("the line at offset %d crosses into %s", sp.Offset, name) + } + return name, sp.Offset - start, nil +} + +// Stats is what the log counts now. +func (l *segments) Stats() recordlog.Stats { + l.mu.Lock() + defer l.mu.Unlock() + b := l.cfg.bounds() + b.MaxSegments = l.most + return statsOf(l.manifest(), b, l.refused) +} + +// statsOf is the Stats of a log of this kind found as m. +func statsOf(m Manifest, b recordlog.Bounds, refused uint64) recordlog.Stats { + sealed, pruned := m.Counts() + return recordlog.Stats{Kind: recordlog.KindSegments, Sealed: sealed, Pruned: pruned, Dropped: m.Dropped, + Retained: m.Retained, Bounds: b, BudgetRefusals: refused} +} diff --git a/internal/segmentlog/manifest.go b/internal/segmentlog/manifest.go index 69aa50401..65006a29f 100644 --- a/internal/segmentlog/manifest.go +++ b/internal/segmentlog/manifest.go @@ -212,15 +212,15 @@ func readSegment(d segmentDoc) (Segment, error) { if s.Last, ok = readDigest(d.Last); !ok { return Segment{}, fmt.Errorf("the last line's digest is not 64 lowercase hex digits") } - if err := s.checkCounts(); err != nil { + if err := checkCounts(s); err != nil { return Segment{}, err } - return s, s.readDates(d) + return s, readDates(&s, d) } // checkCounts refuses a number, or a count of lines and bytes, no seal // writes. -func (s Segment) checkCounts() error { +func checkCounts(s Segment) error { switch { case s.Seq < 1 || s.Seq > MaxSeq: return fmt.Errorf("seq %d", s.Seq) @@ -234,7 +234,7 @@ func (s Segment) checkCounts() error { // readDates reads when s was sealed and, for a pruned segment alone, pruned, // no earlier than its seal. -func (s *Segment) readDates(d segmentDoc) error { +func readDates(s *Segment, d segmentDoc) error { var err error if s.SealedAt, err = readStamp(d.SealedAt); err != nil { return fmt.Errorf("sealed_at: %w", err) diff --git a/internal/segmentlog/manifest_test.go b/internal/segmentlog/manifest_test.go index dfc529eb7..af5b76d2f 100644 --- a/internal/segmentlog/manifest_test.go +++ b/internal/segmentlog/manifest_test.go @@ -24,7 +24,7 @@ const manifestText = `{"format":"` + brand.OTelNamespace + `.segments","version" // sealedLog is a closed log holding one sealed segment of aaa and bbb and a // live one of ccc. -func sealedLog(t *testing.T) Config { +func sealedLog(t *testing.T) settings { t.Helper() cfg := config(logDir(t), 8, 64) l := openLog(t, cfg) @@ -251,7 +251,7 @@ func chmodIn(t *testing.T, dir, name string, mode os.FileMode) { // fullOfTombstones writes a manifest naming MaxSegments-1 pruned segments // and one sealed, of the line aaa, whose file it writes too, beside an empty // live segment, and returns the log's config. -func fullOfTombstones(t *testing.T) Config { +func fullOfTombstones(t *testing.T) settings { t.Helper() cfg := config(logDir(t), 8, 64) _ = openLog(t, cfg).Close() diff --git a/internal/segmentlog/port.go b/internal/segmentlog/port.go index 3790eaec2..88cb31ec6 100644 --- a/internal/segmentlog/port.go +++ b/internal/segmentlog/port.go @@ -2,41 +2,35 @@ package segmentlog import ( "context" - "crypto/sha256" "fmt" "os" - "strconv" "time" + + "github.com/guardana/control/internal/recordlog" ) -// Digest is the SHA-256 of one line, its newline included: the digest an -// evidence export's cursor names a file's first line by. -type Digest = [sha256.Size]byte - -// RecordLog is the record log port: it keeps whole lines in segments. Append -// returns nil only once the lines are durable. Every method of a log that is -// closed, or that a seal or a prune left part way, refuses. -type RecordLog interface { - // Append writes whole lines to the live segment, sealing it first when - // they would take it past its byte bound, and refuses them with - // ErrBudget when they would take the log past its own. - Append(ctx context.Context, lines []byte) error - // Seal seals the live segment; a live segment with no line stays. - Seal() error - // Prune prunes the sealed segments numbered through, and every one - // before it: the tombstone is written before a file is unlinked. - Prune(through int) error - // Locate answers what the segment key names is now, key being - // SegmentKey of its number and its first line. Its zero value is Unknown. - Locate(key Digest) SegmentAnswer - // Manifest is the log as its manifest and live segment hold it. - Manifest() Manifest - Close() error -} +// Digest is recordlog.Digest. +type Digest = recordlog.Digest + +// State is recordlog.State. +type State = recordlog.State -// KindSegments is the default kind: segment files and a manifest in one -// directory. -const KindSegments = "segments" +// Segment is recordlog.Segment. +type Segment = recordlog.Segment + +// Manifest is recordlog.Manifest. +type Manifest = recordlog.Manifest + +// SegmentAnswer is recordlog.SegmentAnswer. +type SegmentAnswer = recordlog.SegmentAnswer + +// The states of recordlog, as this kind's callers name them. +const ( + StateUnknown = recordlog.StateUnknown + StateLive = recordlog.StateLive + StateSealed = recordlog.StateSealed + StatePruned = recordlog.StatePruned +) // LiveFile is the live segment's file as the log's consumer opens it, which // judges what the file may hold and cuts what a crash left of a last line. @@ -51,161 +45,103 @@ type LiveFile interface { Close() error } -// Config is what a log opens with. -type Config struct { - // Kind is the log's kind; only KindSegments is known. - Kind string - // Dir is the log's directory, created mode 0700 when absent. - Dir string - // Tenant and Project bind the log: a new log records them, and an - // existing one bound to another is refused. - Tenant, Project string - // SegmentBytes bounds a live segment before it is sealed, and MaxBytes - // the bytes of every segment not pruned. Both zero refuses every append; - // otherwise MaxBytes is at least twice SegmentBytes. A live segment - // holding a line is sealed before an append would pass SegmentBytes, - // whatever the bound then says, so a full log holds a sealed segment an - // operator can prune unless one append alone is over MaxBytes. - SegmentBytes, MaxBytes int64 - // MaxLineBytes bounds a line before its newline; a longer one in a - // segment refuses the open. - MaxLineBytes int +// Options are what a log of this kind opens with besides its +// recordlog.Config. +type Options struct { // OpenLive opens the live segment by name in the directory root holds, // the one the log judged and locked, creating it when absent. OpenLive func(root *os.Root, name string) (LiveFile, error) - // Visit, when set, is handed every whole line the log holds at open, - // sealed segments first and in order; an error refuses the open. - Visit func(line []byte) error - // Now is the clock seals and prunes are dated by. - Now func() time.Time -} - -// Open opens the log cfg names, of the kind it names. -func Open(cfg Config) (RecordLog, error) { - switch cfg.Kind { - case KindSegments: - l, err := openSegments(cfg) - if err != nil { - return nil, err - } - return l, nil - default: - return nil, fmt.Errorf("%w: %q", ErrKind, cfg.Kind) - } } -// State is what a segment is. -type State uint8 - -const ( - // StateUnknown is a segment the log does not name, or names more than - // once. It is the zero value. - StateUnknown State = iota - // StateLive is the segment appends go to. - StateLive - // StateSealed is a segment no append changes. - StateSealed - // StatePruned is a sealed segment an operator removed; its tombstone - // keeps what it held. - StatePruned -) - -// String names the state as the manifest spells it. -func (s State) String() string { - switch s { - case StateLive: - return "live" - case StateSealed: - return "sealed" - case StatePruned: - return "pruned" - default: - return "unknown" - } +// settings are a recordlog.Config and its Options as this kind reads them. +type settings struct { + Kind recordlog.Kind + // Dir is the log's directory, created mode 0700 when absent. + Dir string + Tenant, Project string + LogID string + // SegmentBytes, MaxBytes and MaxLineBytes are the port's bounds; a live + // segment holding a line is sealed before an append would pass + // SegmentBytes, whatever the bound then says, so a full log holds a + // sealed segment an operator can prune unless one append alone is over + // MaxBytes. + SegmentBytes, MaxBytes int64 + MaxLineBytes int + // MaxSegments is the bound a seal keeps the manifest within. + MaxSegments int + OpenLive func(root *os.Root, name string) (LiveFile, error) + Visit func(line []byte) error + Now func() time.Time } -// Segment is what the log knows of one segment. -type Segment struct { - // Seq numbers the segment from 1, in the order it was sealed, and is - // never given again. - Seq int - State State - // Lines and Bytes are its whole lines and their bytes; First and Last the - // digests of its first and last line. - Lines, Bytes int64 - First, Last Digest - // SealedAt and PrunedAt date the seal and the prune; the live segment - // has neither. - SealedAt, PrunedAt time.Time - // File is the segment's file name in the log's directory, empty once - // pruned. - File string +func settingsOf(cfg recordlog.Config, opt Options) settings { + return settings{Kind: cfg.Kind, Dir: cfg.Location, Tenant: cfg.Tenant, Project: cfg.Project, LogID: cfg.LogID, + SegmentBytes: cfg.Bounds.SegmentBytes, MaxBytes: cfg.Bounds.MaxBytes, MaxLineBytes: cfg.Bounds.MaxLineBytes, + MaxSegments: cfg.Bounds.MaxSegments, OpenLive: opt.OpenLive, Visit: cfg.Visit, Now: cfg.Now} } -// Manifest is the log at one moment. -type Manifest struct { - Tenant, Project string - // Dropped is how many of the first segments were pruned and their - // tombstones dropped, to keep the manifest within MaxSegments entries; - // Segments are the sealed and pruned segments after them, by Seq. Live - // is the live segment, with no line when Live.Lines is 0. - Dropped int - Segments []Segment - Live Segment - // Retained is the bytes of every segment not pruned, the live one's whole - // lines included. - Retained int64 +// bounds are the settings' bounds as Stats reports them. +func (s settings) bounds() recordlog.Bounds { + return recordlog.Bounds{SegmentBytes: s.SegmentBytes, MaxBytes: s.MaxBytes, MaxLineBytes: s.MaxLineBytes, + MaxSegments: s.MaxSegments} } -// SegmentAnswer is what Locate found. Its zero value is Unknown. -type SegmentAnswer struct { - state State - cause string - seg Segment +// checkKind refuses any kind but this one, the zero Kind included. +func checkKind(k recordlog.Kind) error { + if k != recordlog.KindSegments { + return fmt.Errorf("%w: %q", ErrKind, k) + } + return nil } -// State is the segment's state, StateUnknown when no segment the log names -// has the key. -func (a SegmentAnswer) State() State { return a.state } - -// Cause says why the answer is Unknown. -func (a SegmentAnswer) Cause() string { - if a.state == StateUnknown && a.cause == "" { - return "nothing was located" +// checkShared refuses what neither a writer nor a reader opens with, and +// resolves a MaxSegments of zero to this kind's own. +func (s *settings) checkShared() error { + if err := checkKind(s.Kind); err != nil { + return err } - return a.cause + switch { + case s.Dir == "": + return fmt.Errorf("%w: no directory", ErrConfig) + case s.LogID != "": + return fmt.Errorf("%w: a log id needs a manifest version this build does not write", ErrConfig) + case s.MaxLineBytes < 1: + return fmt.Errorf("%w: line bound %d", ErrConfig, s.MaxLineBytes) + case s.MaxSegments < 0 || s.MaxSegments > MaxSegments: + return fmt.Errorf("%w: a bound of %d segments, from 1 to %d", ErrConfig, s.MaxSegments, MaxSegments) + case s.MaxSegments == 0: + s.MaxSegments = MaxSegments + } + return nil } -// Segment is what the log knows of the segment, for an answer that is not -// Unknown. -func (a SegmentAnswer) Segment() Segment { - if a.state == StateUnknown { - return Segment{} +// Open opens the log cfg names as a writer that holds it until Close. +func Open(cfg recordlog.Config, opt Options) (recordlog.Log, error) { + l, err := openSegments(settingsOf(cfg, opt)) + if err != nil { + return nil, err } - return a.seg + return l, nil } -// keyPrefix starts what a segment's key is the SHA-256 of. -const keyPrefix = ManifestFormat + "/" - -// SegmentKey is what names segment seq whose first line has the digest first -// to a reader: the SHA-256 of ManifestFormat, "/", seq in decimal, "/" and -// the 32 bytes of first. A segment keeps its key when it is sealed, -// and no two segments of one log have one, as no number is given twice. -func SegmentKey(seq int, first Digest) Digest { - b := append(strconv.AppendInt([]byte(keyPrefix), int64(seq), 10), '/') - return sha256.Sum256(append(b, first[:]...)) +// Inspect opens the log cfg names to read, as it is now; see view. +func Inspect(cfg recordlog.Config) (recordlog.Reader, error) { + v, err := inspect(settingsOf(cfg, Options{})) + if err != nil { + return nil, err + } + return v, nil } // locate answers for key among segs and live. func locate(segs []Segment, live Segment, key Digest) SegmentAnswer { for _, s := range segs { - if SegmentKey(s.Seq, s.First) == key { - return SegmentAnswer{state: s.State, seg: s} + if recordlog.SegmentKey(s.Seq, s.First) == key { + return recordlog.Found(s) } } - if live.Lines > 0 && SegmentKey(live.Seq, live.First) == key { - return SegmentAnswer{state: StateLive, seg: live} + if live.Lines > 0 && recordlog.SegmentKey(live.Seq, live.First) == key { + return recordlog.Found(live) } - return SegmentAnswer{cause: "no segment this log names has that key"} + return recordlog.NotFound("no segment this log names has that key") } diff --git a/internal/segmentlog/port_test.go b/internal/segmentlog/port_test.go new file mode 100644 index 000000000..5c73c4a1d --- /dev/null +++ b/internal/segmentlog/port_test.go @@ -0,0 +1,236 @@ +package segmentlog + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/guardana/control/internal/recordlog" +) + +// readConfig is what a reader of the log in dir opens with. +func readConfig(dir string) recordlog.Config { + return recordlog.Config{Kind: recordlog.KindSegments, Location: dir, Bounds: recordlog.Bounds{MaxLineBytes: 1 << 10}} +} + +// TestInspectTakesOnlyAKnownKind: a reader opens on the default kind alone; +// the zero Kind and every other name are ErrKind. +func TestInspectTakesOnlyAKnownKind(t *testing.T) { + cfg := config(logDir(t), 8, 64) + openLog(t, cfg) + for _, kind := range []recordlog.Kind{"", "Segments", "segments ", "objects"} { + rc := readConfig(cfg.Dir) + rc.Kind = kind + if r, err := Inspect(rc); r != nil || !errors.Is(err, ErrKind) { + t.Errorf("kind %q inspected %v, %v; want ErrKind", kind, r, err) + } + } + if _, err := Inspect(readConfig(cfg.Dir)); err != nil { + t.Errorf("the default kind: %v", err) + } +} + +// TestALogIDIsRefusedUntilItsManifestIsWritten: no writer and no reader of +// this build takes a log id, which manifest 0.1 cannot hold. +func TestALogIDIsRefusedUntilItsManifestIsWritten(t *testing.T) { + cfg := config(logDir(t), 8, 64) + cfg.LogID = "l1" + if l, err := openKind(cfg); l != nil || !errors.Is(err, ErrConfig) { + t.Errorf("a writer with a log id: %v, %v; want ErrConfig", l, err) + } + cfg.LogID = "" + openLog(t, cfg) + rc := readConfig(cfg.Dir) + rc.LogID = "l1" + if r, err := Inspect(rc); r != nil || !errors.Is(err, ErrConfig) { + t.Errorf("a reader with a log id: %v, %v; want ErrConfig", r, err) + } +} + +// TestTheSegmentBoundIsTheConfigs: a bound of two segments refuses the third +// seal, the kind's own bound and none below it open, and a negative bound or +// one past the kind's is refused. +func TestTheSegmentBoundIsTheConfigs(t *testing.T) { + for _, c := range []struct { + most int + ok bool + }{{-1, false}, {MaxSegments + 1, false}, {MaxSegments, true}, {0, true}, {2, true}} { + cfg := config(logDir(t), 8, 64) + cfg.MaxSegments = c.most + l, err := openKind(cfg) + if (err == nil) != c.ok || (err != nil && !errors.Is(err, ErrConfig)) { + t.Errorf("a bound of %d segments: %v, want opened %v", c.most, err, c.ok) + } + if l != nil { + _ = l.Close() + } + } + cfg := config(logDir(t), 8, 64) + cfg.MaxSegments = 2 + l, err := openKind(cfg) + if err != nil { + t.Fatal(err) + } + defer func() { _ = l.Close() }() + mustAppend(t, l, "aaa") + mustAppend(t, l, "bbb", "ccc") + mustAppend(t, l, "ddd", "eee") + if err := l.Append(context.Background(), []byte("fff\nggg\n")); !errors.Is(err, ErrFull) { + t.Errorf("the third seal under a bound of two: %v, want ErrFull", err) + } + if st := l.Stats(); st.Sealed != 2 || st.Bounds.MaxSegments != 2 { + t.Errorf("the stats after the bound refused a seal: %+v", st) + } +} + +// TestAReaderGivenABindingTakesOnlyItsOwn: a reader given the log's tenant +// and project opens, one given another's is ErrBinding, and one given none +// reads whatever binding the manifest holds. +func TestAReaderGivenABindingTakesOnlyItsOwn(t *testing.T) { + cfg := config(logDir(t), 8, 64) + openLog(t, cfg) + for _, c := range []struct { + tenant, project string + ok bool + }{{"t1", "p1", true}, {"", "", true}, {"t2", "p1", false}, {"t1", "p2", false}, {"t1", "", false}} { + rc := readConfig(cfg.Dir) + rc.Tenant, rc.Project = c.tenant, c.project + r, err := Inspect(rc) + if (err == nil) != c.ok || (err != nil && !errors.Is(err, ErrBinding)) { + t.Errorf("a reader bound to %q and %q: %v, want opened %v", c.tenant, c.project, err, c.ok) + } + if r != nil && r.Manifest().Tenant != "t1" { + t.Errorf("the reader names tenant %q", r.Manifest().Tenant) + } + } +} + +// TestAHoldingThatCannotBeAskedIsUnknown: a lock file that is no regular file +// is a holding of unknown, never free; no lock file is free, and the lock of a +// writer is held. +func TestAHoldingThatCannotBeAskedIsUnknown(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingHeld { + t.Errorf("with the writer open: %s, want held", h) + } + if err := l.Close(); err != nil { + t.Fatal(err) + } + lock := filepath.Join(cfg.Dir, LockName) + if err := os.Remove(lock); err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingFree { + t.Errorf("with no lock file: %s, want free", h) + } + if err := os.Mkdir(lock, 0o700); err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingUnknown { + t.Errorf("with a directory at the lock's name: %s, want unknown", h) + } + if err := os.RemoveAll(cfg.Dir); err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingUnknown { + t.Errorf("with the log's directory gone: %s, want unknown", h) + } +} + +// TestARefusedSpanFailsTheLogAndACancelledOneDoesNot: a span of no bytes and +// one that crosses from a sealed segment into the live one fail the log; a +// read-back asked under a context already done answers that and leaves the +// log taking appends. +func TestARefusedSpanFailsTheLogAndACancelledOneDoesNot(t *testing.T) { + aaa := recordlog.Span{Offset: 0, Size: 4, Sum: sum("aaa")} + for name, span := range map[string]recordlog.Span{ + "empty": {Offset: 0, Size: 0, Sum: sum("aaa")}, + "crosses": {Offset: 4, Size: 8, Sum: sum("bbb\nccc")}, + "over": {Offset: 0, Size: 1<<10 + 2, Sum: sum("aaa")}, + } { + l := openLog(t, config(logDir(t), 8, 64)) + mustAppend(t, l, "aaa", "bbb") + mustAppend(t, l, "ccc") + if err := l.Holds(context.Background(), []recordlog.Span{aaa, span}); !errors.Is(err, ErrFailed) { + t.Errorf("%s: %v, want ErrFailed", name, err) + } + if err := l.Append(context.Background(), []byte("ddd\n")); !errors.Is(err, ErrFailed) { + t.Errorf("%s: an append after the read-back failed: %v", name, err) + } + } + l := openLog(t, config(logDir(t), 8, 64)) + mustAppend(t, l, "aaa") + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := l.Holds(ctx, []recordlog.Span{{Offset: 0, Size: 4, Sum: sum("zzz")}}); !errors.Is(err, context.Canceled) { + t.Errorf("a read-back under a done context: %v", err) + } + mustAppend(t, l, "bbb") + if err := l.Holds(context.Background(), []recordlog.Span{aaa}); err != nil { + t.Errorf("an untouched read-back: %v", err) + } +} + +// TestTheStatsCountWhatTheLogHolds: a writer counts its sealed, pruned and +// dropped segments, the bytes retained, its bounds and each append the budget +// refused; a reader counts the same segments and no refusal. +func TestTheStatsCountWhatTheLogHolds(t *testing.T) { + cfg := config(logDir(t), 8, 16) + l := openLog(t, cfg) + mustAppend(t, l, "aaa", "bbb") + mustAppend(t, l, "ccc", "ddd") + for range 2 { + if err := l.Append(context.Background(), []byte("e\n")); !errors.Is(err, ErrBudget) { + t.Fatalf("an append past the budget: %v", err) + } + } + if err := l.Prune(1); err != nil { + t.Fatal(err) + } + want := recordlog.Stats{Kind: recordlog.KindSegments, Sealed: 1, Pruned: 1, Retained: 8, BudgetRefusals: 2, + Bounds: recordlog.Bounds{SegmentBytes: 8, MaxBytes: 16, MaxLineBytes: 1 << 10, MaxSegments: 10_000}} + if got := l.Stats(); got != want { + t.Errorf("the writer's stats: %+v, want %+v", got, want) + } + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + want.BudgetRefusals, want.Bounds = 0, recordlog.Bounds{MaxLineBytes: 1 << 10, MaxSegments: 10_000} + if got := r.Stats(); got != want { + t.Errorf("the reader's stats: %+v, want %+v", got, want) + } +} + +// TestAnEmptyLiveSegmentWithNoFileOpensEmpty: the live segment of a log whose +// every line was sealed, its file not yet made, opens as no bytes. +func TestAnEmptyLiveSegmentWithNoFileOpensEmpty(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + if err := l.Seal(); err != nil { + t.Fatal(err) + } + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + c, err := r.Open(r.Manifest().Live) + if err != nil || c.Size() != 0 { + t.Fatalf("the empty live segment: %v", err) + } + if n, err := c.ReadAt(make([]byte, 1), 0); n != 0 || err == nil { + t.Errorf("reading the empty live segment: %d, %v", n, err) + } + if err := c.Close(); err != nil { + t.Error(err) + } +} diff --git a/internal/segmentlog/segments.go b/internal/segmentlog/segments.go index 3e782a648..9bec9ed81 100644 --- a/internal/segmentlog/segments.go +++ b/internal/segmentlog/segments.go @@ -39,7 +39,7 @@ func syncRoot(root *os.Root) error { // manifest as last written, and the live segment. type segments struct { mu sync.Mutex - cfg Config + cfg settings root *os.Root lock *os.File // dropped is how many segments before segs were pruned and their @@ -53,18 +53,21 @@ type segments struct { failed error closed bool ops fsOps - // most is MaxSegments, the entries a seal keeps the manifest within; a - // test lowers it to reach the bound with few segment files. + // most is the entries a seal keeps the manifest within; a test lowers it + // to reach the bound with few segment files. most int + // refused counts the appends the byte bound refused. + refused uint64 } -// check refuses a configuration no log opens with. -func (cfg Config) check() error { +// check refuses a configuration no writer opens with. +func (cfg *settings) check() error { + if err := cfg.checkShared(); err != nil { + return err + } switch { case cfg.OpenLive == nil || cfg.Now == nil: return fmt.Errorf("%w: no live segment opener or no clock", ErrConfig) - case cfg.MaxLineBytes < 1: - return fmt.Errorf("%w: line bound %d", ErrConfig, cfg.MaxLineBytes) case cfg.SegmentBytes == 0 && cfg.MaxBytes == 0: case cfg.SegmentBytes < 1 || cfg.MaxBytes/2 < cfg.SegmentBytes: return fmt.Errorf("%w: a segment bound of %d and a log bound of %d; the log bound is at least twice the segment's", @@ -76,9 +79,9 @@ func (cfg Config) check() error { return nil } -func openSegments(cfg Config) (*segments, error) { return openWith(cfg, osOps) } +func openSegments(cfg settings) (*segments, error) { return openWith(cfg, osOps) } -func openWith(cfg Config, ops fsOps) (*segments, error) { +func openWith(cfg settings, ops fsOps) (*segments, error) { if err := cfg.check(); err != nil { return nil, err } @@ -89,7 +92,7 @@ func openWith(cfg Config, ops fsOps) (*segments, error) { if err != nil { return nil, err } - l := &segments{cfg: cfg, root: root, ops: ops, most: MaxSegments} + l := &segments{cfg: cfg, root: root, ops: ops, most: cfg.MaxSegments} if err := l.claim(); err != nil { return nil, errors.Join(err, l.release()) } diff --git a/internal/segmentlog/segments_test.go b/internal/segmentlog/segments_test.go index 2d0c88245..8d3b4c2b7 100644 --- a/internal/segmentlog/segments_test.go +++ b/internal/segmentlog/segments_test.go @@ -12,19 +12,20 @@ import ( "testing" "github.com/guardana/control/internal/brand" + "github.com/guardana/control/internal/recordlog" ) // TestOpenTakesOnlyAKnownKind: the default kind opens, and no other name, // the empty one included, is read as it. func TestOpenTakesOnlyAKnownKind(t *testing.T) { - for _, kind := range []string{"", "Segments", "segments ", "objects"} { + for _, kind := range []recordlog.Kind{"", "Segments", "segments ", "objects"} { cfg := config(logDir(t), 16, 32) cfg.Kind = kind - if l, err := Open(cfg); l != nil || !errors.Is(err, ErrKind) { + if l, err := openKind(cfg); l != nil || !errors.Is(err, ErrKind) { t.Errorf("kind %q opened %v, %v; want ErrKind", kind, l, err) } } - l, err := Open(config(logDir(t), 16, 32)) + l, err := openKind(config(logDir(t), 16, 32)) if err != nil { t.Fatalf("the default kind: %v", err) } @@ -45,7 +46,7 @@ func TestOpenHoldsTheBoundsToEachOther(t *testing.T) { } { cfg := config(logDir(t), c.segment, c.max) cfg.Tenant = c.tenant - l, err := Open(cfg) + l, err := openKind(cfg) if (err == nil) != c.ok || (err != nil && !errors.Is(err, ErrConfig)) { t.Errorf("segment %d, log %d, tenant %q: %v, want opened %v", c.segment, c.max, c.tenant, err, c.ok) } @@ -226,13 +227,17 @@ func TestLocateAnswersForEachState(t *testing.T) { } } -// TestASegmentKeyIsItsNumberAndFirstLine: the key is the SHA-256 the -// contract spells, computed here apart from the package. +// TestASegmentKeyIsItsNumberAndFirstLine: the port's key is the SHA-256 the +// contract spells over this kind's manifest format, computed here apart from +// the port. func TestASegmentKeyIsItsNumberAndFirstLine(t *testing.T) { first := sha256.Sum256([]byte("aaa\n")) - want := sha256.Sum256(append([]byte(brand.OTelNamespace+".segments/12/"), first[:]...)) - if got := SegmentKey(12, first); got != want { - t.Errorf("SegmentKey(12, aaa) = %x, want %x", got, want) + want := sha256.Sum256(append([]byte(ManifestFormat+"/12/"), first[:]...)) + if got := recordlog.SegmentKey(12, first); got != want { + t.Errorf("recordlog.SegmentKey(12, aaa) = %x, want %x", got, want) + } + if ManifestFormat != brand.OTelNamespace+".segments" { + t.Errorf("the manifest format is %q", ManifestFormat) } } diff --git a/internal/segmentlog/view.go b/internal/segmentlog/view.go index 248345d6f..4163f32ab 100644 --- a/internal/segmentlog/view.go +++ b/internal/segmentlog/view.go @@ -3,54 +3,49 @@ package segmentlog import ( "errors" "fmt" + "io" "io/fs" "os" "slices" + + "github.com/guardana/control/internal/recordlog" ) -// View is a log as a reader finds it, holding no lock and writing nothing: the +// view is a log as a reader finds it, holding no lock and writing nothing: the // manifest, and the live segment's whole lines when it was read. A writer may // seal or prune while a view is held; Open notices a segment that moved. -type View struct { - dir string - maxLineBytes int - tenant string - project string - dropped int - segs []Segment - live stats +type view struct { + cfg settings + tenant string + project string + dropped int + segs []Segment + live stats } -// inspected runs between Inspect's read of the manifest and its open of the +// inspected runs between inspect's read of the manifest and its open of the // live file, where a writer may seal; a test seals there. var inspected = func() {} -// Inspect reads the log in dir as it is: a manifest is required, and a live -// segment is read to its last newline. The manifest is read again once the -// live file was read, or found absent: one naming a segment the first read -// did not means the live segment was sealed since, and the file read may be -// the next one, so the view is ErrMoved. Nothing is created, cut or removed. -func Inspect(dir string, maxLineBytes int) (*View, error) { - if maxLineBytes < 1 { - return nil, fmt.Errorf("%w: line bound %d", ErrConfig, maxLineBytes) - } - root, err := os.OpenRoot(dir + string(os.PathSeparator) + ".") - if err != nil { +// inspect reads the log in cfg.Dir as it is: a manifest is required, and a +// live segment is read to its last newline. A Tenant or Project given has to +// be the manifest's. The manifest is read again once the live file was read, +// or found absent: one naming a segment the first read did not means the live +// segment was sealed since, and the file read may be the next one, so the +// view is ErrMoved. Nothing is created, cut or removed. +func inspect(cfg settings) (*view, error) { + if err := cfg.checkShared(); err != nil { return nil, err } - defer func() { _ = root.Close() }() - raw, ok, err := readManifest(root) - switch { - case err != nil: + root, err := os.OpenRoot(cfg.Dir + string(os.PathSeparator) + ".") + if err != nil { return nil, err - case !ok: - return nil, fmt.Errorf("%w: %s holds no %s, so it is no segment log", ErrManifest, dir, ManifestName) } - m, err := decodeManifest(raw) + defer func() { _ = root.Close() }() + v, err := readView(root, cfg) if err != nil { return nil, err } - v := &View{dir: dir, maxLineBytes: maxLineBytes, tenant: m.tenant, project: m.project, dropped: m.dropped, segs: m.segs} inspected() f, err := openRead(root, LiveName) if errors.Is(err, fs.ErrNotExist) { @@ -63,7 +58,7 @@ func Inspect(dir string, maxLineBytes int) (*View, error) { return nil, err } defer func() { _ = f.Close() }() - if v.live, err = scan(f, maxLineBytes, nil); err != nil { + if v.live, err = scan(f, cfg.MaxLineBytes, nil); err != nil { return nil, fmt.Errorf("%s: %w", LiveName, err) } if err := v.stillLive(root); err != nil { @@ -72,13 +67,32 @@ func Inspect(dir string, maxLineBytes int) (*View, error) { return v, nil } +// readView reads the manifest in root as a view with no live segment read. +func readView(root *os.Root, cfg settings) (*view, error) { + raw, ok, err := readManifest(root) + switch { + case err != nil: + return nil, err + case !ok: + return nil, fmt.Errorf("%w: %s holds no %s, so it is no segment log", ErrManifest, cfg.Dir, ManifestName) + } + m, err := decodeManifest(raw) + if err != nil { + return nil, err + } + if (cfg.Tenant != "" || cfg.Project != "") && (m.tenant != cfg.Tenant || m.project != cfg.Project) { + return nil, fmt.Errorf("%w: it is bound to tenant %q and project %q", ErrBinding, m.tenant, m.project) + } + return &view{cfg: cfg, tenant: m.tenant, project: m.project, dropped: m.dropped, segs: m.segs}, nil +} + // sealPending refuses, as moved, the live file of a view read after a seal // named the live segment sealed and before it renamed the file: the newest // sealed segment has no file, and the live file begins with that segment's // first line, or the file opened is that segment's now. Only an open of the // live file is refused, so a reader of the manifest alone, and the writer // that completes the seal, still read it. -func (v *View) sealPending(root *os.Root, f *os.File) error { +func (v *view) sealPending(root *os.Root, f *os.File) error { if len(v.segs) == 0 || v.live.lines == 0 { return nil } @@ -123,16 +137,17 @@ func openRead(root *os.Root, name string) (*os.File, error) { return f, nil } -func (v *View) liveSegment() Segment { +func (v *view) liveSegment() Segment { s := v.live.segment(StateLive) s.Seq, s.File = v.dropped+len(v.segs)+1, LiveName return s } -// Manifest is the log as the view found it. -func (v *View) Manifest() Manifest { +// Manifest is the log as the view found it, with the bytes after the live +// segment's last newline as its Tail. +func (v *view) Manifest() Manifest { m := Manifest{Tenant: v.tenant, Project: v.project, Dropped: v.dropped, Segments: slices.Clone(v.segs), - Live: v.liveSegment(), Retained: v.live.bytes} + Live: v.liveSegment(), Retained: v.live.bytes, Tail: v.live.tail} for _, s := range v.segs { if s.State == StateSealed { m.Retained += s.Bytes @@ -141,85 +156,106 @@ func (v *View) Manifest() Manifest { return m } -// Tail is the bytes after the live segment's last newline when it was read. -func (v *View) Tail() int64 { return v.live.tail } +// Stats is what the view found, its bounds those it was opened with. +func (v *view) Stats() recordlog.Stats { return statsOf(v.Manifest(), v.cfg.bounds(), 0) } // Locate answers for the segment key names. -func (v *View) Locate(key Digest) SegmentAnswer { +func (v *view) Locate(key Digest) SegmentAnswer { return locate(v.segs, v.liveSegment(), key) } // After is the segment that follows seq, sealed or live; Unknown when there is // none, and Pruned when it was pruned. -func (v *View) After(seq int) SegmentAnswer { +func (v *view) After(seq int) SegmentAnswer { i := seq - v.dropped switch { case i < 0: - return SegmentAnswer{cause: fmt.Sprintf("segment %d was dropped", seq)} + return recordlog.NotFound(fmt.Sprintf("segment %d was dropped", seq)) case i < len(v.segs): - s := v.segs[i] - return SegmentAnswer{state: s.State, seg: s} + return recordlog.Found(v.segs[i]) case i == len(v.segs): - return SegmentAnswer{state: StateLive, seg: v.liveSegment()} + return recordlog.Found(v.liveSegment()) default: - return SegmentAnswer{cause: fmt.Sprintf("no segment follows %d", seq)} + return recordlog.NotFound(fmt.Sprintf("no segment follows %d", seq)) } } // First is the first segment not pruned: the first sealed one, or the live // one when every sealed one was pruned. -func (v *View) First() SegmentAnswer { +func (v *view) First() SegmentAnswer { for _, s := range v.segs { if s.State == StateSealed { - return SegmentAnswer{state: StateSealed, seg: s} + return recordlog.Found(s) } } - return SegmentAnswer{state: StateLive, seg: v.liveSegment()} + return recordlog.Found(v.liveSegment()) +} + +// content is a segment's file as opened, read to the length a reader takes. +type content struct { + *io.SectionReader + f *os.File +} + +func (c content) Close() error { + if c.f == nil { + return nil + } + return c.f.Close() } -// Open opens the file of a sealed or the live segment s and returns it with -// the length a reader takes. A sealed segment is read whole first and refused -// unless it holds what the manifest names it with. A live segment that no -// longer begins with the line it began with when the view was read, or whose +// Open opens the file of a sealed or the live segment s, to the length a +// reader takes. A sealed segment is read whole first and refused unless it +// holds what the manifest names it with. A live segment that no longer +// begins with the line it began with when the view was read, or whose // manifest, read again once the file is open, names a segment the view did // not, was sealed since, and is ErrMoved; so is one a seal named sealed and -// has not yet renamed, and a sealed segment pruned since. -func (v *View) Open(s Segment) (*os.File, int64, error) { +// has not yet renamed, and a sealed segment pruned since. A live segment that +// held no line and has no file is empty. +func (v *view) Open(s Segment) (recordlog.Content, error) { if s.State != StateSealed && s.State != StateLive { - return nil, 0, fmt.Errorf("%w: segment %d is %s", ErrPrune, s.Seq, s.State) + return nil, fmt.Errorf("%w: segment %d is %s", ErrPrune, s.Seq, s.State) } - root, err := os.OpenRoot(v.dir + string(os.PathSeparator) + ".") + root, err := os.OpenRoot(v.cfg.Dir + string(os.PathSeparator) + ".") if err != nil { - return nil, 0, err + return nil, err } defer func() { _ = root.Close() }() f, err := openRead(root, s.File) if errors.Is(err, fs.ErrNotExist) { if s.State == StateLive { if moved := v.stillLive(root); moved != nil { - return nil, 0, moved + return nil, moved + } + if s.Lines == 0 { + return content{SectionReader: io.NewSectionReader(eof{}, 0, 0)}, nil } } - return nil, 0, fmt.Errorf("%w: %s: %w", ErrMoved, s.File, err) + return nil, fmt.Errorf("%w: %s: %w", ErrMoved, s.File, err) } if err != nil { - return nil, 0, err + return nil, err } size, err := v.check(f, s) if err == nil && s.State == StateLive { err = errors.Join(v.stillLive(root), v.sealPending(root, f)) } if err != nil { - return nil, 0, errors.Join(err, f.Close()) + return nil, errors.Join(err, f.Close()) } - return f, size, nil + return content{SectionReader: io.NewSectionReader(f, 0, size), f: f}, nil } +// eof is what an empty segment reads. +type eof struct{} + +func (eof) ReadAt([]byte, int64) (int, error) { return 0, io.EOF } + // stillLive refuses, as moved, a manifest that names more segments than the // view's. A seal names the live segment in the manifest before it renames the // file, so a live file opened while the manifest still names no more is the // view's live segment. -func (v *View) stillLive(root *os.Root) error { +func (v *view) stillLive(root *os.Root) error { raw, ok, err := readManifest(root) switch { case err != nil: @@ -238,12 +274,12 @@ func (v *View) stillLive(root *os.Root) error { } // check reads what it must of the open file of s to know it is s. -func (v *View) check(f *os.File, s Segment) (int64, error) { +func (v *view) check(f *os.File, s Segment) (int64, error) { info, err := f.Stat() if err != nil { return 0, err } - st, err := scan(f, v.maxLineBytes, nil) + st, err := scan(f, v.cfg.MaxLineBytes, nil) switch { case err != nil: return 0, fmt.Errorf("%s: %w", s.File, err) @@ -255,20 +291,29 @@ func (v *View) check(f *os.File, s Segment) (int64, error) { return info.Size(), nil } -// Held reports whether a writer holds the log's directory. -func (v *View) Held() (bool, error) { - root, err := os.OpenRoot(v.dir + string(os.PathSeparator) + ".") +// Holding asks whether a writer holds the log's directory now: free when it +// has no lock file, unknown when the directory or the lock file cannot be +// opened or asked. +func (v *view) Holding() recordlog.Holding { + root, err := os.OpenRoot(v.cfg.Dir + string(os.PathSeparator) + ".") if err != nil { - return false, err + return recordlog.HoldingUnknown } defer func() { _ = root.Close() }() f, err := openRead(root, LockName) if errors.Is(err, fs.ErrNotExist) { - return false, nil + return recordlog.HoldingFree } if err != nil { - return false, err + return recordlog.HoldingUnknown } defer func() { _ = f.Close() }() - return HeldByWriter(f) + held, err := HeldByWriter(f) + switch { + case err != nil: + return recordlog.HoldingUnknown + case held: + return recordlog.HoldingHeld + } + return recordlog.HoldingFree } diff --git a/internal/segmentlog/view_test.go b/internal/segmentlog/view_test.go index 96b355142..85650032d 100644 --- a/internal/segmentlog/view_test.go +++ b/internal/segmentlog/view_test.go @@ -8,6 +8,8 @@ import ( "slices" "testing" "time" + + "github.com/guardana/control/internal/recordlog" ) // snapshot is every name in dir with its bytes, mode and modification time. @@ -45,7 +47,7 @@ func TestAViewChangesNothingAndAnswersAsTheLog(t *testing.T) { } _ = f.Close() before := snapshot(t, cfg.Dir) - v, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + v, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil { t.Fatal(err) } @@ -57,7 +59,7 @@ func TestAViewChangesNothingAndAnswersAsTheLog(t *testing.T) { // locatesAsTheLog checks the view of l locates each of its segments as l // does, and one it does not have as Unknown. -func locatesAsTheLog(t *testing.T, v *View, l *segments) { +func locatesAsTheLog(t *testing.T, v *view, l *segments) { t.Helper() for seq, line := range map[int]string{1: "aaa", 2: "ccc", 3: "eee", 4: "zzz"} { got, want := v.Locate(key(seq, line)).State(), l.Locate(key(seq, line)).State() @@ -68,22 +70,22 @@ func locatesAsTheLog(t *testing.T, v *View, l *segments) { } // answersAsTheLog checks the view of l locates, counts and opens as l does. -func answersAsTheLog(t *testing.T, v *View, l *segments) { +func answersAsTheLog(t *testing.T, v *view, l *segments) { t.Helper() - if held, err := v.Held(); err != nil || !held { - t.Errorf("Held = %v, %v while the writer holds the directory", held, err) + if h := v.Holding(); h != recordlog.HoldingHeld { + t.Errorf("Holding = %s while the writer holds the directory", h) } locatesAsTheLog(t, v, l) - if m := v.Manifest(); m.Retained != 12 || m.Live.Lines != 1 || v.Tail() != 2 { - t.Errorf("the view: %+v, tail %d", m, v.Tail()) + if m := v.Manifest(); m.Retained != 12 || m.Live.Lines != 1 || m.Tail != 2 { + t.Errorf("the view: %+v", m) } sealed := v.Locate(key(2, "ccc")).Segment() - sf, size, err := v.Open(sealed) - if err != nil || size != 8 { - t.Fatalf("opening the sealed segment: %d, %v", size, err) + sf, err := v.Open(sealed) + if err != nil || sf.Size() != 8 { + t.Fatalf("opening the sealed segment: %v", err) } _ = sf.Close() - if _, _, err := v.Open(v.Locate(key(1, "aaa")).Segment()); !errors.Is(err, ErrPrune) { + if _, err := v.Open(v.Locate(key(1, "aaa")).Segment()); !errors.Is(err, ErrPrune) { t.Errorf("opening a pruned segment: %v", err) } } @@ -92,18 +94,18 @@ func answersAsTheLog(t *testing.T, v *View, l *segments) { // whose bytes changed at its own length opens for no reader. func TestASealedSegmentChangedInPlaceIsRefusedToAReader(t *testing.T) { cfg := sealedLog(t) - v, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + v, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil { t.Fatal(err) } sealed := v.Locate(key(1, "aaa")).Segment() - f, _, err := v.Open(sealed) + f, err := v.Open(sealed) if err != nil { t.Fatal(err) } _ = f.Close() writeIn(t, cfg.Dir, "segment-00000001.jsonl", "aaa\nbbc\n") - if _, _, err := v.Open(sealed); !errors.Is(err, ErrManifest) { + if _, err := v.Open(sealed); !errors.Is(err, ErrManifest) { t.Errorf("a sealed segment changed in place opened as %v, want ErrManifest", err) } } @@ -111,10 +113,10 @@ func TestASealedSegmentChangedInPlaceIsRefusedToAReader(t *testing.T) { // TestAViewNeedsAManifest: a directory that is not there, and one with no // manifest, are no log to inspect. func TestAViewNeedsAManifest(t *testing.T) { - if _, err := Inspect(filepath.Join(t.TempDir(), "absent"), 64); err == nil { + if _, err := inspectAt(filepath.Join(t.TempDir(), "absent"), 64); err == nil { t.Error("a directory that is not there was inspected") } - if _, err := Inspect(t.TempDir(), 64); !errors.Is(err, ErrManifest) { + if _, err := inspectAt(t.TempDir(), 64); !errors.Is(err, ErrManifest) { t.Errorf("a directory with no manifest: %v", err) } } @@ -138,12 +140,12 @@ func TestASegmentSealedOrPrunedUnderAReaderIsReadFromItsDescriptor(t *testing.T) cfg := config(logDir(t), 8, 64) l := openLog(t, cfg) mustAppend(t, l, "aaa", "bbb") - v, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + v, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil { t.Fatal(err) } live := v.Manifest().Live - f, size, err := v.Open(live) + f, err := v.Open(live) if err != nil { t.Fatal(err) } @@ -151,18 +153,18 @@ func TestASegmentSealedOrPrunedUnderAReaderIsReadFromItsDescriptor(t *testing.T) if err := l.Seal(); err != nil { t.Fatal(err) } - if _, _, err := v.Open(live); !errors.Is(err, ErrMoved) { + if _, err := v.Open(live); !errors.Is(err, ErrMoved) { t.Errorf("the live segment a seal renamed opened as %v, want ErrMoved", err) } mustAppend(t, l, "ccc") - if _, _, err := v.Open(live); !errors.Is(err, ErrMoved) { + if _, err := v.Open(live); !errors.Is(err, ErrMoved) { t.Errorf("a new live segment opened under the old one's view: %v, want ErrMoved", err) } mustAppend(t, l, "ddd", "eee") if err := l.Prune(1); err != nil { t.Fatal(err) } - raw, err := io.ReadAll(io.NewSectionReader(f, 0, size)) + raw, err := io.ReadAll(io.NewSectionReader(f, 0, f.Size())) if err != nil || string(raw) != "aaa\nbbb\n" { t.Errorf("read through the descriptor after a seal and a prune: %q, %v", raw, err) } @@ -186,12 +188,12 @@ func TestALiveSegmentSealedAtTheCapUnderAViewIsMoved(t *testing.T) { if err := l.Prune(1); err != nil { t.Fatal(err) } - v, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + v, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil { t.Fatal(err) } live := v.Manifest().Live - f, _, err := v.Open(live) + f, err := v.Open(live) if err != nil { t.Fatalf("the live segment under its own view: %v", err) } @@ -200,7 +202,7 @@ func TestALiveSegmentSealedAtTheCapUnderAViewIsMoved(t *testing.T) { if m := l.Manifest(); m.Dropped != 1 || len(m.Segments) != 3 || m.Live.First != sum("ggg") { t.Fatalf("want a seal at the cap and a live segment beginning with ggg, got %+v", m) } - if _, _, err := v.Open(live); !errors.Is(err, ErrMoved) { + if _, err := v.Open(live); !errors.Is(err, ErrMoved) { t.Errorf("the live segment after a seal at the cap opened under the old view: %v, want ErrMoved", err) } } @@ -215,7 +217,7 @@ func TestALiveFileBetweenASealsManifestAndItsRenameIsMoved(t *testing.T) { cfg := config(logDir(t), 64, 256) l, _ := crashOpen(t, cfg, 1<<30) mustAppend(t, l, "aaa", "bbb") - before, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + before, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil { t.Fatal(err) } @@ -224,23 +226,23 @@ func TestALiveFileBetweenASealsManifestAndItsRenameIsMoved(t *testing.T) { if err := l.Seal(); !errors.Is(err, errCrash) { t.Fatalf("a seal stopped at its rename: %v", err) } - during, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + during, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil { t.Fatalf("a view of the manifest between the manifest and the rename: %v", err) } if m := during.Manifest(); len(m.Segments) != 1 || m.Segments[0].State != StateSealed { t.Errorf("the view between the manifest and the rename names %+v, want segment 1 sealed", m) } - if _, _, err := during.Open(during.Manifest().Live); !errors.Is(err, ErrMoved) { + if _, err := during.Open(during.Manifest().Live); !errors.Is(err, ErrMoved) { t.Errorf("its live file opened: %v, want ErrMoved", err) } - if _, _, err := before.Open(before.Manifest().Live); !errors.Is(err, ErrMoved) { + if _, err := before.Open(before.Manifest().Live); !errors.Is(err, ErrMoved) { t.Errorf("the live segment of a view read before the seal, opened in its window: %v, want ErrMoved", err) } _ = l.release() _, l = recovered(t, cfg) _ = l.Close() - v, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + v, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil || len(v.Manifest().Segments) != 1 || v.Manifest().Live.Lines != 0 { t.Errorf("after the seal was completed the view is %v, %v; want one sealed segment and none live", err, v) } @@ -259,7 +261,7 @@ func TestALiveFileOpenedBeforeASealsRenameCompletedIsMoved(t *testing.T) { if err := l.Seal(); !errors.Is(err, errCrash) { t.Fatalf("a seal stopped at its rename: %v", err) } - v, err := Inspect(cfg.Dir, cfg.MaxLineBytes) + v, err := inspectAt(cfg.Dir, cfg.MaxLineBytes) if err != nil { t.Fatal(err) } diff --git a/internal/segmentlog/write.go b/internal/segmentlog/write.go index 6d50453f0..400e2277f 100644 --- a/internal/segmentlog/write.go +++ b/internal/segmentlog/write.go @@ -9,6 +9,8 @@ import ( "os" "slices" "time" + + "github.com/guardana/control/internal/recordlog" ) // usable refuses a call on a log that is closed or that a seal or a prune @@ -41,6 +43,9 @@ func (l *segments) Append(ctx context.Context, lines []byte) error { return err } if err := l.makeRoom(int64(len(lines))); err != nil { + if errors.Is(err, ErrBudget) { + l.refused++ + } return err } if err := l.file.AppendLines(ctx, lines); err != nil { @@ -282,7 +287,7 @@ func (l *segments) Locate(key Digest) SegmentAnswer { l.mu.Lock() defer l.mu.Unlock() if err := l.usable(); err != nil { - return SegmentAnswer{cause: err.Error()} + return recordlog.NotFound(err.Error()) } return locate(l.segs, l.liveSegment(), key) } diff --git a/internal/trailfile/held.go b/internal/trailfile/held.go index f2aa9d9fc..964381eed 100644 --- a/internal/trailfile/held.go +++ b/internal/trailfile/held.go @@ -1,110 +1,22 @@ package trailfile import ( - "crypto/sha256" - "errors" - "fmt" - "os" - "strconv" + "context" - "github.com/guardana/control/internal/segmentlog" + "github.com/guardana/control/internal/recordlog" ) -// stillHeld reads back each line the index answers an append with, where the -// log wrote it, in the directory the log opened, reading no more than those -// lines. A line gone, cut or changed means the index no longer says what the -// log holds, so the log fails, refusing this append and every later call. -func (l *Log) stillHeld(held []place) error { +// stillHeld reads back, through the log, each line the index answers an +// append with, where the log wrote it, reading no more than those lines. A +// line gone, cut or changed means the index no longer says what the log +// holds, so the log fails, refusing this append and every later call. +func (l *Log) stillHeld(ctx context.Context, held []place) error { if len(held) == 0 { return nil } - if err := l.readBack(held); err != nil { - l.failed = fmt.Errorf("%w: a line the log holds is no longer as it was written: %w", segmentlog.ErrFailed, err) - return l.failed - } - return nil -} - -func (l *Log) readBack(held []place) error { - // The trailing "." fails on anything but a directory rather than wait on - // a named pipe put at the log's path. - root, err := os.OpenRoot(l.dir + string(os.PathSeparator) + ".") - if err != nil { - return err - } - defer func() { _ = root.Close() }() - info, err := root.Stat(".") - switch { - case err != nil: - return err - case !os.SameFile(info, l.dirInfo): - return fmt.Errorf("%s is another directory than the log opened", strconv.Quote(l.dir)) - } - m := l.rl.Manifest() - opened := map[string]*os.File{} - defer func() { - for _, f := range opened { - _ = f.Close() - } - }() + spans := make([]recordlog.Span, 0, len(held)) for _, p := range held { - name, offset, err := segmentAt(m, p) - if err != nil { - return err - } - f, ok := opened[name] - if !ok { - if f, err = openHeld(root, name); err != nil { - return err - } - opened[name] = f - } - line := make([]byte, p.size) - if _, err := f.ReadAt(line, offset); err != nil { - return fmt.Errorf("%s at offset %d: %w", name, offset, err) - } - if sha256.Sum256(line) != p.line { - return fmt.Errorf("%s at offset %d holds another line", name, offset) - } - } - return nil -} - -// segmentAt is the file of the segment of m holding the line at p, and the -// line's offset in it. -func segmentAt(m segmentlog.Manifest, p place) (string, int64, error) { - var start int64 - for _, s := range m.Segments { - if s.State != segmentlog.StateSealed { - continue - } - if p.at+p.size <= start+s.Bytes { - return s.File, p.at - start, nil - } - start += s.Bytes - } - if p.at+p.size <= start+m.Live.Bytes { - return segmentlog.LiveName, p.at - start, nil - } - return "", 0, fmt.Errorf("no segment holds the line at offset %d", p.at) -} - -// openHeld opens the regular file at name in root to read it, refusing a -// link at the name, without waiting on a named pipe. -func openHeld(root *os.Root, name string) (*os.File, error) { - before, err := root.Lstat(name) - switch { - case err != nil: - return nil, err - case !before.Mode().IsRegular(): - return nil, fmt.Errorf("%s: %w", name, ErrNotRegular) - } - f, err := root.OpenFile(name, os.O_RDONLY|readFlags, 0) - if err != nil { - return nil, err - } - if after, err := f.Stat(); err != nil || !os.SameFile(before, after) { - return nil, errors.Join(fmt.Errorf("another file stood at %s when it was opened", name), err, f.Close()) + spans = append(spans, recordlog.Span{Offset: p.at, Size: p.size, Sum: p.line}) } - return f, nil + return l.latch(l.rl.Holds(ctx, spans)) } diff --git a/internal/trailfile/kind.go b/internal/trailfile/kind.go new file mode 100644 index 000000000..f9d56185e --- /dev/null +++ b/internal/trailfile/kind.go @@ -0,0 +1,28 @@ +package trailfile + +import ( + "github.com/guardana/control/internal/evidence" + "github.com/guardana/control/internal/recordlog" + "github.com/guardana/control/internal/segmentlog" +) + +// recordConfig is the record log of trail segments in dir as a reader opens +// it. A log of trail segments is of the segments kind: no key selects +// another until a second kind exists. +func recordConfig(dir string) recordlog.Config { + return recordlog.Config{Kind: recordlog.KindSegments, Location: dir, + Bounds: recordlog.Bounds{MaxLineBytes: evidence.MaxLineBytes}} +} + +// openRecordLog opens the writer of cfg, handing visit each line it holds, +// with its live segment opened as Open opens a trail file. +func openRecordLog(cfg recordlog.Config, visit func([]byte) error) (recordlog.Log, error) { + cfg.Visit = visit + return segmentlog.Open(cfg, segmentlog.Options{OpenLive: openLive}) +} + +// InspectLog opens the log of trail segments in dir to read it as it is now, +// holding no lock and writing nothing. +func InspectLog(dir string) (recordlog.Reader, error) { + return segmentlog.Inspect(recordConfig(dir)) +} diff --git a/internal/trailfile/log.go b/internal/trailfile/log.go index 6c1c4a214..5378b25a4 100644 --- a/internal/trailfile/log.go +++ b/internal/trailfile/log.go @@ -13,7 +13,7 @@ import ( "github.com/guardana/control/adapters/otel" controlv1 "github.com/guardana/control/api/gen/go/guardana/control/v1" - "github.com/guardana/control/internal/evidence" + "github.com/guardana/control/internal/recordlog" "github.com/guardana/control/internal/segmentlog" ) @@ -41,7 +41,7 @@ type LogConfig struct { // is not written again once its line is read back where the log wrote it. type Log struct { mu sync.Mutex - rl segmentlog.RecordLog + rl recordlog.Log // dir is the log's directory by its absolute, cleaned path, the one the // segment log opened. dir string @@ -59,7 +59,7 @@ type Log struct { failed error } -// OpenLog opens the log in cfg.Dir, of the default kind, and holds it until +// OpenLog opens the log in cfg.Dir, of the one kind, and holds it until // Close. Every line of every segment not pruned is read and indexed, and the // open is refused when a line is not one event, is of another tenant or // project, or carries an event id another line carries with other content. @@ -71,7 +71,7 @@ func OpenLog(cfg LogConfig) (*Log, error) { now = time.Now } if cfg.Dir == "" { - return nil, fmt.Errorf("%w: no directory", segmentlog.ErrConfig) + return nil, fmt.Errorf("%w: no directory", recordlog.ErrConfig) } dir, err := filepath.Abs(cfg.Dir) if err != nil { @@ -79,19 +79,17 @@ func OpenLog(cfg LogConfig) (*Log, error) { } l := &Log{dir: dir, bound: binding{tenant: cfg.Tenant, project: cfg.Project}, ids: index{}} number, at := 0, int64(0) - rl, err := segmentlog.Open(segmentlog.Config{ - Kind: segmentlog.KindSegments, Dir: dir, Tenant: cfg.Tenant, Project: cfg.Project, - SegmentBytes: cfg.SegmentBytes, MaxBytes: cfg.MaxBytes, MaxLineBytes: evidence.MaxLineBytes, Now: now, - OpenLive: openLive, - Visit: func(line []byte) error { - number++ - ev, err := l.ids.addLine(number, at, line) - at += int64(len(line)) - if err == nil && l.bound.refusesEvent(ev) { - err = fmt.Errorf("%w: %w: line %d", ErrDamaged, ErrBinding, number) - } - return err - }, + rc := recordConfig(dir) + rc.Tenant, rc.Project, rc.Now = cfg.Tenant, cfg.Project, now + rc.Bounds.SegmentBytes, rc.Bounds.MaxBytes = cfg.SegmentBytes, cfg.MaxBytes + rl, err := openRecordLog(rc, func(line []byte) error { + number++ + ev, err := l.ids.addLine(number, at, line) + at += int64(len(line)) + if err == nil && l.bound.refusesEvent(ev) { + err = fmt.Errorf("%w: %w: line %d", ErrDamaged, ErrBinding, number) + } + return err }) if err != nil { return nil, err @@ -141,7 +139,7 @@ func (f liveFile) Close() error { return f.w.Close() } // gone, cut or changed fails the log and refuses the append. The whole // append is refused as ErrBinding when one event is of another tenant // or project, as ErrConflict when an event id the log or the append holds -// arrives with another line, and as segmentlog.ErrBudget when it would take +// arrives with another line, and as recordlog.ErrBudget when it would take // the log past its byte bound, which is no refusal for good: the sender // sends it again. func (l *Log) Append(ctx context.Context, events []*controlv1.Event) error { @@ -169,7 +167,7 @@ func (l *Log) Append(ctx context.Context, events []*controlv1.Event) error { if err != nil { return err } - if err := l.stillHeld(held); err != nil { + if err := l.stillHeld(ctx, held); err != nil { return err } if len(buf) == 0 { @@ -185,7 +183,7 @@ func (l *Log) Append(ctx context.Context, events []*controlv1.Event) error { // latch keeps a failure of the segment log, so an append the index alone // answers is refused too. func (l *Log) latch(err error) error { - if errors.Is(err, segmentlog.ErrFailed) { + if errors.Is(err, recordlog.ErrFailed) { l.failed = err } return err @@ -234,7 +232,7 @@ func (l *Log) reindex() error { err = l.sameDir() } if err != nil { - l.failed = fmt.Errorf("%w: the prune completed, and indexing the segments it left failed: %w", segmentlog.ErrFailed, err) + l.failed = fmt.Errorf("%w: the prune completed, and indexing the segments it left failed: %w", recordlog.ErrFailed, err) return l.failed } l.stale = false @@ -255,11 +253,11 @@ func (l *Log) sameDir() error { } // Manifest is the log as it is now. -func (l *Log) Manifest() segmentlog.Manifest { +func (l *Log) Manifest() recordlog.Manifest { l.mu.Lock() defer l.mu.Unlock() if l.rl == nil { - return segmentlog.Manifest{} + return recordlog.Manifest{} } return l.rl.Manifest() } diff --git a/internal/trailfile/log_holding_test.go b/internal/trailfile/log_holding_test.go new file mode 100644 index 000000000..d4295fbdf --- /dev/null +++ b/internal/trailfile/log_holding_test.go @@ -0,0 +1,61 @@ +package trailfile + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/guardana/control/internal/recordlog" + "github.com/guardana/control/internal/segmentlog" +) + +// TestAHoldingOfUnknownIsNeverReadAsFree: a live segment ending in a line +// part written, in a log whose lock no reader can ask, is neither read nor +// exported as one no writer holds; with the lock there and free, the same +// bytes read as unheld and export as a partial tail. +func TestAHoldingOfUnknownIsNeverReadAsFree(t *testing.T) { + dir := filepath.Join(t.TempDir(), "log") + l := openTestLog(t, logConfig(dir)) + appendTo(t, l, event(1)) + if err := l.Close(); err != nil { + t.Fatal(err) + } + appendLive(t, dir, partialTail) + tailReadAsUnheld(t, dir) + + lock := filepath.Join(dir, segmentlog.LockName) + if err := os.Remove(lock); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(lock, 0o700); err != nil { + t.Fatal(err) + } + if rep, err := ReadPath(dir, DefaultMaxLines); !errors.Is(err, recordlog.ErrHoldingUnknown) { + t.Errorf("a read with the holding unknown: %+v, %v; want ErrHoldingUnknown", rep, err) + } + var out bytes.Buffer + if _, err := ExportLog(dir, Query{Limit: 10}, &out); !errors.Is(err, recordlog.ErrHoldingUnknown) { + t.Errorf("an export with the holding unknown: %v, want ErrHoldingUnknown\n%s", err, out.String()) + } + if bytes.Contains(out.Bytes(), []byte(gapPartialTail)) { + t.Errorf("the export reported the tail as a writer's leftovers:\n%s", out.String()) + } +} + +// tailReadAsUnheld checks the log in dir, its lock free, reads and exports its +// partial tail as no writer's. +func tailReadAsUnheld(t *testing.T, dir string) { + t.Helper() + rep, err := ReadPath(dir, DefaultMaxLines) + if err != nil || rep.Held || rep.Unread != int64(len(partialTail)) { + t.Fatalf("with no writer: %+v, %v; want the tail read as unheld", rep, err) + } + var out bytes.Buffer + tr, err := ExportLog(dir, Query{Limit: 10}, &out) + if err != nil || tr.WriterHeld || tr.TailBytes != int64(len(partialTail)) || tr.Gaps != 1 || + !bytes.Contains(out.Bytes(), []byte(gapPartialTail)) { + t.Fatalf("the export with no writer: %+v, %v\n%s\nwant the tail a partial-tail gap", tr, err, out.String()) + } +} diff --git a/internal/trailfile/log_test.go b/internal/trailfile/log_test.go index 7b1cbcd70..9cff3c564 100644 --- a/internal/trailfile/log_test.go +++ b/internal/trailfile/log_test.go @@ -16,7 +16,6 @@ import ( "github.com/guardana/control/adapters/otel" controlv1 "github.com/guardana/control/api/gen/go/guardana/control/v1" - "github.com/guardana/control/internal/evidence" "github.com/guardana/control/internal/segmentlog" ) @@ -401,7 +400,7 @@ func TestFollowingNextCursorUntilTheEndReadsEveryLineOnce(t *testing.T) { func TestALiveSegmentSealedBetweenAViewAndItsOpenIsMoved(t *testing.T) { dir := filepath.Join(t.TempDir(), "log") l := openTestLog(t, logConfig(dir)) - v, err := segmentlog.Inspect(dir, evidence.MaxLineBytes) + v, err := InspectLog(dir) if err != nil { t.Fatal(err) } diff --git a/internal/trailfile/segments.go b/internal/trailfile/segments.go index 49925845a..c37d1c0a0 100644 --- a/internal/trailfile/segments.go +++ b/internal/trailfile/segments.go @@ -11,8 +11,8 @@ import ( "strconv" "time" - "github.com/guardana/control/internal/evidence" "github.com/guardana/control/internal/lineexport" + "github.com/guardana/control/internal/recordlog" "github.com/guardana/control/internal/segmentlog" ) @@ -108,7 +108,7 @@ func ExportPath(path string, q Query, w io.Writer) (Trailer, error) { // ExportLog writes the evidence export of the log in dir, one segment at a // time. With no cursor it is the first segment not pruned. A segment is named -// to a cursor, and in the header's source, by segmentlog.SegmentKey of its +// to a cursor, and in the header's source, by recordlog.SegmentKey of its // number and its first line, so no two segments of the log share a cursor. // The trailer says the end was reached only at the end of the last segment // that held a line when the export began; at the end of an earlier one its @@ -123,7 +123,7 @@ func ExportLog(dir string, q Query, w io.Writer) (Trailer, error) { } for range moveRetries { src, after, done, err := openForExport(dir, q.After) - if errors.Is(err, segmentlog.ErrMoved) { + if errors.Is(err, recordlog.ErrMoved) { continue } if err != nil { @@ -132,14 +132,14 @@ func ExportLog(dir string, q Query, w io.Writer) (Trailer, error) { tr, err := export(src, q, after, w) return tr, errors.Join(err, done()) } - return Trailer{}, fmt.Errorf("%w: %d times running", segmentlog.ErrMoved, moveRetries) + return Trailer{}, fmt.Errorf("%w: %d times running", recordlog.ErrMoved, moveRetries) } // openForExport finds the segment an export after the cursor reads, and opens // it. It returns the source, the cursor to start after within it, and what // closes it. func openForExport(dir, cursor string) (Source, string, func() error, error) { - v, err := segmentlog.Inspect(dir, evidence.MaxLineBytes) + v, err := InspectLog(dir) if err != nil { return Source{}, "", nil, err } @@ -157,22 +157,22 @@ func openForExport(dir, cursor string) (Source, string, func() error, error) { // sealed one to the next once that holds a line. A cursor at that end names // the segment's last line, which the manifest holds, or it is refused as // changed: the move on reads none of the segment's bytes to check it. -func resume(v *segmentlog.View, cursor string) (segmentlog.SegmentAnswer, string, error) { +func resume(v recordlog.Reader, cursor string) (recordlog.SegmentAnswer, string, error) { key, offset, line, err := lineexport.CursorAt(cursor, ErrCursorMalformed) if err != nil { - return segmentlog.SegmentAnswer{}, "", err + return recordlog.SegmentAnswer{}, "", err } ans := v.Locate(key) switch ans.State() { - case segmentlog.StatePruned: + case recordlog.StatePruned: s := ans.Segment() return ans, "", fmt.Errorf("%w: segment %d, pruned at %s", ErrCursorExpired, s.Seq, s.PrunedAt.Format(time.RFC3339)) - case segmentlog.StateSealed, segmentlog.StateLive: + case recordlog.StateSealed, recordlog.StateLive: default: return ans, "", fmt.Errorf("%w: %s", ErrCursorOtherFile, ans.Cause()) } s := ans.Segment() - if s.State != segmentlog.StateSealed || offset != s.Bytes { + if s.State != recordlog.StateSealed || offset != s.Bytes { return ans, cursor, nil } if line != s.Last { @@ -184,35 +184,32 @@ func resume(v *segmentlog.View, cursor string) (segmentlog.SegmentAnswer, string return ans, cursor, nil } -// openSource opens the segment s of the log in dir as an export's source. A -// live segment that holds no line and is not there is an empty source. -func openSource(dir string, v *segmentlog.View, s segmentlog.Segment, after string) (Source, string, func() error, error) { - name := filepath.Join(dir, s.File) - f, size, err := v.Open(s) - gone := prunedBefore(v, s.Seq) - if s.State == segmentlog.StateLive && s.Lines == 0 && errors.Is(err, fs.ErrNotExist) { - return Source{Name: name, R: bytes.NewReader(nil), PrunedBefore: gone}, after, func() error { return nil }, nil - } +// openSource opens the segment s of the log v reads, in dir, as an export's +// source. Whether a writer holds the live segment is asked of the log, and a +// holding of unknown is an error, never free. +func openSource(dir string, v recordlog.Reader, s recordlog.Segment, after string) (Source, string, func() error, error) { + c, err := v.Open(s) if err != nil { return Source{}, "", nil, err } seq := s.Seq m := v.Manifest() - src := Source{Name: name, R: f, Size: size, More: holdsLater(v, s), PrunedBefore: gone, Tenant: m.Tenant, - Project: m.Project, Key: func(first lineexport.Digest) lineexport.Digest { return segmentlog.SegmentKey(seq, first) }} - if s.State == segmentlog.StateLive { - src.Held = func() (bool, error) { return heldByWriter(f) } + src := Source{Name: filepath.Join(dir, s.File), R: c, Size: c.Size(), More: holdsLater(v, s), + PrunedBefore: prunedBefore(v, s.Seq), Tenant: m.Tenant, Project: m.Project, + Key: func(first lineexport.Digest) lineexport.Digest { return recordlog.SegmentKey(seq, first) }} + if s.State == recordlog.StateLive { + src.Held = func() (bool, error) { return v.Holding().Held() } } - return src, after, f.Close, nil + return src, after, c.Close, nil } // prunedBefore is how many segments before seq the view found gone: those // whose tombstones were dropped, and those pruned. -func prunedBefore(v *segmentlog.View, seq int) int { +func prunedBefore(v recordlog.Reader, seq int) int { m := v.Manifest() n := m.Dropped for _, s := range m.Segments { - if s.Seq < seq && s.State == segmentlog.StatePruned { + if s.Seq < seq && s.State == recordlog.StatePruned { n++ } } @@ -222,13 +219,13 @@ func prunedBefore(v *segmentlog.View, seq int) int { // holdsLater reports whether a segment after s held a line, or bytes no // newline ends, when the view was read, so an export of s has not reached the // log's end at s's. -func holdsLater(v *segmentlog.View, s segmentlog.Segment) bool { - if s.State != segmentlog.StateSealed { +func holdsLater(v recordlog.Reader, s recordlog.Segment) bool { + if s.State != recordlog.StateSealed { return false } next := v.After(s.Seq) - return next.State() == segmentlog.StateSealed || - next.State() == segmentlog.StateLive && (next.Segment().Lines > 0 || v.Tail() > 0) + return next.State() == recordlog.StateSealed || + next.State() == recordlog.StateLive && (next.Segment().Lines > 0 || v.Manifest().Tail > 0) } // ReadPath reads a trail file as ReadFile does, or every segment of a log not @@ -252,12 +249,12 @@ func ReadPath(path string, maxLines int) (Report, error) { func ReadLog(dir string, maxLines int) (Report, error) { for range moveRetries { rep, err := readLog(dir, maxLines) - if errors.Is(err, segmentlog.ErrMoved) { + if errors.Is(err, recordlog.ErrMoved) { continue } return rep, err } - return Report{}, fmt.Errorf("%w: %d times running", segmentlog.ErrMoved, moveRetries) + return Report{}, fmt.Errorf("%w: %d times running", recordlog.ErrMoved, moveRetries) } func readLog(dir string, maxLines int) (Report, error) { @@ -274,20 +271,19 @@ func readLog(dir string, maxLines int) (Report, error) { return Report{}, err } rep.Log, rep.Pruned = true, files.pruned - if rep.Unread == 0 || files.live == nil { + if rep.Unread == 0 { return rep, nil } - if rep.Held, err = heldByWriter(files.live); err != nil { + if rep.Held, err = files.reader.Holding().Held(); err != nil { return Report{}, err } return rep, nil } -// logFiles is what openLog found beside the segments it opened: the live -// segment's file when there is one, how many segments are gone, and what the -// log is bound to. +// logFiles is what openLog found beside the segments it opened: the log as +// read, how many segments are gone, and what the log is bound to. type logFiles struct { - live *os.File + reader recordlog.Reader pruned int bound binding } @@ -297,36 +293,30 @@ type logFiles struct { // opened, with the live segment's file and the segments gone, and what // closes them all. func openLog(dir string) (io.Reader, logFiles, func(), error) { - v, err := segmentlog.Inspect(dir, evidence.MaxLineBytes) + v, err := InspectLog(dir) if err != nil { return nil, logFiles{}, nil, err } m := v.Manifest() var readers []io.Reader - files := logFiles{pruned: prunedBefore(v, m.Live.Seq), bound: binding{tenant: m.Tenant, project: m.Project}} - var opened []*os.File + files := logFiles{reader: v, pruned: prunedBefore(v, m.Live.Seq), bound: binding{tenant: m.Tenant, project: m.Project}} + var opened []recordlog.Content done := func() { - for _, f := range opened { - _ = f.Close() + for _, c := range opened { + _ = c.Close() } } for _, s := range append(m.Segments, m.Live) { - if s.State == segmentlog.StatePruned { + if s.State == recordlog.StatePruned { continue } - f, size, err := v.Open(s) - if s.State == segmentlog.StateLive && s.Lines == 0 && errors.Is(err, fs.ErrNotExist) { - break - } + c, err := v.Open(s) if err != nil { done() return nil, logFiles{}, nil, err } - opened = append(opened, f) - readers = append(readers, io.NewSectionReader(f, 0, size)) - if s.State == segmentlog.StateLive { - files.live = f - } + opened = append(opened, c) + readers = append(readers, io.NewSectionReader(c, 0, c.Size())) } return io.MultiReader(readers...), files, done, nil } @@ -345,7 +335,7 @@ func LogBytes(dir string, limit int64) ([]byte, error) { } for range moveRetries { r, files, done, err := openLog(dir) - if errors.Is(err, segmentlog.ErrMoved) { + if errors.Is(err, recordlog.ErrMoved) { continue } if err != nil { @@ -365,5 +355,5 @@ func LogBytes(dir string, limit int64) ([]byte, error) { } return raw, nil } - return nil, fmt.Errorf("%w: %d times running", segmentlog.ErrMoved, moveRetries) + return nil, fmt.Errorf("%w: %d times running", recordlog.ErrMoved, moveRetries) } diff --git a/scripts/ports.txt b/scripts/ports.txt index 96cd36dad..55597b275 100644 --- a/scripts/ports.txt +++ b/scripts/ports.txt @@ -7,5 +7,5 @@ trust-roster internal/trust.Roster file testdata/ports/trust-roster trust operator-authenticator internal/operators.Authenticator roster testdata/ports/operator-authenticator operators.authenticator operator-authorizer internal/operators.Authorizer roster testdata/ports/operator-authorizer operators.authorizer -record-log internal/segmentlog.RecordLog segments testdata/ports/record-log none +record-log internal/recordlog.Log segments testdata/ports/record-log none approval-authority internal/gateway.ApprovalAuthority required testdata/ports/approval-authority approvals.authority diff --git a/testdata/ports/record-log/10-a-reader-answers-as-the-log-did-when-it-was-opened.json b/testdata/ports/record-log/10-a-reader-answers-as-the-log-did-when-it-was-opened.json new file mode 100644 index 000000000..70ff07173 --- /dev/null +++ b/testdata/ports/record-log/10-a-reader-answers-as-the-log-did-when-it-was-opened.json @@ -0,0 +1,18 @@ +{ + "rule": "a reader opened on the log's configuration locates and counts the segments as the log holds them when the reader opens", + "segment_bytes": 8, + "max_bytes": 64, + "steps": [ + {"append": ["aaa", "bbb"]}, + {"append": ["ccc"]}, + {"reader": true, "locate": "aaa", "seq": 1, "state": "sealed"}, + {"reader": true, "locate": "ccc", "seq": 2, "state": "live"}, + {"reader": true, "retained": 12} + ], + "negative_control": [ + {"append": ["aaa", "bbb"]}, + {"reader": true, "locate": "aaa", "seq": 1, "state": "live"}, + {"reader": true, "locate": "ccc", "seq": 2, "state": "unknown"}, + {"reader": true, "retained": 8} + ] +} diff --git a/testdata/ports/record-log/11-a-read-back-of-another-line-fails-the-log.json b/testdata/ports/record-log/11-a-read-back-of-another-line-fails-the-log.json new file mode 100644 index 000000000..b791804a8 --- /dev/null +++ b/testdata/ports/record-log/11-a-read-back-of-another-line-fails-the-log.json @@ -0,0 +1,17 @@ +{ + "rule": "a read-back of a line where the log wrote another fails the log, which then takes no append", + "segment_bytes": 8, + "max_bytes": 64, + "steps": [ + {"append": ["aaa", "bbb"]}, + {"append": ["ccc"]}, + {"holds": [{"line": "aaa", "offset": 0}, {"line": "bbb", "offset": 0}], "want": "failed"}, + {"append": ["ddd"], "want": "failed"} + ], + "negative_control": [ + {"append": ["aaa", "bbb"]}, + {"append": ["ccc"]}, + {"holds": [{"line": "aaa", "offset": 0}, {"line": "bbb", "offset": 4}, {"line": "ccc", "offset": 8}]}, + {"append": ["ddd"]} + ] +} diff --git a/testdata/ports/record-log/12-a-read-back-past-the-retained-lines-fails-the-log.json b/testdata/ports/record-log/12-a-read-back-past-the-retained-lines-fails-the-log.json new file mode 100644 index 000000000..8bd398754 --- /dev/null +++ b/testdata/ports/record-log/12-a-read-back-past-the-retained-lines-fails-the-log.json @@ -0,0 +1,13 @@ +{ + "rule": "a read-back of a line past the lines the log retains fails the log", + "segment_bytes": 8, + "max_bytes": 64, + "steps": [ + {"append": ["aaa"]}, + {"holds": [{"line": "aaa", "offset": 4}], "want": "failed"} + ], + "negative_control": [ + {"append": ["aaa"]}, + {"holds": [{"line": "aaa", "offset": 0}]} + ] +} diff --git a/testdata/ports/record-log/13-a-writer-holds-the-log-until-it-closes.json b/testdata/ports/record-log/13-a-writer-holds-the-log-until-it-closes.json new file mode 100644 index 000000000..7f2f9ceb5 --- /dev/null +++ b/testdata/ports/record-log/13-a-writer-holds-the-log-until-it-closes.json @@ -0,0 +1,17 @@ +{ + "rule": "a reader finds the log held while a writer has it open, and free once it closed", + "segment_bytes": 8, + "max_bytes": 64, + "steps": [ + {"append": ["aaa"]}, + {"holding": "held"}, + {"close": true}, + {"holding": "free"} + ], + "negative_control": [ + {"append": ["aaa"]}, + {"close": true}, + {"reopen": true}, + {"holding": "held"} + ] +} From a21a09c11f56e723690f53a8203585b71bbe8937 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 18:11:36 +0100 Subject: [PATCH 02/12] test(recordlog): pin the read-back mode check, and say what a reader sees A segment others may write now fails a read-back in segmentlog and refuses a repeat in trailfile; both tests kill the mutant that swaps the checked open for a plain one. The import check drops a case that could only ever be an import cycle. Reader.Stats says which numbers are the writer's and unknown to a reader, never a measured zero. Signed-off-by: Konrad Karauda --- internal/recordlog/deps_test.go | 59 ++------------------------ internal/recordlog/port.go | 6 ++- internal/segmentlog/port_test.go | 28 ++++++++++++ internal/trailfile/log_holding_test.go | 20 +++++++++ 4 files changed, 56 insertions(+), 57 deletions(-) diff --git a/internal/recordlog/deps_test.go b/internal/recordlog/deps_test.go index 813401df9..c9c9b151b 100644 --- a/internal/recordlog/deps_test.go +++ b/internal/recordlog/deps_test.go @@ -3,26 +3,20 @@ package recordlog import ( "go/parser" "go/token" - "os" - "os/exec" "path/filepath" "slices" "strconv" "strings" "testing" - - "github.com/guardana/control/internal/brand" ) -// kindTree is the kind a port package must not reach. -const kindTree = "/internal/segmentlog" - // refusedImports are the packages that would hand a consumer files: the port -// names no file-system type. +// names no file-system type. The kind imports this package, so an import of +// the kind here is a cycle the compiler refuses already. var refusedImports = []string{"os", "io/fs", "io/ioutil", "path/filepath", "syscall", "golang.org/x/sys/unix"} // TestThePortImportsNoFileSystemTypes: no Go file of the package, whatever -// its build constraints, imports a package of file-system types or the kind. +// its build constraints, imports a package of file-system types. func TestThePortImportsNoFileSystemTypes(t *testing.T) { files, err := filepath.Glob("*.go") if err != nil { @@ -43,7 +37,7 @@ func TestThePortImportsNoFileSystemTypes(t *testing.T) { if err != nil { t.Fatal(err) } - if refusedImport(path) { + if slices.Contains(refusedImports, path) { t.Errorf("%s imports %s", name, path) } } @@ -53,48 +47,3 @@ func TestThePortImportsNoFileSystemTypes(t *testing.T) { t.Fatalf("read the imports of %d production file(s); the package has more", read) } } - -func refusedImport(path string) bool { - return slices.Contains(refusedImports, path) || path == brand.ModulePath+kindTree || - strings.HasPrefix(path, brand.ModulePath+kindTree+"/") -} - -// TestThePortReachesNoKind: no package the port depends on, on this platform -// or on windows, is the kind. -func TestThePortReachesNoKind(t *testing.T) { - for _, goos := range []string{"linux", "darwin", "windows"} { - cmd := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}}", ".") - cmd.Env = append(os.Environ(), "GOOS="+goos) - out, err := cmd.Output() - if err != nil { - t.Fatalf("GOOS=%s go list -deps: %v", goos, err) - } - deps := strings.Fields(string(out)) - // A listing that does not reach the package itself examined some - // other package, and would pass whatever it found. - if !slices.Contains(deps, brand.ModulePath+"/internal/recordlog") { - t.Fatalf("GOOS=%s: go list -deps reached %d package(s), not this one; nothing was examined", goos, len(deps)) - } - for _, dep := range deps { - if dep == brand.ModulePath+kindTree || strings.HasPrefix(dep, brand.ModulePath+kindTree+"/") { - t.Errorf("GOOS=%s: the port reaches %s", goos, dep) - } - } - } -} - -// TestTheImportCheckRefusesEachPackage: each refused package and the kind are -// refused, and the packages the port does import are not, so the check above -// can fail. -func TestTheImportCheckRefusesEachPackage(t *testing.T) { - for _, path := range append(slices.Clone(refusedImports), brand.ModulePath+kindTree, brand.ModulePath+kindTree+"/x") { - if !refusedImport(path) { - t.Errorf("%s is not refused", path) - } - } - for _, path := range []string{"io", "context", "time", "crypto/sha256", brand.ModulePath + "/internal/brand", "osx"} { - if refusedImport(path) { - t.Errorf("%s is refused", path) - } - } -} diff --git a/internal/recordlog/port.go b/internal/recordlog/port.go index 1dec0bccc..5659f9c02 100644 --- a/internal/recordlog/port.go +++ b/internal/recordlog/port.go @@ -148,8 +148,10 @@ type Reader interface { Open(s Segment) (Content, error) // Holding asks now whether a writer holds the log. Holding() Holding - // Stats is what the reader found. A reader counts no refusal of a - // writer, and knows the byte bounds only as its own Config gave them. + // Stats is what the reader found. Bounds.SegmentBytes, Bounds.MaxBytes + // and BudgetRefusals are the writer's, unknown to a reader: they hold what + // the reader's own Config gave, zero when it gave none, never a measured + // zero. Stats() Stats } diff --git a/internal/segmentlog/port_test.go b/internal/segmentlog/port_test.go index 5c73c4a1d..712317615 100644 --- a/internal/segmentlog/port_test.go +++ b/internal/segmentlog/port_test.go @@ -3,10 +3,13 @@ package segmentlog import ( "context" "errors" + "fmt" "os" "path/filepath" + "strings" "testing" + "github.com/guardana/control/internal/files" "github.com/guardana/control/internal/recordlog" ) @@ -179,6 +182,31 @@ func TestARefusedSpanFailsTheLogAndACancelledOneDoesNot(t *testing.T) { } } +// TestAReadBackOfASegmentOthersMayWriteFailsTheLog: a sealed segment the +// group may write holds the line it held and still fails a read-back, which +// judges the file as the writer does, naming its mode; owner-only, it passes. +func TestAReadBackOfASegmentOthersMayWriteFailsTheLog(t *testing.T) { + for _, c := range []struct { + mode os.FileMode + ok bool + }{{0o600, true}, {0o400, true}, {0o620, false}, {0o602, false}} { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa", "bbb") + mustAppend(t, l, "ccc") + if err := os.Chmod(filepath.Join(cfg.Dir, segmentFile(1)), c.mode); err != nil { + t.Fatal(err) + } + err := l.Holds(context.Background(), []recordlog.Span{{Offset: 0, Size: 4, Sum: sum("aaa")}}) + switch { + case c.ok && err != nil: + t.Errorf("mode %04o: %v, want the line read back", c.mode, err) + case !c.ok && (!errors.Is(err, ErrFailed) || !errors.Is(err, files.ErrMode) || !strings.Contains(fmt.Sprint(err), fmt.Sprintf("mode %04o", c.mode))): + t.Errorf("mode %04o: %v, want ErrFailed naming the mode", c.mode, err) + } + } +} + // TestTheStatsCountWhatTheLogHolds: a writer counts its sealed, pruned and // dropped segments, the bytes retained, its bounds and each append the budget // refused; a reader counts the same segments and no refusal. diff --git a/internal/trailfile/log_holding_test.go b/internal/trailfile/log_holding_test.go index d4295fbdf..fa195c019 100644 --- a/internal/trailfile/log_holding_test.go +++ b/internal/trailfile/log_holding_test.go @@ -2,11 +2,14 @@ package trailfile import ( "bytes" + "context" "errors" "os" "path/filepath" "testing" + controlv1 "github.com/guardana/control/api/gen/go/guardana/control/v1" + "github.com/guardana/control/internal/files" "github.com/guardana/control/internal/recordlog" "github.com/guardana/control/internal/segmentlog" ) @@ -59,3 +62,20 @@ func tailReadAsUnheld(t *testing.T, dir string) { t.Fatalf("the export with no writer: %+v, %v\n%s\nwant the tail a partial-tail gap", tr, err, out.String()) } } + +// TestARepeatWhoseSealedSegmentOthersMayWriteIsRefused: a sealed segment the +// group may write, its bytes untouched, is no longer one only the collector +// wrote, and a resend of its event is refused, failing the log. +func TestARepeatWhoseSealedSegmentOthersMayWriteIsRefused(t *testing.T) { + l, dir := sealedLog(t) + if err := os.Chmod(filepath.Join(dir, firstSegment), 0o620); err != nil { //nolint:gosec // G302: the mode under test + t.Fatal(err) + } + if err := l.Append(context.Background(), []*controlv1.Event{event(1)}); !errors.Is(err, recordlog.ErrFailed) || + !errors.Is(err, files.ErrMode) { + t.Errorf("a resend of an event of a group-writable segment = %v, want ErrFailed naming the mode", err) + } + if err := l.Append(context.Background(), []*controlv1.Event{event(9)}); !errors.Is(err, recordlog.ErrFailed) { + t.Errorf("a new event after the refused resend = %v, want ErrFailed", err) + } +} From 8a11481a5f6bdb6ff7b1896694cb706259def639 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 18:48:03 +0100 Subject: [PATCH 03/12] fix(segmentlog): ask both locks before a log reads as free A reader asked only the directory's lock file whether a writer held the log. With `segments.lock` unlinked under a running collector, `trail` and `trail export` read its partial line as unheld and reported a `partial_tail` gap, where they had asked the live file's own lock before. Holding now asks both: held when either is held, free only when each is free or absent, unknown when either cannot be asked. It also answers unknown when the directory at the log's path is no longer the one the view inspected, and HeldByWriter is ErrNoLock where the platform has no file lock, so a lock it cannot ask is never read as free. Signed-off-by: Konrad Karauda --- internal/segmentlog/lock_unsupported.go | 5 +-- internal/segmentlog/port_test.go | 46 +++++++++++++++++++++++++ internal/segmentlog/view.go | 35 ++++++++++++++++--- internal/trailfile/log_holding_test.go | 23 +++++++++++++ 4 files changed, 103 insertions(+), 6 deletions(-) diff --git a/internal/segmentlog/lock_unsupported.go b/internal/segmentlog/lock_unsupported.go index da95e3f06..15e191295 100644 --- a/internal/segmentlog/lock_unsupported.go +++ b/internal/segmentlog/lock_unsupported.go @@ -8,5 +8,6 @@ import "os" // directory at once, so a writer refuses to open. func Lock(*os.File) error { return ErrNoLock } -// HeldByWriter is false: no writer that takes Lock opens a file here. -func HeldByWriter(*os.File) (bool, error) { return false, nil } +// HeldByWriter is ErrNoLock: a writer elsewhere may hold the file through a +// lock this platform cannot ask, so whether one does is unknown. +func HeldByWriter(*os.File) (bool, error) { return false, ErrNoLock } diff --git a/internal/segmentlog/port_test.go b/internal/segmentlog/port_test.go index 712317615..0277c2c99 100644 --- a/internal/segmentlog/port_test.go +++ b/internal/segmentlog/port_test.go @@ -262,3 +262,49 @@ func TestAnEmptyLiveSegmentWithNoFileOpensEmpty(t *testing.T) { t.Error(err) } } + +// TestAWriterHoldsTheLogThroughEitherLock: a live file a writer locks, as +// trailfile's does, reads as held with the directory's lock file unlinked; with +// neither lock held it is free, and another directory put at the log's path +// after the inspection is unknown. +func TestAWriterHoldsTheLogThroughEitherLock(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + if err := l.Close(); err != nil { + t.Fatal(err) + } + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + live, err := os.OpenFile(filepath.Join(cfg.Dir, LiveName), os.O_RDWR, 0) + if err != nil { + t.Fatal(err) + } + defer func() { _ = live.Close() }() + if err := Lock(live); err != nil { + t.Fatal(err) + } + if err := os.Remove(filepath.Join(cfg.Dir, LockName)); err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingHeld { + t.Errorf("with the lock file unlinked and the live file locked: %s, want held", h) + } + if err := live.Close(); err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingFree { + t.Errorf("with neither lock held: %s, want free", h) + } + if err := os.Rename(cfg.Dir, cfg.Dir+".moved"); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(cfg.Dir, 0o700); err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingUnknown { + t.Errorf("with another directory at the log's path: %s, want unknown", h) + } +} diff --git a/internal/segmentlog/view.go b/internal/segmentlog/view.go index 4163f32ab..4d3cf152f 100644 --- a/internal/segmentlog/view.go +++ b/internal/segmentlog/view.go @@ -16,6 +16,7 @@ import ( // seal or prune while a view is held; Open notices a segment that moved. type view struct { cfg settings + dir os.FileInfo tenant string project string dropped int @@ -42,10 +43,15 @@ func inspect(cfg settings) (*view, error) { return nil, err } defer func() { _ = root.Close() }() + dir, err := root.Stat(".") + if err != nil { + return nil, err + } v, err := readView(root, cfg) if err != nil { return nil, err } + v.dir = dir inspected() f, err := openRead(root, LiveName) if errors.Is(err, fs.ErrNotExist) { @@ -291,16 +297,37 @@ func (v *view) check(f *os.File, s Segment) (int64, error) { return info.Size(), nil } -// Holding asks whether a writer holds the log's directory now: free when it -// has no lock file, unknown when the directory or the lock file cannot be -// opened or asked. +// Holding asks whether a writer holds the log now, of the directory's lock +// file and of the live file's, which a writer may lock too, since either can +// be unlinked under it: held when either is held, free when each is free or +// absent, and unknown when either cannot be asked or the directory at the +// path is no longer the one inspected. func (v *view) Holding() recordlog.Holding { root, err := os.OpenRoot(v.cfg.Dir + string(os.PathSeparator) + ".") if err != nil { return recordlog.HoldingUnknown } defer func() { _ = root.Close() }() - f, err := openRead(root, LockName) + if dir, err := root.Stat("."); err != nil || v.dir == nil || !os.SameFile(dir, v.dir) { + return recordlog.HoldingUnknown + } + holding := recordlog.HoldingFree + for _, name := range []string{LockName, LiveName} { + switch heldAt(root, name) { + case recordlog.HoldingHeld: + holding = recordlog.HoldingHeld + case recordlog.HoldingFree: + default: + return recordlog.HoldingUnknown + } + } + return holding +} + +// heldAt asks whether a writer holds the lock of the file at name in root: +// free when there is no such file. +func heldAt(root *os.Root, name string) recordlog.Holding { + f, err := openRead(root, name) if errors.Is(err, fs.ErrNotExist) { return recordlog.HoldingFree } diff --git a/internal/trailfile/log_holding_test.go b/internal/trailfile/log_holding_test.go index fa195c019..2376353fd 100644 --- a/internal/trailfile/log_holding_test.go +++ b/internal/trailfile/log_holding_test.go @@ -79,3 +79,26 @@ func TestARepeatWhoseSealedSegmentOthersMayWriteIsRefused(t *testing.T) { t.Errorf("a new event after the refused resend = %v, want ErrFailed", err) } } + +// TestAnUnlinkedDirectoryLockLeavesALiveWritersTailHeld: with segments.lock +// unlinked under a running collector, its partial line is still a line being +// written, never a gap. +func TestAnUnlinkedDirectoryLockLeavesALiveWritersTailHeld(t *testing.T) { + dir := filepath.Join(t.TempDir(), "log") + l := openTestLog(t, logConfig(dir)) + appendTo(t, l, event(1)) + appendLive(t, dir, partialTail) + if err := os.Remove(filepath.Join(dir, segmentlog.LockName)); err != nil { + t.Fatal(err) + } + rep, err := ReadPath(dir, DefaultMaxLines) + if err != nil || !rep.Held { + t.Errorf("trail: held=%v err=%v, want held", rep.Held, err) + } + var out bytes.Buffer + tr, err := ExportLog(dir, Query{Limit: 10}, &out) + if err != nil || !tr.WriterHeld || bytes.Contains(out.Bytes(), []byte(gapPartialTail)) { + t.Errorf("export: writer_held=%v err=%v gap=%v, want held and no partial_tail gap", tr.WriterHeld, err, + bytes.Contains(out.Bytes(), []byte(gapPartialTail))) + } +} From d85885e301da1965d720d19167680eceff585762 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 18:48:04 +0100 Subject: [PATCH 04/12] docs(recordlog): describe the port, the third segments line and the locks ADR-0091 is accepted. The changelog names the read-back's file checks, the line `trail segments` adds, the lock a holding is asked of and the `recordlog:` refusals. The watch guide, the glossary, the status rows, the export contract and B14's acceptance say what the port is, what a reader sees and what stays open; two pages cover internal/recordlog. Signed-off-by: Konrad Karauda --- CHANGELOG.md | 23 ++++++ ...-to-its-consumers-with-a-read-interface.md | 2 +- docs/backlog.md | 2 +- docs/concepts/glossary.md | 2 +- docs/contracts.md | 13 ++-- .../watch-a-plane-without-a-collector.md | 18 ++--- docs/index.md | 2 +- docs/reference/cli.md | 2 +- docs/status.md | 18 +++-- ...o-its-consumers-with-a-read-interface.html | 4 +- site/docs/backlog.html | 2 +- site/docs/changelog.html | 71 ++++++++++++------- site/docs/concepts/glossary.html | 2 +- site/docs/contracts.html | 13 ++-- .../watch-a-plane-without-a-collector.html | 16 ++--- site/docs/index.html | 2 +- site/docs/status.html | 18 +++-- site/llms.txt | 2 +- 18 files changed, 136 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe329350a..fc2d66de2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,29 @@ verify one. ## [Unreleased] +### Security + +- `collect` checks for an earlier copy of a resent record through the open + directory, applying the same file type, owner and mode checks as on write. + A segment file writable by another account fails the log on such a resend. + `collect` refuses that record and the next new one. + +### Changed + +- `trail segments ` adds a third line with + `kind=segments max_line_bytes=786432 segment_bytes=unknown max_bytes=unknown budget_refusals=unknown`. + The byte bounds and budget refusal count are local to `collect`. +- For a directory of segments, `trail `, `writer_held` in + `trail export `, and `trail segments ` ask `segments.lock` + whether a writer holds the log. If the lock cannot be asked, + `trail segments` exits 1 with + `trail segments: recordlog: whether a writer holds the log is unknown`. + `trail` and `trail export` refuse the same way if the live segment ends in + a partial line. +- `collect`, `trail`, `trail export`, `trail segments` and `prune` use + `recordlog:` for shared log refusals. Refusals specific to segments keep + `segmentlog:`. + ### Fixed - `policy renew --out ` judges `--out` again if another renew replaces diff --git a/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md b/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md index e53941c5d..987770994 100644 --- a/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md +++ b/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md @@ -1,6 +1,6 @@ # ADR-0091: The record log port moves to its consumers, with a read interface -Status: proposed +Status: accepted Date: 2026-11-27 Amends [ADR-0072](0072-the-collector-keeps-bounded-segments-of-one-project-behind-a-credential.md) diff --git a/docs/backlog.md b/docs/backlog.md index 238da22a7..e0830afb0 100644 --- a/docs/backlog.md +++ b/docs/backlog.md @@ -77,7 +77,7 @@ mappings. | ID | Work | Depends on | Acceptance | | --- | --- | --- | --- | | B13 | Authenticate operators and scope authority | none | Under `approvals.authority: signed`, each receiver enforces operate and admin from the signed roster ([ADR-0071](adr/0071-operators-are-named-by-a-signed-roster.md), [ADR-0073](adr/0073-an-approval-counts-only-as-the-plane-judges-it.md)). Reads are checked by peer uid against `health.socket_uid` on the health socket and by file modes; the roster's `read` grant is reserved. A client's `Run-Token`, `Authorization` and `Cookie` reach no MCP upstream, and the paths that need a second account are tested under real accounts in a CI job declared required ([ADR-0081](adr/0081-tests-that-need-a-second-account-run-in-a-required-job.md)). A signed plane serves one tenant: a configuration whose `listener.principal.tenant_id` differs from `tenant_id` is refused at load ([ADR-0082](adr/0082-a-signed-document-names-its-plane-and-a-signed-plane-serves-one-tenant.md)), and a signed route may stop a finding's agent or principal, matched against the identity the listener's configuration names ([ADR-0083](adr/0083-a-finding-may-stop-an-agent-or-a-principal.md)). Open: reads and operations of another project are refused at every receiver, not only at the signed ones [contracts.md](contracts.md#signed-files-and-their-project-checks) lists. Under `directory` and `memory`, each receiver judges a project under the same tenant: answers and pauses take `tenant_id`, runs and stops the listener's. A stop of an agent or a principal exists outside `signed` and matches an authenticated end user, which needs a listener authenticator no configuration wires. Two operators with overlapping runs pass adversarial tests | -| B14 | Add retention and recovery | none | Rotation, disk budget, cursor expiry, duplicates, interrupted export and backup/restore are tested for evidence and observations. A restored process cannot reuse spent approval authority. Read-only inspection cannot mutate recovery state without saying so. The findings and observation logs take the RecordLog port, which then moves to its consumer with a read interface, a kind selector, its bounds and its diagnostics ([ADR-0072](adr/0072-the-collector-keeps-bounded-segments-of-one-project-behind-a-credential.md)) | +| B14 | Add retention and recovery | none | Rotation, disk budget, cursor expiry, duplicates, interrupted export and backup/restore are tested for evidence and observations. A restored process cannot reuse spent approval authority. Read-only inspection cannot mutate recovery state without saying so. The findings and observation logs take the RecordLog port, with a kind selector and its diagnostics ([ADR-0072](adr/0072-the-collector-keeps-bounded-segments-of-one-project-behind-a-credential.md)) | | B26 | Review findings and export an incident package | B13, B14 | A separate review log records scoped author, time, reason and revision for open/in-review/closed and disposition changes without changing the finding's verdict. Grouped occurrences retain source finding ids, rule versions, tenant/project and run references. Reopening, cross-project access, concurrent edits, export gaps and hostile text have cases. A metadata-only package joins the findings, decisions, approvals, policy/procedure digests, coverage and actual reaction results, marks missing inputs, and is read by an external consumer. Closing a case neither lifts a stop nor grants an approval. Evidence presets are versioned mappings from a named requirement to the records that bear on it, exported with their sources, missing inputs and scope and read by an external consumer; a preset never states a compliance verdict | | B38 | Show an approver the exact action they approve | B12, B13 | The review of a held call shows its principal, agent, delegation, resource, destination, consequential arguments and bounds, policy reasons and expiry from the held request, bound to its action digest, and names what was redacted or is unavailable. A redacted argument preview is shown only under an explicit setting, off by default. A changed, swapped or stale review, another project's call and hostile text are refused or marked in tests. A held call's notice (B12) links to this review in place of the existing one, and following the link approves nothing. Scripted operator and approver personas exercise the review over appropriate, inappropriate and under-informed cases. 1.0 bar: `own evidence` for that functional half. At least three approvers new to the project explain each case's effect, target and bounds before deciding, over the same cases; a fixed rubric scores the explanations, and the scores are published with the number of participants and cases. 1.0 bar: `not met` for the explanations while no new approver takes part; a persona's answers are simulated, with "human participants: 0". A click or the time spent on the page is not evidence of an informed decision | | B39 | A run drawn as a graph, with a rule editor beside it | B13, B26 | Starting from the static page `supervise --view` draws today ([run view](reference/run-view.md)), a local page draws one run's steps, decisions, findings and stops as a graph from the evidence and findings exports, marks missing and uncertain steps as such, and shows, for a selected step, the rule that decided it. A rule changed in the editor becomes a policy document that the existing commands test and sign before any plane takes it; the page itself grants and signs nothing. Cross-project access, hostile text in tool names and arguments, and a stale export have cases | diff --git a/docs/concepts/glossary.md b/docs/concepts/glossary.md index f61bd689f..dde8940b4 100644 --- a/docs/concepts/glossary.md +++ b/docs/concepts/glossary.md @@ -70,7 +70,7 @@ for the same thing; the right column is where the code defines it. | stop list | `stops.jsonl` in the directory `reaction.stops` names: a header naming the route, then `stop`, `covered` and `lift` lines, appended and never rewritten, which `react` and the `stops` commands write under the list's lock; a plane reads it every poll interval and takes no lock | `internal/reaction/stoplist/`, `internal/reaction/stopwrite/`, [reference/reaction](../reference/reaction.md#the-stop-list) | | stop list header | the first line of a stop list `3.0`: an envelope over a `reaction-list-header/3.0` body a roster operator signs, naming the list, its serial, the plane's `plane_id`, tenant, project and stop list file, the route and, for a list carried from another, the previous header's digest; a lift names it and the stop list floor keeps it | `HeaderSigned` in `internal/reaction/header2.go`, [reference/reaction-signed](../reference/reaction-signed.md) | | trail file | a file of events, one per line in the protobuf JSON mapping, each event id once; what `trail` and `trail export` read | `trailfile.Writer` in `internal/trailfile/writer.go` | -| trail segments | the directory the collector writes, bound to one tenant and project: sealed segments, each a trail file, a live one appends go to, and `segments.json` naming each, sealed or pruned; bounded in bytes, pruned only by an operator | `trailfile.Log` in `internal/trailfile/log.go` over `internal/segmentlog/` | +| trail segments | the directory the collector writes, bound to one tenant and project: sealed segments, each a trail file, a live one appends go to, and `segments.json` naming each, sealed or pruned; bounded in bytes, pruned only by an operator | `trailfile.Log` in `internal/trailfile/log.go` over the record log port `internal/recordlog/`, whose one kind is `internal/segmentlog/` | | trust | how far an observation's source can be believed, from its descriptor: `TRUST_SELF_REPORTED` (the agent's own process), `TRUST_PLATFORM` (the platform it runs on) or `TRUST_INDEPENDENT` (something the agent cannot influence) | `Trust` in `api/proto/guardana/control/observe/v1alpha1/source.proto` | | trust roster | the signed file that names operator keys and the tenant, project and level each may act on, under a pinned root, for at most 7 days at a serial that only climbs; a plane reads one only under the signed authority, through `trust.*` | `internal/trust/`, [ADR-0071](../adr/0071-operators-are-named-by-a-signed-roster.md) | | unrecorded read | a read that ran with a trail the sink did not take, under the explicit evidence setting; counted, never held and never closed | `Config.AllowReadsUnrecorded` in `internal/gateway/config.go` | diff --git a/docs/contracts.md b/docs/contracts.md index d60625d10..45c266e65 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1188,12 +1188,13 @@ The export reads the file up to its last newline, at the length the file had when it was opened, and holds no lock. The bytes after the last newline are a line a collector is still writing while one holds the file: the trailer counts them, `writer_held` is `true`, and the next export reads them once they end. -Whether a writer holds the file is asked only when such bytes exist. When none -holds it they are a `partial_tail` gap. A gap takes a record like any other, so -an export whose limit leaves no room for it ends with `end_reached` false and -the next export writes it. A reader refuses an export whose trailer counts -such bytes with `end_reached` true, `writer_held` false and no -`partial_tail` gap. +Whether a writer holds the file is asked only when such bytes exist; for a +directory of segments it is asked of the directory's lock, and when that +cannot be asked the export is refused. When none holds it they are a +`partial_tail` gap. A gap takes a record like any other, so an export whose +limit leaves no room for it ends with `end_reached` false and the next export +writes it. A reader refuses an export whose trailer counts such bytes with +`end_reached` true, `writer_held` false and no `partial_tail` gap. `end_reached` is `true` when every whole line was read and the bytes after the last newline were reported. diff --git a/docs/guides/watch-a-plane-without-a-collector.md b/docs/guides/watch-a-plane-without-a-collector.md index 917762e6d..1d289417b 100644 --- a/docs/guides/watch-a-plane-without-a-collector.md +++ b/docs/guides/watch-a-plane-without-a-collector.md @@ -2,7 +2,7 @@ title: Watch a plane without a collector summary: Run the collector the gateway binary ships, point a plane at it with its credential, read each request's trail in the segments it writes, and prune them. type: how-to -covers: [cmd/guardana-gateway/collect.go, cmd/guardana-gateway/trail.go, cmd/guardana-gateway/segments.go, adapters/otel/receive.go, adapters/otel/receiver.go, internal/trailfile/**, internal/segmentlog/**] +covers: [cmd/guardana-gateway/collect.go, cmd/guardana-gateway/trail.go, cmd/guardana-gateway/segments.go, adapters/otel/receive.go, adapters/otel/receiver.go, internal/trailfile/**, internal/recordlog/**, internal/segmentlog/**] --- # Watch a plane without a collector @@ -133,14 +133,14 @@ refused, exit 2: export the directory, whose header counts the segments pruned before. `evidence-report -state` follows the log from segment to segment. -`trail segments` prints the manifest: the segments sealed, pruned and -dropped, then each one's state, lines, bytes, key and dates, and whether a -collect holds it. `prune` removes the sealed segments up to the one named, -after writing each one's tombstone, which keeps its lines, bytes and digests. -A file is unlinked only while its name names the one read, though POSIX -leaves a moment between that check and the unlink. Stop collect first: a held -directory is refused, and so is a clock before the segment's seal. The live -segment is never pruned. +`trail segments` prints the manifest, whether a collect holds it, the log's +kind and line bound, with the collector's byte bounds and budget refusals +printed `unknown`; it exits 1 when whether a collect holds it is unknown. +`prune` removes sealed segments through the named one, writing tombstones +first with lines, bytes and digests. A file is unlinked only while its name +names the one read, though POSIX leaves a moment between check and unlink. +Stop collect first: a held directory or a clock before the seal is refused. +The live segment is never pruned. ## What the collector promises diff --git a/docs/index.md b/docs/index.md index 7ae2a28c6..3d0d2fc8c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -242,5 +242,5 @@ Have a tool ask before it acts or a sensor report what happened, hold a client t - [ADR-0088: A verdict that compares two events' times is at most suspected](adr/0088-a-verdict-that-compares-two-events-times-is-at-most-suspected.md): proposed - [ADR-0089: Outside signed, every receiver holds its input to the plane's one tenant and project](adr/0089-outside-signed-every-receiver-holds-its-input-to-the-planes-one-tenant-and-project.md): proposed - [ADR-0090: A listener authenticator names the principal a stop and a pause match](adr/0090-a-listener-authenticator-names-the-principal-a-stop-and-a-pause-match.md): proposed -- [ADR-0091: The record log port moves to its consumers, with a read interface](adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md): proposed +- [ADR-0091: The record log port moves to its consumers, with a read interface](adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md): accepted - [ADR-0092: The observation and finding logs are segment logs of one project](adr/0092-the-observation-and-finding-logs-are-segment-logs-of-one-project.md): proposed diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 44d71904d..ee6da363d 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -2,7 +2,7 @@ title: Command line summary: The two binaries, what each prints as its help, and the exit statuses they share. type: reference -covers: [cmd/guardana-control/**, cmd/guardana-gateway/**, internal/policykey/**, internal/pause/**, internal/trailfile/**, internal/segmentlog/**] +covers: [cmd/guardana-control/**, cmd/guardana-gateway/**, internal/policykey/**, internal/pause/**, internal/trailfile/**, internal/recordlog/**, internal/segmentlog/**] --- # Command line diff --git a/docs/status.md b/docs/status.md index 8a3c17e31..7871d7ec4 100644 --- a/docs/status.md +++ b/docs/status.md @@ -675,14 +675,20 @@ quarantines what a collector refuses, and drains one run at a time; - `adapters/otel/` also reads what the exporter sends, strictly, answers only after the records are synced, and refuses 401 a request without the collector's bearer credential -- `internal/segmentlog/` keeps a directory of segments bound to one tenant and - project, sealed at a byte bound, refused past a log bound, pruned only by an - operator with a tombstone first, and completed or refused after a crash +- `internal/recordlog/` declares the port: `Log` appends, seals, prunes, reads + back the lines it wrote and counts its statistics; `Reader` reads the + manifest and opens segments without a lock, and says whether a writer holds + the log as held, free or unknown, unknown never read as free. +- `internal/segmentlog/` is its one kind, `segments`: it keeps a directory of + segments bound to one tenant and project, sealed at a byte bound, refused + past a log bound, pruned only by an operator with a tombstone first, and + completed or refused after a crash. - `internal/trailfile/` writes each live segment under an exclusive lock, refuses another project's event, cuts a torn last line at open, and reads a - file or every segment back with each trail's chain checked; - `guardana-gateway collect` (a unix socket, `--tenant`, `--project`, - `--credential-file`), `trail`, `trail segments` and `prune` + file or every segment back with each trail's chain checked; `trail segments` + prints the log's statistics; `guardana-gateway collect` (a unix socket, + `--tenant`, `--project`, `--credential-file`), `trail`, `trail segments` and + `prune` - [guides/watch-a-plane-without-a-collector.md](guides/watch-a-plane-without-a-collector.md) - [ADR-0020](adr/0020-a-trail-and-counters-without-a-collector.md) - [ADR-0072](adr/0072-the-collector-keeps-bounded-segments-of-one-project-behind-a-credential.md) diff --git a/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html b/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html index bd6a19b62..e9596a2f5 100644 --- a/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html +++ b/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html @@ -4,7 +4,7 @@ ADR-0091: The record log port moves to its consumers, with a read interface · Guardana Control - + @@ -131,7 +131,7 @@

Project

    ADR-0091: The record log port moves to its consumers, with a read interface

    -

    Status: proposed +

    Status: accepted Date: 2026-11-27

    Amends ADR-0072 on where the RecordLog port is declared and how it is read.

    diff --git a/site/docs/backlog.html b/site/docs/backlog.html index d8391471d..7e7297fd5 100644 --- a/site/docs/backlog.html +++ b/site/docs/backlog.html @@ -297,7 +297,7 @@

    Milestone 3: a small team

    B14 Add retention and recovery none -Rotation, disk budget, cursor expiry, duplicates, interrupted export and backup/restore are tested for evidence and observations. A restored process cannot reuse spent approval authority. Read-only inspection cannot mutate recovery state without saying so. The findings and observation logs take the RecordLog port, which then moves to its consumer with a read interface, a kind selector, its bounds and its diagnostics (ADR-0072) +Rotation, disk budget, cursor expiry, duplicates, interrupted export and backup/restore are tested for evidence and observations. A restored process cannot reuse spent approval authority. Read-only inspection cannot mutate recovery state without saying so. The findings and observation logs take the RecordLog port, with a kind selector and its diagnostics (ADR-0072) B26 diff --git a/site/docs/changelog.html b/site/docs/changelog.html index 321d0407b..d2ef0f1bf 100644 --- a/site/docs/changelog.html +++ b/site/docs/changelog.html @@ -139,6 +139,29 @@

    Changelog

    signed and attested from its tag; RELEASING.md shows how to verify one.

    Unreleased

    +

    Security

    +
      +
    • collect checks for an earlier copy of a resent record through the open +directory, applying the same file type, owner and mode checks as on write. +A segment file writable by another account fails the log on such a resend. +collect refuses that record and the next new one.
    • +
    +

    Changed

    +
      +
    • trail segments <dir> adds a third line with +kind=segments max_line_bytes=786432 segment_bytes=unknown max_bytes=unknown budget_refusals=unknown. +The byte bounds and budget refusal count are local to collect.
    • +
    • For a directory of segments, trail <dir>, writer_held in +trail export <dir>, and trail segments <dir> ask segments.lock +whether a writer holds the log. If the lock cannot be asked, +trail segments exits 1 with +trail segments: recordlog: whether a writer holds the log is unknown. +trail and trail export refuse the same way if the live segment ends in +a partial line.
    • +
    • collect, trail, trail export, trail segments and prune use +recordlog: for shared log refusals. Directory, manifest, version, lock +and clock refusals specific to segments keep segmentlog:.
    • +

    Fixed

    • policy renew --out <file> judges --out again if another renew replaces @@ -183,7 +206,7 @@

      Changed

      +

      Changed

      • Breaking: collect and prune refuse a trail directory whose parent is owned by an account other than this one or root, or may be written by @@ -1085,7 +1108,7 @@

        ADR-0085). The hook profile, qualified on two releases of its runtime, was not qualified again for this release.

        -

        Changed

        +

        Changed

        • Breaking: under approvals.authority: signed a plane needs plane_id, an identifier the operator chooses for it, set in the configuration file; any @@ -1231,7 +1254,7 @@

          Documentation

          its signed steps copy the plane's stop list floor for the operator and make the new stops directory before the carry.
        -

        Security

        +

        Security

        • The filesystem server the MCP client check installs locks hono 4.13.18, which fixes GHSA-3gg2-335m-rxc6, GHSA-46wx-v44x-9hh2, GHSA-4h7h-rv7c-7m2v, @@ -1274,7 +1297,7 @@

          Added

          scripts/lib/github-settings.sh declares it a required check; it gates a pull request once the maintainer applies those settings.
        -

        Changed

        +

        Changed

        • Breaking: the plane refuses to start when health.socket_uid names the plane's own account, and doctor fails its health.socket check: the @@ -1339,7 +1362,7 @@

          Fixed

          passes a protected file while the plane runs one its own account may write.
        -

        Security

        +

        Security

        • Built with Go 1.27.4, which fixes GO-2026-6859 in net/http: a race on MaxBytesReader's header could crash an HTTP/1 server. govulncheck @@ -1504,7 +1527,7 @@

          Added

          removes its socket when it stops.
        • doctor warns of every TCP export.endpoint, naming the unix form.
        -

        Changed

        +

        Changed

        • Breaking: under approvals.authority: signed a v1alpha1 route, a 1.0 stop list, a lift of the route's lift key and reaction.public_key @@ -1593,7 +1616,7 @@

          Fixed

          only at start. A sweep that fails is logged and counted under approvals.sweep in /healthz.
        -

        Security

        +

        Security

        • Under approvals.authority: signed any valid rejection wins, a rejection counts only from an operator who may approve, whatever time it names. An @@ -1635,7 +1658,7 @@

          ADR-0071). The hook profile's qualification was not run again for this release.

          -

          Security

          +

          Security

          • The filesystem server the guide's MCP client check installs takes glob 14.0.2, which fixes GHSA-3g3m-2fjr-6pw4, and minimatch 11.0.1, which @@ -1751,7 +1774,7 @@

            Added

            classified. Validate does not change (ADR-0067).

          -

          Changed

          +

          Changed

          • Breaking: trail <file> refuses a file in a log's directory, named @@ -2122,7 +2145,7 @@

            Security

            +

            Security

            • mcp.New refuses an override whose ReturnsTrust or ReturnsSensitivity is a number the contract does not declare. Such an override loaded through @@ -2288,7 +2311,7 @@

              Fixed

              point's published metadata gives its identifier or evaluation endpoint as JSON null, as it does for any other value that is not a string.
            -

            Changed

            +

            Changed

            • The built-in hook profile is qualified on a newer release of its runtime too: all 20 cases passed on the @@ -2398,7 +2421,7 @@

              Fixed

              Built for Solaris, illumos or AIX, which have no flock, the receiver now refuses to listen, and doctor checks the lock file as run would.
            -

            Changed

            +

            Changed

            • A call is handed out only while the policy bundle it was decided under is still installed and fresh. A bundle replaced, or past its staleness budget, @@ -2453,7 +2476,7 @@

              Added

              back. The dry run uploads a development release to TestPyPI the same way, from main.
            -

            Changed

            +

            Changed

            • A change reaches main as one squash-merged pull request whose gate is CI's make quality, a maintainer's own included; only a release commit is @@ -2563,7 +2586,7 @@

              Added

              simulating candidate policies and reviewing findings with an incident export. None is built.
            -

            Changed

            +

            Changed

            • On an enforce_api plane /metrics writes the enforcement API adapter's counts (enforce_*) and the flag listener_enforce_api, and leaves out the @@ -2709,7 +2732,7 @@

              Added

              reads and its stability, held to the code's constants by a test. The wire contract's 1.0 is the one stable format; the product is still 0.x.
            -

            Changed

            +

            Changed

            • The website names the published release, which docs/docs.json sets once a release is out, rather than the newest dated section of this file, and each @@ -2772,7 +2795,7 @@

              Security

              +

              Security

              -

              Changed

              +

              Changed

              • Every reader of a route (route sign, react, a plane at start, doctor and the stops commands) refuses one that names a rule or a rule version outside @@ -2908,7 +2931,7 @@

                Added

                report the route and the list; examples/refund-supervision/ stops one of two runs on a live plane and lifts the stop.
              -

              Changed

              +

              Changed

              • The policy key and the freshness key, in the configuration and in guardana-control policy renew, are compared as points up to their sign: @@ -3060,7 +3083,7 @@

                Added

                finding, and no finding stops a run. examples/refund-supervision/ runs it on a live plane.
              -

              Changed

              +

              Changed

              • An upstream's answer, wire error, listed item or tool definition that quotes a credential the plane sends reaches the agent as a fixed answer, never with @@ -3129,7 +3152,7 @@

                Added

                runtime's traces. A missing or malformed value leaves both empty and changes nothing else.
              -

              Changed

              +

              Changed

              • The plan follows ADR-0039: MCP is one channel of several. The next milestone is one task under @@ -3277,7 +3300,7 @@

                Added

              • guardana-control policy explain prints a clock line: usable, or why the clock stopped the decision.
              -

              Changed

              +

              Changed

              • Breaking: a plane's configuration needs five more keys: @@ -3517,7 +3540,7 @@

                Added

                answered with HTTP 401 or the JSON-RPC error -31102, and the refusals are counted by cause. A plane without runs.dir is unchanged.
              -

              Changed

              +

              Changed

              • The release job waits for a maintainer to approve it in the release environment before it builds; RELEASING.md has the step.
              • @@ -3539,7 +3562,7 @@

                docs/status.md says what is implemented and what is experimental. Nothing here is a security boundary yet.

                -

                Changed

                +

                Changed

                -

                Changed

                +

                Changed

                • A stdio upstream no longer inherits the plane's environment. It gets PATH, HOME, LANG, LC_ALL, TMPDIR and USER, each where the diff --git a/site/docs/concepts/glossary.html b/site/docs/concepts/glossary.html index 66c3b9cfc..2aafc05c7 100644 --- a/site/docs/concepts/glossary.html +++ b/site/docs/concepts/glossary.html @@ -192,7 +192,7 @@

                  Glossary

                • stop list

                  Meaning
                  stops.jsonl in the directory reaction.stops names: a header naming the route, then stop, covered and lift lines, appended and never rewritten, which react and the stops commands write under the list's lock; a plane reads it every poll interval and takes no lock
                  Defined in
                  internal/reaction/stoplist/, internal/reaction/stopwrite/, reference/reaction
                • stop list header

                  Meaning
                  the first line of a stop list 3.0: an envelope over a reaction-list-header/3.0 body a roster operator signs, naming the list, its serial, the plane's plane_id, tenant, project and stop list file, the route and, for a list carried from another, the previous header's digest; a lift names it and the stop list floor keeps it
                  Defined in
                  HeaderSigned in internal/reaction/header2.go, reference/reaction-signed
                • trail file

                  Meaning
                  a file of events, one per line in the protobuf JSON mapping, each event id once; what trail and trail export read
                  Defined in
                  trailfile.Writer in internal/trailfile/writer.go
                • -
                • trail segments

                  Meaning
                  the directory the collector writes, bound to one tenant and project: sealed segments, each a trail file, a live one appends go to, and segments.json naming each, sealed or pruned; bounded in bytes, pruned only by an operator
                  Defined in
                  trailfile.Log in internal/trailfile/log.go over internal/segmentlog/
                • +
                • trail segments

                  Meaning
                  the directory the collector writes, bound to one tenant and project: sealed segments, each a trail file, a live one appends go to, and segments.json naming each, sealed or pruned; bounded in bytes, pruned only by an operator
                  Defined in
                  trailfile.Log in internal/trailfile/log.go over the record log port internal/recordlog/, whose one kind is internal/segmentlog/
                • trust

                  Meaning
                  how far an observation's source can be believed, from its descriptor: TRUST_SELF_REPORTED (the agent's own process), TRUST_PLATFORM (the platform it runs on) or TRUST_INDEPENDENT (something the agent cannot influence)
                  Defined in
                  Trust in api/proto/guardana/control/observe/v1alpha1/source.proto
                • trust roster

                  Meaning
                  the signed file that names operator keys and the tenant, project and level each may act on, under a pinned root, for at most 7 days at a serial that only climbs; a plane reads one only under the signed authority, through trust.*
                  Defined in
                  internal/trust/, ADR-0071
                • unrecorded read

                  Meaning
                  a read that ran with a trail the sink did not take, under the explicit evidence setting; counted, never held and never closed
                  Defined in
                  Config.AllowReadsUnrecorded in internal/gateway/config.go
                • diff --git a/site/docs/contracts.html b/site/docs/contracts.html index 84e62205f..31c7da43a 100644 --- a/site/docs/contracts.html +++ b/site/docs/contracts.html @@ -1468,12 +1468,13 @@

                  What is read

                  when it was opened, and holds no lock. The bytes after the last newline are a line a collector is still writing while one holds the file: the trailer counts them, writer_held is true, and the next export reads them once they end. -Whether a writer holds the file is asked only when such bytes exist. When none -holds it they are a partial_tail gap. A gap takes a record like any other, so -an export whose limit leaves no room for it ends with end_reached false and -the next export writes it. A reader refuses an export whose trailer counts -such bytes with end_reached true, writer_held false and no -partial_tail gap.

                  +Whether a writer holds the file is asked only when such bytes exist; for a +directory of segments it is asked of the directory's lock, and when that +cannot be asked the export is refused. When none holds it they are a +partial_tail gap. A gap takes a record like any other, so an export whose +limit leaves no room for it ends with end_reached false and the next export +writes it. A reader refuses an export whose trailer counts such bytes with +end_reached true, writer_held false and no partial_tail gap.

                  end_reached is true when every whole line was read and the bytes after the last newline were reported.

                  The cursor

                  diff --git a/site/docs/guides/watch-a-plane-without-a-collector.html b/site/docs/guides/watch-a-plane-without-a-collector.html index 5b7105b2f..4936d71ac 100644 --- a/site/docs/guides/watch-a-plane-without-a-collector.html +++ b/site/docs/guides/watch-a-plane-without-a-collector.html @@ -226,14 +226,14 @@

                  5. Read across segments, and prune

                  evidence-report -state follows the log from segment to segment.

                  -

                  trail segments prints the manifest: the segments sealed, pruned and -dropped, then each one's state, lines, bytes, key and dates, and whether a -collect holds it. prune removes the sealed segments up to the one named, -after writing each one's tombstone, which keeps its lines, bytes and digests. -A file is unlinked only while its name names the one read, though POSIX -leaves a moment between that check and the unlink. Stop collect first: a held -directory is refused, and so is a clock before the segment's seal. The live -segment is never pruned.

                  +

                  trail segments prints the manifest, whether a collect holds it, the log's +kind and line bound, with the collector's byte bounds and budget refusals +printed unknown; it exits 1 when whether a collect holds it is unknown. +prune removes sealed segments through the named one, writing tombstones +first with lines, bytes and digests. A file is unlinked only while its name +names the one read, though POSIX leaves a moment between check and unlink. +Stop collect first: a held directory or a clock before the seal is refused. +The live segment is never pruned.

                  What the collector promises

                  Rendered from docs/index.md on main. It describes the tree as it is now; a release's notes say what a tag holds. The latest release is v0.19.1, and its documentation is in its tag.

                  diff --git a/site/docs/status.html b/site/docs/status.html index 1fde4207b..d68415cf6 100644 --- a/site/docs/status.html +++ b/site/docs/status.html @@ -1073,14 +1073,20 @@

                  trail-collector

                • adapters/otel/ also reads what the exporter sends, strictly, answers only after the records are synced, and refuses 401 a request without the collector's bearer credential
                • -
                • internal/segmentlog/ keeps a directory of segments bound to one tenant and -project, sealed at a byte bound, refused past a log bound, pruned only by an -operator with a tombstone first, and completed or refused after a crash
                • +
                • internal/recordlog/ declares the port: Log appends, seals, prunes, reads +back the lines it wrote and counts its statistics; Reader reads the +manifest and opens segments without a lock, and says whether a writer holds +the log as held, free or unknown, unknown never read as free.
                • +
                • internal/segmentlog/ is its one kind, segments: it keeps a directory of +segments bound to one tenant and project, sealed at a byte bound, refused +past a log bound, pruned only by an operator with a tombstone first, and +completed or refused after a crash.
                • internal/trailfile/ writes each live segment under an exclusive lock, refuses another project's event, cuts a torn last line at open, and reads a -file or every segment back with each trail's chain checked; -guardana-gateway collect (a unix socket, --tenant, --project, ---credential-file), trail, trail segments and prune
                • +file or every segment back with each trail's chain checked; trail segments +prints the log's statistics; guardana-gateway collect (a unix socket, +--tenant, --project, --credential-file), trail, trail segments and +prune
                • guides/watch-a-plane-without-a-collector.md
                • ADR-0020
                • ADR-0072
                • diff --git a/site/llms.txt b/site/llms.txt index 639313bbd..7ccb2f316 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -200,5 +200,5 @@ This is alpha software and not a security boundary: do not deploy it as one. Wha - [ADR-0088: A verdict that compares two events' times is at most suspected](https://control.guardana.dev/docs/adr/0088-a-verdict-that-compares-two-events-times-is-at-most-suspected): Decision record, proposed. - [ADR-0089: Outside signed, every receiver holds its input to the plane's one tenant and project](https://control.guardana.dev/docs/adr/0089-outside-signed-every-receiver-holds-its-input-to-the-planes-one-tenant-and-project): Decision record, proposed. - [ADR-0090: A listener authenticator names the principal a stop and a pause match](https://control.guardana.dev/docs/adr/0090-a-listener-authenticator-names-the-principal-a-stop-and-a-pause-match): Decision record, proposed. -- [ADR-0091: The record log port moves to its consumers, with a read interface](https://control.guardana.dev/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface): Decision record, proposed. +- [ADR-0091: The record log port moves to its consumers, with a read interface](https://control.guardana.dev/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface): Decision record, accepted. - [ADR-0092: The observation and finding logs are segment logs of one project](https://control.guardana.dev/docs/adr/0092-the-observation-and-finding-logs-are-segment-logs-of-one-project): Decision record, proposed. From 6ce8c1fa23f7324f28906fea29ba547d5db7f940 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 20:30:08 +0100 Subject: [PATCH 05/12] fix(segmentlog): a writer holds the log through either lock Holding asks segments.lock first and the live segment's lock beside it: held when either is held, unknown when the directory's lock cannot be asked or the directory at the log's path is no longer the one inspected. OpenLive's contract now says the live file is locked, so a second writer is refused even with the directory's lock file unlinked. Signed-off-by: Konrad Karauda --- internal/segmentlog/port.go | 5 ++- internal/segmentlog/port_test.go | 58 +++++++++++++++++++++++--------- internal/segmentlog/view.go | 38 +++++++++++---------- 3 files changed, 66 insertions(+), 35 deletions(-) diff --git a/internal/segmentlog/port.go b/internal/segmentlog/port.go index 88cb31ec6..b559f89d9 100644 --- a/internal/segmentlog/port.go +++ b/internal/segmentlog/port.go @@ -49,7 +49,10 @@ type LiveFile interface { // recordlog.Config. type Options struct { // OpenLive opens the live segment by name in the directory root holds, - // the one the log judged and locked, creating it when absent. + // the one the log judged and locked, creating it when absent, and locks + // it with Lock: a reader asks that lock beside the directory's, and a + // second writer is refused by it even if the directory's lock file was + // unlinked. OpenLive func(root *os.Root, name string) (LiveFile, error) } diff --git a/internal/segmentlog/port_test.go b/internal/segmentlog/port_test.go index 0277c2c99..47ad1f406 100644 --- a/internal/segmentlog/port_test.go +++ b/internal/segmentlog/port_test.go @@ -111,8 +111,8 @@ func TestAReaderGivenABindingTakesOnlyItsOwn(t *testing.T) { } // TestAHoldingThatCannotBeAskedIsUnknown: a lock file that is no regular file -// is a holding of unknown, never free; no lock file is free, and the lock of a -// writer is held. +// is a holding of unknown, never free, and so is no lock file, which a writer +// makes before the manifest; the lock of a writer is held. func TestAHoldingThatCannotBeAskedIsUnknown(t *testing.T) { cfg := config(logDir(t), 8, 64) l := openLog(t, cfg) @@ -131,8 +131,8 @@ func TestAHoldingThatCannotBeAskedIsUnknown(t *testing.T) { if err := os.Remove(lock); err != nil { t.Fatal(err) } - if h := r.Holding(); h != recordlog.HoldingFree { - t.Errorf("with no lock file: %s, want free", h) + if h := r.Holding(); h != recordlog.HoldingUnknown { + t.Errorf("with no lock file: %s, want unknown", h) } if err := os.Mkdir(lock, 0o700); err != nil { t.Fatal(err) @@ -263,10 +263,11 @@ func TestAnEmptyLiveSegmentWithNoFileOpensEmpty(t *testing.T) { } } -// TestAWriterHoldsTheLogThroughEitherLock: a live file a writer locks, as -// trailfile's does, reads as held with the directory's lock file unlinked; with -// neither lock held it is free, and another directory put at the log's path -// after the inspection is unknown. +// TestAWriterHoldsTheLogThroughEitherLock: with no writer and the lock file +// in place the log is free; a live file a writer locks, as trailfile's does, +// reads as held with the directory's lock file unlinked, and unknown once it +// is let go; another directory put at the log's path after the inspection is +// unknown. func TestAWriterHoldsTheLogThroughEitherLock(t *testing.T) { cfg := config(logDir(t), 8, 64) l := openLog(t, cfg) @@ -278,6 +279,7 @@ func TestAWriterHoldsTheLogThroughEitherLock(t *testing.T) { if err != nil { t.Fatal(err) } + wantHolding(t, r, recordlog.HoldingFree, "with no writer") live, err := os.OpenFile(filepath.Join(cfg.Dir, LiveName), os.O_RDWR, 0) if err != nil { t.Fatal(err) @@ -289,22 +291,46 @@ func TestAWriterHoldsTheLogThroughEitherLock(t *testing.T) { if err := os.Remove(filepath.Join(cfg.Dir, LockName)); err != nil { t.Fatal(err) } - if h := r.Holding(); h != recordlog.HoldingHeld { - t.Errorf("with the lock file unlinked and the live file locked: %s, want held", h) - } + wantHolding(t, r, recordlog.HoldingHeld, "with the lock file unlinked and the live file locked") if err := live.Close(); err != nil { t.Fatal(err) } - if h := r.Holding(); h != recordlog.HoldingFree { - t.Errorf("with neither lock held: %s, want free", h) - } + wantHolding(t, r, recordlog.HoldingUnknown, "with the lock file unlinked and the live file let go") if err := os.Rename(cfg.Dir, cfg.Dir+".moved"); err != nil { t.Fatal(err) } if err := os.Mkdir(cfg.Dir, 0o700); err != nil { t.Fatal(err) } - if h := r.Holding(); h != recordlog.HoldingUnknown { - t.Errorf("with another directory at the log's path: %s, want unknown", h) + wantHolding(t, r, recordlog.HoldingUnknown, "with another directory at the log's path") +} + +func wantHolding(t *testing.T, r interface{ Holding() recordlog.Holding }, want recordlog.Holding, when string) { + t.Helper() + if h := r.Holding(); h != want { + t.Errorf("%s: %s, want %s", when, h, want) + } +} + +// TestAHeldDirectoryLockIsHeldWhateverTheLiveFile: a writer holding the +// directory's lock holds the log, even while the live file cannot be asked, as +// between a seal's rename and the next live file. +func TestAHeldDirectoryLockIsHeldWhateverTheLiveFile(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + livePath := filepath.Join(cfg.Dir, LiveName) + if err := os.Rename(livePath, livePath+".aside"); err != nil { + t.Fatal(err) + } + if err := os.Symlink(LiveName+".aside", livePath); err != nil { + t.Fatal(err) + } + if h := r.Holding(); h != recordlog.HoldingHeld { + t.Errorf("with the writer open and a link at the live file's name: %s, want held", h) } } diff --git a/internal/segmentlog/view.go b/internal/segmentlog/view.go index 4d3cf152f..049f50cbb 100644 --- a/internal/segmentlog/view.go +++ b/internal/segmentlog/view.go @@ -298,10 +298,11 @@ func (v *view) check(f *os.File, s Segment) (int64, error) { } // Holding asks whether a writer holds the log now, of the directory's lock -// file and of the live file's, which a writer may lock too, since either can -// be unlinked under it: held when either is held, free when each is free or -// absent, and unknown when either cannot be asked or the directory at the -// path is no longer the one inspected. +// file and of the live file's, which a writer locks too, since either can be +// unlinked under it: held when either is held. A writer makes the lock file +// before the manifest, so a log with no lock file had it removed and is +// unknown, as is one either lock of which cannot be asked, or whose directory +// at the path is no longer the one inspected. Otherwise it is free. func (v *view) Holding() recordlog.Holding { root, err := os.OpenRoot(v.cfg.Dir + string(os.PathSeparator) + ".") if err != nil { @@ -311,25 +312,26 @@ func (v *view) Holding() recordlog.Holding { if dir, err := root.Stat("."); err != nil || v.dir == nil || !os.SameFile(dir, v.dir) { return recordlog.HoldingUnknown } - holding := recordlog.HoldingFree - for _, name := range []string{LockName, LiveName} { - switch heldAt(root, name) { - case recordlog.HoldingHeld: - holding = recordlog.HoldingHeld - case recordlog.HoldingFree: - default: - return recordlog.HoldingUnknown - } + lock := heldAt(root, LockName, recordlog.HoldingUnknown) + if lock == recordlog.HoldingHeld { + return lock + } + live := heldAt(root, LiveName, recordlog.HoldingFree) + switch { + case live == recordlog.HoldingHeld: + return live + case lock == recordlog.HoldingUnknown: + return lock } - return holding + return live } -// heldAt asks whether a writer holds the lock of the file at name in root: -// free when there is no such file. -func heldAt(root *os.Root, name string) recordlog.Holding { +// heldAt asks whether a writer holds the lock of the file at name in root, +// answering absent when there is no such file. +func heldAt(root *os.Root, name string, absent recordlog.Holding) recordlog.Holding { f, err := openRead(root, name) if errors.Is(err, fs.ErrNotExist) { - return recordlog.HoldingFree + return absent } if err != nil { return recordlog.HoldingUnknown From 870e3cc11bc0336250e7515da5c8f62ba7b47c56 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 20:30:08 +0100 Subject: [PATCH 06/12] docs(recordlog): say an export asks both locks Signed-off-by: Konrad Karauda --- CHANGELOG.md | 10 ++++++---- docs/contracts.md | 13 +++++++------ site/docs/changelog.html | 14 ++++++++------ site/docs/contracts.html | 13 +++++++------ 4 files changed, 28 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc2d66de2..52c963b63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ verify one. - `collect` checks for an earlier copy of a resent record through the open directory, applying the same file type, owner and mode checks as on write. A segment file writable by another account fails the log on such a resend. - `collect` refuses that record and the next new one. + `collect` refuses that record and every later append until it opens the + log again. ### Changed @@ -24,9 +25,10 @@ verify one. `kind=segments max_line_bytes=786432 segment_bytes=unknown max_bytes=unknown budget_refusals=unknown`. The byte bounds and budget refusal count are local to `collect`. - For a directory of segments, `trail `, `writer_held` in - `trail export `, and `trail segments ` ask `segments.lock` - whether a writer holds the log. If the lock cannot be asked, - `trail segments` exits 1 with + `trail export `, and `trail segments ` ask `segments.lock` and + the live segment's lock whether a writer holds the log: held when either + is held. If either cannot be asked, `segments.lock` is missing, or the + path no longer names that directory, `trail segments` exits 1 with `trail segments: recordlog: whether a writer holds the log is unknown`. `trail` and `trail export` refuse the same way if the live segment ends in a partial line. diff --git a/docs/contracts.md b/docs/contracts.md index 45c266e65..85e735796 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1189,12 +1189,13 @@ when it was opened, and holds no lock. The bytes after the last newline are a line a collector is still writing while one holds the file: the trailer counts them, `writer_held` is `true`, and the next export reads them once they end. Whether a writer holds the file is asked only when such bytes exist; for a -directory of segments it is asked of the directory's lock, and when that -cannot be asked the export is refused. When none holds it they are a -`partial_tail` gap. A gap takes a record like any other, so an export whose -limit leaves no room for it ends with `end_reached` false and the next export -writes it. A reader refuses an export whose trailer counts such bytes with -`end_reached` true, `writer_held` false and no `partial_tail` gap. +directory of segments it is asked of both `segments.lock` and the live +segment's lock: it is held when either is held, and when the answer is unknown +the export is refused. When none holds it they are a `partial_tail` gap. A gap +takes a record like any other, so an export whose limit leaves no room for it +ends with `end_reached` false and the next export writes it. A reader refuses +an export whose trailer counts such bytes with `end_reached` true, +`writer_held` false and no `partial_tail` gap. `end_reached` is `true` when every whole line was read and the bytes after the last newline were reported. diff --git a/site/docs/changelog.html b/site/docs/changelog.html index d2ef0f1bf..606dc190d 100644 --- a/site/docs/changelog.html +++ b/site/docs/changelog.html @@ -144,7 +144,8 @@

                  Security

                • collect checks for an earlier copy of a resent record through the open directory, applying the same file type, owner and mode checks as on write. A segment file writable by another account fails the log on such a resend. -collect refuses that record and the next new one.
                • +collect refuses that record and every later append until it opens the +log again.

                Changed

                  @@ -152,15 +153,16 @@

                  Changed

                  kind=segments max_line_bytes=786432 segment_bytes=unknown max_bytes=unknown budget_refusals=unknown. The byte bounds and budget refusal count are local to collect.
                • For a directory of segments, trail <dir>, writer_held in -trail export <dir>, and trail segments <dir> ask segments.lock -whether a writer holds the log. If the lock cannot be asked, -trail segments exits 1 with +trail export <dir>, and trail segments <dir> ask segments.lock and +the live segment's lock whether a writer holds the log: held when either +is held. If either cannot be asked, segments.lock is missing, or the +path no longer names that directory, trail segments exits 1 with trail segments: recordlog: whether a writer holds the log is unknown. trail and trail export refuse the same way if the live segment ends in a partial line.
                • collect, trail, trail export, trail segments and prune use -recordlog: for shared log refusals. Directory, manifest, version, lock -and clock refusals specific to segments keep segmentlog:.
                • +recordlog: for shared log refusals. Refusals specific to segments keep +segmentlog:.

                Fixed

                  diff --git a/site/docs/contracts.html b/site/docs/contracts.html index 31c7da43a..2c952728c 100644 --- a/site/docs/contracts.html +++ b/site/docs/contracts.html @@ -1469,12 +1469,13 @@

                  What is read

                  line a collector is still writing while one holds the file: the trailer counts them, writer_held is true, and the next export reads them once they end. Whether a writer holds the file is asked only when such bytes exist; for a -directory of segments it is asked of the directory's lock, and when that -cannot be asked the export is refused. When none holds it they are a -partial_tail gap. A gap takes a record like any other, so an export whose -limit leaves no room for it ends with end_reached false and the next export -writes it. A reader refuses an export whose trailer counts such bytes with -end_reached true, writer_held false and no partial_tail gap.

                  +directory of segments it is asked of both segments.lock and the live +segment's lock: it is held when either is held, and when the answer is unknown +the export is refused. When none holds it they are a partial_tail gap. A gap +takes a record like any other, so an export whose limit leaves no room for it +ends with end_reached false and the next export writes it. A reader refuses +an export whose trailer counts such bytes with end_reached true, +writer_held false and no partial_tail gap.

                  end_reached is true when every whole line was read and the bytes after the last newline were reported.

                  The cursor

                  From 69ba1cfea9b17af500f38c4be0ad594e01171990 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 21:19:04 +0100 Subject: [PATCH 07/12] fix(segmentlog): a writer holds the log by the directory's own lock A writer takes an exclusive lock on the log directory itself, through the directory it judged, before segments.lock, and holds it until it closes. No unlink or replace of a name in the directory drops it, so a second writer, a prune beside a running collector included, is refused whether or not a live segment exists. Holding asks that lock first, through the directory it inspected, then segments.lock and the live segment's lock: held when any is held, free only when every lock asked is free. Once OpenLive returns, the log opens the live file again and refuses it unless a writer holds its lock (ErrLiveUnlocked): an open is refused, an append fails the log. The package's test opener locks, so the conformance suite no longer passes an opener that does not. Signed-off-by: Konrad Karauda --- internal/segmentlog/errors.go | 3 + internal/segmentlog/helpers_test.go | 20 +++- internal/segmentlog/onewriter_test.go | 159 ++++++++++++++++++++++++++ internal/segmentlog/port.go | 7 +- internal/segmentlog/segments.go | 62 ++++++++-- internal/segmentlog/segments_test.go | 7 +- internal/segmentlog/view.go | 39 +++++-- internal/segmentlog/write.go | 12 +- 8 files changed, 278 insertions(+), 31 deletions(-) create mode 100644 internal/segmentlog/onewriter_test.go diff --git a/internal/segmentlog/errors.go b/internal/segmentlog/errors.go index 22d5fe29f..4339795f4 100644 --- a/internal/segmentlog/errors.go +++ b/internal/segmentlog/errors.go @@ -34,6 +34,9 @@ const ( // ErrLiveChanged is a failed append after which the live file no longer // holds what the log counted, so the log fails. ErrLiveChanged Error = "segmentlog: the live file no longer holds what the log counted" + // ErrLiveUnlocked is a live file its opener did not lock, so a second + // writer would not be refused by it and a reader could not ask it. + ErrLiveUnlocked Error = "segmentlog: the live file was opened and not locked" ) // The port's refusals, as this kind returns them. diff --git a/internal/segmentlog/helpers_test.go b/internal/segmentlog/helpers_test.go index 02211bec6..f6f5bfe34 100644 --- a/internal/segmentlog/helpers_test.go +++ b/internal/segmentlog/helpers_test.go @@ -15,11 +15,25 @@ import ( "github.com/guardana/control/internal/recordlog" ) -// testLive is the plainest live file: appends synced at the end, and what -// follows the last newline cut at open, as a crash leaves it. +// testLive is the plainest live file: appends synced at the end, what +// follows the last newline cut at open, as a crash leaves it, and locked as +// Options.OpenLive says. type testLive struct{ f *os.File } func openTestLive(root *os.Root, name string) (LiveFile, error) { + f, err := openCut(root, name) + if err != nil { + return nil, err + } + if err := Lock(f); err != nil { + return nil, errors.Join(err, f.Close()) + } + return testLive{f}, nil +} + +// openCut opens the live file at name to append, creating it when absent, +// and cuts what follows its last newline. +func openCut(root *os.Root, name string) (*os.File, error) { f, err := root.OpenFile(name, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0o600) if err != nil { return nil, err @@ -31,7 +45,7 @@ func openTestLive(root *os.Root, name string) (LiveFile, error) { if err != nil { return nil, errors.Join(err, f.Close()) } - return testLive{f}, nil + return f, nil } func (l testLive) AppendLines(_ context.Context, lines []byte) error { diff --git a/internal/segmentlog/onewriter_test.go b/internal/segmentlog/onewriter_test.go new file mode 100644 index 000000000..76ffccf4c --- /dev/null +++ b/internal/segmentlog/onewriter_test.go @@ -0,0 +1,159 @@ +package segmentlog + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + + "github.com/guardana/control/internal/recordlog" +) + +// openUnlockedLive opens a live file as openTestLive does and takes no lock +// on it. +func openUnlockedLive(root *os.Root, name string) (LiveFile, error) { + f, err := openCut(root, name) + if err != nil { + return nil, err + } + return testLive{f}, nil +} + +// putAt puts a new file holding body at path, in place of what was there. +func putAt(t *testing.T, path, body string) { + t.Helper() + if err := os.WriteFile(path+".new", []byte(body), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Rename(path+".new", path); err != nil { + t.Fatal(err) + } +} + +// TestASecondWriterIsRefusedWithTheLockFileUnlinkedAndNoLiveFile: with +// segments.lock unlinked under a writer that has no live file, one that has +// appended nothing or sealed every line, a second writer is refused; the +// first one closed, it opens. +func TestASecondWriterIsRefusedWithTheLockFileUnlinkedAndNoLiveFile(t *testing.T) { + for _, sealed := range []bool{false, true} { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + if sealed { + mustAppend(t, l, "aaa") + if err := l.Seal(); err != nil { + t.Fatal(err) + } + } + if err := os.Remove(filepath.Join(cfg.Dir, LockName)); err != nil { + t.Fatal(err) + } + if second, err := openSegments(cfg); !errors.Is(err, ErrLocked) { + if second != nil { + _ = second.Close() + } + t.Errorf("sealed %v: a second writer = %v, want ErrLocked", sealed, err) + } + if err := l.Close(); err != nil { + t.Fatal(err) + } + _ = openLog(t, cfg).Close() + } +} + +// TestAPruneBesideAnOpenWriterIsRefused: a pruner opening beside a writer +// that holds the log, with segments.lock replaced by a new file, is refused, +// so the writer's next seal cannot name sealed a segment the prune removed; +// the writer closed, the log opens and the prune goes through. +func TestAPruneBesideAnOpenWriterIsRefused(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa", "bbb") + mustAppend(t, l, "ccc") + if err := l.Seal(); err != nil { + t.Fatal(err) + } + if err := l.Close(); err != nil { + t.Fatal(err) + } + writer := openLog(t, cfg) + putAt(t, filepath.Join(cfg.Dir, LockName), "") + if pruner, err := openSegments(cfg); !errors.Is(err, ErrLocked) { + if pruner != nil { + t.Logf("the pruner's Prune(1): %v", pruner.Prune(1)) + _ = pruner.Close() + } + t.Errorf("a pruner beside the writer = %v, want ErrLocked", err) + } + mustAppend(t, writer, "ddd", "eee") + mustAppend(t, writer, "fff") + if err := writer.Close(); err != nil { + t.Fatal(err) + } + if err := openLog(t, cfg).Prune(1); err != nil { + t.Errorf("Prune(1) with the writer closed = %v", err) + } +} + +// TestAReplacedLockFileWithNoLiveFileReadsHeld: segments.lock replaced by a +// new file under a writer with no live file reads as held; the writer closed, +// the log is free. +func TestAReplacedLockFileWithNoLiveFileReadsHeld(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + putAt(t, filepath.Join(cfg.Dir, LockName), "") + wantHolding(t, r, recordlog.HoldingHeld, "with the lock file replaced and no live file") + if err := l.Close(); err != nil { + t.Fatal(err) + } + wantHolding(t, r, recordlog.HoldingFree, "with the writer closed") +} + +// TestAReplacedLockAndLiveFileReadHeld: segments.lock and the live file both +// replaced by copies under a writer read as held; the writer closed, the +// log is free. +func TestAReplacedLockAndLiveFileReadHeld(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + live := filepath.Join(cfg.Dir, LiveName) + putAt(t, filepath.Join(cfg.Dir, LockName), "") + putAt(t, live, fileText(t, live)) + wantHolding(t, r, recordlog.HoldingHeld, "with the lock file and the live file replaced") + if err := l.Close(); err != nil { + t.Fatal(err) + } + wantHolding(t, r, recordlog.HoldingFree, "with the writer closed") +} + +// TestAnOpenerThatDoesNotLockTheLiveFileIsRefused: a live file its opener +// left unlocked fails the append that opened it and refuses an open that +// finds it; opened by an opener that locks it, it takes the append. +func TestAnOpenerThatDoesNotLockTheLiveFileIsRefused(t *testing.T) { + cfg := config(logDir(t), 64, 256) + cfg.OpenLive = openUnlockedLive + l := openLog(t, cfg) + if err := l.Append(context.Background(), []byte("aaa\n")); !errors.Is(err, ErrLiveUnlocked) || + !errors.Is(err, ErrFailed) { + t.Errorf("an append whose live file was left unlocked = %v, want ErrFailed and ErrLiveUnlocked", err) + } + if err := l.Close(); err != nil { + t.Fatal(err) + } + if again, err := openSegments(cfg); !errors.Is(err, ErrLiveUnlocked) { + if again != nil { + _ = again.Close() + } + t.Errorf("an open whose live file is left unlocked = %v, want ErrLiveUnlocked", err) + } + cfg.OpenLive = openTestLive + mustAppend(t, openLog(t, cfg), "bbb") +} diff --git a/internal/segmentlog/port.go b/internal/segmentlog/port.go index b559f89d9..9f0de7f0f 100644 --- a/internal/segmentlog/port.go +++ b/internal/segmentlog/port.go @@ -50,9 +50,10 @@ type LiveFile interface { type Options struct { // OpenLive opens the live segment by name in the directory root holds, // the one the log judged and locked, creating it when absent, and locks - // it with Lock: a reader asks that lock beside the directory's, and a - // second writer is refused by it even if the directory's lock file was - // unlinked. + // it with Lock, so a reader of an older build that asks the live file + // finds the writer. The log refuses a live file no writer holds the lock + // of once OpenLive returns. A second writer is refused by the lock on the + // directory itself, which no unlink or replace of a name in it drops. OpenLive func(root *os.Root, name string) (LiveFile, error) } diff --git a/internal/segmentlog/segments.go b/internal/segmentlog/segments.go index 9bec9ed81..82e301570 100644 --- a/internal/segmentlog/segments.go +++ b/internal/segmentlog/segments.go @@ -35,12 +35,15 @@ func syncRoot(root *os.Root) error { return errors.Join(d.Sync(), d.Close()) } -// segments is the default kind: the directory held under its lock file, the -// manifest as last written, and the live segment. +// segments is the default kind: the directory held under its own lock and +// its lock file's, the manifest as last written, and the live segment. type segments struct { mu sync.Mutex cfg settings root *os.Root + // held is the directory opened through root, its lock the one no + // unlink or replace of a name in it can drop. + held *os.File lock *os.File // dropped is how many segments before segs were pruned and their // tombstones dropped. @@ -110,6 +113,10 @@ func (l *segments) release() error { errs = append(errs, l.lock.Close()) l.lock = nil } + if l.held != nil { + errs = append(errs, l.held.Close()) + l.held = nil + } if l.root != nil { errs = append(errs, l.root.Close()) l.root = nil @@ -123,11 +130,18 @@ type found struct { sealed map[int]bool } -// claim locks the directory, reads its names and its manifest, completes a -// seal or a prune a crash left part way, checks every segment against the -// manifest, and opens the live segment. +// claim locks the directory and then its lock file, which a reader of an +// older build asks, reads its names and its manifest, completes a seal or a +// prune a crash left part way, checks every segment against the manifest, +// and opens the live segment. func (l *segments) claim() error { var err error + if l.held, err = l.root.Open("."); err != nil { + return err + } + if err := Lock(l.held); err != nil { + return err + } if l.lock, err = openJudged(l.root, LockName, os.O_RDWR|os.O_CREATE); err != nil { return err } @@ -330,11 +344,9 @@ func (l *segments) openLive(have found) error { if !have.live { return nil } - f, err := l.cfg.OpenLive(l.root, LiveName) - if err != nil { - return fmt.Errorf("%s: %w", LiveName, err) + if err := l.openLiveFile(); err != nil { + return err } - l.file = f st, err := l.scanFile(LiveName, l.cfg.Visit) if err != nil { return fmt.Errorf("%s: %w", LiveName, err) @@ -346,6 +358,38 @@ func (l *segments) openLive(have found) error { return nil } +// openLiveFile opens the live segment through the consumer and refuses it, +// closed, unless the consumer locked it as Options.OpenLive says. +func (l *segments) openLiveFile() error { + f, err := l.cfg.OpenLive(l.root, LiveName) + if err != nil { + return fmt.Errorf("%s: %w", LiveName, err) + } + if err := l.liveLocked(); err != nil { + return errors.Join(err, f.Close()) + } + l.file = f + return nil +} + +// liveLocked refuses a live file whose lock no writer holds. A lock is held +// by one open of the file, so an open of its own asks the consumer's. +func (l *segments) liveLocked() error { + f, err := openJudged(l.root, LiveName, os.O_RDONLY) + if err != nil { + return fmt.Errorf("%w: %s: %w", ErrLiveUnlocked, LiveName, err) + } + defer func() { _ = f.Close() }() + held, err := HeldByWriter(f) + switch { + case err != nil: + return fmt.Errorf("%w: %s: %w", ErrLiveUnlocked, LiveName, err) + case !held: + return fmt.Errorf("%w: %s", ErrLiveUnlocked, LiveName) + } + return nil +} + // retained is the bytes of every segment not pruned. func (l *segments) retained() int64 { n := l.live.bytes diff --git a/internal/segmentlog/segments_test.go b/internal/segmentlog/segments_test.go index 8d3b4c2b7..e43d9758d 100644 --- a/internal/segmentlog/segments_test.go +++ b/internal/segmentlog/segments_test.go @@ -287,13 +287,16 @@ func TestEveryLineIsVisitedOnceInOrder(t *testing.T) { } } -// openTornLive opens a live file and cuts nothing, as no consumer of this -// package should open one. +// openTornLive opens and locks a live file and cuts nothing, as no consumer +// of this package should open one. func openTornLive(root *os.Root, name string) (LiveFile, error) { f, err := root.OpenFile(name, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0o600) if err != nil { return nil, err } + if err := Lock(f); err != nil { + return nil, errors.Join(err, f.Close()) + } return testLive{f}, nil } diff --git a/internal/segmentlog/view.go b/internal/segmentlog/view.go index 049f50cbb..555a53f95 100644 --- a/internal/segmentlog/view.go +++ b/internal/segmentlog/view.go @@ -297,20 +297,22 @@ func (v *view) check(f *os.File, s Segment) (int64, error) { return info.Size(), nil } -// Holding asks whether a writer holds the log now, of the directory's lock -// file and of the live file's, which a writer locks too, since either can be -// unlinked under it: held when either is held. A writer makes the lock file -// before the manifest, so a log with no lock file had it removed and is -// unknown, as is one either lock of which cannot be asked, or whose directory -// at the path is no longer the one inspected. Otherwise it is free. +// Holding asks whether a writer holds the log now: first the lock on the +// directory itself, which a writer holds for its whole life and no change to +// a name in it drops, opened through the directory inspected; then the lock +// file's and the live file's, which a writer locks too. Held when any is +// held. Unknown when the directory at the path is no longer the one +// inspected, when a lock cannot be asked, or when the lock file is missing, +// as a writer makes it before the manifest and so it was removed. Free only +// when every lock asked is free; a missing live file asks nothing. func (v *view) Holding() recordlog.Holding { root, err := os.OpenRoot(v.cfg.Dir + string(os.PathSeparator) + ".") if err != nil { return recordlog.HoldingUnknown } defer func() { _ = root.Close() }() - if dir, err := root.Stat("."); err != nil || v.dir == nil || !os.SameFile(dir, v.dir) { - return recordlog.HoldingUnknown + if dir := v.dirHolding(root); dir != recordlog.HoldingFree { + return dir } lock := heldAt(root, LockName, recordlog.HoldingUnknown) if lock == recordlog.HoldingHeld { @@ -326,6 +328,27 @@ func (v *view) Holding() recordlog.Holding { return live } +// dirHolding asks the lock on the directory root holds, unknown unless it is +// the directory inspected. +func (v *view) dirHolding(root *os.Root) recordlog.Holding { + d, err := root.Open(".") + if err != nil { + return recordlog.HoldingUnknown + } + defer func() { _ = d.Close() }() + if info, err := d.Stat(); err != nil || v.dir == nil || !os.SameFile(info, v.dir) { + return recordlog.HoldingUnknown + } + held, err := HeldByWriter(d) + switch { + case err != nil: + return recordlog.HoldingUnknown + case held: + return recordlog.HoldingHeld + } + return recordlog.HoldingFree +} + // heldAt asks whether a writer holds the lock of the file at name in root, // answering absent when there is no such file. func heldAt(root *os.Root, name string, absent recordlog.Holding) recordlog.Holding { diff --git a/internal/segmentlog/write.go b/internal/segmentlog/write.go index 400e2277f..caaca87eb 100644 --- a/internal/segmentlog/write.go +++ b/internal/segmentlog/write.go @@ -63,7 +63,8 @@ func (l *segments) Append(ctx context.Context, lines []byte) error { // makeRoom seals a live segment holding a line that n bytes more would take // past its bound, before it asks the log's own, so a log the bound refuses // holds a sealed segment to prune; refuses n bytes past the log's bound; and -// opens the live segment when none is open. +// opens the live segment when none is open, failing the log when its opener +// did not lock it. func (l *segments) makeRoom(n int64) error { if l.cfg.MaxBytes == 0 { return fmt.Errorf("%w: the log was opened with no bound, so it takes no append", ErrBudget) @@ -79,12 +80,11 @@ func (l *segments) makeRoom(n int64) error { if l.file != nil { return nil } - f, err := l.cfg.OpenLive(l.root, LiveName) - if err != nil { - return fmt.Errorf("%s: %w", LiveName, err) + err := l.openLiveFile() + if errors.Is(err, ErrLiveUnlocked) { + return l.fail(err) } - l.file = f - return nil + return err } // Seal seals the live segment when it holds a line. From efa5fe8d2b39d45039ab648b97587e235902f5ff Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 22:06:21 +0100 Subject: [PATCH 08/12] fix(segmentlog): report an unaskable live lock as it is, and pin the directory check A live file whose lock the check cannot ask is refused with that error, not as unlocked, so an append does not fail the log for good on a passing open failure. A test pins that a copy of the log put at its path reads as unknown to a reader that inspected the original. Signed-off-by: Konrad Karauda --- internal/segmentlog/onewriter_test.go | 27 +++++++++++++++++++++++++++ internal/segmentlog/segments.go | 9 +++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/internal/segmentlog/onewriter_test.go b/internal/segmentlog/onewriter_test.go index 76ffccf4c..be4c21aaa 100644 --- a/internal/segmentlog/onewriter_test.go +++ b/internal/segmentlog/onewriter_test.go @@ -157,3 +157,30 @@ func TestAnOpenerThatDoesNotLockTheLiveFileIsRefused(t *testing.T) { cfg.OpenLive = openTestLive mustAppend(t, openLog(t, cfg), "bbb") } + +// TestACopyOfTheLogAtItsPathIsUnknown: a writer's log moved aside and copied +// back to its path, every file the same, reads unknown to a reader that +// inspected the original, never free. +func TestACopyOfTheLogAtItsPathIsUnknown(t *testing.T) { + cfg := config(logDir(t), 8, 64) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + aside := cfg.Dir + ".old" + if err := os.Rename(cfg.Dir, aside); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(cfg.Dir, 0o700); err != nil { + t.Fatal(err) + } + for _, name := range dirNames(t, aside) { + putAt(t, filepath.Join(cfg.Dir, name), fileText(t, filepath.Join(aside, name))) + } + wantHolding(t, r, recordlog.HoldingUnknown, "with a copy of the log at its path") + if err := l.Close(); err != nil { + t.Fatal(err) + } +} diff --git a/internal/segmentlog/segments.go b/internal/segmentlog/segments.go index 82e301570..8c29f5800 100644 --- a/internal/segmentlog/segments.go +++ b/internal/segmentlog/segments.go @@ -372,18 +372,19 @@ func (l *segments) openLiveFile() error { return nil } -// liveLocked refuses a live file whose lock no writer holds. A lock is held -// by one open of the file, so an open of its own asks the consumer's. +// liveLocked refuses a live file whose lock no writer holds, and one whose +// lock cannot be asked. A lock is held by one open of the file, so an open of +// its own asks the consumer's. func (l *segments) liveLocked() error { f, err := openJudged(l.root, LiveName, os.O_RDONLY) if err != nil { - return fmt.Errorf("%w: %s: %w", ErrLiveUnlocked, LiveName, err) + return fmt.Errorf("%s: asking its lock: %w", LiveName, err) } defer func() { _ = f.Close() }() held, err := HeldByWriter(f) switch { case err != nil: - return fmt.Errorf("%w: %s: %w", ErrLiveUnlocked, LiveName, err) + return fmt.Errorf("%s: asking its lock: %w", LiveName, err) case !held: return fmt.Errorf("%w: %s", ErrLiveUnlocked, LiveName) } From 21d1c07bcd44f27eb3acbf99dd13a418d3c460e8 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sat, 28 Nov 2026 22:12:20 +0100 Subject: [PATCH 09/12] docs(recordlog): state the directory lock, the live-file check and the upgrade order Signed-off-by: Konrad Karauda --- CHANGELOG.md | 25 +++++++++++++++--- ...-to-its-consumers-with-a-read-interface.md | 21 +++++++++++++++ docs/contracts.md | 9 ++++--- ...o-its-consumers-with-a-read-interface.html | 20 ++++++++++++++ site/docs/changelog.html | 26 ++++++++++++++++--- site/docs/contracts.html | 9 ++++--- 6 files changed, 96 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b1f955d6..5013a5034 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,11 +25,14 @@ verify one. `kind=segments max_line_bytes=786432 segment_bytes=unknown max_bytes=unknown budget_refusals=unknown`. The byte bounds and budget refusal count are local to `collect`. - For a directory of segments, `trail `, `writer_held` in - `trail export `, and `trail segments ` ask `segments.lock` and - the live segment's lock whether a writer holds the log: held when either - is held. If either cannot be asked, `segments.lock` is missing, or the - path no longer names that directory, `trail segments` exits 1 with + `trail export `, and `trail segments ` ask the directory's own + lock, `segments.lock` and the live segment's lock in order. Any held lock + answers held; a lock that cannot be asked beside one that is held answers + held. If the path no longer names that directory or its lock cannot be + asked, or, with none held, `segments.lock` is missing or either file's + lock cannot be asked, `trail segments` exits 1 with `trail segments: recordlog: whether a writer holds the log is unknown`. + A missing live segment counts as free when the locks are free. `trail` and `trail export` refuse the same way if the live segment ends in a partial line. - `collect`, `trail`, `trail export`, `trail segments` and `prune` use @@ -63,6 +66,20 @@ verify one. ### Fixed +- A writer of a directory of segments now holds an exclusive lock on the + log directory itself, so a second writer (`prune` beside a running + `collect`) is refused with + `segmentlog: the directory is held by another writer` even with + `segments.lock` unlinked or replaced and no live segment. Before, such a + `prune` could open beside the collector, and the collector's next seal + left a log that refused to open with + `segment-00000001.jsonl is named sealed and is not there`. The log also + refuses a live segment its opener did not lock + (`segmentlog: the live file was opened and not locked`). + Stop every `collect` and `prune` of an earlier version before running + this one on the same directory, because while an earlier writer runs + there, one writer per log rests on `segments.lock` alone, as before. + - `guardana-gateway doctor` now fails its `upstreams` check, in every mode (`OBSERVE` included), when a tool name is listed more than once, within or across upstreams. It names each (` is listed more than once, so a call diff --git a/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md b/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md index 987770994..4954d7405 100644 --- a/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md +++ b/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md @@ -58,6 +58,18 @@ more consumers. has no `/metrics` of its own. - The manifest's format `guardana.control.segments` `0.1` is unchanged for the evidence trail; ADR-0092 adds `0.2`. +- The `segments` kind takes the log directory's exclusive lock through the + directory it judged before taking `segments.lock` and holds it until + close. `segments.lock` stays for readers and writers of earlier builds. + Name changes leave the directory locked, so only one writer holds the + log with or without a live segment. Readers ask the directory's lock + through the directory they inspected, then `segments.lock`, then the live + segment's lock. Any held lock answers held. The answer is free if every + lock asked is free and unknown otherwise. Outside the port, + `Options.OpenLive` must lock the returned file with `segmentlog.Lock`. + Once it returns, the kind reopens the file and asks its lock: it refuses + open or fails the log on append with `ErrLiveUnlocked`. The conformance + suite uses the package's test opener, which locks. ## Security / compatibility impact @@ -66,6 +78,15 @@ what changes is where the port is declared and that every read goes through it. A dependency test refuses an import of the kind, or of file-system types, from the port package. +Writers (`collect`, `prune`) lock the log directory exclusively before +`segments.lock`. Earlier writers and readers ask only `segments.lock` (and an +earlier reader reads a missing `segments.lock` as free). While an earlier +writer runs there, one writer per log rests on `segments.lock` alone, as +before. Stop every earlier `collect` and `prune` before running this version +there. File systems unable to lock directories refuse the writer opening the +log (reporting the lock error); readers there answer that whether a writer +holds the log is unknown. Nothing falls back to the lock file alone. + ## Alternatives considered - Moving the existing types as they are: the port would still hand out file diff --git a/docs/contracts.md b/docs/contracts.md index 85e735796..28a321ed1 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1189,9 +1189,12 @@ when it was opened, and holds no lock. The bytes after the last newline are a line a collector is still writing while one holds the file: the trailer counts them, `writer_held` is `true`, and the next export reads them once they end. Whether a writer holds the file is asked only when such bytes exist; for a -directory of segments it is asked of both `segments.lock` and the live -segment's lock: it is held when either is held, and when the answer is unknown -the export is refused. When none holds it they are a `partial_tail` gap. A gap +directory of segments the export asks the directory's lock, `segments.lock` +and the live segment's lock in order. Any held lock answers held. The +export is refused if the path no longer names that directory or its lock +cannot be asked. With none held, all locks must answer free, counting a +missing live segment as free, or the export is refused. +When none holds it they are a `partial_tail` gap. A gap takes a record like any other, so an export whose limit leaves no room for it ends with `end_reached` false and the next export writes it. A reader refuses an export whose trailer counts such bytes with `end_reached` true, diff --git a/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html b/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html index e9596a2f5..c4b08eb99 100644 --- a/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html +++ b/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html @@ -180,12 +180,32 @@

                  Decision

                  has no /metrics of its own.
                • The manifest's format guardana.control.segments 0.1 is unchanged for the evidence trail; ADR-0092 adds 0.2.
                • +
                • The segments kind takes the log directory's exclusive lock through the +directory it judged before taking segments.lock and holds it until +close. segments.lock stays for readers and writers of earlier builds. +Name changes leave the directory locked, so only one writer holds the +log with or without a live segment. Readers ask the directory's lock +through the directory they inspected, then segments.lock, then the live +segment's lock. Any held lock answers held. The answer is free if every +lock asked is free and unknown otherwise. Outside the port, +Options.OpenLive must lock the returned file with segmentlog.Lock. +Once it returns, the kind reopens the file and asks its lock: it refuses +open or fails the log on append with ErrLiveUnlocked. The conformance +suite uses the package's test opener, which locks.

                Security / compatibility impact

                No file format, export, cursor or command line changes for the evidence trail; what changes is where the port is declared and that every read goes through it. A dependency test refuses an import of the kind, or of file-system types, from the port package.

                +

                Writers (collect, prune) lock the log directory exclusively before +segments.lock. Earlier writers and readers ask only segments.lock (and an +earlier reader reads a missing segments.lock as free). While an earlier +writer runs there, one writer per log rests on segments.lock alone, as +before. Stop every earlier collect and prune before running this version +there. File systems unable to lock directories refuse the writer opening the +log (reporting the lock error); readers there answer that whether a writer +holds the log is unknown. Nothing falls back to the lock file alone.

                Alternatives considered

                • Moving the existing types as they are: the port would still hand out file diff --git a/site/docs/changelog.html b/site/docs/changelog.html index 17d878e20..64b8030ea 100644 --- a/site/docs/changelog.html +++ b/site/docs/changelog.html @@ -156,11 +156,14 @@

                  Changed

                • For a directory of segments, trail <dir>, writer_held in -trail export <dir>, and trail segments <dir> ask segments.lock and -the live segment's lock whether a writer holds the log: held when either -is held. If either cannot be asked, segments.lock is missing, or the -path no longer names that directory, trail segments exits 1 with +trail export <dir>, and trail segments <dir> ask the directory's own +lock, segments.lock and the live segment's lock in order. Any held lock +answers held; a lock that cannot be asked beside one that is held answers +held. If the path no longer names that directory or its lock cannot be +asked, or, with none held, segments.lock is missing or either file's +lock cannot be asked, trail segments exits 1 with trail segments: recordlog: whether a writer holds the log is unknown. +A missing live segment counts as free when the locks are free. trail and trail export refuse the same way if the live segment ends in a partial line.

                • @@ -198,6 +201,21 @@

                  Changed

                  Fixed

                  • +

                    A writer of a directory of segments now holds an exclusive lock on the +log directory itself, so a second writer (prune beside a running +collect) is refused with +segmentlog: the directory is held by another writer even with +segments.lock unlinked or replaced and no live segment. Before, such a +prune could open beside the collector, and the collector's next seal +left a log that refused to open with +segment-00000001.jsonl is named sealed and is not there. The log also +refuses a live segment its opener did not lock +(segmentlog: the live file was opened and not locked). +Stop every collect and prune of an earlier version before running +this one on the same directory, because while an earlier writer runs +there, one writer per log rests on segments.lock alone, as before.

                    +
                  • +
                  • guardana-gateway doctor now fails its upstreams check, in every mode (OBSERVE included), when a tool name is listed more than once, within or across upstreams. It names each (<name> is listed more than once, so a call to it is unclassified) and counts them on the check line (N tool name(s) listed more than once). Names from withheld definitions print as <withheld name>, here and for unclassified tools, since they may hold the scan's diff --git a/site/docs/contracts.html b/site/docs/contracts.html index 2c952728c..8236835ac 100644 --- a/site/docs/contracts.html +++ b/site/docs/contracts.html @@ -1469,9 +1469,12 @@

                    What is read

                    line a collector is still writing while one holds the file: the trailer counts them, writer_held is true, and the next export reads them once they end. Whether a writer holds the file is asked only when such bytes exist; for a -directory of segments it is asked of both segments.lock and the live -segment's lock: it is held when either is held, and when the answer is unknown -the export is refused. When none holds it they are a partial_tail gap. A gap +directory of segments the export asks the directory's lock, segments.lock +and the live segment's lock in order. Any held lock answers held. The +export is refused if the path no longer names that directory or its lock +cannot be asked. With none held, all locks must answer free, counting a +missing live segment as free, or the export is refused. +When none holds it they are a partial_tail gap. A gap takes a record like any other, so an export whose limit leaves no room for it ends with end_reached false and the next export writes it. A reader refuses an export whose trailer counts such bytes with end_reached true, From 1b5bb95bcfcb3d38821891c4dce2f41fd6bb53eb Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sun, 29 Nov 2026 20:00:33 +0100 Subject: [PATCH 10/12] fix(segmentlog): pin a reader's open to the directory inspected, refuse a non-empty new live file A view's Open reopened the log by path and never compared the directory it found with the one inspected, so with a copy swapped in at the path an export could read another writer's line in progress as a partial tail no writer held. Open now refuses, as moved, a directory other than the one inspected. With no live file open, an append took whatever stood at live.jsonl as empty, so a file holding lines put there after a seal was adopted and the next seal named wrong bytes. The append now fails the log when the file it opened holds bytes, read through the descriptor that asked its lock. The live lock's unaskable path gets tests: a link at the live name, and a lock asked in error through an unexported seam. Signed-off-by: Konrad Karauda --- internal/segmentlog/onewriter_test.go | 79 +++++++++++++++++++++++++++ internal/segmentlog/segments.go | 39 ++++++++----- internal/segmentlog/view.go | 20 ++++++- internal/segmentlog/view_test.go | 61 +++++++++++++++++++++ internal/segmentlog/write.go | 13 +++-- 5 files changed, 191 insertions(+), 21 deletions(-) diff --git a/internal/segmentlog/onewriter_test.go b/internal/segmentlog/onewriter_test.go index be4c21aaa..30f455d17 100644 --- a/internal/segmentlog/onewriter_test.go +++ b/internal/segmentlog/onewriter_test.go @@ -184,3 +184,82 @@ func TestACopyOfTheLogAtItsPathIsUnknown(t *testing.T) { t.Fatal(err) } } + +// openLinkedLive opens and locks the live file as openTestLive does, then +// moves it to name.x and leaves a link to it at name. +func openLinkedLive(root *os.Root, name string) (LiveFile, error) { + f, err := openTestLive(root, name) + if err != nil { + return nil, err + } + if err := root.Rename(name, name+".x"); err != nil { + return nil, errors.Join(err, f.Close()) + } + if err := root.Symlink(name+".x", name); err != nil { + return nil, errors.Join(err, f.Close()) + } + return f, nil +} + +// TestALiveFileWhoseLockCannotBeAskedRefusesTheAppend: a live file locked by +// its opener and then put behind a link at its name, so its lock cannot be +// asked through the name, refuses the append that opened it as the link it +// is, not as unlocked, and nothing is written to it. +func TestALiveFileWhoseLockCannotBeAskedRefusesTheAppend(t *testing.T) { + cfg := config(logDir(t), 64, 256) + cfg.OpenLive = openLinkedLive + l := openLog(t, cfg) + err := l.Append(context.Background(), []byte("aaa\n")) + if !errors.Is(err, ErrDirectory) || errors.Is(err, ErrLiveUnlocked) { + t.Errorf("an append whose live file's lock cannot be asked = %v, want ErrDirectory and not ErrLiveUnlocked", err) + } + if got := fileText(t, filepath.Join(cfg.Dir, LiveName+".x")); got != "" { + t.Errorf("the live file holds %q after the refused append, want nothing", got) + } +} + +// TestALiveLockAskedInErrorRefusesTheAppendAndLeavesTheLogUsable: an append +// whose live file's lock answers an error when asked is refused with that +// error, neither as unlocked nor failing the log; asked again once it +// answers, the next append is taken alone. +func TestALiveLockAskedInErrorRefusesTheAppendAndLeavesTheLogUsable(t *testing.T) { + cfg := config(logDir(t), 64, 256) + l := openLog(t, cfg) + errAsk := errors.New("the lock cannot be asked") + t.Cleanup(func() { heldByWriter = HeldByWriter }) + heldByWriter = func(*os.File) (bool, error) { return false, errAsk } + err := l.Append(context.Background(), []byte("aaa\n")) + if !errors.Is(err, errAsk) || errors.Is(err, ErrLiveUnlocked) || errors.Is(err, ErrFailed) { + t.Errorf("an append whose live lock answers an error = %v, want that error, not ErrLiveUnlocked or ErrFailed", err) + } + heldByWriter = HeldByWriter + mustAppend(t, l, "bbb") + if got := fileText(t, filepath.Join(cfg.Dir, LiveName)); got != "bbb\n" { + t.Errorf("the live file holds %q, want %q", got, "bbb\n") + } +} + +// TestALiveFileWithLinesPutAtTheNameAfterASealFailsTheLog: a file holding a +// line put at the live name once a seal renamed the live file is refused by +// the next append, which fails the log and writes nothing to it, so no seal +// names its bytes. +func TestALiveFileWithLinesPutAtTheNameAfterASealFailsTheLog(t *testing.T) { + cfg := config(logDir(t), 64, 256) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + if err := l.Seal(); err != nil { + t.Fatal(err) + } + live := filepath.Join(cfg.Dir, LiveName) + putAt(t, live, "zzz\n") + err := l.Append(context.Background(), []byte("bbb\n")) + if !errors.Is(err, ErrFailed) || !errors.Is(err, ErrLiveChanged) { + t.Errorf("an append onto a file put at the live name = %v, want ErrFailed and ErrLiveChanged", err) + } + if err := l.Seal(); !errors.Is(err, ErrFailed) { + t.Errorf("a seal after it = %v, want ErrFailed", err) + } + if got := fileText(t, live); got != "zzz\n" { + t.Errorf("the file put at the live name holds %q, want %q", got, "zzz\n") + } +} diff --git a/internal/segmentlog/segments.go b/internal/segmentlog/segments.go index 8c29f5800..fae283ef8 100644 --- a/internal/segmentlog/segments.go +++ b/internal/segmentlog/segments.go @@ -344,7 +344,7 @@ func (l *segments) openLive(have found) error { if !have.live { return nil } - if err := l.openLiveFile(); err != nil { + if _, err := l.openLiveFile(); err != nil { return err } st, err := l.scanFile(LiveName, l.cfg.Visit) @@ -359,36 +359,45 @@ func (l *segments) openLive(have found) error { } // openLiveFile opens the live segment through the consumer and refuses it, -// closed, unless the consumer locked it as Options.OpenLive says. -func (l *segments) openLiveFile() error { +// closed, unless the consumer locked it as Options.OpenLive says; it returns +// the bytes the file held once locked. +func (l *segments) openLiveFile() (int64, error) { f, err := l.cfg.OpenLive(l.root, LiveName) if err != nil { - return fmt.Errorf("%s: %w", LiveName, err) + return 0, fmt.Errorf("%s: %w", LiveName, err) } - if err := l.liveLocked(); err != nil { - return errors.Join(err, f.Close()) + size, err := l.liveLocked() + if err != nil { + return 0, errors.Join(err, f.Close()) } l.file = f - return nil + return size, nil } +// heldByWriter asks the live file's lock; a test makes it answer an error. +var heldByWriter = HeldByWriter + // liveLocked refuses a live file whose lock no writer holds, and one whose -// lock cannot be asked. A lock is held by one open of the file, so an open of -// its own asks the consumer's. -func (l *segments) liveLocked() error { +// lock cannot be asked, and returns the bytes it holds. A lock is held by one +// open of the file, so an open of its own asks the consumer's. +func (l *segments) liveLocked() (int64, error) { f, err := openJudged(l.root, LiveName, os.O_RDONLY) if err != nil { - return fmt.Errorf("%s: asking its lock: %w", LiveName, err) + return 0, fmt.Errorf("%s: asking its lock: %w", LiveName, err) } defer func() { _ = f.Close() }() - held, err := HeldByWriter(f) + held, err := heldByWriter(f) switch { case err != nil: - return fmt.Errorf("%s: asking its lock: %w", LiveName, err) + return 0, fmt.Errorf("%s: asking its lock: %w", LiveName, err) case !held: - return fmt.Errorf("%w: %s", ErrLiveUnlocked, LiveName) + return 0, fmt.Errorf("%w: %s", ErrLiveUnlocked, LiveName) } - return nil + info, err := f.Stat() + if err != nil { + return 0, err + } + return info.Size(), nil } // retained is the bytes of every segment not pruned. diff --git a/internal/segmentlog/view.go b/internal/segmentlog/view.go index 555a53f95..f6f7c6b7a 100644 --- a/internal/segmentlog/view.go +++ b/internal/segmentlog/view.go @@ -216,8 +216,9 @@ func (c content) Close() error { // begins with the line it began with when the view was read, or whose // manifest, read again once the file is open, names a segment the view did // not, was sealed since, and is ErrMoved; so is one a seal named sealed and -// has not yet renamed, and a sealed segment pruned since. A live segment that -// held no line and has no file is empty. +// has not yet renamed, a sealed segment pruned since, and any segment once +// the path no longer names the directory inspected. A live segment that held +// no line and has no file is empty. func (v *view) Open(s Segment) (recordlog.Content, error) { if s.State != StateSealed && s.State != StateLive { return nil, fmt.Errorf("%w: segment %d is %s", ErrPrune, s.Seq, s.State) @@ -227,6 +228,9 @@ func (v *view) Open(s Segment) (recordlog.Content, error) { return nil, err } defer func() { _ = root.Close() }() + if err := v.inspectedAt(root); err != nil { + return nil, err + } f, err := openRead(root, s.File) if errors.Is(err, fs.ErrNotExist) { if s.State == StateLive { @@ -252,6 +256,18 @@ func (v *view) Open(s Segment) (recordlog.Content, error) { return content{SectionReader: io.NewSectionReader(f, 0, size), f: f}, nil } +// inspectedAt refuses, as moved, a root that is not the directory inspected. +func (v *view) inspectedAt(root *os.Root) error { + at, err := root.Stat(".") + switch { + case err != nil: + return err + case v.dir == nil || !os.SameFile(at, v.dir): + return fmt.Errorf("%w: %s no longer names the directory inspected", ErrMoved, v.cfg.Dir) + } + return nil +} + // eof is what an empty segment reads. type eof struct{} diff --git a/internal/segmentlog/view_test.go b/internal/segmentlog/view_test.go index 85650032d..06f3d2c37 100644 --- a/internal/segmentlog/view_test.go +++ b/internal/segmentlog/view_test.go @@ -286,3 +286,64 @@ func TestALiveFileOpenedBeforeASealsRenameCompletedIsMoved(t *testing.T) { } _ = l.release() } + +// TestALiveSegmentOpenedThroughAnotherDirectoryAtThePathIsMoved: a view's +// live segment opened while a copy of the log, held by a writer with a line +// begun, stands at the path is ErrMoved; the inspected directory back at the +// path, it opens and reads what the view found. +func TestALiveSegmentOpenedThroughAnotherDirectoryAtThePathIsMoved(t *testing.T) { + cfg := config(logDir(t), 64, 256) + l := openLog(t, cfg) + mustAppend(t, l, "aaa") + if err := l.Close(); err != nil { + t.Fatal(err) + } + r, err := Inspect(readConfig(cfg.Dir)) + if err != nil { + t.Fatal(err) + } + live := r.Manifest().Live + inspectedDir := cfg.Dir + ".inspected" + if err := os.Rename(cfg.Dir, inspectedDir); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(cfg.Dir, 0o700); err != nil { + t.Fatal(err) + } + for _, name := range dirNames(t, inspectedDir) { + putAt(t, filepath.Join(cfg.Dir, name), fileText(t, filepath.Join(inspectedDir, name))) + } + copyWriter := openLog(t, cfg) + f, err := os.OpenFile(filepath.Join(cfg.Dir, LiveName), os.O_WRONLY|os.O_APPEND, 0) + if err != nil { + t.Fatal(err) + } + _, err = f.WriteString("bb") + if err := errors.Join(err, f.Close()); err != nil { + t.Fatal(err) + } + if c, err := r.Open(live); !errors.Is(err, ErrMoved) { + if c != nil { + _ = c.Close() + } + t.Errorf("the live segment opened through a copy at the path = %v, want ErrMoved", err) + } + if err := copyWriter.Close(); err != nil { + t.Fatal(err) + } + if err := os.Rename(cfg.Dir, cfg.Dir+".copy"); err != nil { + t.Fatal(err) + } + if err := os.Rename(inspectedDir, cfg.Dir); err != nil { + t.Fatal(err) + } + c, err := r.Open(live) + if err != nil { + t.Fatalf("the live segment opened with the inspected directory back = %v", err) + } + defer func() { _ = c.Close() }() + raw, err := io.ReadAll(io.NewSectionReader(c, 0, c.Size())) + if err != nil || string(raw) != "aaa\n" { + t.Errorf("the live segment read = %q, %v, want %q", raw, err, "aaa\n") + } +} diff --git a/internal/segmentlog/write.go b/internal/segmentlog/write.go index caaca87eb..61419f3d1 100644 --- a/internal/segmentlog/write.go +++ b/internal/segmentlog/write.go @@ -64,7 +64,7 @@ func (l *segments) Append(ctx context.Context, lines []byte) error { // past its bound, before it asks the log's own, so a log the bound refuses // holds a sealed segment to prune; refuses n bytes past the log's bound; and // opens the live segment when none is open, failing the log when its opener -// did not lock it. +// did not lock it or it holds bytes, as the log counts none. func (l *segments) makeRoom(n int64) error { if l.cfg.MaxBytes == 0 { return fmt.Errorf("%w: the log was opened with no bound, so it takes no append", ErrBudget) @@ -80,11 +80,16 @@ func (l *segments) makeRoom(n int64) error { if l.file != nil { return nil } - err := l.openLiveFile() - if errors.Is(err, ErrLiveUnlocked) { + size, err := l.openLiveFile() + switch { + case errors.Is(err, ErrLiveUnlocked): return l.fail(err) + case err != nil: + return err + case size != 0: + return l.fail(fmt.Errorf("%w: %s held %d bytes when it was opened", ErrLiveChanged, LiveName, size)) } - return err + return nil } // Seal seals the live segment when it holds a line. From 5cf86b7e479f95c43f20d30062dba9039299b91c Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sun, 29 Nov 2026 20:26:38 +0100 Subject: [PATCH 11/12] refactor(segmentlog): open a view's directory through one check, keep Open and its test under the complexity bound Signed-off-by: Konrad Karauda --- internal/segmentlog/view.go | 21 ++++++++------ internal/segmentlog/view_test.go | 47 ++++++++++++++++++++------------ 2 files changed, 42 insertions(+), 26 deletions(-) diff --git a/internal/segmentlog/view.go b/internal/segmentlog/view.go index f6f7c6b7a..9c1ce19a8 100644 --- a/internal/segmentlog/view.go +++ b/internal/segmentlog/view.go @@ -223,14 +223,11 @@ func (v *view) Open(s Segment) (recordlog.Content, error) { if s.State != StateSealed && s.State != StateLive { return nil, fmt.Errorf("%w: segment %d is %s", ErrPrune, s.Seq, s.State) } - root, err := os.OpenRoot(v.cfg.Dir + string(os.PathSeparator) + ".") + root, err := v.openInspected() if err != nil { return nil, err } defer func() { _ = root.Close() }() - if err := v.inspectedAt(root); err != nil { - return nil, err - } f, err := openRead(root, s.File) if errors.Is(err, fs.ErrNotExist) { if s.State == StateLive { @@ -256,16 +253,22 @@ func (v *view) Open(s Segment) (recordlog.Content, error) { return content{SectionReader: io.NewSectionReader(f, 0, size), f: f}, nil } -// inspectedAt refuses, as moved, a root that is not the directory inspected. -func (v *view) inspectedAt(root *os.Root) error { +// openInspected opens the directory at the path, refusing as moved one that +// is not the directory inspected. +func (v *view) openInspected() (*os.Root, error) { + root, err := os.OpenRoot(v.cfg.Dir + string(os.PathSeparator) + ".") + if err != nil { + return nil, err + } at, err := root.Stat(".") switch { case err != nil: - return err case v.dir == nil || !os.SameFile(at, v.dir): - return fmt.Errorf("%w: %s no longer names the directory inspected", ErrMoved, v.cfg.Dir) + err = fmt.Errorf("%w: %s no longer names the directory inspected", ErrMoved, v.cfg.Dir) + default: + return root, nil } - return nil + return nil, errors.Join(err, root.Close()) } // eof is what an empty segment reads. diff --git a/internal/segmentlog/view_test.go b/internal/segmentlog/view_test.go index 06f3d2c37..b2724291c 100644 --- a/internal/segmentlog/view_test.go +++ b/internal/segmentlog/view_test.go @@ -287,6 +287,34 @@ func TestALiveFileOpenedBeforeASealsRenameCompletedIsMoved(t *testing.T) { _ = l.release() } +// copyAtPath moves the directory at dir to aside and puts a copy of each of +// its files at dir. +func copyAtPath(t *testing.T, dir, aside string) { + t.Helper() + if err := os.Rename(dir, aside); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(dir, 0o700); err != nil { + t.Fatal(err) + } + for _, name := range dirNames(t, aside) { + putAt(t, filepath.Join(dir, name), fileText(t, filepath.Join(aside, name))) + } +} + +// appendText appends text to the file at path as it is, a newline or not. +func appendText(t *testing.T, path, text string) { + t.Helper() + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0) //nolint:gosec // G304: the test's own directory + if err != nil { + t.Fatal(err) + } + _, err = f.WriteString(text) + if err := errors.Join(err, f.Close()); err != nil { + t.Fatal(err) + } +} + // TestALiveSegmentOpenedThroughAnotherDirectoryAtThePathIsMoved: a view's // live segment opened while a copy of the log, held by a writer with a line // begun, stands at the path is ErrMoved; the inspected directory back at the @@ -304,24 +332,9 @@ func TestALiveSegmentOpenedThroughAnotherDirectoryAtThePathIsMoved(t *testing.T) } live := r.Manifest().Live inspectedDir := cfg.Dir + ".inspected" - if err := os.Rename(cfg.Dir, inspectedDir); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(cfg.Dir, 0o700); err != nil { - t.Fatal(err) - } - for _, name := range dirNames(t, inspectedDir) { - putAt(t, filepath.Join(cfg.Dir, name), fileText(t, filepath.Join(inspectedDir, name))) - } + copyAtPath(t, cfg.Dir, inspectedDir) copyWriter := openLog(t, cfg) - f, err := os.OpenFile(filepath.Join(cfg.Dir, LiveName), os.O_WRONLY|os.O_APPEND, 0) - if err != nil { - t.Fatal(err) - } - _, err = f.WriteString("bb") - if err := errors.Join(err, f.Close()); err != nil { - t.Fatal(err) - } + appendText(t, filepath.Join(cfg.Dir, LiveName), "bb") if c, err := r.Open(live); !errors.Is(err, ErrMoved) { if c != nil { _ = c.Close() From 219aedfe95db4d04b3790b37c523dacf02ce4565 Mon Sep 17 00:00:00 2001 From: Konrad Karauda Date: Sun, 29 Nov 2026 21:14:33 +0100 Subject: [PATCH 12/12] docs(recordlog): say what earlier builds ask and what a reader's open pins Earlier writers lock segments.lock and the live file, and earlier trail and trail export ask only the live file's lock, so one writer per log rests on both locks while an earlier writer runs, not on segments.lock alone. An unaskable directory lock answers unknown without asking the others; an unaskable live lock refuses the append and leaves the log usable. A reader opens each segment through the directory it inspected, and a new live file that holds bytes fails the log. Signed-off-by: Konrad Karauda --- CHANGELOG.md | 51 +++++++++++-------- ...-to-its-consumers-with-a-read-interface.md | 33 +++++++----- ...o-its-consumers-with-a-read-interface.html | 33 +++++++----- site/docs/changelog.html | 51 +++++++++++-------- 4 files changed, 102 insertions(+), 66 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5965de6d6..a6fe246ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,15 +26,21 @@ verify one. The byte bounds and budget refusal count are local to `collect`. - For a directory of segments, `trail `, `writer_held` in `trail export `, and `trail segments ` ask the directory's own - lock, `segments.lock` and the live segment's lock in order. Any held lock - answers held; a lock that cannot be asked beside one that is held answers - held. If the path no longer names that directory or its lock cannot be - asked, or, with none held, `segments.lock` is missing or either file's - lock cannot be asked, `trail segments` exits 1 with - `trail segments: recordlog: whether a writer holds the log is unknown`. - A missing live segment counts as free when the locks are free. - `trail` and `trail export` refuse the same way if the live segment ends in - a partial line. + lock, `segments.lock` and the live segment's lock in order. When the + directory's own lock cannot be asked, the answer is unknown at once and + neither file's lock is asked. Otherwise any held lock answers held; + between `segments.lock` and the live segment's lock, a lock that cannot be + asked beside one that is held answers held. If the path no longer names + that directory or its lock cannot be asked, or, with none held, + `segments.lock` is missing or either file's lock cannot be asked, + `trail segments` exits 1 with + `trail segments: recordlog: whether a writer holds the log is unknown`. A + missing live segment counts as free when the locks are free. `trail` and + `trail export` refuse the same way if the live segment ends in a partial + line. Both read each segment through the directory they inspected; if the + path names another directory by the time a segment is opened, the read + starts again, and after three such moves in a row it is refused with + `recordlog: the segment moved while it was opened: 3 times running`. - `collect`, `trail`, `trail export`, `trail segments` and `prune` use `recordlog:` for shared log refusals. Refusals specific to segments keep `segmentlog:`. @@ -66,19 +72,24 @@ verify one. ### Fixed -- A writer of a directory of segments now holds an exclusive lock on the - log directory itself, so a second writer (`prune` beside a running - `collect`) is refused with - `segmentlog: the directory is held by another writer` even with - `segments.lock` unlinked or replaced and no live segment. Before, such a - `prune` could open beside the collector, and the collector's next seal - left a log that refused to open with +- A writer of a directory of segments now holds an exclusive lock on the log + directory itself, so a second writer (`prune` beside a running `collect`) + is refused with `segmentlog: the directory is held by another writer` even + with `segments.lock` unlinked or replaced and no live segment. Before, + such a `prune` could open beside the collector, and the collector's next + seal left a log that refused to open with `segment-00000001.jsonl is named sealed and is not there`. The log also refuses a live segment its opener did not lock - (`segmentlog: the live file was opened and not locked`). - Stop every `collect` and `prune` of an earlier version before running - this one on the same directory, because while an earlier writer runs - there, one writer per log rests on `segments.lock` alone, as before. + (`segmentlog: the live file was opened and not locked`). After a seal, a + `collect` that finds a file holding bytes at `live.jsonl` when it opens + the next live segment fails the log and writes nothing to that file, with + `segmentlog: the live file no longer holds what the log counted: live.jsonl held N bytes when it was opened`; + before, it appended onto those bytes and the next seal named a segment by + counts that did not match its file, which only the next open refused. Stop + every `collect` and `prune` of an earlier version before running this one + on the same directory, because while an earlier writer runs there, one + writer per log rests on `segments.lock` and the live segment's lock, as + before. - `runs prune` puts a signed runs directory's marker and pruned records in the archive's only directory, `records/`, so `runs list` reads the archive diff --git a/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md b/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md index 4954d7405..bb67a21da 100644 --- a/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md +++ b/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.md @@ -61,15 +61,20 @@ more consumers. - The `segments` kind takes the log directory's exclusive lock through the directory it judged before taking `segments.lock` and holds it until close. `segments.lock` stays for readers and writers of earlier builds. - Name changes leave the directory locked, so only one writer holds the - log with or without a live segment. Readers ask the directory's lock - through the directory they inspected, then `segments.lock`, then the live + Name changes leave the directory locked, so only one writer holds the log + with or without a live segment. Readers ask the directory's lock through + the directory they inspected, then `segments.lock`, then the live segment's lock. Any held lock answers held. The answer is free if every lock asked is free and unknown otherwise. Outside the port, `Options.OpenLive` must lock the returned file with `segmentlog.Lock`. - Once it returns, the kind reopens the file and asks its lock: it refuses - open or fails the log on append with `ErrLiveUnlocked`. The conformance - suite uses the package's test opener, which locks. + Once it returns, the kind reopens the file and asks its lock. A lock that + answers free refuses the open, or fails the log on append, with + `ErrLiveUnlocked`. A lock that cannot be asked refuses the open with that + error, or refuses that append with it and leaves the log usable (the next + append asks again). When the kind opens a new live segment on append + (after a seal), the file must hold no bytes; one that does fails the log + with `ErrLiveChanged`. The conformance suite uses the package's test + opener, which locks. ## Security / compatibility impact @@ -79,13 +84,15 @@ A dependency test refuses an import of the kind, or of file-system types, from the port package. Writers (`collect`, `prune`) lock the log directory exclusively before -`segments.lock`. Earlier writers and readers ask only `segments.lock` (and an -earlier reader reads a missing `segments.lock` as free). While an earlier -writer runs there, one writer per log rests on `segments.lock` alone, as -before. Stop every earlier `collect` and `prune` before running this version -there. File systems unable to lock directories refuse the writer opening the -log (reporting the lock error); readers there answer that whether a writer -holds the log is unknown. Nothing falls back to the lock file alone. +`segments.lock`. Earlier writers lock `segments.lock` and the live segment's +file they open. Earlier `trail` and `trail export` ask only the live segment's +lock; only earlier `trail segments` asks `segments.lock` (and reads a missing +`segments.lock` as free). While an earlier writer runs there, one writer per +log rests on `segments.lock` and the live segment's lock, as before. Stop every +earlier `collect` and `prune` before running this version there. File systems +unable to lock directories refuse the writer opening the log (reporting the +lock error); readers there answer that whether a writer holds the log is +unknown. Nothing falls back to the lock file alone. ## Alternatives considered diff --git a/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html b/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html index c4b08eb99..9eadb72e0 100644 --- a/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html +++ b/site/docs/adr/0091-the-record-log-port-moves-to-its-consumers-with-a-read-interface.html @@ -183,15 +183,20 @@

                    Decision

                  • The segments kind takes the log directory's exclusive lock through the directory it judged before taking segments.lock and holds it until close. segments.lock stays for readers and writers of earlier builds. -Name changes leave the directory locked, so only one writer holds the -log with or without a live segment. Readers ask the directory's lock -through the directory they inspected, then segments.lock, then the live +Name changes leave the directory locked, so only one writer holds the log +with or without a live segment. Readers ask the directory's lock through +the directory they inspected, then segments.lock, then the live segment's lock. Any held lock answers held. The answer is free if every lock asked is free and unknown otherwise. Outside the port, Options.OpenLive must lock the returned file with segmentlog.Lock. -Once it returns, the kind reopens the file and asks its lock: it refuses -open or fails the log on append with ErrLiveUnlocked. The conformance -suite uses the package's test opener, which locks.
                  • +Once it returns, the kind reopens the file and asks its lock. A lock that +answers free refuses the open, or fails the log on append, with +ErrLiveUnlocked. A lock that cannot be asked refuses the open with that +error, or refuses that append with it and leaves the log usable (the next +append asks again). When the kind opens a new live segment on append +(after a seal), the file must hold no bytes; one that does fails the log +with ErrLiveChanged. The conformance suite uses the package's test +opener, which locks.

                  Security / compatibility impact

                  No file format, export, cursor or command line changes for the evidence trail; @@ -199,13 +204,15 @@

                  Security / compatibility impact

                  A dependency test refuses an import of the kind, or of file-system types, from the port package.

                  Writers (collect, prune) lock the log directory exclusively before -segments.lock. Earlier writers and readers ask only segments.lock (and an -earlier reader reads a missing segments.lock as free). While an earlier -writer runs there, one writer per log rests on segments.lock alone, as -before. Stop every earlier collect and prune before running this version -there. File systems unable to lock directories refuse the writer opening the -log (reporting the lock error); readers there answer that whether a writer -holds the log is unknown. Nothing falls back to the lock file alone.

                  +segments.lock. Earlier writers lock segments.lock and the live segment's +file they open. Earlier trail and trail export ask only the live segment's +lock; only earlier trail segments asks segments.lock (and reads a missing +segments.lock as free). While an earlier writer runs there, one writer per +log rests on segments.lock and the live segment's lock, as before. Stop every +earlier collect and prune before running this version there. File systems +unable to lock directories refuse the writer opening the log (reporting the +lock error); readers there answer that whether a writer holds the log is +unknown. Nothing falls back to the lock file alone.

                  Alternatives considered

                  • Moving the existing types as they are: the port would still hand out file diff --git a/site/docs/changelog.html b/site/docs/changelog.html index 0fd205f2a..138600ae3 100644 --- a/site/docs/changelog.html +++ b/site/docs/changelog.html @@ -157,15 +157,21 @@

                    Changed

                  • For a directory of segments, trail <dir>, writer_held in trail export <dir>, and trail segments <dir> ask the directory's own -lock, segments.lock and the live segment's lock in order. Any held lock -answers held; a lock that cannot be asked beside one that is held answers -held. If the path no longer names that directory or its lock cannot be -asked, or, with none held, segments.lock is missing or either file's -lock cannot be asked, trail segments exits 1 with -trail segments: recordlog: whether a writer holds the log is unknown. -A missing live segment counts as free when the locks are free. -trail and trail export refuse the same way if the live segment ends in -a partial line.

                    +lock, segments.lock and the live segment's lock in order. When the +directory's own lock cannot be asked, the answer is unknown at once and +neither file's lock is asked. Otherwise any held lock answers held; +between segments.lock and the live segment's lock, a lock that cannot be +asked beside one that is held answers held. If the path no longer names +that directory or its lock cannot be asked, or, with none held, +segments.lock is missing or either file's lock cannot be asked, +trail segments exits 1 with +trail segments: recordlog: whether a writer holds the log is unknown. A +missing live segment counts as free when the locks are free. trail and +trail export refuse the same way if the live segment ends in a partial +line. Both read each segment through the directory they inspected; if the +path names another directory by the time a segment is opened, the read +starts again, and after three such moves in a row it is refused with +recordlog: the segment moved while it was opened: 3 times running.

                  • collect, trail, trail export, trail segments and prune use @@ -201,19 +207,24 @@

                    Changed

                    Fixed

                    • -

                      A writer of a directory of segments now holds an exclusive lock on the -log directory itself, so a second writer (prune beside a running -collect) is refused with -segmentlog: the directory is held by another writer even with -segments.lock unlinked or replaced and no live segment. Before, such a -prune could open beside the collector, and the collector's next seal -left a log that refused to open with +

                      A writer of a directory of segments now holds an exclusive lock on the log +directory itself, so a second writer (prune beside a running collect) +is refused with segmentlog: the directory is held by another writer even +with segments.lock unlinked or replaced and no live segment. Before, +such a prune could open beside the collector, and the collector's next +seal left a log that refused to open with segment-00000001.jsonl is named sealed and is not there. The log also refuses a live segment its opener did not lock -(segmentlog: the live file was opened and not locked). -Stop every collect and prune of an earlier version before running -this one on the same directory, because while an earlier writer runs -there, one writer per log rests on segments.lock alone, as before.

                      +(segmentlog: the live file was opened and not locked). After a seal, a +collect that finds a file holding bytes at live.jsonl when it opens +the next live segment fails the log and writes nothing to that file, with +segmentlog: the live file no longer holds what the log counted: live.jsonl held N bytes when it was opened; +before, it appended onto those bytes and the next seal named a segment by +counts that did not match its file, which only the next open refused. Stop +every collect and prune of an earlier version before running this one +on the same directory, because while an earlier writer runs there, one +writer per log rests on segments.lock and the live segment's lock, as +before.

                    • runs prune puts a signed runs directory's marker and pruned records in