Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 51 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,38 @@ verify one.

### 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 every later append until it opens the
log again.

### 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 the directory's own
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:`.

- Under `approvals.authority: signed`, the plane reads the part of an inbox
name before the first `.` without regard to ASCII letter case. A name
holding a byte outside ASCII is read for every approval. A file the
Expand All @@ -23,8 +55,6 @@ verify one.
or junk, or vary case on a folding volume, and the sticky bit kept the
operator from removing it, letting another approval run the call.

### Changed

- Answers failing authentication, including answers signed by a key a
newer roster no longer names, count under cause `unauthenticated`; another
approval's body counts `other_approval`. Non-ASCII names (read for every
Expand Down Expand Up @@ -95,6 +125,25 @@ 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`). 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.

- Before, a retry read the ledger, then closed on a refusal. It now gives up
the approval (`not resumed`) first. Give-up and spend share one
compare-and-swap in both ledgers. If spend wins, the spender runs once and
Expand Down
5 changes: 2 additions & 3 deletions cmd/guardana-gateway/collect_bound_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down
46 changes: 22 additions & 24 deletions cmd/guardana-gateway/segments.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <segment> <dir>"

// 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))
}
Expand Down Expand Up @@ -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)
}
Expand Down
68 changes: 68 additions & 0 deletions cmd/guardana-gateway/segments_test.go
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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)
Expand Down Expand Up @@ -58,6 +58,23 @@ 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. 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

Expand All @@ -66,6 +83,17 @@ 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 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
Expand Down
2 changes: 1 addition & 1 deletion docs/backlog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Loading
Loading