The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Rename ID-less events when their file rotates; cap retention
shukieshahc5ed1c20e002
diff --git a/cli/beacon/cmd/endpoint_traces_history.go b/cli/beacon/cmd/endpoint_traces_history.goindex 564af4a4..5f1eeddb 100644--- a/cli/beacon/cmd/endpoint_traces_history.go+++ b/cli/beacon/cmd/endpoint_traces_history.go@@ -137,9 +137,12 @@ var endpointTracesResetCmd = &cobra.Command{// maxHistorySizeMB bounds --max-size-mb well above any real disk, so the byte count cannot overflow.const maxHistorySizeMB = 1 << 30+// maxHistoryRetentionDays is the longest --retention-days accepted: 100 years, which never expires.+const maxHistoryRetentionDays = 100 * 365+func runEndpointTracesReindex(cmd *cobra.Command, args []string) error {- if endpointTraceHistoryOpts.retentionDays < 0 {- return errors.New("--retention-days must be zero (keep the current setting) or more")+ if endpointTraceHistoryOpts.retentionDays < 0 || endpointTraceHistoryOpts.retentionDays > maxHistoryRetentionDays {+ return fmt.Errorf("--retention-days must be between 0 (keep the current setting) and %d (never expire)", maxHistoryRetentionDays)}if endpointTraceHistoryOpts.maxSizeMB < 0 || endpointTraceHistoryOpts.maxSizeMB > maxHistorySizeMB {return fmt.Errorf("--max-size-mb must be between 0 (keep the current setting) and %d", maxHistorySizeMB)diff --git a/cli/beacon/cmd/endpoint_traces_history_test.go b/cli/beacon/cmd/endpoint_traces_history_test.goindex 15a982e8..28b8cb50 100644--- a/cli/beacon/cmd/endpoint_traces_history_test.go+++ b/cli/beacon/cmd/endpoint_traces_history_test.go@@ -141,6 +141,7 @@ func TestTraceHistoryReindexRejectsOutOfRangeLimits(t *testing.T) {traceHistoryFixture(t, false, "")for _, set := range []func(){func() { endpointTraceHistoryOpts.retentionDays = -1 },+ func() { endpointTraceHistoryOpts.retentionDays = maxHistoryRetentionDays + 1 },func() { endpointTraceHistoryOpts.maxSizeMB = -1 },func() { endpointTraceHistoryOpts.maxSizeMB = maxHistorySizeMB + 1 },} {diff --git a/cli/beacon/internal/endpoint/dashboard/history_ingest.go b/cli/beacon/internal/endpoint/dashboard/history_ingest.goindex 8080925f..2e692da3 100644--- a/cli/beacon/internal/endpoint/dashboard/history_ingest.go+++ b/cli/beacon/internal/endpoint/dashboard/history_ingest.go@@ -266,6 +266,11 @@ func (s *historyStore) catchUp(logPath string, progress func(done, total int64),key := lf.key()seen[key] = truecp := checkpoints[key]+ if cp.archive != lf.archive && cp.offset > 0 && cp.offset <= lf.size {+ if err := relabelIDlessEvents(tx, sourceID, lf); err != nil {+ return 0, err+ }+ }if cp.offset > lf.size {// Shorter than what was read from it: not the file the checkpoint describes.cp = fileCheckpoint{}@@ -407,9 +412,9 @@ type historyPass struct {const historyFlushEvery = 4096func newHistoryPass(tx *sql.Tx, sourceID int64) (*historyPass, error) {- insertEvent, err := tx.Prepare(`INSERT INTO events (source_id, file_key, offset, record_id, trace_key, seq, event_type, event_id, ts_ns,+ insertEvent, err := tx.Prepare(`INSERT INTO events (source_id, file_key, offset, record_id, line_no, idless, trace_key, seq, event_type, event_id, ts_ns,ord_ts, ord_seq, span_id, parent_span_id, otel_trace_id, span_name, hay, line)- VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT (source_id, file_key, offset) DO NOTHING`)if err != nil {return nil, err@@ -527,7 +532,11 @@ func (p *historyPass) add(fileKey string, offset int64, record EventRecord) erroif err != nil {return err}- result, err := p.insertEvent.Exec(p.sourceID, fileKey, offset, record.ID, row.traceKey, row.eventType, row.eventID, row.tsNS,+ idless := 0+ if record.Event.Event.ID == "" {+ idless = 1+ }+ result, err := p.insertEvent.Exec(p.sourceID, fileKey, offset, record.ID, record.Line, idless, row.traceKey, row.eventType, row.eventID, row.tsNS,row.order.ts, int64(row.order.seq), row.spanID, row.parentSpanID, row.otelTraceID, row.spanName, row.hay, compressLine(stored))if err != nil {return err@@ -989,7 +998,7 @@ func (p *historyPass) storedEventsInOrder(traceKey string) ([]*historyEvent, err// event numbers of what remains do not move.func pruneHistory(tx *sql.Tx, now time.Time, retentionDays, maxBytes int64) (bool, error) {pruned := false- cutoff := now.Add(-time.Duration(retentionDays) * 24 * time.Hour).UnixNano()+ cutoff := retentionCutoff(now, retentionDays)expired, err := historyTraceRows(tx, `SELECT id, source_id, trace_key FROM traces WHERE retain_ns < ? ORDER BY retain_ns`, cutoff)if err != nil {return false, err@@ -1021,8 +1030,8 @@ func pruneHistory(tx *sql.Tx, now time.Time, retentionDays, maxBytes int64) (boo}// Events are most of the store, so a trace's share of the events estimates its share of the// bytes.- excess := used - maxBytes*4/5- eventsToFree := (excess*totalEvents + used - 1) / used+ excess := used - maxBytes/5*4+ eventsToFree := int64(math.Ceil(float64(excess) / float64(used) * float64(totalEvents)))oldest, err := historyOldestTraces(tx, eventsToFree)if err != nil {return false, err@@ -1154,11 +1163,68 @@ func historyUsedBytes(tx *sql.Tx) (int64, error) {// hasExpiredTraces reports whether any trace is past retention, so an idle log still has its old// history pruned on schedule.func (s *historyStore) hasExpiredTraces(now time.Time) (bool, error) {- days := s.metaInt("retention_days", defaultHistoryRetentionDays)- cutoff := now.Add(-time.Duration(days) * 24 * time.Hour).UnixNano()+ cutoff := retentionCutoff(now, s.metaInt("retention_days", defaultHistoryRetentionDays))var oldest sql.NullInt64if err := s.db.QueryRow(`SELECT MIN(retain_ns) FROM traces`).Scan(&oldest); err != nil {return false, err}return oldest.Valid && oldest.Int64 < cutoff, nil}++// retentionCutoff is the time before which a trace's last event is past retention. Retention is+// capped at maxHistoryRetentionDays, beyond which nothing expires: a longer period would overflow+// time.Duration, put the cutoff in the future, and prune everything.+func retentionCutoff(now time.Time, days int64) int64 {+ if days <= 0 || days >= maxHistoryRetentionDays {+ return math.MinInt64+ }+ return now.Add(-time.Duration(days) * 24 * time.Hour).UnixNano()+}++// relabelIDlessEvents renames the events of a file that rotated since it was read. An event the+// writer left without an ID is named by its place in the log -- line-N in the live file,+// archive-K-line-N once rotation has moved the file to .K -- and the JSONL path names it by where+// the file is now, so the store follows.+func relabelIDlessEvents(tx *sql.Tx, sourceID int64, lf logFile) error {+ rows, err := tx.Query(`SELECT id, line_no, hay, line FROM events WHERE source_id = ? AND file_key = ? AND idless = 1`, sourceID, lf.key())+ if err != nil {+ return err+ }+ type stored struct {+ id int64+ lineNo int+ hay string+ line []byte+ }+ var events []stored+ for rows.Next() {+ var row stored+ if err := rows.Scan(&row.id, &row.lineNo, &row.hay, &row.line); err != nil {+ rows.Close()+ return err+ }+ events = append(events, row)+ }+ if err := rows.Close(); err != nil {+ return err+ }+ source := eventSource{path: lf.path, archive: lf.archive}+ for _, row := range events {+ event, err := decodeStoredEvent(row.line)+ if err != nil {+ return err+ }+ recordID := source.lineID(row.lineNo)+ derived := deriveRow(EventRecord{ID: recordID, Line: row.lineNo, Event: event})+ if _, err := tx.Exec(`INSERT INTO event_fts (event_fts, rowid, hay) VALUES ('delete', ?, ?)`, row.id, row.hay); err != nil {+ return err+ }+ if _, err := tx.Exec(`UPDATE events SET record_id = ?, event_id = ?, hay = ? WHERE id = ?`, recordID, derived.eventID, derived.hay, row.id); err != nil {+ return err+ }+ if _, err := tx.Exec(`INSERT INTO event_fts (rowid, hay) VALUES (?, ?)`, row.id, derived.hay); err != nil {+ return err+ }+ }+ return nil+}diff --git a/cli/beacon/internal/endpoint/dashboard/history_store.go b/cli/beacon/internal/endpoint/dashboard/history_store.goindex a94f028a..d3c13fac 100644--- a/cli/beacon/internal/endpoint/dashboard/history_store.go+++ b/cli/beacon/internal/endpoint/dashboard/history_store.go@@ -44,6 +44,8 @@ const (historyDerivationVersion = 1defaultHistoryRetentionDays = 90+ // maxHistoryRetentionDays is 100 years: a retention this long or longer means nothing expires.+ maxHistoryRetentionDays = 100 * 365defaultHistoryMaxBytes = int64(1) << 30// historyMaxLineBytes matches the JSONL scanner's line limit, so a line too long for one path@@ -304,6 +306,8 @@ func (s *historyStore) ensureSchema() error {file_key TEXT NOT NULL,offset INTEGER NOT NULL,record_id TEXT NOT NULL,+ line_no INTEGER NOT NULL,+ idless INTEGER NOT NULL,trace_key TEXT NOT NULL,seq INTEGER NOT NULL,event_type TEXT NOT NULL,@@ -320,6 +324,9 @@ func (s *historyStore) ensureSchema() error {UNIQUE (source_id, file_key, offset))`,`CREATE INDEX events_by_trace ON events (source_id, trace_key, seq)`,+ // Events the writer left without an ID are named by their place in the log, which moves+ // when the file rotates; this finds them.+ `CREATE INDEX events_idless ON events (source_id, file_key) WHERE idless = 1`,// traces keeps each trace's running aggregate, so a catch-up updates a summary with the new// events alone instead of rereading the trace.`CREATE TABLE traces (diff --git a/cli/beacon/internal/endpoint/dashboard/history_test.go b/cli/beacon/internal/endpoint/dashboard/history_test.goindex 4df1e2b0..2e4e3878 100644--- a/cli/beacon/internal/endpoint/dashboard/history_test.go+++ b/cli/beacon/internal/endpoint/dashboard/history_test.go@@ -5,6 +5,7 @@ import ("encoding/hex""encoding/json""fmt"+ "math""os""path/filepath""regexp"@@ -885,3 +886,67 @@ func TestHistoryRefoldsWhenAnEventArrivesLate(t *testing.T) {t.Fatalf("show = %#v ok=%v err=%v", show.Range, ok, err)}}++// A retention longer than time.Duration can hold must keep everything, not wrap around and prune+// everything.+func TestHistoryVeryLongRetentionKeepsEverything(t *testing.T) {+ path := newTestLog(t, parityFixture())+ withHistory(t)+ for _, days := range []int{maxHistoryRetentionDays, 365000, 1 << 40} {+ status, err := EnableHistoryStore(path, HistoryOptions{RetentionDays: days})+ if err != nil {+ t.Fatal(err)+ }+ if status.Traces == 0 {+ t.Fatalf("retention of %d days pruned every trace", days)+ }+ }+ if cutoff := retentionCutoff(time.Now(), 1<<40); cutoff != math.MinInt64 {+ t.Fatalf("cutoff for an overflowing retention = %d, want no expiry", cutoff)+ }+}++// An event the writer left without an ID is named by where it sits in the log, and the name+// changes when the file rotates. The store renames it too, so show and search keep matching the+// JSONL path.+func TestHistoryRenamesIDlessEventsWhenTheirFileRotates(t *testing.T) {+ withHistory(t)+ idless := func(ts, session, text string) []byte {+ return []byte(`{"timestamp":"` + ts + `","event":{"action":"prompt.submitted","category":"prompt"},"harness":{"name":"cursor"},"session":{"id":"` + session + `"},"prompt":{"text":"` + text + `"},"trace":{"id":"t-idless","span_id":"sp-` + text + `"}}`)+ }+ path := newTestLog(t, [][]byte{+ idless("2026-06-11T10:00:00Z", "a", "first-idless"),+ []byte(`{"timestamp":"2026-06-11T10:00:01Z","event":{"id":"with-id","action":"command.executed","category":"command"},"harness":{"name":"cursor"},"session":{"id":"a"},"command":{"command":"ls"}}`),+ idless("2026-06-11T10:00:02Z", "a", "second-idless"),+ })+ optIn(t, path)+ // Rotate: the live file becomes .1 and a new live file starts.+ if err := os.Rename(path, path+".1"); err != nil {+ t.Fatal(err)+ }+ writeTestLog(t, path, idless("2026-06-11T10:00:03Z", "a", "third-idless"))+ ids := []string{"trace:t-idless"}+ history := traceAnswers(t, path, ids)+ for _, q := range []string{"line-1", "archive-1-line-3", "archive-1", "line-3"} {+ result, err := SearchTraces(path, TraceQuery{EventQuery: EventQuery{Q: q}, ResultLevel: "event", Limit: 10})+ if err != nil {+ t.Fatal(err)+ }+ history["idless "+q] = mustJSON(t, result)+ }+ previous := os.Getenv(endpointconfig.HistoryStoreEnv)+ withoutHistory(t)+ want := traceAnswers(t, path, ids)+ for _, q := range []string{"line-1", "archive-1-line-3", "archive-1", "line-3"} {+ result, err := SearchTraces(path, TraceQuery{EventQuery: EventQuery{Q: q}, ResultLevel: "event", Limit: 10})+ if err != nil {+ t.Fatal(err)+ }+ want["idless "+q] = mustJSON(t, result)+ }+ t.Setenv(endpointconfig.HistoryStoreEnv, previous)+ compareAnswers(t, want, history)+ if !strings.Contains(want["idless archive-1-line-3"], "archive-1-line-3") {+ t.Fatalf("fixture did not produce a rotated ID: %s", want["idless archive-1-line-3"])+ }+}