Skip to content

bug(analytics): results are not limited to their source — require it on the route, no silent default #20513

Open
2 of 3 issues completed

Description

@mrveiss

Problem

A Codebase Analytics result can come from a different source than the one being viewed, and nothing says so. The maintainer saw a job for another source while looking at AutoBot's analysis (#20491). repo_tests/source_scoping_guard_17758_test.py guards one shape of this class, X if source_id else <unscoped>, and #17761 tracks its seven frozen sites. The shapes below pass that guard. The class has been closed four times and returned (#17761 lists them), so this needs a rule that holds at the route, not another sweep.

Evidence

Read from the code on main at f88cd37, not run.

Shape Where What happens
Silent default to the most recent source default_source_id() callers: endpoints/stats.py:612, report.py:2229, dependencies.py:489, import_tree.py:264; and use_default in endpoints/shared.py:137-142 A request with no source gets another source's results, with nothing in the response saying which
No source at all /index/current (endpoints/indexing.py:319) One global job. PR #20501 adds its source and has the page ignore another source's job; the route itself still takes none
Global result key bug_pred_task:latest_task_id (api/analytics_bug_prediction.py), debt:latest (api/analytics_debt.py), /api/quality/health-score Cached under no source
Results not limited to the analysed root #20224 (PR #20410 labels this rather than limiting it) The response reads as if it covered one root
Index keyed by relative path #20402 Files from different roots can overwrite each other

