Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

refactor(activity): fold Filter.Source into Filter.Sources so the store narrows its file walk on the set (PIN-396)

Luigi Agosti65197a36b734
diff --git a/internal/activity/activity.go b/internal/activity/activity.go
index 1a0595ef..2dd7bc98 100644
--- a/internal/activity/activity.go
+++ b/internal/activity/activity.go
@@ -76,7 +76,6 @@ type StepCounts struct {
}
type Filter struct {
- Source string
Sources []string
RequestID string
SessionID string
@@ -485,13 +484,6 @@ func (noopRecorder) Query(Filter) ([]Event, error) {
}
func (f Filter) matches(evt Event) bool {
- // Compare normalized names: the source is stored verbatim from the client
- // header but the per-source file is named with the normalized form, so
- // matching raw here would discard events from the very file queryFiles
- // selected for this source.
- if f.Source != "" && normalizeSourceName(evt.Source) != normalizeSourceName(f.Source) {
- return false
- }
if len(f.Sources) > 0 && !matchesAnySource(evt.Source, f.Sources) {
return false
}
@@ -599,7 +591,7 @@ func (s *Store) queryFiles(filter Filter) []string {
files = append(files, legacyPath)
}
- source := normalizeSourceName(filter.Source)
+ wantSources := normalizedSources(filter.Sources)
for _, entry := range entries {
if entry.IsDir() {
continue
@@ -608,7 +600,7 @@ func (s *Store) queryFiles(filter Filter) []string {
if !isActivityLogFile(name) {
continue
}
- if source != "" && !isSourceLogFile(name, source) {
+ if len(wantSources) > 0 && !matchesAnySourceLogFile(name, wantSources) {
continue
}
if day, ok := activityLogDay(name); ok && !dayInRange(day, sinceDay, untilDay) {
@@ -717,6 +709,33 @@ func isActivityLogFile(name string) bool {
return name != "events.jsonl" && strings.HasPrefix(name, "events-") && strings.HasSuffix(name, ".jsonl")
}
+// normalizedSources normalizes a filter's requested sources, dropping any that
+// normalize to empty. A nil result means "no source narrowing".
+func normalizedSources(sources []string) []string {
+ if len(sources) == 0 {
+ return nil
+ }
+ out := make([]string, 0, len(sources))
+ for _, s := range sources {
+ if n := normalizeSourceName(s); n != "" {
+ out = append(out, n)
+ }
+ }
+ return out
+}
+
+// matchesAnySourceLogFile reports whether name is the per-source log of any of
+// the already-normalized sources, so the file walk opens only the requested
+// sources' logs instead of every source's log in the retention window.
+func matchesAnySourceLogFile(name string, normalizedSources []string) bool {
+ for _, s := range normalizedSources {
+ if isSourceLogFile(name, s) {
+ return true
+ }
+ }
+ return false
+}
+
// isSourceLogFile anchors on the trailing day so a query for "mcp" does not
// also scan every "mcp-<something>" source log.
func isSourceLogFile(name, source string) bool {
diff --git a/internal/activity/activity_test.go b/internal/activity/activity_test.go
index d8db7e30..4d8df6fd 100644
--- a/internal/activity/activity_test.go
+++ b/internal/activity/activity_test.go
@@ -33,7 +33,7 @@ func TestQueryKeepsNewestWithinLimitInOrder(t *testing.T) {
}
}
- got, err := store.Query(Filter{Source: "client", Limit: 3})
+ got, err := store.Query(Filter{Sources: []string{"client"}, Limit: 3})
if err != nil {
t.Fatalf("Query: %v", err)
}
@@ -351,7 +351,7 @@ func TestStorePartitionsDashboardEventsOutsidePrimaryLog(t *testing.T) {
t.Fatalf("unfiltered query = %d events, want 2 (server + dashboard)", len(gotAll))
}
- gotDashboard, err := store.Query(Filter{Source: "dashboard", Limit: 10})
+ gotDashboard, err := store.Query(Filter{Sources: []string{"dashboard"}, Limit: 10})
if err != nil {
t.Fatalf("Query dashboard: %v", err)
}
@@ -359,7 +359,7 @@ func TestStorePartitionsDashboardEventsOutsidePrimaryLog(t *testing.T) {
t.Fatalf("dashboard query = %#v, want dashboard event", gotDashboard)
}
- gotServer, err := store.Query(Filter{Source: "server", Limit: 10})
+ gotServer, err := store.Query(Filter{Sources: []string{"server"}, Limit: 10})
if err != nil {
t.Fatalf("Query server: %v", err)
}
@@ -787,7 +787,7 @@ func TestStoreRecordConcurrentNoCorruption(t *testing.T) {
}
wg.Wait()
- got, err := store.Query(Filter{Source: "server", Limit: 1000})
+ got, err := store.Query(Filter{Sources: []string{"server"}, Limit: 1000})
if err != nil {
t.Fatalf("Query: %v", err)
}
@@ -808,3 +808,87 @@ func TestStoreRecordConcurrentNoCorruption(t *testing.T) {
}
}
}
+
+// A query narrowed to a set of sources must open only those sources' per-source
+// log files, not every source's log in the retention window. The dashboard file
+// is poisoned with a line longer than the query scanner's token buffer, so the
+// query errors if — and only if — it opens the file it was not asked for. Fails
+// on HEAD, where a Sources-only filter narrowed nothing and walked every file.
+func TestQuerySourcesNarrowsFileWalkAndSkipsUnrequestedSource(t *testing.T) {
+ store, err := NewStore(t.TempDir(), 7)
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ day := time.Date(2026, 9, 12, 10, 0, 0, 0, time.UTC)
+ for _, src := range []string{SourceClient, SourceScheduler, SourceDashboard} {
+ if err := store.Record(Event{Source: src, Timestamp: day, Method: "GET", Path: "/" + src, Status: 200}); err != nil {
+ t.Fatalf("Record(%s): %v", src, err)
+ }
+ }
+
+ dashPath := store.sourceFilePathFor(SourceDashboard, day)
+ if dashPath == "" {
+ t.Fatal("no dashboard per-source path")
+ }
+ poison := []byte(strings.Repeat("x", 2*1024*1024) + "\n") // > the 1 MiB scanner token cap
+ if err := os.WriteFile(dashPath, poison, 0600); err != nil {
+ t.Fatalf("poison dashboard file: %v", err)
+ }
+
+ got, err := store.Query(Filter{Sources: []string{SourceClient, SourceScheduler}})
+ if err != nil {
+ t.Fatalf("query opened the dashboard file it was not asked for: %v", err)
+ }
+ if len(got) != 2 {
+ t.Fatalf("got %d events, want 2 (client + scheduler): %v", len(got), paths(got))
+ }
+ for _, e := range got {
+ if normalizeSourceName(e.Source) == SourceDashboard {
+ t.Errorf("a dashboard event leaked into a {client, scheduler} query: %+v", e)
+ }
+ }
+}
+
+// The store query and the IsDashboardAgentActivity predicate normalize the same
+// way: a capitalised or const-spelled source select the same events, and the
+// predicate agrees with the query on a capitalised source. Fails on HEAD for the
+// predicate, which compared evt.Source unnormalized.
+func TestQuerySourcesNormalizationMatchesPredicate(t *testing.T) {
+ store, err := NewStore(t.TempDir(), 7)
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ now := time.Now().UTC()
+ if err := store.Record(Event{Source: SourceClient, Timestamp: now, Method: "GET", Path: "/c", Status: 200}); err != nil {
+ t.Fatalf("Record client: %v", err)
+ }
+ if err := store.Record(Event{Source: SourceScheduler, Timestamp: now, Method: "GET", Path: "/s", Status: 200}); err != nil {
+ t.Fatalf("Record scheduler: %v", err)
+ }
+
+ capitalised, err := store.Query(Filter{Sources: []string{"Client"}})
+ if err != nil {
+ t.Fatalf("Query(Sources={\"Client\"}): %v", err)
+ }
+ constSpelled, err := store.Query(Filter{Sources: []string{SourceClient}})
+ if err != nil {
+ t.Fatalf("Query(Sources={SourceClient}): %v", err)
+ }
+ if len(capitalised) != 1 || len(constSpelled) != 1 {
+ t.Fatalf("capitalised=%d const=%d, want 1 each", len(capitalised), len(constSpelled))
+ }
+ if capitalised[0].Path != constSpelled[0].Path {
+ t.Errorf("capitalised query returned %q, const spelling %q", capitalised[0].Path, constSpelled[0].Path)
+ }
+
+ if !IsDashboardAgentActivity(Event{Source: "Scheduler"}) {
+ t.Error("IsDashboardAgentActivity(\"Scheduler\") = false; it disagrees with a normalized Sources query")
+ }
+ sched, err := store.Query(Filter{Sources: []string{"Scheduler"}})
+ if err != nil {
+ t.Fatalf("Query(Sources={\"Scheduler\"}): %v", err)
+ }
+ if len(sched) != 1 || sched[0].Path != "/s" {
+ t.Fatalf("capitalised scheduler query returned %v, want the one scheduler event", paths(sched))
+ }
+}
diff --git a/internal/activity/api.go b/internal/activity/api.go
index 6a755dde..71715389 100644
--- a/internal/activity/api.go
+++ b/internal/activity/api.go
@@ -86,7 +86,6 @@ func convertRoute(r *browserops.RouteMetadata) *apiTypes.RouteMetadata {
func filterFromRequest(r *http.Request) (Filter, error) {
q := r.URL.Query()
filter := Filter{
- Source: strings.TrimSpace(q.Get("source")),
RequestID: strings.TrimSpace(q.Get("requestId")),
SessionID: strings.TrimSpace(q.Get("sessionId")),
AgentID: strings.TrimSpace(q.Get("agentId")),
@@ -97,6 +96,9 @@ func filterFromRequest(r *http.Request) (Filter, error) {
Action: strings.TrimSpace(q.Get("action")),
PathPrefix: strings.TrimSpace(q.Get("pathPrefix")),
}
+ if source := strings.TrimSpace(q.Get("source")); source != "" {
+ filter.Sources = []string{source}
+ }
if limit := strings.TrimSpace(q.Get("limit")); limit != "" {
n, err := strconv.Atoi(limit)
diff --git a/internal/activity/source_filter_test.go b/internal/activity/source_filter_test.go
index 9226a346..8234fa27 100644
--- a/internal/activity/source_filter_test.go
+++ b/internal/activity/source_filter_test.go
@@ -28,7 +28,7 @@ func TestQuerySourceFilterIsNormalized(t *testing.T) {
t.Fatalf("Record: %v", err)
}
- got, err := s.Query(Filter{Source: "mcp"})
+ got, err := s.Query(Filter{Sources: []string{"mcp"}})
if err != nil {
t.Fatalf("Query: %v", err)
}
@@ -53,7 +53,7 @@ func TestQuerySourceFilterDoesNotMatchPrefix(t *testing.T) {
}
}
- got, err := s.Query(Filter{Source: "mcp"})
+ got, err := s.Query(Filter{Sources: []string{"mcp"}})
if err != nil {
t.Fatalf("Query: %v", err)
}
diff --git a/internal/activity/sources.go b/internal/activity/sources.go
index a3bbdc7f..0c12c8da 100644
--- a/internal/activity/sources.go
+++ b/internal/activity/sources.go
@@ -24,10 +24,5 @@ func DashboardAgentSources() []string {
// a restart; two separately spelled predicates drifted once and dropped scheduled
// actions from the per-agent summaries after any restart.
func IsDashboardAgentActivity(evt Event) bool {
- for _, source := range DashboardAgentSources() {
- if evt.Source == source {
- return true
- }
- }
- return false
+ return matchesAnySource(evt.Source, DashboardAgentSources())
}
diff --git a/internal/scheduler/activity_test.go b/internal/scheduler/activity_test.go
index adeec017..da2c1549 100644
--- a/internal/scheduler/activity_test.go
+++ b/internal/scheduler/activity_test.go
@@ -96,7 +96,7 @@ func recordScheduledTask(t *testing.T, want TaskState, instanceHandler http.Hand
var events []activity.Event
poll := time.After(2 * time.Second)
for {
- events, err = rec.Query(activity.Filter{Source: "scheduler"})
+ events, err = rec.Query(activity.Filter{Sources: []string{"scheduler"}})
if err != nil {
t.Fatalf("query: %v", err)
}