Skip to content

refactor: simplify pass across the codebase - #518

Merged
vishr merged 4 commits into
mainfrom
refactor/simplify-pass
Nov 25, 2026
Merged

vishr merged 4 commits into
mainfrom
refactor/simplify-pass

Conversation

@vishr

@vishr vishr commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Behavior-preserving cleanups from a reuse, simplification, efficiency, and altitude review of the whole tree.

  • engine/telemetry: reuse per-signal source lists in cacheBatches; allocate scan buffers once in forAffectedKeys; one multi-row version_rollup_batches insert; remove the snapshotSource pass-through; share summaryRelations, scopePredicate, telemetry.SyncDirectory, and openParquet; use ParquetStore path helpers.
  • query/pitotql: scan destinations allocated once per frame; resultCache.leave and requestTime replace duplicated blocks; variables hashed once per check; capProblems, sqlString, query.Grouped, and maps/slices replace hand-rolled copies.
  • api/mcp/ingest/alert/dashboard: alert rule lookups wrap ErrNotFound and callers use errors.Is; DeleteRule is :execrows with no pre-read; shared recordRequestAudit, ingest resourceIdentity, and detector readWindowAnomalies; dashboard Get runs ensureInitial only on a miss; OAuth user lookups use the request context, so the unused UserStore.GetByID is removed.
  • ui/site: shared servicesQuery, telemetrySchemaQuery, dashboardKey, and dashboardVersionsKey; endRun, layoutOf, useWindowHeight, measureText, seriesOf, and copy-button components replace duplicates; one htmlFiles module for the site check scripts.

Observable differences: a rule-delete database failure reads store: delete rule: … without (pre-check), and a cancelled MCP request now cancels its user lookup.

Left out on purpose: map-based ingest attribute lookup, batching alert lookups per tick, and returning the answer-only flag from StartRun. Each changes edge-case behavior or reaches well beyond a local cleanup.

Caching changes found in the review (pitotql vocabulary cache, single MCP body decode, engine view SQL built at init, chat memoization) are left out pending local benchmarks.

Test plan

  • just test
  • just lint, just go-deadcode, just test-names-check, gofmt
  • readbench/filebench compile
  • ui/host: lint (tsc), knip, just ui-boundaries-check, vitest (1790 tests)
  • site check-canonical, check-social-card, check-tables
  • CI Gate (ui-check, site build, e2e)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of missing alert rules so they’re consistently reported as not found.
    • Corrected dashboard loading behavior when a requested dashboard is unavailable.
    • Improved query-time validation and cancellation handling.
    • Standardized service identity and namespace handling during telemetry ingestion.
    • Improved query diagnostics, including clearer notices when results are limited.
  • Improvements

    • Dashboard charts and service maps now share text measurement, and labels display singular or plural forms correctly.
    • Alert forms and service search use consistent service data.
    • Telemetry processing and file operations include performance and reliability improvements.

Behavior-preserving cleanups from a reuse, simplification, efficiency,
and altitude review of the whole tree.

- engine/telemetry: build each signal's column SQL once, reuse cached
  source lists, batch version-rollup inserts, drop the snapshotSource
  pass-through, and share path, sync, scope, and Parquet-open helpers.
- query/pitotql: hoist scan destinations, share flight-leave and
  request-time helpers, cache vocabulary lookups per compile, hash
  variables once per check, and reuse existing quoting and grouping.
- api/mcp/ingest/alert: decode each MCP body once, use ErrNotFound
  instead of string matching, delete rules in one query, share audit,
  ingest resource, and detector helpers, and pass request contexts to
  user lookups (removing the unused UserStore.GetByID).
- ui/site: memoize chat derivations, share query and cache-key
  definitions, and dedupe teardown, layout, text-measure, copy-button,
  and HTML-walk helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

Walkthrough

Changes: Alert not-found handling

Layer / File(s) Summary
Not-found errors from alert storage and API
internal/alert/store.go, internal/db/queries/rules.sql, internal/api/alerts.go
Rule reads and replacements wrap ErrNotFound. Deletion uses affected-row counts, and API handlers return 404 when errors match the sentinel.
Email rule lookup
internal/alert/email.go
stillAddressed identifies missing rules by matching ErrNotFound instead of searching error text.

User lookup and request auditing