Size not established. Lines declaring source_id as optional under endpoints/*.py, matched by source_id: str | None or Optional[str]: 75. That count includes helpers and is not a count of routes. Paths outside endpoints/, other spellings and the per-route verdicts have not been measured.

Fix

  • A route that returns per-source results requires a source through SourceIdQuery and refuses a request without one. No default to the most recent source.
  • A result that is really across sources says so in its response, by a named property the guard can read.
  • Responses state the source they came from.
  • The frontend sends the source on every such call. A caller that sends none today gets a 422 after this, so each caller is checked first.

Acceptance criteria

  • Every route under api/codebase_analytics/endpoints/ that returns per-source results requires a source, or carries a named cross-source declaration. The list of routes and each verdict is posted here.
  • default_source_id and use_default have no caller serving an HTTP request, or each remaining one states why.
  • The global keys in the table are keyed by source, or declared cross-source.
  • A guard fails on a new route with an optional or missing source. It reads the registered routes, states how many it examined, fails if that count falls below its floor, and has a control route it must flag and one it must pass.
  • Any baseline freezing today's sites is content-keyed, can only shrink and has its count re-derived by a second method, per RATCHET_BASELINES.md.
  • A request for source A never returns source B's stored result (test with two sources).

Related

Class witnesses, each keeping its own issue: #17761 (fallback sites), #20224, #20402, #20491, #17758.

Activity

  1. added
    needs-structureMissing goal milestone, matching phase label or native parent (#19522)
    on Nov 1, 2026
  2. github-actions commented on Nov 1, 2026

    @github-actions
    Contributor

    needs-structure cleared: goal milestone, matching phase label and native parent (or sub-issues) are all present (#19522).

  3. removed
    needs-structureMissing goal milestone, matching phase label or native parent (#19522)
    on Nov 1, 2026
  4. mrveiss commented on Nov 2, 2026

    @mrveiss
    OwnerAuthor

    Route inventory against main at 87eae8a, read from the code and not run. The per-route verdict list this issue's first AC asks for still has to be posted; these are the class counts.

    86 route registrations, 83 unique paths. Decorators alone count 81, so a guard that greps @router. would miss routes registered through add_clear_stuck_route. A guard should read the registered routes, as the AC says.

    Class Count
    Requires a source 15
    Optional source, silently defaults to the most recent source 21
    Optional source, no default: unscoped read or a "default" tag 16
    Optional source in the request body 2
    No source, takes path, defaulting to the project root 7
    No source, touches shared or per-source state 4
    No source and no per-source result by route shape 21

    Wrong-source results even when a source is named:

    • _get_last_indexed (endpoints/sources.py:475-481) falls back to the global codebase_stats document when a source has no stats of its own, so that source reports another's last-indexed time. Confirmed by reading it.
    • The in-memory /hardcodes fallback (endpoints/stats.py) reads codebase:hardcodes:* with no source. The helper takes no source; the call path still needs confirming.

    Other things this adds to the issue's table:

    • Requests with no source are cached in memory under a constant ("default" or ""), which doesn't change when the most recent source does. A later request can get a result computed for an earlier default. Read from the code, not run.
    • pattern_task:latest_task_id and patsummary_task:latest_task_id are further global keys. debt:latest and /api/quality/health-score weren't checked.
    • resolve_scan_root falls through to AutoBot's own tree when no source can be resolved.

    Requiring a source will break callers unless they change first. withSourceId and sourceIdQuery send nothing when no source is selected, so those callers would get a 422. usePatternAnalysis.ts, useImpactAnalysis.ts and the debug health check in useAnalyticsDebug.ts never send one. Non-frontend clients weren't searched.

    Not established: whether a task id's result belongs to the caller's source, whether the code graph collection behind /impact holds one source or several, and what /report's sub-analyses key on.

  5. mrveiss commented on Nov 2, 2026

    @mrveiss
    OwnerAuthor

    Correction to my inventory comment: the in-memory /hardcodes fallback is not a wrong-source read today. endpoints/shared.py:36 _in_memory_storage = {} is never written, so it's always empty, and stats.py:363 never takes that branch. With no Redis, /hardcodes answers no_data, which is honest.

    It's still unfinished: _fetch_hardcodes_from_memory ignores the source and calls scan_iter on what is a plain dict, so it would both fail and be unscoped if anything filled that store. storage.py:100 InMemoryStorage exists and isn't wired to it. Left in place and recorded here, since it isn't reachable.

    _get_last_indexed is the confirmed wrong-source read; its fix is in #20612.

  6. mrveiss commented on Nov 2, 2026

    @mrveiss
    OwnerAuthor

    #20612 landed in #20692 (58cbf98): _get_last_indexed and _get_problems_from_chromadb no longer fall back to the global stats document. Still open: require a source on routes, per-route verdicts, a guard that reads registered routes, the frontend 422 check, and the global keys.

  7. mrveiss commented on Nov 7, 2026

    @mrveiss
    OwnerAuthor

    Witness from the review of #20491 (checked against origin/main, 2026-11-07). This is the route-level shape this issue's first AC covers.

    Route: autobot-backend/api/codebase_analytics/endpoints/pattern_analysis.py:539-542, GET /patterns/cached-summary, with source_id: str | None = Query(default=None).

    Silent default: when source_id is absent, _build_chromadb_where_filter (pattern_analysis.py:634) substitutes the sentinel source_id or "default". The summary is therefore read from the "default" partition, not from the selected source and not from all sources, and the response does not say so.

    Frontend caller: autobot-frontend/src/composables/usePatternAnalysis.ts:494 calls /api/analytics/codebase/patterns/cached-summary with no params. It does not use scopeToSource or withSourceId (composables/analytics/useAnalyticsDataFetchers.ts:153, CodebaseAnalytics.vue:556).

    Fix in this issue's scope:

    • The route requires source_id (or declares a cross-source result), per the first AC.
    • The frontend sends source_id through the canonical scopeToSource / withSourceId pattern.
    • A test asserts that the request carries source_id for the selected source.
  8. mrveiss commented on Nov 7, 2026

    @mrveiss
    OwnerAuthor

    Decisions for the first PR of this issue (#21008), recorded before it merges.

    1. Task routes are exempt. Routes addressed by {task_id} (status, result, cancel, */tasks/clear-stuck, clear-all) do not take a source: the id was minted for one source's run and the caller cannot usefully re-assert it. The route guard classifies them by the {task_id} path marker and by a named ops list (POST /sources, POST /embedding-stats/reset, POST /patterns/tasks/clear-all, the clear-stuck suffix).

    2. POST /index requires exactly one of source_id / root_path. The dev root_path mode stays. A body naming neither (which used to index AutoBot's own project root) or both is a 422. The frontend indexing trigger now sends source_id alone when a source is selected.

    3. path on the /patterns/* routes is relative to the source root. It is optional (no path scans the whole source), resolved with resolve_scan_root(strict=True) and validated with validate_relative_path so it cannot leave the source. The previous default was AutoBot's own project root.

    4. /impact is cross-source, and says so. Evidence, read from the code: CodeIndexer (services/knowledge/code_indexer.py) writes node metadata {source, record_type, node_kind, node_name, source_path, line, parent, origin} and edge metadata {source, record_type, kind, source_id, target_id, ...}; the source_id on an edge is the CALLER NODE's id, not a registry source. The only writer, POST /api/knowledge_base/index/code, takes a directory, not a source. So no where-filter by code source is possible, and node ids are path-based, so the same id in two sources is one node. The route carries x-source-scope: cross-source in its OpenAPI metadata and every response carries source_scope: "cross-source". Scoping it needs the graph writer to tag nodes with a source first (follow-up below).

    Visible API change: the source-bound analytics routes now answer 422 without a well-formed source_id. The full list and the guard output are in the PR body.

    Scope of the next PR (PR 2), after the page-open PR that touches the same files lands: /index/current and /index/cancel scoping, deleting jobBelongsToSource, and the edits to analytics_page_open_reads_only_20491_test.py.

    Follow-ups, not in either PR:

    • /api/quality health-score and metrics routes.
    • Global keys bug_pred_task: and debt:latest.
    • The scheduled population task (analytics_cache_population.py) dispatches with no source.
    • Tag code-graph nodes with a source, then scope /impact.
    • resolve_scan_root still falls back to AutoBot's own tree when a NAMED source does not resolve on the non-strict routes.
    • source_storage.get_default_source_id has no production caller after this PR.
    • The pattern write side tags a source-less analysis "default".
  9. 42 remaining items

  10. mrveiss commented on Nov 22, 2026

    @mrveiss
    OwnerAuthor

    Instance inventory, re-verified on origin/main (2026-11-22)

    Rule applied: where an analyzer's own code lives is legitimate; what tree it scans must be the selected source's clone. Paths are under autobot-backend/api/ unless noted.

    A. Scan root is not the selected source (live defects)

    # file:line What it scans
    1 analytics_bug_prediction.py:824,904,947,1113,1276 (/analyze GET+POST, /high-risk, /heatmap, /summary) path=Query("."): the server's working directory (the install tree). No source_id anywhere in the module. This is #18030, still live.
    2 analytics_bug_prediction.py:59,69,910 Cache key built from path only; bug_pred_task:latest_task_id is global. /cached ignores the source (frontend useBugPrediction.ts:67 sends none).
    3 codebase_analytics/endpoints/report.py:1603-1607 Bug-pattern/pattern report scans PATH.BACKEND_DIR (install backend) whenever the source root equals the install's git root.
    4 report.py:1662 Duplicate analysis falls back to parents[4] when project_root is falsy.
    5 report.py:1785 Bug prediction in the report falls back to PATH.PROJECT_ROOT.
    6 duplicate_detector.py:476 DuplicateCodeDetector() with no root scans parents[3] (install backend).
    7 api_endpoint_scanner.py:203,970,1402 APIEndpointChecker, endpoint scanners and the checker fall back to resolve_git_repo_root(), which probes <base>/code_source then parents[4].
    8 endpoints/shared.py:297-345 get_project_root() (parents[4], no live caller found) and resolve_git_repo_root() (walk-up for .git, then <base>/code_source, then parents[4]). Root cause of 3, 7, 9, 10, 11.
    9 endpoints/shared.py:377 filter_problems_by_file_existence(root_path=None) resolves problems against resolve_git_repo_root().
    10 tasks/analytics_cache_population.py:164 Daily cache job passes resolve_git_repo_root() as the project root to the modules that take a path; only some modules also get the per-source list.
    11 codebase_analytics/scanner.py:275 scan_codebase(root_path=None) scans PATH.PROJECT_ROOT.
    12 endpoints/indexing.py:184 A dequeued job with no root_path indexes PATH.PROJECT_ROOT.
    13 schemas_analytics.py:1068 CodeAnalysisRequest.target_path defaults to PATH.PROJECT_ROOT.
    14 analytics_architecture.py:368-372 base_path defaults to config.base_dir.
    15 analytics_debt.py:412,432,443 Debt result keyed debt:latest, global; target_path echoed from the request.

    B. source_id optional, so an unsourced call is not a 4xx (the #20513 shape)

    • analytics_quality.py:132,203,701,1033,1091,1163,1227,1355,1400,1515
    • analytics_code_review.py:426,496,614,682,757
    • analytics_evolution.py:328,398,552,816
    • analytics_code_generation.py:936
    • analytics_reporting.py:78
    • codebase_analytics/endpoints/charts.py:37,163,238
    • codebase_analytics/endpoints/cross_language_patterns.py:49
    • codebase_analytics/endpoints/report.py:1300,1393,1526,1752,2125

    C. Legitimate, not scan roots (allowlist): environment.py:235-244 (puts the backend on sys.path and loads env_analyzer.py), ownership.py:49-54 (loads ownership_analyzer.py), analytics_controller.py:76-77 (tool locations). default_source_id / use_default callers listed in the issue body no longer exist on main (grep: 0).

    D. Frontend: composables/analytics/useBugPrediction.ts:67 calls /api/analytics/bug-prediction/cached with no source_id; the other analytics composables need the same audit.

    #18030 is the same defect as rows 1-2 and is fully fixed only when the bug-prediction routes require source_id.

  11. mrveiss commented on Nov 22, 2026

    @mrveiss
    OwnerAuthor

    Owner decision on row 15 (technical debt): debt moves under the codebase page (codebase/:id) as a tab of the selected codebase, with source_id required on every debt route and results kept per codebase. It lands in PR 3 with the other optional-source_id routes. PR 2 (#22085) leaves /api/debt/* unchanged.

  12. mrveiss commented on Nov 22, 2026

    @mrveiss
    OwnerAuthor

    Added to the instance list: autobot-backend/api/code_intelligence.py POST /evolution/analyze (line 1685 on main) takes a caller-typed path query (Query(...), validated only for existence) and mines that repository, so it scans a path rather than the selected source's checkout. It moves to a required source_id and the source's checkout; it rides with the evolution PR (#22089) because no open PR touches that file.

  13. mrveiss commented on Nov 22, 2026

    @mrveiss
    OwnerAuthor

    Instances left out of the PRs so far, each with its plan (read from code, not run)

    Instance What it does Plan
    autobot-backend/api/code_intelligence.py path-typed scans: POST /analyze and GET /health-score; POST /redis/analyze and GET /redis/health-score; POST /security/analyze, GET /security/report; POST /performance/analyze, GET /performance/score, GET /performance/report; POST /security/score/analyze (path / request.path, checked only for existence) scan any host directory the caller types Own PR after the debt tab ("code-intelligence path routes"): source_id required, scan root from resolve_scan_root (an optional sub-path goes through scan_path_in_source), result keys per source. GET /security/score and /security/score/cached already take a source (#21463). The evolution routes of this file are fixed in #22089.
    autobot-backend/api/analytics_quality.py GET /remediation-deltas reads remediation:delta:history, written by code_analysis/src/remediation_loop.py with no source on the record Out of the class for now: it reports the remediation loop's own before/after history, and no record names a tree. If the loop is ever run per source, it must write the source id and this route requires it. Named as left unchanged in the quality PR (#22090) body so the omission is a stated decision.
    autobot-backend/api/analytics_quality.py runtime_risk drill-down and the runtime_risk metric (code_analysis/src/runtime_risk.py:44, build_runtime_risk_map) a risk map built from runtime error patterns, not from the selected checkout In the class (a source's quality page shows a risk map not derived from its tree). Own small PR with the quality follow-ups: keep only map entries whose file is under the source's checkout. Not verified: where the runtime error patterns record their file paths relative to.
  14. mrveiss commented on Nov 22, 2026

    @mrveiss
    OwnerAuthor

    For PR 1 (resolver), checked on main: resolve_source_root returns Path(source.clone_path) unresolved and resolve_scan_root accepts it when is_dir() is true, which follows symlinks. A clone_path that is itself a link (or sits under one) is therefore scanned wherever it points, while containment checks elsewhere (confirm_scan_dir_in_source, the quality and evolution filters) compare against root.resolve(), so the two can disagree about what the root is. PR 1 should return the resolved path from resolve_scan_root so every scanner and every containment check use one real root. Not verified: whether source registration restricts clone_path for local sources (if it accepts any path, the link case is no wider than registering that path directly). The pattern analyzer's missing cooperative cancel token is #22094 (sub-issue of this one).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendbugSomething isn't workingphase:M4.11Safety net: tests and analysers reach the whole treepriority: high

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions