refactor: testing from the beginning. a journey in 150k lines of tests to none

This commit is contained in:
sam committed 2026-10-03 21:16:25 +10:00
1 parent ba37e37e53
commit ff424b70ac
651 files changed
-146443

No files matched your search

-154
View File
@@ -1,154 +0,0 @@
package logging
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"testing"
"time"
)
// TestFlattenAttrs pins the shape FeedHandler and any other slog.Handler
// producing Entry.Fields must agree on: handler-bound attrs, group prefixes,
// and the record's own attrs all merge into one flat map, dotted by group.
func TestFlattenAttrs(t *testing.T) {
tests := []struct {
name string
base []slog.Attr
groups []string
record func() slog.Record
want map[string]any
}{
{
name: "record attrs only",
record: func() slog.Record { return newTestRecord("component", "gate") },
want: map[string]any{"component": "gate"},
},
{
name: "base attrs merge with record attrs",
base: []slog.Attr{slog.String("task", "42")},
record: func() slog.Record { return newTestRecord("component", "gate") },
want: map[string]any{"task": "42", "component": "gate"},
},
{
name: "groups prefix every key",
groups: []string{"agent"},
record: func() slog.Record { return newTestRecord("component", "gate") },
want: map[string]any{"agent.component": "gate"},
},
{
name: "no attrs at all yields nil, not an empty map",
record: func() slog.Record { return newTestRecord() },
want: nil,
},
{
// base is what WithAttrs accumulates; by the time it reaches
// FlattenAttrs it must already carry whatever group prefix was
// active when it was added (see prefixAttrs) -- groups here is
// the chain active *now*, for the record's own attrs, and must
// not be re-applied to base. Callers that instead pass raw,
// un-prefixed attrs as base alongside a non-empty groups chain
// are the historical bug this case pins: it would wrongly nest
// "task" under "agent" too.
name: "groups only apply to the record's own attrs, not to base",
base: []slog.Attr{slog.String("task", "42")}, // pre-grouped by the caller; here, not grouped at all
groups: []string{"agent"},
record: func() slog.Record { return newTestRecord("component", "gate") },
want: map[string]any{"task": "42", "agent.component": "gate"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := FlattenAttrs(tt.record(), tt.base, tt.groups)
if len(got) != len(tt.want) {
t.Fatalf("FlattenAttrs() = %#v, want %#v", got, tt.want)
}
for k, v := range tt.want {
if got[k] != v {
t.Errorf("FlattenAttrs()[%q] = %v, want %v", k, got[k], v)
}
}
if tt.want == nil && got != nil {
t.Errorf("FlattenAttrs() = %#v, want nil", got)
}
})
}
}
// TestFlattenAttrsConvertsErrorsToTheirMessageString pins the regression that
// shipped archie-core's task/system logs full of "err":{}: SystemLogHandler
// and FeedHandler both json.Marshal Entry.Fields directly rather than going
// through slog's own JSON handler, and encoding/json has no idea an `error`
// value should become its message -- it reflects the concrete type's fields,
// which for a stdlib error are unexported, so the message vanishes into `{}`.
func TestFlattenAttrsConvertsErrorsToTheirMessageString(t *testing.T) {
tests := []struct {
name string
err error
want string
}{
{name: "plain error", err: errors.New("boom"), want: "boom"},
{name: "wrapped error", err: fmt.Errorf("outer: %w", errors.New("inner")), want: "outer: inner"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
record := slog.NewRecord(time.Now(), slog.LevelError, "handle failed", 0)
record.AddAttrs(slog.Any("err", tt.err))
got := FlattenAttrs(record, nil, nil)
value, ok := got["err"].(string)
if !ok {
t.Fatalf("FlattenAttrs()[%q] = %#v (%T), want a string", "err", got["err"], got["err"])
}
if value != tt.want {
t.Errorf("FlattenAttrs()[%q] = %q, want %q", "err", value, tt.want)
}
encoded, marshalErr := json.Marshal(map[string]any{"err": got["err"]})
if marshalErr != nil {
t.Fatalf("json.Marshal: %v", marshalErr)
}
if string(encoded) == `{"err":{}}` {
t.Errorf("json.Marshal(%#v) = %s, error message was discarded", got["err"], encoded)
}
})
}
}
// typedNilError has a pointer receiver Error() that dereferences itself, so
// calling it on a nil *typedNilError panics -- the classic Go footgun where
// a non-nil error interface wraps a nil concrete pointer.
type typedNilError struct{ msg string }
func (e *typedNilError) Error() string { return e.msg }
// TestFlattenAttrsDoesNotPanicOnATypedNilError pins the case
// TestFlattenAttrsConvertsErrorsToTheirMessageString's err != nil check
// misses: `var e *typedNilError; var err error = e` is a non-nil interface,
// so a naive nil check would call Error() on a nil receiver and crash the
// process -- the one failure mode a logging package must never have.
func TestFlattenAttrsDoesNotPanicOnATypedNilError(t *testing.T) {
var e *typedNilError
var err error = e
record := slog.NewRecord(time.Now(), slog.LevelError, "handle failed", 0)
record.AddAttrs(slog.Any("err", err))
got := FlattenAttrs(record, nil, nil) // must not panic
if _, err := json.Marshal(map[string]any{"err": got["err"]}); err != nil {
t.Fatalf("json.Marshal: %v", err)
}
}
func newTestRecord(kvs ...string) slog.Record {
r := slog.NewRecord(time.Now(), slog.LevelInfo, "msg", 0)
for i := 0; i+1 < len(kvs); i += 2 {
r.AddAttrs(slog.String(kvs[i], kvs[i+1]))
}
return r
}
-56
View File
@@ -1,56 +0,0 @@
package logging
import (
"bytes"
"context"
"encoding/json"
"log/slog"
"testing"
)
func TestFeedCapturesStructuredSlogEntriesInOrder(t *testing.T) {
feed := NewFeed(2)
logger := slog.New(NewFeedHandler(slog.NewJSONHandler(testWriter{}, nil), feed))
logger.Info("started", "component", "daemon")
logger.Warn("slow", "component", "worker")
entries := feed.Snapshot()
if len(entries) != 2 || entries[0].ID == 0 || entries[1].ID <= entries[0].ID {
t.Fatalf("entries = %#v", entries)
}
if entries[0].Message != "started" || entries[0].Fields["component"] != "daemon" {
t.Fatalf("first entry = %#v", entries[0])
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
updates := feed.Subscribe(ctx)
logger.Error("failed", "component", "worker")
if got := <-updates; got.Message != "failed" || got.Level != "ERROR" {
t.Fatalf("live entry = %#v", got)
}
}
func TestFeedHandlerWithAttrsPropagatesToWrappedHandler(t *testing.T) {
feed := NewFeed(2)
var buf bytes.Buffer
logger := slog.New(NewFeedHandler(slog.NewJSONHandler(&buf, nil), feed)).With("component", "curator")
logger.Info("ran")
entries := feed.Snapshot()
if len(entries) != 1 || entries[0].Fields["component"] != "curator" {
t.Fatalf("feed entry = %#v, want component=curator", entries)
}
var decoded map[string]any
if err := json.Unmarshal(buf.Bytes(), &decoded); err != nil {
t.Fatalf("json.Unmarshal(persistent sink output) = %v", err)
}
if decoded["component"] != "curator" {
t.Fatalf("persistent sink output = %#v, want component=curator", decoded)
}
}
type testWriter struct{}
func (testWriter) Write(p []byte) (int, error) { return len(p), nil }
-247
View File
@@ -1,247 +0,0 @@
package logging
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func TestNewWritesToFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "archied.log")
log, closer, err := New(Options{File: path})
if err != nil {
t.Fatalf("New: %v", err)
}
log.Info("hello", "task", 42)
if err := closer.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
body, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read log: %v", err)
}
var entry map[string]any
if err := json.Unmarshal([]byte(strings.TrimSpace(string(body))), &entry); err != nil {
t.Fatalf("log line is not JSON: %v (%q)", err, body)
}
if entry["msg"] != "hello" {
t.Errorf("msg = %v, want hello", entry["msg"])
}
}
func TestNewCreatesParentDirectory(t *testing.T) {
path := filepath.Join(t.TempDir(), "nested", "deeper", "archied.log")
_, closer, err := New(Options{File: path})
if err != nil {
t.Fatalf("New: %v", err)
}
t.Cleanup(func() { _ = closer.Close() })
if _, err := os.Stat(path); err != nil {
t.Errorf("log file not created: %v", err)
}
}
// TestNewFallsBackWhenFileUnavailable pins that an unopenable log file
// degrades to stderr with an error, rather than leaving the daemon without a
// logger or refusing to start. Losing the durable copy must not take the
// daemon down with it.
func TestNewFallsBackWhenFileUnavailable(t *testing.T) {
// A path whose parent is a regular file cannot be created.
blocker := filepath.Join(t.TempDir(), "not-a-dir")
if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
log, closer, err := New(Options{File: filepath.Join(blocker, "archied.log")})
if err == nil {
t.Error("New returned nil error for an unusable path, want one reported")
}
if log == nil {
t.Fatal("New returned a nil logger; a usable logger is required even on failure")
}
log.Info("still works")
if closer == nil {
t.Fatal("New returned a nil closer")
}
if err := closer.Close(); err != nil {
t.Errorf("Close on the fallback closer: %v", err)
}
}
func TestLevelFiltering(t *testing.T) {
tests := []struct {
name string
level string
wantDebug bool
wantInfo bool
}{
{"default is info", "", false, true},
{"debug shows everything", "debug", true, true},
{"warn hides info", "warn", false, false},
{"error hides info", "error", false, false},
{"unrecognised falls back to info", "chatty", false, true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "archied.log")
log, closer, err := New(Options{File: path, Level: tc.level})
if err != nil {
t.Fatalf("New: %v", err)
}
log.Debug("a-debug-line")
log.Info("an-info-line")
if err := closer.Close(); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
got := string(body)
if strings.Contains(got, "a-debug-line") != tc.wantDebug {
t.Errorf("debug present = %v, want %v", !tc.wantDebug, tc.wantDebug)
}
if strings.Contains(got, "an-info-line") != tc.wantInfo {
t.Errorf("info present = %v, want %v", !tc.wantInfo, tc.wantInfo)
}
})
}
}
// TestRotation pins that the file is capped and old generations are kept in
// order, so a resident daemon cannot fill the disk.
func TestRotation(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "archied.log")
// 1MB cap, keep 2. Rotation is size-driven, so write past it.
w, err := newRotatingFile(path, 1, 2)
if err != nil {
t.Fatalf("newRotatingFile: %v", err)
}
line := strings.Repeat("x", 64*1024) + "\n"
for range 40 {
if _, err := w.Write([]byte(line)); err != nil {
t.Fatalf("Write: %v", err)
}
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("live log missing: %v", err)
}
if info.Size() > 2*1024*1024 {
t.Errorf("live log is %d bytes, want it capped near 1MB", info.Size())
}
for i := 1; i <= 2; i++ {
if _, err := os.Stat(fmt.Sprintf("%s.%d", path, i)); err != nil {
t.Errorf("rotated file .%d missing: %v", i, err)
}
}
// Retention is honoured: nothing beyond keep survives.
if _, err := os.Stat(path + ".3"); err == nil {
t.Error("archied.log.3 exists, want retention capped at 2")
}
}
// TestRotationSurvivesFailedReopen pins that a failed rotation reopen (a
// full filesystem, a permission change hit exactly when archied tries to
// recreate the live file) does not take down the file sink permanently.
// The write that triggered rotation must not be silently swallowed, and
// -- unlike losing a single line -- every write after the failure must
// not be lost either.
func TestRotationSurvivesFailedReopen(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "archied.log")
w, err := newRotatingFile(path, 1, 2)
if err != nil {
t.Fatalf("newRotatingFile: %v", err)
}
// Push size right up to the cap without writing megabytes of
// fixture data -- white-box, same package -- so the marker write
// below is guaranteed to be the one that crosses maxSize and
// triggers rotate.
marker := []byte("MARKER-LINE\n")
w.size = w.maxSize - 1
// Simulate the reopen failing (disk full, permission change) while
// the rename that frees the old name still succeeds -- the scenario
// a chmod on the directory can't isolate, since that would also
// block the rename.
prevOpenFile := openFile
openFile = func(name string, flag int, perm os.FileMode) (*os.File, error) {
return nil, fmt.Errorf("simulated reopen failure")
}
t.Cleanup(func() { openFile = prevOpenFile })
if _, err := w.Write(marker); err != nil {
t.Fatalf("Write after a failed reopen returned an error (line lost): %v", err)
}
// A second write after the same failure must also land -- this is
// what distinguishes "lost one line during rotation" from "the sink
// is now permanently broken".
marker2 := []byte("MARKER-LINE-2\n")
if _, err := w.Write(marker2); err != nil {
t.Fatalf("second write after a failed reopen returned an error: %v", err)
}
openFile = prevOpenFile
if err := w.Close(); err != nil {
t.Fatal(err)
}
// The live file was never successfully recreated (reopen kept
// failing on every write), so each write's rotate attempt renamed
// the same still-open descriptor further down the generation chain
// -- the exact filename it lands under is incidental. What matters
// is that neither marker is gone: scan the whole directory.
var all strings.Builder
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
b, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
t.Fatal(err)
}
all.Write(b)
}
if !strings.Contains(all.String(), "MARKER-LINE\n") {
t.Error("MARKER-LINE missing after a failed reopen")
}
if !strings.Contains(all.String(), "MARKER-LINE-2\n") {
t.Error("MARKER-LINE-2 missing -- the sink stayed broken after the transient failure")
}
}
func TestRotationDefaults(t *testing.T) {
path := filepath.Join(t.TempDir(), "archied.log")
w, err := newRotatingFile(path, 0, 0)
if err != nil {
t.Fatalf("newRotatingFile: %v", err)
}
t.Cleanup(func() { _ = w.Close() })
if w.maxSize != int64(DefaultMaxSizeMB)*1024*1024 {
t.Errorf("maxSize = %d, want the %dMB default", w.maxSize, DefaultMaxSizeMB)
}
if w.keep != DefaultKeep {
t.Errorf("keep = %d, want the default %d", w.keep, DefaultKeep)
}
}
-693
View File
@@ -1,693 +0,0 @@
package logging
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
func writeLog(t *testing.T, lines ...string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "archied.log")
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
return path
}
func line(level, msg string, extra ...string) string {
var s strings.Builder
fmt.Fprintf(&s, `{"time":"2026-08-04T01:00:00Z","level":%q,"msg":%q`, level, msg)
for _, e := range extra {
s.WriteString("," + e)
}
return s.String() + "}"
}
func TestTailStageFilter(t *testing.T) {
path := writeLog(
t,
line("INFO", "stage starting", `"stage":"prepare"`),
line("INFO", "stage finished", `"stage":"prepare"`, `"component":"daemon"`),
line("INFO", "stage starting", `"stage":"implement"`),
line("INFO", "agent turn", `"component":"daemon"`),
line("INFO", "stage starting", `"stage":"PREPARE"`),
)
tests := []struct {
name string
query Query
want []string
}{
{"stage selects only that stage's entries", Query{Stage: "prepare"}, []string{"stage starting", "stage finished", "stage starting"}},
{"stage match is case-insensitive", Query{Stage: "Implement"}, []string{"stage starting"}},
{"an entry with no stage never matches", Query{Stage: "prepare"}, []string{"stage starting", "stage finished", "stage starting"}},
{"stage combines with level", Query{Stage: "prepare", Levels: []string{"INFO"}}, []string{"stage starting", "stage finished", "stage starting"}},
{"stage combines with component", Query{Stage: "prepare", Component: "daemon"}, []string{"stage finished"}},
{"a stage nothing carries is empty, not an error", Query{Stage: "nonexistent"}, nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
res, err := Tail(path, tc.query)
if err != nil {
t.Fatalf("Tail: %v", err)
}
got := make([]string, 0, len(res.Entries))
for _, e := range res.Entries {
got = append(got, e.Message)
}
if len(got) != len(tc.want) {
t.Fatalf("got %v, want %v", got, tc.want)
}
for i := range got {
if got[i] != tc.want[i] {
t.Errorf("got %v, want %v", got, tc.want)
break
}
}
})
}
}
func TestTailFilters(t *testing.T) {
path := writeLog(
t,
line("INFO", "started", `"component":"daemon"`),
line("WARN", "telegram rate limited", `"component":"gateway-telegram"`),
line("ERROR", "pull failed", `"component":"container"`),
line("DEBUG", "noisy detail", `"component":"daemon"`),
)
tests := []struct {
name string
query Query
want []string
}{
{"no filter returns everything", Query{}, []string{"started", "telegram rate limited", "pull failed", "noisy detail"}},
{"single level", Query{Levels: []string{"ERROR"}}, []string{"pull failed"}},
{"several levels", Query{Levels: []string{"WARN", "ERROR"}}, []string{"telegram rate limited", "pull failed"}},
{"level match is case-insensitive", Query{Levels: []string{"error"}}, []string{"pull failed"}},
{"component", Query{Component: "daemon"}, []string{"started", "noisy detail"}},
{"text matches the message", Query{Contains: "rate"}, []string{"telegram rate limited"}},
{"text matches a field value", Query{Contains: "container"}, []string{"pull failed"}},
{"text is case-insensitive", Query{Contains: "TELEGRAM"}, []string{"telegram rate limited"}},
{"filters combine", Query{Levels: []string{"DEBUG"}, Component: "daemon"}, []string{"noisy detail"}},
{"no match is empty, not an error", Query{Contains: "nothing here"}, nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
res, err := Tail(path, tc.query)
if err != nil {
t.Fatalf("Tail: %v", err)
}
got := make([]string, 0, len(res.Entries))
for _, e := range res.Entries {
got = append(got, e.Message)
}
if len(got) != len(tc.want) {
t.Fatalf("got %v, want %v", got, tc.want)
}
for i := range got {
if got[i] != tc.want[i] {
t.Errorf("got %v, want %v", got, tc.want)
break
}
}
})
}
}
// TestTailOrderIsOldestFirst pins the ordering the UI depends on: history is
// rendered then live lines are appended, so history must not arrive reversed.
func TestTailOrderIsOldestFirst(t *testing.T) {
path := writeLog(t, line("INFO", "first"), line("INFO", "second"), line("INFO", "third"))
res, err := Tail(path, Query{})
if err != nil {
t.Fatal(err)
}
want := []string{"first", "second", "third"}
for i, e := range res.Entries {
if e.Message != want[i] {
t.Fatalf("entry %d = %q, want %q", i, e.Message, want[i])
}
}
}
// TestTailKeepsNewestWhenLimited pins that the limit drops the OLDEST entries.
// Truncating from the other end would show a stale window and hide whatever
// just went wrong, which is the reason anyone opens this view.
func TestTailKeepsNewestWhenLimited(t *testing.T) {
lines := make([]string, 0, 10)
for i := range 10 {
lines = append(lines, line("INFO", fmt.Sprintf("m%d", i)))
}
res, err := Tail(writeLog(t, lines...), Query{Limit: 3})
if err != nil {
t.Fatal(err)
}
if len(res.Entries) != 3 {
t.Fatalf("got %d entries, want 3", len(res.Entries))
}
for i, want := range []string{"m7", "m8", "m9"} {
if res.Entries[i].Message != want {
t.Errorf("entry %d = %q, want %q", i, res.Entries[i].Message, want)
}
}
if !res.Truncated {
t.Error("Truncated = false, want true when older entries were dropped")
}
}
func TestTailLimitIsClamped(t *testing.T) {
res, err := Tail(writeLog(t, line("INFO", "one")), Query{Limit: MaxTailLines * 10})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(res.Entries) != 1 {
t.Errorf("got %d entries, want 1", len(res.Entries))
}
}
// TestTailTolerates pins that non-JSON lines and a missing file are survivable:
// a log may carry subprocess output, and file logging is optional.
func TestTailTolerates(t *testing.T) {
t.Run("non-JSON lines are skipped", func(t *testing.T) {
path := writeLog(t, "not json at all", line("INFO", "real entry"), "}{")
res, err := Tail(path, Query{})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(res.Entries) != 1 || res.Entries[0].Message != "real entry" {
t.Errorf("got %+v, want just the parseable entry", res.Entries)
}
})
t.Run("missing file is empty, not an error", func(t *testing.T) {
res, err := Tail(filepath.Join(t.TempDir(), "absent.log"), Query{})
if err != nil {
t.Errorf("Tail on a missing file: %v, want nil", err)
}
if len(res.Entries) != 0 {
t.Errorf("got %d entries, want 0", len(res.Entries))
}
})
t.Run("empty path is empty, not an error", func(t *testing.T) {
if _, err := Tail("", Query{}); err != nil {
t.Errorf("Tail(\"\"): %v, want nil", err)
}
})
}
func TestDecodeKeepsStructuredFields(t *testing.T) {
path := writeLog(t, line("ERROR", "pull failed", `"component":"container"`, `"err":"unauthorized"`))
res, err := Tail(path, Query{})
if err != nil {
t.Fatal(err)
}
e := res.Entries[0]
if e.Level != "ERROR" || e.Message != "pull failed" {
t.Fatalf("got level=%q msg=%q", e.Level, e.Message)
}
if e.Fields["component"] != "container" || e.Fields["err"] != "unauthorized" {
t.Errorf("fields = %v, want component and err preserved", e.Fields)
}
if e.Time.IsZero() {
t.Error("Time is zero; the timestamp was not parsed")
}
}
// TestPageMatchesTailWhenLimitFitsWholeFile pins the first-cut promise of
// Page: with cursor=0 and a Limit large enough to hold every match, the
// page is identical to what Tail would have returned.
func TestPageMatchesTailWhenLimitFitsWholeFile(t *testing.T) {
lines := []string{
line("INFO", "started", `"component":"daemon"`),
line("WARN", "rate limit", `"component":"telegram"`),
line("ERROR", "pull failed", `"component":"container"`),
line("DEBUG", "noisy", `"component":"daemon"`),
}
path := writeLog(t, lines...)
tail, err := Tail(path, Query{})
if err != nil {
t.Fatal(err)
}
page, err := Page(path, Query{}, 0)
if err != nil {
t.Fatal(err)
}
if page.MoreAvailable || page.Truncated {
t.Errorf("page flags = (more=%v, trunc=%v), want both false", page.MoreAvailable, page.Truncated)
}
if len(page.Entries) != len(tail.Entries) {
t.Fatalf("page has %d entries, tail has %d", len(page.Entries), len(tail.Entries))
}
for i := range page.Entries {
if page.Entries[i].Message != tail.Entries[i].Message {
t.Errorf("entry %d: page=%q tail=%q", i, page.Entries[i].Message, tail.Entries[i].Message)
}
}
}
// TestPageWalksWholeFileWithoutGapsOrDuplication is the issue's acceptance
// criterion #5: repeated paged calls against a log LARGER THAN THE CAP must
// retrieve every entry exactly once.
//
// total deliberately exceeds MaxTailLines (2000), because that is the cap the
// criterion is about: a single call can never return more than MaxTailLines
// entries, so a log below that size would be satisfied by one call and would
// not exercise paging at all. It stays well under maxScanBytes (8 MiB) so that
// EVERY entry is genuinely reachable -- see TestPageAcrossSizeCapSeek for the
// oversized case, where the scan window makes the oldest entries unreachable
// by design.
func TestPageWalksWholeFileWithoutGapsOrDuplication(t *testing.T) {
const total = MaxTailLines + 500
const pageSize = 700
lines := make([]string, total)
for i := range lines {
lines[i] = line("INFO", fmt.Sprintf("entry-%05d", i))
}
path := writeLog(t, lines...)
var got []string
cursor := int64(0)
for call := range 100 {
page, err := Page(path, Query{Limit: pageSize}, cursor)
if err != nil {
t.Fatalf("call %d: %v", call, err)
}
for _, e := range page.Entries {
got = append(got, e.Message)
}
if !page.MoreAvailable {
if page.Cursor < cursor {
t.Fatalf("call %d: cursor went backwards: prev=%d new=%d", call, cursor, page.Cursor)
}
break
}
if page.Cursor <= cursor {
t.Fatalf("call %d: cursor did not advance: prev=%d new=%d", call, cursor, page.Cursor)
}
cursor = page.Cursor
}
if len(got) != total {
t.Fatalf("walked %d entries, want %d (first few: %v)", len(got), total, got[:min(len(got), 5)])
}
seen := map[string]int{}
for _, m := range got {
seen[m]++
}
if len(seen) != total {
t.Errorf("got %d distinct messages, want %d (duplicates: %v)", len(seen), total, dupCount(seen))
}
}
// dupCount returns the messages seen more than once, for test diagnostics.
func dupCount(seen map[string]int) []string {
out := []string{}
for k, v := range seen {
if v > 1 {
out = append(out, fmt.Sprintf("%s×%d", k, v))
}
}
return out
}
// appendInt formats n in decimal into dst and returns the extended
// slice. Used by TestPageAcrossSizeCapSeek so every line is exactly
// the bytes the JSON encoder produced -- a fixed byte boundary would
// truncate some lines mid-string and the JSON decoder would drop them.
func appendInt(dst []byte, n int) []byte {
if n == 0 {
return append(dst, '0')
}
var digits [20]byte
i := len(digits)
for n > 0 {
i--
digits[i] = byte('0' + n%10)
n /= 10
}
return append(dst, digits[i:]...)
}
// TestPageCursorSurvivesNoOpAdvances: a page that returns no entries
// must still produce a Cursor equal to the input -- otherwise the caller
// cannot distinguish "no matches ahead" from "I lost my place".
func TestPageCursorAdvancesWithFile(t *testing.T) {
path := writeLog(
t,
line("INFO", "first"),
line("INFO", "second"),
line("INFO", "third"),
)
page, err := Page(path, Query{Limit: 10}, 0)
if err != nil {
t.Fatal(err)
}
if page.MoreAvailable {
t.Errorf("MoreAvailable = true with 3 lines and Limit 10, want false")
}
if page.Cursor <= 0 {
t.Errorf("Cursor = %d, want > 0 (the file is non-empty)", page.Cursor)
}
}
// TestPageCursorPastEOFIsEmpty confirms the rotation-shrank case: a cursor
// past the current file size returns no entries and no MoreAvailable.
func TestPageCursorPastEOFIsEmpty(t *testing.T) {
path := writeLog(t, line("INFO", "only entry"))
page, err := Page(path, Query{}, 1<<20)
if err != nil {
t.Fatal(err)
}
if len(page.Entries) != 0 || page.MoreAvailable {
t.Errorf("cursor-past-EOF page = %+v, want empty + no more", page)
}
}
// TestQuerySinceUntilFilters checks the time-range filter on the new
// fields. Times are read from each entry's `time` field; the helper
// `line` writes a fixed timestamp, so the test pins the inclusive
// boundary behaviour directly.
func TestQuerySinceUntilFilters(t *testing.T) {
// Three entries: two seconds apart on the same minute.
path := writeLog(
t,
`{"time":"2026-08-04T01:00:00Z","level":"INFO","msg":"early"}`,
`{"time":"2026-08-04T01:00:02Z","level":"INFO","msg":"middle"}`,
`{"time":"2026-08-04T01:00:04Z","level":"INFO","msg":"late"}`,
)
since, _ := time.Parse(time.RFC3339Nano, "2026-08-04T01:00:02Z")
until, _ := time.Parse(time.RFC3339Nano, "2026-08-04T01:00:02Z")
page, err := Page(path, Query{Since: since, Until: until, Limit: 10}, 0)
if err != nil {
t.Fatal(err)
}
if len(page.Entries) != 1 || page.Entries[0].Message != "middle" {
got := make([]string, len(page.Entries))
for i, e := range page.Entries {
got[i] = e.Message
}
t.Fatalf("Since==Until page = %v, want [middle] (inclusive on both bounds)", got)
}
// Loose bounds: only the late entry passes.
page, err = Page(path, Query{Since: since.Add(2 * time.Second), Limit: 10}, 0)
if err != nil {
t.Fatal(err)
}
if len(page.Entries) != 1 || page.Entries[0].Message != "late" {
got := make([]string, len(page.Entries))
for i, e := range page.Entries {
got[i] = e.Message
}
t.Fatalf("Since=since+2s page = %v, want [late]", got)
}
// Loose bounds: only the early entry passes (Until is strictly less
// than middle so middle is excluded).
page, err = Page(path, Query{Until: since.Add(-time.Nanosecond), Limit: 10}, 0)
if err != nil {
t.Fatal(err)
}
if len(page.Entries) != 1 || page.Entries[0].Message != "early" {
got := make([]string, len(page.Entries))
for i, e := range page.Entries {
got[i] = e.Message
}
t.Fatalf("Until=since-1ns page = %v, want [early]", got)
}
}
// TestTimeBoundsExcludeUnparseableTimestamps pins the symmetry between
// Since and Until for a record whose "time" did not parse. Such a record
// cannot be placed in a range, so BOTH bounds must exclude it -- the
// naive comparison keeps it under Until (zero.After(x) is false) while
// dropping it under Since (zero.Before(x) is true).
func TestTimeBoundsExcludeUnparseableTimestamps(t *testing.T) {
bound, err := time.Parse(time.RFC3339Nano, "2026-08-04T01:00:02Z")
if err != nil {
t.Fatal(err)
}
path := writeLog(
t,
`{"level":"INFO","msg":"no-time-field"}`,
`{"time":"not a timestamp","level":"INFO","msg":"unparseable-time"}`,
`{"time":"2026-08-04T01:00:02Z","level":"INFO","msg":"has-time"}`,
)
for _, tc := range []struct {
name string
query Query
}{
{"since only", Query{Since: bound, Limit: 10}},
{"until only", Query{Until: bound, Limit: 10}},
{"both bounds", Query{Since: bound, Until: bound, Limit: 10}},
} {
t.Run(tc.name, func(t *testing.T) {
page, err := Page(path, tc.query, 0)
if err != nil {
t.Fatal(err)
}
got := make([]string, len(page.Entries))
for i, e := range page.Entries {
got[i] = e.Message
}
if len(got) != 1 || got[0] != "has-time" {
t.Fatalf("entries = %v, want only [has-time]: a record with no usable "+
"timestamp must not satisfy a time-bounded query", got)
}
})
}
// Without any bound, all three are returned -- the exclusion is a
// property of time-bounded queries, not of the records themselves.
page, err := Page(path, Query{Limit: 10}, 0)
if err != nil {
t.Fatal(err)
}
if len(page.Entries) != 3 {
t.Errorf("unbounded query returned %d entries, want all 3", len(page.Entries))
}
}
// TestPageRespectsFilter ensures paging with a level filter walks only
// matching entries and the MoreAvailable/Cursor fields account for
// every line in the scan window, not just the matches.
func TestPageRespectsFilter(t *testing.T) {
lines := []string{
line("INFO", "i1"),
line("ERROR", "e1"),
line("INFO", "i2"),
line("ERROR", "e2"),
line("INFO", "i3"),
line("ERROR", "e3"),
}
path := writeLog(t, lines...)
page, err := Page(path, Query{Levels: []string{"ERROR"}, Limit: 2}, 0)
if err != nil {
t.Fatal(err)
}
if len(page.Entries) != 2 || page.Entries[0].Message != "e1" || page.Entries[1].Message != "e2" {
t.Fatalf("first page = %+v, want [e1, e2]", page.Entries)
}
if !page.MoreAvailable {
t.Errorf("MoreAvailable = false, want true (one match remains)")
}
page2, err := Page(path, Query{Levels: []string{"ERROR"}, Limit: 2}, page.Cursor)
if err != nil {
t.Fatal(err)
}
if len(page2.Entries) != 1 || page2.Entries[0].Message != "e3" {
t.Fatalf("second page = %+v, want [e3]", page2.Entries)
}
if page2.MoreAvailable {
t.Errorf("MoreAvailable = true on final page, want false")
}
}
// TestPageCursorAtEOFWithTrailingNonMatchingLines pins the fix for the
// doc-vs-code contradiction the adversarial pass found: when the walk
// runs to EOF but the final lines fail the filter, Cursor must equal the
// file size (the walk's own end offset), NOT the end of the last
// matching line. Returning the latter would leave the trailing bytes
// unread, and a caller that follows PageResult's documented "cursor ==
// file size means done" rule would loop.
func TestPageCursorAtEOFWithTrailingNonMatchingLines(t *testing.T) {
path := writeLog(
t,
line("ERROR", "e1"),
line("INFO", "i1"),
line("INFO", "i2"),
)
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
page, err := Page(path, Query{Levels: []string{"ERROR"}, Limit: 100}, 0)
if err != nil {
t.Fatal(err)
}
if len(page.Entries) != 1 || page.Entries[0].Message != "e1" {
t.Fatalf("entries = %+v, want just [e1]", page.Entries)
}
if page.MoreAvailable {
t.Errorf("MoreAvailable = true, want false (only one ERROR line)")
}
if page.Cursor != info.Size() {
t.Errorf("Cursor = %d, want file size %d: the walk ran to EOF past the "+
"trailing INFO lines, so the cursor must sit at end-of-file, not at "+
"the end of the last match", page.Cursor, info.Size())
}
}
// TestPageAcrossSizeCapSeek is the regression test for the readLines
// refactor: a file larger than maxScanBytes must trigger the seek to
// windowStart, and paged reads across that boundary must visit every
// line without duplicates or gaps. The earlier "no-gap" test used a
// 3 KB file that never crossed maxScanBytes (8 MiB), so the seek
// branch was uncovered.
//
// The test writes a file whose size is well above maxScanBytes and
// pages through it in chunks of MaxTailLines, asserting that the union
// of returned pages contains every line exactly once. It also pins
// the Truncated flag: the first page should report Truncated=true.
func TestPageAcrossSizeCapSeek(t *testing.T) {
// 12 MiB of JSONL, fixed-width lines that decode unambiguously.
// We do NOT truncate the line at a fixed byte boundary, because a
// truncated JSON object silently fails to decode and would
// invalidate the no-gap invariant. Instead, every line is the
// same fixed size, computed from a per-line message id that
// always fits.
const totalBytes = 12 << 20
path := filepath.Join(t.TempDir(), "big.log")
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = f.Close() })
var total int
buf := make([]byte, 0, 128)
for written := 0; written < totalBytes; {
buf = buf[:0]
buf = append(buf, []byte(`{"time":"2026-08-04T01:00:00Z","level":"INFO","msg":"x`)...)
buf = appendInt(buf, total)
buf = append(buf, '"', '}', '\n')
if _, err := f.Write(buf); err != nil {
t.Fatal(err)
}
written += len(buf)
total++
}
// Walk the whole scan window by paging.
var ids []int
seen := map[int]struct{}{}
cursor := int64(0)
for call := range 500 {
page, err := Page(path, Query{Limit: MaxTailLines}, cursor)
if err != nil {
t.Fatalf("call %d: %v", call, err)
}
if call == 0 && !page.Truncated {
t.Fatal("first page Truncated = false, want true: the file exceeds maxScanBytes " +
"so the oldest entries were never examined, and the caller must be told")
}
for _, e := range page.Entries {
id, err := strconv.Atoi(strings.TrimPrefix(e.Message, "x"))
if err != nil {
t.Fatalf("call %d: unparseable message %q -- a line was split mid-record", call, e.Message)
}
if _, dup := seen[id]; dup {
t.Fatalf("call %d: duplicate entry x%d", call, id)
}
seen[id] = struct{}{}
ids = append(ids, id)
}
if !page.MoreAvailable {
break
}
if page.Cursor <= cursor {
t.Fatalf("call %d: cursor did not advance: prev=%d new=%d", call, cursor, page.Cursor)
}
cursor = page.Cursor
}
// The contract is NOT "every line in the file" -- maxScanBytes caps
// the window, and for this deliberately-oversized file the oldest
// entries are out of reach by design (that is what Truncated says).
// The contract IS: everything inside the window, in order, exactly
// once, ending at the file's final entry.
if len(ids) == 0 {
t.Fatal("paged zero entries from a 12 MiB log")
}
for i := 1; i < len(ids); i++ {
if ids[i] != ids[i-1]+1 {
t.Fatalf("gap in paged walk at index %d: x%d followed by x%d", i, ids[i-1], ids[i])
}
}
if last := ids[len(ids)-1]; last != total-1 {
t.Errorf("walk ended at x%d, want the file's final entry x%d", last, total-1)
}
// Sanity-check the window arithmetic itself: the reachable count is
// determined by where maxScanBytes lands, so assert the walk covered
// a large majority of the window rather than a hardcoded count that
// would rot the moment the line format changes.
if len(ids) < 100_000 {
t.Errorf("paged only %d entries out of a %d-entry file; the 8 MiB "+
"scan window should reach far more than that", len(ids), total)
}
}
// TestPagePreservesTruncatedOnGiantLine pins the second regression the
// refactor fixes: a file that exceeds maxScanBytes with no '\\n' in the
// scan window still reports Truncated, because older matching entries
// exist beyond what was examined.
func TestPagePreservesTruncatedOnGiantLine(t *testing.T) {
path := filepath.Join(t.TempDir(), "giant.log")
// One JSON object spanning 10 MiB -- no terminator at all within
// the 8 MiB scan window.
body := []byte(`{"time":"2026-08-04T01:00:00Z","level":"INFO","msg":"x","pad":`)
body = append(body, bytes.Repeat([]byte("a"), 10<<20)...)
body = append(body, '}')
if err := os.WriteFile(path, body, 0o600); err != nil {
t.Fatal(err)
}
page, err := Page(path, Query{}, 0)
if err != nil {
t.Fatal(err)
}
if !page.Truncated {
t.Errorf("Truncated = false on giant-line file > maxScanBytes, want true")
}
}
func TestComponents(t *testing.T) {
path := writeLog(
t,
line("INFO", "a", `"component":"daemon"`),
line("INFO", "b", `"component":"gateway-telegram"`),
line("INFO", "c", `"component":"daemon"`),
line("INFO", "d"),
)
got, err := Components(path)
if err != nil {
t.Fatal(err)
}
want := []string{"daemon", "gateway-telegram"}
if len(got) != len(want) {
t.Fatalf("got %v, want %v", got, want)
}
for i := range got {
if got[i] != want[i] {
t.Errorf("got %v, want %v (sorted, deduplicated)", got, want)
}
}
}
-315
View File
@@ -1,315 +0,0 @@
package logging
import (
"fmt"
"os"
"sync"
"testing"
"time"
)
func TestTaskRegistryOpenWriteCloseRoundTripsThroughTail(t *testing.T) {
baseDir := t.TempDir()
feed := NewFeed(10)
reg := NewTaskRegistry(baseDir, feed, TaskSinkOptions{})
if err := reg.Open(42, 1); err != nil {
t.Fatalf("Open: %v", err)
}
if ok := reg.Write(t.Context(), 42, Entry{Level: "WARN", Message: "gate failed", Fields: map[string]any{"component": "gate"}}); !ok {
t.Fatal("Write() = false, want true for an open task")
}
if err := reg.Close(42); err != nil {
t.Fatalf("Close: %v", err)
}
result, err := Tail(TaskLogPath(baseDir, 42, 1), Query{})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(result.Entries) != 1 {
t.Fatalf("got %d entries, want 1: %+v", len(result.Entries), result.Entries)
}
entry := result.Entries[0]
if entry.Message != "gate failed" || entry.Level != "WARN" || entry.Fields["component"] != "gate" {
t.Errorf("entry = %+v, want message=gate failed level=WARN component=gate", entry)
}
}
// TestTaskRegistryWriteKeepsEachEntriesOwnEventTime guards the point of a
// task log: a record shipped from the container must be filed under the time
// the event happened, not the time the daemon happened to receive it. A run's
// iterations spread over minutes must be interleaved on disk the way they
// happened; collapsing them onto one receipt burst makes a task's timing
// unrecoverable (which stage ran when, how long an iteration took, whether a
// stage stalled). The daemon's receipt time is kept too, but separately -- in
// the record's own received_at field -- so "the event's time" and "when this
// process saw it" cannot be confused for one another.
func TestTaskRegistryWriteKeepsEachEntriesOwnEventTime(t *testing.T) {
baseDir := t.TempDir()
feed := NewFeed(10)
reg := NewTaskRegistry(baseDir, feed, TaskSinkOptions{})
if err := reg.Open(11, 1); err != nil {
t.Fatal(err)
}
// Three iterations, minutes apart -- the shape a real run has.
happened := []time.Time{
time.Date(2026, 10, 1, 9, 30, 0, 123456789, time.UTC),
time.Date(2026, 10, 1, 9, 33, 41, 987654321, time.UTC),
time.Date(2026, 10, 1, 9, 37, 12, 500000000, time.UTC),
}
for i, at := range happened {
if ok := reg.Write(t.Context(), 11, Entry{Time: at, Level: "INFO", Message: fmt.Sprintf("iteration %d", i+1)}); !ok {
t.Fatalf("Write() = false for an open task, iteration %d", i)
}
}
if err := reg.Close(11); err != nil {
t.Fatal(err)
}
result, err := Tail(TaskLogPath(baseDir, 11, 1), Query{})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(result.Entries) != len(happened) {
t.Fatalf("got %d entries, want %d", len(result.Entries), len(happened))
}
for i, want := range happened {
entry := result.Entries[i]
if !entry.Time.Equal(want) {
t.Errorf("entry %d time = %s, want the iteration's own time %s", i, entry.Time, want)
}
if _, ok := entry.Fields[receivedAtField]; !ok {
t.Errorf("entry %d fields = %+v, want receipt time preserved separately as received_at", i, entry.Fields)
}
}
// The live dashboard feed must carry the event's time too, not the
// mirror's own write time.
snapshot := feed.Snapshot()
if len(snapshot) != len(happened) {
t.Fatalf("feed has %d entries, want %d", len(snapshot), len(happened))
}
for i, want := range happened {
if !snapshot[i].Time.Equal(want) {
t.Errorf("feed entry %d time = %s, want %s", i, snapshot[i].Time, want)
}
}
}
// TestTaskRegistryWriteStampsAnEntryWithNoEventTime pins the fallback: a
// locally-produced entry that carries no time of its own (recordPark does set
// one, but the field is optional) is stamped now, so a log line is never
// filed under the zero time and never sinks to the bottom of a time-ordered
// view.
func TestTaskRegistryWriteStampsAnEntryWithNoEventTime(t *testing.T) {
baseDir := t.TempDir()
reg := NewTaskRegistry(baseDir, NewFeed(10), TaskSinkOptions{})
if err := reg.Open(12, 1); err != nil {
t.Fatal(err)
}
before := time.Now()
if ok := reg.Write(t.Context(), 12, Entry{Level: "INFO", Message: "no time of its own"}); !ok {
t.Fatal("Write() = false for an open task")
}
after := time.Now()
if err := reg.Close(12); err != nil {
t.Fatal(err)
}
result, err := Tail(TaskLogPath(baseDir, 12, 1), Query{})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(result.Entries) != 1 {
t.Fatalf("got %d entries, want 1", len(result.Entries))
}
got := result.Entries[0].Time
if got.Before(before) || got.After(after) {
t.Errorf("entry time = %s, want a receipt-time stamp between %s and %s", got, before, after)
}
}
// TestTaskRegistryWriteMirrorsToTheDashboardFeed guards the other half of
// the point of routing writes through a slog.Logger built on FeedHandler
// instead of writing the file directly: a remotely-shipped entry must show
// up live on the dashboard the same way a locally-written one does.
func TestTaskRegistryWriteMirrorsToTheDashboardFeed(t *testing.T) {
baseDir := t.TempDir()
feed := NewFeed(10)
reg := NewTaskRegistry(baseDir, feed, TaskSinkOptions{})
if err := reg.Open(1, 1); err != nil {
t.Fatalf("Open: %v", err)
}
reg.Write(t.Context(), 1, Entry{Level: "INFO", Message: "hello"})
if err := reg.Close(1); err != nil {
t.Fatal(err)
}
snapshot := feed.Snapshot()
if len(snapshot) != 1 || snapshot[0].Message != "hello" {
t.Fatalf("feed snapshot = %+v, want one entry with message %q", snapshot, "hello")
}
}
// TestTaskRegistryWriteWithoutOpenIsANoOp pins that a system-log message for
// a task with no currently-open sink -- a late or duplicate delivery after
// the task finished, or one this daemon instance never dispatched -- is
// expected, not exceptional: no panic, no error return path to check.
func TestTaskRegistryWriteWithoutOpenIsANoOp(t *testing.T) {
reg := NewTaskRegistry(t.TempDir(), NewFeed(10), TaskSinkOptions{})
if ok := reg.Write(t.Context(), 999, Entry{Message: "orphan"}); ok {
t.Error("Write() = true for a task with no open sink, want false")
}
}
// TestTaskRegistryOpenReplacesThePreviousAttempt guards a retry: the same
// task ID reopens at a higher Attempt, and writes after that must land in
// the new attempt's file, not silently keep flowing to the old one under
// its name.
func TestTaskRegistryOpenReplacesThePreviousAttempt(t *testing.T) {
baseDir := t.TempDir()
reg := NewTaskRegistry(baseDir, NewFeed(10), TaskSinkOptions{})
if err := reg.Open(7, 1); err != nil {
t.Fatalf("Open attempt 1: %v", err)
}
reg.Write(t.Context(), 7, Entry{Message: "attempt one"})
if err := reg.Open(7, 2); err != nil {
t.Fatalf("Open attempt 2: %v", err)
}
reg.Write(t.Context(), 7, Entry{Message: "attempt two"})
if err := reg.Close(7); err != nil {
t.Fatal(err)
}
attemptOne, err := Tail(TaskLogPath(baseDir, 7, 1), Query{})
if err != nil {
t.Fatal(err)
}
if len(attemptOne.Entries) != 1 || attemptOne.Entries[0].Message != "attempt one" {
t.Errorf("attempt 1 file = %+v, want exactly [attempt one]", attemptOne.Entries)
}
attemptTwo, err := Tail(TaskLogPath(baseDir, 7, 2), Query{})
if err != nil {
t.Fatal(err)
}
if len(attemptTwo.Entries) != 1 || attemptTwo.Entries[0].Message != "attempt two" {
t.Errorf("attempt 2 file = %+v, want exactly [attempt two]", attemptTwo.Entries)
}
}
func TestTaskRegistryCloseWithoutOpenIsSafe(t *testing.T) {
reg := NewTaskRegistry(t.TempDir(), NewFeed(10), TaskSinkOptions{})
if err := reg.Close(123); err != nil {
t.Errorf("Close() on a never-opened task = %v, want nil", err)
}
}
func TestTaskRegistryRemoveDeletesTheTaskDirectory(t *testing.T) {
baseDir := t.TempDir()
reg := NewTaskRegistry(baseDir, NewFeed(10), TaskSinkOptions{})
if err := reg.Open(5, 1); err != nil {
t.Fatal(err)
}
reg.Write(t.Context(), 5, Entry{Message: "x"})
if err := reg.Close(5); err != nil {
t.Fatal(err)
}
dir := TaskLogDir(baseDir, 5)
if _, err := os.Stat(dir); err != nil {
t.Fatalf("task dir missing before Remove: %v", err)
}
if err := reg.Remove(5); err != nil {
t.Fatalf("Remove: %v", err)
}
if _, err := os.Stat(dir); !os.IsNotExist(err) {
t.Errorf("task dir still present after Remove: err=%v", err)
}
}
func TestTaskRegistryRemoveOnUnopenedTaskIsNotAnError(t *testing.T) {
reg := NewTaskRegistry(t.TempDir(), NewFeed(10), TaskSinkOptions{})
if err := reg.Remove(404); err != nil {
t.Errorf("Remove() on a task with no directory = %v, want nil", err)
}
}
// TestTaskRegistryNilReceiverIsSafe mirrors Feed's own nil-safety: a
// *TaskRegistry is wired by composition and left nil when task logging
// isn't configured, the same "optional, nil means disabled" convention
// every other Daemon field follows. Every method must tolerate that without
// the caller checking first.
func TestTaskRegistryNilReceiverIsSafe(t *testing.T) {
var reg *TaskRegistry
if err := reg.Open(1, 1); err != nil {
t.Errorf("Open() on nil registry = %v, want nil", err)
}
if ok := reg.Write(t.Context(), 1, Entry{Message: "x"}); ok {
t.Error("Write() on nil registry = true, want false")
}
if err := reg.Close(1); err != nil {
t.Errorf("Close() on nil registry = %v, want nil", err)
}
if err := reg.Remove(1); err != nil {
t.Errorf("Remove() on nil registry = %v, want nil", err)
}
}
// TestTaskRegistryConcurrentTasksDoNotRace exercises the registry the way
// the daemon actually will: many tasks' Open/Write/Close interleaved from
// different goroutines (task dispatch vs. the NATS subscription handler),
// TestTaskRegistryPathMirrorsTaskLogPath guards the reason a query surface
// (the API handler, the chat tool) can hold only a *TaskRegistry rather than
// also needing baseDir threaded through separately: Path must compute
// exactly what TaskLogPath would from the same baseDir.
func TestTaskRegistryPathMirrorsTaskLogPath(t *testing.T) {
baseDir := t.TempDir()
reg := NewTaskRegistry(baseDir, nil, TaskSinkOptions{})
got := reg.Path(42, 3)
want := TaskLogPath(baseDir, 42, 3)
if got != want {
t.Errorf("Path(42, 3) = %q, want %q", got, want)
}
}
// TestNilTaskRegistryPathIsEmpty guards the "nil means task logging is not
// configured" convention every other TaskRegistry method already follows --
// a query surface must be able to call Path on a possibly-nil registry
// without a separate nil check.
func TestNilTaskRegistryPathIsEmpty(t *testing.T) {
var reg *TaskRegistry
if got := reg.Path(42, 1); got != "" {
t.Errorf("Path() on nil registry = %q, want empty", got)
}
}
// none sharing a task ID. Run with -race.
func TestTaskRegistryConcurrentTasksDoNotRace(t *testing.T) {
reg := NewTaskRegistry(t.TempDir(), NewFeed(100), TaskSinkOptions{})
var wg sync.WaitGroup
for i := int64(1); i <= 20; i++ {
wg.Add(1)
go func(taskID int64) {
defer wg.Done()
if err := reg.Open(taskID, 1); err != nil {
t.Errorf("Open(%d): %v", taskID, err)
return
}
reg.Write(t.Context(), taskID, Entry{Message: "line"})
if err := reg.Close(taskID); err != nil {
t.Errorf("Close(%d): %v", taskID, err)
}
}(i)
}
wg.Wait()
}
-190
View File
@@ -1,190 +0,0 @@
package logging
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func TestTaskLogPath(t *testing.T) {
tests := []struct {
name string
baseDir string
taskID int64
attempt int
want string
}{
{"first attempt", "/var/log/archie/tasks", 42, 1, "/var/log/archie/tasks/42/attempt-1.jsonl"},
{"later attempt", "/var/log/archie/tasks", 42, 3, "/var/log/archie/tasks/42/attempt-3.jsonl"},
{"different task", "/var/log/archie/tasks", 7, 1, "/var/log/archie/tasks/7/attempt-1.jsonl"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := TaskLogPath(tt.baseDir, tt.taskID, tt.attempt)
want := filepath.FromSlash(tt.want)
if got != want {
t.Errorf("TaskLogPath(%q, %d, %d) = %q, want %q", tt.baseDir, tt.taskID, tt.attempt, got, want)
}
})
}
}
// TestNewTaskSinkWritesEntriesReadableByTail pins that a task sink's on-disk
// format is exactly what Tail/Query/Components already know how to parse --
// a task's log history must be readable with the same reader the daemon-wide
// log uses, not a second incompatible format.
func TestNewTaskSinkWritesEntriesReadableByTail(t *testing.T) {
baseDir := t.TempDir()
sink, err := NewTaskSink(baseDir, 42, 1, TaskSinkOptions{})
if err != nil {
t.Fatalf("NewTaskSink: %v", err)
}
sink.Logger().Warn("gate failed", "component", "gate", "cmd", "go build ./...")
if err := sink.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
path := TaskLogPath(baseDir, 42, 1)
result, err := Tail(path, Query{})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(result.Entries) != 1 {
t.Fatalf("got %d entries, want 1: %+v", len(result.Entries), result.Entries)
}
entry := result.Entries[0]
if entry.Message != "gate failed" {
t.Errorf("Message = %q, want %q", entry.Message, "gate failed")
}
if entry.Level != "WARN" {
t.Errorf("Level = %q, want WARN", entry.Level)
}
if got := entry.Fields["component"]; got != "gate" {
t.Errorf("Fields[component] = %v, want gate", got)
}
}
func TestNewTaskSinkCreatesNestedTaskDirectory(t *testing.T) {
baseDir := t.TempDir()
sink, err := NewTaskSink(baseDir, 99, 1, TaskSinkOptions{})
if err != nil {
t.Fatalf("NewTaskSink: %v", err)
}
t.Cleanup(func() { _ = sink.Close() })
if _, err := os.Stat(TaskLogPath(baseDir, 99, 1)); err != nil {
t.Errorf("task log file not created: %v", err)
}
}
// TestNewTaskSinkHonoursRotationOptions confirms TaskSinkOptions.MaxSizeMB
// and .Keep both actually reach the underlying rotatingFile, not just
// MaxSizeMB. Writing enough to rotate past DefaultKeep (5) generations while
// asking for Keep: 2 is deliberate: if Keep were silently dropped and
// defaulted, generation .3 would still exist and this test would catch it --
// a smaller write volume that only ever produces 1-2 rotations would pass
// whether or not Keep was wired through at all. Rotation ordering itself
// (which generation holds what) is already covered by TestRotation; this
// only checks that TaskSink forwards both options.
func TestNewTaskSinkHonoursRotationOptions(t *testing.T) {
baseDir := t.TempDir()
sink, err := NewTaskSink(baseDir, 1, 1, TaskSinkOptions{MaxSizeMB: 1, Keep: 2})
if err != nil {
t.Fatalf("NewTaskSink: %v", err)
}
line := strings.Repeat("x", 64*1024)
for range 200 { // ~12MB against a 1MB cap: well past DefaultKeep (5) generations.
sink.Logger().Info(line)
}
if err := sink.Close(); err != nil {
t.Fatal(err)
}
path := TaskLogPath(baseDir, 1, 1)
for i := 1; i <= 2; i++ {
if _, err := os.Stat(fmt.Sprintf("%s.%d", path, i)); err != nil {
t.Errorf("rotated file .%d missing, want rotation to have engaged: %v", i, err)
}
}
if _, err := os.Stat(path + ".3"); err == nil {
t.Error("generation .3 exists, want retention capped at Keep=2 (not the default of 5, " +
"which .3 surviving would indicate Keep was dropped)")
}
}
func TestNewTaskSinkLevelFiltersEntries(t *testing.T) {
baseDir := t.TempDir()
sink, err := NewTaskSink(baseDir, 1, 1, TaskSinkOptions{Level: "warn"})
if err != nil {
t.Fatalf("NewTaskSink: %v", err)
}
sink.Logger().Info("info-line")
sink.Logger().Warn("warn-line")
if err := sink.Close(); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(TaskLogPath(baseDir, 1, 1))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "info-line") {
t.Error("info-line present, want it filtered at warn level")
}
if !strings.Contains(string(body), "warn-line") {
t.Error("warn-line missing")
}
}
// TestNewTaskSinkRejectsUnusableDirectory confirms a task sink surfaces the
// error instead of quietly falling back -- unlike the daemon-wide New, which
// intentionally degrades to stderr because losing the daemon over a log path
// is worse than losing the durable copy. A task sink has no such tradeoff:
// there is no equivalent fallback destination for one task's log, so a task
// sink that fails to open should fail loudly and let the caller decide.
func TestNewTaskSinkRejectsUnusableDirectory(t *testing.T) {
blocker := filepath.Join(t.TempDir(), "not-a-dir")
if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
_, err := NewTaskSink(blocker, 1, 1, TaskSinkOptions{})
if err == nil {
t.Error("NewTaskSink returned nil error for an unusable base directory")
}
}
func TestTaskSinkOutputIsValidJSONLines(t *testing.T) {
baseDir := t.TempDir()
sink, err := NewTaskSink(baseDir, 1, 1, TaskSinkOptions{})
if err != nil {
t.Fatalf("NewTaskSink: %v", err)
}
sink.Logger().Info("one")
sink.Logger().Info("two")
if err := sink.Close(); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(TaskLogPath(baseDir, 1, 1))
if err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.TrimSpace(string(body)), "\n")
if len(lines) != 2 {
t.Fatalf("got %d lines, want 2", len(lines))
}
for _, line := range lines {
var raw map[string]any
if err := json.Unmarshal([]byte(line), &raw); err != nil {
t.Errorf("line is not JSON: %v (%q)", err, line)
}
}
}