Skip to content

feat(search): trace-level AND scope across spans (#3004) - #3154

Open
eugeneo17 wants to merge 39 commits into
ClickHouse:mainfrom
CloudGeometry:feature/3004-trace-scope
Open

eugeneo17 wants to merge 39 commits into
ClickHouse:mainfrom
CloudGeometry:feature/3004-trace-scope

Conversation

@eugeneo17

@eugeneo17 eugeneo17 commented Sep 18, 2026 •

Copy link
Copy Markdown

Add a Span | Trace search scope. Span (default) is unchanged; Trace matches traces where predicates are satisfied by different spans of the same trace, by rewriting each predicate into a TraceId IN (SELECT TraceId ... WHERE <predicate> AND <time>) membership subquery and AND-composing them, with the time filter pushed into every subquery.

Trace scope is fail-closed: offered only for trace sources exposing a trace-id expression, and reset to Span on source switch, so existing searches and saved queries are unaffected.

Closes #3004

Summary

Today A AND B on a trace source matches only when both conditions are true within a single span. A trace, however, is many spans across many services, so the common question "find traces where A happened in one span and B in another span of the same trace" (cross-span) is not expressible.

This PR adds an explicit Search scope control with two modes:

  • Span — default, unchanged. Every predicate must hold within a single span.
  • Trace — new. A AND B matches traces where A and B are satisfied by different spans of the same trace (cross-span).

How it works. In Trace scope, each predicate is rewritten into its own trace-id membership subquery and the parts are AND-composed, with the time filter pushed into every subquery:

WHERE (<time>)
  AND TraceId IN (SELECT TraceId FROM <source> WHERE (<predicate A>) AND (<time>))
  AND TraceId IN (SELECT TraceId FROM <source> WHERE (<predicate B>) AND (<time>))

The rewrite lives in renderWhere (packages/common-utils/src/core/renderChartConfig.ts) and activates only when filtersScope === 'trace' and a traceIdExpression is present; otherwise it falls through to the existing single-WHERE path unchanged.

Fail-closed / backward compatible. Trace scope is offered only for trace sources that expose a trace-id expression (resolveTraceScope, packages/common-utils/src/core/traceScope.ts); on any other source it is disabled with a clear message and resets to Span when the source is switched. Span stays the default, so existing searches and saved queries behave exactly as before.

Scope / limits (MVP). Applies to AND composition of separate predicates (search bar + filters); OR is out of scope for this iteration. A single string with AND inside one predicate remains same-span by definition.

Tests. Unit, integration, a11y and e2e coverage is included (traceScope.test.ts, searchChartConfig.test.ts, renderChartConfig.test.ts + snapshot, DBSearchPage.searchScope.test.tsx, DBSearchPageFilters.test.tsx, SearchScopeControl.a11y.test.tsx, trace-scope-search.spec.ts).

Screenshots or video

After
Screenshot 2026-09-18 090229

Before
Screenshot 2026-09-18 090449
Screenshot 2026-09-18 090430

How to test on Vercel preview

Preview routes: /search

Steps:

  1. Open /search and set Data Source to Traces.
  2. Verify a Search scope control with Span and Trace options is visible next to the query bar (Span selected by default).
  3. Click Trace and confirm it becomes the selected scope (the results header shows the Trace scope badge).
  4. Switch Data Source to Logs. Verify the Trace option is disabled with the message that trace scope isn't available for this source.
  5. Confirm the scope has reset to Span after the source switch.

References


Note

Medium Risk
Changes core ClickHouse WHERE generation and saved-search/alert query paths; span default and fail-closed guards limit blast radius, but trace-scope SQL and negation edge cases could affect result correctness.

Overview
Adds a Span | Trace search scope so multi-predicate AND can match across spans in the same trace, not only within one span. Span stays the default; Trace rewrites each positive predicate into its own TraceId IN (SELECT TraceId … WHERE <predicate> AND <time>) subquery and AND-composes them, while exclusions stay on the outer WHERE via new isNegatedFilterCondition logic.

The choice flows through buildSearchChartConfig → filtersScope, traceIdExpression, and renderWhere in common-utils, with traceScopeDateRange on chunked/paginated queries and traceScopeOuterFilters for span-level UI filters (e.g. delta selection). searchScope is persisted on saved searches, exposed in the API/OpenAPI/MCP layer, and wired through alerts and preview charts so evaluations match the UI.

The app adds SearchScopeControl in the filters sidebar, URL/state handling, a Scope: Trace badge, trace-specific empty copy, and fail-closed behavior when the source lacks a trace-id expression or is not a trace source.

Reviewed by Cursor Bugbot for commit b68924a. Bugbot is set up for automated code reviews on this repo. Configure here.

Add a Span | Trace search scope. Span (default) is unchanged; Trace matches
traces where predicates are satisfied by different spans of the same trace,
by rewriting each predicate into a TraceId IN (SELECT TraceId ... WHERE
<predicate> AND <time>) membership subquery and AND-composing them, with the
time filter pushed into every subquery.

Trace scope is fail-closed: offered only for trace sources exposing a
trace-id expression, and reset to Span on source switch, so existing
searches and saved queries are unaffected.

Closes ClickHouse#3004
@changeset-bot

changeset-bot Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: b68924a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@hyperdx/common-utils Minor
@hyperdx/app Minor
@hyperdx/api Minor
@hyperdx/otel-collector Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel

vercel Bot commented Sep 18, 2026

Copy link
Copy Markdown

@eugeneo17 is attempting to deploy a commit to the HyperDX Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions github-actions Bot added external needs-vouch Author needs a maintainer to vouch for them labels Sep 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hi @eugeneo17, thanks for the pull request!

Before we review code from a first-time contributor we ask that a maintainer vouches for you, and you're not on our list yet. This PR stays open — it just isn't in the review queue until someone vouches.

To get vouched, open an issue saying hello and what you're working on:

https://github.com/hyperdxio/hyperdx/issues/new?template=introduce-yourself.md

A maintainer will usually reply within a day or two, and then this PR gets picked up as normal. More detail in our contributing guide.

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

No description provided.

@greptile-apps

greptile-apps Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 1/5

[Medium impact] The change affects query matching within trace searches and their results.

The PR is not ready to merge because the earlier search-state and delta-query bugs remain.

Fix All in Claude CodeFindings

  1. P1 Delta loses cross-span matches ▶
  2. P1 Saved searches lose Trace scope ▶
  3. P1 Form resets lose Trace scope ▶
  4. P1 Source changes retain Trace scope ▶
  5. P2 Invalid trace IDs correlate ▶
  6. P2 Badge uses palette colors ▶
  7. P2 Test steps narrate actions ▶
  8. P2 Wrapper mock uses any ▶
  9. P2 Scope value bypasses narrowing ▶
  10. P2 Fixtures bypass source typing ▶
  11. P2 Ad-hoc trace empty state ▶
  12. P2 Control expands oversized file ▶
  13. P2 Oversized page grows further ▶

Summary

Adds Span and Trace search scopes. Trace searches combine separate predicates through trace-ID subqueries.

  • Trace searches can match conditions across separate spans.
  • The search page lets users choose and identify Trace scope.
  • Delta charts keep their internal queries at span scope.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Search form and URL] --> B[Build search configuration]
  B --> C{Trace scope and usable trace source?}
  C -->|No| D[Existing span query]
  C -->|Yes| E[Separate positive predicates]
  E --> F[Trace-ID subquery for each predicate]
  F --> G[Combine matches with AND]
  G --> H[Apply outer time window and exclusions]
Loading

Reviews (25) · Last reviewed commit: "Merge remote-tracking branch 'upstream/m..." · Reviewed by Greptile

});
const membershipSubqueries = searchPredicates.map(
predicate =>
chSql`${tid} IN (SELECT ${tid} FROM ${from} WHERE ${concatChSql(' AND ', predicate, timeFilter)})`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Invalid trace IDs correlate

Trace scope correlates rows solely by their raw trace ID without excluding empty or all-zero values. The trace pipeline and ClickHouse schema do not reject these values, so unrelated spans with the same invalid ID can satisfy separate predicates and produce a false trace-level match. Exclude invalid IDs from both the membership subqueries and the outer results.

Fix in Claude Code Fix in Conductor Fix in Cursor Fix in Codex

Comment thread packages/app/src/DBSearchPage.tsx Resolved
Comment thread packages/app/src/DBSearchPage.tsx Outdated
Comment on lines +2672 to +2676
color={
executedSearchScope === 'trace'
? 'blue'
: 'gray'
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge uses palette colors

The new badge selects raw Mantine palette colors (blue and gray). The repository requires colors and surfaces to use semantic theme properties rather than ad-hoc palette values. This requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Conductor Fix in Cursor Fix in Codex

Comment thread packages/app/src/DBSearchPage.tsx Resolved
initialSortBy={initialSortBy}
enableSmallFirstWindow
onResolvedColumnsChange={onResolvedColumnsChange}
noResultsMessage={

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — noResultsMessage is not a prop of DBSqlRowTableWithSideBar, so the trace-zero empty state never renders

Props in packages/app/src/components/DBSqlRowTableWithSidebar.tsx:29-54 has no noResultsMessage, and the empty copy is hardcoded in packages/app/src/components/DBRowTable.tsx:1297 (No results found.). Passing the prop is an excess-property error in JSX (breaks tsc) and is silently dropped at runtime, so getTraceZeroEmptyDescription() is never shown and the new e2e assertion traceZeroEmptyState (packages/app/tests/e2e/features/trace-scope-search.spec.ts:1027) cannot pass. Thread the message through DBSqlRowTableWithSideBar → DBSqlRowTable → DBRowTable and render it with EmptyState per the repo's REQUIRED empty-state rule, or drop the prop.

const traceApplicable = traceScope?.applicable ?? false;
const reasonId = useId();

useEffect(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Scope is force-reset to Span while the source query is still loading, so ?searchScope=trace can never be restored

source comes from useSource({ id: sourceId }) (line 1193), an async react-query call whose data is undefined on first render (and sourceId itself is undefined until useSources() resolves in DBSearchPage). So on any load/refresh of a trace-scoped URL or saved link, traceApplicable is false on mount and the effect calls onChange('span') with shouldDirty: true, discarding the scope before the source arrives. Gate the effect on the source actually being resolved (if (source && !traceApplicable && value === 'trace')); the existing scopeValue fallback at line 1086 already keeps the display on Span while loading, and renderWhere fails closed without a traceIdExpression.

from: chartConfig.from,
isRenderingRawSqlTemplate: chartConfig.isRenderingRawSqlTemplate,
});
const membershipSubqueries = searchPredicates.map(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Negated predicates become existential at trace scope, so exclusion filters stop excluding

Every predicate is rewritten to TraceId IN (SELECT TraceId … WHERE <predicate>), i.e. "some span of the trace satisfies it". The filter sidebar emits exclusions as <col> NOT IN (…) (packages/common-utils/src/filters.ts:90-96), so excluding ServiceName = 'api' becomes "the trace has at least one span whose ServiceName is not api" — true for essentially every multi-service trace, and api spans are still returned. Same for a negated search-bar query. Keep negated/exclusion predicates as ordinary span-level conjuncts in the outer WHERE (or express them as TraceId NOT IN (SELECT … WHERE <negated-inverse>)) instead of wrapping them in a membership subquery.

chSql`${tid} IN (SELECT ${tid} FROM ${from} WHERE ${concatChSql(' AND ', predicate, timeFilter)})`,
);

return concatChSql(' AND ', timeFilter, ...membershipSubqueries);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — The outer query keeps no predicate, so trace-scope results are every span of every matching trace

concatChSql(' AND ', timeFilter, ...membershipSubqueries) leaves the outer WHERE with only the time filter plus trace-membership tests, so a Search query (LIMIT 200) returns all spans of the matching traces — a search for ServiceName:api AND SpanName:checkout fills the table with spans matching neither, and the histogram/SearchNumRows count spans while the copy says "traces". Since no single span can satisfy all predicates at trace scope, AND-ing them back is wrong, but an OR of the same predicates in the outer WHERE would restrict the rows to the spans that actually matched while the membership subqueries still enforce the cross-span AND.

Comment thread packages/common-utils/src/types.ts Outdated
filtersLogicalOperator: z.enum(['AND', 'OR']).optional(),
// Whether multi-predicate AND is evaluated per span (default) or across all
// spans of a trace. Absence resolves to span, preserving existing output.
filtersScope: z.enum(['span', 'trace']).optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — New _ChartConfigSchema fields are unclassified by the alert-config drift guard

BuilderSavedChartConfigWithoutAlertSchema (types.ts:1812-1822) extends _ChartConfigSchema.shape, so filtersScope and traceIdExpression now appear in AlertChartConfigSchema. The drift-guard test at packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts:603-615 asserts every internal field is listed in one of the sets in alertChartConfig.ts (EXTERNAL_TO_INTERNAL_KEY, EVALUATION_INERT_CONFIG_KEYS, KNOWN_LOSSY_CONFIG_KEYS) and will fail for both keys. Classify them deliberately — filtersScope changes what an alert evaluates, so it belongs in KNOWN_LOSSY_CONFIG_KEYS (or the refuse list), not silently through. Also gate traceIdExpression in searchChartConfig.ts:193 on input.searchScope === 'trace'; today it is attached to every trace-source search config even though only the trace branch reads it.

Comment thread packages/app/src/DBSearchPage.tsx Outdated
return 'No traces match all predicates at trace scope.';
}

export function getResultViewState({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — getResultViewState is exported and tested but has no caller

Grep shows the only references are the two new test files; the page still selects error/empty/results with the pre-existing inline hasQueryError ? … : … ternary at 2726-2874, so the function cannot affect what a user sees. Either wire the results panel through it or delete it along with its tests.

});
});

describe('result-scope surface states', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The result-scope surface states tests assert on markup the test itself writes

These cases render <span aria-label={getScopeIndicatorLabel('trace')}> and <div>{getTraceZeroEmptyDescription()}</div> — literals constructed in the test — so they pass no matter what DBSearchPage renders, and would still pass with the badge and empty state removed entirely. Two related gaps: the new snapshot does not alter the span-scope SQL … (packages/common-utils/src/tests/snapshots/renderChartConfig.test.ts.snap) is written fresh by this PR, so it cannot detect the alteration it claims to guard; and no test — unit or e2e — asserts that a trace-scope query actually matches a trace whose predicates are satisfied by different spans, which is the whole point of the feature. Assert against the rendered page (or a renderChartConfig result over a two-span fixture) instead of against locally built JSX.

Comment thread packages/app/src/DBSearchPage.tsx Outdated
<>
<div className="h-100 w-100 px-4 mt-4 align-items-center justify-content-center text-muted overflow-auto">
<Alert
color="red"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — New callout uses raw Mantine palette colors instead of the semantic variants

<Alert color="red" title="Query failed"> breaks the "Semantic component variants" rule (prefer variant="danger" for any new callout); the <Badge variant="light" color={… 'blue' : 'gray'}> at 2670-2683 likewise reaches for raw palette values where a semantic token is expected. Use <Alert variant="danger"> and a token-driven badge color. While there: the banner and its "this is not a zero-result. Scope: Span." copy render for every query failure regardless of scope, on top of the existing error panel below it — scope-specific wording belongs behind executedSearchScope === 'trace', and the badge is shown even on log sources where scope is inapplicable.

);
};

export type SearchScope = 'span' | 'trace';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The span/trace union is restated in six places under two different names

SearchScope here, type SearchScope in DBSearchPage.tsx:210, searchScope?: 'span' | 'trace' | null in packages/app/src/types.ts:25, searchScope?: 'span' | 'trace' in searchChartConfig.ts:82, z.enum(['span','trace']) in DBSearchPage.tsx:193, and filtersScope: z.enum(['span','trace']) in common-utils/src/types.ts:1626 — plus the SEARCH_SCOPE_PARAM array. The repo's REQUIRED DRY rule wants one canonical definition: export a single Zod enum (and its inferred type) from common-utils/dist/types and derive the rest from it, and pick one name — the concept is currently searchScope in the app and filtersScope in the chart config, which is a second thing to keep in sync by hand.

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

5 finding(s): 🔴 1 P0/P1 · 🟡 2 P2 · 🔵 2 P3

None could be anchored to changed lines; they are listed below. 2 P3 folded at the bottom. 1 unchanged from an earlier push (already inline above).

Findings outside the changed lines

  • 🔴 P1 packages/common-utils/src/core/renderChartConfig.ts:3035 — 'Root spans only' toggle does nothing under trace scope → The sidebar's root-span toggle (setRootSpansOnly in packages/app/src/components/DBSearchPageFilters.tsx:1563) emits ParentSpanId IN ('') or isRootSpan IN (true). Nothing marks it as negated, so it becomes a TraceId IN (SELECT … WHERE ParentSpanId IN ('')) membership test. Almost every trace has a root span, and the outer rows are no longer filtered, so the table shows every span while the toggle still reads as on. Route this row-level selector to the outer WHERE (traceScopeOuterFilters, or a marker on the filter), and add a test for it.
  • 🟡 P2 packages/common-utils/src/core/renderChartConfig.ts:2927 — Fallback negation regex matches operators inside string literals; existing quote-aware helper is ignored → When the parser rejects a predicate (for example a Map['k'] lookup), /(?:!=|<>)/ and \bNOT\s+… also match text inside quoted values. So SpanAttributes['k'] = 'a != b' is treated as an exclusion and leaves the trace-membership path without notice. packages/common-utils/src/filters.ts:287 already has containsOutsideQuotes, which parseQuery uses for the same NOT IN check. Export it and use it here.
🔵 2 P3 — no action needed before merge
  • 🔵 P3 packages/common-utils/src/types.ts:3162 — TraceScopeResolution.reason is never read → Outside tests, no code reads reason. The UI shows one generic message (TRACE_SCOPE_UNAVAILABLE_REASON) and every caller checks only .applicable. Either drop the reason variant and return { applicable: false }, or use it to tell the user which case applies (not a trace source, or no trace-id expression).
  • 🔵 P3 packages/app/src/DBSearchPage.tsx:3260 — New scope indicator uses a Mantine Badge where the conventions prefer click-ui's → The Click UI conventions say to prefer a @clickhouse/click-ui component when one exists for a simple primitive, and Badge is on that list. Render the indicator with click-ui's Badge. Also drop aria-label: it repeats the visible text and adds nothing.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

eugeneo17 and others added 2 commits September 18, 2026 09:17
- Remove the unused getResultViewState helper (and its tests); the shipped
  result rendering branches on hasQueryError and delegates empty/results to
  the row table, so the helper was dead code that could drift.
- Share the SearchScope union: import it from DBSearchPageFilters in
  DBSearchPage instead of redeclaring it.
- Note that trace scope deliberately omits the $__filters raw-SQL-template
  expansion (search-only by contract).