Layer / File(s) Summary
Context-aware user lookups
internal/auth/user_store.go, internal/api/*.go, internal/auth/user_store_test.go
UserStore replaces GetByID with GetByIDContext. API callers and tests pass request or test contexts to user lookups.
Shared request audit writes
internal/api/auth.go, internal/api/auth_middleware.go, internal/api/oidc.go
Authentication, authorization-denial, and OIDC audit events use recordRequestAudit instead of direct detached-context writes.

Dashboard owner and lookup handling

Layer / File(s) Summary
Owner validation and initial dashboard fallback
internal/dashboard/service.go
Service.Get returns successful and non-not-found lookup results directly. requireOwner provides the shared blank-owner check.

Engine query and batch processing

Layer / File(s) Summary
Version-rollup batch markers
internal/engine/annotations.go, internal/engine/annotation_maintenance_test.go
Pending version-rollup markers use one multi-row insert, and the test expects both batch markers in that statement.
Cached sources and scan buffers
internal/engine/batch_cache.go, internal/engine/duck.go, internal/engine/edge_pass_test.go
Batch source queries and scan buffers are reused. A shared scope predicate is added, and edge-pass SQL setup is moved to the test.
Physical Parquet sources and scoped queries
internal/engine/file_snapshot.go, internal/engine/file_snapshot_*, internal/engine/resource_inventory.go, internal/engine/trace_exemplars.go
Snapshot, inventory, and exemplar query paths use physicalSource and shared scope predicates. Tests and benchmarks use the updated source selection.

Ingestion identity and anomaly queries

Layer / File(s) Summary
Shared resource identity extraction
internal/ingest/server.go
Trace, log, and metric exports use resourceIdentity to decode attributes and apply the default namespace.
Shared anomaly window queries
internal/intelligence/detector.go
Error-rate, latency, and volume detectors use readWindowAnomalies for timestamp conversion, namespace scoping, SQL construction, and row retrieval.

MCP request and fragment processing

Layer / File(s) Summary
Fragment overrides and SQL literals
internal/mcp/fragments.go, internal/mcp/server.go
Dashboard normalization follows time and comparison overrides. Fragment filters and trace predicates use sqlLiteral; MIME-type membership uses slices.Contains.

Query-language completion and validation

Layer / File(s) Summary
Completion keys and field quoting
internal/pitotql/complete.go, internal/pitotql/print.go, internal/pitotql/resolve.go
Completion keys use standard map and slice helpers. Keyed fields use sqlString.
Diagnostic formatting and limits
internal/pitotql/format.go, internal/pitotql/pitotql.go, internal/pitotql/resolve.go, internal/query/diagnose.go
Problem lists are capped through capProblems. Query diagnostics use Grouped and sqlString for displayed counts and literal checks.
Query memo keys and filter validation
internal/query/check.go
Checks hash variables once, reuse the hash in memo keys, and prepare sample scope before filter validation.
Time validation and result processing
internal/query/validate.go, internal/query/exec.go, internal/query/exemplars.go, internal/query/filter.go, internal/query/frame.go, internal/query/result_cache.go, internal/query/shape.go
Run and exemplar requests share requestTime. Array extraction checks field types first, frame scanning reuses destinations, and cache cleanup shares waiter-release logic.

Parquet access and directory syncing

Layer / File(s) Summary
Shared Parquet and directory helpers
internal/telemetry/parquet.go
openParquet opens files using their current size, and SyncDirectory provides the shared directory-sync operation.
Parquet reader call sites
internal/telemetry/footer_cache.go, internal/telemetry/log_index.go, internal/telemetry/order.go, internal/telemetry/parquet_merge.go, internal/telemetry/verify.go
Footer, log-index, order, merge, and verification paths use openParquet instead of separately statting files.
Directory sync call sites
internal/telemetry/parquet.go, internal/telemetry/retire.go, internal/telemetry/store/*
Batch publication, retirement, compaction, repair, and cleanup paths use telemetry.SyncDirectory.

Shared HTML file discovery

Layer / File(s) Summary
Shared HTML traversal
site/scripts/html-files.mjs, site/scripts/check-canonical.mjs, site/scripts/check-social-card.mjs, site/scripts/check-tables.mjs, scripts/site-tables.test.ts
htmlFiles collects HTML paths recursively. The canonical, social-card, and table checks import it instead of defining local traversals.

Host UI shared query options

Layer / File(s) Summary
Shared services query
ui/host/src/alerts/api.ts, ui/host/src/alerts/rule-form.tsx, ui/host/src/rail.tsx
servicesQuery centralizes the services request and is used by the alert rule form and service rail.
Shared telemetry-schema query
ui/host/src/dashboards/api.ts, ui/host/src/explore/page.tsx, ui/host/src/explore/search-page.tsx
telemetrySchemaQuery centralizes schema query options for the explore page and search page.

Dashboard host UI

Layer / File(s) Summary
Dashboard query keys and cache updates
ui/host/src/dashboards/api.ts, ui/host/src/dashboards/grid.tsx, ui/host/src/dashboards/history.tsx, ui/host/src/dashboards/page.tsx, ui/host/src/dashboards/panel-editor.tsx, ui/host/src/explore/save-dialog.tsx
Dashboard key helpers replace inline query keys in dashboard, history, editor, and save-dialog cache operations.
Shared layout and text measurement
ui/host/src/dashboards/layout.ts, ui/host/src/dashboards/grid.tsx, ui/host/src/dashboards/measure-text.ts
useWindowHeight tracks window height, shared text-measurement helpers reuse a canvas context, and grid layout construction is extracted into layoutOf.
Dashboard visualization helpers
ui/host/src/dashboards/echart-canvas.tsx, ui/host/src/dashboards/fragment-view.tsx, ui/host/src/dashboards/panel-card.tsx, ui/host/src/dashboards/viz/*
Charts, panels, and visualizations reuse series, measurement, and pluralization helpers. FragmentView uses shared window-height tracking.

Host run termination

Layer / File(s) Summary
Shared run termination
ui/host/src/app.tsx
Run errors, failures, exceptions, and explicit stops delegate state updates to endRun. Dashboard updates use shared dashboard query keys.

Host UI component updates

Layer / File(s) Summary
Chat formatting
ui/host/src/chat.tsx
Chat rendering uses shared plural, clock, and numeric-cell formatting, including numeric values with whitespace before supported unit suffixes.
Telemetry copy controls
ui/host/src/connect-telemetry.tsx
Field and configuration copy interactions are extracted into CopyIconButton and CopyConfigButton and used in connection displays.

Role membership checks

Layer / File(s) Summary
Role and capability membership
cmd/pitot-docgen/roles.go
Role checks use slices.Contains, and the local contains helper is removed.

Host API type cleanup

Layer / File(s) Summary
Remove Envelope type
ui/host/src/api.ts
The exported Envelope type alias is removed.

Change: Refactor

Security architecture risk: Minimal · up to 8c829

The changes reviewed did not show broader access, weaker authorization, or a loss of protection against partial writes. The principal behavior changes are that cancelled requests can stop identity lookups, dashboard reads initialize defaults only on a miss, and alert deletion reports whether a row was actually removed.

Retained concerns
No architecture-level concerns identified.

Security review details

Trust Boundaries and Controls

  • observed — MCP token verification now uses a cancellable lookup for the user ID recorded on the token. Lookup errors still stop verification, and the existing user and scope checks still precede issuance of authenticated identity to the handler.
  • observed — The trace tool still uses the selected trace ID in the same equality filter. The extracted literal helper preserves the base revision's quoting and quote-doubling behavior.
  • observed — Alert deletion still runs behind the manage permission and targets the same rule ID. The removed pre-read detected absence; it did not authorize the delete.
Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

ast-grep (0.51.3)

internal/mcp/apps/panels.html

ast-grep timed out on this file

Review coverage is incomplete: 1 file could not be fully reviewed. Findings from completed review steps are included; see review info for details.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 8169279d-0f36-4416-bee3-b5214a32094e
Commits

Reviewing files that changed from the base of the PR and between b06005a and 8c82946.

Files ignored due to path filters: 39

  • internal/ui/dist/assets/alerts-B7Kt5DXx.js is excluded by !**/dist/**
  • internal/ui/dist/assets/alerts-DTGcaFaK.js is excluded by !**/dist/**
  • internal/ui/dist/assets/chat-C3pUUpyK.js is excluded by !**/dist/**
  • internal/ui/dist/assets/chat-Dss3MKkH.js is excluded by !**/dist/**
  • internal/ui/dist/assets/chat._threadId-C2nVKtcm.js is excluded by !**/dist/**
  • internal/ui/dist/assets/chat._threadId-lpbmAvms.js is excluded by !**/dist/**
  • internal/ui/dist/assets/chat.index-C2nVKtcm.js is excluded by !**/dist/**
  • internal/ui/dist/assets/chat.index-lpbmAvms.js is excluded by !**/dist/**
  • internal/ui/dist/assets/dashboards._dashboardId-DufysEmV.js is excluded by !**/dist/**
  • internal/ui/dist/assets/dashboards.index-Dxg8QJBs.js is excluded by !**/dist/**
  • internal/ui/dist/assets/explore-CCjeo0G7.js is excluded by !**/dist/**
  • internal/ui/dist/assets/index-Bh2RZhek.js is excluded by !**/dist/**, !**/assets/index-[0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-].js
  • internal/ui/dist/assets/index-IsfUlUQn.js is excluded by !**/dist/**, !**/assets/index-[0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-][0-9a-z_-].js
  • internal/ui/dist/assets/live-data-meta-BsOjL82f.js is excluded by !**/dist/**
  • internal/ui/dist/assets/logs-C7DnGEjv.js is excluded by !**/dist/**
  • internal/ui/dist/assets/mcp-app-frame-B5FuBNjO.js is excluded by !**/dist/**
  • internal/ui/dist/assets/mcp-app-frame-BLXY9W6a.js is excluded by !**/dist/**
  • internal/ui/dist/assets/new-dashboard-kgL9TPS9.js is excluded by !**/dist/**
  • internal/ui/dist/assets/page-BEXaHHh2.js is excluded by !**/dist/**
  • internal/ui/dist/assets/page-CQ8fKOlc.js is excluded by !**/dist/**
  • internal/ui/dist/assets/page-Dzzxn2dx.js is excluded by !**/dist/**
  • internal/ui/dist/assets/panel-editor-CAph3o0V.js is excluded by !**/dist/**
  • internal/ui/dist/assets/panel-editor-CLM2HC_e.js is excluded by !**/dist/**
  • internal/ui/dist/assets/save-dialog-CDzpKM22.js is excluded by !**/dist/**
  • internal/ui/dist/assets/save-dialog-CgE7U8ko.js is excluded by !**/dist/**
  • internal/ui/dist/assets/search-DZVuioNG.js is excluded by !**/dist/**
  • internal/ui/dist/assets/search-DcD5ASwS.js is excluded by !**/dist/**
  • internal/ui/dist/assets/search-page-CaWlHYqV.js is excluded by !**/dist/**
  • internal/ui/dist/assets/search-page-DzsFcae4.js is excluded by !**/dist/**
  • internal/ui/dist/assets/settings-CKmdzOKk.js is excluded by !**/dist/**
  • internal/ui/dist/assets/settings-Cw3aQUd4.js is excluded by !**/dist/**
  • internal/ui/dist/assets/settings-D4MyKJ_O.js is excluded by !**/dist/**
  • internal/ui/dist/assets/settings-MaIi3YUS.js is excluded by !**/dist/**
  • internal/ui/dist/assets/settings_.ingest-BXr5E_JD.js is excluded by !**/dist/**
  • internal/ui/dist/assets/settings_.ingest-ByP9luht.js is excluded by !**/dist/**
  • internal/ui/dist/assets/toolbar-B55HiFHT.js is excluded by !**/dist/**
  • internal/ui/dist/assets/traces-Cu6UND8j.js is excluded by !**/dist/**
  • internal/ui/dist/assets/useMutation-CMJQjSPA.js is excluded by !**/dist/**
  • internal/ui/dist/index.html is excluded by !**/dist/**
Files selected for processing: 3

  • internal/mcp/apps/panels.html
  • internal/pitotql/resolve.go
  • ui/host/src/chat.tsx
Files not reviewed because the changes were too large to process: 1

  • internal/mcp/apps/panels.html

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

vishr and others added 3 commits November 25, 2026 07:40
Keep the stop teardown ahead of abortRun, look up the shared canvas
context on each use so replaced getContext implementations are honoured,
and drop an unused import from the site table check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Revert the pitotql vocabulary cache, the remembered MCP body decode, the
precomputed engine view SQL, and the chat page memoization. Each adds
caching machinery whose benefit has not been measured; they move to a
separate change that lands with benchmarks. Rebuild the embedded UI
bundles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vishr
vishr added this pull request to the merge queue Nov 25, 2026
Merged via the queue into main with commit 430b8d0 Nov 25, 2026
33 of 37 checks passed
@vishr
vishr deleted the refactor/simplify-pass branch November 25, 2026 20:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant