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.

fix(metrics): reconcile retained history across storage tiers

rcourtman3a189f31d447
diff --git a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
index 0e24cc4ce1..ce85608a23 100644
--- a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
+++ b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
@@ -311,3 +311,86 @@ provider readiness probe. The final saved-session pixel pass followed a correcti
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.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 1f1a6bd192..96f614a7af 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -5648,15 +5648,11 @@
"status": "partial",
"completion": {
"state": "bounded-residual",
- "summary": "Performance is at the current release floor with bounded residuals. Retained queries still require temporal tier reconciliation so an existing aggregate does not hide newer raw evidence. Scalability headroom and performance follow-up remain tracked separately.",
+ "summary": "Performance is at the current release floor with bounded residuals. Retained query tier reconciliation and extrema preservation are verified. Additional scalability headroom and performance follow-up remain tracked separately.",
"tracking": [
{
"kind": "lane-followup",
"id": "performance-post-rc-headroom"
- },
- {
- "kind": "lane-followup",
- "id": "retained-metric-query-coverage"
}
]
},
@@ -9730,19 +9726,6 @@
"pulse-pro"
],
"subsystem_ids": []
- },
- {
- "id": "retained-metric-query-coverage",
- "summary": "Repair temporal coverage across retained metric tiers. A 24-hour Query or QueryAll currently returns an older non-empty aggregate tier even when a newer raw point exists. Reconcile bucket precedence, extrema and downsampling consistently across single-series, all-series and batch reads. The model-facing evidence tool reports the returned timestamps but does not make this shared-store query complete. Required for trustworthy Patrol and Assistant history, tracked with patrol-assistant-customer-outcome-qualification.",
- "owner": "project-owner",
- "status": "planned",
- "recorded_at": "2026-09-05",
- "lane_ids": [
- "L10"
- ],
- "subsystem_ids": [
- "performance-and-scalability"
- ]
}
],
"coverage_gaps": [
@@ -10218,19 +10201,23 @@
},
{
"id": "patrol-assistant-customer-outcome-qualification",
- "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 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 now covers single and batch queries, with extrema preserved through rollups and indexed overlap probes. Metrics race and query SLO checks pass on the worker. The live retained summary reaches seven seconds before its query instead of returning a roughly 45-minute-stale tail. The adjacent node History tab exposed a separate canonical-target defect and an inferred Agent link from discovery routing. The unified PVE metrics target now matches the node store writer, the drawer consumes that target and explicit Agent linkage, and summary tools no longer carry a PVE-specific exception. Full diagnosis and autonomous Patrol outcomes remain unqualified.",
"owner": "project-owner",
"status": "planned",
"recorded_at": "2026-09-05",
"lane_ids": [
"L6",
- "L10"
+ "L8",
+ "L10",
+ "L13"
],
"subsystem_ids": [
"ai-runtime",
"api-contracts",
+ "frontend-primitives",
"patrol-intelligence",
- "performance-and-scalability"
+ "performance-and-scalability",
+ "unified-resources"
],
"proposed_resolution": "lane-expansion",
"coverage_impact": 4,
@@ -10245,6 +10232,11 @@
"path": "docs/release-control/v6/internal/subsystems/performance-and-scalability.md",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/subsystems/unified-resources.md",
+ "kind": "file"
+ },
{
"repo": "pulse",
"path": "internal/ai/qualification",
@@ -10383,7 +10375,9 @@
"target_id": "v6-product-lane-expansion",
"current_lane_ids": [
"L6",
- "L10"
+ "L8",
+ "L10",
+ "L13"
],
"coverage_gap_ids": [
"patrol-assistant-customer-outcome-qualification"
@@ -10391,8 +10385,10 @@
"subsystem_ids": [
"ai-runtime",
"api-contracts",
+ "frontend-primitives",
"patrol-intelligence",
- "performance-and-scalability"
+ "performance-and-scalability",
+ "unified-resources"
],
"demand_evidence": [
"user-direction: 2026-09-05 prioritise dependable Patrol and Assistant outcomes as core Pulse Pro value",
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 12d624091f..b8a567f524 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -7121,11 +7121,11 @@ the reporting request shape the way the API report path's
the resolved metrics target rides `MetricsResourceID`, so the
engine's store queries actually find data instead of silently
returning zero points. Reporting types are classified from the
-unified resource (agent-backed hosts as `agent`, pure Proxmox
-nodes as `node` — the documented exception where the metrics
-target labels the agent family but node metrics live under the
-`node` store type — pure Docker hosts as `docker-host`), and the
-resolved target's type wins elsewhere. `resource_type` is now an
+unified resource, with the canonical metrics target taking precedence.
+Agent-backed hosts use `agent`, pure Proxmox nodes use `node`, and
+pure Docker hosts use `docker-host`. The Proxmox storage-family
+correction belongs to the unified target, so summary tools no longer
+carry their own exception. `resource_type` is now an
optional filter/default for fleet mode and only required for
`action=resource` when the identifier is not a known resource.
Every remaining error path in the tool tells the model to
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 76af611960..89b1546659 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -20,6 +20,13 @@
## Purpose
+The frontend `Node` projection preserves the unified resource's optional
+`metricsTarget` without deriving storage coordinates from its display identity.
+Proxmox-only nodes advertise the `node` storage family and provider-native ID.
+An explicit Agent source takes precedence with its own `agent` coordinates.
+Discovery routing alone does not establish an installed Agent or its history
+capabilities. Resource adapters and history consumers preserve that distinction.
+
The manual Patrol API consumes the service's selected-mode runtime verdict as
an execution check. Dimension-level presentation warnings cannot authorize a
run after a provider failure leaves Watch-only readiness unassessed. Operator
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index b89f22c8c8..159c6f0238 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -207,6 +207,15 @@ on Overview or reintroduce object-local tab or range-selector chrome. The
metrics and chart groups may remain object-specific without changing this
navigation contract.
+Node history consumes the canonical `metricsTarget` carried by the resource
+projection before legacy node identifiers. Proxmox-only history uses the
+collector's `node` coordinates even when the unified resource has an `agent`
+display identity. The presence of discovery routing does not enable Agent-only
+disk-throughput charts. Explicit Agent linkage owns that capability distinction.
+`nodeDrawerModel.branchcov0713.test.ts` pins target precedence and unsupported
+target fallback, while `NodeDrawer.test.tsx` verifies the chart request and
+API-only chart groups through the rendered History tab.
+
Platform inventory presentation has one structural owner across provider pages,
drawers, and inline detail rows. `PlatformTableShell` owns framed page tables;
`PlatformDetailTable`, `PlatformDetailTableHeader`, and
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index efaed6c42c..cb3c81b403 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -15,17 +15,34 @@
## 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 and fleet queries use the same streaming aggregator.
+
+The overlap probes use indexed series/time searches in one SQLite statement per
+bounded resource chunk. 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 --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index a4f1dc5a59..5bf1decfb8 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -15,6 +15,16 @@
## Purpose
+Canonical resource identity and metrics storage coordinates are distinct.
+API-only Proxmox hosts remain `agent` resources but their metrics target is
+`node` with the Proxmox source ID, matching the collector's writes. A real
+linked Agent source retains priority and its `agent` store ID. Consumers must
+use that target rather than reconstructing storage coordinates from display
+identity or discovery routing. The node view carries the canonical target into
+its History tab. Discovery can route by a host name without an installed Agent,
+so it does not establish a `linkedAgentId` or Agent-only disk-throughput coverage.
+The explicit Agent facet/link owns that evidence.
+
ResourceIncident carries optional nativeSeverity JSON evidence independently of canonical Severity and identity. Missing nativeSeverity remains compatible with older payloads. TrueNAS INFO and NOTICE may share canonical monitor risk without becoming indistinguishable to alert consumers; native severity does not change resource or incident identity.
Unraid adapters preserve optional `numDisks` in both host and storage metadata, including explicit zero in JSON and absence for unknown counts. Disk count is topology evidence only: changing it must not change canonical host/storage identity. The storage projection uses the monitoring-owned assessment so an explicit pool-only array does not acquire a no-parity warning.
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index c9b39b4a4d..032c0022ec 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,53 +1,41 @@
{
"version": 1,
- "base_sha": "75976c60be5e156be46fca344a02b7df5f573416",
- "verified_at": "2026-09-05T17:45:39.915245Z",
+ "base_sha": "5288b64d40642b29cd27fa0ca67080cb261d37f1",
+ "verified_at": "2026-09-05T22:04:00.286Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/components/AI/Chat/hooks/useExplanationRequest.ts",
- "frontend-modern/src/components/AI/Chat/index.tsx",
- "frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx",
- "frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx",
- "frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts",
- "frontend-modern/src/stores/aiChat.ts",
- "frontend-modern/src/utils/aiChatPresentation.ts"
+ "frontend-modern/src/components/Workloads/nodeDrawerModel.ts",
+ "frontend-modern/src/types/api.ts",
+ "frontend-modern/src/utils/resourceStateAdapters.ts"
],
"content_sha256": {
- "frontend-modern/src/components/AI/Chat/hooks/useExplanationRequest.ts": "8606c79c11b0197ed5a55ed1d2ec83e0cd7dd0adda182937e5aad9144571cb17",
- "frontend-modern/src/components/AI/Chat/index.tsx": "6b1d6243d9a99d688229dea9e954ae6aa770a8b6e07e7f0ce75316b486090f09",
- "frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx": "f373ff21a1c54304d63b92498c39fa45f5ffb036a2b02e93de64fafbbf8ee52e",
- "frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx": "f098cddd58823d2df7687f0db7774363fc9c81a7a8845a917e73415a7f5aae10",
- "frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts": "4152a3bec5412b4d744436128e8e038be349d9b6419fc58d3b7527908ffc982f",
- "frontend-modern/src/stores/aiChat.ts": "d0b1ef69bcb454e6f0ce17a157c98bdd34d68d90f607b76081e9cd1bd6778e4c",
- "frontend-modern/src/utils/aiChatPresentation.ts": "4b05f663110ec6c789f8ff050993a945e3e9d41c6e3fee4047500e979a48531d"
+ "frontend-modern/src/components/Workloads/nodeDrawerModel.ts": "2a46640db19fe358e9f0ab32c4819a1c30a7c91b71015104b53253296176bdd6",
+ "frontend-modern/src/types/api.ts": "16e3c1c60450eb5bb8e4f0db57f595d29cc9dbfd2e01bffee1f0529262f9f60a",
+ "frontend-modern/src/utils/resourceStateAdapters.ts": "98ee10447e5fa0fe122122727ce1b59a29c92afbcdcf7f046f4cea9f2edc9e80"
},
"routes": [
+ "/proxmox",
"/patrol",
- "/alerts"
+ "/settings/pulse-intelligence/patrol"
],
"viewports": [
{
"width": 1440,
"height": 1000
},
- {
- "width": 900,
- "height": 1000
- },
{
"width": 390,
"height": 1000
}
],
"states": [
- "Current hot-dev frontend with mock monitoring backend. Scripted attention evidence and inference responses. Other non-GET requests blocked. No real model or infrastructure outcome qualification.",
- "Patrol selected item, expanded evidence, scoped explanation, streamed response, failed provider request and successful retry. Draft preserved across Escape and context-only reopen.",
- "Active alert secondary menu at desktop and narrow widths. Open, Escape dismissal, outside click dismissal, reopen, select explanation, menu closes and alert context sent. Screenshots inspected for menu placement, readable response, reachable composer and error controls."
+ "Current managed frontend and backend, mock monitoring disabled, real homelab and read-only model investigation. No infrastructure mutation or repeated refused readiness probe.",
+ "Proxmox node overview and History, 1h/24h/7d ranges, populated utilization/network/thermal charts. API-only node does not claim an installed Agent or expose unavailable disk throughput.",
+ "Assistant pending/completed turn, thirteen tool controls and full output/answer scrolling. Saved provider refusal remains visible and actual manual execution returns HTTP 409."
],
"interactions": [
- "node scripts/check-patrol-assistant-journey.mjs",
- "Patrol at 1440/900/390: keyboard focus and Enter on Explain, exactly one selected-issue request, correct evidence/resource, autonomous false, no generic workflow starters, close/reopen preserves draft without inference.",
- "Alerts at 1440/390: More alert actions, Escape, reopen, outside click, reopen, Explain. Selected alert evidence and resource attached with autonomous false. No Patrol trigger or configuration mutation.",
- "Provider failure, Try again retains original handoff, reload does not resubmit. No page errors or unexpected non-GET requests."
+ "Node expansion, History tab, native range selection, hover on each chart, Overview/History switching, reload and reopen. Normal and narrow chart pixels inspected.",
+ "Assistant send and completion, keyboard Enter/pointer expansion and collapse, inner output scroll to end, answer pixels, Escape, history selection and reload.",
+ "Local Playwright receipts: retained-canonical-coverage/history-receipt.json and receipt.json. Source hashes match the final implementation. The model outcome is a bounded evidence-path pass, not diagnosis or autonomous Patrol qualification."
]
}
diff --git a/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx b/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
index 8b289b1930..5f2b640fb5 100644
--- a/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
+++ b/frontend-modern/src/components/Workloads/NodeDrawer.test.tsx
@@ -319,6 +319,31 @@ describe('NodeDrawer', () => {
);
});
+ it('uses canonical history coordinates instead of the display resource identity', async () => {
+ render(() => (
+ <NodeDrawer
+ node={makeNode({
+ id: 'agent-canonical-id',
+ linkedAgentId: '',
+ metricsTarget: { resourceType: 'node', resourceId: 'cluster-pve-native' },
+ })}
+ />
+ ));
+ await fireEvent.click(screen.getByText('History'));
+ await waitFor(() =>
+ expect(chartsApiMocks.getMetricsHistory).toHaveBeenCalledWith(
+ expect.objectContaining({
+ resourceType: 'node',
+ resourceId: 'cluster-pve-native',
+ range: '24h',
+ }),
+ ),
+ );
+ expect(
+ screen.getAllByTestId('guest-history-group-chart').map((chart) => chart.dataset.historyGroup),
+ ).toEqual(['utilization', 'network', 'thermals']);
+ });
+
it('renders API-only node history without unavailable disk throughput', async () => {
render(() => (
<NodeDrawer
diff --git a/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0713.test.ts b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0713.test.ts
index d86ddf604a..a1d33c76e0 100644
--- a/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0713.test.ts
+++ b/frontend-modern/src/components/Workloads/__tests__/nodeDrawerModel.branchcov0713.test.ts
@@ -47,6 +47,34 @@ const makeTemp = (overrides: Partial<Temperature> = {}): Temperature => ({
describe('nodeDrawerModel (branch coverage 0713)', () => {
describe('getNodeDrawerHistoryTarget', () => {
+ it.each(['node', 'agent'] as const)(
+ 'uses canonical %s storage coordinates before display and linked identities',
+ (resourceType) => {
+ const node = makeNode({
+ linkedAgentId: 'agent:legacy-link',
+ metricsTarget: { resourceType, resourceId: 'retained-native-id' },
+ });
+ expect(getNodeDrawerHistoryTarget(node)).toStrictEqual({
+ resourceType,
+ resourceId: 'retained-native-id',
+ });
+ },
+ );
+
+ it.each([
+ { resourceType: 'node', resourceId: ' ' },
+ { resourceType: 'vm', resourceId: 'guest-id' },
+ ] as const)(
+ 'retains legacy history when canonical coordinates are unusable: %o',
+ (metricsTarget) => {
+ expect(
+ getNodeDrawerHistoryTarget(
+ makeNode({ linkedAgentId: 'agent:legacy-link', metricsTarget }),
+ ),
+ ).toStrictEqual({ resourceType: 'agent', resourceId: 'legacy-link' });
+ },
+ );
+
it('strips only the first agent: prefix when the value is double-prefixed', () => {
// stripAgentPrefix runs a single startsWith + slice, so 'agent:agent:node-9'
// collapses to 'agent:node-9' (one prefix removed), NOT 'node-9'.
diff --git a/frontend-modern/src/components/Workloads/nodeDrawerModel.ts b/frontend-modern/src/components/Workloads/nodeDrawerModel.ts
index caeb682004..805d8491c5 100644
--- a/frontend-modern/src/components/Workloads/nodeDrawerModel.ts
+++ b/frontend-modern/src/components/Workloads/nodeDrawerModel.ts
@@ -25,6 +25,11 @@ export const PVE_API_NODE_HISTORY_GROUPS: GuestDrawerHistoryGroupConfig[] =
HOST_METRICS_HISTORY_GROUPS.filter((group) => group.id !== 'disk-io');
export const getNodeDrawerHistoryTarget = (node: Node): NodeDrawerHistoryTarget | null => {
+ const target = node.metricsTarget;
+ if (target && (target.resourceType === 'node' || target.resourceType === 'agent')) {
+ const resourceId = target.resourceId.trim();
+ if (resourceId) return { resourceType: target.resourceType, resourceId };
+ }
const linkedAgentId = (node.linkedAgentId || '').trim();
if (linkedAgentId) {
const resourceId = stripAgentPrefix(linkedAgentId);
diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.ts
index edfd4f1ad0..fceb0202c9 100644
--- a/frontend-modern/src/types/api.ts
+++ b/frontend-modern/src/types/api.ts
@@ -152,6 +152,7 @@ export interface KubernetesDeployment {
}
export interface Node {
+ metricsTarget?: Resource['metricsTarget'];
id: string;
name: string;
displayName?: string;
diff --git a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
index c75f55195d..797ee03f22 100644
--- a/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
+++ b/frontend-modern/src/utils/__tests__/resourceStateAdapters.test.ts
@@ -52,6 +52,20 @@ const createServiceResource = (
}) as Resource;
describe('resourceStateAdapters nodeFromResource', () => {
+ it('keeps Proxmox metric coordinates without inventing an agent from discovery routing', () => {
+ const resource = {
+ ...createNodeResource({ proxmox: { nodeName: 'pve-node-1' } }),
+ id: 'agent-canonical-id',
+ metricsTarget: { resourceType: 'node', resourceId: 'cluster-pve-node-1' },
+ discoveryTarget: { resourceType: 'agent', resourceId: 'pve-node-1', agentId: 'pve-node-1' },
+ } as Resource;
+ const node = nodeFromResource(resource);
+ expect(node?.metricsTarget).toEqual(resource.metricsTarget);
+ expect(node?.linkedAgentId).toBeUndefined();
+ const linked = nodeFromResource({ ...resource, agent: { agentId: 'real-agent' } });
+ expect(linked?.linkedAgentId).toBe('real-agent');
+ });
+
it('maps canonical linkedAgentId', () => {
const node = nodeFromResource(
createNodeResource({
diff --git a/frontend-modern/src/utils/resourceStateAdapters.ts b/frontend-modern/src/utils/resourceStateAdapters.ts
index 1872fa1bad..c9617893dd 100644
--- a/frontend-modern/src/utils/resourceStateAdapters.ts
+++ b/frontend-modern/src/utils/resourceStateAdapters.ts
@@ -25,7 +25,7 @@ import { $RAW } from 'solid-js/store';
import type { Resource } from '@/types/resource';
import {
- getActionableAgentIdFromResource,
+ getExplicitAgentIdFromResource,
getExplicitResourceClusterName,
hasDockerFacetEvidence,
} from '@/utils/agentResources';
@@ -1424,7 +1424,7 @@ export const nodeFromResource = (resource: Resource): Node | null => {
preferredHostLabel;
const name = asString(proxmox?.nodeName) || asString(proxmox?.node) || preferredHostLabel;
const linkedAgentId =
- asString(platform?.linkedAgentId) || getActionableAgentIdFromResource(resource);
+ asString(platform?.linkedAgentId) || getExplicitAgentIdFromResource(resource);
const agentFacet = resource.agent;
const agentNetworkInterfaces = agentFacet?.networkInterfaces;
const proxmoxNetworkInterfaces = Array.isArray(proxmox?.networkInterfaces)
@@ -1439,6 +1439,7 @@ export const nodeFromResource = (resource: Resource): Node | null => {
return {
id: resource.id,
+ metricsTarget: resource.metricsTarget,
name,
displayName: getPreferredInfrastructureDisplayName(resource),
instance,
diff --git a/internal/ai/tools/tools_summarize.go b/internal/ai/tools/tools_summarize.go
index 33dbca637d..e322c2da4d 100644
--- a/internal/ai/tools/tools_summarize.go
+++ b/internal/ai/tools/tools_summarize.go
@@ -315,9 +315,7 @@ func summarizeReportTypeForResource(res unifiedresources.Resource) string {
// on it) while the metrics target rides MetricsResourceID. When the resolved
// target's type is one reporting understands, it wins over the static
// classification — merged host resources advertise the store family their
-// metrics are actually written under. Pure Proxmox nodes are the documented
-// exception: their metrics live under the "node" store type while the target
-// labels the agent family, so the node classification is kept there.
+// metrics are actually written under.
func (e *PulseToolExecutor) summarizeFleetCandidateFor(res unifiedresources.Resource) (summarizeFleetCandidate, bool) {
id := strings.TrimSpace(res.ID)
reportType := summarizeReportTypeForResource(res)
@@ -332,10 +330,8 @@ func (e *PulseToolExecutor) summarizeFleetCandidateFor(res unifiedresources.Reso
}
if target := e.resourceMetricsTarget(res); target != nil {
cand.metricsID = strings.TrimSpace(target.ResourceID)
- if reportType != "node" {
- if canonical := reporting.CanonicalResourceType(target.ResourceType); canonical != "" {
- cand.reportType = canonical
- }
+ if canonical := reporting.CanonicalResourceType(target.ResourceType); canonical != "" {
+ cand.reportType = canonical
}
}
return cand, true
diff --git a/internal/ai/tools/tools_summarize_test.go b/internal/ai/tools/tools_summarize_test.go
index 2d2fbc34b3..821025b372 100644
--- a/internal/ai/tools/tools_summarize_test.go
+++ b/internal/ai/tools/tools_summarize_test.go
@@ -411,7 +411,7 @@ func newSummarizeStubProvider() *stubSummarizeResourceProvider {
},
},
targets: map[string]*unifiedresources.MetricsTarget{
- "host-abc123": {ResourceType: "agent", ResourceID: "delly-node-id"},
+ "host-abc123": {ResourceType: "node", ResourceID: "delly-node-id"},
"vm-def456": {ResourceType: "vm", ResourceID: "pve1:node:101"},
},
}
@@ -448,8 +448,7 @@ func TestSummarizeTool_FleetEnumeratesWhenIDsOmitted(t *testing.T) {
if len(parsed.Resources) != 2 || parsed.Resources[0].Name != "delly" || parsed.Resources[1].Type != "vm" {
t.Errorf("Resources = %+v", parsed.Resources)
}
- // Pure Proxmox node classification keeps the "node" reporting type even
- // though the metrics target labels the agent family.
+ // Pure Proxmox history follows its canonical node store coordinates.
if parsed.Resources[0].Type != "node" {
t.Errorf("host entry type = %q, want node", parsed.Resources[0].Type)
}
diff --git a/internal/unifiedresources/metrics_targets.go b/internal/unifiedresources/metrics_targets.go
index e4d9930aa1..7d301fc80b 100644
--- a/internal/unifiedresources/metrics_targets.go
+++ b/internal/unifiedresources/metrics_targets.go
@@ -31,7 +31,9 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metric
return &MetricsTarget{ResourceType: "agent", ResourceID: st.SourceID}
}
if st, ok := bySource[SourceProxmox]; ok {
- return &MetricsTarget{ResourceType: "agent", ResourceID: st.SourceID}
+ // Resource identity is agent-shaped, but PVE history is written
+ // under the node store family. Keep storage coordinates explicit.
+ return &MetricsTarget{ResourceType: "node", ResourceID: st.SourceID}
}
if st, ok := bySource[SourceVMware]; ok {
return &MetricsTarget{ResourceType: "agent", ResourceID: st.SourceID}
diff --git a/internal/unifiedresources/metrics_targets_test.go b/internal/unifiedresources/metrics_targets_test.go
index 92adec8c6e..c689df6577 100644
--- a/internal/unifiedresources/metrics_targets_test.go
+++ b/internal/unifiedresources/metrics_targets_test.go
@@ -7,12 +7,13 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/models"
)
-func TestBuildMetricsTarget_UsesCanonicalAgentTypeForInfrastructureFamilies(t *testing.T) {
+func TestBuildMetricsTarget_UsesWrittenStoreCoordinatesForInfrastructureFamilies(t *testing.T) {
tests := []struct {
name string
resource Resource
sourceTargets []SourceTarget
wantID string
+ wantType string
}{
{
name: "proxmox infrastructure node",
@@ -23,7 +24,8 @@ func TestBuildMetricsTarget_UsesCanonicalAgentTypeForInfrastructureFamilies(t *t
Source: SourceProxmox,
SourceID: "pve-node-1",
}},
- wantID: "pve-node-1",
+ wantID: "pve-node-1",
+ wantType: "node",
},
{
name: "vmware host",
@@ -66,8 +68,12 @@ func TestBuildMetricsTarget_UsesCanonicalAgentTypeForInfrastructureFamilies(t *t
if target == nil {
t.Fatal("BuildMetricsTarget() returned nil")
}
- if target.ResourceType != "agent" {
- t.Fatalf("ResourceType = %q, want agent", target.ResourceType)
+ wantType := tt.wantType
+ if wantType == "" {
+ wantType = "agent"
+ }
+ if target.ResourceType != wantType {
+ t.Fatalf("ResourceType = %q, want %q", target.ResourceType, wantType)
}
if target.ResourceID != tt.wantID {
t.Fatalf("ResourceID = %q, want %q", target.ResourceID, tt.wantID)
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index 9009c813ea..2f28129854 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -1211,215 +1211,27 @@ func (s *Store) coalesceQueuedRequests(initial writeRequest) []writeRequest {
}
}
-// Query retrieves metrics for a resource within a time range, with optional downsampling
+// Query retrieves one metric using the same tier reconciliation as fleet reads.
func (s *Store) Query(resourceType, resourceID, metricType string, start, end time.Time, stepSecs int64) ([]MetricPoint, error) {
- resourceType = normalizeMetricResourceType(resourceType)
- resourceID = normalizeMetricIdentifier(resourceID)
- metricType = normalizeMetricType(metricType)
- tiers := s.tierFallbacks(end.Sub(start))
- if len(tiers) == 0 {
- return []MetricPoint{}, nil
- }
-
- for i, tier := range tiers {
- points, err := s.queryWithTier(resourceType, resourceID, metricType, start, end, stepSecs, tier)
- if err != nil {
- return nil, err
- }
- if len(points) > 0 || i == len(tiers)-1 {
- return points, nil
- }
-
- log.Debug().
- Str("resourceType", resourceType).
- Str("resourceId", resourceID).
- Str("metric", metricType).
- Str("fromTier", string(tier)).
- Str("toTier", string(tiers[i+1])).
- Msg("Metrics query empty; falling back to more detailed tier")
- }
-
- return []MetricPoint{}, nil
-}
-
-func (s *Store) queryWithTier(resourceType, resourceID, metricType string, start, end time.Time, stepSecs int64, tier Tier) ([]MetricPoint, error) {
- var rows *sql.Rows
- var err error
-
- sqlQuery := `
- SELECT timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND metric_type = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY timestamp ASC
- `
- queryParams := []interface{}{resourceType, resourceID, metricType, string(tier), start.Unix(), end.Unix()}
-
- if stepSecs > 1 {
- sqlQuery = `
- SELECT
- (timestamp / ?) * ? + (? / 2) as bucket_ts,
- AVG(value),
- MIN(COALESCE(min_value, value)),
- MAX(COALESCE(max_value, value))
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND metric_type = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- GROUP BY bucket_ts
- ORDER BY bucket_ts ASC
- `
- queryParams = []interface{}{
- stepSecs, stepSecs, stepSecs,
- resourceType, resourceID, metricType, string(tier), start.Unix(), end.Unix(),
- }
- }
-
- // Retry on SQLITE_BUSY
- for i := 0; i < 5; i++ {
- rows, err = s.db.Query(sqlQuery, queryParams...)
-
- if err == nil {
- break
- }
- if i < 4 && (err.Error() == "database is locked" || err.Error() == "sql: database is closed") {
- time.Sleep(time.Duration(100*(i+1)) * time.Millisecond)
- continue
- }
- return nil, fmt.Errorf("failed to query metrics: %w", err)
- }
- defer rows.Close()
-
- var points []MetricPoint
- for rows.Next() {
- var ts int64
- var p MetricPoint
- if err := rows.Scan(&ts, &p.Value, &p.Min, &p.Max); err != nil {
- log.Warn().Err(err).Msg("Failed to scan metric row")
- continue
- }
- p.Timestamp = time.Unix(ts, 0)
- points = append(points, p)
+ result, err := s.queryBatch(resourceType, []string{resourceID}, []string{metricType}, start, end, stepSecs)
+ if err != nil {
+ return nil, err
}
-
- return points, rows.Err()
+ return result[normalizeMetricIdentifier(resourceID)][normalizeMetricType(metricType)], nil
}
-// QueryAll retrieves all metric types for a resource within a time range, with optional downsampling
+// QueryAll retrieves all metric types, filling observation times missing from
+// the preferred tier before applying optional downsampling.
func (s *Store) QueryAll(resourceType, resourceID string, start, end time.Time, stepSecs int64) (map[string][]MetricPoint, error) {
- resourceType = normalizeMetricResourceType(resourceType)
- resourceID = normalizeMetricIdentifier(resourceID)
- tiers := s.tierFallbacks(end.Sub(start))
- if len(tiers) == 0 {
- return map[string][]MetricPoint{}, nil
- }
-
- result := make(map[string][]MetricPoint)
- for i, tier := range tiers {
- tierResult, err := s.queryAllWithTier(resourceType, resourceID, start, end, stepSecs, tier)
- if err != nil {
- return nil, err
- }
- if len(tierResult) == 0 {
- if i < len(tiers)-1 && len(result) == 0 {
- log.Debug().
- Str("resourceType", resourceType).
- Str("resourceId", resourceID).
- Str("fromTier", string(tier)).
- Str("toTier", string(tiers[i+1])).
- Msg("Metrics query empty; falling back to more detailed tier")
- }
- continue
- }
-
- // Merge in any metrics missing from higher tier results.
- added := 0
- for metric, points := range tierResult {
- if len(points) == 0 {
- continue
- }
- if existing, ok := result[metric]; !ok || len(existing) == 0 {
- result[metric] = points
- added++
- }
- }
-
- // If we already have some metrics and this tier didn't add anything new,
- // keep going in case lower tiers have newly introduced metrics.
- if added == 0 && i < len(tiers)-1 && len(result) == 0 {
- log.Debug().
- Str("resourceType", resourceType).
- Str("resourceId", resourceID).
- Str("fromTier", string(tier)).
- Str("toTier", string(tiers[i+1])).
- Msg("Metrics query empty; falling back to more detailed tier")
- }
- }
-
- return result, nil
-}
-
-func (s *Store) queryAllWithTier(resourceType, resourceID string, start, end time.Time, stepSecs int64, tier Tier) (map[string][]MetricPoint, error) {
- var rows *sql.Rows
- var err error
-
- sqlQuery := `
- SELECT metric_type, timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY metric_type, timestamp ASC
- `
- queryParams := []interface{}{resourceType, resourceID, string(tier), start.Unix(), end.Unix()}
-
- if stepSecs > 1 {
- sqlQuery = `
- SELECT
- metric_type,
- (timestamp / ?) * ? + (? / 2) as bucket_ts,
- AVG(value),
- MIN(COALESCE(min_value, value)),
- MAX(COALESCE(max_value, value))
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- GROUP BY metric_type, bucket_ts
- ORDER BY metric_type, bucket_ts ASC
- `
- queryParams = []interface{}{
- stepSecs, stepSecs, stepSecs,
- resourceType, resourceID, string(tier), start.Unix(), end.Unix(),
- }
- }
-
- // Retry on SQLITE_BUSY
- for i := 0; i < 5; i++ {
- rows, err = s.db.Query(sqlQuery, queryParams...)
-
- if err == nil {
- break
- }
- if i < 4 && (err.Error() == "database is locked" || err.Error() == "sql: database is closed") {
- time.Sleep(time.Duration(100*(i+1)) * time.Millisecond)
- continue
- }
- return nil, fmt.Errorf("failed to query all metrics: %w", err)
+ result, err := s.queryBatch(resourceType, []string{resourceID}, nil, start, end, stepSecs)
+ if err != nil {
+ return nil, err
}
- defer rows.Close()
-
- result := make(map[string][]MetricPoint)
- for rows.Next() {
- var metricType string
- var ts int64
- var p MetricPoint
- if err := rows.Scan(&metricType, &ts, &p.Value, &p.Min, &p.Max); err != nil {
- log.Warn().Err(err).Msg("Failed to scan metric row")
- continue
- }
- p.Timestamp = time.Unix(ts, 0)
- result[metricType] = append(result[metricType], p)
+ metrics := result[normalizeMetricIdentifier(resourceID)]
+ if metrics == nil {
+ metrics = make(map[string][]MetricPoint)
}
-
- return result, rows.Err()
+ return metrics, nil
}
// queryAllBatchChunkSize limits the number of resource IDs per SQL IN clause
@@ -1480,40 +1292,17 @@ func (s *Store) queryBatch(
}
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
@@ -1543,65 +1332,66 @@ func normalizeMetricTypes(metricTypes []string) []string {
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] = "?"
- }
- inClause := strings.Join(placeholders, ",")
+// 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.
+func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, start, end time.Time, tiers []Tier) (string, []interface{}) {
+ idSlots := strings.TrimSuffix(strings.Repeat("?,", len(resourceIDs)), ",")
metricClause := ""
- metricArgs := make([]interface{}, 0, len(metricTypes))
if len(metricTypes) > 0 {
- metricPlaceholders := make([]string, len(metricTypes))
- for i, metricType := range metricTypes {
- metricPlaceholders[i] = "?"
- metricArgs = append(metricArgs, metricType)
- }
- metricClause = fmt.Sprintf(" AND metric_type IN (%s)", strings.Join(metricPlaceholders, ","))
+ metricClause = " AND m.metric_type IN (" + strings.TrimSuffix(strings.Repeat("?,", len(metricTypes)), ",") + ")"
}
-
+ branches := make([]string, 0, len(tiers))
var params []interface{}
- var sqlQuery string
-
- if stepSecs > 1 {
- params = make([]interface{}, 0, len(resourceIDs)+len(metricArgs)+4)
+ for i, tier := range tiers {
+ branch := `SELECT m.resource_id, m.metric_type, m.timestamp, m.value,
+ COALESCE(m.min_value, m.value) AS min_value, COALESCE(m.max_value, m.value) AS max_value
+ FROM metrics AS m
+ WHERE m.resource_type = ? AND m.resource_id IN (` + idSlots + `)` + metricClause + `
+ AND m.tier = ? AND m.timestamp >= ? AND m.timestamp <= ?`
params = append(params, resourceType)
for _, id := range resourceIDs {
params = append(params, id)
}
- 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)
+ for _, metric := range metricTypes {
+ params = append(params, metric)
}
- params = append(params, metricArgs...)
params = append(params, string(tier), start.Unix(), end.Unix())
+ for _, preferred := range tiers[:i] {
+ // Retention intervals nest on UTC minute/hour/day boundaries. Using the
+ // larger interval makes both finer and coarser overlap probes indexable.
+ bucket := max(tierBucketSeconds(tier), tierBucketSeconds(preferred))
+ branch += fmt.Sprintf(` AND NOT EXISTS (
+ 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())
+ }
+ branches = append(branches, branch)
+ }
+ return strings.Join(branches, " UNION ALL ") + " ORDER BY resource_id, metric_type, timestamp ASC", params
+}
- 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)
+func tierBucketSeconds(tier Tier) int64 {
+ switch tier {
+ case TierMinute:
+ return 60
+ case TierHourly:
+ return 3600
+ case TierDaily:
+ return 86400
+ default:
+ return 1
}
+}
+
+func (s *Store) queryRetainedChunk(resourceType string, resourceIDs []string, metricTypes []string, start, end time.Time, stepSecs int64, tiers []Tier) (map[string]map[string][]MetricPoint, error) {
+ sqlQuery, params := retainedQuerySQL(resourceType, resourceIDs, metricTypes, start, end, tiers)
// Retry on SQLITE_BUSY
var rows *sql.Rows
@@ -1756,10 +1546,10 @@ func estimateQueryAllBatchSeriesCapacity(start, end time.Time, stepSecs int64) i
}
// selectTier chooses the appropriate data tier based on time range
-// Note: Tier selection uses fixed thresholds to ensure queries use tiers with complete data:
+// Tier selection defines preferred resolution, not a guarantee of coverage:
// - Raw: up to 2 hours (high-resolution real-time data)
// - Minute: up to 24 hours (recent detailed data)
-// - Hourly: up to 7 days (medium-term with mock/seeded data coverage)
+// - Hourly: up to 7 days (medium-term history)
// - Daily: beyond 7 days (long-term historical data)
func (s *Store) selectTier(duration time.Duration) Tier {
const (
@@ -1783,10 +1573,10 @@ func (s *Store) selectTier(duration time.Duration) Tier {
func (s *Store) tierFallbacks(duration time.Duration) []Tier {
switch s.selectTier(duration) {
case TierRaw:
- // Fall back to coarser tiers when raw is empty (e.g., mock mode with seeded data)
+ // Coarser buckets fill times with no preferred raw observations.
return []Tier{TierRaw, TierMinute, TierHourly}
case TierMinute:
- // Fall back to coarser tiers when minute is empty (e.g., mock mode with seeded data)
+ // Raw observations fill missing minute buckets before hourly fallback.
return []Tier{TierMinute, TierRaw, TierHourly}
case TierHourly:
return []Tier{TierHourly, TierMinute, TierRaw}
@@ -2024,8 +1814,8 @@ func (s *Store) rollupTierWindow(fromTier, toTier Tier, bucketSecs, startTs, end
resource_id,
metric_type,
AVG(value) as value,
- MIN(value) as min_value,
- MAX(value) as max_value,
+ MIN(COALESCE(min_value, value)) as min_value,
+ MAX(COALESCE(max_value, value)) as max_value,
(timestamp / ?) * ? as bucket_ts,
?
FROM metrics
@@ -2069,8 +1859,8 @@ func (s *Store) rollupCandidate(resourceType, resourceID, metricType string, fro
resource_id,
metric_type,
AVG(value) as value,
- MIN(value) as min_value,
- MAX(value) as max_value,
+ MIN(COALESCE(min_value, value)) as min_value,
+ MAX(COALESCE(max_value, value)) as max_value,
(timestamp / ?) * ? as bucket_ts,
?
FROM metrics
diff --git a/pkg/metrics/store_query_plan_test.go b/pkg/metrics/store_query_plan_test.go
index 1b78a8bc29..49524fcf36 100644
--- a/pkg/metrics/store_query_plan_test.go
+++ b/pkg/metrics/store_query_plan_test.go
@@ -6,6 +6,7 @@ import (
"net/url"
"strings"
"testing"
+ "time"
_ "modernc.org/sqlite"
)
@@ -15,7 +16,7 @@ import (
// This catches index regressions — if a schema migration drops an index or a
// query change breaks index eligibility, these tests fail immediately.
//
-// Each sub-test runs EXPLAIN QUERY PLAN on the exact SQL the store uses at
+// Each sub-test runs EXPLAIN QUERY PLAN on SQL the store uses at
// runtime. Queries are classified by how they should access the table:
// - searchRequired: the plan must use SEARCH (B-tree point/range lookup)
// - allowCoveringIndexScan: the plan may use a covering-index scan, which
@@ -24,7 +25,8 @@ import (
//
// In all cases, a bare "SCAN TABLE metrics" (full table scan) is rejected.
//
-// NOTE: The schema and SQL here are intentionally duplicated from store.go.
+// NOTE: Maintenance SQL is duplicated from store.go. Retained reads exercise
+// the shared runtime builder directly in TestRetainedQueryPlansUseIndexes.
// If store.go's schema or queries change, these tests must be updated in
// lockstep — a mismatch means they validate stale SQL.
func TestQueryPlansUseIndexes(t *testing.T) {
@@ -49,96 +51,6 @@ func TestQueryPlansUseIndexes(t *testing.T) {
// or ORDER BY without a separate sort, but still reads table rows.
allowIndexScan bool
}{
- {
- name: "single metric lookup",
- query: `SELECT timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND metric_type = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY timestamp ASC`,
- args: []any{"vm", "vm-1", "cpu", "raw", int64(0), farFuture},
- wantIndex: "idx_metrics_lookup",
- },
- {
- name: "single metric with downsampling",
- query: `SELECT
- (timestamp / ?) * ? + (? / 2) as bucket_ts,
- AVG(value),
- MIN(COALESCE(min_value, value)),
- MAX(COALESCE(max_value, value))
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND metric_type = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- GROUP BY bucket_ts
- ORDER BY bucket_ts ASC`,
- args: []any{int64(60), int64(60), int64(60), "vm", "vm-1", "cpu", "raw", int64(0), farFuture},
- wantIndex: "idx_metrics_lookup",
- },
- {
- name: "multi-metric lookup (QueryAll)",
- query: `SELECT metric_type, timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY metric_type, timestamp ASC`,
- args: []any{"vm", "vm-1", "raw", int64(0), farFuture},
- // The planner uses an indexed SEARCH — it may pick idx_metrics_query_all
- // or idx_metrics_lookup depending on statistics.
- // All are valid; the key invariant is that it does a SEARCH, not a SCAN.
- },
- {
- name: "multi-metric with downsampling (QueryAll)",
- query: `SELECT
- metric_type,
- (timestamp / ?) * ? + (? / 2) as bucket_ts,
- AVG(value),
- MIN(COALESCE(min_value, value)),
- MAX(COALESCE(max_value, value))
- FROM metrics
- WHERE resource_type = ? AND resource_id = ? AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- GROUP BY metric_type, bucket_ts
- ORDER BY metric_type, bucket_ts ASC`,
- args: []any{int64(60), int64(60), int64(60), "vm", "vm-1", "raw", int64(0), farFuture},
- },
- {
- name: "multi-resource multi-metric lookup (QueryAllBatch)",
- query: `SELECT resource_id, metric_type, timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id IN (?, ?, ?) AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY resource_id, metric_type, timestamp ASC`,
- args: []any{"vm", "vm-1", "vm-2", "vm-3", "raw", int64(0), farFuture},
- // QueryAllBatch is the anti-N+1 dashboard path. The planner may choose
- // idx_metrics_query_all or idx_metrics_lookup
- // depending on statistics; the invariant is an indexed SEARCH rather
- // than a full table scan.
- },
- {
- name: "multi-resource multi-metric with downsampling (QueryAllBatch)",
- query: `SELECT
- resource_id,
- metric_type,
- (timestamp / ?) * ? + (? / 2) as bucket_ts,
- AVG(value),
- MIN(COALESCE(min_value, value)),
- MAX(COALESCE(max_value, value))
- FROM metrics
- WHERE resource_type = ? AND resource_id IN (?, ?, ?) AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- GROUP BY resource_id, metric_type, bucket_ts
- ORDER BY resource_id, metric_type, bucket_ts ASC`,
- args: []any{int64(60), int64(60), int64(60), "vm", "vm-1", "vm-2", "vm-3", "raw", int64(0), farFuture},
- },
- {
- name: "multi-resource filtered-metric lookup (QueryMetricTypesBatch)",
- query: `SELECT resource_id, metric_type, timestamp, value, COALESCE(min_value, value), COALESCE(max_value, value)
- FROM metrics
- WHERE resource_type = ? AND resource_id IN (?, ?, ?) AND metric_type IN (?, ?) AND tier = ?
- AND timestamp >= ? AND timestamp <= ?
- ORDER BY resource_id, metric_type, timestamp ASC`,
- args: []any{"vm", "vm-1", "vm-2", "vm-3", "cpu", "memory", "raw", int64(0), farFuture},
- },
{
name: "retention delete by tier+time",
query: `DELETE FROM metrics WHERE tier = ? AND timestamp < ?`,
@@ -162,8 +74,8 @@ func TestQueryPlansUseIndexes(t *testing.T) {
SELECT
resource_type, resource_id, metric_type,
AVG(value) as value,
- MIN(value) as min_value,
- MAX(value) as max_value,
+ MIN(COALESCE(min_value, value)) as min_value,
+ MAX(COALESCE(max_value, value)) as max_value,
(timestamp / ?) * ? as bucket_ts,
?
FROM metrics
@@ -181,8 +93,8 @@ func TestQueryPlansUseIndexes(t *testing.T) {
resource_id,
metric_type,
AVG(value) as value,
- MIN(value) as min_value,
- MAX(value) as max_value,
+ MIN(COALESCE(min_value, value)) as min_value,
+ MAX(COALESCE(max_value, value)) as max_value,
(timestamp / ?) * ? as bucket_ts,
?
FROM metrics
@@ -252,6 +164,39 @@ func TestQueryPlansUseIndexes(t *testing.T) {
}
}
+// Query, QueryAll and both batch variants share this exact runtime SQL. The
+// display step is applied by the streaming reader after tier reconciliation.
+func TestRetainedQueryPlansUseIndexes(t *testing.T) {
+ db := newPlanTestDB(t)
+ store := &Store{}
+ for _, window := range []time.Duration{time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 30 * 24 * time.Hour} {
+ for _, filtered := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/filtered_%v", window, filtered), func(t *testing.T) {
+ var metrics []string
+ if filtered {
+ metrics = []string{"cpu", "memory"}
+ }
+ end := time.Unix(2000000000, 0)
+ sql, args := retainedQuerySQL("vm", []string{"vm-1", "vm-2", "vm-3"}, metrics, end.Add(-window), end, store.tierFallbacks(window))
+ plan := explainQueryPlan(t, db, sql, args)
+ searches := 0
+ for _, line := range strings.Split(plan, "\n") {
+ if strings.Contains(line, "SCAN m ") || strings.Contains(line, "SCAN h ") {
+ t.Fatalf("unbounded metrics read: %s", plan)
+ }
+ if strings.Contains(line, "SEARCH m ") || strings.Contains(line, "SEARCH h ") {
+ searches++
+ }
+ }
+ n := len(store.tierFallbacks(window))
+ if searches != n*(n+1)/2 {
+ t.Fatalf("expected every tier and overlap probe indexed, got %d: %s", searches, plan)
+ }
+ })
+ }
+ }
+}
+
func TestAvailabilityHistoryQueryPlansUseIndexes(t *testing.T) {
db := newPlanTestDB(t)
diff --git a/pkg/metrics/store_test.go b/pkg/metrics/store_test.go
index b6ed2ac519..552f16e0ff 100644
--- a/pkg/metrics/store_test.go
+++ b/pkg/metrics/store_test.go
@@ -610,7 +610,7 @@ func TestQueryAllBatch(t *testing.T) {
}
})
- t.Run("per-resource fallback stops at first non-empty tier like QueryAll", func(t *testing.T) {
+ t.Run("batch and single queries exclude fallback points outside the window", func(t *testing.T) {
tsMinute := ts.Add(-24 * time.Hour)
store.writeBatch([]bufferedMetric{
{resourceType: "disk", resourceID: "disk-raw", metricType: "smart_temp", value: 41, timestamp: ts, tier: TierRaw},
diff --git a/pkg/metrics/store_tier_coverage_test.go b/pkg/metrics/store_tier_coverage_test.go
new file mode 100644
index 0000000000..c966bb1327
--- /dev/null
+++ b/pkg/metrics/store_tier_coverage_test.go
@@ -0,0 +1,173 @@
+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)
+ }
+ })
+ }
+}