- Explain the searchScope -> filtersScope field mapping in searchChartConfig.
});
const membershipSubqueries = searchPredicates.map(
predicate =>
chSql`${tid} IN (SELECT ${tid} FROM ${from} WHERE ${concatChSql(' AND ', predicate, timeFilter)})`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 critical — Trace-scope subqueries inherit the paginated time window, so cross-span AND misses the matches it exists to find

The results table paginates by progressive time windows: useOffsetPaginatedQuery rewrites config.dateRange to [timeWindow.startTime, timeWindow.endTime] per page (packages/app/src/hooks/useOffsetPaginatedQuery.tsx:212, windows of 1m/15m/6h/6h/12h/24h from packages/app/src/utils/searchWindows.ts:1), and windowing is active whenever the first ORDER BY is the timestamp — the search page default. Because the rewrite pushes that already-narrowed timeFilter into every membership subquery, a trace whose ServiceName='api' span is at T-20h and whose SpanName='checkout' span is at T-1m never matches any single window's query, and the user sees the new "No traces match all predicates at trace scope" empty state even though the trace is inside the selected range. Carry the user-selected range (not the windowed one) for the membership subqueries — e.g. thread an unwindowed dateRange onto the config for the subquery time filter — or disable window pagination when filtersScope === 'trace'.

initialSortBy={initialSortBy}
enableSmallFirstWindow
onResolvedColumnsChange={onResolvedColumnsChange}
noResultsMessage={

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 critical — noResultsMessage is not a prop of DBSqlRowTableWithSideBar; the trace-zero empty state never renders

Props in packages/app/src/components/DBSqlRowTableWithSidebar.tsx:29-54 has no noResultsMessage (and no rest spread), and DBRowTable hardcodes No results found. at packages/app/src/components/DBRowTable.tsx:1297. So this is a TS error on an excess prop and, even if it compiled, the trace-zero copy is dropped — the new e2e assertion searchPage.traceZeroEmptyState (packages/app/tests/e2e/features/trace-scope-search.spec.ts:911) cannot pass. Add the prop through DBSqlRowTableWithSideBar → DBSqlRowTable down to the no-results branch, and render it via EmptyState per the repository's REQUIRED EmptyState rule rather than the ad-hoc <div>.

Comment thread packages/common-utils/src/types.ts Outdated
filtersLogicalOperator: z.enum(['AND', 'OR']).optional(),
// Whether multi-predicate AND is evaluated per span (default) or across all
// spans of a trace. Absence resolves to span, preserving existing output.
filtersScope: z.enum(['span', 'trace']).optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — New _ChartConfigSchema fields are unclassified, breaking the alert external-API drift guard

filtersScope and traceIdExpression land in BuilderSavedChartConfigWithoutAlertSchema (it extends _ChartConfigSchema.omit(...).shape at packages/common-utils/src/types.ts:1870), so the drift-guard test at packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts:603-615 now runs classifies the internal builder config field "filtersScope" / "traceIdExpression" and fails: neither key is in the external schema, EVALUATION_INERT_CONFIG_KEYS, or KNOWN_LOSSY_CONFIG_KEYS. Both change what an alert evaluates, so add them to KNOWN_LOSSY_CONFIG_KEYS in packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts:132 (making an echo-PUT fail loudly instead of silently re-scoping an alert).

from: chartConfig.from,
isRenderingRawSqlTemplate: chartConfig.isRenderingRawSqlTemplate,
});
const membershipSubqueries = searchPredicates.map(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Exclusion filters become existential in trace scope, so excluded values still come back

The filter sidebar emits exclusions as <col> NOT IN (...) (packages/common-utils/src/filters.ts:90-97). Wrapping that predicate in TraceId IN (SELECT TraceId ... WHERE (ServiceName NOT IN ('api')) AND <time>) asks for traces that have some span that is not api — true for essentially every multi-service trace — so "exclude ServiceName: api" stops excluding anything and api spans keep appearing in the results. Negated predicates need TraceId NOT IN (SELECT ... WHERE <positive form>), or they must stay span-level conjuncts on the outer WHERE; either way the current unconditional existential rewrite is wrong for them.

const traceApplicable = traceScope?.applicable ?? false;
const reasonId = useId();

useEffect(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Fail-closed reset fires while the source is still loading, discarding a trace scope restored from the URL

source comes from useSource({ id: sourceId }) (line 1193) and is undefined on the first renders, so traceScope is undefined → traceApplicable is false → the effect calls onChange('span'). Opening a shared link with ?searchScope=trace therefore flips the form to span (and flashes "Trace scope isn't available for this source.") before the trace source resolves. Gate the reset on a resolved source (e.g. skip while isLoading/source == null) so "not yet known" is distinguished from "not applicable".

Comment thread packages/app/src/DBSearchPage.tsx Outdated
enableParallelQueries
/>
<Group gap="sm" align="center">
<Badge

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Scope badge reports Trace even when the rewrite was never applied

executedSearchScope is derived only from the URL value, never from applicability, while the SQL rewrite additionally requires a trace traceIdExpression (renderChartConfig.ts:1455). The reset that is supposed to keep those in sync lives in SearchScopeControl, which is only mounted when the filter sidebar is open (DBSearchPage.tsx:2515 renders DBSearchPageFilters under !isFilterSidebarCollapsed), so switching from a trace source to a log source with the sidebar collapsed leaves searchScope=trace in the URL and the badge claiming Scope: Trace over span-scoped results. Move the applicability reset into DBSearchPage (where the source changes, independent of sidebar visibility) and derive the badge from resolveTraceScope(searchedSource) as well as the stored scope — and only show it when trace scope is applicable, so log searches don't gain a permanent Scope: Span chip.

Comment thread packages/app/src/DBSearchPage.tsx Outdated
{hasQueryError && queryError ? (
<>
<div className="h-100 w-100 px-4 mt-4 align-items-center justify-content-center text-muted overflow-auto">
<Alert

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — New query-error Alert fires for every failure and hardcodes color="red"

This alert renders on any query error for any source — a Lucene syntax error on a log source now reads "The query didn't complete, so this is not a zero-result. Scope: Span.", which is noise unrelated to the failure. Gate it on executedSearchScope === 'trace' (that is the only case where a failure could be misread as a trace-zero), and use the repository's semantic callout variant <Alert variant="danger" …> instead of the forbidden raw palette color="red" (Semantic component variants convention).

Comment thread packages/app/src/DBSearchPage.tsx Outdated
source: z.string(),
where: z.string(),
whereLanguage: z.enum(['sql', 'lucene']),
searchScope: z.enum(['span', 'trace']).default('span'),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The span/trace union is restated in five places instead of one shared definition

'span' | 'trace' is written independently in common-utils/src/types.ts:1678 (zod enum), core/searchChartConfig.ts:89, app/src/types.ts:25, here (schema + SEARCH_SCOPE_PARAM), and as SearchScope in components/DBSearchPageFilters.tsx:1062. Per the REQUIRED DRY rule, export one SearchScopeSchema/SearchScope from common-utils/src/types.ts and derive/alias it everywhere else so the enum has a single source of truth.

const TRACE_SCOPE_UNAVAILABLE_REASON =
"Trace scope isn't available for this source.";

export const SearchScopeControl = ({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — SearchScopeControl is appended to an already 1,900-line file that has a sibling directory for extracted pieces

DBSearchPageFilters.tsx is far past the 300-line guideline and already has components/DBSearchPageFilters/ for split-out parts (NestedFilterGroup, utils). Move SearchScopeControl (and its SearchScope type / unavailable-reason copy) into components/DBSearchPageFilters/SearchScopeControl.tsx and re-export, matching how NestedFilterGroup is organised.

selectionResetKey={selectionResetKey}
onSelectedRowsChange={onSelectedRowsChange}
onResolvedColumnsChange={onResolvedColumnsChange}
noResultsMessage={

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 critical — noResultsMessage is not a prop of DBSqlRowTableWithSideBar — type error, and the trace-zero empty state never renders

Props in packages/app/src/components/DBSqlRowTableWithSidebar.tsx:29-57 has no noResultsMessage, so this is a JSX excess-property error (next.config.mjs:121 does not set ignoreBuildErrors, so next build fails), and even ignoring types the string is dropped — DBRowTable.tsx:1345 always renders the hardcoded "No results found." The e2e assertion on searchPage.traceZeroEmptyState (tests/e2e/features/trace-scope-search.spec.ts) therefore cannot pass. Thread an optional noResultsMessage through DBSqlRowTableWithSideBar → DBSqlRowTable → DBRowTable and render it in that empty block (via EmptyState's description, per the EmptyState convention).

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

from: chartConfig.from,
isRenderingRawSqlTemplate: chartConfig.isRenderingRawSqlTemplate,
});
const membershipSubqueries = searchPredicates.map(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 critical — Trace-scope rewrite inverts negative predicates, so exclusions silently stop filtering

Every predicate is wrapped as TraceId IN (SELECT TraceId … WHERE <predicate>), which means "some span of the trace satisfies it". For a negative predicate that is nearly always true: clicking "exclude" on ServiceName: checkout in the filter sidebar produces ServiceName NOT IN ('checkout') (packages/common-utils/src/filters.ts:90-97), which renders as TraceId IN (SELECT TraceId … WHERE (ServiceName NOT IN ('checkout'))) — every trace that has at least one span from any other service still matches, so the excluded traces are still returned. Same for a Lucene -foo or a != typed into the search bar. Emit TraceId NOT IN (SELECT …) for negated predicates, or keep exclusion predicates as outer-level conjuncts, instead of turning them into existence tests; no test covers a negative predicate today.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

Comment thread packages/common-utils/src/types.ts Outdated
filtersLogicalOperator: z.enum(['AND', 'OR']).optional(),
// Whether multi-predicate AND is evaluated per span (default) or across all
// spans of a trace. Absence resolves to span, preserving existing output.
filtersScope: z.enum(['span', 'trace']).optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — New _ChartConfigSchema fields are unclassified in the external alert API drift guard

filtersScope and traceIdExpression flow into AlertChartConfigSchema via BuilderSavedChartConfigWithoutAlertSchema (types.ts:1888-1899), and packages/api/src/routers/external-api/v2/utils/__tests__/alertChartConfig.test.ts:603-615 asserts every key of that schema is in the representable / EVALUATION_INERT_CONFIG_KEYS / KNOWN_LOSSY_CONFIG_KEYS sets — neither new key is, so that test now fails. Decide and record the classification: both are evaluation-relevant-only-together, so KNOWN_LOSSY_CONFIG_KEYS (config refuses external emission) or EVALUATION_INERT_CONFIG_KEYS in packages/api/src/routers/external-api/v2/utils/alertChartConfig.ts:98.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

const traceApplicable = traceScope?.applicable ?? false;
const reasonId = useId();

useEffect(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Scope reset on source switch only happens while the filter sidebar is mounted, so the badge can claim Trace on a span-scoped query

This effect is the only thing that forces scope back to span for a non-trace source, but DBSearchPageFilters is unmounted when isFilterSidebarCollapsed is true (DBSearchPage.tsx:2540). With the sidebar collapsed, switching Traces → Logs leaves searchScope: 'trace' in the form; the source-change effect (DBSearchPage.tsx:1436-1490) resets select/orderBy/filters but not the scope, then auto-submits. The SQL correctly falls back to span (no traceIdExpression), but the results header renders the "Scope: Trace" badge and, once wired, the trace-zero empty copy — the indicator lies about how the query ran. Move the reset into the source-change effect in DBSearchPage, and derive the badge from resolveTraceScope(searchedSource).applicable && scope === 'trace'.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
enableParallelQueries
/>
<Group gap="sm" align="center">
<Badge

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The scope badge renders unconditionally, including "Scope: Span" on every log search

executedSearchScope is always defined, so every search on every source now carries a permanent gray badge for a control most sources can't even use. Render the badge only when executedSearchScope === 'trace', and drop the raw color="blue"/"gray" palette props in favour of a semantic token per the design-token convention.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
<>
<div className="h-100 w-100 px-4 mt-4 align-items-center justify-content-center text-muted overflow-auto">
<Alert
color="red"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Query-failure alert uses color="red" and appends the scope label to every error, on every source

The conventions list <Alert color="red" title="Failed"> as a forbidden pattern — use <Alert variant="danger" title="Query failed">. Also, "… this is not a zero-result. Scope: Span." is now appended to every query failure, including log searches where scope is neither offered nor meaningful; only append the scope sentence when executedSearchScope === 'trace'.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

});
});

describe('result-scope surface states', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The result-scope surface states tests assert on markup the test itself renders, not on the product

Both cases build a local <span aria-label={...}> / <div>{description}</div> and then assert the string they just rendered — they would pass unchanged if the badge and empty state were deleted from DBSearchPage. Render the real surfaces (or assert the wiring in a DBSearchPage test) so a regression in the badge/empty-state plumbing — e.g. the unused noResultsMessage prop above — actually fails.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

* Whether multi-predicate AND is evaluated per span (default) or across all
* spans of a trace. Omitted resolves to span downstream.
*/
searchScope?: 'span' | 'trace';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The 'span' | 'trace' union is restated four times under two names

It appears inline here, as filtersScope: z.enum(['span','trace']) (common-utils/src/types.ts:1678), as SearchScope (app/src/components/DBSearchPageFilters.tsx:1062), and inline again in app/src/types.ts:25 — against the REQUIRED "don't retype the definition" rule. Export one SearchScopeSchema/SearchScope from common-utils/src/types.ts (inferred from the zod enum) and import it everywhere; keeping one name for one concept also removes the searchScope ↔ filtersScope translation.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

- Restore the noResultsMessage plumbing through DBSqlRowTableWithSidebar and
  DBRowTable so the trace-zero empty state renders (and the JSX type-checks);
  it was dropped when isolating the change.
- Classify the new filtersScope / traceIdExpression config fields as
  KNOWN_LOSSY in the external-API alert drift guard so the schema test passes.
- Don't reset trace scope while the source is still loading, so a
  trace-scoped URL / saved link is no longer discarded on mount.
- Only surface the scope badge / scope copy when trace scope actually applied
  (trace source with a trace-id expression), so the badge never claims Trace
  on a fallback-to-span query and no gray 'Scope: Span' badge shows on log
  searches.
- Use the semantic Alert variant (danger) instead of raw color=red.
- Single-source the span|trace union: export SearchScopeSchema/SearchScope
  from common-utils and consume it everywhere.
- Document the trace-scope negation/exclusion limitation inline.

Verified: common-utils build, common-utils/app/api unit tests, app tsc --noEmit,
and prettier all pass locally.
});
const membershipSubqueries = searchPredicates.map(
predicate =>
chSql`${tid} IN (SELECT ${tid} FROM ${from} WHERE ${concatChSql(' AND ', predicate, timeFilter)})`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 critical — Trace-membership subqueries inherit the windowed date range, so cross-span matches that straddle a window boundary are silently dropped

The search results table renders the config once per time window (packages/app/src/hooks/useOffsetPaginatedQuery.tsx:209, windows of 1m/15m/6h… from utils/searchWindows.ts, active whenever the first ORDER BY is the timestamp — the search page default), and the histogram/total-count chunk the range too (useChartConfig.tsx:161-185). timeFilter here is that chunk's range, so predicate A at 10:00:30 and predicate B at 10:01:10 never intersect: each window's subquery only sees its own minute, and the same trace yields different memberships per chunk. Pin the subqueries to the user's full selected range the same way the series-limit CTE already does via seriesLimitDateRange (renderChartConfig.ts:1572) — add an analogous traceScopeDateRange set by the windowing layers — or refuse to window/chunk when filtersScope === 'trace'.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

// the already-rendered SQL here; handling negation correctly (as
// `TraceId NOT IN (SELECT ... WHERE <positive form>)`) needs the structured
// filter and is left to a follow-up.
const searchPredicates = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Exclusion filters become no-ops at trace scope with no UI warning

A sidebar "exclude" selection renders as col NOT IN (…) (packages/common-utils/src/filters.ts:93), and wrapping it in TraceId IN (SELECT … WHERE (col NOT IN (…))) matches every trace that has any other span — so excluding ServiceName='noisy' in Trace scope returns exactly the traces the user was excluding. The code comment acknowledges this, but nothing tells the user: either keep negated predicates on the outer WHERE (span-scoped) or surface a warning/disable the exclude affordance while Trace scope is selected.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

const reasonId = useId();

useEffect(() => {
// Only fall back to span once the source has actually resolved. While it is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The fail-closed reset-to-span lives in a conditionally mounted control, so it never runs with the filter sidebar collapsed

DBSearchPageFilters is only rendered when !isFilterSidebarCollapsed (DBSearchPage.tsx:2548), and isFilterSidebarCollapsed is a persisted localStorage preference; with it collapsed, switching from a trace source to a log source leaves searchScope=trace in the form and URL, and switching to another trace source silently re-applies cross-span AND. Move the reset into the page's source-change effect (DBSearchPage.tsx:1436) where the source actually changes, and leave the control presentational.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
{hasQueryError && queryError ? (
<>
<div className="h-100 w-100 px-4 mt-4 align-items-center justify-content-center text-muted overflow-auto">
<Alert

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — New "Query failed / this is not a zero-result" alert fires for every query error, not just trace scope

This banner renders on any error on any source (a Lucene typo on a log search shows "The query didn't complete, so this is not a zero-result.") and sits directly above the existing "Error encountered for query with inputs…"/"Error Message" block that already reports the failure; its data-testid="search-query-error" has no reader. Gate it on traceScopeActive or drop it and keep the existing error surface.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond


jest.mock('@/layout', () => ({
withAppNav: (component: any) => component,
}));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — New page-level tests assert constants, never the wiring that is actually broken

This file only checks Zod defaults and that getScopeIndicatorLabel('trace') === 'Scope: Trace', and SearchScopeControl.a11y.test.tsx:130 renders a hand-built <span aria-label={…}> rather than the page — so nothing exercises the form/URL round trip, which is where the reset bug above lives (the e2e passes because it asserts the badge, not the control, after searching). Render DBSearchPage (or extract the scope↔URL state into a hook) and assert the control still reads Trace after a submit.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/common-utils/src/types.ts Outdated
filtersLogicalOperator: z.enum(['AND', 'OR']).optional(),
// Whether multi-predicate AND is evaluated per span (default) or across all
// spans of a trace. Absence resolves to span, preserving existing output.
filtersScope: SearchScopeSchema.optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — filtersScope + traceIdExpression as two independent optionals admits invalid states on every chart config

Both fields are added to _ChartConfigSchema, so any chart config (dashboard tiles, alerts, MCP) can carry filtersScope: 'trace' with no expression or vice versa, and the renderer has to re-check the pairing at renderChartConfig.ts:1455 while buildSearchChartConfig attaches traceIdExpression to every trace-source config even at span scope. Model it as one optional object (traceScope?: { traceIdExpression: string }) so "trace without an expression" is unrepresentable.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Wrapping a negated filter as TraceId IN (SELECT ... WHERE <col> NOT IN (...))
means 'some span of the trace is not x', which is true for almost any
multi-span trace, so exclusions stopped excluding at trace scope.

Represent exclusions structurally: filtersToQuery tags them with an optional
negated flag (the condition string is unchanged, so span scope, dashboards
and the parseQuery round-trip are untouched). At trace scope only positive
predicates become membership subqueries; negated filters are applied to the
outer rows instead, so excluded values genuinely disappear from the results.

Adds a regression test and updates the filtersToQuery expectations for the
new flag.

Verified: common-utils build + unit tests (incl. new exclusion test, span
snapshots unchanged), app tsc --noEmit, prettier.
@eugeneo17

Copy link
Copy Markdown
Author

Thanks for the automated reviews — here's a summary of what I addressed.

Fixed (blocking / correctness):

  • Trace-zero empty state + build error — restored the noResultsMessage plumbing through DBSqlRowTableWithSidebar → DBRowTable, so the empty-state renders and the JSX type-checks (tsc --noEmit is clean).
  • Alert external-API drift guard — classified the new filtersScope / traceIdExpression config fields as KNOWN_LOSSY_CONFIG_KEYS; the drift-guard test passes again.
  • Exclusion filters at trace scope — a negated predicate was wrapped as TraceId IN (SELECT … WHERE <col> NOT IN (…)), i.e. "some span is not x", which matches almost any multi-span trace. Exclusions are now represented structurally (an optional negated flag on the filter; the condition string is unchanged, so span scope, dashboards and the parseQuery round-trip are untouched) and applied to the outer rows at trace scope instead of as membership subqueries, so excluded values genuinely disappear. Added a regression test.
  • Scope reset while the source is still loading — no longer discards a ?searchScope=trace URL/saved link on mount; the reset now waits for a resolved source.
  • Badge / scope copy consistency — the scope badge and the error-alert scope sentence render only when trace scope actually applied (trace source with a trace-id expression), so the badge never claims Trace on a fallback-to-span query and no gray "Scope: Span" badge shows on log searches.
  • Semantic variants / DRY — <Alert variant="danger"> instead of color="red"; the span | trace union is now a single SearchScopeSchema / SearchScope exported from common-utils and imported everywhere.

Not changed here (happy to discuss in-thread):

  • Empty / all-zero trace IDs correlating and paginated time-window inside the subqueries — these weren't confirmed as blocking by the deep-review pass and touch trace-scope semantics more broadly; I'd prefer to scope them with a maintainer rather than widen this PR.
  • Search-bar negation (as opposed to filter-chip exclusions) is still treated as a single positive membership predicate — documented as a known MVP limitation in the code.

Verified locally: common-utils build, common-utils / app / api unit tests (including the new exclusion test; span-scope snapshots unchanged), app tsc --noEmit, and prettier all pass. The branch is up to date with main.

This is my second/third fix round, so per the contributing guide I'll pause on further automated findings and defer scope decisions to a maintainer. (Also still looking for a vouch to enter the review queue — happy to open an intro issue.)

// matches when *some* span satisfies the predicate"), AND-ed together so a
// trace must satisfy each across (possibly different) spans. The search bar
// and aggConditions are treated as positive.
const membershipPredicates = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 critical — Trace scope wraps search-bar and sql_ast negations in a membership subquery, so they stop excluding

membershipPredicates treats whereSearchCondition and every sql_ast filter as positive (the latter is hardcoded negated: false at line 1411). A search bar containing -ServiceName:"cart" (Lucene) or ServiceName != 'cart' (SQL) renders as TraceId IN (SELECT TraceId … WHERE (NOT ServiceName = 'cart') AND <time>) — "some span isn't cart" — which is true for nearly every multi-span trace, so the query silently returns the traces the user asked to exclude. This is the same hazard the comment at line 1483 guards against for sidebar filters. Detect negation from the rendered predicate (or run the search-bar/sql_ast predicates through the same exclusion path) instead of assuming the search bar is positive.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

Comment thread packages/common-utils/src/filters.ts Outdated
.join(', ')})`,
// Exclusion: kept out of the trace-scope existential membership
// rewrite, where "some span is NOT x" would match almost every trace.
negated: true,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — negated is a persisted second source of truth that pre-existing URLs and saved searches don't carry

useSearchPageFilterState only re-emits filters through filtersToQuery when the user mutates a facet (packages/app/src/searchFilters.tsx:137); filters hydrated from a saved search or an existing URL are passed straight to buildSearchChartConfig (DBSearchPage.tsx:1193, 1226). Any exclusion created before this PR therefore arrives with no negated, and renderWhere turns it into a TraceId IN (SELECT … WHERE col NOT IN (…)) membership test that matches almost every trace — the exclusion stops excluding, silently. Derive negation from the condition at render time (the condition string is already the source of truth, and parseQuery in this same file can recover the excluded set) rather than trusting an out-of-band boolean that old rows lack.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

}}
>
<Stack gap="sm" p="xs">
{onSearchScopeChange && (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — The scope control is unreachable when the filter sidebar is collapsed

DBSearchPageFilters is only mounted when !isFilterSidebarCollapsed (DBSearchPage.tsx:2548), and that flag is persisted in localStorage (DBSearchPage.tsx:1122). Any user who has collapsed the sidebar cannot see or change the search scope at all, and SearchScopeControl's fail-back-to-span effect (line 1077) never runs on source switch — the inconsistency the comment at DBSearchPage.tsx:1581 describes. Put the control next to the query bar as the PR description states, or render it outside the collapsible sidebar.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
enableParallelQueries
/>
<Group gap="sm" align="center">
{traceScopeActive && (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Trace scope labels the results as traces but the count, histogram and rows are still spans

The outer query keeps SELECT … FROM <source> with only time + membership + exclusions, so every span of each matching trace is returned. SearchNumRows (line 2697) and histogramTimeChartConfig (line 1948) spread the same trace-scoped chartConfig, so a one-predicate trace search reports every span of every matching trace as a "result" while the badge says "Scope: Trace" and the empty state says "No traces match all predicates". Either make the count distinct on the trace-id expression at trace scope, or word the badge/empty state so the user knows the rows are spans of matching traces.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
{hasQueryError && queryError ? (
<>
<div className="h-100 w-100 px-4 mt-4 align-items-center justify-content-center text-muted overflow-auto">
<Alert

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — New "Query failed" banner is shown for every search error, not just trace scope

Only the trailing sentence is scope-specific; the Alert and its Retry button render on every hasQueryError, duplicating the existing "Error encountered for query with inputs:" panel directly below (line 2784) that already shows the failing SELECT/WHERE/ORDER BY. Gate the banner on traceScopeActive, or drop it and append the scope sentence to the existing panel — an unconditional new error surface is outside this PR's stated scope.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

});
});

describe('result-scope surface states', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The result-scope surface states tests assert against markup the test itself builds

Both tests render a literal <span aria-label={getScopeIndicatorLabel('trace')}> / <div>{getTraceZeroEmptyDescription()}</div> and then assert that string is present — they exercise no product code, and expect(description.toLowerCase()).toContain('trace') is tautological given the helper returns a constant. The five preceding a11y cases also duplicate assertions already in DBSearchPageFilters.test.tsx (radiogroup role, checked state, disabled + aria-describedby, arrow-key). Delete this block and instead cover what is actually untested: that DBSearchPage renders the badge/empty-state when searchedConfig.searchScope === 'trace' on a trace source and not otherwise.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

expect(spanSql).toMatchSnapshot();
});

it('produces a single subquery whose trace set equals the span-scope predicate for one predicate @AC-FR006-01', async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The @AC-FR006-01 test claims an equivalence it never checks, and the claim is false

The test is named "produces a single subquery whose trace set equals the span-scope predicate" but only counts TraceId IN (SELECT occurrences and greps for substrings in each SQL separately — it would pass for any single-predicate rewrite. The stated equivalence also does not hold: at span scope the query returns the matching spans, at trace scope it returns every span of each matching trace. Rename it to what it verifies (one subquery per predicate) or assert the subquery's inner WHERE equals the span-scope WHERE.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
return scope === 'trace' ? 'trace' : 'span';
}

export const SEARCH_SCOPE_PARAM = parseAsStringEnum<SearchScope>([

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The span/trace union is restated in three places

SearchScopeSchema (packages/common-utils/src/types.ts:1671) is the declared single source of truth, but SEARCH_SCOPE_PARAM re-lists ['span','trace'] and resolveSearchScope (line 214) hand-rolls the parse as a ternary. Use parseAsStringEnum<SearchScope>(SearchScopeSchema.options) and SearchScopeSchema.catch('span').parse(scope) so adding a third scope later is a one-line change — the repo marks DRY as REQUIRED.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

const TRACE_SCOPE_UNAVAILABLE_REASON =
"Trace scope isn't available for this source.";

export const SearchScopeControl = ({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — SearchScopeControl is appended to an already ~1740-line file instead of the sibling directory

packages/app/src/components/DBSearchPageFilters/ already exists and holds the extracted pieces (NestedFilterGroup, utils). Move SearchScopeControl and TRACE_SCOPE_UNAVAILABLE_REASON into DBSearchPageFilters/SearchScopeControl.tsx and re-export, per the 300-line file-size rule and "put related components in a single directory".

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Address the review findings on the exclusion handling and time windowing:

- Derive negation from the condition at render time instead of a persisted
  'negated' flag (removed). The flag only reached freshly-emitted sidebar
  filters, so exclusions from saved searches / older URLs became existential.
  isNegatedFilterCondition now classifies the sidebar 'col NOT IN (...)',
  a sql_ast '!=', and a single-negation search bar (Lucene '-'/'NOT', SQL
  '!='), routing them to the outer WHERE rather than a membership subquery.

- Pin each membership subquery to the user's full selected range via a new
  traceScopeDateRange (set by useOffsetPaginatedQuery / useChartConfig when the
  query is chunked). Previously the subqueries inherited the paginated window,
  so a cross-span match whose spans fell in different windows was dropped.

- Tests: NOT IN without a flag, sql_ast '!=' + negated search bar, and
  full-range vs windowed subqueries; revert the filtersToQuery flag expectations.

Verified: common-utils build + unit tests (465, snapshots unchanged), app tsc
--noEmit, app unit tests (181), prettier.
@eugeneo17

Copy link
Copy Markdown
Author

Thanks — the latest round exposed real gaps in the exclusion handling plus a separate time-windowing bug. Addressed in the newest commit:

Fixed (critical / correctness):

  • Windowed range dropped cross-span matches — the membership subqueries inherited the paginated time window (useOffsetPaginatedQuery / useChartConfig chunk dateRange), so predicates in spans that fell in different windows never intersected. Added a traceScopeDateRange (the user's full selected range, set when the query is chunked) and pinned every membership subquery to it; the outer query still uses the window.
  • Negation was derived from a flag saved searches/URLs don't carry — removed the negated flag (the "second source of truth") from the schema, filtersToQuery, and its tests. Negation is now derived from the condition at render time (isNegatedFilterCondition): the sidebar's col NOT IN (...), a sql_ast !=, and a single-negation search bar (Lucene -/NOT, SQL !=). Detected negations are applied to the outer WHERE instead of a membership subquery, so exclusions from saved searches and older URLs are handled too.

Added tests for NOT IN without a marker, sql_ast != + a negated search bar, and full-range-vs-windowed subqueries. Verified locally: common-utils build + unit tests (snapshots unchanged), app tsc --noEmit, app unit tests, prettier.

Replying rather than patching (surrounding code / would widen the PR):

  • Scope control unreachable when the filter sidebar is collapsed — moving the control out of the collapsible sidebar into the query toolbar is a layout change to code this PR doesn't otherwise touch. Happy to do it, but flagging as a follow-up so this PR stays scoped — let me know if you'd prefer it here.
  • Trace scope labels rows as traces while the count/rows are spans — this is the intended MVP behavior (the result set is the spans of matching traces); rethinking it as a trace-level result view is a larger design change worth its own discussion.
  • A mixed positive+negative search bar (e.g. frontend -api in one box) still goes through the membership path for the whole expression; only a single-negation search bar is routed out. Documented as a known limitation of this iteration.

Minors noted (banner duplication, SEARCH_SCOPE_PARAM DRY, the constant-only assertions, independent filtersScope/traceIdExpression optionals) — can fold them in if you'd like, otherwise I'll leave them to keep the diff focused.

This is now several fix rounds of automated feedback, so per the contributing guide I'll pause here and defer the remaining scope calls to a maintainer. (Still looking for a vouch to get into the review queue.)

Comment on lines +17 to +35
await test.step('Select the traces data source', async () => {
await searchPage.selectSource(DEFAULT_TRACES_SOURCE_NAME);
});

await test.step('Scope defaults to span and both options are reachable', async () => {
await expect(searchPage.searchScopeControl).toBeVisible();
await expect(searchPage.spanScopeOption).toBeChecked();
await expect(searchPage.traceScopeOption).toBeEnabled();
});

await test.step('Switch to trace scope and run the search', async () => {
await searchPage.timePicker.selectRelativeTime('Last 1 days');
await searchPage.selectTraceScope();
await expect(searchPage.traceScopeOption).toBeChecked();
await searchPage.performSearch('');
});

await test.step('The results header reports the trace scope', async () => {
await expect(searchPage.resultScopeIndicator).toBeVisible();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test steps narrate actions

These test.step labels repeat routine actions and assertions already clear from the code, such as selecting the source and checking the result badge. The same pattern appears again in the second test at lines 40–52. Repository guidance requires test bodies not to narrate each straightforward step, so this requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Conductor Fix in Cursor Fix in Codex

# Conflicts:
#	packages/common-utils/src/types.ts
): boolean {
const c = (condition ?? '').trim();
if (!c) return false;
if (/\b(AND|OR)\b/i.test(c)) return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — isNegatedFilterCondition matches AND/OR inside string literals, so exclusions stop excluding at trace scope

/\b(AND|OR)\b/i is tested against the raw condition including quoted values, and it is case-insensitive. Exclude a facet value containing the word "and"/"or" — e.g. ServiceName NOT IN ('search-and-index') or a Body value 'connection refused or timeout', both produced verbatim by filtersToQuery (packages/common-utils/src/filters.ts:93) — and the guard returns false, so the exclusion is treated as positive and wrapped as TraceId IN (SELECT TraceId ... WHERE ServiceName NOT IN ('search-and-index')), which is true for essentially every multi-span trace: the exclusion silently does nothing. The mirror-image false positive is /!=|<>/ matching inside a literal, which demotes a positive predicate to the outer WHERE. filters.ts already solves exactly this with quote- and paren-aware helpers — containsOutsideQuotes(part, [' NOT IN ']) (line 261), containsOperatorOutsideQuotes (line 304) and the top-level AND splitter in extractInClauses (line 377) — or use parseQuery's excluded set; export and reuse those instead of new regexes.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

// Positive predicates become existential trace-membership tests ("a trace
// matches when *some* span satisfies the predicate"), AND-ed together so a
// trace must satisfy each across (possibly different) spans.
const membershipPredicates = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — A search-bar query with a top-level AND stays same-span under Trace scope, with no indication

chartConfig.where is always treated as one predicate, so with Trace selected, typing ServiceName:"api" AND SpanName:"checkout" renders a single membership subquery containing both terms — i.e. the exact span-scope result the feature exists to avoid — while the badge still reports "Scope: Trace". Split the search bar on top-level AND into separate membership predicates (the quote/paren-aware splitter in packages/common-utils/src/filters.ts:377 already does this), or surface the limitation next to the scope control so the user knows to split the terms into filters.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

{ label: 'Trace', value: 'trace', disabled: !traceApplicable },
]}
/>
{!traceApplicable && (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — "Trace scope isn't available for this source" flashes while the source is still loading

source is undefined until useSource (line 1196) resolves, so traceApplicable is false and the control renders the disabled Trace option plus the unavailability reason on every mount and source switch, even for a trace source. Gate both on the source having resolved: {source && !traceApplicable && (...)} and disabled: !source || !traceApplicable — matching the guard the useEffect above already uses.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

});
});

describe('result-scope surface states', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The result-scope surface states tests assert on markup the test itself renders, and the rest of the file duplicates existing tests

Both tests build their own <span aria-label={getScopeIndicatorLabel('trace')}> / <div>{getTraceZeroEmptyDescription()}</div> and then assert that string is present — they would pass if DBSearchPage never rendered the badge or never passed noResultsMessage to the table. The six SearchScopeControl tests above them repeat assertions already made in DBSearchPageFilters.test.tsx (radiogroup, disabled reason, aria-describedby, arrow-key switching). Replace the two surface-state tests with a render of DBSearchPage (or extract the badge/empty-state wiring into a component that can be rendered) asserting the badge appears only when traceScopeActive, and drop the duplicated control tests — no current test covers the page wiring, which is where the reset() bug above lives.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
return scope === 'trace' ? 'trace' : 'span';
}

export const SEARCH_SCOPE_PARAM = parseAsStringEnum<SearchScope>([

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The scope enum is restated twice despite SearchScopeSchema being introduced as the single source of truth

SEARCH_SCOPE_PARAM hardcodes ['span', 'trace'] and resolveSearchScope hardcodes the 'trace' literal, so adding a third scope needs three edits and the type annotation is the only thing keeping them aligned. Derive both: parseAsStringEnum<SearchScope>(SearchScopeSchema.options) and SearchScopeSchema.catch('span').parse(scope).

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
'trace',
]);

export function getScopeIndicatorLabel(scope: SearchScope): string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — getScopeIndicatorLabel's span branch is unreachable in product code

All three call sites pass the literal 'trace' (the badge at line 2685 and the error alert at line 2746 both render only when traceScopeActive), so the 'Scope: Span' branch exists only for its own unit test. Make it a TRACE_SCOPE_BADGE_LABEL constant (and likewise getTraceZeroEmptyDescription, a zero-argument function returning a literal), or render the span label somewhere so the parameter earns its keep.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

} from '@/DBSearchPage';

jest.mock('@/layout', () => ({
withAppNav: (component: any) => component,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Wrapper mock uses any

The new withAppNav mock declares its component parameter as any. This violates the repository directive to use proper TypeScript types instead of any, so the requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Conductor Fix in Cursor Fix in Codex

aria-label="Search scope"
aria-describedby={!traceApplicable ? reasonId : undefined}
value={scopeValue}
onChange={scope => onChange(scope as SearchScope)}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Scope value bypasses narrowing

The callback force-casts every string from the control to SearchScope without validating or narrowing it. This violates the repository directive to avoid as casts when proper typing or narrowing can preserve the type, so the requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Conductor Fix in Cursor Fix in Codex

Comment on lines +739 to +753
} as unknown as TSource;

const logSource = {
id: 'log-src',
kind: SourceKind.Log,
name: 'Logs',
connection: 'conn',
from: { databaseName: 'db', tableName: 'otel_logs' },
timestampValueExpression: 'Timestamp',
} as unknown as TSource;

const traceSourceNoExpr = {
...traceSource,
traceIdExpression: ' ',
} as unknown as TSource;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Fixtures bypass source typing

The new trace and log fixtures use as unknown as TSource, bypassing type checking instead of constructing typed fixtures. The accessibility test repeats this at packages/app/src/components/__tests__/SearchScopeControl.a11y.test.tsx:19-28. This violates the repository directive to avoid casts when possible, so the requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Conductor Fix in Cursor Fix in Codex

}
// SQL: the deterministic sidebar exclusion (`col NOT IN (...)`), a leading
// `NOT`, or a single `!=` / `<>` comparison.
return /^NOT\s/i.test(c) || /\bNOT\s+IN\b/i.test(c) || /!=|<>/.test(c);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Regex negation detection misfires on literals containing !=, <> or NOT IN, silently demoting a positive predicate out of the cross-span rewrite

/!=|<>/ and /\bNOT\s+IN\b/i are tested against the whole condition string, including string literals. A positive predicate such as Body LIKE '%exit != 0%' or a facet value SpanAttributes['msg'] IN ('a <> b') is classified as negated, so it lands in exclusionConditions (outer WHERE) instead of a membership subquery — trace scope silently returns span-scope results for that predicate, with no error. The include/exclude intent already exists structurally where the condition is built (filtersToQuery in packages/common-utils/src/filters.ts derives NOT IN from the excluded set), so carry it on the Filter (defaulting the regex path only for legacy saved searches) rather than re-deriving it from SQL text; at minimum strip quoted literals before matching.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

const traceApplicable = traceScope?.applicable ?? false;
const reasonId = useId();

useEffect(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The fail-closed reset lives in a component that is unmounted when the filter sidebar is collapsed

DBSearchPage renders DBSearchPageFilters only when !isFilterSidebarCollapsed (a persisted localStorage preference, DBSearchPage.tsx:2548), so the "reset to Span on source switch" invariant the PR advertises — and the only control for the feature — disappear with the sidebar. A shared ?searchScope=trace URL opened with the sidebar collapsed runs trace-scoped with a Trace badge and no way to change it. Move the reset effect to DBSearchPage, next to the state it owns (it already has inputSourceObj and resolveTraceScope), so it holds regardless of sidebar state.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

});
});

describe('result-scope surface states', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The result-scope surface states tests assert on JSX the test itself renders, not on product code

Both cases render a local <span aria-label={getScopeIndicatorLabel('trace')}> / <div>{getTraceZeroEmptyDescription()}</div> and then assert the string is present — they pass no matter what DBSearchPage does with the badge, noResultsMessage, or traceScopeActive. Combined with DBSearchPage.searchScope.test.tsx, which only exercises the string helpers and the zod schema, nothing covers the page wiring (which is why the reset() regression above is invisible). Extract the badge/empty-state into a small component and assert against that, or render DBSearchPage and assert the badge appears only when the source exposes a trace-id expression.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

});
const membershipSubqueries = membershipPredicates.map(
predicate =>
chSql`${tid} IN (SELECT ${tid} FROM ${from} WHERE ${concatChSql(' AND ', predicate, membershipTimeFilter)})`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Each pagination window re-executes one full-range membership scan per predicate

membershipTimeFilter deliberately pins the subqueries to traceScopeDateRange (the user's full range) while the outer query is windowed, and useOffsetPaginatedQuery issues a fresh query per window/offset — so a 30-day, 3-predicate trace search re-scans the full 30 days three times for every page fetched, with no dedup (ClickHouse cannot share the subqueries across statements). Consider computing the trace-id set once in a WITH CTE intersected across predicates (as renderSeriesLimitCte does for the series cap) so the per-page cost is one CTE reference.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
{hasQueryError && queryError ? (
<>
<div className="h-100 w-100 px-4 mt-4 align-items-center justify-content-center text-muted overflow-auto">
<Alert

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The new "Query failed / this is not a zero-result" alert and Retry button fire for every search error, not just trace scope

The Alert is rendered whenever hasQueryError, so a plain Lucene/SQL syntax error on a log source now gets trace-scope framing ("so this is not a zero-result") stacked above the existing error panel that already shows the inputs and the ClickHouse message. Gate it on traceScopeActive (the only case the copy is about) or drop it; also note onSubmit() here defaults recordExploration to true, so a retry counts as a genuine user search for the onboarding task.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
return scope === 'trace' ? 'trace' : 'span';
}

export const SEARCH_SCOPE_PARAM = parseAsStringEnum<SearchScope>([

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The span/trace value set is restated three times in one file despite the canonical zod enum

SearchScopeSchema is imported, then the same two values are re-listed for parseAsStringEnum([...]) and re-implemented as a ternary in resolveSearchScope. Adding a third scope later requires editing all three. Use parseAsStringEnum<SearchScope>(SearchScopeSchema.options) and SearchScopeSchema.catch('span').parse(scope) so the enum stays the single source of truth.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread packages/app/src/DBSearchPage.tsx Outdated
'trace',
]);

export function getScopeIndicatorLabel(scope: SearchScope): string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — getScopeIndicatorLabel's span branch is unreachable

All three call sites pass the literal 'trace' (badge text, badge aria-label, error-alert suffix); nothing renders a "Scope: Span" indicator. The parameter and its false branch exist only for the @AC-FR004-03 test, which therefore pins dead code. Make it a constant (e.g. TRACE_SCOPE_INDICATOR_LABEL) and drop that test, or add the span indicator the branch implies.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

@eugeneo17

Copy link
Copy Markdown
Author

Thanks @greptile — triaged the findings against the current head (9d2df50). Several were raised on an earlier revision and are already resolved; grouping them below.

Already addressed in the current head

  • Form resets lose Trace scope (DBSearchPage.tsx): the useForm values now include searchScope: resolveSearchScope(searchedConfig.searchScope), so the URL-to-form sync keeps the scope.
  • The result-scope badge and the trace zero-result empty state are present on the page.

Confirmed and will fix

  • Saved searches lose Trace scope: correct — SavedSearchSchema has no searchScope field, so a saved Trace search reloads as Span and an alert built from it evaluates Span. I'll add searchScope to the schema, the save/load paths, and the alert query builder.
  • Retry disappears for span-scope errors: I'll restore the Retry action on the non-trace error path.
  • Source changes retain Trace scope: I'll move the reset so it runs on any source change, independent of the sidebar/control.

Will validate on a running instance before changing the query builder (correctness-sensitive, I don't want to patch these blind):

  • Invalid trace IDs correlate (renderChartConfig.ts) — exclude empty/all-zero IDs from the membership subqueries and outer results.
  • Delta loses cross-span matches (DBDeltaChart.tsx) — keep the delta queries' population consistent with the heatmap under Trace scope.
  • Quoted operators / negated exclusions (renderChartConfig.ts) — the compound-expression and negated handling for saved searches.

Style/convention (semantic theme colors vs raw Mantine palette, scope-label casing, any/as casts in tests, verbose test.step labels, file size): I'll align these with the repo's lint rules in the same pass.

I'll push the schema/UX fixes and follow up on the query-builder items after validating them locally. Appreciate the detailed review!

…House#3004)

Address review feedback on the trace-scope search PR:

- Persist searchScope on saved searches: add the field to SavedSearchSchema
  and wire it through the create/update mutations and the saved-search load
  path, so a saved Trace search reloads as Trace (and alerts built from it
  evaluate Trace) instead of silently falling back to Span.
- Restore a Retry action on span-scope query errors: the error alert was
  gated behind traceScopeActive, leaving span errors with no retry. Always
  render it inside the error branch and keep the trace-specific wording
  conditional.
- Narrow the SearchScopeControl onChange value instead of casting the raw
  string with 'as SearchScope'.
- Type the withAppNav test mock generically instead of 'any'.

Signed-off-by: Eugene Olkhovski <eugeneo@cloudgeometry.com>
@eugeneo17
eugeneo17 requested a review from a team as a code owner November 5, 2026 15:40
@eugeneo17
eugeneo17 requested a review from karl-power November 5, 2026 15:40
@eugeneo17

Copy link
Copy Markdown
Author

Pushed 66e5410 addressing the review. Per-item status:

Fixed

  • Saved searches lose Trace scope (P1): added searchScope to SavedSearchSchema and wired it through the create/update mutations and the saved-search load path, so a saved Trace search reloads as Trace (and an alert built from it evaluates Trace) instead of falling back to Span.
  • Retry disappears for span errors (P2): the "Query failed" alert and its Retry button now render for both scopes inside the error branch; only the trace-specific wording stays conditional on traceScopeActive.
  • Scope value bypasses narrowing (P2): SearchScopeControl onChange now narrows the segmented-control string instead of casting with as SearchScope.
  • Wrapper mock uses any (P2): the withAppNav test mock is now a generic pass-through (<T,>(component: T): T) rather than any.

Already in the current head

  • Form resets lose Trace scope: the useForm values already include searchScope: resolveSearchScope(...), so the URL-to-form sync keeps the scope.

Keeping as-is (replying per your note)

  • Source changes retain Trace scope: the control fail-closes to Span when a source can't support Trace, and re-applies on sidebar expand. Switching between two trace-capable sources intentionally keeps Trace. Happy to change if maintainers prefer a hard reset-to-Span on every source change.
  • Palette colors / scope-label casing: this file already uses raw Mantine colors (e.g. color="gray") and title-case labels in adjacent UI, so these match the file's existing conventions. Glad to move to semantic tokens if that's a confirmed project-wide rule.
  • as unknown as TSource test fixtures: intentional partial fixtures for focused tests; a fully-typed TSource would add noise without extra coverage.

Deferred pending validation on a running instance (correctness-sensitive ClickHouse query-builder changes I don't want to land unverified):

  • Invalid trace IDs correlate (renderChartConfig) — exclude empty/all-zero IDs.
  • Delta loses cross-span matches (DBDeltaChart) — align the delta population with the heatmap under Trace scope.
  • Quoted operators / negated exclusions become existential (renderChartConfig).
    I'll verify these against ClickHouse locally and follow up.

@jordan-simonovski — the above fixes are pushed; this is ready for another look when you have a moment, and I'll follow up on the three query-builder items after local validation. Thanks!

alerts: z.array(AlertSchema).optional(),
// Persist the span-vs-trace search scope so a saved Trace search reloads as
// Trace (and alerts built from it evaluate Trace), not Span.
searchScope: SearchScopeSchema.optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Saved searches never persist searchScope: the Mongoose model has no field for it

SavedSearchSchema now accepts searchScope, but the Mongoose schema in packages/api/src/models/savedSearch.ts (around lines 51-61) has no searchScope path. Mongoose's default strict mode drops unknown fields, so searchScope is lost on create and update, and toJSON (around line 87) never returns it. A saved Trace search reloads as Span. Fix: add searchScope: String to the schema and to toJSON/ISavedSearch, and add an API test that saves searchScope: 'trace' and reads it back.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

orderBy: z.string().optional(),
filters: z.array(FilterSchema).optional(),
alerts: z.array(AlertSchema).optional(),
// Persist the span-vs-trace search scope so a saved Trace search reloads as

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Alerts on a Trace saved search still evaluate at span scope, despite the comment saying they evaluate Trace

getChartConfigFromAlert in packages/api/src/tasks/checkAlerts/index.ts:801 and AlertPreviewChart.tsx:91 call buildSearchChartConfig without searchScope. So even once the field is persisted, a Trace saved search alerts on same-span AND and fires differently from what the user saw. Pass searchScope: savedSearch.searchScope in both places, or remove the claim from the comment.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

// the box", and `indexHint` (always 1) into a match on every trace — breaking
// the delta. Strip the scope so every delta query stays span-scoped; the
// user's search predicates still apply, just at span granularity.
const baseConfig = useMemo(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Delta chart drops trace scope, so cross-span searches show an empty or wrong delta under a trace-scoped heatmap

The heatmap renders the trace-scoped result (all spans of the matching traces). This strip runs the user's predicates at span scope instead. For A AND B where A and B are in different spans, the delta's outlier, inlier and all-spans queries return 0 rows while the heatmap shows data. Fix: keep the user's predicates as trace-membership conditions, for example by pre-rendering them or passing them separately from the delta's own range/indexHint filters, and apply only the delta-internal predicates at span level.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond

// so an excluded value genuinely disappears from the results. Negation is
// derived from the condition at render time, so exclusions from saved
// searches / older URLs (which carry no marker) are handled too.
const exclusionConditions = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Exclusions in Trace scope filter rows, not traces, so traces containing the excluded value still match

With SpanName = 'checkout' and ServiceName NOT IN ('cart'), a trace with a checkout span and a cart span still matches. Only the cart rows are hidden. That contradicts the trace-level meaning the scope badge claims. Fix: render negated predicates as TraceId NOT IN (SELECT TraceId ... WHERE <positive form> AND <time>), or document in the UI that exclusions stay at span level.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

}
}

const membershipSubqueries = membershipPredicates.map(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 major — Membership subqueries cannot see the outer query's SELECT aliases, so filters on aliases likely break in Trace scope (not verified against ClickHouse)

In span scope, a filter or search on a select alias (for example SpanAttributes['x'] AS foo with foo:1) resolves because ClickHouse lets WHERE reference SELECT aliases. The row table does not pass alias WITH clauses (dbSqlRowTableConfig in DBSearchPage.tsx:1877). So the new SELECT TraceId FROM t WHERE (foo = 1) subquery should fail with an unknown identifier, even though the histogram works because it passes with: aliasWith. I did not run this query. Fix: emit the alias map as WITH clauses for the trace-scope path, or render the subquery predicates with aliases expanded.

Nothing blocks merge automatically, but a maintainer will expect this fixed if it is a real defect in code this PR changes. If it is about surrounding code, reply and say so instead of patching. Do not widen the PR. How to respond


useEffect(() => {
// Only fall back to span once the source has actually resolved. While it is
// still loading (`source` undefined), `traceApplicable` is false, and

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Scope reset on source switch only runs while the filters sidebar is mounted

The reset to span is a useEffect inside SearchScopeControl. That control is only mounted when the sidebar is open and queryReady is true. If the user collapses the sidebar, switches to a log source and searches, searchScope=trace stays in the URL and the form, and gets persisted on save. Fix: move the reset into the existing source-change handler in DBSearchPage.tsx (around line 1559, next to setValue('select', '')) and keep the control presentational.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

// The search-level `searchScope` maps onto the chart-config `filtersScope`,
// which is how `renderChartConfig` refers to the same span-vs-trace choice.
...(input.searchScope ? { filtersScope: input.searchScope } : {}),
...(traceScope.applicable

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — traceIdExpression is attached to every trace search config, even in span scope

Every trace-source config now carries traceIdExpression, whatever the scope. That is why DBDeltaChart has to strip it, and it contradicts the alertChartConfig.ts comment that it is 'absent on ordinary (span-scope) alerts'. A span config that carries it is classified as lossy and unrepresentable. Only set it when input.searchScope === 'trace' && traceScope.applicable.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

});

describe('result-scope surface states', () => {
it('@AC-FR004-01 labels a trace-scoped result header with the trace scope', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The 'result-scope surface states' tests render their own markup, so they test nothing from the app

These tests render a hand-written <span>/<div> around the helper strings. They would still pass if DBSearchPage never showed the badge or never passed noResultsMessage. Together with the trivial helper tests in DBSearchPage.searchScope.test.tsx, nothing covers the URL/form → buildSearchChartConfig wiring, saved-search persistence, or the source-switch reset. Replace them with tests that render the real result header and table, or one that asserts filtersScope reaches the chart config.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Resolve conflicts from upstream's filter/theme refactor:

- searchChartConfig.ts: keep the trace-scope resolution (resolveTraceScope)
  and adopt upstream's getSourceTableFilters() helper, which is identical
  to the inline logs tableFilter this branch had.
- DBSearchPageFilters.test.tsx: keep both the SearchScopeControl import and
  describe block (this branch) and the getFilterGroupDefaultExpanded import
  and describe block (upstream).

common-utils type-check clean; 3172 common-utils tests pass.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
@eugeneo17
eugeneo17 requested a review from a team as a code owner November 11, 2026 13:06
Comment thread packages/app/src/DBSearchPage.tsx Resolved
Comment thread packages/app/src/DBSearchPage.tsx Resolved
…d alerts (ClickHouse#3004)

- Include searchScope in the URL-to-form reset so the control does not
  fall back to Span after every search.
- Declare searchScope on the SavedSearch Mongoose schema; strict mode was
  dropping it, so a saved Trace search reloaded as Span.
- Pass the saved search scope to the scheduled alert task, the alert
  preview chart, and the saved search created from the alert modal.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
Comment thread packages/common-utils/src/types.ts Resolved
// source isn't confirmed local — a CTE source, a missing database/table, or
// a failed lookup — so trace scope never emits an `IN` a clustered
// deployment rejects.
let membershipInOperator = 'GLOBAL IN';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — The IN vs GLOBAL IN choice now exists twice, once in app and once in common-utils

DBDeltaChart.tsx (around line 137) already picks IN or GLOBAL IN from getTableMetadata(...).isPointerTable and falls back to GLOBAL IN on failure. This block repeats that logic in renderChartConfig. Fix: move it into one common-utils helper, e.g. resolveMembershipInOperator(metadata, from, connection, with), and use it from both places.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one: the IN / GLOBAL IN choice in DBDeltaChart predates this PR, so hoisting both into a shared helper would widen the change. Happy to do it as a follow-up if a maintainer wants it.

Comment thread packages/app/src/DBSearchPage.tsx Resolved
Comment thread packages/app/src/DBSearchPage.tsx Resolved
@eugeneo17

Copy link
Copy Markdown
Author

Synced with the latest main (clean merge) and addressed the three major findings from the 11 Nov automated review in 8aa2c35:

  • History sync dropped Trace scope: the URL to form reset() now carries searchScope, so the control no longer falls back to Span after a search.
  • Saved searches lost Trace scope: searchScope is now declared on the SavedSearch Mongoose schema (strict mode was dropping it), with a model unit test.
  • Alerts ignored the scope: the scheduled alert task, the alert preview chart and the saved search created from the alert modal now pass searchScope through.

The remaining automated items are either documented MVP limits (mixed negations at Trace scope, AND-only composition) or would widen the PR (DBDeltaChart population, External API v2 exposure of searchScope). Per the repo guidance I'd rather leave those to a maintainer's call than keep iterating on bot findings. Happy to take any of them here or as a follow-up.

@karl-power, could you take a look when you have a moment? The only red checks are the Vercel preview deploys, which need a team member to authorize for a fork, and the CI workflows are waiting for approval.

Resolve two conflicts: the trace-scope badge and the new RED/Heatmap control now sit side by side in the results toolbar, and DBSearchPageFilters.test.tsx keeps the imports its searchScope tests use (dropping UseQueryResult, which main's fromPartial mocks replaced).

Adapt the trace-scope tests to main's typed mocks: DBDeltaChart.test.tsx reads each call through getBuilderConfig, and renderChartConfig.test.ts builds its trace configs as BuilderChartConfigWithOptDateRange.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
Comment thread packages/app/src/DBSearchPage.tsx Resolved
- Exclusions: classify a predicate as an exclusion from its parsed AST, so a
  compound of exclusions (`-a -b`, `A != x AND B != y`) stays on the outer
  WHERE instead of becoming a membership subquery that stops excluding. Lucene
  now uses the search-bar parser; the hand-written tokenizer is gone.
- Delta chart: keep the search trace-scoped so it compares the same population
  as the heatmap, and send only the delta's own predicates (selection box,
  aggregate timestamps, indexHint) to the new runtime-only
  traceScopeOuterFilters, which renderWhere never folds into membership.
- aggConditions stay an outer-row index hint under trace scope instead of a
  redundant full-range membership subquery.
- filtersScope / traceIdExpression move out of the persisted chart-config
  schema into the runtime-only DateRange fields, so tiles and tile alerts
  cannot store them; the KNOWN_LOSSY_CONFIG_KEYS entries are no longer needed.
- Chunked queries only carry traceScopeDateRange when trace-scoped, leaving
  other configs unchanged.
- Drop the extra "Query failed" alert and its Retry; the existing error panel
  covers every scope.
- Derive the scope helpers and the Mongoose enum from SearchScopeSchema and
  move them to src/searchScope.ts; the indicator label and trace-zero copy are
  constants, with page-level tests for the badge and empty state replacing the
  tests that rendered their own markup.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
@eugeneo17

Copy link
Copy Markdown
Author

Pushed 0fd3c03c addressing the 11 and 17 Nov automated findings, plus the 23 Nov one:

  • Exclusions under trace scope: negation is classified from the parsed AST (lucene via the search-bar parser, tokenizer removed), and a compound of exclusions (-a -b, A != x AND B != y) now stays on the outer WHERE.
  • Delta chart: keeps the search trace-scoped so it matches the heatmap; only its own selection-box / timestamp / indexHint filters go to a new runtime-only traceScopeOuterFilters that never enters membership subqueries.
  • Persisted schema: filtersScope / traceIdExpression are runtime-only now (out of _ChartConfigSchema, KNOWN_LOSSY_CONFIG_KEYS change reverted), and chunked queries only carry traceScopeDateRange when trace-scoped.
  • UI: the extra "Query failed" alert and Retry are gone; scope helpers and the Mongoose enum derive from SearchScopeSchema, with page-level tests for the badge and the trace-zero empty state.

The one finding left open is the IN / GLOBAL IN dedupe, since that logic predates this PR. Local runs: common-utils 3489 tests, app 5875 (one timezone test only times out under full-suite load and passes on its own), tsc clean for app, api and common-utils.

@karl-power this has now been through several bot rounds, so per AGENTS.md I'll stop iterating on automated findings here. Could you take a look at the overall scope when you have a moment?

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
@github-actions

Copy link
Copy Markdown
Contributor

No description provided.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>

# Conflicts:
#	packages/common-utils/src/__tests__/renderChartConfig.test.ts
…t casts

Mantine's SegmentedControl hides its radio inputs, so the trace-scope e2e steps now click the option label. The scope control tests build typed sources with satisfies instead of as unknown as TSource, bringing the app oxlint count back under the ceiling.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

type: String,
enum: SearchScopeSchema.options,
required: false,
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

External saved search drops scope

Low Severity

toExternalJSON and the MCP save payload never include searchScope, even though the Mongoose model and SavedSearchSchema now persist it. MCP get/save and any other toExternalJSON consumer omit the field, so a Trace saved search round-trips as Span through those APIs.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c7ac108. Configure here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 46fd39b. toExternalJSON now returns searchScope (documented on the SavedSearch response schema), so the external API and MCP get/save report a Trace search as Trace. The MCP save tool accepts an optional searchScope; omitted on update it keeps the stored value, like whereLanguage and filters. Covered by the new case in models/__tests__/savedSearch.test.ts.

@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical (P0/P1) issues found. The default Span path is provably unchanged (span-scope snapshot test is untouched), and every finding below sits inside the new, opt-in Trace scope. The feature is fail-closed (gated on a trace source with a trace-id expression), SQL injection surface is unchanged (user predicates reuse the existing parameterized path; only the admin-configured trace-id expression and a hardcoded IN/GLOBAL IN literal use the raw channel), and persistence through saved searches / MCP / external API / alerts is additive and backward-compatible. The P2s are correctness edge cases and cost/coverage gaps worth addressing before or shortly after merge.

🟡 P2 -- recommended

  • packages/common-utils/src/core/renderChartConfig.ts:1510 -- A dash-prefixed, parenthesized Lucene exclusion (-ServiceName:(cart OR api)) is classified positive because the group's leading - lives on the group node's field, which classifyLuceneNode only inspects on leaf terms, so it leaks into a membership subquery and returns nearly all traces instead of excluding; the equivalent NOT ... spelling is handled correctly.
    • Fix: In classifyLuceneNode, flip the whole group's classification when the parenthesized group node's field starts with -, mirroring the serializer's isNegatedAndParenthesized.
    • correctness
  • packages/common-utils/src/core/renderChartConfig.ts:1882 -- Membership subqueries intersect on the raw trace-id with no empty/all-zero guard, so spans sharing a blank or zero trace-id (orphaned/no-context spans) can satisfy separate predicates and falsely match as one trace; the exemplar trace path already guards this with notEmpty(...).
    • Fix: Add a non-empty/non-zero guard on the trace-id expression in both the membership subqueries and the outer rows.
    • adversarial, previous-comments, testing
  • packages/api/src/tasks/checkAlerts/index.ts:883 -- A trace-scoped saved search drives a count() alert whose outer WHERE reduces to time AND TraceId IN (SELECT ...), so the alert counts every sibling span of each matching trace (and double-counts traces straddling granularity buckets) rather than matching events, silently shifting thresholds carried over from span scope.
    • Fix: For the count/alert path under trace scope, count distinct matching traces (or keep the predicate on the outer rows), and document the trace-scoped alert semantics.
    • adversarial, correctness, reliability, testing
  • packages/common-utils/src/core/renderChartConfig.ts:1806 -- A single search-bar expression mixing inclusion and exclusion (frontend -api) is classified as one positive predicate, so the exclusion is wrapped inside the existential subquery and only applies per-span; traces with api in other spans are not excluded, yielding results that visibly contain the excluded term with no UI signal.
    • Fix: Split mixed predicates so the positive part drives membership and the exclusion applies to outer rows, or surface the limitation in the Trace-scope UI copy.
    • adversarial, correctness
  • packages/common-utils/src/core/renderChartConfig.ts:1880 -- Each positive predicate becomes its own full-range TraceId GLOBAL IN (SELECT TraceId ... ) subquery with no LIMIT, re-executed on every paginated page (the outer window shrinks but traceScopeDateRange stays full), giving a P×N full-range-scan blow-up and broadcasting unbounded trace-id sets across a cluster.
    • Fix: Materialize the membership trace-id set once per search and reuse it across pages (shared CTE / query cache), and bound cluster memory via explicit settings on the subqueries.
    • performance, reliability
  • packages/app/src/hooks/useOffsetPaginatedQuery.tsx:253 -- The new trace-scope windowing branch that pins traceScopeDateRange to the full range on the paginated results-table path (the primary way users view trace-scope results) has zero test coverage, while only the sibling useChartConfig path is tested -- a regression dropping the pinned range would silently drop cross-window matches with green tests.
    • Fix: Add a test asserting every windowed config on this path carries traceScopeDateRange === the full dateRange for trace scope and omits it otherwise.
    • testing
🔵 P3 nitpicks (10)
  • packages/common-utils/src/core/renderChartConfig.ts:1888 -- The trace branch AND-composes positive filters as separate membership subqueries and never consults filtersLogicalOperator, so a future caller setting both filtersScope:'trace' and OR would silently get AND; not reachable today because buildSearchChartConfig never sets an OR operator.
    • Fix: Guard or fold filtersLogicalOperator === 'OR' into a single OR'd membership subquery so the combination cannot silently collapse later.
  • packages/app/src/components/DBSearchPageFilters.tsx:1164 -- The fail-closed scope reset lives inside SearchScopeControl, which unmounts when the desktop filter sidebar is collapsed, and the page's source-switch effect never resets searchScope, so a stale trace value can persist across a source switch; render-time gating fail-closes to span so results are not corrupted, only the stored scope is stale.
    • Fix: Lift the reset-to-span into the page, keyed on the resolved source's trace applicability, independent of sidebar mount state.
    • julik-frontend-races, previous-comments
  • packages/common-utils/src/types.ts:2133 -- Four runtime-only trace fields (filtersScope, traceIdExpression, traceScopeOuterFilters, traceScopeDateRange) are flattened onto the DateRange type, two of which have nothing to do with a date range, so every DateRange consumer transitively depends on trace-scope concepts.
    • Fix: Group the trace-scope runtime fields into a dedicated sub-type intersected alongside DateRange.
  • packages/common-utils/src/core/searchChartConfig.ts:204 -- The same span-vs-trace concept is named searchScope (input/URL/saved search), filtersScope (chart config), and traceScope* (runtime fields), reconciled only at a single one-line mapping, so a reader grepping searchScope in renderWhere finds nothing.
    • Fix: Unify on one name across layers, keeping the traceScope* prefix only for genuinely trace-specific derived fields.
  • packages/common-utils/src/types.ts:3114 -- TraceScopeResolution.reason ('non-trace-source' | 'missing-trace-id-expression') is read only in tests; all production callers use .applicable, and the UI shows one hardcoded unavailable message.
    • Fix: Consume reason in the control's unavailable tooltip, or collapse the non-applicable case to { applicable: false }.
  • packages/common-utils/src/core/renderChartConfig.ts:1744 -- The aggCondition OR-group (wrapChSqlIfNotEmpty(concatChSql(' OR ', selectSearchConditions), ...)) is expressed twice -- once as aggConditionGroup in the trace branch and once inlined in the span return -- and the traceScopeDateRange chunk assignment is duplicated verbatim across two hooks.
    • Fix: Hoist the aggCondition group to one shared local reused by both return paths.
  • packages/app/src/types.ts:54 -- searchScope is modeled as SearchScope | null in the app but SearchScope | undefined in common-utils/api, forcing a conversion at each boundary; bridged everywhere today but a future call site could forward null into an undefined slot.
    • Fix: Bridge all three-state scope values through resolveSearchScope at entry for a single representation.
  • packages/app/src/DBSearchPageAlertModal.tsx:585 -- The alert-modal saved-search create normalizes scope with ?? undefined while the search page's save path uses resolveSearchScope, so two parallel create paths normalize the same field differently.
    • Fix: Route the alert-modal create through resolveSearchScope for consistency.
  • packages/api/src/routers/external-api/v2/savedSearches.ts:554 -- The external v2 PUT description states every optional field resets when omitted, but searchScope is read-only and silently preserved (absent from the request schema and stripped by zod), creating an undocumented exception a read-modify-write client could misread.
    • Fix: Note in the PUT OpenAPI description that searchScope is read-only and preserved across updates.
  • packages/common-utils/src/core/renderChartConfig.ts:1605 -- The unparseable-SQL fallback /(?:!=|<>)/.test(c) would match a != inside a string literal and misclassify a positive predicate as negated; the effect is safe (predicate moves to the outer WHERE, more filtering, never broken SQL) but imprecise.
    • Fix: Tighten the fallback or accept the safe over-classification and add a test pinning it.

Pre-existing (not introduced by this PR)

  • packages/app/src/components/DBRowTable.tsx:389 -- The file is ~2060 lines, far over the repo's 300-line component limit (CLAUDE.md, agent_docs/code_style.md); this PR adds only an optional noResultsMessage prop (~19 lines) and does not materially worsen it.
    • Fix: Track the split as a separate refactor; do not expand this PR's scope.
    • maintainability, project-standards, previous-comments

Reviewers (12): correctness, adversarial, security, performance, api-contract, reliability, testing, maintainability, project-standards, previous-comments, kieran-typescript, julik-frontend-races.

Testing gaps:

  • Alert path threading searchScope into the trace rewrite (checkAlerts, AlertPreviewChart) has no test -- a refactor dropping the field would silently revert trace-scoped alerts to span.
  • isNegatedFilterCondition unparseable-SQL and unparseable-Lucene fallback branches are never exercised (all suite cases parse successfully).
  • No test for empty/all-zero TraceId correlation, nor for dash-prefixed grouped Lucene exclusions.
  • GLOBAL IN selection via CTE source / missing database-table / null metadata is uncovered (only pointer-table, lookup-throw, and local-table are tested).
  • traceScopeActive fail-closed negative (badge and trace-zero empty state suppressed on a non-applicable source) is not asserted.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

toExternalJSON now returns searchScope, so the external API and the MCP get/save tools no longer report a Trace saved search as Span. The MCP save tool accepts an optional searchScope; omitted on update it keeps the stored value, like whereLanguage and filters.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
Other badges in the app take the theme's default colors; a raw Mantine palette color is not theme-aware.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
@eugeneo17

Copy link
Copy Markdown
Author

Thanks for the review. The Bugbot finding is fixed in 46fd39b and the badge nit in 3237b50. The other Deep Review P2/P3 items are answered below. I kept them out of this PR so it doesn't grow further.

Bugbot, external saved search drops scope: fixed in 46fd39b.

  • toExternalJSON now returns searchScope, and the field is documented on the SavedSearch response schema in openapi.json. A Trace saved search therefore reads as Trace through the external API and through MCP get/save.
  • The MCP save tool accepts an optional searchScope. When it is omitted on update, the stored value is kept, the same as whereLanguage and filters.
  • The external v2 PUT body is unchanged. It doesn't touch the field, so a PUT keeps the stored scope.

Deep Review P2:

  • Empty or all-zero trace IDs: spans without a trace ID can indeed share one membership key. Trace scope is only offered for trace sources, where every span carries a trace ID, so in practice this needs malformed data. A guard changes the SQL of every membership subquery and its snapshots. I'd rather do that as a follow-up than in this PR.
  • Negation classified with the Postgres dialect: this is a known limit of the shared SQL parser. When parsing fails, the fallback only recognises the sidebar's own exclusion shapes (NOT IN, !=, <>), so a hand-written ClickHouse-only negated form is the residual case. Classifying with a ClickHouse grammar is a parser change outside this feature.
  • Mixed inclusion and exclusion in one search-bar expression: this is the documented MVP behavior. Splitting a single expression into terms is the follow-up the docs describe.

Deep Review P3:

  • Reset effect inside SearchScopeControl: with the sidebar collapsed, a stale trace value can remain. Execution falls back to span there, so nothing breaks, and lifting the effect to the page is a small follow-up.
  • color="blue" badge: fixed in 3237b50. It now takes the theme default like the other badges in the app.
  • Structural AST types: the parser versions are pinned in the lockfile, and the classification tests in renderChartConfig.test.ts exercise representative ASTs, so a shape change surfaces there.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>

# Conflicts:
#	packages/api/src/models/savedSearch.ts
#	packages/common-utils/src/types.ts
- A dash-prefixed Lucene group (-field:(a OR b)) is classified as an exclusion; the parser keeps its dash on the group's field.
- The unparseable-SQL fallback also recognises NOT LIKE, NOT ILIKE and NOT BETWEEN, matching SQL_NEGATION_OPERATORS.
- Alert notification sample lines and the alert detail chart use the saved search's searchScope, like the alert evaluation.

Signed-off-by: CloudGeometry: Eugene Olkhovski <eugeneo@cloudgeometry.com>
@eugeneo17

Copy link
Copy Markdown
Author

The main conflicts are resolved in add04c2: defaultTimeRange and searchScope sit side by side in the model and the schema. This review round is addressed in b68924a.

Fixed:

  • Lucene negation (deep-review P2): -ServiceName:(cart OR api) is now classified as an exclusion. The parser keeps the group's - on the group's field, so classifyLuceneNode flips the whole group when the field starts with -. This now behaves the same as the NOT ... spelling.
  • SQL fallback (claude-review P2): when the parser rejects a predicate, the fallback also recognises NOT LIKE, NOT ILIKE and NOT BETWEEN, matching SQL_NEGATION_OPERATORS. The tests use ::String casts, which the Postgres-dialect parser actually rejects, so they exercise the fallback.
  • Alert samples and alert detail chart (claude-review P2, two items): fetchSampleLines and AlertDetailChart now pass the saved search's searchScope, so both use the same scope as the alert evaluation.

Not changed:

  • Inclusive membership bounds (claude-review P2): this is intentional. traceScopeDateRange is set only by the windowed hooks. Their chunk configs mark every window except the first as end-exclusive, so copying a chunk's flags would cut the end of the full range for those chunks. When the field is absent, as in alerts, the outer timeFilter is reused, and the two bounds are identical.
  • Trace-scoped count() alerts (deep-review P2): under trace scope the outer rows are the spans of matching traces, so the alert counts spans, not matching traces. That is a semantics choice: count spans, or count distinct matching traces. I'd rather a maintainer decide it than pick one here.
  • Follow-ups (deep-review P2): the empty trace-id guard, mixed include/exclude expressions in the search bar, reusing the membership set across pages, and a test for the useOffsetPaginatedQuery windowing branch. Each is either a known MVP limit or a widening of this PR. Details are in my previous comment.
  • P3 nitpicks: left as they are.

The automated reviews have reported no P0/P1 for several rounds now. Per AGENTS.md I'm stopping on automated findings here. Could a maintainer review the scope and say which of the remaining items should land in this PR and which should be follow-ups?

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit b68924a. Configure here.

// `-field:(a OR b)`: the parser keeps the group's `-` on its field rather
// than on the terms inside, so it negates the group as a whole.
return node.field?.startsWith('-') ? flipNegation(result) : result;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grouped lucene dashes skip exclusion rewrite

Medium Severity

classifyLuceneNode only treats a non-leaf as negated when start is NOT or field begins with -. It ignores prefix and a start of - on grouped nodes, so queries like -(ServiceName:cart OR SpanName:api) stay classified as positive. Trace scope then wraps that predicate in a TraceId IN subquery, which makes the exclusion existential and almost every multi-span trace matches.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b68924a. Configure here.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

external needs-vouch Author needs a maintainer to vouch for them

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] Trace-level AND search across spans

2 participants