Skip to content

O(1) Prometheus-backed statistics rework and 4-tab dashboard - #928

Merged
rgushchin merged 15 commits into
mainfrom
feat/stats-rework
Nov 20, 2026
Merged

rgushchin merged 15 commits into
mainfrom
feat/stats-rework

Conversation

@rgushchin

Copy link
Copy Markdown
Member

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

  • Design doc: designs/DESIGN_STATISTICS_REWORK.md
  • Lock-free runtime telemetry (src/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.
  • Migration 024 (src/migrations/024_stats_rollups.sql, src/db/stats_queries.rs): Adds stats_state_gauges, stats_bug_section_links, stats_bug_subsystem_facets, stats_series, stats_rollups (5m / 1h / 1d retention tiers with covering indexes idx_stats_rollups_cover, idx_stats_bug_subsys_cover, idx_bugs_fixed_updated), and review_pipeline_stats. Keeps live gauges and BugAccess-scoped subsystem facets exact via SQLite triggers.
  • Bounded async backfill & pipeline extractor (src/worker/stats_backfill.rs, src/db/pipeline_stats.rs): Backfills historical rollups, email_outbox outcomes, clean patch counts, versioned issues/patch (v1 vs v2+), and the last 1,000 non-inherited review pipeline summaries idempotently with per-entity guards.

Prometheus API & Anti-DDoS Hardening

  • Endpoints (src/prom_api.rs, src/promql.rs, src/server.rs):
    • GET /metrics (Prometheus 0.0.4 text format, optional metrics_token Bearer auth)
    • GET|POST /api/v1/query, /api/v1/query_range, POST /api/v1/query_batch
    • GET|POST /api/v1/labels, GET /api/v1/label/{name}/values, GET /api/v1/metadata
  • Anti-DDoS & Resource Bounds (StatsApiGuard):
    • Per-IP token bucket (30 burst, 2/s, bounded 4,096-IP table with idle eviction), global token bucket (120 burst, 20/s, debited only after per-IP check), 8-permit non-blocking in-flight semaphore (503), 5s timeout (504), proxy-safe IP extraction, and 16–64 KiB body limits.
    • AST/batch/sample/row bounds (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:

  1. Project (#/stats/project, default): 4w | 12w | 26w | 52w | All windows + mailing list filter, upstream release date markers, weekly patchsets (v1 vs v2+) & patches, Issues / Patch (v1 vs v2+ 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.
  2. Bugs (#/stats/bugs): 12w | 26w | 52w | All cumulative Open vs Fixed trend (excluding duplicates/dismissed) with release markers, Engineering vs CVSS v4.0 severity chart, and BugAccess-scoped top subsystems (Open vs Fixed (60d) + Fixed (All)).
  3. Health (#/stats/health): 1h | 24h windows with 7d / 30d baselines — 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.
  4. Pipeline (#/stats/pipeline): Last 100 | 500 | 1000 non-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, clippy across all feature profiles, full unit + integration test suite)
  • Local sashiko review --project sashiko --agent self-review (status: "clean", 0 findings)
  • Verified live against a 63 GiB production database (Project (All) 258ms cold / 29ms warm; Bugs (All) 48ms cold / 14ms warm; Health / Pipeline < 20ms)

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-bot

sashiko-bot Bot commented Nov 20, 2026

Copy link
Copy Markdown

Sashiko review

Commit 2/15 — 3d8288b5 metrics, logging: add lock-free telemetry registry and tracing layer

  • [LOW] src/metrics.rs: LogComponent::from_target() checks
    rest.starts_with("patch") in the LogComponent::Ingestor branch before
    checking rest.starts_with("patchwork") for LogComponent::Patchwork.
    Warnings and errors logged under sashiko::patchwork match "patch" first and
    are counted under the ingestor component instead of patchwork. Check for
    "patchwork" before "patch", or match exact "patch" and "patch::" prefixes.

Commit 4/15 — 2f18f097 worker, db: wire rollup flushes, pipeline stats, and backfill

  • [MEDIUM] src/db.rs: Database::insert_review_email_outbox() only calls
    record_initial_outbox_outcome() when updating an existing row, omitting it
    after a fresh INSERT. Conversely, Database::insert_patchset_email_outbox()
    calls record_initial_outbox_outcome() on a fresh INSERT, but omits it when
    updating an existing row to a new status. Per-patch review emails inserted
    with status Muted, Skipped, Disabled, Dry-Run, or Embargoed (and patchset
    emails updated in place to a new non-Pending status) are never counted in
    sashiko_outbox_events_total. Call record_initial_outbox_outcome() in both
    missing branches.

  • [LOW] src/db.rs: Database::cancel_aborted_review() narrows its UPDATE filter
    to status IN ('Pending', 'In Review') so it can pass the affected row count
    to metrics::add_reviews_completed(). When Database::cancel_patchset() runs
    first, it already sets reviews.status to 'Cancelled' without populating
    result_description, so the unwinding worker's call to
    cancel_aborted_review() matches zero rows and leaves result_description
    unset. Update result_description even when the row is already 'Cancelled',
    while only incrementing the metric for rows transitioning out of 'Pending'
    or 'In Review'.

  • [LOW] src/db.rs and src/db/stats_queries.rs: widening
    Database::get_releasable_embargoed_patchsets() and
    Database::claim_patchset_embargo_release() to include 'Failed' and 'Failed
    To Apply' causes Reviewer::release_embargoed_results() on upgrade to drain
    historical mailing-list patchsets whose expired embargo_until was never
    cleared. Database::clear_patchset_embargo() then calls
    Database::record_patchset_release_rollups() with event_ts set to the current
    timestamp and writes the stats_rollup:ps_done: guard before
    backfill_patchsets_chunk() reaches them, attributing those historical
    completions to the upgrade timestamp bucket instead of the patchset date.

  • [LOW] src/db.rs and src/db/stats_queries.rs:
    Database::add_subsystem_to_patch() and
    Database::add_subsystem_to_patchset() commit the INSERT OR IGNORE link row
    and release tx_lock before Database::record_subsystem_link_rollup() opens a
    second transaction to compare entity_id against the backfill cursor. If
    backfill_patches_chunk() or backfill_patchsets_chunk() processes that chunk
    between the two transactions, both the backfill chunk and
    record_subsystem_link_rollup() count the same subsystem link. Run the link
    insert and cursor check inside a single transaction.

Commit 9/15 — 553e80a5 metrics, git_ops, prom_api: expose stale git trees and email backfill

  • [LOW] src/worker/stats_backfill.rs: backfill_email_outbox() maps Sent,
    Failed, Muted, and Skipped into sashiko_outbox_events_total, but drops
    Dry-Run and Disabled rows even though
    Database::record_initial_outbox_outcome() in src/db.rs maps Disabled to
    skipped and Dry-Run to dry_run. In addition,
    Database::insert_review_email_outbox() calls
    record_initial_outbox_outcome() only on the existing-row update path and
    omits it when inserting a new per-patch email_outbox row, whereas
    Database::insert_patchset_email_outbox() calls it on new-row inserts and
    omits it on existing-row updates. Map Disabled and Dry-Run in
    backfill_email_outbox() and call record_initial_outbox_outcome() on both
    insert and update paths.

Full review and stage logs on sashiko.sashiko.dev

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>
@rgushchin

Copy link
Copy Markdown
Member Author

Addressed all 6 findings from sashiko-bot and folded each fix (with regression tests) into its introducing commit:

  1. LogComponent::from_target() (src/metrics.rs, 8bffbe2fc0c5): Check worker::patchwork / patchwork before Ingestor and match patch / patch:: explicitly so sashiko::patchwork logs classify under patchwork instead of ingestor.
  2. insert_review_email_outbox() & insert_patchset_email_outbox() (src/db.rs, 581325c51b38): Call record_initial_outbox_outcome() on both fresh inserts and status-changing updates in both methods.
  3. cancel_aborted_review() (src/db.rs, 581325c51b38): Still populate result_description (and clear interaction_id) when the row was already marked Cancelled by cancel_patchset(), while only incrementing add_reviews_completed() for rows transitioning out of Pending / In Review.
  4. Pre-upgrade embargo release timestamp attribution (src/db/stats_queries.rs, 581325c51b38): In record_patchset_release_rollups(), check stats_backfill:cutoff:patchsets inside the immediate transaction and attribute pre-upgrade patchsets (patchset_id <= cutoff) to their historical patchsets.date instead of now_ts.
  5. Atomic subsystem link + rollup cursor check (src/db.rs, src/db/stats_queries.rs, 581325c51b38): Execute INSERT OR IGNORE and the stats_backfill:v1:cursor:{patches,patchsets} check + rollup upsert in a single IMMEDIATE transaction (add_subsystem_link_with_rollup) serialized with backfill chunks.
  6. backfill_email_outbox() (src/worker/stats_backfill.rs, f203efdb5c91): Map Disabled -> skipped and Dry-Run -> dry_run to match record_initial_outbox_outcome().

Re-verified with make check-pr RANGE=origin/main..HEAD and local sashiko review --project sashiko --agent on all three updated commits (status: "clean", 0 findings).

@sashiko-bot

sashiko-bot Bot commented Nov 20, 2026

Copy link
Copy Markdown

Sashiko review — v2

Commit 4/15 — 581325c5 worker, db: wire rollup flushes, pipeline stats, and backfill

  • [MEDIUM] src/ai/backoff_provider.rs: BackoffProvider::generate_content()
    starts call_started before calling self.inner.generate_content() and
    records observe_ai_request_duration() when it returns. Because
    BackoffProvider wraps ConcurrencyLimitedProvider, the recorded latency
    includes time spent waiting for an llm_semaphore permit, RPS/TPM rate-limit
    pacing, and quota cooldowns while queued. In addition, if budget.check()
    fails inside ConcurrencyLimitedProvider::generate_content() before the
    request is dispatched, BackoffProvider records a latency sample and counts
    the deadline error as a fatal AI provider error via inc_ai_error(). Measure
    request duration and provider errors at the active dispatch boundary inside
    ConcurrencyLimitedProvider when self.inner.handles_active_budget() is true.

Commit 5/15 — afbe96f0 server, promql, db: add O(1) Prometheus HTTP API and metrics endpoint

  • [MEDIUM] src/prom_api.rs: load_authorized_bug_subsystems() calls
    Database::get_bug_subsystem_facets_o1() with lifecycle_status set to None,
    and fold_subsystem_facet_row() in src/db/stats_queries.rs accumulates
    sev_critical, sev_high, sec_critical, and sec_high across all lifecycle
    statuses. When populate_instant_metrics() emits the high_crit_open and
    sec_high_crit_open facets of sashiko_bugs_by_subsystem from those fields,
    both metrics include fixed, duplicate, dismissed, closed, and untriaged
    bugs and can exceed the subsystem open count.

Full review and stage logs on sashiko.sashiko.dev

@rgushchin

Copy link
Copy Markdown
Member Author

Addressed both v2 findings from sashiko-bot and folded each fix into its introducing commit:

  1. AI request latency & error telemetry at the active dispatch boundary (src/ai/mod.rs, src/ai/concurrency_limited_provider.rs, src/ai/backoff_provider.rs, src/scan.rs, c745096beb28): Added AiProvider::handles_request_telemetry() (implemented on ConcurrencyLimitedProvider, delegated through scan.rs), measuring observe_ai_request_duration() and inc_ai_error() strictly around self.inner.generate_content() inside ConcurrencyLimitedProvider after semaphore acquisition, quota pacing, and budget.check(). BackoffProvider only records them when !self.inner.handles_request_telemetry(), avoiding queueing inflation and pre-dispatch deadline false errors.
  2. Open-only severity facets on sashiko_bugs_by_subsystem (src/db/stats_queries.rs, src/prom_api.rs, c2727a264288): Tracked open_sev_critical, open_sev_high, open_sec_critical, and open_sec_high in BugSubsystemFacetSummary strictly for lifecycle_status == "open" rows in fold_subsystem_facet_row(), and wired high_crit_open and sec_high_crit_open in populate_instant_metrics() to use those open-only counts (+ regression test).

Re-verified with make check-pr RANGE=origin/main..HEAD and local sashiko review --project sashiko --agent on both updated commits (status: "clean", 0 findings).

@sashiko-bot

sashiko-bot Bot commented Nov 20, 2026

Copy link
Copy Markdown

Sashiko review — v3

Commit 4/15 — c745096b worker, db: wire rollup flushes, pipeline stats, and backfill

  • [MEDIUM] src/db/stats_queries.rs: record_single_patchset_release_in_tx()
    sets the permanent stats_rollup:ps_done: meta guard when a patchset
    finishes as Failed or Failed To Apply. If a late cover letter or manual
    rerun requeues the patchset via Database::reset_patchset_review_state() in
    src/db.rs and the review succeeds, the second call sees the existing guard
    and returns early without recording Reviewed completion, finding, subsystem
    finding, or prior-feedback rollups. Clear or upgrade the guard when a
    failed patchset is reset or transitions to Reviewed.

Commit 13/15 — 7486b018 ui, docs: reorder tabs, add weekly clean %, cumulative bugs, and 52w/All

  • [LOW] static/index.html: renderBugsStatsTab() clamps oRun and fRun with
    Math.max(0, ...) before adding weekly deltas, and checks openCum[i] > 0 ||
    fixCum[i] > 0 when trimming the All window. When open bugs are later marked
    duplicate, dismissed, or closed, the window sum of netOpenWk exceeds
    openCnt, so clamping oRun to 0 makes the final point of openCum exceed the
    Open Bugs count in the summary table. Conversely, when bugs are discovered
    or fixed on the current UTC day after alignedEndUtc(), oRun or fRun starts
    above 0 at week 0 and the openCum/fixCum check in findIndex() prevents
    leading empty weeks from being trimmed in the All view. Compute openCum and
    fixCum without pre-clamping oRun and fRun (clamp only each displayed point
    to 0), and trim the All window based on d > 0 || fixWk[i] > 0 alone.

Full review and stage logs on sashiko.sashiko.dev

@rgushchin

Copy link
Copy Markdown
Member Author

Addressed both v3 findings from sashiko-bot and folded each fix into its introducing commit:

  1. Upgrading stats_rollup:ps_done:<id> on Failed / Failed To Apply → Reviewed (src/db/stats_queries.rs, d7cb1d9e60f9): Store the recorded terminal status in stats_rollup:ps_done:<id> instead of a permanent '1' flag. Repeated failures or repeated Reviewed calls remain strict no-ops (including legacy '1' entries), while a patchset that previously recorded Failed / Failed To Apply and later succeeds as Reviewed (e.g. after a late cover letter or manual rerun) upgrades the guard to 'Reviewed' and records its Reviewed completion, findings, subsystem findings, clean patches, versioned issues, and prior-feedback rollups without double-counting sashiko_patches_ingested_by_lineage_total (+ regression test).
  2. Cumulative Open vs Fixed Bugs anchor & All trimming (static/index.html, 0ca6d1869a58): Compute oRun and fRun without pre-clamping to 0 (clamping only each displayed point with Math.max(0, ...)) so the final plotted point always matches the summary table's openCnt/fixedCnt, and trim leading empty weeks in All strictly by d > 0 || fixWk[i] > 0.

Re-verified with make check-pr RANGE=origin/main..HEAD and local sashiko review --project sashiko --agent on both updated commits (status: "clean", 0 findings).

@sashiko-bot

sashiko-bot Bot commented Nov 20, 2026

Copy link
Copy Markdown

Sashiko review — v4

Commit 4/15 — d7cb1d9e worker, db: wire rollup flushes, pipeline stats, and backfill

  • [MEDIUM] src/db/stats_queries.rs: record_single_patchset_release_in_tx()
    records findings and prior_feedback_resolutions even when a patchset
    finishes with status Failed. When a multi-patch series has both reviewed
    and failed patches, rerun_patchset() preserves the already-reviewed rows
    and their findings while retrying only the failed patches. Once the retry
    succeeds and upgrades the stats_rollup:ps_done: guard from Failed to
    Reviewed, record_single_patchset_release_in_tx() skips patch_lineages via
    upgraded_from_non_reviewed, but still counts findings_list and prior_list a
    second time. Only record findings and prior feedback rollups when status is
    Reviewed.

  • [LOW] src/main.rs: run_daemon() calls metrics_handle.abort() on shutdown
    and immediately runs prepare_runtime_flush() and flush_rollup_samples()
    without awaiting metrics_handle or serializing flushes. Because abort() is
    asynchronous and FLUSH_WATERMARK is only updated in commit_runtime_flush()
    after the database write returns, a shutdown that arrives while
    MetricsWorker is flushing can read the old watermark and commit the same
    60-second counter deltas twice. Await metrics_handle after aborting it or
    guard the flush cycle with an async lock.

Full review and stage logs on sashiko.sashiko.dev

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>
@rgushchin

Copy link
Copy Markdown
Member Author

Addressed both v4 findings from sashiko-bot and folded them into Commit 4 (f94c055d802d):

  1. Defer findings/prior-feedback rollups until Reviewed (src/db/stats_queries.rs): In record_single_patchset_release_in_tx(), only query and record sashiko_findings_discovered_total, sashiko_subsystem_findings_total, and sashiko_prior_feedback_total when status == "Reviewed" (and skip re-querying patch_lineages on Failed/Failed To Apply → Reviewed upgrades). When a partially-reviewed multi-patch series fails and later succeeds via rerun_patchset(), preserved findings and prior-feedback resolutions are now recorded once on Reviewed rather than twice. Extended test_failed_patchset_rerun_upgrades_release_guard_to_reviewed to cover this exact scenario.
  2. Serialize shutdown runtime metrics flush with MetricsWorker (src/main.rs): Guard the prepare_runtime_flush() → flush_rollup_samples() → commit_runtime_flush() cycle with a shared tokio::sync::Mutex<()> and acquire it before calling metrics_handle.abort() and awaiting metrics_handle on shutdown, ensuring any in-flight flush finishes updating FLUSH_WATERMARK before the final shutdown flush runs.

Re-verified with make check-pr RANGE=origin/main..HEAD and local sashiko review --project sashiko --agent f94c055d802d (status: "clean", 0 findings).

@sashiko-bot

sashiko-bot Bot commented Nov 20, 2026

Copy link
Copy Markdown

Sashiko review — v5

✓ No issues found across 15 commits.

Full review log on sashiko.sashiko.dev

@rgushchin
rgushchin merged commit 56f25fe into main Nov 20, 2026
1 check passed
@rgushchin
rgushchin deleted the feat/stats-rework branch November 22, 2026 17:38
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