A tenant monitor's Start goroutine assigned discoveryService in
startModeRuntime without holding m.mu, while request handlers such as
auto-register read it through GetDiscoveryService. The race detector
flagged the pair intermittently in
TestTenantProxmoxInstallTokenGrantLivesOnInstanceRecord and failed
unrelated pull requests.
startModeRuntime now chooses and assigns the service under m.mu, and
GetDiscoveryService reads it under the read lock, matching
StartDiscoveryService and StopDiscoveryService. The org ID is read
directly because GetOrgID would take the read lock again. A new race
proof calls startModeRuntime and GetDiscoveryService from two
goroutines with no ordering between them.
Contract-Neutral: Locking fix for an existing monitor field; no API, schema, discovery behavior or subsystem contract change.
Keep restored collectors running after helper rollback with their error
status. Require typed post-replacement restart failure before handing over
to the service manager. Sync executable bytes and mode before an atomic
POSIX replacement and apply the same barriers to persistent copies.
Make helper startup evidence authoritative, including an explicit absence,
so recovered and later helper starts cannot consume stale local markers.
Carry updater evidence through the canonical agent facet and host snapshot
with owned status and timestamp copies for fleet diagnostics.
Keep fleet diagnostic rows keyed by connection identity so refreshed
update evidence does not discard an open disclosure or its keyboard focus.
Keep delivery permission and SQLite available until queue workers,
admitted writes and direct fallback sends finish. Leave unclaimed rows
pending so restart and reload retain delivery work and firing receipts.
Restore shared webhook policy before persistent work is activated, including
tenant queues. Reject unreadable policy before queue creation and preserve
deployment URL locks when restoring saved installation settings.
Cover admission, concurrent stops, operator pause, channel disable,
direct fallback, restart recovery and bootstrap policy with persistent tests.
Keep API coverage of later policy replacement and revocation.
Per-sensor alerts, history and a CPU-source choice (#3565) need to name
one hardware input reliably, and the existing flat maps cannot: their
keys drop the chip's bus address and lower-case the label, so two NVMe
drives, two CPU sockets or applesmc's TC1F/TC1f collapse into one
reading, and readings outside 0-150 °C vanish.
The agent now also reports sensors.native: one entry per tempN_input
and fanN_input of every chip, keyed "<chip>/<channel>", with the
original label, kind, unit, unconverted value and an ok/invalid status.
Implausible readings such as applesmc's -127 °C stay listed as invalid
rather than disappearing, a stopped fan's 0 RPM is a reading, and a
chip whose inputs leave the legacy maps empty still reports. The list
is sorted, deduplicated and bounded at 256 entries; cluster peer
results leave it out.
Ingest accepts an entry only when its ID is exactly <chip>/<channel>
for a canonical channel of the reported kind, derives the unit, and
recomputes the status with the same shared plausibility policy, so the
server does not depend on the agent's judgement. The inventory is
carried through the host model, frontend state, unified resources,
clones and the read-state projection.
Nothing consumes it yet. The legacy maps keep their keys, filters and
consumers. The contract notes record what later slices must add first:
completeness state before a missing entry can mean a removed sensor,
and a collision-free encoding before the ID becomes a lower-cased
alert or metric key.
Refs #3565
Keep successful scopes useful when another read spends the existing budget, without renewing unread history or asserting complete protection. Bind background publication to its admitted runtime and client, and preserve explicit cancellation and ordinary recovery.
Contract-Neutral: PBS collection implementation only; no host-agent lifecycle, API, auth, polling-budget or protection-policy delta.
Change-source: pulse-maintainer
Coalesce scans across core cycles, cancel and fence retired/replaced owners, and prevent late inventories or task logs from renewing accepted evidence. Preserve independent storage/snapshot budgets and existing read-only behaviour with lifecycle regressions.
Contract-Neutral: Internal PVE poll ownership only; public schemas, provider permissions, guest operations and host-agent lifecycle are unchanged.
Change-source: pulse-maintainer
Retain live-first admission and the 25-request cap, but offer the first execution turn to the queue not served by the last actual request. Keep that cursor connection-local, advance it only for a real request and prune it with an empty history window. Cover the mixed timeout, saturated and fast-live cases without changing guest verdicts or observation ages.
Contract-Neutral: Repairs the documented no-starvation guarantee with private scheduling state; no provider, data, auth, observation or agent-lifecycle contract delta. The monitoring note clarifies the existing context-budget guarantee.
Change-source: pulse-maintainer
Keep typed HTTP 403 denials on the existing 30-minute APT and five-minute guest-memory negative intervals, without promoting stale or absent observations. Preserve successful clocks, independent target scopes, ordinary transient retries and guest lifecycle/uncertainty fences. Cover direct and cluster transports, expiry, recovery, zero evidence and shared runtime separation.
Report and patch reference: Pulse #3546 by @tyvsmith; this candidate implements the scoped repair from current source.
Reported-by: tyvsmith
Change-source: pulse-maintainer
Keep native per-device rate samples independently of complete host totals, map them only to the connection's exact inventory device, and persist the selected rates at their original bucket times. Do not invent cumulative counters, busy percentages or absent readings.
Exercise pinned REST through the poller, registry, target resolver and local/persistent disk history for both boot names, incomplete catalogues and observed zero. Preserve memory/ARC behaviour and native-writer authority.
Change-source: pulse-maintainer
The PMG poller joined every downstream read failure (queue, mail
statistics, quarantine, backups, relay domains, domain statistics,
cluster status) into the poll error the scheduler acts on. After a
successful version read, one broken optional endpoint therefore backed
off the whole connection and, after the retry limit, moved it to the
dead-letter queue at a 30-minute interval.
Every other PMG reading then went stale, which is what #2960 hit when
the queue read stopped decoding.
Split the two. Connection, authentication, version and config failures,
and a poll cut short by its own deadline or cancellation, still drive
backoff, the circuit breaker and dead-lettering. A read that fails after
the connection succeeded is recorded as a scheduler success, so the
poll keeps its normal interval and freshness, but it stays the
connection's outstanding poll error (category "partial") until a poll
completes every read. Failed readings stay missing and alert recovery
is unchanged.
PBS already keeps its optional datastore and node-status reads out of
the scheduler outcome; a new test pins that alongside the PMG cases.
Contract-Neutral: agent-lifecycle maps internal/monitoring/monitor.go; this changes only scheduler poll-outcome bookkeeping with no host-agent lifecycle delta. The monitoring contract and its proof files are updated in this commit.
Tenant monitors start asynchronously after GetMonitor returns their canonical configuration to API handlers. Consolidating that same configuration in Start races with auto-registration. Finish the existing normalization synchronously in New, before building provider caches and clients, without copying or changing the token inventory.
Contract-Neutral: Preserve tenant, registration, TLS and persistence contracts; move existing startup normalization before monitor publication and verify its ordering.
Change-source: pulse-maintainer
A provider MSP client workspace is a tenant organization of a hosted
runtime. Settings > Infrastructure minted its agent install tokens into the
org's own config copy (configapi getContextState). Agents never send
X-Pulse-Org-ID, so auth only looks them up in the instance inventory and
routes them by the token's org binding. Every agent installed from a client
workspace got 401 on every report, on v6.5.0 and v6.6.0, so a provider's
first client never received data.
The control plane's hosted install command already stored org-bound tokens
in the instance inventory, but bridged the tenant monitor with an
in-memory copy that agent removal revoked alone, that a tenant reload
dropped, and that diverged from the instance record. Store a tenant org's
tokens only in the instance inventory, from both paths, and let the tenant
monitor read them through Monitor.APITokenInventories: its own config, then
the instance records bound only to its org. Proxmox bootstrap and
auto-register, install-time command policy, Connections, Agent Doctor and
removal revocation now act on the record where it lives. Own config comes
first so a duplicate an earlier version persisted keeps its grant state,
and revocation commits in every inventory or in none. The default org and
single-runtime installs keep one inventory and are unchanged.
Tokens minted in a tenant org before this fix stay in the org copy and
still cannot authenticate; regenerating the install command fixes them.
Keep the existing guest and filesystem wire bytes, source normalization, nulls and zero values while avoiding map construction, interface boxing and key sorting on each snapshot. Retain the parent encoder as a full-wire oracle and check allocation reduction.
Contract-Neutral: Proxmox guest/platform and filesystem fields, permissions, lifecycle, sampling and wire bytes are unchanged; only synchronous broadcast serialization uses fixed records instead of dynamic maps.
Change-source: pulse-maintainer
Keep retained enrollments unknown while their accepted-report lease is
current, then show offline if no fresh report arrives. Preserve historical
timestamps, removals and report ordering without manufacturing telemetry.
Use the shared first-report state in Machines, resource details and Settings.
Refs #2980
Preserve selected memory freshness and the VM/LXC interpretation.
Retain both native tool contracts and current API concurrency controls.
Qualify this source separately from release and installed recovery.
Contract-Neutral: Integrate already-governed parents without a new contract change. Incoming verification files already match main. Fresh integration tests and source-bound browser proof cover the combined memory and installer surfaces.
The hub kept tenant-scoped delivery for state and alerts, but every
other event went through Broadcast/BroadcastMessage, which sent to all
connected clients. In a multi-tenant install a member of one
organization therefore received another organization's discovery
progress, discovered servers (addresses, ports, versions, hostnames),
node auto-registration and node-change events.
Discovery now carries the org of the monitor that owns it, and setup
and node handlers send through BroadcastMessageToTenant with the
request's org (the setup token's org for auto-registration). The
global BroadcastMessage accepts only instance-wide types (ping,
settingsUpdate, update:progress) and refuses everything else, so a new
caller cannot leak by default. Legacy clients without an org are
registered under the default tenant, so single-org installs receive
these events as before. The unused unscoped alert wrappers are removed.
Clone only primary backup, replication and connection-health fields under State's lock. Preserve source-pointer capture, mock behaviour, normalization and the previous serialized projections; fleet metadata no longer drives the allocation cost of unrelated API reads.
Contract-Neutral: Scoped in-memory projections preserve backup/job/health values, empty and mock semantics, locking and existing clone ownership; no resource, API or collection contract changes.
Change-source: pulse-maintainer
Carry cancellation through PVE/PBS construction, cluster probes and retained sessions, startup retries and port fallback. Preserve prior health/errors on caller termination; accepted clients retain independent ordinary reads and full timeouts. Cover real pinned HTTPS cancellation, deadlines, form fallback and first-poll publication.
Contract-Neutral: Restore existing caller cancellation and usable-session guarantees; no wire/API schema, agent lifecycle, TLS trust, guest safety, polling cadence or History contract delta.
Change-source: pulse-maintainer
Stage both enumeration routes' guest readings, snapshots, alerts, backup eligibility and History until their complete cycle is admitted. Retirement, runtime replacement and transport changes cancel obsolete reads and serialize state withdrawal against admitted effects without holding the monitor mutex through callbacks.
Retain authoritative inventory after detail-budget expiry, independent agents and accepted cache safety; cancellation is not command completion. Add deterministic late-reply and publication-order controls.
Change-source: pulse-maintainer
Invalidate successful and negative QGA memory caches on guest unavailability, observed stops and connection retirement. Retain and cancel obsolete read owners until completion, discard late/cancelled samples and coalesce overlapping refreshes without weakening transport uncertainty. Verify both collectors, served readings, History and independent linked-agent evidence.
Change-source: pulse-maintainer
Cancel obsolete enrichment contexts on explicit cache invalidation and PVE instance retirement while retaining ownership until completion. Serialize publication and retry scheduling with invalidation, re-read fallback metadata within the reservation, and discard late network, OS and version outcomes without weakening shared guest-command uncertainty fences. Cover late readers, slot waiting, direct/cluster HTTP cancellation and ordinary independent recovery.
Change-source: pulse-maintainer
Separate metadata-cache activity from successful observation age so empty or failing guest reads cannot erase OS-info suppression or its accumulated failures. Preserve useful and OS evidence ages, ordinary backoff and guest-command fences; expire only idle non-in-flight state and clean activity on explicit invalidation and instance retirement.
Change-source: pulse-maintainer
Close background catch-up admission atomically with its wait group, cancel between whole lifecycle events and keep the applied watermark before closing history. Start joins replay admitted by router attachment; Stop also covers a monitor that never started. Retain blocked-writer ownership through the existing tenant deletion budget, and resume the unapplied tail in a new monitor.
Contract-Neutral: Preserve canonical occurrence history, notification policy, tenant isolation and bounded deletion refusal; make existing background projection writers obey monitor lifetime without changing public API or delivery behaviour.
Change-source: pulse-maintainer
Capture store, tenant and provider selection once across source ownership, records and consume-once changes. Keep provider callbacks outside locks, refuse replaced collections, and order non-queueing read refreshes with ingest. Preserve admitted history and leave skipped changes pending.
Contract-Neutral: Internal dependency/publication ownership only; resource schemas, tenant authorization, notification policy, thresholds, retention and shutdown semantics are unchanged.
Change-source: pulse-maintainer
Apply saved notification policy before initial resource publication, batch supplemental bindings and retain explicit withdrawals for existing and future tenants. Serialize complete router initialization and refuse old binding collections before ordered writes; preserve admitted alert joins without clearing active alerts. Keep native and demo provider records separated across the mock-switch hook gap.
Contract-Neutral: Internal resource dependency wiring and publication ordering only; existing resource/API schemas, authorization and tenant boundaries, alert thresholds, retention and shutdown policy are unchanged.
Change-source: pulse-maintainer
Monitor.Start launched mock and connection alert passes without joining them. Tenant deletion could close stores and remove its directory while a pass still emitted alert writes. Wait for admitted passes, refuse new checks after cancellation, and retain the existing bounded-deletion refusal. Log real persistence deletion errors without exposing them in the API response.
Contract-Neutral: Preserve token scopes, tenant isolation, API responses and deletion safety contracts; bind existing internal alert passes to their monitor lifetime and retain failure diagnostics.
Change-source: pulse-maintainer
The mock-mode unified view caches its linked build keyed on
sameManualLinks, which compared each link's resource pair and primary
and said link metadata, time included, does not change a fold. Among
otherwise equal candidates, chained links now fold into the primary of
the earliest-created link (linkChainRootLocked), so that is false for
the creation time: a list that differs only in a time can leave a
different row standing. In a cycle of a Proxmox storage, a TrueNAS VM
and a vSphere VM the TrueNAS VM keeps its row while its link is older
than the vSphere VM's and the vSphere VM keeps it once it is newer, yet
with the fixture data version unchanged the cached view kept serving
the old row while the live rebuild, which reloads the links from the
store, served the new one.
Compare CreatedAt too. The comparison has three readers and all take the
fix: the data-version cache hit, the decision to keep the previous
freshness when a view is published, and the structure view that serves
callers reading identity and topology.
The regression test replaces the TrueNAS VM's link with one that differs
only in its time, with no fixture tick, and expects the surviving row a
mock.UnifiedResourceSnapshotWithLinks build keeps: through the structure
view and the data-version view when the time moves later, and through the
data-version view when it moves back. Removing the CreatedAt term fails
it, and so does reverting any one of the three readers on its own. The
monitoring and unified-resources contracts now say the key includes the
creation time.
Follow-up to #2778. Stacks cleanly on main; the contract prose
cross-references the wiring change in #2796, so land that first if both
are open.
## What was wrong
In mock mode the unified view is keyed on the fixture data version,
which advances on every metric tick, and building it for the default
1,776-resource estate costs about half a second of CPU (many seconds on
a starved process). #2778 moved the metrics-target lookup onto the
fixture structure revision. The other callers that read only what the
estate lists and how it connects still rebuilt the whole view after each
tick: at startup they made 42 view requests, all misses (the
Docker-alert prune 18, the connection snapshots 13, the host-agent
evaluation 8, the chart prewarm 2, the metrics-target lookup 1), and
with no client connected the monitor tick alone rebuilt the estate about
every nine seconds.
## What changes
- Callers that read identity and topology share the view built for the
current structure revision and operator links
(`currentStructureUnifiedStateView`, `GetUnifiedStructureReadState`,
`currentModeStructureReadState`, in
`internal/monitoring/unified_structure_view.go`; `mockMetricsTarget`
uses the same cache reader): the Docker-alert prune, the workload chart
prewarm, the demo Patrol operator-state resolver, and the host-agent
evaluation. `evaluateHostAgents`, which runs on every monitor tick, now
lists nodes only when an offline host names a linked node.
- The connection-degraded alert feed keeps only platform rows
(`snapshotConnectionsForAlerts` drops every agent row, and a PBS row's
reported node name only becomes a host alias that its snapshot does not
carry). It now builds the aggregator inputs with `platformRowsOnly`, so
it no longer reads the hosts, their desired-config fingerprints or the
PBS instances. The connections endpoint, diagnostics and runtime
inventory still read them.
- Deliberately not moved:
- The mock storage chart (`resolveMockStorageTotal`): a linked pool
takes its capacity from whichever source was seen last, which a tick can
move without a structure change. It stays on the data-version view, read
once per request instead of once per uncached pool.
- `linkedHostForNode`, `getHostAgentTemperatureForNode` and
`carriedTemperatureOutlivesAgentLease` (only reachable with
`PULSE_MOCK_KEEP_REAL_POLLING`): they read a host's status, disks,
sensors and report lease, which a tick moves. Hoisting them would need
the read state threaded through the node poller, and they run after
startup, so they stay as they were.
Real mode is unchanged.
## Measured (pulse-dev, probe builds, one pinned core, GOMAXPROCS=1,
host load 30 to 110, single runs)
| | #2796 alone | with this change |
|---|---|---|
| estate view builds before the listener answers | 2 | 1 |
| estate builds, no client connected, 299 s of life | 33 | 2 (both at
startup) |
| process CPU over a 180 s steady window | 12.3 s | 3.3 s |
A separate run of the pre-#2796 build used 9.0 s over that window, so
read 12.3 against 3.3 as the comparison rather than as exact
percentages. The public demo host runs a mock estate, so the
steady-state saving is the one that matters there.
## Verification
- New tests (in registered proof files): no consumer of the structure
view rebuilds the view after a fixture tick (Docker prune, structure
node listing, workload prewarm, host-agent evaluation including an
offline host that names a linked node); the data-version view still
rebuilds; the structure view follows a structural fixture change and an
operator link; lazy correlation lists nodes only for a linked host; a
storage chart reads the estate only when it is not cached; the alert
feed does not rebuild the view, its platform rows equal the full
aggregator's, and configured PVE/PBS/PMG rows survive without the hosts;
the Patrol resolver does not rebuild the view.
- Negative controls (each fails the named test): prune, prewarm, eager
node listing, structure node listing, alert feed and Patrol resolver
each moved back to the data-version view, and a storage chart that reads
the estate before checking its cache.
- `go vet` and the targeted tests on pulse-dev.
## Known limits
- The structure view can be several ticks old, so a caller on it must
not read status, metric values, timestamps, sensors or anything a link
merges by freshness; the contract says so. The fixture sets pod node
names (which feed the platform aliases a Patrol reference can resolve
through) when the estate is built, not on a tick.
- `pbsInstanceFromReadStateView` never copies `NodeName`, so
`pbsReportedNodeNamesByInstance` appears to feed empty host aliases on
the connections endpoint. That is a separate bug, not changed here.
- The batch sharing of the storage chart's read (`sync.OnceValue` in
`GetStorageMetricsForChartBatch`) is not pinned by a test; the
single-chart laziness is.
Not a feature: no demand-ledger entry.
In mock mode the unified view is keyed on the fixture data version, which
advances on every metric tick, and building it for the default
1,776-resource estate costs about half a second of CPU (many seconds on a
starved process). #2778 moved the metrics-target lookup onto the fixture
structure revision; the other callers that read only what the estate
lists and how it connects still rebuilt the whole view after each tick.
At startup they made 42 view requests, all misses, and with no client
connected the monitor tick alone rebuilt the estate about every nine
seconds.
Callers that read identity and topology now share the view built for the
current structure revision and operator links (currentStructureUnifiedStateView,
GetUnifiedStructureReadState): the Docker-alert prune, the workload chart
prewarm, the demo Patrol resolver, and the host-agent evaluation, which
also lists nodes only when an offline host names a linked node. The
connection-degraded alert feed keeps only platform rows, so it no longer
reads the hosts, their desired-config fingerprints or the PBS instances
that only feed agent rows and a host alias its snapshot drops.
The mock storage chart is not one of them: a linked pool takes its
capacity from whichever source was seen last, which a tick can move
without a structure change. It keeps the data-version view, read once per
request instead of once per uncached pool. The per-node polling lookups
of a monitor that keeps real polling in mock mode (linkedHostForNode,
getHostAgentTemperatureForNode, carriedTemperatureOutlivesAgentLease)
read a host's status, disks and sensors, which a tick moves, so they stay
on the data-version view.
On pulse-dev (one pinned core, host load 30 to 110, probe builds): a
start built the estate view twice before the listener answered with the
wiring change alone and once with this; with no client connected the
process built the estate 33 times in 299 s and used 12.3 s of CPU over a
180 s window, against twice and 3.3 s with this change.
The PBS poll records the hostname the node reports about itself on
PBSInstance.NodeName so /api/connections can alias the PBS connection by
it and group the host agent running on that machine into the PBS row.
The name reaches the unified PBS resource (PBSData.NodeName), but
Monitor.PBSInstancesSnapshot() rebuilds each instance from the read-state
view, and the view had no accessor for it, so the snapshot always carried
an empty NodeName. The ledger's reported-name map was therefore always
empty and a PBS machine configured by IP or DNS alias still showed as an
API row plus a separate agent row. The unit tests missed it because they
hand the aggregator its inputs instead of going through the monitor.
Add PBSInstanceView.NodeName() and copy it in pbsInstanceFromReadStateView.
The new ledger test drives a real monitor through the input builder, the
connection aliases and the system grouping: with the conversion line
removed it fails on the missing alias, with it the agent attaches to the
PBS system.
Only direct root@pam sessions can read the node name (API-token
connections get none), so this restores grouping for password-auth PBS
connections; token-auth ones still match only on what they were
configured with.
Splitting a merged physical disk (the drawer's "Split merged resource",
POST /api/resources/{id}/report-merge) recorded its exclusions and the
registry kept two rows, but the PVE disk poller had already paired the
linked agent's SMART row with the Proxmox disk by WWN, serial or path
before the registry saw either, and read no exclusions. The split Proxmox
row still carried the agent's attributes, I/O, health, any serial, WWN,
type or temperature it filled, and AgentSMARTReported, which hands the
disk's temperature alert to the agent's CheckHost. #2748 listed this as
the part of the split it did not reach.
mergeHostAgentSMARTIntoDisks now asks the resource store
(MonitorAdapter.ProxmoxDiskAgentSMARTSplit) once per matched row. The
answer is physicalDiskSplitLocked's, applied to the agent's disk as the
registry generation holds it and to the Proxmox observation under its own
ID, so the exclusions that keep the registry's rows apart keep the
poller's pair apart: an exclusion naming only the agent's candidate
splits nothing, a replacement in the slot inherits no split recorded
against the disk it replaced, and a manual link that leaves the
generation holding both observations as one disk pairs them again.
A split disk takes nothing from the row. That includes the node-sensor
temperature the agent supplied: the node poll takes its SMART list from a
reporting agent whose report carries a usable reading, so that reading is
the agent's row of the other disk; an SSH-supplied reading stays and the
PVE disk check judges it. The record is marked AgentSMARTSplit, so the
poll's evidence retention restores nothing into it, and the
Proxmox-query-failure fallback gives it no stand-in row.
The split applies on the first full disk poll that collects the node from
Proxmox and matches the agent's row; the unified-resources contract names
that lag and the other limits.
An operator's split of a Proxmox node and its pulse-agent (report-merge
or unlink) split the registry's rows in #2741, but the monitor's own
link (Node.LinkedAgentID, Host.LinkedNodeID) stayed. Everything that
reads that link kept treating two machines as one: the agent's SMART
inventory as the node's disk fallback, its --disk-exclude patterns on
the node's disks, guest discovery through the agent, deployment
reporting the node as already running an agent, service discovery, the
agent's container filesystem readings, the node's temperatures and the
node/agent alert correlation.
The resource store's exclusion is now the one record of the split.
MonitorAdapter decides it with the registry's own rule for a node's link
and confirms a split against the store's latest decisions, and
models.State holds both sides of a split link back on every link write,
before a link can steer where node views fold. The agents API's node
link is the operator's newer decision, so it removes the pair's split
from the store (TakeExclusion) before recording manual intent, and
puts it back, unless the operator decided again meanwhile, if the
intent fails to persist (RestoreExclusion). A split recorded after a
manual link ends that intent on the agent's next report that finds the
split confirmed, so the node is no longer reserved for that agent.
A rebuild that cannot read the store's decisions still loads none, in
the registry as in monitoring; that needs a change in registry.go and
monitor_adapter.go and is left for a follow-up.
Alert evaluation resolves a metrics target for every resource and
windowed metric. In mock mode that went through the unified view cache,
keyed on the fixture data version, which advances on every 2 s metric
tick. Building the view for the default 1,776-resource estate costs about
half a second of CPU, so a process starved of CPU published each build
under an already-stale version and the next lookup built again. Startup
runs the first alert pass before the listener opens, so it never got
there: 675 of 929 view requests missed at a 16 s average build, and the
process had not served at 606 s.
A target depends only on a resource's type and source mappings, which a
metric tick never changes. Key the lookup on a new structure revision
(mock.FixtureStructureRevision, the existing structural-only counter)
and the link list instead, and answer from the targets the cached view
captured. An ID the estate does not list resolves to nothing without a
build. The view itself stays keyed on the data version for every other
consumer. The fixture now advances its data version before its structure
revision, and a cache fill reads the revision first, so a reader that sees
a new revision cannot cache the previous estate's snapshot under it.
This is not a regression from 1a094646d7..d2ac0c5112: both commits stall
identically under equal CPU contention and both start in 14 to 16 s at
normal load. Real mode does not pay the cost in steady state either; a
full store pass over 1,694 resources takes about 108 ms.
On pulse-dev, with the process pinned to one core behind four busy
loops, the fixed binary serves at 148 s where the previous behaviour had
not served at 606 s. The remaining startup time there is one view build
per consumer per tick, and the monitor's repeated full resource-store
passes; neither is changed here.
## Problem
In mock mode, operator manual links (`POST /api/resources/{id}/link`)
never reached the websocket broadcast or `/api/state` `resources`, even
after a restart, while `GET /api/resources/{id}` showed the pair merged.
`Monitor.currentUnifiedStateView` builds the mock view from the fixture
graph, and both the fixture build and the view's re-ingest used
`unifiedresources.NewRegistry(nil)`, so no links were loaded. The
resources API seeds its own store-backed registry from that same list,
which is why it showed the merge.
## Change
- `mock.UnifiedResourceSnapshotWithLinks(links)` builds the fixture
graph in `unifiedresources.NewRegistryWithManualLinks(links)`, a
registry with the links but no store. The links apply at each ingest
stage (snapshot, TrueNAS and vSphere records, then availability), as in
the live rebuild, so an availability check that names the folded
resource by source still projects onto the primary. Nothing the fixture
build ingests can write identity pins, successions or change rows.
Without links the shared memoized snapshot is used, as before.
- The monitor takes the links from its resource store's current
generation (`MonitorAdapter.ManualLinks`). It keys the cached mock view
on the fixture data version and the link list, so a link change rebuilds
the view without waiting for a fixture tick.
- The view's freshness is the key for the resources API's registry
cache, so it is now assigned in publication order. A view with the
published fixture freshness and links keeps the published value. Any
other view gets a value later than every view before it, so a slow build
that publishes late cannot reuse one.
- The real-mode fence view behind `currentModeReadState` still leaves
the links out. It only covers the short window after leaving mock mode,
before the registry rebuilds. Its comment now says why.
## Verification
- Private mock stack, websocket not blocked. Linked standalone agent
Apollo-114 into VM checkout-web-01.
- Before: REST showed the agent facet while `/api/state` and the
websocket `initialState` still listed the agent as its own row. Machines
still listed both linked agents.
- After: REST, `/api/state` and `initialState` agree, and they still
agree after a restart.
- On a websocket held open across the link, a `resourceDelta` upserted
the VM with sources `[proxmox, agent]` and removed the agent.
- A headless browser kept the Machines table open while the link was
posted from outside the page. The agent left the table in 3.6 s, with no
reload.
- New tests:
- `TestMockUnifiedViewAppliesOperatorManualLinks`
(monitor_host_agents_test.go)
- `TestFixtureGraphAppliesManualLinksAtEachIngestStage` and
`TestUnifiedResourceSnapshotWithLinksLeavesTheSharedSnapshotUnlinked`
(platform_fixtures_test.go)
- `TestRegistryWithManualLinksFoldsLikeTheStoreBackedRegistry`
(registry_test.go)
- Negative controls, run with `go test -overlay`. Each one fails at the
expected assertion:
- main's monitor.go
- a `NewRegistryWithManualLinks` that drops its links
- monitor.go without the publication-order freshness rule
- `internal/unifiedresources/...`, `internal/monitoring/...` and
`internal/mock/...` pass on pulse-dev. In `internal/api/...` there are
two failures, and neither is from this change.
`TestServerInfoEndpointReportsDevelopment` fails because the synced tree
has no `.git`. `TestContainerBootstrapFailuresStopAndClean/hangup`
failed under load and passed 3 of 3 runs alone.
## Interplay with #2725 and #2739
Those landed while this was open. Unlink now deletes the pair's link, so
it reaches the mock view through `ManualLinks` at the adapter's next
rebuild, the same timing as live. The broadcast's presentation
coalescing now takes exclusions from the resource store adapter for
store-less views, and the mock view is one of those. The merge commit
updates the unified-resources notes for both changes.
Resolve agent-lifecycle.md by keeping both sides (additive notes), and
bring the unified-resources notes in line with #2725 and #2739: unlink now
reaches the mock view through ManualLinks, and broadcast presentation
coalescing honours exclusions for store-less views.
Additively incorporate the exact main repair that landed during this publication turn. Preserve every starting reviewed commit and the deferred browser qualification boundary.
Change-source: pulse-maintainer
The resources API rebuilds its registry from the monitor's unified
seed, but built it with NewRegistry and plain ingests, so its stale
pass used the registry defaults while the monitor judges each source
by its configured polling cadence. A Proxmox node polled every two
minutes read stale, with warning status, in /api/resources ninety
seconds after its poll while the websocket called it online.
Presentation coalescing had the same gap in both views. When it merges
an agent row the registry kept apart into its Proxmox node by hostname,
it picked each reading's source by the default thresholds, so the row
showed a silent agent's readings over a poll the registry calls
current.
The seed now carries the thresholds its registry generation was judged
by. The monitor adapter records them per generation: thresholds set
since the last rebuild wait for the rebuild that applies them, and the
read-state overlays and live supplemental refreshes of a generation are
judged by its thresholds, since re-judging a listing cannot clear a
stale verdict it already carries. The monitor lists a generation with
its thresholds from one registry pointer, and a view built from mock
fixtures or a bare snapshot reports none (the defaults it was judged
by). The monitor hands seed, freshness and thresholds over from one
view, per tenant too. The resources API builds
its registry with them (NewRegistryWithStaleThresholds: ingests and
stale passes that pass none use them) and keys its cache on its own
copy. The coalesce judges metric freshness with metricSourceStale, the
rule the stale pass and the merge already share, and both the
broadcast and ListForPresentation pass their view's thresholds. The
broadcast coalesce also honours the operator's merge exclusions, so the
adapter's CoalesceForPresentation takes the listing's thresholds next
to them.
Patrol's scoped runtime state still rebuilds registries with the
defaults.
Preserve the exact upstream commits already present at coordination start; later upstream reconciliation remains with the publication gate.
Change-source: pulse-maintainer
After a restart, an agent an operator linked into a live resource, such
as an agent inside a vSphere VM, exists only through saved-host
continuity until it reports again. Three consumers then disagreed about
what a reference to it meant. The read state kept the saved agent as its
own offline row and resolved references to it there. The resources API,
which seeds a registry from that listing and re-applies the links,
folded it into the VM and merged its stale telemetry. Alert intent
resolved through the published registry, where the agent is absent, so
its agent:<host ID> alerts kept their literal reference. Maintenance or
NeverAutoRemediate set on the VM reached neither the agent's alerts nor
its Patrol findings in that window, while the API said it applied.
An operator link names one identity; telemetry separation is the only
reason the saved row stays apart. Link application now holds a saved
row beside the link's primary instead of merging it, in every registry.
A reference that resolves to the saved row (its canonical ID,
agent:<host ID>, its machine ID or an alias it shares with the primary)
resolves to the primary, as a folded row's references do, while each
row keeps its own telemetry. An in-memory marker on rows continuity
introduced rides clones, so the resources API's registry holds them the
same way. A saved primary leaves a live member its own identity.
Alert intent now resolves references and ancestors through the published
registry with saved hosts overlaid, the read state Patrol resolves
through. That also lets intent set on an unlinked saved host reach its
offline alert. The resolver runs under the alert manager's lock once
per metric check, so the overlay is kept per published registry
generation, publication builds it before alerts are evaluated, and a
build that overlaps a mock-mode switch is discarded.
Compose upstream b7bdf1b4eb available at batch start without re-parenting published or reviewed commits. Resolve concurrent append-only contract and regression-test additions by retaining both the existing partial-inventory controls and published presentation-split controls. No frontend source changes.
Change-source: pulse-maintainer
In mock mode the websocket broadcast and /api/state serve a view of the
fixture graph, and the fixture graph was built in a registry with no
store, so it never loaded the operator's manual links. The resources API
seeds its own store-backed registry from that list and applied them, so
a standalone agent linked into a VM showed merged in /api/resources and
stayed a separate row in the broadcast, even after a restart. Peers
verifying link UI on mock stacks had to block the websocket to see it.
The mock view now builds the fixture graph with the links the monitor
adapter's current registry generation loaded (MonitorAdapter.ManualLinks),
through NewRegistryWithManualLinks: a registry with those links and no
store, so fixture ingest cannot persist identity pins, successions or
change rows. The links apply at each ingest stage, as in the live
rebuild, so an availability check that names the folded resource by
source still projects onto the primary. Without links the shared
memoized snapshot is used as before.
The cached view is keyed on the fixture version and the link list, so a
link change rebuilds it without a fixture tick. Its freshness, which the
resources API keys its registry cache on, is assigned in publication
order: a view with the published fixture freshness and links keeps the
published value, and any other view gets a later one than every view
before it.
The fence view behind currentModeReadState still omits links; it only
covers the window after leaving mock mode, before the registry rebuilds.
POST /api/resources/{id}/unlink recorded only an exclusion. The link row
stayed, and applyManualLinks never consults exclusions, so the monitor's
rebuilds, the resources API and the websocket kept the pair folded while
the API answered "Resources unlinked".
A pair now carries one operator decision. AddExclusion deletes the pair's
links and AddLink its exclusions, in one transaction and in either ID
order. Reads keep each pair's latest decision, so rows written before
this change, or rewritten onto one pair by canonical-ID succession,
resolve by their later write, and a registry resolves its two reads
together so an unlink landing between them cannot load both.
While a Proxmox node was linked to an agent, the merged resource's
identity pin could take the agent's machine key. After unlink the node
completed that key, minted the agent's ID and folded into it by ID, where
no exclusion check runs. A pin no longer completes a record the operator
split from the pinned resource.
The broadcast coalesced host views without exclusions while REST's
ListForPresentation honoured them, so a split host pair was one websocket
row and two REST rows. The broadcast now coalesces through the read state
that listed the rows, with the same exclusion filter.
Additively incorporate exact upstream 36d3f8c557 while retaining all accepted local commits and proposal 31eccb559e. Resolve the single adjacent insertion conflict by retaining both reviewed observation-gap interruption and upstream metric tag cleanup. Preserve upstream shared guest and disk-type threshold judgement, phone drawer sizing, future Patrol timing and POST-only Assistant mutations. Exact final validation and outstanding browser/security dispositions remain required before advancing publication.
Change-source: pulse-maintainer
Use a dedicated shared mutex for every monitor random-source access, including lazy poll-backoff initialisation. Preserve the existing seeded jitter, intervals and nil-source metadata policy. Cover deterministic source ownership, mixed concurrent access and independent real HTTP guest enrichment.
Contract-Neutral: Correct internal random-source ownership without changing public interfaces, refresh or backoff durations, distributions, guest commands, lock checks or uncertainty fences.
Change-source: pulse-maintainer
Honour cold-cache retry backoff and retain a per-key in-flight reservation until enrichment returns, rather than treating a timed hold as completion. Avoid duplicate command sequences and stale safety-state writers while preserving existing lock, uncertainty, observation and refresh policies. Cover blocked real HTTP reads, early deferral, slot cancellation and ordinary recovery.
Contract-Neutral: Restore the existing per-key metadata reservation and retry scheduling semantics; no public API, configuration, guest command, lock, uncertainty fence, observation or numeric duration changes.
Change-source: pulse-maintainer
A Proxmox disk that only the node's sensors report never raised a
temperature alert: CheckDiskHealth judges health and wearout only, and
unified evaluation covers TrueNAS disks, not PVE ones. Physical Disks
could read the disk Running Hot under the per-type thresholds while
alerts stayed silent, and whether a disk alerted depended on whether a
Pulse agent happened to run on the node.
The PVE disk poller now hands each disk's current reading to
CheckProxmoxDiskTemperature, which judges it by the same disk
temperature policy as agent and TrueNAS disks (DiskTempByType under the
agent Disk Temp default) under the disk's existing PVE alert reference.
A disk a still-reporting linked agent lists in its SMART report is the
agent's: CheckHost alerts on it and the PVE alert closes as moved to the
agent, so no disk alerts twice. A retained reading holds the alert,
an excluded device or a switched-off policy closes it, warnings wait the
same 300s stability window as other disk temperatures, a config save
re-judges the alert per disk type, and resource history owns its rows by
the disk's recorded identity like the health and wearout alerts.
Keep the published process-wide tenant switch while using the retained removal lifecycle for both agent and Docker fixture hosts in every ended epoch. Preserve both lifecycle regression tests; no candidate source is re-parented.
Change-source: pulse-maintainer
Follow-up to #2656 (the per-monitor mock-mode epoch fence), which
documented this gap as not covered.
## Problem
Mock mode is one process-wide flag (`mock.SetEnabled`), but
`Monitor.SetMockMode` ended the fence epoch, cleared the alerts, forgot
the fixture agents and reset the state of only the monitor it was called
on. The server runs one `Monitor` per organization
(`MultiTenantMonitor.GetMonitor` → `New` + `Start`), and each runs its
own mock alert pass into its own alert manager. A switch made through
one monitor (the mock-mode API uses the requesting tenant's monitor; the
demo-fixture licence sync uses the default one) left every other running
monitor holding what it raised in the mode the process had left: fixture
alerts and fixture-agent node links in live mode, live alerts in mock
mode, until the 24-hour stale sweep.
## Fix
- `internal/monitoring/mock_mode_switch.go`: a process-wide set of
running monitors, guarded by the existing `mockModeSwitchMu`. `Start`
joins it and leaves when its loop returns. While joining it picks the
mock metrics sampler or discovery under the lock (now
`startModeRuntime`), so no switch lands between reading the mode and
starting the runtime for it.
- `SetMockMode` flips the flag once, then for the receiver and every
running monitor: ends the epoch, waits for admitted calls, clears
alerts, forgets fixture agents (when leaving mock mode) and resets state
(`endMockModeEpoch`). Only after that does it restart the sampler, polls
and discovery of each monitor in the set (`resumeAfterMockModeSwitch`).
A monitor that has not joined yet gets its runtime from its own `Start`.
- Each monitor records the mode its alerts and state belong to
(`mockModeAligned`, set in `New` from the same read that decides whether
persisted alerts are restored) and the number of switches made so far
(`mockModeSwitchesSeen`). If it missed switches between `New` and
`Start`, it leaves what it holds before joining, even after a round trip
that brought the flag back. A call for the mode the flag already holds
still moves any reached monitor that belongs to the other mode, and
leaves the rest alone.
Callers are unchanged and no API surface moves.
## Is this reachable in release builds?
Barely. In a `release` build `mockruntime.ValidateEnablement` refuses
mock fixtures unless `SetReleaseFixturesAuthorized(true)` was called.
Its only caller is `syncReleaseDemoFixtureRuntime`, which requires
`DemoMode` plus the `demo_fixtures` entitlement and runs only for the
default organization. Several tenant monitors in mock mode would also
need more than one organization's monitor running on that demo instance.
Demo mode's read-only middleware normally blocks creating organizations
and the mock-mode API's POST. It does forward any request carrying
`Upgrade: websocket` whatever its method; that bypass predates this
change and is being fixed separately. So in practice this is a
dev/mock-stack problem, and the fix stays inside the monitoring package.
## Tests
New tests in `internal/monitoring/monitor_mock_alerts_test.go`:
- `TestLeavingMockModeClearsEveryRunningTenantMonitor` and
`TestEnteringMockModeClearsEveryRunningTenantMonitor` start the default
and one other tenant monitor through `MultiTenantMonitor`, as the server
does, and wait until both have joined. They raise alerts in both, switch
through one, and check both.
- `TestMonitorStartedAfterAMockModeSwitchLeavesTheModeItWasBuiltIn`
covers a switch that lands between `New` and `Start`.
- `TestMonitorStartedAfterAMockModeRoundTripDropsWhatItRaisedMeanwhile`
covers two switches in that window, with fixture alerts raised in
between.
- `TestSetMockModeAlignsAMonitorWhoseModeTheFlagAlreadyHolds` covers a
call for the mode the flag already holds.
- `TestMockModeSwitchLeavesAnUnjoinedMonitorsRuntimeToItsStart` covers a
switch reaching a monitor that has not joined.
One more is in
`internal/monitoring/monitor_host_agent_removal_lifecycle_test.go`:
`TestLeavingMockModeReleasesFixtureAgentNodeLinksOnEveryRunningMonitor`.
It switches through the default monitor and checks that the other
tenant's fixture node is no longer suppressed by a fixture agent's
leftover node link.
Negative controls (`go test -overlay`):
| Control | Failing tests | What happened |
|---|---|---|
| Fence-PR runtime | Leaving, entering, node-link | Default monitor kept
69–104 fixture alerts (varies by run) and 69 fixture agents; org-b kept
its live alert; org-b's `mock-cluster-1-pve1` stayed suppressed |
| Set kept, switch reaches only the receiver | Same three | Same
failures |
| No realign at join |
`TestMonitorStartedAfterAMockModeSwitchLeavesTheModeItWasBuiltIn` | |
| Join compares only the mode, not the switch count |
`TestMonitorStartedAfterAMockModeRoundTripDropsWhatItRaisedMeanwhile` |
Started in live mode with the fixture node's memory alert |
| Plain early return when the flag already matches |
`TestSetMockModeAlignsAMonitorWhoseModeTheFlagAlreadyHolds` | |
| Resume ignores set membership |
`TestMockModeSwitchLeavesAnUnjoinedMonitorsRuntimeToItsStart` | |
Every control failed only the tests it targets.
Also run: the full `internal/monitoring` package; `-race -count=3` on
the new tests plus the existing `TestLeavingMockMode*` and
`TestMockModeFence*`; and the mock-mode tests in `internal/api` and
`internal/api/configapi`.