Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

perf(metrics): reuse retained query plans and output series

rcourtmanf26668aa6ddc
diff --cc docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
index 906c6c9736,0e24cc4ce1..e905280307
--- a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
+++ b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
@@@ -4,107 -4,6 +4,107 @@@ The customer job is: "Tell me what need
deal with it without creating more work." Patrol owns the issue and investigation.
Assistant explains that same issue and uses existing governed action contracts.
+## Active redesign plan, 2026-09-05
+
+The maintainer requested a whole-design assessment and an explicit goal to
+complete the resulting plan. The existing customer-outcomes candidate remains
+the active scope under `v6-product-lane-expansion`. This is an architecture and
+qualification effort, not further cosmetic refinement of the current surface.
+
+### Product and architecture decision
+
+Patrol owns proactive investigation of the user's infrastructure and retained
+operating intent. Assistant explains and continues that same issue and its
+existing investigation/action records. An observed signal, model hypothesis,
+proposed action, accepted plan, executed operation and independently verified
+outcome are different facts. No transition may promote one into another merely
+because a tool accepted a structurally valid record.
+
+Keep canonical resource identity, observation provenance, retained evidence,
+operator intent and existing governed action records. Keep permissions, approval,
+mutual exclusion, idempotency, explicit resource/cost limits, execution and
+independent postcondition verification deterministic. Interpretation, relevance,
+causal diagnosis, investigation choices and action judgment belong to the model.
+Every orchestration pass must identify its objective invariant. A pass whose
+purpose is to manufacture or force a diagnosis from proxy counts must be removed
+or replaced with better model context and an explicit model decision.
+
+The design review reproduced a concrete trust violation in
+`internal/ai/chat/agentic_investigation_budget.go`: accepted proposal rationale is
+called an evidence checkpoint, inserted into the final Root Cause section, and
+the completion prompt forbids downgrading it in the reviewed baseline. Acceptance establishes that a
+proposal was recorded, not that its causal claim is true. This mechanism must
+be corrected before the diagnosis/action journey can qualify. The current
+working change removes both insertion paths and the duplicated proposal prompt
+state. A full-service regression now preserves the exact uncertain conclusion in the
+stream, returned result and persisted session after evidence and proposal turns.
+The full live investigation journey remains to be qualified.
+
+### Baseline and measurement limits
+
+The recorded 2026-09-05 telemetry review in the owning coverage gap used latest
+reports from monitoring-active, multi-ping installations, excluding development
+and deployment proof. It contained 127 paid installations, 71 with Patrol enabled
+and 23 with Assistant calls. Fourteen reported verified resolutions came from one
+installation. These are the previously recorded aggregate review, not a fresh
+query made during this redesign. Paid includes all non-free tiers. Cooccurring
+usage does not establish a linked successful task. Schema 17 outcome/provider/cost
+fields had no adoption in that review, so those fields cannot establish present
+customer effectiveness or model cost.
+
+Local live proof has independently exposed lost evidence, incorrect history
+coordinates, premature compaction, unsupported causal claims and roughly
+three-minute interactive investigations. One maintainer installation is useful
+reproduction evidence, not a representative customer success rate.
+
+### Execution order and acceptance
+
+| Step | Work | Acceptance | Current state |
+|---|---|---|---|
+| 1. Product contract and baseline | Map the current loop and sources of judgment. Record telemetry populations and gaps. | Every identified decision has an owner. Activity is not labelled usefulness. | Complete for this redesign scope. Contract, ownership decisions and baseline limits are recorded. |
- | 2. Shared evidence | Preserve canonical risk reasons and SMART counters, source/time semantics and history across tools/turns. | Regression tests preserve unknown versus zero and all canonical evidence. Real responses can inspect the same facts as the product. | Implemented and qualified for the named shared-evidence defects. Canonical disk detail, risk and cadence pass real data-path proof. Affected package and concurrency checks pass. Commit f01db995ed corrects the PR benchmark regressions. Exact-base worker comparisons and full metrics/database and focused race checks pass. Final landing CI remains open. Real-model interpretation failures remain tracked in step 5. |
++| 2. Shared evidence | Preserve canonical risk reasons and SMART counters, source/time semantics and history across tools/turns. | Regression tests preserve unknown versus zero and all canonical evidence. Real responses can inspect the same facts as the product. | Implemented and qualified for the named shared-evidence defects. Canonical disk detail, risk and cadence pass real data-path proof. Affected package and concurrency checks pass. Integrated CI later exposed remaining query and allocation regressions. The final bounded query-reuse correction passes complete selected exact-base worker comparisons and full metrics/database and focused race checks. Final landing CI remains open. Real-model interpretation failures remain tracked in step 5. |
+| 3. Diagnostic orchestration | Correct proposal-as-proof. Audit triage budgets, unmatched-signal evaluation, assessment completion and investigation cutoffs. | No code-written causal conclusion. No quality inferred from tool, flag or finding counts. Each retained pass has an objective reason. Safety boundaries and incomplete outcomes remain explicit. | Proposal promotion and capture inference were removed in c5d2f56dda. Commit 668af3fe6b removes investigation success-call floors, checkpoint instructions and generic call-count wrap-up rules. The detection slice removes contextless follow-up passes, flag/report-count policy and first-finding completion modes. Full chat and AI suites, focused API and conversation race tests pass. Real-model/action outcome qualification remains open. |
+| 4. Issue through verified outcome | Follow existing issue/investigation/action records into Assistant, approval, execution and independent readback. | Accepted proposal is visibly distinct from execution and verification. Rejected or unsupported actions do not become success. Uncertainty can survive an action proposal. | Existing foundation, full journey qualification pending. |
+| 5. Ground-truth qualification and landing | Extend existing qualification tooling only where necessary. Exercise healthy/unhealthy, dependency, missing-access, storage/backup and approved/rejected action cases. Inspect the final browser journey at desktop and narrow widths. | Record exact source/model/permissions, evidence, decisions, faults/misses, latency and verification. Fix in-scope failures, pass appropriate proofs and land scoped commits. | Pending. |
+
+Use one shared runtime and the existing qualification runner, not a second
+product intelligence engine or a new parallel lifecycle. Preserve independent
+negative controls and fault oracles. Recorded fixtures prove contracts and
+reproducibility, not live model competence. Do not tune success wording or
+scoring to make the model pass.
+
+### Diagnostic orchestration audit
+
+| Mechanism | Current implementation | Decision for implementation review |
+|---|---|---|
+| Proposal rationale inserted as Root Cause | The reviewed baseline amended the conclusion after acceptance in the agent loop and service. Both mutations are removed in the working change. | Prove uncertain prose survives accepted proposals through stream, persistence and linked Assistant display. Keep the proposal record as an attributed model decision and allow uncertainty in the diagnosis. |
+| Causal-resource validator | Removed the duplicate resource graph and name/status inference from the working capture boundary. Causal attribution is optional when unknown. | Prove capability/schema validation, parameter isolation and invocation integrity remain enforced. Dependency evidence remains available to the model through canonical queries. |
+| Flag-count turn ladder | Removed in the detection slice. Ordinary runs have a fixed forty-turn limit, explicit quick runs retain four. | Verify flags and inventory size cannot change the execution limit or mandate findings. |
+| Unmatched-signal evaluation | Removed the separate evaluator and its signal-count report budget. | Verify the original model conclusion and usage are retained without a second diagnostic session. Ground-truth missed-fault qualification remains required. |
+| Missing-finding assessment sweep | Removed the separate session. | Preserve explicit assessments in the original conversation and incomplete status for omissions. No old finding excerpt may become a fresh verdict. |
+| First accepted finding ends investigation | Removed the post-write summary, continuation and repair modes. | Preserve evidence tools and original context within the run limit. Accepted decisions survive a later provider failure without hiding that failure. |
+| Investigation evidence-call floor | Removed in the current slice. Seed-only and failed-read conclusions survive without forced extra calls. | Completion is not diagnostic correctness. Preserve explicit limits, failed/unavailable evidence and independent action freshness checks. |
+| Generic wrap-up counters | Removed the 12/18-call tool-result instructions and four silent-turn cutoff. | Explicit run limits bound work. Counts and silence do not establish evidential sufficiency. A twenty-read regression preserves available tools, observations and the model conclusion. |
+| Authority and execution boundaries | Tenant identity, capability schemas, approvals, invocation IDs, parameter redaction and independent readback. | Keep and prove unchanged when diagnostic policy is simplified. These enforce objective invariants. |
+
+This is an audited change list, not a claim that the changes are already made.
+Each removal must run its focused regression and affected complete journey.
+
+### Completion and external dependencies
+
+The local implementation goal remains open until required qualification is
+performed. Ordinary Assistant requests work with the current subscription route,
+but autonomous Patrol has an explicit provider-policy refusal and remains
+blocked. Do not rephrase the refused probe, bypass the readiness boundary or
+count an interactive request as an autonomous Patrol pass. A supported provider
+path is required for that qualification. Prepare other work while resolving the
+provider dependency through supported configuration.
+
+Release publication and wider product readiness are separate. Independent
+volunteered Pro environments are still required before claiming repeatable
+customer value. Capture that rollout requirement in the owning qualification gap
+rather than presenting one homelab result as completion of it.
+
## Implemented interaction
`Explain with Assistant` on an attention item or active alert starts an explicit
@@@ -413,500 -311,3 +413,549 @@@ provider readiness probe. The final sav
to the tool's descriptive governance metadata. Runtime source hashes, transcript
and screenshots are retained in the local homelab evidence-trust artifact set.
These receipts do not qualify autonomous Patrol or infrastructure mutations.
+
+
+## Retained history reconciliation, 2026-09-05
+
+The shared metrics query now reconciles each resource/metric across retained
+tiers before downsampling. Preferred buckets exclude overlapping lower-priority
+observations, and uncovered times and new metrics remain visible to single,
+all-series and batch consumers. Rollups preserve stored extrema through later
+aggregation stages. This does not recover historical peaks already discarded
+or observations that were never collected. Query-plan checks exercise the actual
+shared SQL builder and require indexed overlap probes.
+
+The original local fixture now returns both the minute and newer raw point for
+24-hour single/all-series reads. Regression cases cover older fallback buckets,
+internal gaps, newer raw tails, overlap precedence at minute/hour/day boundaries,
+resource-family isolation, per-metric filters, downsampling after reconciliation,
+and single/batch parity. Customer issue #1717 independently documents the value
+of API-only Proxmox history, although its earlier canonical-ID defect is distinct
+from this query-tier defect. The full issue and comments were read. It has no
+supplied screenshots and this work makes no new claim about that reporter's fix.
+
+The live read-only Assistant repeat completed in 161 seconds. Its 24-hour
+summary now contained 444 CPU/memory points and 436 temperature points, ending
+at 22:43:54 BST, seven seconds before the summary query. The previous run returned
+83 points ending at 21:39, about 45 minutes stale. The returned observation span
+is now roughly 2 hours 27 minutes, with a largest timestamp gap of 61 seconds.
+This validates the recovered recent tail, not a full day of collection.
+
+The model again correctly distinguished high utilisation from demonstrated
+pressure and disclosed the unavailable host agent evidence. Diagnosis remains
+unqualified. It asserted continuous collection from point spacing, inferred a
+monitoring/store restart from coincident timestamps, and called two temperature
+readings contradictory without ruling out change between their different
+observation times. It suggested treating a rising memory floor as evidence of
+a leak without workload attribution. These are model-reasoning failures, not
+additional proof of a storage defect or homelab fault. No infrastructure mutation
+or new refused provider-readiness probe was performed.
+
+Playwright exercised `/patrol` Assistant submission/completion, all eleven tool
+controls with keyboard and pointer expansion/collapse, inner output scrolling,
+answer pixels, Escape, session selection and reload at 1440x1000 and 390x1000.
+The actual cached provider-refusal state at
+`/settings/pulse-intelligence/patrol` and the manual HTTP 409 gate still hold.
+The local retained-coverage artifact set contains transcript, current source
+hashes and final browser screenshots.
+
+
+The adjacent `/proxmox` node History check found a second evidence-path defect.
+The view inferred a linked Agent from discovery routing, requested `agent/delly2`,
+and showed Collecting history while the real source was `node/homelab-delly2`.
+The canonical unified metrics target now advertises the collector's `node`
+storage family and source ID for API-only Proxmox hosts, while preserving real
+Agent-source precedence. The node projection carries that target to the drawer
+and takes Agent linkage only from explicit metadata. Summary tools consume the
+corrected target without their former Proxmox-specific exception.
+
+Current-build browser verification exercised the node History tab at 1h, 24h
+and 7d on 1440x1000 and 390x1000 viewports. Utilisation, network and thermal
+charts all contained retained points. Chart hover, range changes, Overview/History
+switching and reload were checked. API-only nodes no longer show Agent-only disk
+throughput or a fabricated linked-Agent label. A real linked-Agent case remains
+covered by drawer regression tests. No historical data was fabricated to fill
+the unavailable portion of the selected range.
+
+Worker verification passed the metrics package with the race detector
+(excluding timing-sensitive SLO tests), all query SLO tests without the race
+detector, and the full unified-resources package. Focused summary/reporting
+regressions, the two changed frontend suites (58 tests) and frontend type checking
+also passed. The node History receipt binds its final source hashes and returned
+range/point metadata separately from the model transcript.
+
+The final repeat after the canonical node-target correction completed in 215
+seconds with thirteen visible tool controls. It read 194 retained points through
+22:58:55 BST at 22:59:06, approximately eleven seconds old. Point count changed
+as the normal rollup replaced raw points with preferred minute buckets, while
+the recent tail remained available. The answer preserved the pressure-versus-
+utilisation distinction and recognised a resolved thermal alert, but still
+inferred a restart, continuous collection and a previously working Agent without
+sufficient evidence. It also repeated the known disk-health/wear explanation
+gap. These residuals remain in the outcome qualification gap. The final
+retained-canonical-coverage receipts bind the current code to Assistant
+expansion, output scrolling, answer pixels and reload at both viewports, plus
+the actual saved provider refusal and HTTP 409 gate.
+
+
+## Redesign baseline retest, 2026-09-05
+
+The unchanged performance question completed in 224 seconds with eleven visible
+tool controls after the local disk and timestamp-context changes. Playwright
+exercised `/patrol` at 1440x1000 and 390x1000, including keyboard/pointer tool
+expansion, output scrolling, Escape, session selection and reload. Initial answer
+pixels were inspected. Final conclusion pixels and the focused disk question
+remain pending, so this is not full browser qualification for the slice.
+
+The model explicitly repeated the timestamp caveat while still calling the
+returned series unbroken and inferring that the alert start almost certainly
+marked collection start. It also treated a present-time pressure read as a
+definitive resolution of the historical pressure question. These are failed
+diagnoses, not evidence that more caveat text is sufficient.
+
+The changed disk tool returned SMART `PASSED`, canonical `warning`, and remaining
+life 63, but neither SMART counters nor risk reasons. A direct canonical resource
+API read confirmed those fields are absent upstream too. The subsequent source-status read identified `proxmox.status=stale`, which
+explains a freshness warning without a hardware-risk reason. The disk tool had
+omitted that field too. Preserve the canonical source status alongside health
+and risk before qualifying this explanation. Do not fabricate a wear warning
+from 63 percent remaining.
+
+Artifacts remain private under the local
+`tmp/patrol-outcome-telemetry/homelab/diagnostic-evidence-performance` directory.
+An initial browser attempt never reached a provider because the configured SSD
+temporary directory was absent. The directory was restored before the recorded
+run. Installed Chrome was used because the expected cached Playwright browser
+was unavailable. No refused readiness probe or infrastructure mutation occurred.
+
+The qualification scorer also needs an explicit trust review: current root-cause
+grounding checks match resource names/IDs in a named Markdown section, and other
+diagnosis checks use required words. Combined with code-inserted proposal prose,
+this can reward a formatted assertion without independent diagnostic support.
+Keep the physical fault oracles and action readback checks, but do not treat
+those text checks as semantic proof of cause.
+
+### Regression work discovered during redesign
+
+PR #1920 CI exposed a retained-history performance regression, including the
+bounded chart query and shared store reads. Reconciliation must remain correct,
+but display aggregation belongs inside SQLite rather than scanning all retained
+points into Go. The working correction also reuses scan destinations. Initial paired
+worker benchmarks confirm reduced allocations but still show material runtime
+regressions. Performance correction and source-bound browser proof remain open.
+
+The resource API test selected the first canonical `agent` resource and assumed
+it was Agent-backed. A Proxmox-only node has the same canonical resource type,
+but different history storage coordinates. The test now selects the fixture's
+actual Agent identity and separately asserts the Proxmox node target.
+
+Disk warning investigation exposed another canonical gap. Proxmox physical disks
+poll every five minutes by default, but source freshness currently uses the
+shorter general Proxmox threshold. Registry merge status selection also requires
+a regression check for recovery from stale Proxmox data. Preserve source
+freshness in the tool now, and correct cadence/recovery at the owning registry
+and monitoring boundary before qualifying those warnings as useful diagnosis.
+
+### Disk live retest, 2026-09-06 local time
+
+The current local Assistant answered the disk question through Claude Opus 5
+in about three minutes. The source freshness field was visible and correctly
+identified as distinct from SMART failure. The answer still failed qualification:
+it invented a midnight polling restart from coincident timestamps, treated the
+remaining-life measurement as ambiguous, and hit three rejected disk-detail calls.
+The tool advertised `physical-disk` for get but its handler did not support it.
+
+The next working correction routes exact canonical disk get/health requests
+through the same shared projection and labels remaining life with the explicit
+`life_remaining_percent` field. The live answer is a recorded failure, not proof
+of completed diagnosis. The screenshots exercised `/patrol`, Assistant, tool
+expansions, keyboard activation, narrow wrapping, Escape and session reload at
+1440x1000 and 390x1000. Fresh browser proof is required after these later changes.
+
+### Canonical freshness correction under verification
+
+Physical disk collection now carries its independent polling interval into the
+canonical per-source freshness record. Staleness uses at least two expected
+intervals, while retaining a longer configured source threshold. A new observation
+from the highest-priority available source may refresh its resource status,
+including a Proxmox-only resource that previously kept its first warning.
+The targeted regression covers five- and fifteen-minute disk schedules, stale
+transition, identity-preserving recovery and measured hardware risk after recovery.
+The live collector exposed a further loss in the quick temperature refresh:
+`physicalDiskFromReadStateView` discarded cadence before writing disk records
+back to monitoring state. That conversion now preserves the typed source status
+schedule. Broader registry regressions and final browser proof remain required. This does not make timestamp coincidences evidence of collector restarts.
+
+The retained-query candidate also encountered a SQLite native fault during the
+full metrics package run. The same baseline package passed. This is unresolved
+until the failing context and current candidate are verified. Narrow benchmark
+and query-plan success do not close this failure.
+
+### Continued orchestration review
+
+The assessment sweep currently receives only the retained finding title, severity,
+resource and up to 500 characters of old evidence. It receives neither the main
+run's observations nor their collection times. That is insufficient context for a
+new present/resolved judgment. The completion obligation may remain mechanical,
+but any continuation must share the actual investigation context. It must not
+turn old evidence into a fresh assessment.
+
+The investigation evidence-call floor also misclassifies a failed or
+approval-blocked read as no evidence at all. Such a result establishes a limit
+on available access, while a successful tool call alone establishes no diagnostic
+quality. Remove the quality inference and forced start-repair turn. Preserve
+explicit call/turn/time limits and let an incomplete or uncertain conclusion
+record the unavailable evidence. Action authority remains independently enforced.
+
+The unmatched-signal follow-up rebuilds a reduced evidence list after the main
+model run and prohibits further investigation. Its candidate selection ranks
+health/reliability/backup/connectivity/anomaly categories and caps them at twenty.
+This duplicates interpretation outside the model and discards the main reasoning
+context. The planned replacement is the original model assessment with complete
+seed/tool evidence, measured against independent missed-fault controls.
+
+A fresh live canonical disk read after the cadence round-trip correction returned
+`online` and `expectedUpdateIntervalSeconds=300`. This verifies the actual
+collector-to-canonical-resource path. Full affected package tests and the current
+Assistant answer remain separate acceptance checks.
+
+### Current disk answer and browser evidence
+
+The 2026-09-06 00:28 BST Assistant retest completed through the configured Claude
+subscription route in 2m38s, with 12,436 reported tokens. All nine evidence calls
+completed, including the exact canonical disk detail request that failed before.
+The answer correctly interpreted 63 percent remaining life, source recency and
+the distinction between disk and node temperature evidence.
+
+The overall answer still fails qualification. It asserted that recovery exists
+because an online backup datastore has space, without reading actual backup
+coverage or restore evidence. It also offered host commands without checking
+that execution access exists. The conclusion should remain bounded to the
+observed disk state. Latency and unnecessary fleet-wide explanation remain
+product defects to address in the shared diagnostic contract.
+
+Playwright exercised `/patrol` and the Assistant drawer at 1440x1000 and
+390x1000, expanded all nine evidence calls with keyboard activation, scrolled
+long outputs, collapsed them, used Escape, reloaded and reopened the retained
+session. Root inspection covered actual disk-list/detail output pixels, retained
+summary output and the final answer through its last paragraph. The answer and
+evidence remain readable at both widths. The source-bound receipt and screenshots
+are private under `tmp/patrol-outcome-telemetry/homelab/diagnostic-evidence-disk-canonical-final`.
+This is interface and data-path proof, not a passing diagnostic outcome.
+
+### Retained-performance retest and transport correction
+
+The 00:32 BST read-only performance request completed in 3m36s with 17,677
+reported tokens. It correctly reported unavailable agent access and separated
+high memory occupancy from established pressure. It still called the retained
+slice unbroken and inferred collector startup from coincident timestamps despite
+explicitly repeating the evidence caveat. That diagnosis remains failed.
+
+This run also exposed raw serialized routing JSON in the visible conversation.
+The subscription fallback had accumulated native CLI text before the first
+declared tool call and forwarded it as Assistant content. It also retained only
+one call from a native batch. The working provider correction returns the entire
+first declared batch in order, emits no routing-turn prose, and keeps the
+structured final answer unchanged. Targeted provider tests pass. All explicit
+refusal and local-tool isolation boundaries remain. Fresh browser evidence is
+required after this runtime change.
+
+The transport retest exceeded the browser's five-minute limit and was cancelled
+when that browser closed. The saved session contains four ordered routing turns
+with 2, 5, 4 and 3 calls respectively. Their answer content is empty, so the
+protocol text leak is absent from the persisted transport result. Fourteen calls
+did not produce a final answer before cancellation. This is incomplete browser
+qualification and failed interactive latency, not a completed diagnostic run.
+The response instruction currently demands thorough investigation and suggested
+next steps even after the user's specific question can be answered. Review that
+shared product instruction before collecting another equally broad run.
+
+### Scoped response and rendering retest
+
+The 00:56 BST performance request completed in 2m42s with 13,021 reported
+tokens after the shared response prompt was scoped to the user's actual job.
+Routing JSON was absent, missing agent access remained explicit and memory
+pressure was correctly left unknown. The answer still overstated continuous
+coverage from retained timestamps, inferred history start causes, treated an
+alert on the same utilization measurement as corroboration, and mixed UTC/BST.
+This remains a failed diagnostic outcome. It does not qualify autonomous Patrol.
+
+That real answer exposed a six-column table expanding the narrow conversation.
+The shared sanitized renderer now gives tables their own keyboard-scrollable
+region. Playwright reopened the real session at 1440x1000, 900x1000 and 390x1000,
+reached the last column, verified fixed conversation width, and exercised Escape,
+reload and session reopening. Browser-only short and streaming table fixtures
+confirmed preserved focus, region identity and scroll position. Actual pixels
+were inspected. The source-bound frontend receipt is
+`frontend-modern/browser-verification.json`; private artifacts are under
+`tmp/patrol-outcome-telemetry/homelab/markdown-table-final`. These fixture results
+establish rendering behavior only. No additional model calls were made.
+
+### Final evidence-foundation proof
+
+The affected tools, chat, providers, models, unified resources, monitoring and
+resource API package suites pass on the worker. The final metrics implementation
+(`store.go` SHA256 `5ef4b22506ecc73131bcd881a5bbc72d2a45f43f393f2dccbfba52dc287b18e8`)
+passes the full metrics suite in 90.446s, the database suite in 0.131s and the
+focused concurrent read/write race proof in 19.625s. Tests cover new/deleted
+history visibility, resource isolation, bounded compiled-statement retention,
+one-connection operation and transaction-bound query instrumentation.
+
+The unchanged bounded chart benchmark measures 889.3 microseconds baseline
+versus 888.8 microseconds candidate (p=.796, n=10), with no significant slowdown.
+Final paired metrics benchmarks pass the existing regression checker. The
+single-metric downsample case reports +10.00% (p=.005, n=10), close to the
+checker's greater-than-10% threshold. Raw single-series and both multi-metric
+queries have no significant latency difference. These are bounded worker
+measurements, not a production latency guarantee. The earlier +20.34% chart
+regression is corrected by reusing compiled presence SQL while evaluating it
+inside every current read snapshot. No history or tier-presence result is cached.
+
+One earlier metrics package run terminated inside SQLite native binding code.
+Subsequent full and focused race runs passed, including the final implementation.
+The original fault has no established root cause and is not labelled harmless
+or explained by the successful reruns. Its private worker log is
+`paired-metrics-local-20260905T235637/full-metrics-final.log`.
+
+### Diagnostic orchestration slice, 2026-09-06
+
+The investigation loop no longer rejects a conclusion for having no successful
+read or forces extra tool calls when seed context or unavailable access supports
+an honest unknown conclusion. Evidence attempts still consume the configured
+limit, which remains visible as a system fact. Removed completion checkpoints
+and the Assistant/Watch 12/18-call wrap-up instructions from tool results, along
+with the four silent-tool-turn cutoff. Overall turns, advertised capability
+boundaries, configured budgets and repeated-call/error recovery remain bounded.
+
+Full worker chat and AI packages pass against the exact changed runtime source.
+The longer-read regression executes twenty distinct reads over five silent tool
+turns, retains unchanged observations, and preserves the model's conclusion.
+Seed-only and failed/policy-blocked read cases retain uncertainty. These are
+contract tests, not proof of real diagnosis.
+
+Browser qualification reproduced a linked-issue defect: a finding folded under
+an existing alert could not stay selected because selection searched only the
+non-mirrored display groups. Selection now resolves the canonical filtered
+findings, preserving the existing interactive inline surface. The final
+Playwright matrix opens ordinary and mirrored findings at 1440/900/390 widths,
+opens the nested failed-read transcript, collapses the review and
+passes the same finding, unknown conclusion and access limit to Assistant.
+Scripted inference and blocked writes make this a presentation/context proof.
+
+PR #1920's initial worker proof passed against local source 5288b64d, but its CI
+comparison against the actual base 4f9de86e failed nine benchmark comparisons,
+including small single-resource retained reads. Landing is blocked while the
+exact base/candidate comparison is reproduced and corrected. Do not treat the
+previous narrower performance pass as complete CI qualification.
+
+### Exact-base retained-read correction
+
+The small retained-read path performed an extra tier-presence query and opened
+an explicit transaction even when the reconciliation was already one SQLite
+statement. Plain reads now reuse bounded compiled reconciliation statements.
+All-metric plain reads retain index time order instead of sorting by metric.
+Each output series remains chronological. Display aggregation retains its
+required series grouping and same-snapshot presence optimization. No data or
+tier-presence result is cached.
+
+The corrected `store.go` SHA256 is
+`41132f7eae5a987e72092aceb8813a20f3dc44986c849023ffa0654e5bfe58aa`.
+Ten alternating 100 ms worker samples against exact PR base 4f9de86e report:
+
+| Query | Base | Correction | Comparison |
+|---|---:|---:|---|
+| Bounded single-metric API chart | 848.6 us | 894.5 us | No significant difference, p=.436 |
+| Single series across resources | 916.98 us | 47.12 us | -94.86%, p<.001 |
+| Single query, 500-node load fixture | 18.78 ms | 51.50 us | -99.73%, p<.001 |
+| All-metric dashboard | 309.3 us | 174.3 us | -43.66%, p<.001 |
+| Batch dashboard, 10 nodes | 1.912 ms | 1.723 ms | -9.86%, p=.007 |
+| Batch dashboard, 50 nodes | 8.807 ms | 8.337 ms | -5.34%, p=.023 |
+| Batch dashboard, 100 nodes | 17.56 ms | 16.08 ms | -8.43%, p=.002 |
+| Batch dashboard, 500 nodes | 87.56 ms | 82.34 ms | No significant difference, p=.052 |
+
+These are worker measurements, not a production latency guarantee. An exact
+query-plan reproduction shows the old single-query SQL choosing the broad
+tier/time index on this worker. The corrected runtime uses the series/range
+index explicitly. This explains the large worker single-query difference but
+does not establish which plan the prior CI runner chose. No benchmark threshold
+was relaxed. The final full metrics suite passes in 87.114s, the database
+suite in 0.119s and focused concurrent read/write race proof in 19.065s. The
+remaining failed CI comparisons have no significant worker latency difference:
+API memory fallback, 163.6 versus 167.3 us (p=.315), and the fifty-guest chart
+batch, 128.0 versus 121.3 ms (p=.190). These comparisons cover the earlier failed
+cases. A fresh CI run must still qualify the final landing commit. The earlier
+unexplained native SQLite fault remains an open observation.
+
+Private worker evidence is retained under
+`/opt/pulse-release-worker/pr1920-bench-4f9-c5d2/`, with source-bound
+`full-metrics-second.log`, `full-db-second.log`, `race-metrics-second.log`,
+`second-candidate-*` and `adj-*` artifacts.
+
+
+### Detection conversation redesign
+
+The original model conversation now owns reads, finding decisions and correction
+of rejected calls within the explicit run limit. Removed the separate evaluator,
+old-evidence assessment sweep, signal-count report budget and post-finding prompt
+replacement. The standing prompt describes Pulse's evidence, existing alerts,
+active-finding obligation and action boundaries without fixed tool sequences or
+forcing symptom reports before investigation. A run with no new finding may be called all clear only when the model's
+evidence supports that conclusion. Final-turn and output-limit recovery instructions
+also retain missing/stale evidence and avoid repeating accepted assessments.
+
+The 01:55 UTC ordinary Assistant recheck did not yield a final answer. Server
+logs record `context canceled` at 01:57:06 UTC, before the qualification runner
+was interrupted at about 01:57:44 UTC. The request's eleven tool calls and partial
+session remain reproduction evidence. It is a runtime failure with an unresolved
+cancellation source, not a completed diagnosis. Its source/binary correspondence
+has not been established as an exact final-build proof. No autonomous request or
+paid alternate-provider call was made.
+
+The rebuilt local runtime retains the same unknown cause and failed-read evidence
+through ordinary and alert-mirrored finding review and the linked Assistant.
+The scripted browser matrix passes at 1440x1000, 900x1000 and 390x1000, including
+nested transcript expansion/collapse, keyboard review and explanation, selected
+issue identity, draft preservation, menu dismissal and error/retry. Actual pixels
+were inspected. This proves presentation and context continuity, not diagnosis.
+The private source-bound receipt is `tmp/patrol-assistant-journey/result.json`.
+Runtime binary SHA-256 before/after the pass was
+`724941045a17714460f703724528a040645c752aabe01c114fc1aae6cecca52c`.
+
+Final affected worker proof passes: full chat 13.670s, full AI 10.216s,
+Patrol/API bridge tests 24.421s and focused conversation race tests 1.043s.
+The race cases cover mixed accepted/rejected finding calls, a fresh evidence read
+between independent findings, provider failure after an accepted finding and
+exact accepted-call idempotency. The integration case retains an omitted
+assessment as active and incomplete after exactly one original model run.
+Zero, one and fifteen heuristic flags do not change the run limit, trigger an
+auxiliary session, manufacture findings or inflate model usage. Existing
+control-mode, capability and objective-observer tests remain part of the passing
+full packages. Private proof logs are `/opt/pulse-release-worker/final-affected2-chat.log`
+and `final-affected3-{ai,api,race}.log`.
+
+The subsequent ordinary Assistant check on the unchanged binary completed from
+02:45:25.486 to 02:48:18.734 UTC, about 173 seconds, with thirteen visible tool
+records. It distinguished high utilisation from proven pressure and preserved
+failed access. It still inferred observation startup from timestamp coincidence
+and asserted that a change across retained resolutions was not an aggregation
+artefact without supporting evidence. The temporal conclusion therefore remains
+unqualified. Completion of this request does not explain the earlier cancellation
+and does not qualify autonomous Patrol.
+
+This real run also reproduced a canonical result defect: `pulse_read` with
+`action=file` returned missing-agent text but a successful result. The shared
+file-read boundary now returns a tool error for absent agents and nonzero
+host/container command exits, preserving the original explanation. Success
+continues to require actual file content. Focused negative controls cover absent
+agents and both stderr/stdout error paths. The final real Assistant check executed the exact file read once and returned
+`tool_end.success=false`. The failed badge and original explanation were visible
+in desktop and narrow views, survived expansion/collapse and reload, and the
+model described a collection limit without claiming file evidence. The single
+request ran from 02:52:16.552 to 02:52:48.461 UTC. The scripted linked-issue matrix
+also passed again at 1440/900/390 widths on the final rebuilt runtime.
+
+Final binary SHA-256 was
+`a575a40a640af1aaed479b56636dc5a3205c76df6999bbb20546ccf09fe70659`,
+unchanged throughout both passes. `tools_file.go` SHA-256 was
+`a5585c787e8a24aa5bc694b40a6c945709ecab06d9f581105131531dd16d3ac3`.
+Private receipts remain under the task's
+`diagnostic-evidence-file-read-failure-final/` and the repository's
+`tmp/patrol-assistant-journey/`. This qualifies the named ordinary read failure
+and presentation contract, not autonomous investigation or action outcomes.
+
+The final full tools package passes in 59.413s and focused file-read race proof
+in 1.033s, covering successful reads alongside the failed-read controls.
+Private worker logs are `file-read-full.log` and `file-read-race.log` under
+`/opt/pulse-release-worker/`.
+
+## Integration qualification, 2026-09-06
+
+The detection and failed-read slice is committed as `61607333cc9e`. Integration
+with main `3f74c0c27304` required a fresh browser receipt. Intermediate-width
+inspection exposed the shared delivery-health card squeezing its explanation
+under the action buttons. The shared card now wraps by available width and uses
+an opaque semantic heading colour. Permanent fixtures include 900 pixels and
+check control bounds and heading overflow.
+
+Final worker proof passes 18 delivery-ordering cases and 12 Overview refresh
+cases at 1440, 900 and 390 pixels, with Overview checked in light and dark themes.
+Unavailable health, retained retry/dismiss actions, pending refresh and healthy
+recovery were exercised. Final card pixels were inspected at all three widths.
+Frontend lint, type checking and three affected test files pass. Focused merged
+Patrol/API/adapter/Docker-result proof passes. The final local scripted
+`/patrol` and `/alerts` journey passes at 1440x1000, 900x1000 and 390x1000,
+including nested failed-read evidence and the linked Assistant. This qualifies
+the integrated presentation and context contract only. Exact staged hook and
+remote landing are subsequent delivery checks. Real diagnosis and autonomous
+action outcomes remain unqualified, and the provider refusal remains enforced.
+
+## Qualification catalogue contract, 2026-09-06
+
+The published JSON schema omitted `health_process_stop`, although the runtime
+implements it and all three approved, rejected and autonomous restart scenarios
+use it. A regression against the checked-in catalogue reproduced all three
+rejections. The schema now accepts that implemented injector. The regression
+reads the published enum and checks actual catalogue faults rather than keeping
+a second injector list. This is a fault-type compatibility check, not a full
+JSON Schema validator or a live-model result.
+
+At source base `f779bf064ab4`, the corrected catalogue validates all eleven
+scenarios and both qualification packages pass on pulse-dev (4.232s and 0.005s).
+The private worker log is `/opt/pulse-release-worker/patrol-schema-f779.log`.
+No provider request, fault injection or infrastructure mutation was performed.
+
+The existing live runner covers Docker health, process exit/restart and network
+dependency faults. It has no missing-access or storage/backup scenario or
+corresponding independent lab probe. The ordinary homelab file-read failure
+proof remains useful but does not close that autonomous qualification gap.
+Those cases require suitable independent ground truth through the existing
+qualification framework before the overall goal can complete.
++
++## Retained-read performance correction, 2026-09-06
++
++Build and Test run `34008823529` for integration `f779bf064ab4` failed its
++benchmark comparison against exact main `3f74c0c27304`. All other jobs passed,
++and Core E2E run `34008823534` passed all eight browser shards. The benchmark
++failure comprised fifteen time/allocation comparisons, including batch reads
++up to 59% slower and small-read bytes about 198% higher. Earlier narrow worker
++comparisons omitted the actual QueryAllBatch cases and did not establish this
++integrated performance result. The initial status report calling that CI job
++passed was incorrect and was explicitly corrected.
++
++The canonical reader now reuses bounded SQL templates and numbered bindings,
++checks absent preferred tiers once within the current statement, and appends
++consecutive results directly to their series. It retains tier reconciliation,
++current snapshots, scope isolation and output semantics. No benchmark threshold
++was relaxed. An initial correction still regressed the plain raw-read case by
++11% and was revised before landing.
++
++Final production `pkg/metrics/store.go` SHA-256:
++`9a66d1acea82c17ca540abe9a9ee66e089a36420620e2ebb8ca7e6d102191a8d`.
++Ten alternating 100ms samples on pulse-dev, Go 1.26.8 and GOMAXPROCS=4,
++compare the final implementation with exact base `3f74c0c27304`. The complete
++selected Query, QueryAllBatch, RollupCandidate, fleet dashboard, history API,
++chart batch and NormalizeRoute benchmark families have no statistically
++significant greater-than-10% regression in time, bytes or allocations. Plain
++raw reads show no significant time change. Batch reads improve 16–42%, with
++bytes reduced 28–34%. Single-metric downsampling is 5.66% slower and the
++1,000-point rollup candidate is 6.04% slower, both inside the unchanged gate.
++The bounded history API shows no significant time change. These are selected
++worker comparisons, not a claim that final remote CI has passed.
++
++Private raw samples and benchstat outputs are under
++`tmp/patrol-f779-v2-selected/` and `tmp/patrol-f779-v2-normalize/` at the
++workspace root. Focused tests cover newly appearing preferred buckets after a
++cached absent-tier read, current resource family, metric, window and display
++step bindings, per-series overlap and batch parity. Integration with main
++`6c000837e27b` brings three test-only changes and no additional runtime changes.
++Full metrics and database packages pass on pulse-dev in 77.265s and 0.272s.
++Focused retained coverage, fresh bindings and batch identity race proof passes
++in 5.349s. The two latency-based concurrent SLO tests run in the ordinary suite
++but explicitly skip under the race detector. A separate canonical hot-path
++regression exercises eight concurrent query scopes and mixed display steps
++through a one-connection pool without latency assertions. It passes normally
++(0.043s) and under race (2.106s), with no cross-query binding leakage or lock
++inversion. Its worker log is `patrol-retained-concurrent-bindings.log`.
++Private full/race logs are under
++`tmp/patrol-f779-final-proof/`. Exact staged hook and remote landing remain
++pending. This correction does not close the outstanding real-model/action outcome gap.
diff --cc docs/release-control/v6/internal/status.json
index 6583f6d250,1f1a6bd192..776555419b
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@@ -10201,7 -10218,7 +10201,7 @@@
},
{
"id": "patrol-assistant-customer-outcome-qualification",
- "summary": "The maintainer requested a whole-design assessment and an explicit completion goal for Patrol and Assistant. The ordered plan and source-bound evidence are in docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md. The contract separates observations, model conclusions, proposals, execution and independently verified outcomes. Assistant continues the same issue and governed action records. The explicit explanation handoff is an implemented frontend foundation, not outcome qualification. The recorded 2026-09-05 latest-report, monitoring-active, multi-ping review excluded development and deployment proof and contained 127 paid installs, 71 with Patrol enabled and 23 with Assistant calls. Fourteen reported verified resolutions came from one install. Paid includes all non-free tiers. Activity cooccurrence does not establish a successful linked task, and schema 17 outcome/provider/cost fields had no adoption in that review. Real read-only homelab testing with Claude Opus 5 exposed missing canonical evidence, history target/tier gaps, premature context loss, unsupported causal claims and multi-minute responses. Prior history and handoff changes are recorded in the plan. The current working slice removes proposal rationale promotion into Root Cause and duplicate causal inference, preserves disk SMART/risk/source freshness and explicit remaining life, supports canonical disk get/health, and corrects collector cadence and status recovery. Targeted regressions and the live disk data path pass. Affected full worker package suites pass. The single-metric downsample regression and an adjacent bounded chart regression are corrected. Compiled presence statements are reused within a bounded set, but every query reads current data in one snapshot. The chart comparison shows no significant slowdown. Final metrics/database suites, focused concurrency race checks and the existing benchmark guard pass. Single-metric downsampling remains close to the performance threshold. PR #1920 CI subsequently failed nine benchmark comparisons against the actual base 4f9de86e, including small retained reads. The prior worker comparison used local source 5288b64d and does not establish final CI performance. The exact-base correction removes unnecessary plain-read presence probes, transaction wrappers and metric sorting while retaining canonical reconciliation and current snapshots. Full metrics/database and focused race suites pass. Ten alternating worker samples cover the previously failed CI comparisons without a significant greater-than-10% regression. Final CI landing qualification remains pending. One earlier SQLite native binding fault has no established root cause, although subsequent final full and focused race proofs pass. The latest live answers still infer collector startup from timestamp coincidence, claim continuous coverage from retained spacing and infer backup recovery from an online datastore. They fail diagnostic qualification. A serialized routing-envelope leak prompted a subscription transport correction with targeted regression proof, verified without routing prose in a completed real Assistant answer. A narrow answer-table overflow defect is corrected in the shared sanitized renderer with desktop, intermediate and mobile browser proof. The selected subscription provider explicitly refused autonomous Patrol readiness. The runtime and API preserve that refusal and prevent execution. Ordinary Assistant success is not autonomous proof. Required healthy/unhealthy, dependency, missing-access, backup/capacity and approved/rejected action qualification remains incomplete. Independent volunteered Pro environments are required before claiming repeatable customer value or wider readiness. The next diagnostic slice removes successful-read completion floors, evidence checkpoint instructions and generic call-count/silent-turn wrap-up policy. Full worker chat and AI suites pass. Browser qualification exposed and corrected mirrored-alert finding selection in the shared review lookup. Ordinary/mirrored records and linked uncertainty/failed-read context pass Playwright at 1440/900/390 widths. The detection slice removes contextless evaluation and assessment sessions, the flag-count turn ladder, signal-count report quotas and post-finding prompt replacement. The original conversation retains evidence tools and accepted records alongside errors. Full chat and AI packages, focused Patrol API tests and conversation race regressions pass. Source-bound scripted browser proof against the rebuilt runtime preserves linked uncertainty and failed reads at 1440/900/390 widths. Integration with current main and final landing verification remain pending. The latest ordinary Assistant recheck ended with context cancellation before a final answer, with eleven tool results retained. Its cancellation source and exact running binary correspondence are unresolved. The subsequent unchanged-runtime ordinary Assistant check completed in about 173 seconds, correctly distinguished utilisation from pressure, but still made unsupported temporal claims. It also exposed a failed file read marked successful. The shared file-read correction now preserves error status for absent agents and nonzero exits, with a final real ordinary file-read check returning success=false and showing the failed badge, preserved explanation and honest collection limit through reload. The linked-issue browser matrix passes again on the final rebuilt runtime. The full tools package and focused file-read race proof pass. Final integrated landing proof remains pending. Real-model/action outcome qualification remains open. Integrated main 3f74c0c27304 passes focused API proof and final frontend lint, type checking and three affected test files. Permanent browser fixtures pass 18 delivery-ordering and 12 light/dark Overview cases at 1440/900/390 widths after repairing shared card wrapping and heading readability. The final linked Patrol/Assistant browser matrix also passes. Exact staged hook and remote landing remain pending. These checks do not close the real-model/action outcome gap. The qualification schema now accepts the implemented health_process_stop injector used by all three action scenarios. A new catalogue/schema compatibility regression reproduced the old rejection. All eleven manifests validate and both qualification packages pass on pulse-dev. The existing live lab has no missing-access or storage/backup scenario or independent probe, so those required autonomous cases remain open. No live provider or infrastructure action was used for this schema proof.",
- "summary": "The 2026-09-05 product review found that Explain with Assistant opened a blank generic conversation and the attention workbench discarded richer canonical finding context. The explicit explanation dispatcher and canonical handoff repair address that frontend break, with scripted browser proof and regression tests. They do not qualify model reasoning, real infrastructure actions, or repeated customer value. Latest-report, monitoring-active, multi-ping telemetry excluding dev and deployment proof contained 127 paid installs, 71 with Patrol enabled and 23 with Assistant calls. Fourteen reported verified resolutions were concentrated in one install. Paid includes all non-free tiers, and activity cooccurrence is not a linked successful journey. Schema 17 outcome/provider/cost fields had no adoption in that review. Three real jobs remain to qualify across named provider/model/version configurations: unhealthy service diagnosis, backup or capacity risk, and supported VM/LXC plan, approval and verified result. Repeatability must be established across independent paid customer environments without pooling free-tier or ineligible installs. The same-day real maintainer homelab evaluation with Claude Opus 5 exposed missing Proxmox temperature-tool evidence, contradictory summary health, incomplete visible prose, alert-count confusion and an inaccurately classified provider refusal during Patrol readiness. The shared temperature projection and premature within-window evidence compaction are repaired, while the documented reasoning, completion, readiness and end-to-end outcome failures remain unqualified. The continuation repaired canonical resource lookup, operation-versus-disk filtering, Proxmox CPU topology and retained resource-scoped history across backend restarts. Unscoped summary/baseline modernization, wear semantics, disk risk explanation and complete retained-window coverage remain open. A named-resource repeat exposed overly restrictive current_resource recovery guidance, now corrected without weakening the attachment boundary. Live testing also exposed warning-based API execution after an incomplete provider check. Runtime and API now enforce the selected-mode verdict, including saved incomplete results, and the repaired live endpoint returns HTTP 409. One read-only test run started before the gate correction and was stopped, so it is not qualification evidence. The evidence interpretation continuation replaces model-facing heuristic summaries with retained statistics, explicit source scope, real observation coverage and preserved bucket extrema/timestamps. A typed provider_refusal diagnosis now survives CLI exit and legacy cache decoding without granting readiness or repeating the refused request. The final real summary distinguished utilisation from demonstrated pressure and explained extrema versus bucket averages, but still speculated about sensor artefacts and monitoring restarts, inferred continuous coverage from minute spacing, and conflated returned history with retained history. Reasoning remains unqualified. A local fixture confirmed that 24-hour Query and QueryAll can hide newer raw points when a preferred aggregate tier is non-empty. Shared temporal tier reconciliation, including batch queries, is required in L10 before claiming current requested-window history.",
++ "summary": "The explicit Patrol/Assistant redesign goal and ordered source-bound evidence are recorded in docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md. Observations, conclusions, proposals, execution and independently verified outcomes remain distinct, with Assistant continuing the same issue and governed action records. The 2026-09-05 telemetry review found 127 paid installs, 71 with Patrol enabled and 23 with Assistant calls, but fourteen verified resolutions came from one install and schema 17 outcome/provider/cost fields had no adoption. Activity does not establish useful linked tasks. Implemented corrections preserve canonical risk, evidence provenance, retained history, failed-read status and the original diagnostic conversation while removing proposal-as-root-cause promotion, duplicate causal inference, contextless evaluation passes, report quotas and call-count completion proxies. Full affected package and focused race proofs, real ordinary failed-read verification and linked-issue browser matrices are recorded in the plan. Integrated presentation passes 18 delivery-ordering and 12 Overview light/dark cases at 1440/900/390 widths, plus the Patrol/Assistant journey. The qualification schema accepts the implemented health_process_stop injector and all eleven manifests validate. Integration f779bf064ab4 passed all eight Core E2E shards but Build and Test run 34008823529 failed fifteen benchmark comparisons against exact main 3f74c0c27304. An initial performance correction still failed the raw-read comparison and was revised. The final reader reuses bounded SQL templates/current numbered bindings, avoids repeated absent-tier probes within the same snapshot and appends output series directly. Ten alternating worker samples of complete selected query, batch, fleet, API, chart and route benchmark families show no significant greater-than-10% time, byte or allocation regression against that exact base. Final full metrics/database proof passes (77.265s/0.272s), as does focused retained/binding/batch race proof (5.349s). Latency-based concurrent SLO tests pass normally but skip under race. A separate concurrent binding regression with eight scopes and a one-connection pool passes normally (0.043s) and under race (2.106s). Exact staged hook and remote landing remain pending. An earlier native SQLite binding fault has no established root cause. The latest ordinary model diagnosis still makes unsupported temporal claims and remains unqualified despite the successful failed-read contract check. Claude Max explicitly refused autonomous readiness, and cached refusal/API409 enforcement remains intact. Ordinary Assistant success does not qualify autonomy. Required healthy/unhealthy, dependency, missing-access, storage/backup and approved/rejected action outcome qualification remains incomplete. The live catalogue lacks missing-access and storage/backup scenarios with independent probes. Alternate paid-provider approval remains pending, with no paid request, fault injection or infrastructure mutation performed. Volunteered Pro environments remain a separate wider-readiness gate.",
"owner": "project-owner",
"status": "planned",
"recorded_at": "2026-09-05",
diff --cc docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index ca1ea3af6b,efaed6c42c..6770cfc059
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@@ -15,55 -15,17 +15,65 @@@
## Purpose
-The open `patrol-assistant-customer-outcome-qualification` gap includes retained
-query coverage in `pkg/metrics/store.go`. A 24-hour `Query` returns the first
-non-empty resolution tier, and `QueryAll` fills missing metric names rather than
-missing times. A fixture with a minute-tier CPU point at 21:37 and a raw point
-at 22:16 returns only 21:37 for both 24-hour APIs, while a two-hour query returns
-22:16. The new model-facing evidence contract discloses the returned timestamps
-but does not repair this shared-store defect. Canonical follow-up must reconcile
-temporal coverage across tiers for single-series, all-series and batch queries,
-with explicit bucket precedence, extrema and downsampling semantics. Do not
-claim complete or current requested-window coverage from the present fallback
-behavior. This belongs to metrics-store qualification, not model prompting.
+Retained reads use one shared query contract in `pkg/metrics/store.go` for
+`Query`, `QueryAll`, `QueryAllBatch` and `QueryMetricTypesBatch`. A non-empty
+preferred resolution no longer hides a newer raw tail, an older uncovered
+bucket, a gap, or another metric on the same resource. Resource identity,
+metric filters and timestamp bounds apply to every tier and overlap probe.
+
+Tier priority still follows the requested range. An aggregate owns its UTC
+minute/hour/day bucket when that tier has priority. Lower-priority observations
+inside it are excluded. A coarser fallback that overlaps a preferred observation
+is omitted as an indivisible aggregate, never split or interpolated. Only
+buckets whose stored timestamp lies in the requested window participate. This
+avoids double-counting and prevents observations outside the requested range
+from suppressing evidence inside it. Reconciliation precedes display
+aggregation, which retains the existing unweighted mean and centred display
+bucket timestamp. Single-resource charts aggregate in SQLite after reconciliation so only display
+buckets cross into Go. Fleet queries stream ordered observations into bounded
+display buckets without retaining every input point. Both preserve identical
+bucket, mean and extrema semantics, and reuse scan destinations across rows.
+
+Each bounded resource chunk reads one consistent snapshot. Plain reads execute
+the canonical reconciliation query as one SQLite statement. They require no
+separate presence probe or explicit transaction. All-metric plain reads use
+resource/time index order, which preserves each output series' chronology
+without an unnecessary metric sort. Streaming display aggregation still
+requires contiguous series and requests that ordering explicitly.
+
+Display-aggregated reads use one transaction. Indexed existence checks identify
+which retention tiers have observations in that snapshot. Every present tier
+participates in the shared indexed overlap query. Presence never stands in for
+per-series coverage. The store retains at most 32 compiled read-statement shapes
- and evaluates them again inside each current read snapshot.
- It never caches tier presence, query results or timestamp windows. Less common
++and 32 SQL templates keyed only by parameter counts, tier order and aggregation
++shape. Numbered SQLite bindings supply each current identity, window and display
++step once across all branches. An uncorrelated existence guard in the same
++statement avoids per-observation overlap probes when a preferred tier is absent.
++If any preferred observation exists, the correlated same-series check still
++owns coverage. Both checks are reevaluated in the current snapshot.
++The template lock performs no database I/O and is separate from statement
++preparation. The store never caches tier presence, query results or timestamp
++windows. Consecutive output points append directly to the current series slice,
++flushing it to the result map on series change and completion. Interleaved
++metrics resume their existing slices. A single chunk returns its result directly
++without copying the outer map. Less common
+shapes run uncached after the bound is reached. Preparation occurs before
+acquiring the transaction, including with a single-connection pool. The shared
+database instrumentation preserves timing for transaction-bound prepared
+statements, and database closure owns their lifetime. In display-aggregated
+reads, empty tiers need no per-observation probe and an all-raw series uses a
+direct range query. Fixed query dimensions need
+not be decoded again for every returned point. Query-plan tests exercise the runtime SQL builder,
+including all tier priorities and metric filters. Multi-stage rollups preserve
+recorded minima and maxima instead of taking extrema from bucket averages.
+Already discarded historical extrema cannot be reconstructed by this change.
+
+The `retained-metric-query-coverage` follow-up addresses the specific first-tier
+query defect reproduced during Patrol outcome qualification. Returned points
+still do not prove continuous collection or a complete requested window.
+Uncollected observations and unavailable pressure evidence remain unavailable.
+`pkg/metrics/store_tier_coverage_test.go` owns the overlap, tail, gap, per-series
+scope, downsampling parity and retained-extrema regression cases.
Resource-scoped Assistant performance reads query retained CPU, memory and
diff --cc pkg/metrics/store.go
index 1d7a5afbcb,9009c813ea..b81ae793ed
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@@ -196,11 -195,6 +196,17 @@@ type Store struct
db *pdb.InstrumentedDB
config StoreConfig
+ // Cache compiled read SQL only. Results always come from the current
+ // database snapshot. Bound the number of parameter-count shapes retained.
+ readMu sync.Mutex
+ readStatements map[string]*pdb.InstrumentedStmt
+
++ // SQL templates contain only parameter positions, never query values.
++ // Keep this lock separate from statement preparation, which may wait for
++ // a database connection while another caller owns a read transaction.
++ queryMu sync.Mutex
++ readQueryShapes map[retainedQueryShape]string
++
// Write buffer
bufferMu sync.Mutex
buffer []bufferedMetric
@@@ -1296,19 -1478,42 +1302,22 @@@ func (s *Store) queryBatch
if len(tiers) == 0 {
return map[string]map[string][]MetricPoint{}, nil
}
++ if len(unique) <= queryAllBatchChunkSize {
++ return s.queryRetainedChunk(resourceType, unique, normalizedMetricTypes, start, end, stepSecs, tiers)
++ }
result := make(map[string]map[string][]MetricPoint, len(unique))
- unresolved := unique
-
- for _, tier := range tiers {
- if len(unresolved) == 0 {
- break
+ // Reconcile every series in one snapshot per chunk. A resource with one
+ // aggregate must not hide another metric or a newer tail in a different tier.
+ for lo := 0; lo < len(unique); lo += queryAllBatchChunkSize {
+ hi := min(lo+queryAllBatchChunkSize, len(unique))
+ chunkResult, err := s.queryRetainedChunk(resourceType, unique[lo:hi], normalizedMetricTypes, start, end, stepSecs, tiers)
+ if err != nil {
+ return nil, err
}
-
- nextUnresolved := make([]string, 0, len(unresolved))
-
- // Process in chunks to stay within SQLite parameter limits.
- for lo := 0; lo < len(unresolved); lo += queryAllBatchChunkSize {
- hi := lo + queryAllBatchChunkSize
- if hi > len(unresolved) {
- hi = len(unresolved)
- }
- chunk := unresolved[lo:hi]
- tierResult, err := s.queryAllBatchWithTier(resourceType, chunk, normalizedMetricTypes, start, end, stepSecs, tier)
- if err != nil {
- return nil, err
- }
-
- // Match QueryAll semantics per resource: once any tier returns data
- // for a resource, stop falling back for that resource.
- for _, resID := range chunk {
- metricMap, found := tierResult[resID]
- if !found || len(metricMap) == 0 {
- nextUnresolved = append(nextUnresolved, resID)
- continue
- }
- result[resID] = metricMap
- }
+ for id, metrics := range chunkResult {
+ result[id] = metrics
}
-
- unresolved = nextUnresolved
}
return result, nil
@@@ -1338,237 -1543,64 +1347,275 @@@ func normalizeMetricTypes(metricTypes [
return normalized
}
-func (s *Store) queryAllBatchWithTier(resourceType string, resourceIDs []string, metricTypes []string, start, end time.Time, stepSecs int64, tier Tier) (map[string]map[string][]MetricPoint, error) {
- placeholders := make([]string, len(resourceIDs))
- for i := range resourceIDs {
- placeholders[i] = "?"
++type retainedQueryShape struct {
++ resources, metrics int
++ tiers [4]Tier
++ aggregate, groupSeries bool
++}
++
++func retainedQueryParameters(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier) []interface{} {
++ params := make([]interface{}, 0, len(resourceIDs)+len(metricTypes)+len(tiers)+4)
++ params = append(params, resourceType)
++ for _, id := range resourceIDs {
++ params = append(params, id)
++ }
++ for _, metric := range metricTypes {
++ params = append(params, metric)
++ }
++ params = append(params, start.Unix(), end.Unix())
++ for _, tier := range tiers {
++ params = append(params, string(tier))
++ }
++ if stepSecs > 1 {
++ params = append(params, stepSecs)
+ }
- inClause := strings.Join(placeholders, ",")
- metricClause := ""
- metricArgs := make([]interface{}, 0, len(metricTypes))
++ return params
++}
++
++func (s *Store) retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier, groupSeries bool) (string, []interface{}) {
++ shape := retainedQueryShape{resources: len(resourceIDs), metrics: len(metricTypes), aggregate: stepSecs > 1, groupSeries: groupSeries}
++ cacheable := len(tiers) <= len(shape.tiers)
++ copy(shape.tiers[:], tiers)
++ if cacheable {
++ s.queryMu.Lock()
++ query := s.readQueryShapes[shape]
++ s.queryMu.Unlock()
++ if query != "" {
++ return query, retainedQueryParameters(resourceType, resourceIDs, metricTypes, start, end, stepSecs, tiers)
++ }
++ }
++ query, params := retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, stepSecs, tiers, groupSeries)
++ if cacheable {
++ s.queryMu.Lock()
++ if len(s.readQueryShapes) < maxRetainedReadStatements {
++ if s.readQueryShapes == nil {
++ s.readQueryShapes = make(map[retainedQueryShape]string)
++ }
++ s.readQueryShapes[shape] = query
++ }
++ s.queryMu.Unlock()
++ }
++ return query, params
++}
++
+// retainedQuerySQL reconciles overlapping storage buckets before any display
+// aggregation. The preferred tier owns its bucket, lower tiers fill uncovered
+// buckets, and a coarser fallback is omitted if a preferred point overlaps it.
- // A bucket's presence does not establish continuous underlying collection.
- // All probes are scoped to the same series and requested timestamp window.
++// Presence never establishes continuous collection or per-series coverage.
++// Every probe is restricted to the requested identities and timestamp window.
+func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier, groupSeries bool) (string, []interface{}) {
- // Query dimensions fixed by the caller need not be decoded per point.
++ params := retainedQueryParameters(resourceType, resourceIDs, metricTypes, start, end, stepSecs, tiers)
+ identityColumns := ""
+ if len(resourceIDs) != 1 {
+ identityColumns += "resource_id, "
+ }
+ if len(metricTypes) != 1 {
+ identityColumns += "metric_type, "
+ }
- idSlots := strings.TrimSuffix(strings.Repeat("?,", len(resourceIDs)), ",")
- metricClause := ""
- if len(metricTypes) > 0 {
- metricClause = " AND m.metric_type IN (" + strings.TrimSuffix(strings.Repeat("?,", len(metricTypes)), ",") + ")"
- }
++ // Reuse SQLite's numbered bindings across every branch and overlap probe.
++ // Each identity, timestamp and display step is bound only once per read.
++ slots := func(first, count int) string {
++ values := make([]string, count)
++ for i := range values {
++ values[i] = fmt.Sprintf("?%d", first+i)
++ }
++ return strings.Join(values, ",")
++ }
++ idSlots := slots(2, len(resourceIDs))
++ metricSlots := slots(2+len(resourceIDs), len(metricTypes))
++ startParam := 2 + len(resourceIDs) + len(metricTypes)
++ endParam := startParam + 1
++ tierParam := endParam + 1
++ stepParam := tierParam + len(tiers)
+ index := "idx_metrics_query_all"
if len(metricTypes) > 0 {
- metricPlaceholders := make([]string, len(metricTypes))
- for i, metricType := range metricTypes {
- metricPlaceholders[i] = "?"
- metricArgs = append(metricArgs, metricType)
+ index = "idx_metrics_lookup"
+ }
- // Keep tier and timestamp constraints in the index even when an ordering
- // index could avoid a sort by walking unrelated retention tiers.
- scope := `m.resource_type = ? AND m.resource_id IN (` + idSlots + `)` + metricClause + `
- AND m.tier = ? AND m.timestamp >= ? AND m.timestamp <= ?`
- branches := make([]string, 0, len(tiers))
- var params []interface{}
- appendScopeParams := func(tier Tier) {
- params = append(params, resourceType)
- for _, id := range resourceIDs {
- params = append(params, id)
- }
- for _, metric := range metricTypes {
- params = append(params, metric)
++ scope := func(alias string, tierIndex int) string {
++ clause := alias + ".resource_type = ?1 AND " + alias + ".resource_id IN (" + idSlots + ")"
++ if len(metricTypes) > 0 {
++ clause += " AND " + alias + ".metric_type IN (" + metricSlots + ")"
}
- params = append(params, string(tier), start.Unix(), end.Unix())
- metricClause = fmt.Sprintf(" AND metric_type IN (%s)", strings.Join(metricPlaceholders, ","))
++ return clause + fmt.Sprintf(" AND %s.tier = ?%d AND %s.timestamp >= ?%d AND %s.timestamp <= ?%d", alias, tierParam+tierIndex, alias, startParam, alias, endParam)
+ }
+ projection := identityColumns + `m.timestamp, m.value,
+ COALESCE(m.min_value, m.value) AS min_value, COALESCE(m.max_value, m.value) AS max_value`
+ directAggregate := stepSecs > 1 && len(tiers) == 1
++ bucketExpression := fmt.Sprintf("(timestamp / ?%d) * ?%d + (?%d / 2)", stepParam, stepParam, stepParam)
+ if directAggregate {
- // A snapshot containing one tier needs no intermediate projection.
- // Aggregate its values directly, avoiding expression materialization
- // for every input row while keeping the same bounded output.
- projection = identityColumns + `(m.timestamp / ?) * ? + (? / 2) AS bucket_ts,
++ projection = identityColumns + bucketExpression + ` AS bucket_ts,
+ AVG(m.value), MIN(COALESCE(m.min_value, m.value)), MAX(COALESCE(m.max_value, m.value))`
- params = append(params, stepSecs, stepSecs, stepSecs)
+ }
++ branches := make([]string, 0, len(tiers))
+ for i, tier := range tiers {
- branch := `SELECT ` + projection + `
- FROM metrics AS m INDEXED BY ` + index + ` WHERE ` + scope
- appendScopeParams(tier)
- for _, preferred := range tiers[:i] {
- branch += ` AND NOT EXISTS (`
- // Retention intervals nest on UTC minute/hour/day boundaries. Using the
- // larger interval makes both finer and coarser overlap probes indexable.
++ branch := "SELECT " + projection + " FROM metrics AS m INDEXED BY " + index + " WHERE " + scope("m", i)
++ for j, preferred := range tiers[:i] {
++ // SQLite evaluates the uncorrelated existence check once. An empty
++ // preferred tier must not incur a correlated index probe for every
++ // fallback observation. Both checks use this statement's snapshot.
++ branch += " AND (NOT EXISTS (SELECT 1 FROM metrics AS coverage INDEXED BY " + index + " WHERE " + scope("coverage", j) + ") OR NOT EXISTS ("
+ bucket := max(tierBucketSeconds(tier), tierBucketSeconds(preferred))
+ branch += fmt.Sprintf(`
+ SELECT 1 FROM metrics AS h
+ WHERE h.resource_type = m.resource_type AND h.resource_id = m.resource_id
- AND h.metric_type = m.metric_type AND h.tier = ?
- AND h.timestamp >= MAX(?, (m.timestamp / %d) * %d)
- AND h.timestamp <= ? AND h.timestamp < (m.timestamp / %d) * %d + %d
- )`, bucket, bucket, bucket, bucket, bucket)
- params = append(params, string(preferred), start.Unix(), end.Unix())
++ AND h.metric_type = m.metric_type AND h.tier = ?%d
++ AND h.timestamp >= MAX(?%d, (m.timestamp / %d) * %d)
++ AND h.timestamp <= ?%d AND h.timestamp < (m.timestamp / %d) * %d + %d
++ ))`, tierParam+j, startParam, bucket, bucket, endParam, bucket, bucket, bucket)
+ }
+ branches = append(branches, branch)
+ }
+ query := strings.Join(branches, " UNION ALL ")
+ if directAggregate {
+ query += " GROUP BY " + identityColumns + "bucket_ts ORDER BY " + identityColumns + "bucket_ts ASC"
+ } else if stepSecs > 1 {
- // Reconcile first, then aggregate inside SQLite so a bounded chart does
- // not allocate and scan every retained observation in Go.
- query = `SELECT ` + identityColumns + `
- (timestamp / ?) * ? + (? / 2) AS bucket_ts,
- AVG(value), MIN(min_value), MAX(max_value)
- FROM (` + query + `)
- GROUP BY ` + identityColumns + `bucket_ts
- ORDER BY ` + identityColumns + `bucket_ts ASC`
- params = append([]interface{}{stepSecs, stepSecs, stepSecs}, params...)
++ query = "SELECT " + identityColumns + bucketExpression + ` AS bucket_ts,
++ AVG(value), MIN(min_value), MAX(max_value)
++ FROM (` + query + ") GROUP BY " + identityColumns + "bucket_ts ORDER BY " + identityColumns + "bucket_ts ASC"
+ } else {
+ orderColumns := identityColumns
+ if !groupSeries && len(metricTypes) == 0 {
- // The all-metric index orders each resource by time. Interleaved
- // metrics still append in timestamp order within each output series,
- // so plain reads need no extra sort by metric. Streaming display
- // aggregation explicitly requests contiguous series instead.
+ orderColumns = ""
+ if len(resourceIDs) != 1 {
+ orderColumns = "resource_id, "
+ }
+ }
+ query += " ORDER BY " + orderColumns + "timestamp ASC"
+ }
+ return query, params
+}
+
+func tierBucketSeconds(tier Tier) int64 {
+ switch tier {
+ case TierMinute:
+ return 60
+ case TierHourly:
+ return 3600
+ case TierDaily:
+ return 86400
+ default:
+ return 1
}
+}
- var params []interface{}
- var sqlQuery string
+// The database owns statement closure. Once the bounded set is full, uncommon
+// parameter-count shapes run uncached. No result, tier presence or time window
+// is cached, and no eviction can close a statement another reader is binding.
+const maxRetainedReadStatements = 32
+func (s *Store) retainedReadStatement(query string) (*pdb.InstrumentedStmt, error) {
+ s.readMu.Lock()
+ defer s.readMu.Unlock()
+ if stmt := s.readStatements[query]; stmt != nil {
+ return stmt, nil
+ }
+ if len(s.readStatements) >= maxRetainedReadStatements {
+ return nil, nil
+ }
+ stmt, err := s.db.Prepare(query)
+ if err != nil {
+ return nil, err
+ }
+ if s.readStatements == nil {
+ s.readStatements = make(map[string]*pdb.InstrumentedStmt)
+ }
+ s.readStatements[query] = stmt
+ return stmt, nil
+}
+
+func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier) (map[string]map[string][]MetricPoint, error) {
+ var tx *pdb.InstrumentedTx
+ var err error
if stepSecs > 1 {
- params = make([]interface{}, 0, len(resourceIDs)+len(metricArgs)+4)
- params = append(params, resourceType)
- for _, id := range resourceIDs {
- params = append(params, id)
+ // Determine which tiers exist in the same read snapshot used below. An
+ // all-raw series should cost a direct range read, not a UNION and an empty
+ // overlap probe for every observation. Presence does not imply coverage:
+ // every tier with any matching observations still participates.
+ // EXISTS needs only indexed identity and time columns. Do not build or
+ // order the value projection for each presence probe.
+ idSlots := strings.TrimSuffix(strings.Repeat("?,", len(resourceIDs)), ",")
+ presenceScope := "resource_type = ? AND resource_id IN (" + idSlots + ")"
+ index := "idx_metrics_query_all"
+ if len(metricTypes) > 0 {
+ presenceScope += " AND metric_type IN (" + strings.TrimSuffix(strings.Repeat("?,", len(metricTypes)), ",") + ")"
+ index = "idx_metrics_lookup"
}
- params = append(params, metricArgs...)
- params = append(params, string(tier), start.Unix(), end.Unix())
-
- sqlQuery = fmt.Sprintf(`
- SELECT
- resource_id,
- metric_type,
- timestamp,
- value,
- COALESCE(min_value, value),
- COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id IN (%s)%s AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY resource_id, metric_type, timestamp ASC
- `, inClause, metricClause)
- } else {
- params = make([]interface{}, 0, len(resourceIDs)+len(metricArgs)+4)
- params = append(params, resourceType)
- for _, id := range resourceIDs {
- params = append(params, id)
+ presenceScope += " AND tier = ? AND timestamp >= ? AND timestamp <= ?"
+ check := "EXISTS (SELECT 1 FROM metrics INDEXED BY " + index + " WHERE " + presenceScope + ")"
+ checks := make([]string, len(tiers))
+ checkParams := make([]interface{}, 0, len(tiers)*(len(resourceIDs)+len(metricTypes)+4))
+ present := make([]bool, len(tiers))
+ checkDestinations := make([]interface{}, len(tiers))
+ for i, tier := range tiers {
+ checks[i] = check
+ checkParams = append(checkParams, resourceType)
+ for _, id := range resourceIDs {
+ checkParams = append(checkParams, id)
+ }
+ for _, metric := range metricTypes {
+ checkParams = append(checkParams, metric)
+ }
+ checkParams = append(checkParams, string(tier), start.Unix(), end.Unix())
+ checkDestinations[i] = &present[i]
+ }
+ presenceQuery := "SELECT " + strings.Join(checks, ", ")
+ statement, err := s.retainedReadStatement(presenceQuery)
+ if err != nil {
+ return nil, fmt.Errorf("prepare retained metrics presence: %w", err)
+ }
+ // Prepare before acquiring the transaction so a one-connection pool never
+ // waits for itself while preparing a database-level statement.
+ tx, err = s.db.BeginTx(context.Background(), &sql.TxOptions{ReadOnly: true})
+ if err != nil {
+ return nil, fmt.Errorf("begin retained metrics snapshot: %w", err)
+ }
+ defer tx.Rollback()
+ var presenceRow *sql.Row
+ if statement != nil {
+ bound := tx.Stmt(statement)
+ defer bound.Close()
+ presenceRow = bound.QueryRow(checkParams...)
+ } else {
+ presenceRow = tx.QueryRow(presenceQuery, checkParams...)
+ }
+ if err := presenceRow.Scan(checkDestinations...); err != nil {
+ return nil, fmt.Errorf("inspect retained metrics tiers: %w", err)
+ }
+ available := make([]Tier, 0, len(tiers))
+ for i, tier := range tiers {
+ if present[i] {
+ available = append(available, tier)
+ }
+ }
+ if len(available) == 0 {
+ return make(map[string]map[string][]MetricPoint), nil
+ }
+ tiers = available
+ }
+ // Fleet results are already ordered by series and time. Stream their
+ // display buckets to avoid SQLite's fleet-wide temporary GROUP BY tree.
+ // Single-resource charts aggregate in SQLite to bound rows crossing Go.
+ streamBuckets := stepSecs > 1 && len(resourceIDs) > 1
+ queryStep := stepSecs
+ if streamBuckets {
+ queryStep = 0
+ }
- sqlQuery, params := retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, queryStep, tiers, streamBuckets)
++ sqlQuery, params := s.retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, queryStep, tiers, streamBuckets)
+
+ queryRows := func() (*sql.Rows, error) { return tx.Query(sqlQuery, params...) }
+ if tx == nil {
+ // One SQLite statement already owns a consistent read snapshot. Plain
+ // retained reads need neither a separate presence probe nor a transaction
+ // wrapper. Compile the canonical reconciliation query once per shape.
+ statement, prepareErr := s.retainedReadStatement(sqlQuery)
+ if prepareErr != nil {
+ return nil, fmt.Errorf("prepare retained metrics query: %w", prepareErr)
+ }
+ if statement != nil {
+ queryRows = func() (*sql.Rows, error) { return statement.Query(params...) }
+ } else {
+ queryRows = func() (*sql.Rows, error) { return s.db.Query(sqlQuery, params...) }
}
- params = append(params, metricArgs...)
- params = append(params, string(tier), start.Unix(), end.Unix())
-
- sqlQuery = fmt.Sprintf(`
- SELECT resource_id, metric_type, timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id IN (%s)%s AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY resource_id, metric_type, timestamp ASC
- `, inClause, metricClause)
}
// Retry on SQLITE_BUSY
@@@ -1588,46 -1621,103 +1635,67 @@@
result := make(map[string]map[string][]MetricPoint, len(resourceIDs))
seriesCapacity := estimateQueryAllBatchSeriesCapacity(start, end, stepSecs)
- if stepSecs > 1 {
- type bucketAggregate struct {
- active bool
- resourceID string
- metricType string
- bucketStart int64
- sum float64
- min float64
- max float64
- count int
- }
- appendPoint := func(resourceID, metricType string, point MetricPoint) {
- if result[resourceID] == nil {
- result[resourceID] = make(map[string][]MetricPoint, 8)
- appendBucketPoint := func(resourceID, metricType string, point MetricPoint) {
- if _, exists := result[resourceID]; !exists {
- result[resourceID] = make(map[string][]MetricPoint, 8)
- }
- if _, exists := result[resourceID][metricType]; !exists {
- result[resourceID][metricType] = make([]MetricPoint, 0, seriesCapacity)
- }
- result[resourceID][metricType] = append(result[resourceID][metricType], point)
++ // Consecutive points in one series append directly to its slice. Flush on
++ // a series change so interleaved metrics can resume their existing slices
++ // without performing repeated nested-map lookups for every observation.
++ var outputResource, outputMetric string
++ var outputMetrics map[string][]MetricPoint
++ var outputPoints []MetricPoint
++ flushSeries := func() {
++ if outputMetrics != nil {
++ outputMetrics[outputMetric] = outputPoints
}
- if result[resourceID][metricType] == nil {
- result[resourceID][metricType] = make([]MetricPoint, 0, seriesCapacity)
-
- var aggregate bucketAggregate
- flushAggregate := func() {
- if !aggregate.active || aggregate.count == 0 {
- return
- }
- appendBucketPoint(aggregate.resourceID, aggregate.metricType, MetricPoint{
- Timestamp: time.Unix(aggregate.bucketStart+(stepSecs/2), 0),
- Value: aggregate.sum / float64(aggregate.count),
- Min: aggregate.min,
- Max: aggregate.max,
- })
- aggregate = bucketAggregate{}
- }
-
- for rows.Next() {
- var resourceID, metricType string
- var ts int64
- var value, minVal, maxVal float64
- if err := rows.Scan(&resourceID, &metricType, &ts, &value, &minVal, &maxVal); err != nil {
- log.Warn().Err(err).Msg("Failed to scan batch metric row")
- continue
- }
-
- bucketStart := (ts / stepSecs) * stepSecs
- if !aggregate.active {
- aggregate = bucketAggregate{
- active: true,
- resourceID: resourceID,
- metricType: metricType,
- bucketStart: bucketStart,
- sum: value,
- min: minVal,
- max: maxVal,
- count: 1,
++ }
++ appendPoint := func(resourceID, metricType string, point MetricPoint) {
++ if outputMetrics == nil || outputResource != resourceID || outputMetric != metricType {
++ flushSeries()
++ if outputMetrics == nil || outputResource != resourceID {
++ outputResource = resourceID
++ outputMetrics = result[resourceID]
++ if outputMetrics == nil {
++ outputMetrics = make(map[string][]MetricPoint, 8)
++ result[resourceID] = outputMetrics
+ }
- continue
+ }
-
- if aggregate.resourceID != resourceID || aggregate.metricType != metricType || aggregate.bucketStart != bucketStart {
- flushAggregate()
- aggregate = bucketAggregate{
- active: true,
- resourceID: resourceID,
- metricType: metricType,
- bucketStart: bucketStart,
- sum: value,
- min: minVal,
- max: maxVal,
- count: 1,
- }
- continue
++ outputMetric = metricType
++ outputPoints = outputMetrics[metricType]
++ if outputPoints == nil {
++ outputPoints = make([]MetricPoint, 0, seriesCapacity)
+ }
-
- aggregate.sum += value
- if minVal < aggregate.min {
- aggregate.min = minVal
- }
- if maxVal > aggregate.max {
- aggregate.max = maxVal
- }
- aggregate.count++
}
- result[resourceID][metricType] = append(result[resourceID][metricType], point)
-
- if err := rows.Err(); err != nil {
- return nil, err
++ outputPoints = append(outputPoints, point)
+ }
+ var bucketResource, bucketMetric string
+ var bucketStart int64
+ var bucketPoint MetricPoint
+ var bucketCount int
+ flushBucket := func() {
+ if bucketCount == 0 {
+ return
}
- flushAggregate()
- return result, nil
+ bucketPoint.Value /= float64(bucketCount)
+ bucketPoint.Timestamp = time.Unix(bucketStart+stepSecs/2, 0)
+ appendPoint(bucketResource, bucketMetric, bucketPoint)
+ bucketCount = 0
+ }
+ var resourceID, metricType string
+ var ts int64
+ var p MetricPoint
+ destinations := make([]interface{}, 0, 6)
+ if len(resourceIDs) == 1 {
+ resourceID = resourceIDs[0]
+ } else {
+ destinations = append(destinations, &resourceID)
}
-
+ if len(metricTypes) == 1 {
+ metricType = metricTypes[0]
+ } else {
+ destinations = append(destinations, &metricType)
+ }
+ destinations = append(destinations, &ts, &p.Value, &p.Min, &p.Max)
for rows.Next() {
- var resourceID, metricType string
- var ts int64
- var p MetricPoint
- if err := rows.Scan(&resourceID, &metricType, &ts, &p.Value, &p.Min, &p.Max); err != nil {
+ if err := rows.Scan(destinations...); err != nil {
log.Warn().Err(err).Msg("Failed to scan batch metric row")
continue
}
@@@ -1655,7 -1736,6 +1723,8 @@@
return nil, err
}
+ flushBucket()
++ flushSeries()
return result, nil
}
diff --cc pkg/metrics/store_additional_test.go
index 2ae0efbf4d,2ae0efbf4d..7338766542
--- a/pkg/metrics/store_additional_test.go
+++ b/pkg/metrics/store_additional_test.go
@@@ -11,6 -11,6 +11,7 @@@ import
"testing"
"time"
++ pdb "github.com/rcourtman/pulse-go-rewrite/pkg/db"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
@@@ -1250,3 -1250,3 +1251,53 @@@ func TestCommercialHistoryRetentionNeve
t.Fatalf("commercial ceiling expanded shorter operator retention: %v", got)
}
}
++
++// Exercise shared query reuse under race detection without latency assertions.
++// A one-connection pool also exposes preparation/read-transaction lock inversion.
++func TestStoreRetainedConcurrentQueryBindings(t *testing.T) {
++ db := newPlanTestDB(t)
++ db.SetMaxOpenConns(1)
++ store := &Store{db: pdb.Wrap(db, "concurrent-retained-bindings")}
++ base := time.Date(2026, 9, 6, 0, 0, 0, 0, time.UTC)
++ type scope struct {
++ family, id, metric string
++ value float64
++ }
++ var scopes []scope
++ for i := 0; i < 8; i++ {
++ item := scope{family: "node", id: strconv.Itoa(i / 2), metric: "cpu", value: float64(i + 1)}
++ if i%2 != 0 {
++ item.family = "vm"
++ }
++ if i%4 >= 2 {
++ item.metric = "memory"
++ }
++ if _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES (?,?,?,'raw',?,?)`, item.family, item.id, item.metric, base.Add(70*time.Second).Unix(), item.value); err != nil {
++ t.Fatal(err)
++ }
++ scopes = append(scopes, item)
++ }
++ start := make(chan struct{})
++ var workers sync.WaitGroup
++ for _, item := range scopes {
++ workers.Add(1)
++ go func(item scope) {
++ defer workers.Done()
++ <-start
++ for i := 0; i < 12; i++ {
++ step := []int64{0, 60, 120}[i%3]
++ points, err := store.Query(item.family, item.id, item.metric, base.Add(time.Duration(i)*time.Second), base.Add(3*time.Minute), step)
++ if err != nil {
++ t.Errorf("scope %+v step %d: %v", item, step, err)
++ return
++ }
++ if len(points) != 1 || points[0].Value != item.value {
++ t.Errorf("scope %+v step %d received another query's values: %+v", item, step, points)
++ return
++ }
++ }
++ }(item)
++ }
++ close(start)
++ workers.Wait()
++}
diff --cc pkg/metrics/store_tier_coverage_test.go
index 6d4864d4c3,0000000000..92df758e9e
mode 100644,000000..100644
--- a/pkg/metrics/store_tier_coverage_test.go
+++ b/pkg/metrics/store_tier_coverage_test.go
@@@ -1,226 -1,0 +1,272 @@@
+package metrics
+
+import (
+ "fmt"
+ pdb "github.com/rcourtman/pulse-go-rewrite/pkg/db"
+ "reflect"
+ "testing"
+ "time"
+)
+
+func TestStoreRetainedTierCoverage(t *testing.T) {
+ db := newPlanTestDB(t)
+ store := &Store{db: pdb.Wrap(db, "tier-coverage-test")}
+ base := time.Date(2026, 9, 5, 12, 0, 0, 0, time.UTC)
+ insert := func(id, metric string, tier Tier, offset time.Duration, value, low, high float64) {
+ t.Helper()
+ _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value,min_value,max_value) VALUES ('node',?,?,?,?,?,?,?)`, id, metric, tier, base.Add(offset).Unix(), value, low, high)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Raw observations before, within and after aggregate buckets. The raw
+ // overlap deliberately differs so double-counting is visible in the mean.
+ insert("a", "cpu", TierMinute, 0, 10, 2, 90)
+ insert("a", "cpu", TierMinute, 2*time.Minute, 30, 25, 40)
+ insert("a", "cpu", TierRaw, -time.Minute, 5, 5, 5)
+ insert("a", "cpu", TierRaw, 20*time.Second, 999, 999, 999)
+ insert("a", "cpu", TierRaw, time.Minute, 20, 20, 20)
+ insert("a", "cpu", TierRaw, 3*time.Minute, 50, 50, 50)
+ insert("a", "memory", TierRaw, 3*time.Minute, 88, 88, 88)
+ // The older hourly fallback remains useful, but the overlapping hour is
+ // indivisible and must not be mixed with the preferred minute/raw evidence.
+ insert("a", "cpu", TierHourly, -2*time.Hour, 7, 1, 9)
+ insert("a", "cpu", TierHourly, 0, 777, 777, 777)
+ insert("b", "cpu", TierRaw, 20*time.Second, 60, 60, 60)
+ insert("b", "memory", TierMinute, 0, 70, 65, 75)
+ insert("b", "memory", TierRaw, 3*time.Minute, 80, 80, 80)
+ // Same ID in another resource family cannot shadow or contribute evidence.
+ _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES ('vm','a','cpu','minute',?,1234)`, base.Add(time.Minute).Unix())
+ if err != nil {
+ t.Fatal(err)
+ }
+ start, end := base.Add(-23*time.Hour), base.Add(4*time.Minute)
+ want := []MetricPoint{
+ {base.Add(-2 * time.Hour), 7, 1, 9}, {base.Add(-time.Minute), 5, 5, 5},
+ {base, 10, 2, 90}, {base.Add(time.Minute), 20, 20, 20},
+ {base.Add(2 * time.Minute), 30, 25, 40}, {base.Add(3 * time.Minute), 50, 50, 50},
+ }
+ for _, step := range []int64{0, 120} {
+ t.Run(fmt.Sprintf("step_%d", step), func(t *testing.T) {
+ batch, err := store.QueryAllBatch("node", []string{"a", "b", "a", "missing"}, start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ filtered, err := store.QueryMetricTypesBatch("node", []string{"a", "b"}, []string{"cpu"}, start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, id := range []string{"a", "b"} {
+ all, err := store.QueryAll("node", id, start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(all, batch[id]) {
+ t.Fatalf("batch differs for %s: %v != %v", id, batch[id], all)
+ }
+ for _, metric := range []string{"cpu", "memory"} {
+ single, err := store.Query("node", id, metric, start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(single, all[metric]) {
+ t.Fatalf("single differs for %s/%s", id, metric)
+ }
+ }
+ if len(filtered[id]) != 1 || !reflect.DeepEqual(filtered[id]["cpu"], all["cpu"]) {
+ t.Fatalf("filtered mismatch: %+v", filtered)
+ }
+ }
+ got := batch["a"]["cpu"]
+ expected := want
+ if step == 120 {
+ expected = []MetricPoint{{base.Add(-119 * time.Minute), 7, 1, 9}, {base.Add(-time.Minute), 5, 5, 5}, {base.Add(time.Minute), 15, 2, 90}, {base.Add(3 * time.Minute), 40, 25, 50}}
+ }
+ if len(got) != len(expected) {
+ t.Fatalf("got %+v\nwant %+v", got, expected)
+ }
+ for i, p := range got {
+ want := expected[i]
+ if !p.Timestamp.Equal(want.Timestamp) || p.Value != want.Value || p.Min != want.Min || p.Max != want.Max {
+ t.Fatalf("point %d: got %+v, want %+v", i, p, want)
+ }
+ }
+ if _, ok := batch["missing"]; ok {
+ t.Fatal("invented missing resource")
+ }
+ })
+ }
+ // On a short raw-preferred window the real raw sample wins, rather than
+ // its encompassing minute/hour buckets. With no raw in a minute, retain it.
+ short, err := store.Query("node", "a", "cpu", base, base.Add(4*time.Minute), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(short) != 4 || short[0].Value != 999 || short[2].Value != 30 {
+ t.Fatalf("raw precedence: %+v", short)
+ }
+ // An aggregate outside the requested timestamp window cannot suppress a
+ // raw point inside it, even when they share a nominal retention bucket.
+ clipped, err := store.Query("node", "a", "cpu", base.Add(10*time.Second), base.Add(20*time.Second), 0)
+ if err != nil || len(clipped) != 1 || clipped[0].Value != 999 {
+ t.Fatalf("clipped boundary: %+v, %v", clipped, err)
+ }
+}
+
+func TestStoreRetainedDailyAndHourlyCoverage(t *testing.T) {
+ db := newPlanTestDB(t)
+ store := &Store{db: pdb.Wrap(db, "tier-coverage-test")}
+ base := time.Date(2026, 9, 5, 0, 0, 0, 0, time.UTC)
+ for _, row := range []struct {
+ tier Tier
+ offset time.Duration
+ value float64
+ }{
+ {TierDaily, -24 * time.Hour, 10}, {TierHourly, -23 * time.Hour, 999},
+ {TierHourly, 0, 20}, {TierMinute, 30 * time.Minute, 999},
+ {TierMinute, time.Hour, 30}, {TierRaw, time.Hour + 20*time.Second, 999},
+ {TierRaw, time.Hour + time.Minute, 40},
+ } {
+ _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES ('node','a','cpu',?,?,?)`, row.tier, base.Add(row.offset).Unix(), row.value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ got, err := store.Query("node", "a", "cpu", base.Add(-30*24*time.Hour), base.Add(2*time.Hour), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 4 {
+ t.Fatalf("coverage: %+v", got)
+ }
+ for i, p := range got {
+ if p.Value != float64((i+1)*10) {
+ t.Fatalf("precedence: %+v", got)
+ }
+ }
+}
+
+func TestStoreRollupPreservesRetainedExtrema(t *testing.T) {
+ for _, legacy := range []bool{false, true} {
+ t.Run(fmt.Sprintf("legacy_%v", legacy), func(t *testing.T) {
+ db := newPlanTestDB(t)
+ store := &Store{db: pdb.Wrap(db, "tier-coverage-test")}
+ base := time.Date(2026, 9, 5, 0, 0, 0, 0, time.UTC)
+ _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value,min_value,max_value) VALUES ('node','a','cpu','minute',?,10,1,99),('node','a','cpu','minute',?,20,5,35)`, base.Unix(), base.Add(time.Minute).Unix())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if legacy {
+ store.rollupCandidate("node", "a", "cpu", TierMinute, TierHourly, 3600, base.Unix(), base.Add(time.Hour).Unix())
+ } else if !store.rollupTierWindow(TierMinute, TierHourly, 3600, base.Unix(), base.Add(time.Hour).Unix()) {
+ t.Fatal("rollup failed")
+ }
+ var value, low, high float64
+ if err := db.QueryRow(`SELECT value,min_value,max_value FROM metrics WHERE tier='hourly'`).Scan(&value, &low, &high); err != nil {
+ t.Fatal(err)
+ }
+ if value != 15 || low != 1 || high != 99 {
+ t.Fatalf("lost retained extrema: %v %v %v", value, low, high)
+ }
+ })
+ }
+}
+
+func TestRetainedReadStatementsReadCurrentSnapshot(t *testing.T) {
+ for _, step := range []int64{0, 60} {
+ t.Run(fmt.Sprint(step), func(t *testing.T) {
+ db := newPlanTestDB(t)
+ db.SetMaxOpenConns(1)
+ store := &Store{db: pdb.Wrap(db, "presence-snapshot")}
+ end := time.Unix(2000000040, 0)
- start := end.Add(-time.Hour)
++ start := end.Add(-3 * time.Hour)
+ query := func(id string) []MetricPoint {
+ t.Helper()
+ points, err := store.Query("node", id, "cpu", start, end, step)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return points
+ }
+ if points := query("a"); len(points) != 0 {
+ t.Fatalf("empty inventory: %+v", points)
+ }
++ // Warm the fallback query while the preferred minute tier is absent.
++ // A later preferred bucket must replace its overlapping raw point,
++ // even when the same SQL template and statement are reused.
++ if _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES ('node','a','cpu','raw',?,23)`, end.Add(-40*time.Second).Unix()); err != nil {
++ t.Fatal(err)
++ }
++ if points := query("a"); len(points) != 1 || points[0].Value != 23 {
++ t.Fatalf("raw fallback was hidden: %+v", points)
++ }
+ if _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES ('node','a','cpu','minute',?,17)`, end.Add(-time.Minute).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ if points := query("a"); len(points) != 1 || points[0].Value != 17 {
+ t.Fatalf("newly present tier was hidden: %+v", points)
+ }
+ if points := query("b"); len(points) != 0 {
+ t.Fatalf("statement reused another resource's result: %+v", points)
+ }
+ if _, err := db.Exec("DELETE FROM metrics"); err != nil {
+ t.Fatal(err)
+ }
+ if points := query("a"); len(points) != 0 {
+ t.Fatalf("removed history remained present: %+v", points)
+ }
+ // Vary the parameter-count shape beyond the bound. Uncached shapes must
+ // remain functional without expanding the retained statement set.
+ for n := 1; n <= maxRetainedReadStatements+2; n++ {
+ ids := make([]string, n)
+ for i := range ids {
+ ids[i] = fmt.Sprintf("missing-%d", i)
+ }
+ got, err := store.QueryAllBatch("node", ids, start, end, step)
+ if err != nil || len(got) != 0 {
+ t.Fatalf("shape %d: %+v, %v", n, got, err)
+ }
+ }
+ if len(store.readStatements) > maxRetainedReadStatements {
+ t.Fatalf("unbounded compiled SQL retention: %d", len(store.readStatements))
+ }
++ if len(store.readQueryShapes) > maxRetainedReadStatements {
++ t.Fatalf("unbounded SQL template retention: %d", len(store.readQueryShapes))
++ }
+ })
+ }
+}
++
++func TestRetainedQueryTemplatesBindCurrentWindowAndStep(t *testing.T) {
++ db := newPlanTestDB(t)
++ db.SetMaxOpenConns(1)
++ store := &Store{db: pdb.Wrap(db, "query-template-bindings")}
++ base := time.Date(2026, 9, 6, 0, 0, 0, 0, time.UTC)
++ for _, row := range []struct {
++ family, metric string
++ offset time.Duration
++ value float64
++ }{{"node", "cpu", 10 * time.Second, 5}, {"node", "cpu", 70 * time.Second, 15}, {"vm", "cpu", 70 * time.Second, 91}, {"node", "memory", 70 * time.Second, 99}} {
++ if _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES (?,'a',?,'raw',?,?)`, row.family, row.metric, base.Add(row.offset).Unix(), row.value); err != nil {
++ t.Fatal(err)
++ }
++ }
++ for _, tc := range []struct {
++ family, metric string
++ start time.Duration
++ step int64
++ values []float64
++ }{{"node", "cpu", 0, 60, []float64{5, 15}}, {"node", "cpu", 0, 120, []float64{10}}, {"node", "cpu", time.Minute, 120, []float64{15}}, {"vm", "cpu", 0, 120, []float64{91}}, {"node", "memory", 0, 120, []float64{99}}} {
++ points, err := store.Query(tc.family, "a", tc.metric, base.Add(tc.start), base.Add(3*time.Minute), tc.step)
++ if err != nil {
++ t.Fatal(err)
++ }
++ var values []float64
++ for _, point := range points {
++ values = append(values, point.Value)
++ }
++ if !reflect.DeepEqual(values, tc.values) {
++ t.Fatalf("%+v returned stale bindings: %+v", tc, points)
++ }
++ }
++}