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): avoid ordinal binding allocations

rcourtman1f41fa174d7d
diff --git a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
index 58fc367449..79ea603afa 100644
--- a/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
+++ b/docs/qualification/PATROL_ASSISTANT_CUSTOMER_JOURNEY.md
@@ -1055,3 +1055,77 @@ file hashes unchanged. This supersedes the pending-hook statements above for tha
slice only. Current remote CI is not a completed pass. The f266 benchmark job
also failed and its comparison remains under investigation. The overall goal,
real-model/action qualification and provider refusal remain open and unchanged.
+
+## Large-scope query binding correction, 2026-09-06
+
+The disk-probe slice is committed as `b964eea767` and pushed to open PR #1928.
+Its final exact staged hook passes all 163 tests in 128.317s, with six unchanged
+source hashes. This supersedes the pending disk-hook status above.
+
+Build and Test run `34011979848` compares `f26668aa6ddc` against PR base
+`3347f561ec7b`, rather than the earlier `3f74c0c27304` worker baseline. Its
+remaining benchmark failure is the 500-node dashboard batch read: allocation
+events increase 24.73%, allocated bytes increase 0.62% and runtime has no
+statistically significant change. Ten alternating 100ms samples on pulse-dev
+with Go 1.26.8 and GOMAXPROCS=4 reproduce all three results. The unchanged
+repository benchmark checker rejects that candidate.
+
+The pinned SQLite driver matches each numbered parameter against argument
+ordinals, converting each compared ordinal to a string. Large scopes repeatedly
+pay those conversions. The allocation profile identifies that conversion path.
+The correction retains shared parameter values across query branches but uses
+alphabetic names and `database/sql.Named`. Every read still supplies current
+values. Resource identity, retention coverage, snapshots and cached shape bounds
+are unchanged. Parameter names are internal positions, never user values.
+
+An initial source-bound experiment against the same exact baseline reduces the
+500-node allocation difference to +0.26% and allocated bytes to -1.68%. Runtime
+has no statistically significant difference. Ten samples per variant pass the
+actual repository benchmark checker. Experiment source SHA-256 is
+`b73ea7984bded06b2a3319ed3a62fbe63ee87f63fd317a40b51d451f5c21b89c`.
+Query-plan, fresh snapshot/window/step, concurrent binding and large-scope
+binding tests pass in 0.201s. The new large-scope test reuses one cached shape
+with 500 current IDs and changed family, metric filters and time window. IDs
+that resemble SQL or parameter names remain data.
+
+Private raw experiment comparisons and profiles are under
+`tmp/patrol-disk-bench-go1268/` at the workspace root. The final product source
+also includes an explanatory comment. Full affected package/race proof, broader
+final-source comparisons and the final staged hook remain pending. The goal
+remains open for real-model diagnosis, missing-access and action-outcome
+qualification. The provider refusal is unchanged.
+
+Final product source SHA-256 is
+`72a7674a67ed1114be74038fb9a3d1e9c9d0507fb0d9597995f38aec0c8cbc56`.
+Final test source SHA-256 is
+`76be5a315e8b6dafd4a93b09711e01854087ce9f6f5a94ddb8c2ff20b3e8f708`.
+Full metrics and database packages pass on Go 1.26.8 in 77.390s and 0.203s.
+Focused retained/tier/binding/batch race proof, including the new 500-resource
+binding case, passes in 7.707s. Both source hashes match before and after proof.
+The worker log is `/opt/pulse-release-worker/patrol-named-binding-final-tests.log`.
+Broader final-source performance comparison and staged-hook qualification
+remain pending.
+
+The two latency-based concurrent SLO tests are included in the ordinary full
+suite and deliberately skip under the race detector. The separate concurrent
+and large-scope binding regressions execute under race without latency gates.
+
+The final broader comparison uses ten paired 100ms rounds on pulse-dev, with
+baseline before candidate in each round, against exact CI base `3347f561ec7b`.
+It covers all Query, QueryAllBatch, QueryManyResources and 500-node dashboard
+query/concurrent-load cases, plus history API, memory-fallback control and
+workload/summary chart APIs. All forty invocations succeed. Both metrics and
+API comparisons pass the unchanged repository checker for time, bytes and
+allocations. The 500-node read remains +0.26% in allocation events and -1.68%
+in bytes versus base, with no statistically significant runtime difference.
+
+Base source hashes match the actual git object and final source hashes match
+the product manifest above. The local and worker benchmark checker hashes are
+identical. An earlier setup used the invalid package path `./pkg/api` and is
+discarded. The complete final run uses `./internal/api` and an actual frontend
+build artifact. Its raw worker directory is
+`/opt/pulse-release-worker/patrol-wide-results-corrected/`, with the final
+comparisons, gates and logs copied to `tmp/patrol-named-binding-final-proof/` at
+the workspace root. This establishes the selected local performance proof,
+not a completed remote CI pass. Final staged-hook qualification and landing
+remain pending.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 1ca9d9f5cd..c9b78eda6b 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -10201,7 +10201,7 @@
},
{
"id": "patrol-assistant-customer-outcome-qualification",
- "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 now has a bounded service-storage scenario with independent filesystem measurements. Full qualification/CLI proof passes (4.223s/0.005s), and a provider-free Docker oracle verifies ENOSPC, zero free space, unhealthy service/healthy control, recovery, refused overwrite and symlink writes, and unchanged pre-existing inventory (final live test 8.65s). This qualifies only the fault/oracle, not model diagnosis. Missing-access at the Pulse source/tool boundary and broader host/storage-pool or backup cases remain absent. Alternate paid-provider approval remains pending. No paid request or production mutation was performed. Only run-owned disposable worker containers were faulted and removed. The published schema now accepts equivalent summary-term groups used by the new and three existing action scenarios. All twelve manifests and five full-schema regression tests pass using the CI-pinned validator. The final shipped guide passes Playwright and pixel inspection at /docs/AI_PATROL_QUALIFICATION, 1440/900/390x1000, including catalogue/section/command/limits, horizontal command scrolling, reload and keyboard index/history navigation. Storage slice staged hook and landing remain pending. Volunteered Pro environments remain a separate wider-readiness gate. Storage slice 618700db5e is pushed to open PR #1928 after the exact staged hook passed 163 tests in 127.989s with fourteen unchanged file hashes. CI on f266 exposes a shared disk-probe completion race and another benchmark failure. A controlled regression reproduces result publication before registry retirement. The canonical fix makes retirement and publication atomic to later collectors. Twenty full hostmetrics runs pass (16.687s), as do three complete race runs (1.864s), with source hashes recorded in the plan. Benchmark comparison investigation and final disk-fix staged hook/landing remain pending. These checks do not qualify model diagnosis or action outcomes.",
+ "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 now has a bounded service-storage scenario with independent filesystem measurements. Full qualification/CLI proof passes (4.223s/0.005s), and a provider-free Docker oracle verifies ENOSPC, zero free space, unhealthy service/healthy control, recovery, refused overwrite and symlink writes, and unchanged pre-existing inventory (final live test 8.65s). This qualifies only the fault/oracle, not model diagnosis. Missing-access at the Pulse source/tool boundary and broader host/storage-pool or backup cases remain absent. Alternate paid-provider approval remains pending. No paid request or production mutation was performed. Only run-owned disposable worker containers were faulted and removed. The published schema now accepts equivalent summary-term groups used by the new and three existing action scenarios. All twelve manifests and five full-schema regression tests pass using the CI-pinned validator. The final shipped guide passes Playwright and pixel inspection at /docs/AI_PATROL_QUALIFICATION, 1440/900/390x1000, including catalogue/section/command/limits, horizontal command scrolling, reload and keyboard index/history navigation. Storage slice staged hook and landing remain pending. Volunteered Pro environments remain a separate wider-readiness gate. Storage slice 618700db5e is pushed to open PR #1928 after the exact staged hook passed 163 tests in 127.989s with fourteen unchanged file hashes. CI on f266 exposes a shared disk-probe completion race and another benchmark failure. A controlled regression reproduces result publication before registry retirement. The canonical fix makes retirement and publication atomic to later collectors. Twenty full hostmetrics runs pass (16.687s), as do three complete race runs (1.864s), with source hashes recorded in the plan. Benchmark comparison investigation and final disk-fix staged hook/landing remain pending. These checks do not qualify model diagnosis or action outcomes. Disk-probe correction b964eea767 is committed and pushed to open PR #1928 after the final six-file staged hook passed 163 tests in 128.317s. The f266 CI benchmark base is 3347f561ec7b. Its 500-node dashboard query has 24.73% more allocation events, 0.62% more bytes and no significant runtime change. Ten alternating Go 1.26.8 worker samples reproduce the failure. The pinned driver repeatedly converts ordinals to strings when matching numbered parameters. Alphabetic named bindings preserve current values and query-branch reuse while avoiding those conversions. A ten-sample experiment reduces allocation difference to +0.26% and bytes to -1.68%, with no significant runtime change, and passes the actual repository benchmark checker. Final source preserves resource/metric/window semantics, snapshot coverage and cache bounds. Full metrics/database tests pass 77.390s/0.203s and focused retained/tier/binding/batch race proof passes 7.707s, including a new 500-resource cached-scope test with parameter-like and SQL-like IDs. Final source hashes and experiment receipts are recorded in the plan. Broader final-source performance proof and the staged hook remain pending. Live-model/action qualification and the provider-refusal boundary remain unchanged. The final broader comparison now passes: ten paired 100ms rounds, baseline before candidate each round, against exact CI base 3347, covering query/batch/fleet/concurrent reads and history/chart APIs with a memory-fallback control. All forty invocations succeed, and both metrics/API comparisons pass the unchanged repository time/byte/allocation checker. The final 500-node result is +0.26% allocation events and -1.68% bytes versus base with no significant runtime change. Actual base/current/checker hashes are verified. The discarded invalid ./pkg/api setup is not evidence. Final raw logs and selected-scope limits are recorded in the plan. Staged hook and landing remain pending, and remote CI is not claimed complete.",
"owner": "project-owner",
"status": "planned",
"recorded_at": "2026-09-05",
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 6770cfc059..b8917f40ba 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -46,8 +46,14 @@ 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 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
+shape. Alphabetic named SQLite bindings supply each current identity, window and
+display step once across all branches. Bindings use `database/sql.Named` so the
+driver need not repeatedly convert ordinals to strings while matching a large
+parameter set. Names describe parameter positions only. Resource IDs and all
+other values remain bound data, never interpolated SQL. The large-scope binding
+regression reuses a 500-resource query shape with new resource family, identities,
+metrics and time window, including IDs that resemble parameter names or SQL.
+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.
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index b81ae793ed..00281afe7f 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -1369,6 +1369,11 @@ func retainedQueryParameters(resourceType string, resourceIDs, metricTypes []str
if stepSecs > 1 {
params = append(params, stepSecs)
}
+ // Alphabetic names avoid the SQLite driver's repeated ordinal-to-string
+ // conversions while matching numbered parameters in large scopes.
+ for i, value := range params {
+ params[i] = sql.Named("p"+strconv.Itoa(i+1), value)
+ }
return params
}
@@ -1412,12 +1417,12 @@ func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, st
if len(metricTypes) != 1 {
identityColumns += "metric_type, "
}
- // Reuse SQLite's numbered bindings across every branch and overlap probe.
+ // Reuse SQLite's named 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)
+ values[i] = fmt.Sprintf(":p%d", first+i)
}
return strings.Join(values, ",")
}
@@ -1432,16 +1437,16 @@ func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, st
index = "idx_metrics_lookup"
}
scope := func(alias string, tierIndex int) string {
- clause := alias + ".resource_type = ?1 AND " + alias + ".resource_id IN (" + idSlots + ")"
+ clause := alias + ".resource_type = :p1 AND " + alias + ".resource_id IN (" + idSlots + ")"
if len(metricTypes) > 0 {
clause += " AND " + alias + ".metric_type IN (" + metricSlots + ")"
}
- return clause + fmt.Sprintf(" AND %s.tier = ?%d AND %s.timestamp >= ?%d AND %s.timestamp <= ?%d", alias, tierParam+tierIndex, alias, startParam, alias, endParam)
+ return clause + fmt.Sprintf(" AND %s.tier = :p%d AND %s.timestamp >= :p%d AND %s.timestamp <= :p%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)
+ bucketExpression := fmt.Sprintf("(timestamp / :p%d) * :p%d + (:p%d / 2)", stepParam, stepParam, stepParam)
if directAggregate {
projection = identityColumns + bucketExpression + ` AS bucket_ts,
AVG(m.value), MIN(COALESCE(m.min_value, m.value)), MAX(COALESCE(m.max_value, m.value))`
@@ -1458,9 +1463,9 @@ func retainedQuerySQL(resourceType string, resourceIDs, metricTypes []string, st
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 = ?%d
- AND h.timestamp >= MAX(?%d, (m.timestamp / %d) * %d)
- AND h.timestamp <= ?%d AND h.timestamp < (m.timestamp / %d) * %d + %d
+ AND h.metric_type = m.metric_type AND h.tier = :p%d
+ AND h.timestamp >= MAX(:p%d, (m.timestamp / %d) * %d)
+ AND h.timestamp <= :p%d AND h.timestamp < (m.timestamp / %d) * %d + %d
))`, tierParam+j, startParam, bucket, bucket, endParam, bucket, bucket, bucket)
}
branches = append(branches, branch)
diff --git a/pkg/metrics/store_additional_test.go b/pkg/metrics/store_additional_test.go
index 7338766542..5a3e12d82a 100644
--- a/pkg/metrics/store_additional_test.go
+++ b/pkg/metrics/store_additional_test.go
@@ -1301,3 +1301,48 @@ func TestStoreRetainedConcurrentQueryBindings(t *testing.T) {
close(start)
workers.Wait()
}
+
+// A cached large-scope query must bind every identity and filter anew. Values
+// resembling SQL parameters or SQL syntax remain resource data.
+func TestStoreRetainedLargeQueryBindings(t *testing.T) {
+ db := newPlanTestDB(t)
+ store := &Store{db: pdb.Wrap(db, "large-retained-bindings")}
+ base := time.Date(2026, 9, 6, 0, 0, 0, 0, time.UTC)
+ for round := 0; round < 2; round++ {
+ family := []string{"node", "vm"}[round]
+ metrics := [][]string{{"cpu", "memory"}, {"disk_read", "disk_write"}}[round]
+ start := base.Add(time.Duration(round) * time.Hour)
+ observed := start.Add(30 * time.Second)
+ ids := make([]string, queryAllBatchChunkSize)
+ for i := range ids {
+ ids[i] = strconv.Itoa(round) + "/resource-" + strconv.Itoa(i)
+ }
+ ids[0] += ":p1"
+ ids[len(ids)-1] += "' OR 1=1 --"
+ for _, index := range []int{0, len(ids) - 1} {
+ for _, metric := range metrics {
+ if _, err := db.Exec(`INSERT INTO metrics(resource_type,resource_id,metric_type,tier,timestamp,value) VALUES (?,?,?,'raw',?,?)`, family, ids[index], metric, observed.Unix(), float64(index+round+1)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ result, err := store.QueryMetricTypesBatch(family, ids, metrics, start, start.Add(time.Minute), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(result) != 2 {
+ t.Fatalf("round %d returned %d resources, want two", round, len(result))
+ }
+ for _, index := range []int{0, len(ids) - 1} {
+ if len(result[ids[index]]) != len(metrics) {
+ t.Fatalf("round %d resource %q returned unexpected metrics: %+v", round, ids[index], result[ids[index]])
+ }
+ for _, metric := range metrics {
+ points := result[ids[index]][metric]
+ if len(points) != 1 || points[0].Value != float64(index+round+1) || !points[0].Timestamp.Equal(observed) {
+ t.Fatalf("round %d resource %q metric %q returned wrong scope: %+v", round, ids[index], metric, points)
+ }
+ }
+ }
+ }
+}