Repository navigation
O(1) Prometheus-backed statistics rework and 4-tab dashboard - #928
Conversation
Sashiko's existing statistics endpoints execute full-table scans across messages, patchsets, patches, reviews, and findings, while operational SRE signals, bug security facets, maintainer revision fixup metrics, and per-stage pipeline telemetry inside compressed review maps are either untracked or unqueryable in bounded time. Document the architecture for reworking Sashiko statistics around four bounded O(1) storage layers (lock-free runtime counters and histograms, trigger-maintained state and subsystem gauges, multi-resolution SQLite time-series rollups, and pre-extracted pipeline summaries), exposed through Prometheus /metrics and /api/v1 query endpoints that power a four-tab web UI (Operational, Bugs, Maintainers, and Pipeline) while preserving BugAccess and patchset embargo boundaries. Signed-off-by: Roman Gushchin <roman@kernel.org>
Sashiko reviewCommit 2/15 —
|
Operational signals such as warning and error rates by component, LLM request and review latencies, worker supervision restarts, git remote freshness, NNTP lag, and outbound delivery outcomes had no structured runtime storage or Prometheus exposition format. Expand the metrics module with bounded domain enums, fixed-bucket lock-free histograms, two-phase rollup delta snapshotting, and Prometheus text 0.0.4 serialization. Wire a zero-allocation tracing MetricsLayer in logging initialization and record unexpected exits and panics in supervised worker loops. Signed-off-by: Roman Gushchin <roman@kernel.org>
Computing live counts for messages, patchsets, reviews, outboxes, and bugs required scanning application tables on read or in periodic background polls, and per-subsystem bug counts joined bugs against bug_subsystems on every request. Add schema migration 024 introducing stats_state_gauges, stats_bug_section_links, stats_bug_subsystem_facets, stats_series, stats_rollups, and review_pipeline_stats. Seed live state gauges from covering indexes, record table high-water marks in meta for asynchronous rollup backfilling, install SQLite triggers keeping gauges and BugAccess-scoped subsystem facets exact on writes, and switch MetricsWorker message and patchset counts to O(1) gauge lookups. Signed-off-by: Roman Gushchin <roman@kernel.org>
|
Addressed all 6 findings from
Re-verified with |
871e7a4 to
09f4bbd
Compare
Sashiko review — v2Commit 4/15 —
|
|
Addressed both v2 findings from
Re-verified with |
09f4bbd to
6b9e9c8
Compare
Sashiko review — v3Commit 4/15 —
|
6b9e9c8 to
80bc475
Compare
|
Addressed both v3 findings from
Re-verified with |
Sashiko review — v4Commit 4/15 —
|
Connect runtime worker pipelines, review completion, and historical upgrade backfill to the O(1) statistics rollups and summary tables: - Add db::pipeline_stats to extract per-review stage attribution, pairwise stage overlap, concern-to-finding dismissal funnel counts, tool aggregates, and prior-feedback recall metrics into review_pipeline_stats, with single-pass multi-window aggregation over the latest 100, 500, and 1000 completed non-inherited reviews. - Add worker::stats_backfill to populate historical time-series rollups and the latest 1000 review_pipeline_stats rows in bounded, resumable chunks below the migration high-water marks stored in meta. - Wire AI request latency, error classification, prompt cache hits, inflight concurrency, quota cooldowns, git fetch/repack/baseline durations, remote freshness, NNTP lag, outbox outcomes, ingestion rollups, and embargo-safe patchset release rollups. - Extend MetricsWorker with two-phase 60-second rollup delta flushes, hourly retention pruning, and a final shutdown flush. Signed-off-by: Roman Gushchin <roman@kernel.org>
Expose a Prometheus-compatible telemetry surface backed exclusively by
Sashiko's O(1) SQLite rollups, live state gauges, pipeline summaries,
and lock-free runtime atomics:
- Add promql with a bounded recursive-descent parser and evaluator
supporting instant/range selectors, regex label matchers, offset
modifiers, increase/rate/sum_over_time/avg_over_time/max_over_time,
sum/avg/min/max/count with by/without grouping, topk, clamp_min,
histogram_quantile, and binary vector/scalar arithmetic.
- Add prom_api serving GET /metrics (Prometheus text 0.0.4) and
GET/POST /api/v1/query, /api/v1/query_range, /api/v1/labels,
/api/v1/label/{name}/values, and /api/v1/metadata, folding unflushed
in-memory counter deltas into live range queries.
- Enforce Principal and BugVisibility scoping on
sashiko_bugs_by_subsystem and subsystem label enumeration, and add
optional constant-time server.metrics_token bearer authentication
scoped strictly to /metrics with Debug secret masking and
configuration documentation.
- Re-point legacy /api/stats/{timeline,reviews,tools} queries to O(1)
rollups, state gauges, and primary-key-bounded lookups so no stats
endpoint scans unbounded history.
Signed-off-by: Roman Gushchin <roman@kernel.org>
Replace the legacy single-page statistics view in static/index.html with four persona-focused tabs backed directly by Sashiko's O(1) Prometheus HTTP API (/api/v1/query, /api/v1/query_range, and /api/v1/label/subsystem/values): - Operational (#/stats/ops): 1h and 24h SRE telemetry with automatic comparisons against 7d/30d averages and 7d-offset baselines covering message ingestion, NNTP lag, git tree freshness, warnings/errors by component, worker restarts, p50/p90/p99 latencies, LLM token burn, cache hit rates, quota cooldowns, and outbox delivery outcomes. - Bugs Database (#/stats/bugs): lifecycle totals, 12-week discovery and fix velocity, CVSS v4.0 security rating and security_class stacked breakdowns, engineering severity, reproducer/fix attachment coverage, and BugAccess-scoped per-subsystem facets. - Maintainers (#/stats/maintainers): 4w/12w/26w patchset and patch throughput, v1 vs v2+ revision mix, clean series rate, findings per patchset/patch by severity, prior-feedback author fixups split by Sashiko vs human reviewers, skipped unchanged patches, and optional public subsystem filtering. - Pipeline (#/stats/pipeline): Last 100/500/1000 review summaries with verification dismissal funnel, total vs exclusive stage discoveries, 2D pairwise stage overlap heatmap, stage token ROI table, tool usage, and human-reviewer recall alignment. - Document /metrics, /api/v1/*, and the 4-tab UI in docs/daemon.md. Signed-off-by: Roman Gushchin <roman@kernel.org>
Optimize Prometheus query latency on large production databases and add upstream release timestamp markers: - Add POST /api/v1/query_batch (capped at 64 queries, 64 KiB body) so dashboard tabs load in a single HTTP round-trip instead of fanning out dozens of concurrent HTTP/1.1 requests. - Add Database::query_rollup_sums_filtered to push interior-bucket SUM(value) GROUP BY series_id aggregation into SQLite for instant increase/rate/sum_over_time queries while keeping exact edge weighting. - Cache state gauges (5s), unrestricted bug subsystem facets (15s), pipeline stats (60s), and recent target-repo release tags (1h) in AppState, exposing sashiko_project_release_timestamp_seconds. Signed-off-by: Roman Gushchin <roman@kernel.org>
Rework the 4-tab statistics view in static/index.html and update docs/daemon.md to match Sashiko's native monospace UI and keep only actionable metrics per audience: - Remove white stat cards, shadowed chart boxes, and the /metrics link; render summaries as plain Sashiko tables with one metric per row and charts directly on the page background. - Rename tabs to Health, Bugs, Project, and Pipeline (preserving ops and maintainers hash aliases) and load each tab via a single POST /api/v1/query_batch call. - Align range queries to UTC boundaries for exact integer buckets, add upstream release date vertical markers on weekly trend charts, split automated_bot from sashiko_review fixups, and restrict subsystem views to strictly subsystem-scoped metrics. Signed-off-by: Roman Gushchin <roman@kernel.org>
Add per-remote staleness telemetry for git trees and historical rollup backfill for email_outbox so ongoing service health monitoring has both stale tree details and outgoing email volume baselines: - Publish sashiko_git_remote_stale_age_seconds (labeled by remote, state, and sanitized URL) from refresh_remote_freshness_metrics and expose it via /metrics and the PromQL HTTP API. - Sanitize remote URLs in sanitize_git_remote_url so credentials, query parameters, fragments, and local filesystem paths never appear in public metrics. - Backfill historical terminal email_outbox rows into sashiko_outbox_events_total in StatsBackfill, guarded by stats_backfill:skip_email_outbox:<id> for rows that were Pending or Sending during migration 023. Signed-off-by: Roman Gushchin <roman@kernel.org>
Extend per-subsystem bug facets with a rolling 60-day fixed count and
record clean vs dirty patch review rollups:
- Populate fixed_60d on BugSubsystemFacetSummary via an indexed
stats_bug_section_links join scoped strictly to the caller's
authorized subsystems and expose sashiko_bugs_by_subsystem{facet=
"fixed_60d"} in prom_api.
- Record sashiko_patches_reviewed_total{clean="true"|"false"} in
record_single_patchset_release_in_tx (respecting embargo release)
and add an incremental backfill pass for already-migrated databases.
Signed-off-by: Roman Gushchin <roman@kernel.org>
Update the 4 statistics tabs in static/index.html and docs/daemon.md based on live production data review: - Health: add Outgoing Emails summary row (sent, pending, failed, total sent, and 7d/30d baselines), Outgoing Emails bar chart, and a Stale Git Trees table at the bottom listing non-fresh remotes with state, age, and sanitized URL. - Bugs: switch Weekly Discovery vs Fixes to a two-line chart and plot Open vs Fixed (60d) on Subsystems with Most Open Bugs (keeping Fixed All in the subsystem table). - Project: add Clean Patches alongside Clean Patchsets and clarify the v2+ prior review findings row with per-source fix rates and fractions. - Pipeline: align the verification funnel with active Stage-1 concerns now that Stage-1 self-dismissals are excluded from dismissed_1b. Signed-off-by: Roman Gushchin <roman@kernel.org>
Profiled live queries against a 63 GiB production database and fixed three latency bottlenecks on the Bugs and Project tabs: - Remove the chunked IN (...) filter on the fixed_60d bug facet join in get_bug_subsystem_facets_o1, add partial covering index idx_bugs_fixed_updated on bugs(updated_at, id) WHERE lifecycle_status = 'fixed', and attach counts in Rust strictly to the caller's already-authorized subsystems (zero bugs table lookups). - Add covering indexes idx_stats_rollups_cover and idx_stats_bug_subsys_cover in migration 023 (and ensure them idempotently on startup) so rollup sums and subsystem facet scans never fetch table pages. - Route weekly and longer rollup windows (>= 7d) to the 1d rollup tier in select_resolution_tier, replace chunked series_id IN (...) and OR edge queries in query_rollup_sums_filtered with a single stats_series JOIN pass, and cache unfiltered rollup sums and unrestricted bug facets for 60s. Signed-off-by: Roman Gushchin <roman@kernel.org>
Update static/index.html and docs/daemon.md: - Reorder statistics tabs to Project -> Bugs -> Health -> Pipeline and make Project the default #/stats tab. - Project tab: plot weekly Clean Patches % and Clean Patchsets % with upstream release date markers, and extend window options to 4w, 12w, 26w, 52w, and All (trimming leading stray/empty weeks and scaling weekly averages to the active span). - Bugs tab: switch the first line chart to cumulative Open vs Fixed counts anchored to current open/fixed totals (excluding duplicates and dismissed bugs), and add a 12w/26w/52w/All window selector. Signed-off-by: Roman Gushchin <roman@kernel.org>
Add layered rate limiting, concurrency shedding, caching, and query
complexity bounds across all Prometheus and legacy stats endpoints
(/metrics, /api/v1/*, /api/stats*):
- StatsApiGuard middleware: per-IP token bucket (burst 30, 2 req/s,
bounded 4096-IP table with idle eviction), global token bucket
(burst 120, 20 req/s), 8-permit non-blocking in-flight concurrency
cap (503 Service Unavailable), and 5s per-request timeout (504).
Per-IP tokens are checked before debiting the global bucket so a
single flooding client cannot starve other IPs, and proxy headers
(rightmost X-Forwarded-For / X-Real-IP) are only trusted from
loopback/private peers.
- PromQL & batch bounds: enforce MAX_AST_NODES (64),
MAX_MATCHERS_PER_SELECTOR (16), MAX_RANGE_POINTS (400),
MAX_BATCH_QUERIES (40), MAX_BATCH_EVAL_POINTS (2400),
MAX_RESULT_SAMPLES (25000), MAX_PRELOADED_ROLLUP_ROWS (50000), and
16 KiB body limits on /api/v1/query, /api/v1/query_range, and
/api/v1/labels.
- O(log N) range evaluation & cache-bust resistance: sort preloaded
rollup buckets by bucket_ts and binary-search per step, align rollup
cache keys to bucket boundaries, add bounded singleflight caches for
range buckets, backfill completion, label values, public subsystems,
and /api/stats/timeline, and restrict /api/v1/label/{name}/values to
the static label allowlist.
Signed-off-by: Roman Gushchin <roman@kernel.org>
Add version-bucketed reviewed-patch and patch-finding rollups so the Project statistics view can track defect density normalized by patch volume across initial submissions (v1) and follow-up revisions (v2+): - Record sashiko_patches_reviewed_by_version_total and sashiko_findings_by_version_total (labeled by version_bucket, excluding preexisting findings) on patchset release and in an idempotent incremental backfill guarded per patchset by stats_rollup:ps_ver_issues_done:<id>. - Register both counters in DB_METRIC_CATALOG. - Project tab: promote Issues / Patch in the summary table with v1 vs v2+ breakdown and add a weekly Issues per Patch by Revision (v1 vs v2+ and All) line chart with upstream release date markers. Signed-off-by: Roman Gushchin <roman@kernel.org>
80bc475 to
e3f2b1e
Compare
|
Addressed both v4 findings from
Re-verified with |
Sashiko review — v5✓ No issues found across 15 commits. |
Summary
Reworks Sashiko's telemetry, database statistics layer, HTTP API, and Web UI (
#/stats) into an O(1) Prometheus-backed architecture designed to stay sub-100ms even on multi-gigabyte production databases.Architecture & Storage
designs/DESIGN_STATISTICS_REWORK.mdsrc/metrics.rs,src/logging.rs): Atomic runtime counters, gauges, and histograms (sashiko_messages_ingested_total,sashiko_reviews_completed_total,sashiko_ai_tokens_total,sashiko_git_remotes,sashiko_git_remote_stale_age_seconds,sashiko_nntp_lag_articles, etc.) plus a tracing layer counting warnings/errors by level and component.src/migrations/024_stats_rollups.sql,src/db/stats_queries.rs): Addsstats_state_gauges,stats_bug_section_links,stats_bug_subsystem_facets,stats_series,stats_rollups(5m/1h/1dretention tiers with covering indexesidx_stats_rollups_cover,idx_stats_bug_subsys_cover,idx_bugs_fixed_updated), andreview_pipeline_stats. Keeps live gauges andBugAccess-scoped subsystem facets exact via SQLite triggers.src/worker/stats_backfill.rs,src/db/pipeline_stats.rs): Backfills historical rollups,email_outboxoutcomes, clean patch counts, versioned issues/patch (v1vsv2+), and the last 1,000 non-inherited review pipeline summaries idempotently with per-entity guards.Prometheus API & Anti-DDoS Hardening
src/prom_api.rs,src/promql.rs,src/server.rs):GET /metrics(Prometheus0.0.4text format, optionalmetrics_tokenBearer auth)GET|POST /api/v1/query,/api/v1/query_range,POST /api/v1/query_batchGET|POST /api/v1/labels,GET /api/v1/label/{name}/values,GET /api/v1/metadataStatsApiGuard):30burst,2/s, bounded 4,096-IP table with idle eviction), global token bucket (120burst,20/s, debited only after per-IP check),8-permit non-blocking in-flight semaphore (503),5stimeout (504), proxy-safe IP extraction, and 16–64 KiB body limits.MAX_AST_NODES = 64,MAX_MATCHERS_PER_SELECTOR = 16,MAX_RANGE_POINTS = 400,MAX_BATCH_QUERIES = 40,MAX_BATCH_EVAL_POINTS = 2400,MAX_RESULT_SAMPLES = 25000,MAX_PRELOADED_ROLLUP_ROWS = 50000), O(log N) binary-search range evaluation, bucket-aligned singleflight caches, and static label allowlist.4-Tab Statistics Dashboard (
static/index.html,docs/daemon.md)Reordered to Project → Bugs → Health → Pipeline in flat Sashiko-native monospace tables + ECharts:
#/stats/project, default):4w | 12w | 26w | 52w | Allwindows + mailing list filter, upstream release date markers, weekly patchsets (v1vsv2+) & patches, Issues / Patch (v1vsv2+and All) trend, Clean Patches & Patchsets per Week (%), issues by severity, v2+ prior-feedback fixup breakdown (Sashiko reviews,Human reviewers,Other bots (LKP/CI)), and mailing list volume/density table.#/stats/bugs):12w | 26w | 52w | Allcumulative Open vs Fixed trend (excluding duplicates/dismissed) with release markers, Engineering vs CVSS v4.0 severity chart, andBugAccess-scoped top subsystems (OpenvsFixed (60d)+Fixed (All)).#/stats/health):1h | 24hwindows with7d/30dbaselines — queue backlog, ingestion vs 7d ago, review outcomes, outgoing email delivery, errors/warnings, stale git trees table, and LLM token burn + prompt cache hit rate.#/stats/pipeline): Last100 | 500 | 1000non-inherited reviews — active-concern verification funnel and dismissal rate (excluding Stage-1 self-dismissals), final outcomes (patch findings + pre-existing bugs), exclusive stage catches, 2D stage × stage overlap heatmap, stage precision & token ROI, and tool usage.Verification
make check-pr RANGE=origin/main..HEAD(DCO sign-offs,cargo fmt,clippyacross all feature profiles, full unit + integration test suite)sashiko review --project sashiko --agentself-review (status: "clean",0findings)Project (All)258ms cold / 29ms warm;Bugs (All)48ms cold / 14ms warm;Health/Pipeline< 20ms)