Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

localingest: remember a failed send across hook processes; report spooled lines

Claudeb2519860cad9
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index 65f9928d..63869e24 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -13,6 +13,7 @@ import (
"strconv"
"strings"
"sync"
+ "testing"
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
@@ -528,7 +529,21 @@ func writeEndpointJSONFile(path string, event map[string]interface{}) error {
// EndpointIngest delivers to the system log through the collector when the endpoint is in the
// restricted log access mode. Tests point it at a socket and spool of their own; nothing else
// changes it.
-var EndpointIngest = localingest.Deliverer{}
+var EndpointIngest = defaultEndpointIngest()
+
+// defaultEndpointIngest is the real socket and the account's spool, except in a test binary, where
+// a test writing a system log as an ordinary account must never reach the machine's collector or
+// leave lines in the developer's own spool.
+func defaultEndpointIngest() localingest.Deliverer {
+ if !testing.Testing() {
+ return localingest.Deliverer{}
+ }
+ dir := filepath.Join(os.TempDir(), fmt.Sprintf("beacon-hooks-test-%d", os.Getpid()))
+ return localingest.Deliverer{
+ Client: localingest.Client{SocketPath: filepath.Join(dir, "no-collector.sock")},
+ Spool: localingest.Spool{Dir: filepath.Join(dir, "spool")},
+ }
+}
// deliverEndpointLine writes one finished line to the runtime log at path.
//
diff --git a/cli/beacon/cmd/endpoint.go b/cli/beacon/cmd/endpoint.go
index ab6a3cbb..b1deb381 100644
--- a/cli/beacon/cmd/endpoint.go
+++ b/cli/beacon/cmd/endpoint.go
@@ -708,7 +708,7 @@ func runEndpointVSCodeValidate() error {
}
func writeValidationEvent(cfg endpointconfig.Config, destination string) (string, error) {
- return writer.AppendEvent(syntheticEvent(destination), writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode})
+ return writer.AppendEvent(syntheticEvent(destination), writer.Options{Path: cfg.LogPath, UserMode: cfg.UserMode, RequireWritten: true})
}
func loadOrDefaultConfig() endpointconfig.Config {
diff --git a/cli/beacon/internal/endpoint/writer/ingest_unix_test.go b/cli/beacon/internal/endpoint/writer/ingest_unix_test.go
index 114b7326..c97a587f 100644
--- a/cli/beacon/internal/endpoint/writer/ingest_unix_test.go
+++ b/cli/beacon/internal/endpoint/writer/ingest_unix_test.go
@@ -7,6 +7,7 @@ import (
"errors"
"os"
"path/filepath"
+ "strings"
"sync"
"testing"
"time"
@@ -148,6 +149,46 @@ func TestAppendEventSpoolsWhenARestrictedLogRefusesIt(t *testing.T) {
}
}
+// A destination validation proves the log takes events, so an event that only reached the spool
+// must fail it rather than pass.
+func TestASpooledEventFailsAnAppendThatMustBeWritten(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("root is never refused by a file mode")
+ }
+ logPath, _ := useIngest(t, false)
+ if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(logPath, nil, 0o440); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := AppendEvent(ingestEvent("validate"), Options{Path: logPath, RequireWritten: true}); !errors.Is(err, ErrSpooled) {
+ t.Fatalf("AppendEvent = %v, want ErrSpooled", err)
+ }
+}
+
+func TestAnAppendThatMustBeWrittenPassesThroughTheCollector(t *testing.T) {
+ logPath, stub := useIngest(t, true)
+ if _, err := AppendEvent(ingestEvent("validate"), Options{Path: logPath, RequireWritten: true}); err != nil {
+ t.Fatal(err)
+ }
+ if len(stub.lines()) != 1 {
+ t.Fatalf("collector received %d lines", len(stub.lines()))
+ }
+}
+
+// A test binary's default deliverer must never reach the machine's collector or the developer's
+// own spool.
+func TestTheDefaultIngestInATestStaysOffTheMachine(t *testing.T) {
+ d := defaultIngest()
+ if d.Client.SocketPath == "" || d.Client.SocketPath == localingest.DefaultSocketPath {
+ t.Fatalf("socket = %q", d.Client.SocketPath)
+ }
+ if !strings.HasPrefix(d.Spool.Dir, os.TempDir()) {
+ t.Fatalf("spool = %q", d.Spool.Dir)
+ }
+}
+
// A backfill sets a guard and a budget, which only a direct writer holding the log's lock can
// honor, so it never goes through the socket.
func TestGuardedAppendsAreWrittenDirectly(t *testing.T) {
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index a5255408..71df04ad 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -11,6 +11,7 @@ import (
"reflect"
"strconv"
"strings"
+ "testing"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
@@ -42,8 +43,17 @@ type Options struct {
// Budget, when set, caps what this append may add to the log; an event that does not fit
// is refused with ErrBudgetSpent. See Budget.
Budget *Budget
+ // RequireWritten makes a line that could only be spooled an error (ErrSpooled) rather than a
+ // success. A caller whose job is to prove the log takes events, such as a destination
+ // validation, sets it; telemetry writers leave it unset, because a spooled line is late, not
+ // lost.
+ RequireWritten bool
}
+// ErrSpooled reports that a restricted log refused a line while its collector was unreachable, so
+// the line waits in this account's spool for a later one to carry it in.
+var ErrSpooled = errors.New("the event was spooled: the restricted runtime log refused it and the Beacon collector is unreachable")
+
// SystemLogPath is the system-mode runtime log, resolved per platform.
//
// Delegated rather than duplicated: this was one of fourteen copies of the same literal, and the
@@ -136,7 +146,22 @@ func AppendEvent(event schema.Event, opts Options) (string, error) {
// Ingest delivers to the system log through the collector when the endpoint is in the restricted
// log access mode. Tests point it at a socket and spool of their own; nothing else changes it.
-var Ingest = localingest.Deliverer{}
+var Ingest = defaultIngest()
+
+// defaultIngest is the real socket and the account's spool, except in a test binary, where a
+// test that writes a system log as an ordinary account must never reach the machine's collector
+// or leave lines in the developer's own spool: there it is a socket that does not exist and a
+// spool in a private temporary directory.
+func defaultIngest() localingest.Deliverer {
+ if !testing.Testing() {
+ return localingest.Deliverer{}
+ }
+ dir := filepath.Join(os.TempDir(), fmt.Sprintf("beacon-writer-test-%d", os.Getpid()))
+ return localingest.Deliverer{
+ Client: localingest.Client{SocketPath: filepath.Join(dir, "no-collector.sock")},
+ Spool: localingest.Spool{Dir: filepath.Join(dir, "spool")},
+ }
+}
// deliver writes one line to the system log as an account that is not root, the way the hook
// adapter does: through the collector's ingest socket when there is one, directly otherwise, and
@@ -145,9 +170,13 @@ var Ingest = localingest.Deliverer{}
// here: those limits are decided under the log's lock, which only a direct writer holds, and the
// backfill that sets them runs as root on a system log.
func deliver(opts Options, data []byte) error {
- return Ingest.Write(opts.Path, data, func(line []byte) error {
+ outcome, err := Ingest.WriteOutcome(opts.Path, data, func(line []byte) error {
return appendJSONL(opts.Path, append(line[:len(line):len(line)], '\n'), opts.RotateSize, opts.RotateArchives, nil, nil)
})
+ if err == nil && outcome == localingest.Spooled && opts.RequireWritten {
+ return ErrSpooled
+ }
+ return err
}
// compactRetainedContent drops an event's retained text and records that it did, so a reader can
diff --git a/pkg/asymptoteobserve/localingest/deliver.go b/pkg/asymptoteobserve/localingest/deliver.go
index c4a0e751..2ad19a5c 100644
--- a/pkg/asymptoteobserve/localingest/deliver.go
+++ b/pkg/asymptoteobserve/localingest/deliver.go
@@ -27,7 +27,7 @@ func DefaultSpoolDir() string {
return filepath.Join(home, spoolDirInHome)
}
-// defaultFailureBackoff is how long a process skips the socket after a failed send.
+// defaultFailureBackoff is how long an account skips the socket after a failed send.
const defaultFailureBackoff = 10 * time.Second
// lastSendFailure is when this process last failed to send, in Unix nanoseconds; zero when the last
@@ -46,7 +46,7 @@ type Deliverer struct {
Spool Spool
// Euid reports the process's effective uid; nil means os.Geteuid. Tests replace it.
Euid func() int
- // FailureBackoff is how long, after a failed send, this process goes straight to the direct
+ // FailureBackoff is how long, after a failed send, this account goes straight to the direct
// append without trying the socket. Zero means 10s; negative turns it off.
FailureBackoff time.Duration
}
@@ -67,6 +67,20 @@ func (d Deliverer) Applies(logPath string) bool {
return euid != 0 && !asymptoteobserve.RuntimeLogIsPrivate(logPath)
}
+// Outcome is where Write put a line.
+type Outcome int
+
+const (
+ // Appended: written directly, as writers always have.
+ Appended Outcome = iota
+ // Sent: handed to the collector, which wrote it.
+ Sent
+ // Spooled: kept in this account's spool, to be written with a later line. Callers that only
+ // record telemetry treat it as success; one whose job is to prove the log takes events (a
+ // destination validation) must not.
+ Spooled
+)
+
// Write gets one line, meant for logPath, into that log. appendLine appends one line directly, the
// way the writer always has.
//
@@ -75,35 +89,45 @@ func (d Deliverer) Applies(logPath string) bool {
// writes logPath, and it takes the line. A rejected line is reported, never retried.
// - If there is no socket, or the send fails -- a socket a crashed collector left behind, a
// collector that is hung -- the line is appended directly. On a shared log that simply works.
-// - Only when the direct append is refused for permission, as a restricted log refuses it, is the
-// line spooled.
+// - Only when the direct append is refused for permission, as a restricted log refuses it while
+// its collector is down, is the line spooled. A collector that answered for some other log
+// will never take it, so then the refusal is returned instead.
//
// Every line that gets through takes up to a batch of this account's spool for logPath with it, by
-// the same route. After a failed send the process skips the socket for FailureBackoff, so a hook
-// writing several events waits out a hung collector once.
+// the same route. After a failed send the account skips the socket for FailureBackoff, in this
+// process and in the hook processes that follow it, so a hung collector costs one timeout rather
+// than one per event.
func (d Deliverer) Write(logPath string, line []byte, appendLine func([]byte) error) error {
+ _, err := d.WriteOutcome(logPath, line, appendLine)
+ return err
+}
+
+// WriteOutcome is Write, reporting where the line went.
+func (d Deliverer) WriteOutcome(logPath string, line []byte, appendLine func([]byte) error) (Outcome, error) {
if !d.Applies(logPath) {
- return appendLine(line)
+ return Appended, appendLine(line)
}
+ collectorElsewhere := false
if !d.inBackoff() {
c := d.Client
c.LogPath = logPath
resp, err := c.Send([][]byte{line})
switch {
case err == nil && resp.Rejected > 0:
- return fmt.Errorf("the collector rejected the event: %w", ErrRejected)
+ return Sent, fmt.Errorf("the collector rejected the event: %w", ErrRejected)
case err == nil:
- lastSendFailure.Store(0)
+ d.clearFailure()
d.drain(logPath, func(lines [][]byte) (int, error) {
resp, err := c.Send(lines)
return resp.Processed, err
})
- return nil
- case errors.Is(err, ErrNoSocket), errors.Is(err, ErrUntrustedSocket), errors.Is(err, ErrLogMismatch):
- // Not a collector this line can go through; the endpoint is shared, or the line is for
- // some other log.
+ return Sent, nil
+ case errors.Is(err, ErrLogMismatch):
+ collectorElsewhere = true
+ case errors.Is(err, ErrNoSocket), errors.Is(err, ErrUntrustedSocket):
+ // No collector this line can go through: the endpoint is shared.
default:
- lastSendFailure.Store(time.Now().UnixNano())
+ d.recordFailure()
}
}
err := appendLine(line)
@@ -116,24 +140,81 @@ func (d Deliverer) Write(logPath string, line []byte, appendLine func([]byte) er
}
return len(lines), nil
})
- return nil
+ return Appended, nil
}
- if !errors.Is(err, fs.ErrPermission) {
- return err
+ if !errors.Is(err, fs.ErrPermission) || collectorElsewhere {
+ return Appended, err
}
if spoolErr := d.spoolLine(logPath, line); spoolErr != nil {
- return fmt.Errorf("%w; spool: %v", err, spoolErr)
+ return Spooled, fmt.Errorf("%w; spool: %v", err, spoolErr)
}
- return nil
+ return Spooled, nil
+}
+
+// sendFailureMarker, in the account's spool directory, is touched when a send fails. Hooks run as
+// a new process per event, so the failure has to outlive the process that saw it.
+const sendFailureMarker = ".send-failure"
+
+func (d Deliverer) backoff() time.Duration {
+ if d.FailureBackoff == 0 {
+ return defaultFailureBackoff
+ }
+ return d.FailureBackoff
}
func (d Deliverer) inBackoff() bool {
- backoff := d.FailureBackoff
- if backoff == 0 {
- backoff = defaultFailureBackoff
+ backoff := d.backoff()
+ if backoff <= 0 {
+ return false
+ }
+ if last := lastSendFailure.Load(); last != 0 && time.Since(time.Unix(0, last)) < backoff {
+ return true
+ }
+ dir := d.spoolRoot()
+ if dir == "" {
+ return false
+ }
+ info, err := os.Stat(filepath.Join(dir, sendFailureMarker))
+ if err != nil {
+ return false
+ }
+ age := time.Since(info.ModTime())
+ return age >= 0 && age < backoff
+}
+
+func (d Deliverer) recordFailure() {
+ lastSendFailure.Store(time.Now().UnixNano())
+ if d.backoff() <= 0 {
+ return
+ }
+ dir := d.spoolRoot()
+ if dir == "" {
+ return
+ }
+ if err := os.MkdirAll(dir, SpoolDirMode); err != nil {
+ return
+ }
+ path := filepath.Join(dir, sendFailureMarker)
+ now := time.Now()
+ if err := os.Chtimes(path, now, now); err != nil {
+ if f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, SpoolFileMode); err == nil {
+ _ = f.Close()
+ }
+ }
+}
+
+func (d Deliverer) clearFailure() {
+ lastSendFailure.Store(0)
+ if dir := d.spoolRoot(); dir != "" {
+ _ = os.Remove(filepath.Join(dir, sendFailureMarker))
+ }
+}
+
+func (d Deliverer) spoolRoot() string {
+ if d.Spool.Dir != "" {
+ return d.Spool.Dir
}
- last := lastSendFailure.Load()
- return backoff > 0 && last != 0 && time.Since(time.Unix(0, last)) < backoff
+ return DefaultSpoolDir()
}
// spoolFor is the spool for logPath: its own directory under the account's spool, named by a
diff --git a/pkg/asymptoteobserve/localingest/deliver_unix_test.go b/pkg/asymptoteobserve/localingest/deliver_unix_test.go
index 2a520f6e..9c832da6 100644
--- a/pkg/asymptoteobserve/localingest/deliver_unix_test.go
+++ b/pkg/asymptoteobserve/localingest/deliver_unix_test.go
@@ -339,6 +339,104 @@ func TestWriteRetriesTheSocketOnceTheBackoffPasses(t *testing.T) {
}
}
+// Hooks run as a new process per event, so a hung collector must cost the next process nothing
+// either: the failure is remembered in the account's spool directory, not only in memory.
+func TestASendFailureIsRememberedAcrossProcesses(t *testing.T) {
+ sock := filepath.Join(shortTempDir(t), "run", "ingest.sock")
+ l, err := Listen(sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ go func() { // accepts and never answers
+ var held []net.Conn
+ for {
+ c, err := l.Accept()
+ if err != nil {
+ for _, h := range held {
+ _ = h.Close()
+ }
+ return
+ }
+ held = append(held, c)
+ }
+ }()
+ d := deliverer(t, sock)
+ d.Client.Timeout = 200 * time.Millisecond
+ d.FailureBackoff = 0
+ log := &directLog{refuse: true}
+ if err := d.Write(testLog, lines(t, 1)[0], log.append); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(d.Spool.Dir, sendFailureMarker)); err != nil {
+ t.Fatalf("the failure was not recorded: %v", err)
+ }
+ lastSendFailure.Store(0) // a new process
+ start := time.Now()
+ if err := d.Write(testLog, lines(t, 1)[0], log.append); err != nil {
+ t.Fatal(err)
+ }
+ if elapsed := time.Since(start); elapsed > 100*time.Millisecond {
+ t.Fatalf("the next process waited %v for the hung collector", elapsed)
+ }
+}
+
+func TestASuccessfulSendClearsTheRememberedFailure(t *testing.T) {
+ h := startServer(t, nil)
+ d := deliverer(t, h.path)
+ d.FailureBackoff = 0
+ marker := filepath.Join(d.Spool.Dir, sendFailureMarker)
+ if err := os.MkdirAll(d.Spool.Dir, SpoolDirMode); err != nil {
+ t.Fatal(err)
+ }
+ old := time.Now().Add(-defaultFailureBackoff - time.Second)
+ if err := os.WriteFile(marker, nil, SpoolFileMode); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chtimes(marker, old, old); err != nil {
+ t.Fatal(err)
+ }
+ if err := d.Write(testLog, lines(t, 1)[0], (&directLog{}).append); err != nil {
+ t.Fatal(err)
+ }
+ if h.rec.count() != 1 {
+ t.Fatal("an expired failure kept the socket from being tried")
+ }
+ if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("the failure marker survived a successful send: %v", err)
+ }
+}
+
+// A collector that serves some other log will never take this line, so spooling it would only
+// strand it: the refusal is returned instead.
+func TestARefusedLineForALogTheCollectorDoesNotServeIsNotSpooled(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.LogPath = testLog })
+ d := deliverer(t, h.path)
+ other := "/tmp/elsewhere/runtime.jsonl"
+ log := &directLog{refuse: true}
+ err := d.Write(other, lines(t, 1)[0], log.append)
+ if !errors.Is(err, fs.ErrPermission) {
+ t.Fatalf("Write = %v, want the refusal", err)
+ }
+ if n, _ := d.Pending(other); n != 0 {
+ t.Fatalf("Pending = %d; nothing will ever drain it", n)
+ }
+}
+
+func TestWriteOutcome(t *testing.T) {
+ h := startServer(t, nil)
+ if got, err := deliverer(t, h.path).WriteOutcome(testLog, lines(t, 1)[0], (&directLog{}).append); err != nil || got != Sent {
+ t.Fatalf("through the socket: %v, %v", got, err)
+ }
+ none := filepath.Join(shortTempDir(t), "none.sock")
+ if got, err := deliverer(t, none).WriteOutcome(testLog, lines(t, 1)[0], (&directLog{}).append); err != nil || got != Appended {
+ t.Fatalf("direct: %v, %v", got, err)
+ }
+ if got, err := deliverer(t, none).WriteOutcome(testLog, lines(t, 1)[0], (&directLog{refuse: true}).append); err != nil || got != Spooled {
+ t.Fatalf("refused: %v, %v", got, err)
+ }
+}
+
func TestDefaultSpoolDir(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)