Files
cc-backend/e5/83b7b11439/0/full.jsonl
Jan Eitzinger b2679990c3 Checkpoint: e583b7b11439
Entire-Session: 734f1e28-b805-471f-8f2c-275878888543
Entire-Strategy: manual-commit
Entire-Agent: Claude Code
Ephemeral-branch: entire/50aed59-e3b0c4
2026-03-18 06:32:14 +01:00

68 lines
432 KiB
JSON
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{"type":"file-history-snapshot","messageId":"e61b6d31-15d1-4b25-a4d5-dc4c0ddd1260","snapshot":{"messageId":"e61b6d31-15d1-4b25-a4d5-dc4c0ddd1260","trackedFileBackups":{},"timestamp":"2026-03-18T05:29:19.393Z"},"isSnapshotUpdate":false}
{"parentUuid":null,"isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"SessionStart","hookName":"SessionStart:clear","command":"entire hooks claude-code session-start"},"parentToolUseID":"ac077ae6-a17a-4376-bf05-384c328b0b0f","toolUseID":"ac077ae6-a17a-4376-bf05-384c328b0b0f","timestamp":"2026-03-18T05:29:19.341Z","uuid":"6e47e120-4d61-402d-a1b3-1f979008a883","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"6e47e120-4d61-402d-a1b3-1f979008a883","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":"Implement the following plan:\n\n# Fix WAL Channel Saturation (3M+ messages dropped)\n\n## Context\n\nAfter the initial slow-consumer fixes (multi-worker decode, non-blocking WAL send, 65K channel buffer, 256-batch drain), the WAL channel is still permanently full. 3M+ messages are being dropped — the single `WALStaging` goroutine fundamentally cannot keep up with `NumWorkers` concurrent decode goroutines producing WAL messages.\n\n## Root Cause\n\nThe single `WALStaging` goroutine is the bottleneck. For every message it must:\n1. `path.Join()` to build hostDir string — **allocates**\n2. Map lookup in `hostFiles`\n3. `buildWALPayload()` — **allocates a new `[]byte`** per message\n4. `writeWALRecord()` — **allocates another `[]byte`** (record = magic+len+payload+crc)\n5. `bufio.Write()` — copies into buffer, occasionally flushes to disk\n\nWith `NumWorkers` producers (e.g., 5-10 goroutines) each decoding batches of metrics, the single consumer cannot match. The 65K channel buffer fills in seconds, then every message is dropped.\n\n## Plan: Sharded WAL Writers\n\nReplace the single `WALStaging` goroutine with **N sharded writer goroutines**, each owning a subset of hosts. Messages are routed to shards by hashing `cluster+node`. This:\n- Parallelizes serialization and I/O across goroutines\n- Keeps per-host writes serial (required for correct WAL files)\n- Eliminates the single-goroutine bottleneck entirely\n\nAdditionally, eliminate per-message heap allocations in `buildWALPayload`/`writeWALRecord` by encoding directly into the `bufio.Writer`.\n\n### Change 1: Sharded WAL writer goroutines\n**File:** `pkg/metricstore/walCheckpoint.go`\n\nReplace the single `WALMessages` channel + `WALStaging()` goroutine with:\n\n```go\nconst walShards = 16 // or NumWorkers\n\n// Per-shard channel + goroutine\nvar walShardChs []chan *WALMessage\n\nfunc walShard(msg *WALMessage) int {\n // FNV-1a hash of cluster+node, mod shard count\n h := fnv.New32a()\n h.Write([]byte(msg.Cluster))\n h.Write([]byte{0})\n h.Write([]byte(msg.Node))\n return int(h.Sum32()) % len(walShardChs)\n}\n```\n\nEach shard goroutine:\n- Owns its own `hostFiles` map (no contention)\n- Drains its channel with the existing batch-drain pattern\n- Handles rotate requests for its hosts\n\n**Shard count:** Use `NumWorkers` (already configured, sensible default).\n\n**Channel buffer per shard:** `65536 / numShards` — same total memory, but each shard only buffers its hosts.\n\n### Change 2: Eliminate per-message allocations\n**File:** `pkg/metricstore/walCheckpoint.go`\n\nReplace `buildWALPayload()` → `writeWALRecord()` (2 allocations per message) with `writeWALRecordDirect(w *bufio.Writer, msg *WALMessage)` that encodes directly into the `bufio.Writer` using a small stack-allocated scratch buffer:\n\n```go\nfunc writeWALRecordDirect(w *bufio.Writer, msg *WALMessage) error {\n // Build payload into a pooled or stack buffer, compute CRC inline,\n // write magic+len, then payload, then CRC — all directly to w.\n // Zero heap allocations in the hot path.\n var scratch [128]byte // stack-allocated, covers most records\n // ... encode payload into scratch or a pooled []byte if >128 ...\n}\n```\n\nKeep the old `writeWALRecord`/`buildWALPayload` for use in tests or non-hot paths, but the shard goroutines use the direct version.\n\n### Change 3: Route WAL sends to shards from DecodeLine\n**File:** `pkg/metricstore/lineprotocol.go:355-372`\n\nReplace:\n```go\nselect {\ncase WALMessages <- msg:\ndefault:\n // dropped\n}\n```\nWith:\n```go\nshard := walShard(msg)\nselect {\ncase walShardChs[shard] <- msg:\ndefault:\n // dropped\n}\n```\n\n### Change 4: Shard-aware rotation\n**File:** `pkg/metricstore/walCheckpoint.go`\n\n`RotateWALFiles` must send rotate requests to the correct shard. Each shard has its own `walRotateCh`. The checkpoint goroutine hashes the hostDir to find the right shard and sends the rotate request there.\n\n### Change 5: Shutdown\n**File:** `pkg/metricstore/metricstore.go` (Shutdown function)\n\nClose all shard channels instead of the single `WALMessages` channel. Each shard goroutine drains and flushes on close.\n\n## Files to Modify\n\n- `pkg/metricstore/walCheckpoint.go` — sharded goroutines, direct record writing, shard-aware rotation\n- `pkg/metricstore/lineprotocol.go` — route WAL sends to shard channels\n- `pkg/metricstore/metricstore.go` — `WALStaging()` call updated, `Shutdown()` closes shard channels\n\n## Verification\n\n1. `go build ./...`\n2. `go test ./pkg/metricstore/...`\n3. Deploy and verify:\n - WAL drop count stays at 0 (or near-zero during extreme bursts)\n - WAL files are correct (load a checkpoint, verify data)\n - No \"WAL channel full\" log messages\n - Memory usage roughly same (total channel buffer size unchanged)\n\n\nIf you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/jan/.claude/projects/-Users-jan-prg-ClusterCockpit-cc-backend/5eb20a94-f8df-4979-a0ae-2aa99bfad884.jsonl"},"uuid":"e61b6d31-15d1-4b25-a4d5-dc4c0ddd1260","timestamp":"2026-03-18T05:29:19.088Z","planContent":"# Fix WAL Channel Saturation (3M+ messages dropped)\n\n## Context\n\nAfter the initial slow-consumer fixes (multi-worker decode, non-blocking WAL send, 65K channel buffer, 256-batch drain), the WAL channel is still permanently full. 3M+ messages are being dropped — the single `WALStaging` goroutine fundamentally cannot keep up with `NumWorkers` concurrent decode goroutines producing WAL messages.\n\n## Root Cause\n\nThe single `WALStaging` goroutine is the bottleneck. For every message it must:\n1. `path.Join()` to build hostDir string — **allocates**\n2. Map lookup in `hostFiles`\n3. `buildWALPayload()` — **allocates a new `[]byte`** per message\n4. `writeWALRecord()` — **allocates another `[]byte`** (record = magic+len+payload+crc)\n5. `bufio.Write()` — copies into buffer, occasionally flushes to disk\n\nWith `NumWorkers` producers (e.g., 5-10 goroutines) each decoding batches of metrics, the single consumer cannot match. The 65K channel buffer fills in seconds, then every message is dropped.\n\n## Plan: Sharded WAL Writers\n\nReplace the single `WALStaging` goroutine with **N sharded writer goroutines**, each owning a subset of hosts. Messages are routed to shards by hashing `cluster+node`. This:\n- Parallelizes serialization and I/O across goroutines\n- Keeps per-host writes serial (required for correct WAL files)\n- Eliminates the single-goroutine bottleneck entirely\n\nAdditionally, eliminate per-message heap allocations in `buildWALPayload`/`writeWALRecord` by encoding directly into the `bufio.Writer`.\n\n### Change 1: Sharded WAL writer goroutines\n**File:** `pkg/metricstore/walCheckpoint.go`\n\nReplace the single `WALMessages` channel + `WALStaging()` goroutine with:\n\n```go\nconst walShards = 16 // or NumWorkers\n\n// Per-shard channel + goroutine\nvar walShardChs []chan *WALMessage\n\nfunc walShard(msg *WALMessage) int {\n // FNV-1a hash of cluster+node, mod shard count\n h := fnv.New32a()\n h.Write([]byte(msg.Cluster))\n h.Write([]byte{0})\n h.Write([]byte(msg.Node))\n return int(h.Sum32()) % len(walShardChs)\n}\n```\n\nEach shard goroutine:\n- Owns its own `hostFiles` map (no contention)\n- Drains its channel with the existing batch-drain pattern\n- Handles rotate requests for its hosts\n\n**Shard count:** Use `NumWorkers` (already configured, sensible default).\n\n**Channel buffer per shard:** `65536 / numShards` — same total memory, but each shard only buffers its hosts.\n\n### Change 2: Eliminate per-message allocations\n**File:** `pkg/metricstore/walCheckpoint.go`\n\nReplace `buildWALPayload()` → `writeWALRecord()` (2 allocations per message) with `writeWALRecordDirect(w *bufio.Writer, msg *WALMessage)` that encodes directly into the `bufio.Writer` using a small stack-allocated scratch buffer:\n\n```go\nfunc writeWALRecordDirect(w *bufio.Writer, msg *WALMessage) error {\n // Build payload into a pooled or stack buffer, compute CRC inline,\n // write magic+len, then payload, then CRC — all directly to w.\n // Zero heap allocations in the hot path.\n var scratch [128]byte // stack-allocated, covers most records\n // ... encode payload into scratch or a pooled []byte if >128 ...\n}\n```\n\nKeep the old `writeWALRecord`/`buildWALPayload` for use in tests or non-hot paths, but the shard goroutines use the direct version.\n\n### Change 3: Route WAL sends to shards from DecodeLine\n**File:** `pkg/metricstore/lineprotocol.go:355-372`\n\nReplace:\n```go\nselect {\ncase WALMessages <- msg:\ndefault:\n // dropped\n}\n```\nWith:\n```go\nshard := walShard(msg)\nselect {\ncase walShardChs[shard] <- msg:\ndefault:\n // dropped\n}\n```\n\n### Change 4: Shard-aware rotation\n**File:** `pkg/metricstore/walCheckpoint.go`\n\n`RotateWALFiles` must send rotate requests to the correct shard. Each shard has its own `walRotateCh`. The checkpoint goroutine hashes the hostDir to find the right shard and sends the rotate request there.\n\n### Change 5: Shutdown\n**File:** `pkg/metricstore/metricstore.go` (Shutdown function)\n\nClose all shard channels instead of the single `WALMessages` channel. Each shard goroutine drains and flushes on close.\n\n## Files to Modify\n\n- `pkg/metricstore/walCheckpoint.go` — sharded goroutines, direct record writing, shard-aware rotation\n- `pkg/metricstore/lineprotocol.go` — route WAL sends to shard channels\n- `pkg/metricstore/metricstore.go` — `WALStaging()` call updated, `Shutdown()` closes shard channels\n\n## Verification\n\n1. `go build ./...`\n2. `go test ./pkg/metricstore/...`\n3. Deploy and verify:\n - WAL drop count stays at 0 (or near-zero during extreme bursts)\n - WAL files are correct (load a checkpoint, verify data)\n - No \"WAL channel full\" log messages\n - Memory usage roughly same (total channel buffer size unchanged)\n","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"type":"custom-title","customTitle":"fix-wal-channel-saturation","sessionId":"734f1e28-b805-471f-8f2c-275878888543"}
{"type":"agent-name","agentName":"fix-wal-channel-saturation","sessionId":"734f1e28-b805-471f-8f2c-275878888543"}
{"parentUuid":"e61b6d31-15d1-4b25-a4d5-dc4c0ddd1260","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01XZzrun9oNQmo8YoM39V67m","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"","signature":"Eo0CCkYICxgCKkBB3JUR8RceDifEVpJ5saswU7iqN3o44znUuwQeESuGGQJqUZbgvxUHfbWvV1okZLejuWtAQBvdQRpgZVOCE1gxEgxxDXDgV8DLZP22JMYaDIVAnq9h6ZsvI+YEnSIw4GSm+WVIogkatfgJG3s39+oKIaa3FAEgDsc+4FmNdM8JQ6FseAMtg4TH34xt6IRpKnWu5ubLr827ytXZbv0/WaXVMjXML5W+gMKiZhnP6t6hWqpxZaIDQHaN13HMD0TzxLmfkK5Toyj53olElFxuIZzV5kCzrOExPVzrfVYMotccSPJIhW659WzySyBnM29XB8/J538cqlyBUG3G+peIIn8modlyTwsYAQ=="}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":11338,"cache_read_input_tokens":8666,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":11338},"output_tokens":10,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zeJVxWMXaD6uiZvMX5","type":"assistant","uuid":"06383803-4aca-45cf-844b-b6ced600f3fe","timestamp":"2026-03-18T05:29:22.671Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"06383803-4aca-45cf-844b-b6ced600f3fe","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01XZzrun9oNQmo8YoM39V67m","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01Bpiwhgdg2b1q67cr6FPH4S","name":"Read","input":{"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":11338,"cache_read_input_tokens":8666,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":11338},"output_tokens":10,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zeJVxWMXaD6uiZvMX5","type":"assistant","uuid":"53cacb9b-842f-4b11-adeb-ae3f42fafd4a","timestamp":"2026-03-18T05:29:23.129Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"53cacb9b-842f-4b11-adeb-ae3f42fafd4a","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Read","command":"callback"},"parentToolUseID":"toolu_01Bpiwhgdg2b1q67cr6FPH4S","toolUseID":"toolu_01Bpiwhgdg2b1q67cr6FPH4S","timestamp":"2026-03-18T05:29:23.141Z","uuid":"3a4a0a08-252f-4c86-b3f8-0c82c3692aed","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"53cacb9b-842f-4b11-adeb-ae3f42fafd4a","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01Bpiwhgdg2b1q67cr6FPH4S","type":"tool_result","content":" 1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n 2→// All rights reserved. This file is part of cc-backend.\n 3→// Use of this source code is governed by a MIT-style\n 4→// license that can be found in the LICENSE file.\n 5→\n 6→// Package metricstore provides walCheckpoint.go: WAL-based checkpoint implementation.\n 7→//\n 8→// This replaces the Avro shadow tree with an append-only Write-Ahead Log (WAL)\n 9→// per host, eliminating the extra memory overhead of the AvroStore and providing\n 10→// truly continuous (per-write) crash safety.\n 11→//\n 12→// # Architecture\n 13→//\n 14→//\tMetric write (DecodeLine)\n 15→//\t │\n 16→//\t ├─► WriteToLevel() → main MemoryStore (unchanged)\n 17→//\t │\n 18→//\t └─► WALMessages channel\n 19→//\t │\n 20→//\t ▼\n 21→//\t WALStaging goroutine\n 22→//\t │\n 23→//\t ▼\n 24→//\t checkpoints/cluster/host/current.wal (append-only, binary)\n 25→//\n 26→//\tPeriodic checkpoint (Checkpointing goroutine):\n 27→//\t 1. Write <timestamp>.bin snapshot (column-oriented, from main tree)\n 28→//\t 2. Signal WALStaging to truncate current.wal per host\n 29→//\n 30→//\tOn restart (FromCheckpoint):\n 31→//\t 1. Load most recent <timestamp>.bin snapshot\n 32→//\t 2. Replay current.wal (overwrite-safe: buffer.write handles duplicate timestamps)\n 33→//\n 34→// # WAL Record Format\n 35→//\n 36→//\t[4B magic 0xCC1DA7A1][4B payload_len][payload][4B CRC32]\n 37→//\n 38→//\tpayload:\n 39→//\t [8B timestamp int64]\n 40→//\t [2B metric_name_len uint16][N metric name bytes]\n 41→//\t [1B selector_count uint8]\n 42→//\t per selector: [1B selector_len uint8][M selector bytes]\n 43→//\t [4B value float32 bits]\n 44→//\n 45→// # Binary Snapshot Format\n 46→//\n 47→//\t[4B magic 0xCC5B0001][8B from int64][8B to int64]\n 48→//\tLevel tree (recursive):\n 49→//\t [4B num_metrics uint32]\n 50→//\t per metric:\n 51→//\t [2B name_len uint16][N name bytes]\n 52→//\t [8B frequency int64][8B start int64]\n 53→//\t [4B num_values uint32][num_values × 4B float32]\n 54→//\t [4B num_children uint32]\n 55→//\t per child: [2B name_len uint16][N name bytes] + Level (recursive)\n 56→package metricstore\n 57→\n 58→import (\n 59→\t\"bufio\"\n 60→\t\"context\"\n 61→\t\"encoding/binary\"\n 62→\t\"fmt\"\n 63→\t\"hash/crc32\"\n 64→\t\"io\"\n 65→\t\"math\"\n 66→\t\"os\"\n 67→\t\"path\"\n 68→\t\"strings\"\n 69→\t\"sync\"\n 70→\t\"sync/atomic\"\n 71→\n 72→\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n 73→\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n 74→)\n 75→\n 76→// Magic numbers for binary formats.\n 77→const (\n 78→\twalFileMagic = uint32(0xCC1DA701) // WAL file header magic\n 79→\twalRecordMagic = uint32(0xCC1DA7A1) // WAL record magic\n 80→\tsnapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic\n 81→)\n 82→\n 83→// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\n 84→// Buffered to allow burst writes without blocking the metric ingestion path.\n 85→var WALMessages = make(chan *WALMessage, 65536)\n 86→\n 87→// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\n 88→// (close, delete, reopen) after a binary snapshot has been written.\n 89→var walRotateCh = make(chan walRotateReq, 256)\n 90→\n 91→// WALMessage represents a single metric write to be appended to the WAL.\n 92→// Cluster and Node are NOT stored in the WAL record (inferred from file path).\n 93→type WALMessage struct {\n 94→\tMetricName string\n 95→\tCluster string\n 96→\tNode string\n 97→\tSelector []string\n 98→\tValue schema.Float\n 99→\tTimestamp int64\n 100→}\n 101→\n 102→// walRotateReq requests WAL file rotation for a specific host directory.\n 103→// The done channel is closed by the WAL goroutine when rotation is complete.\n 104→type walRotateReq struct {\n 105→\thostDir string\n 106→\tdone chan struct{}\n 107→}\n 108→\n 109→// walFileState holds an open WAL file handle and buffered writer for one host directory.\n 110→type walFileState struct {\n 111→\tf *os.File\n 112→\tw *bufio.Writer\n 113→}\n 114→\n 115→// WALStaging starts a background goroutine that receives WALMessage items\n 116→// and appends binary WAL records to per-host current.wal files.\n 117→// Also handles WAL rotation requests from the checkpoint goroutine.\n 118→func WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n 119→\twg.Go(func() {\n 120→\t\tif Keys.Checkpoints.FileFormat == \"json\" {\n 121→\t\t\treturn\n 122→\t\t}\n 123→\n 124→\t\thostFiles := make(map[string]*walFileState)\n 125→\n 126→\t\tdefer func() {\n 127→\t\t\tfor _, ws := range hostFiles {\n 128→\t\t\t\tif ws.f != nil {\n 129→\t\t\t\t\tws.w.Flush()\n 130→\t\t\t\t\tws.f.Close()\n 131→\t\t\t\t}\n 132→\t\t\t}\n 133→\t\t}()\n 134→\n 135→\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n 136→\t\t\tws, ok := hostFiles[hostDir]\n 137→\t\t\tif ok {\n 138→\t\t\t\treturn ws\n 139→\t\t\t}\n 140→\n 141→\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n 142→\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n 143→\t\t\t\treturn nil\n 144→\t\t\t}\n 145→\n 146→\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n 147→\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n 148→\t\t\tif err != nil {\n 149→\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n 150→\t\t\t\treturn nil\n 151→\t\t\t}\n 152→\n 153→\t\t\tw := bufio.NewWriter(f)\n 154→\n 155→\t\t\t// Write file header magic if file is new (empty).\n 156→\t\t\tinfo, err := f.Stat()\n 157→\t\t\tif err == nil && info.Size() == 0 {\n 158→\t\t\t\tvar hdr [4]byte\n 159→\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n 160→\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n 161→\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n 162→\t\t\t\t\tf.Close()\n 163→\t\t\t\t\treturn nil\n 164→\t\t\t\t}\n 165→\t\t\t}\n 166→\n 167→\t\t\tws = &walFileState{f: f, w: w}\n 168→\t\t\thostFiles[hostDir] = ws\n 169→\t\t\treturn ws\n 170→\t\t}\n 171→\n 172→\t\tprocessMsg := func(msg *WALMessage) {\n 173→\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n 174→\t\t\tws := getOrOpenWAL(hostDir)\n 175→\t\t\tif ws == nil {\n 176→\t\t\t\treturn\n 177→\t\t\t}\n 178→\t\t\tif err := writeWALRecord(ws.w, msg); err != nil {\n 179→\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n 180→\t\t\t}\n 181→\t\t}\n 182→\n 183→\t\tprocessRotate := func(req walRotateReq) {\n 184→\t\t\tws, ok := hostFiles[req.hostDir]\n 185→\t\t\tif ok && ws.f != nil {\n 186→\t\t\t\tws.w.Flush()\n 187→\t\t\t\tws.f.Close()\n 188→\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n 189→\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n 190→\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n 191→\t\t\t\t}\n 192→\t\t\t\tdelete(hostFiles, req.hostDir)\n 193→\t\t\t}\n 194→\t\t\tclose(req.done)\n 195→\t\t}\n 196→\n 197→\t\tdrain := func() {\n 198→\t\t\tfor {\n 199→\t\t\t\tselect {\n 200→\t\t\t\tcase msg, ok := <-WALMessages:\n 201→\t\t\t\t\tif !ok {\n 202→\t\t\t\t\t\treturn\n 203→\t\t\t\t\t}\n 204→\t\t\t\t\tprocessMsg(msg)\n 205→\t\t\t\tcase req := <-walRotateCh:\n 206→\t\t\t\t\tprocessRotate(req)\n 207→\t\t\t\tdefault:\n 208→\t\t\t\t\t// Flush all buffered writers after draining remaining messages.\n 209→\t\t\t\t\tfor _, ws := range hostFiles {\n 210→\t\t\t\t\t\tif ws.f != nil {\n 211→\t\t\t\t\t\t\tws.w.Flush()\n 212→\t\t\t\t\t\t}\n 213→\t\t\t\t\t}\n 214→\t\t\t\t\treturn\n 215→\t\t\t\t}\n 216→\t\t\t}\n 217→\t\t}\n 218→\n 219→\t\tfor {\n 220→\t\t\tselect {\n 221→\t\t\tcase <-ctx.Done():\n 222→\t\t\t\tdrain()\n 223→\t\t\t\treturn\n 224→\t\t\tcase msg, ok := <-WALMessages:\n 225→\t\t\t\tif !ok {\n 226→\t\t\t\t\treturn\n 227→\t\t\t\t}\n 228→\t\t\t\tprocessMsg(msg)\n 229→\n 230→\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n 231→\t\t\t\tfor range 256 {\n 232→\t\t\t\t\tselect {\n 233→\t\t\t\t\tcase msg, ok := <-WALMessages:\n 234→\t\t\t\t\t\tif !ok {\n 235→\t\t\t\t\t\t\treturn\n 236→\t\t\t\t\t\t}\n 237→\t\t\t\t\t\tprocessMsg(msg)\n 238→\t\t\t\t\tcase req := <-walRotateCh:\n 239→\t\t\t\t\t\tprocessRotate(req)\n 240→\t\t\t\t\tdefault:\n 241→\t\t\t\t\t\tgoto flushed\n 242→\t\t\t\t\t}\n 243→\t\t\t\t}\n 244→\t\t\tflushed:\n 245→\t\t\t\t// Flush all buffered writers after processing the batch.\n 246→\t\t\t\tfor _, ws := range hostFiles {\n 247→\t\t\t\t\tif ws.f != nil {\n 248→\t\t\t\t\t\tws.w.Flush()\n 249→\t\t\t\t\t}\n 250→\t\t\t\t}\n 251→\t\t\tcase req := <-walRotateCh:\n 252→\t\t\t\tprocessRotate(req)\n 253→\t\t\t}\n 254→\t\t}\n 255→\t})\n 256→}\n 257→\n 258→// RotateWALFiles sends rotation requests for the given host directories\n 259→// and blocks until all rotations complete.\n 260→func RotateWALFiles(hostDirs []string) {\n 261→\tdones := make([]chan struct{}, len(hostDirs))\n 262→\tfor i, dir := range hostDirs {\n 263→\t\tdones[i] = make(chan struct{})\n 264→\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n 265→\t}\n 266→\tfor _, done := range dones {\n 267→\t\t<-done\n 268→\t}\n 269→}\n 270→\n 271→// RotateWALFiles sends rotation requests for the given host directories\n 272→// and blocks until all rotations complete.\n 273→func RotateWALFilesAfterShutdown(hostDirs []string) {\n 274→\tfor _, dir := range hostDirs {\n 275→\t\twalPath := path.Join(dir, \"current.wal\")\n 276→\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n 277→\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n 278→\t\t}\n 279→\t}\n 280→}\n 281→\n 282→// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\n 283→func buildWALPayload(msg *WALMessage) []byte {\n 284→\tsize := 8 + 2 + len(msg.MetricName) + 1 + 4\n 285→\tfor _, s := range msg.Selector {\n 286→\t\tsize += 1 + len(s)\n 287→\t}\n 288→\n 289→\tbuf := make([]byte, 0, size)\n 290→\n 291→\t// Timestamp (8 bytes, little-endian int64)\n 292→\tvar ts [8]byte\n 293→\tbinary.LittleEndian.PutUint64(ts[:], uint64(msg.Timestamp))\n 294→\tbuf = append(buf, ts[:]...)\n 295→\n 296→\t// Metric name (2-byte length prefix + bytes)\n 297→\tvar mLen [2]byte\n 298→\tbinary.LittleEndian.PutUint16(mLen[:], uint16(len(msg.MetricName)))\n 299→\tbuf = append(buf, mLen[:]...)\n 300→\tbuf = append(buf, msg.MetricName...)\n 301→\n 302→\t// Selector count (1 byte)\n 303→\tbuf = append(buf, byte(len(msg.Selector)))\n 304→\n 305→\t// Selectors (1-byte length prefix + bytes each)\n 306→\tfor _, sel := range msg.Selector {\n 307→\t\tbuf = append(buf, byte(len(sel)))\n 308→\t\tbuf = append(buf, sel...)\n 309→\t}\n 310→\n 311→\t// Value (4 bytes, float32 bit representation)\n 312→\tvar val [4]byte\n 313→\tbinary.LittleEndian.PutUint32(val[:], math.Float32bits(float32(msg.Value)))\n 314→\tbuf = append(buf, val[:]...)\n 315→\n 316→\treturn buf\n 317→}\n 318→\n 319→// writeWALRecord appends a binary WAL record to the writer.\n 320→// Format: [4B magic][4B payload_len][payload][4B CRC32]\n 321→func writeWALRecord(w io.Writer, msg *WALMessage) error {\n 322→\tpayload := buildWALPayload(msg)\n 323→\tcrc := crc32.ChecksumIEEE(payload)\n 324→\n 325→\trecord := make([]byte, 0, 4+4+len(payload)+4)\n 326→\n 327→\tvar magic [4]byte\n 328→\tbinary.LittleEndian.PutUint32(magic[:], walRecordMagic)\n 329→\trecord = append(record, magic[:]...)\n 330→\n 331→\tvar pLen [4]byte\n 332→\tbinary.LittleEndian.PutUint32(pLen[:], uint32(len(payload)))\n 333→\trecord = append(record, pLen[:]...)\n 334→\n 335→\trecord = append(record, payload...)\n 336→\n 337→\tvar crcBytes [4]byte\n 338→\tbinary.LittleEndian.PutUint32(crcBytes[:], crc)\n 339→\trecord = append(record, crcBytes[:]...)\n 340→\n 341→\t_, err := w.Write(record)\n 342→\treturn err\n 343→}\n 344→\n 345→// readWALRecord reads one WAL record from the reader.\n 346→// Returns (nil, nil) on clean EOF. Returns error on data corruption.\n 347→// A CRC mismatch indicates a truncated trailing record (expected on crash).\n 348→func readWALRecord(r io.Reader) (*WALMessage, error) {\n 349→\tvar magic uint32\n 350→\tif err := binary.Read(r, binary.LittleEndian, &magic); err != nil {\n 351→\t\tif err == io.EOF {\n 352→\t\t\treturn nil, nil // Clean EOF\n 353→\t\t}\n 354→\t\treturn nil, fmt.Errorf(\"read record magic: %w\", err)\n 355→\t}\n 356→\n 357→\tif magic != walRecordMagic {\n 358→\t\treturn nil, fmt.Errorf(\"invalid record magic 0x%08X (expected 0x%08X)\", magic, walRecordMagic)\n 359→\t}\n 360→\n 361→\tvar payloadLen uint32\n 362→\tif err := binary.Read(r, binary.LittleEndian, &payloadLen); err != nil {\n 363→\t\treturn nil, fmt.Errorf(\"read payload length: %w\", err)\n 364→\t}\n 365→\n 366→\tif payloadLen > 1<<20 { // 1 MB sanity limit\n 367→\t\treturn nil, fmt.Errorf(\"record payload too large: %d bytes\", payloadLen)\n 368→\t}\n 369→\n 370→\tpayload := make([]byte, payloadLen)\n 371→\tif _, err := io.ReadFull(r, payload); err != nil {\n 372→\t\treturn nil, fmt.Errorf(\"read payload: %w\", err)\n 373→\t}\n 374→\n 375→\tvar storedCRC uint32\n 376→\tif err := binary.Read(r, binary.LittleEndian, &storedCRC); err != nil {\n 377→\t\treturn nil, fmt.Errorf(\"read CRC: %w\", err)\n 378→\t}\n 379→\n 380→\tif crc32.ChecksumIEEE(payload) != storedCRC {\n 381→\t\treturn nil, fmt.Errorf(\"CRC mismatch (truncated write or corruption)\")\n 382→\t}\n 383→\n 384→\treturn parseWALPayload(payload)\n 385→}\n 386→\n 387→// parseWALPayload decodes a binary payload into a WALMessage.\n 388→func parseWALPayload(payload []byte) (*WALMessage, error) {\n 389→\tif len(payload) < 8+2+1+4 {\n 390→\t\treturn nil, fmt.Errorf(\"payload too short: %d bytes\", len(payload))\n 391→\t}\n 392→\n 393→\toffset := 0\n 394→\n 395→\t// Timestamp (8 bytes)\n 396→\tts := int64(binary.LittleEndian.Uint64(payload[offset : offset+8]))\n 397→\toffset += 8\n 398→\n 399→\t// Metric name (2-byte length + bytes)\n 400→\tif offset+2 > len(payload) {\n 401→\t\treturn nil, fmt.Errorf(\"metric name length overflows payload\")\n 402→\t}\n 403→\tmLen := int(binary.LittleEndian.Uint16(payload[offset : offset+2]))\n 404→\toffset += 2\n 405→\n 406→\tif offset+mLen > len(payload) {\n 407→\t\treturn nil, fmt.Errorf(\"metric name overflows payload\")\n 408→\t}\n 409→\tmetricName := string(payload[offset : offset+mLen])\n 410→\toffset += mLen\n 411→\n 412→\t// Selector count (1 byte)\n 413→\tif offset >= len(payload) {\n 414→\t\treturn nil, fmt.Errorf(\"selector count overflows payload\")\n 415→\t}\n 416→\tselCount := int(payload[offset])\n 417→\toffset++\n 418→\n 419→\tselectors := make([]string, selCount)\n 420→\tfor i := range selCount {\n 421→\t\tif offset >= len(payload) {\n 422→\t\t\treturn nil, fmt.Errorf(\"selector[%d] length overflows payload\", i)\n 423→\t\t}\n 424→\t\tsLen := int(payload[offset])\n 425→\t\toffset++\n 426→\n 427→\t\tif offset+sLen > len(payload) {\n 428→\t\t\treturn nil, fmt.Errorf(\"selector[%d] data overflows payload\", i)\n 429→\t\t}\n 430→\t\tselectors[i] = string(payload[offset : offset+sLen])\n 431→\t\toffset += sLen\n 432→\t}\n 433→\n 434→\t// Value (4 bytes, float32 bits)\n 435→\tif offset+4 > len(payload) {\n 436→\t\treturn nil, fmt.Errorf(\"value overflows payload\")\n 437→\t}\n 438→\tbits := binary.LittleEndian.Uint32(payload[offset : offset+4])\n 439→\tvalue := schema.Float(math.Float32frombits(bits))\n 440→\n 441→\treturn &WALMessage{\n 442→\t\tMetricName: metricName,\n 443→\t\tTimestamp: ts,\n 444→\t\tSelector: selectors,\n 445→\t\tValue: value,\n 446→\t}, nil\n 447→}\n 448→\n 449→// loadWALFile reads a WAL file and replays all valid records into the Level tree.\n 450→// l is the host-level node. Corrupt or partial trailing records are silently skipped\n 451→// (expected on crash). Records older than 'from' are skipped.\n 452→func (l *Level) loadWALFile(m *MemoryStore, f *os.File, from int64) error {\n 453→\tbr := bufio.NewReader(f)\n 454→\n 455→\t// Verify file header magic.\n 456→\tvar fileMagic uint32\n 457→\tif err := binary.Read(br, binary.LittleEndian, &fileMagic); err != nil {\n 458→\t\tif err == io.EOF {\n 459→\t\t\treturn nil // Empty file, no data\n 460→\t\t}\n 461→\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: read file header: %w\", err)\n 462→\t}\n 463→\n 464→\tif fileMagic != walFileMagic {\n 465→\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: invalid file magic 0x%08X (expected 0x%08X)\", fileMagic, walFileMagic)\n 466→\t}\n 467→\n 468→\t// Cache level lookups to avoid repeated tree traversal.\n 469→\tlvlCache := make(map[string]*Level)\n 470→\n 471→\tfor {\n 472→\t\tmsg, err := readWALRecord(br)\n 473→\t\tif err != nil {\n 474→\t\t\t// Truncated trailing record is expected after a crash; stop replaying.\n 475→\t\t\tcclog.Debugf(\"[METRICSTORE]> WAL: stopping replay at corrupted/partial record: %v\", err)\n 476→\t\t\tbreak\n 477→\t\t}\n 478→\t\tif msg == nil {\n 479→\t\t\tbreak // Clean EOF\n 480→\t\t}\n 481→\n 482→\t\tif msg.Timestamp < from {\n 483→\t\t\tcontinue // Older than retention window\n 484→\t\t}\n 485→\n 486→\t\tminfo, ok := m.Metrics[msg.MetricName]\n 487→\t\tif !ok {\n 488→\t\t\tcontinue // Unknown metric (config may have changed)\n 489→\t\t}\n 490→\n 491→\t\t// Cache key is the null-separated selector path.\n 492→\t\tcacheKey := joinSelector(msg.Selector)\n 493→\t\tlvl, ok := lvlCache[cacheKey]\n 494→\t\tif !ok {\n 495→\t\t\tlvl = l.findLevelOrCreate(msg.Selector, len(m.Metrics))\n 496→\t\t\tlvlCache[cacheKey] = lvl\n 497→\t\t}\n 498→\n 499→\t\t// Write directly to the buffer, same as WriteToLevel but without the\n 500→\t\t// global level lookup (we already have the right level).\n 501→\t\tlvl.lock.Lock()\n 502→\t\tb := lvl.metrics[minfo.offset]\n 503→\t\tif b == nil {\n 504→\t\t\tb = newBuffer(msg.Timestamp, minfo.Frequency)\n 505→\t\t\tlvl.metrics[minfo.offset] = b\n 506→\t\t}\n 507→\t\tnb, writeErr := b.write(msg.Timestamp, msg.Value)\n 508→\t\tif writeErr == nil && b != nb {\n 509→\t\t\tlvl.metrics[minfo.offset] = nb\n 510→\t\t}\n 511→\t\t// Ignore write errors for timestamps before buffer start (can happen when\n 512→\t\t// replaying WAL entries that predate a loaded snapshot's start time).\n 513→\t\tlvl.lock.Unlock()\n 514→\t}\n 515→\n 516→\treturn nil\n 517→}\n 518→\n 519→// joinSelector builds a cache key from a selector slice using null bytes as separators.\n 520→func joinSelector(sel []string) string {\n 521→\tif len(sel) == 0 {\n 522→\t\treturn \"\"\n 523→\t}\n 524→\tvar result strings.Builder\n 525→\tresult.WriteString(sel[0])\n 526→\tfor i := 1; i < len(sel); i++ {\n 527→\t\tresult.WriteString(\"\\x00\" + sel[i])\n 528→\t}\n 529→\treturn result.String()\n 530→}\n 531→\n 532→// ToCheckpointWAL writes binary snapshot files for all hosts in parallel.\n 533→// Returns the number of files written, the list of host directories that were\n 534→// successfully checkpointed (for WAL rotation), and any errors.\n 535→func (m *MemoryStore) ToCheckpointWAL(dir string, from, to int64) (int, []string, error) {\n 536→\t// Collect all cluster/host pairs.\n 537→\tm.root.lock.RLock()\n 538→\ttotalHosts := 0\n 539→\tfor _, l1 := range m.root.children {\n 540→\t\tl1.lock.RLock()\n 541→\t\ttotalHosts += len(l1.children)\n 542→\t\tl1.lock.RUnlock()\n 543→\t}\n 544→\tm.root.lock.RUnlock()\n 545→\n 546→\tlevels := make([]*Level, 0, totalHosts)\n 547→\tselectors := make([][]string, 0, totalHosts)\n 548→\n 549→\tm.root.lock.RLock()\n 550→\tfor sel1, l1 := range m.root.children {\n 551→\t\tl1.lock.RLock()\n 552→\t\tfor sel2, l2 := range l1.children {\n 553→\t\t\tlevels = append(levels, l2)\n 554→\t\t\tselectors = append(selectors, []string{sel1, sel2})\n 555→\t\t}\n 556→\t\tl1.lock.RUnlock()\n 557→\t}\n 558→\tm.root.lock.RUnlock()\n 559→\n 560→\ttype workItem struct {\n 561→\t\tlevel *Level\n 562→\t\thostDir string\n 563→\t\tselector []string\n 564→\t}\n 565→\n 566→\tn, errs := int32(0), int32(0)\n 567→\tvar successDirs []string\n 568→\tvar successMu sync.Mutex\n 569→\n 570→\tvar wg sync.WaitGroup\n 571→\twg.Add(Keys.NumWorkers)\n 572→\twork := make(chan workItem, Keys.NumWorkers*2)\n 573→\n 574→\tfor range Keys.NumWorkers {\n 575→\t\tgo func() {\n 576→\t\t\tdefer wg.Done()\n 577→\t\t\tfor wi := range work {\n 578→\t\t\t\terr := wi.level.toCheckpointBinary(wi.hostDir, from, to, m)\n 579→\t\t\t\tif err != nil {\n 580→\t\t\t\t\tif err == ErrNoNewArchiveData {\n 581→\t\t\t\t\t\tcontinue\n 582→\t\t\t\t\t}\n 583→\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> binary checkpoint error for %s: %v\", wi.hostDir, err)\n 584→\t\t\t\t\tatomic.AddInt32(&errs, 1)\n 585→\t\t\t\t} else {\n 586→\t\t\t\t\tatomic.AddInt32(&n, 1)\n 587→\t\t\t\t\tsuccessMu.Lock()\n 588→\t\t\t\t\tsuccessDirs = append(successDirs, wi.hostDir)\n 589→\t\t\t\t\tsuccessMu.Unlock()\n 590→\t\t\t\t}\n 591→\t\t\t}\n 592→\t\t}()\n 593→\t}\n 594→\n 595→\tfor i := range levels {\n 596→\t\thostDir := path.Join(dir, path.Join(selectors[i]...))\n 597→\t\twork <- workItem{\n 598→\t\t\tlevel: levels[i],\n 599→\t\t\thostDir: hostDir,\n 600→\t\t\tselector: selectors[i],\n 601→\t\t}\n 602→\t}\n 603→\tclose(work)\n 604→\twg.Wait()\n 605→\n 606→\tif errs > 0 {\n 607→\t\treturn int(n), successDirs, fmt.Errorf(\"[METRICSTORE]> %d errors during binary checkpoint (%d successes)\", errs, n)\n 608→\t}\n 609→\treturn int(n), successDirs, nil\n 610→}\n 611→\n 612→// toCheckpointBinary writes a binary snapshot file for a single host-level node.\n 613→// Uses atomic rename (write to .tmp then rename) to avoid partial reads on crash.\n 614→func (l *Level) toCheckpointBinary(dir string, from, to int64, m *MemoryStore) error {\n 615→\tcf, err := l.toCheckpointFile(from, to, m)\n 616→\tif err != nil {\n 617→\t\treturn err\n 618→\t}\n 619→\tif cf == nil {\n 620→\t\treturn ErrNoNewArchiveData\n 621→\t}\n 622→\n 623→\tif err := os.MkdirAll(dir, CheckpointDirPerms); err != nil {\n 624→\t\treturn fmt.Errorf(\"mkdir %s: %w\", dir, err)\n 625→\t}\n 626→\n 627→\t// Write to a temp file first, then rename (atomic on POSIX).\n 628→\ttmpPath := path.Join(dir, fmt.Sprintf(\"%d.bin.tmp\", from))\n 629→\tfinalPath := path.Join(dir, fmt.Sprintf(\"%d.bin\", from))\n 630→\n 631→\tf, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, CheckpointFilePerms)\n 632→\tif err != nil {\n 633→\t\treturn fmt.Errorf(\"open binary snapshot %s: %w\", tmpPath, err)\n 634→\t}\n 635→\n 636→\tbw := bufio.NewWriter(f)\n 637→\tif err := writeBinarySnapshotFile(bw, cf); err != nil {\n 638→\t\tf.Close()\n 639→\t\tos.Remove(tmpPath)\n 640→\t\treturn fmt.Errorf(\"write binary snapshot: %w\", err)\n 641→\t}\n 642→\tif err := bw.Flush(); err != nil {\n 643→\t\tf.Close()\n 644→\t\tos.Remove(tmpPath)\n 645→\t\treturn err\n 646→\t}\n 647→\tf.Close()\n 648→\n 649→\treturn os.Rename(tmpPath, finalPath)\n 650→}\n 651→\n 652→// writeBinarySnapshotFile writes the binary snapshot file header and level tree.\n 653→func writeBinarySnapshotFile(w io.Writer, cf *CheckpointFile) error {\n 654→\tif err := binary.Write(w, binary.LittleEndian, snapFileMagic); err != nil {\n 655→\t\treturn err\n 656→\t}\n 657→\tif err := binary.Write(w, binary.LittleEndian, cf.From); err != nil {\n 658→\t\treturn err\n 659→\t}\n 660→\tif err := binary.Write(w, binary.LittleEndian, cf.To); err != nil {\n 661→\t\treturn err\n 662→\t}\n 663→\treturn writeBinaryLevel(w, cf)\n 664→}\n 665→\n 666→// writeBinaryLevel recursively writes a CheckpointFile level in binary format.\n 667→func writeBinaryLevel(w io.Writer, cf *CheckpointFile) error {\n 668→\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Metrics))); err != nil {\n 669→\t\treturn err\n 670→\t}\n 671→\n 672→\tfor name, metric := range cf.Metrics {\n 673→\t\tif err := writeString16(w, name); err != nil {\n 674→\t\t\treturn err\n 675→\t\t}\n 676→\t\tif err := binary.Write(w, binary.LittleEndian, metric.Frequency); err != nil {\n 677→\t\t\treturn err\n 678→\t\t}\n 679→\t\tif err := binary.Write(w, binary.LittleEndian, metric.Start); err != nil {\n 680→\t\t\treturn err\n 681→\t\t}\n 682→\t\tif err := binary.Write(w, binary.LittleEndian, uint32(len(metric.Data))); err != nil {\n 683→\t\t\treturn err\n 684→\t\t}\n 685→\t\tfor _, v := range metric.Data {\n 686→\t\t\tif err := binary.Write(w, binary.LittleEndian, math.Float32bits(float32(v))); err != nil {\n 687→\t\t\t\treturn err\n 688→\t\t\t}\n 689→\t\t}\n 690→\t}\n 691→\n 692→\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Children))); err != nil {\n 693→\t\treturn err\n 694→\t}\n 695→\n 696→\tfor name, child := range cf.Children {\n 697→\t\tif err := writeString16(w, name); err != nil {\n 698→\t\t\treturn err\n 699→\t\t}\n 700→\t\tif err := writeBinaryLevel(w, child); err != nil {\n 701→\t\t\treturn err\n 702→\t\t}\n 703→\t}\n 704→\n 705→\treturn nil\n 706→}\n 707→\n 708→// writeString16 writes a 2-byte length-prefixed string to w.\n 709→func writeString16(w io.Writer, s string) error {\n 710→\tif err := binary.Write(w, binary.LittleEndian, uint16(len(s))); err != nil {\n 711→\t\treturn err\n 712→\t}\n 713→\t_, err := io.WriteString(w, s)\n 714→\treturn err\n 715→}\n 716→\n 717→// loadBinaryFile reads a binary snapshot file and loads data into the Level tree.\n 718→// The retention check (from) is applied to the file's 'to' timestamp.\n 719→func (l *Level) loadBinaryFile(m *MemoryStore, f *os.File, from int64) error {\n 720→\tbr := bufio.NewReader(f)\n 721→\n 722→\tvar magic uint32\n 723→\tif err := binary.Read(br, binary.LittleEndian, &magic); err != nil {\n 724→\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read magic: %w\", err)\n 725→\t}\n 726→\tif magic != snapFileMagic {\n 727→\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: invalid magic 0x%08X (expected 0x%08X)\", magic, snapFileMagic)\n 728→\t}\n 729→\n 730→\tvar fileFrom, fileTo int64\n 731→\tif err := binary.Read(br, binary.LittleEndian, &fileFrom); err != nil {\n 732→\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read from: %w\", err)\n 733→\t}\n 734→\tif err := binary.Read(br, binary.LittleEndian, &fileTo); err != nil {\n 735→\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read to: %w\", err)\n 736→\t}\n 737→\n 738→\tif fileTo != 0 && fileTo < from {\n 739→\t\treturn nil // File is older than retention window, skip it\n 740→\t}\n 741→\n 742→\tcf, err := readBinaryLevel(br)\n 743→\tif err != nil {\n 744→\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read level tree: %w\", err)\n 745→\t}\n 746→\tcf.From = fileFrom\n 747→\tcf.To = fileTo\n 748→\n 749→\treturn l.loadFile(cf, m)\n 750→}\n 751→\n 752→// readBinaryLevel recursively reads a level from the binary snapshot format.\n 753→func readBinaryLevel(r io.Reader) (*CheckpointFile, error) {\n 754→\tcf := &CheckpointFile{\n 755→\t\tMetrics: make(map[string]*CheckpointMetrics),\n 756→\t\tChildren: make(map[string]*CheckpointFile),\n 757→\t}\n 758→\n 759→\tvar numMetrics uint32\n 760→\tif err := binary.Read(r, binary.LittleEndian, &numMetrics); err != nil {\n 761→\t\treturn nil, fmt.Errorf(\"read num_metrics: %w\", err)\n 762→\t}\n 763→\n 764→\tfor range numMetrics {\n 765→\t\tname, err := readString16(r)\n 766→\t\tif err != nil {\n 767→\t\t\treturn nil, fmt.Errorf(\"read metric name: %w\", err)\n 768→\t\t}\n 769→\n 770→\t\tvar freq, start int64\n 771→\t\tif err := binary.Read(r, binary.LittleEndian, &freq); err != nil {\n 772→\t\t\treturn nil, fmt.Errorf(\"read frequency for %s: %w\", name, err)\n 773→\t\t}\n 774→\t\tif err := binary.Read(r, binary.LittleEndian, &start); err != nil {\n 775→\t\t\treturn nil, fmt.Errorf(\"read start for %s: %w\", name, err)\n 776→\t\t}\n 777→\n 778→\t\tvar numValues uint32\n 779→\t\tif err := binary.Read(r, binary.LittleEndian, &numValues); err != nil {\n 780→\t\t\treturn nil, fmt.Errorf(\"read num_values for %s: %w\", name, err)\n 781→\t\t}\n 782→\n 783→\t\tdata := make([]schema.Float, numValues)\n 784→\t\tfor i := range numValues {\n 785→\t\t\tvar bits uint32\n 786→\t\t\tif err := binary.Read(r, binary.LittleEndian, &bits); err != nil {\n 787→\t\t\t\treturn nil, fmt.Errorf(\"read value[%d] for %s: %w\", i, name, err)\n 788→\t\t\t}\n 789→\t\t\tdata[i] = schema.Float(math.Float32frombits(bits))\n 790→\t\t}\n 791→\n 792→\t\tcf.Metrics[name] = &CheckpointMetrics{\n 793→\t\t\tFrequency: freq,\n 794→\t\t\tStart: start,\n 795→\t\t\tData: data,\n 796→\t\t}\n 797→\t}\n 798→\n 799→\tvar numChildren uint32\n 800→\tif err := binary.Read(r, binary.LittleEndian, &numChildren); err != nil {\n 801→\t\treturn nil, fmt.Errorf(\"read num_children: %w\", err)\n 802→\t}\n 803→\n 804→\tfor range numChildren {\n 805→\t\tchildName, err := readString16(r)\n 806→\t\tif err != nil {\n 807→\t\t\treturn nil, fmt.Errorf(\"read child name: %w\", err)\n 808→\t\t}\n 809→\n 810→\t\tchild, err := readBinaryLevel(r)\n 811→\t\tif err != nil {\n 812→\t\t\treturn nil, fmt.Errorf(\"read child %s: %w\", childName, err)\n 813→\t\t}\n 814→\t\tcf.Children[childName] = child\n 815→\t}\n 816→\n 817→\treturn cf, nil\n 818→}\n 819→\n 820→// readString16 reads a 2-byte length-prefixed string from r.\n 821→func readString16(r io.Reader) (string, error) {\n 822→\tvar sLen uint16\n 823→\tif err := binary.Read(r, binary.LittleEndian, &sLen); err != nil {\n 824→\t\treturn \"\", err\n 825→\t}\n 826→\tbuf := make([]byte, sLen)\n 827→\tif _, err := io.ReadFull(r, buf); err != nil {\n 828→\t\treturn \"\", err\n 829→\t}\n 830→\treturn string(buf), nil\n 831→}\n 832→"}]},"uuid":"311973a6-2ed6-45c9-8815-188a98dee868","timestamp":"2026-03-18T05:29:23.141Z","toolUseResult":{"type":"text","file":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","content":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides walCheckpoint.go: WAL-based checkpoint implementation.\n//\n// This replaces the Avro shadow tree with an append-only Write-Ahead Log (WAL)\n// per host, eliminating the extra memory overhead of the AvroStore and providing\n// truly continuous (per-write) crash safety.\n//\n// # Architecture\n//\n//\tMetric write (DecodeLine)\n//\t │\n//\t ├─► WriteToLevel() → main MemoryStore (unchanged)\n//\t │\n//\t └─► WALMessages channel\n//\t │\n//\t ▼\n//\t WALStaging goroutine\n//\t │\n//\t ▼\n//\t checkpoints/cluster/host/current.wal (append-only, binary)\n//\n//\tPeriodic checkpoint (Checkpointing goroutine):\n//\t 1. Write <timestamp>.bin snapshot (column-oriented, from main tree)\n//\t 2. Signal WALStaging to truncate current.wal per host\n//\n//\tOn restart (FromCheckpoint):\n//\t 1. Load most recent <timestamp>.bin snapshot\n//\t 2. Replay current.wal (overwrite-safe: buffer.write handles duplicate timestamps)\n//\n// # WAL Record Format\n//\n//\t[4B magic 0xCC1DA7A1][4B payload_len][payload][4B CRC32]\n//\n//\tpayload:\n//\t [8B timestamp int64]\n//\t [2B metric_name_len uint16][N metric name bytes]\n//\t [1B selector_count uint8]\n//\t per selector: [1B selector_len uint8][M selector bytes]\n//\t [4B value float32 bits]\n//\n// # Binary Snapshot Format\n//\n//\t[4B magic 0xCC5B0001][8B from int64][8B to int64]\n//\tLevel tree (recursive):\n//\t [4B num_metrics uint32]\n//\t per metric:\n//\t [2B name_len uint16][N name bytes]\n//\t [8B frequency int64][8B start int64]\n//\t [4B num_values uint32][num_values × 4B float32]\n//\t [4B num_children uint32]\n//\t per child: [2B name_len uint16][N name bytes] + Level (recursive)\npackage metricstore\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)\n\n// Magic numbers for binary formats.\nconst (\n\twalFileMagic = uint32(0xCC1DA701) // WAL file header magic\n\twalRecordMagic = uint32(0xCC1DA7A1) // WAL record magic\n\tsnapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic\n)\n\n// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\n// Buffered to allow burst writes without blocking the metric ingestion path.\nvar WALMessages = make(chan *WALMessage, 65536)\n\n// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\n// (close, delete, reopen) after a binary snapshot has been written.\nvar walRotateCh = make(chan walRotateReq, 256)\n\n// WALMessage represents a single metric write to be appended to the WAL.\n// Cluster and Node are NOT stored in the WAL record (inferred from file path).\ntype WALMessage struct {\n\tMetricName string\n\tCluster string\n\tNode string\n\tSelector []string\n\tValue schema.Float\n\tTimestamp int64\n}\n\n// walRotateReq requests WAL file rotation for a specific host directory.\n// The done channel is closed by the WAL goroutine when rotation is complete.\ntype walRotateReq struct {\n\thostDir string\n\tdone chan struct{}\n}\n\n// walFileState holds an open WAL file handle and buffered writer for one host directory.\ntype walFileState struct {\n\tf *os.File\n\tw *bufio.Writer\n}\n\n// WALStaging starts a background goroutine that receives WALMessage items\n// and appends binary WAL records to per-host current.wal files.\n// Also handles WAL rotation requests from the checkpoint goroutine.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\twg.Go(func() {\n\t\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\t\treturn\n\t\t}\n\n\t\thostFiles := make(map[string]*walFileState)\n\n\t\tdefer func() {\n\t\t\tfor _, ws := range hostFiles {\n\t\t\t\tif ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\tws, ok := hostFiles[hostDir]\n\t\t\tif ok {\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\tif err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t// Write file header magic if file is new (empty).\n\t\t\tinfo, err := f.Stat()\n\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\tvar hdr [4]byte\n\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\tf.Close()\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws = &walFileState{f: f, w: w}\n\t\t\thostFiles[hostDir] = ws\n\t\t\treturn ws\n\t\t}\n\n\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\tif ws == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := writeWALRecord(ws.w, msg); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tprocessRotate := func(req walRotateReq) {\n\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\tif ok && ws.f != nil {\n\t\t\t\tws.w.Flush()\n\t\t\t\tws.f.Close()\n\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t}\n\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t}\n\t\t\tclose(req.done)\n\t\t}\n\n\t\tdrain := func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\tdefault:\n\t\t\t\t\t// Flush all buffered writers after draining remaining messages.\n\t\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tdrain()\n\t\t\t\treturn\n\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\tfor range 256 {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tflushed:\n\t\t\t\t// Flush all buffered writers after processing the batch.\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase req := <-walRotateCh:\n\t\t\t\tprocessRotate(req)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFiles(hostDirs []string) {\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFilesAfterShutdown(hostDirs []string) {\n\tfor _, dir := range hostDirs {\n\t\twalPath := path.Join(dir, \"current.wal\")\n\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t}\n\t}\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {\n\tsize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tsize += 1 + len(s)\n\t}\n\n\tbuf := make([]byte, 0, size)\n\n\t// Timestamp (8 bytes, little-endian int64)\n\tvar ts [8]byte\n\tbinary.LittleEndian.PutUint64(ts[:], uint64(msg.Timestamp))\n\tbuf = append(buf, ts[:]...)\n\n\t// Metric name (2-byte length prefix + bytes)\n\tvar mLen [2]byte\n\tbinary.LittleEndian.PutUint16(mLen[:], uint16(len(msg.MetricName)))\n\tbuf = append(buf, mLen[:]...)\n\tbuf = append(buf, msg.MetricName...)\n\n\t// Selector count (1 byte)\n\tbuf = append(buf, byte(len(msg.Selector)))\n\n\t// Selectors (1-byte length prefix + bytes each)\n\tfor _, sel := range msg.Selector {\n\t\tbuf = append(buf, byte(len(sel)))\n\t\tbuf = append(buf, sel...)\n\t}\n\n\t// Value (4 bytes, float32 bit representation)\n\tvar val [4]byte\n\tbinary.LittleEndian.PutUint32(val[:], math.Float32bits(float32(msg.Value)))\n\tbuf = append(buf, val[:]...)\n\n\treturn buf\n}\n\n// writeWALRecord appends a binary WAL record to the writer.\n// Format: [4B magic][4B payload_len][payload][4B CRC32]\nfunc writeWALRecord(w io.Writer, msg *WALMessage) error {\n\tpayload := buildWALPayload(msg)\n\tcrc := crc32.ChecksumIEEE(payload)\n\n\trecord := make([]byte, 0, 4+4+len(payload)+4)\n\n\tvar magic [4]byte\n\tbinary.LittleEndian.PutUint32(magic[:], walRecordMagic)\n\trecord = append(record, magic[:]...)\n\n\tvar pLen [4]byte\n\tbinary.LittleEndian.PutUint32(pLen[:], uint32(len(payload)))\n\trecord = append(record, pLen[:]...)\n\n\trecord = append(record, payload...)\n\n\tvar crcBytes [4]byte\n\tbinary.LittleEndian.PutUint32(crcBytes[:], crc)\n\trecord = append(record, crcBytes[:]...)\n\n\t_, err := w.Write(record)\n\treturn err\n}\n\n// readWALRecord reads one WAL record from the reader.\n// Returns (nil, nil) on clean EOF. Returns error on data corruption.\n// A CRC mismatch indicates a truncated trailing record (expected on crash).\nfunc readWALRecord(r io.Reader) (*WALMessage, error) {\n\tvar magic uint32\n\tif err := binary.Read(r, binary.LittleEndian, &magic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil, nil // Clean EOF\n\t\t}\n\t\treturn nil, fmt.Errorf(\"read record magic: %w\", err)\n\t}\n\n\tif magic != walRecordMagic {\n\t\treturn nil, fmt.Errorf(\"invalid record magic 0x%08X (expected 0x%08X)\", magic, walRecordMagic)\n\t}\n\n\tvar payloadLen uint32\n\tif err := binary.Read(r, binary.LittleEndian, &payloadLen); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload length: %w\", err)\n\t}\n\n\tif payloadLen > 1<<20 { // 1 MB sanity limit\n\t\treturn nil, fmt.Errorf(\"record payload too large: %d bytes\", payloadLen)\n\t}\n\n\tpayload := make([]byte, payloadLen)\n\tif _, err := io.ReadFull(r, payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload: %w\", err)\n\t}\n\n\tvar storedCRC uint32\n\tif err := binary.Read(r, binary.LittleEndian, &storedCRC); err != nil {\n\t\treturn nil, fmt.Errorf(\"read CRC: %w\", err)\n\t}\n\n\tif crc32.ChecksumIEEE(payload) != storedCRC {\n\t\treturn nil, fmt.Errorf(\"CRC mismatch (truncated write or corruption)\")\n\t}\n\n\treturn parseWALPayload(payload)\n}\n\n// parseWALPayload decodes a binary payload into a WALMessage.\nfunc parseWALPayload(payload []byte) (*WALMessage, error) {\n\tif len(payload) < 8+2+1+4 {\n\t\treturn nil, fmt.Errorf(\"payload too short: %d bytes\", len(payload))\n\t}\n\n\toffset := 0\n\n\t// Timestamp (8 bytes)\n\tts := int64(binary.LittleEndian.Uint64(payload[offset : offset+8]))\n\toffset += 8\n\n\t// Metric name (2-byte length + bytes)\n\tif offset+2 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name length overflows payload\")\n\t}\n\tmLen := int(binary.LittleEndian.Uint16(payload[offset : offset+2]))\n\toffset += 2\n\n\tif offset+mLen > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name overflows payload\")\n\t}\n\tmetricName := string(payload[offset : offset+mLen])\n\toffset += mLen\n\n\t// Selector count (1 byte)\n\tif offset >= len(payload) {\n\t\treturn nil, fmt.Errorf(\"selector count overflows payload\")\n\t}\n\tselCount := int(payload[offset])\n\toffset++\n\n\tselectors := make([]string, selCount)\n\tfor i := range selCount {\n\t\tif offset >= len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] length overflows payload\", i)\n\t\t}\n\t\tsLen := int(payload[offset])\n\t\toffset++\n\n\t\tif offset+sLen > len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] data overflows payload\", i)\n\t\t}\n\t\tselectors[i] = string(payload[offset : offset+sLen])\n\t\toffset += sLen\n\t}\n\n\t// Value (4 bytes, float32 bits)\n\tif offset+4 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"value overflows payload\")\n\t}\n\tbits := binary.LittleEndian.Uint32(payload[offset : offset+4])\n\tvalue := schema.Float(math.Float32frombits(bits))\n\n\treturn &WALMessage{\n\t\tMetricName: metricName,\n\t\tTimestamp: ts,\n\t\tSelector: selectors,\n\t\tValue: value,\n\t}, nil\n}\n\n// loadWALFile reads a WAL file and replays all valid records into the Level tree.\n// l is the host-level node. Corrupt or partial trailing records are silently skipped\n// (expected on crash). Records older than 'from' are skipped.\nfunc (l *Level) loadWALFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\t// Verify file header magic.\n\tvar fileMagic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &fileMagic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil // Empty file, no data\n\t\t}\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: read file header: %w\", err)\n\t}\n\n\tif fileMagic != walFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: invalid file magic 0x%08X (expected 0x%08X)\", fileMagic, walFileMagic)\n\t}\n\n\t// Cache level lookups to avoid repeated tree traversal.\n\tlvlCache := make(map[string]*Level)\n\n\tfor {\n\t\tmsg, err := readWALRecord(br)\n\t\tif err != nil {\n\t\t\t// Truncated trailing record is expected after a crash; stop replaying.\n\t\t\tcclog.Debugf(\"[METRICSTORE]> WAL: stopping replay at corrupted/partial record: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tif msg == nil {\n\t\t\tbreak // Clean EOF\n\t\t}\n\n\t\tif msg.Timestamp < from {\n\t\t\tcontinue // Older than retention window\n\t\t}\n\n\t\tminfo, ok := m.Metrics[msg.MetricName]\n\t\tif !ok {\n\t\t\tcontinue // Unknown metric (config may have changed)\n\t\t}\n\n\t\t// Cache key is the null-separated selector path.\n\t\tcacheKey := joinSelector(msg.Selector)\n\t\tlvl, ok := lvlCache[cacheKey]\n\t\tif !ok {\n\t\t\tlvl = l.findLevelOrCreate(msg.Selector, len(m.Metrics))\n\t\t\tlvlCache[cacheKey] = lvl\n\t\t}\n\n\t\t// Write directly to the buffer, same as WriteToLevel but without the\n\t\t// global level lookup (we already have the right level).\n\t\tlvl.lock.Lock()\n\t\tb := lvl.metrics[minfo.offset]\n\t\tif b == nil {\n\t\t\tb = newBuffer(msg.Timestamp, minfo.Frequency)\n\t\t\tlvl.metrics[minfo.offset] = b\n\t\t}\n\t\tnb, writeErr := b.write(msg.Timestamp, msg.Value)\n\t\tif writeErr == nil && b != nb {\n\t\t\tlvl.metrics[minfo.offset] = nb\n\t\t}\n\t\t// Ignore write errors for timestamps before buffer start (can happen when\n\t\t// replaying WAL entries that predate a loaded snapshot's start time).\n\t\tlvl.lock.Unlock()\n\t}\n\n\treturn nil\n}\n\n// joinSelector builds a cache key from a selector slice using null bytes as separators.\nfunc joinSelector(sel []string) string {\n\tif len(sel) == 0 {\n\t\treturn \"\"\n\t}\n\tvar result strings.Builder\n\tresult.WriteString(sel[0])\n\tfor i := 1; i < len(sel); i++ {\n\t\tresult.WriteString(\"\\x00\" + sel[i])\n\t}\n\treturn result.String()\n}\n\n// ToCheckpointWAL writes binary snapshot files for all hosts in parallel.\n// Returns the number of files written, the list of host directories that were\n// successfully checkpointed (for WAL rotation), and any errors.\nfunc (m *MemoryStore) ToCheckpointWAL(dir string, from, to int64) (int, []string, error) {\n\t// Collect all cluster/host pairs.\n\tm.root.lock.RLock()\n\ttotalHosts := 0\n\tfor _, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\ttotalHosts += len(l1.children)\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\tlevels := make([]*Level, 0, totalHosts)\n\tselectors := make([][]string, 0, totalHosts)\n\n\tm.root.lock.RLock()\n\tfor sel1, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\tfor sel2, l2 := range l1.children {\n\t\t\tlevels = append(levels, l2)\n\t\t\tselectors = append(selectors, []string{sel1, sel2})\n\t\t}\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\ttype workItem struct {\n\t\tlevel *Level\n\t\thostDir string\n\t\tselector []string\n\t}\n\n\tn, errs := int32(0), int32(0)\n\tvar successDirs []string\n\tvar successMu sync.Mutex\n\n\tvar wg sync.WaitGroup\n\twg.Add(Keys.NumWorkers)\n\twork := make(chan workItem, Keys.NumWorkers*2)\n\n\tfor range Keys.NumWorkers {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor wi := range work {\n\t\t\t\terr := wi.level.toCheckpointBinary(wi.hostDir, from, to, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == ErrNoNewArchiveData {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> binary checkpoint error for %s: %v\", wi.hostDir, err)\n\t\t\t\t\tatomic.AddInt32(&errs, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.AddInt32(&n, 1)\n\t\t\t\t\tsuccessMu.Lock()\n\t\t\t\t\tsuccessDirs = append(successDirs, wi.hostDir)\n\t\t\t\t\tsuccessMu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor i := range levels {\n\t\thostDir := path.Join(dir, path.Join(selectors[i]...))\n\t\twork <- workItem{\n\t\t\tlevel: levels[i],\n\t\t\thostDir: hostDir,\n\t\t\tselector: selectors[i],\n\t\t}\n\t}\n\tclose(work)\n\twg.Wait()\n\n\tif errs > 0 {\n\t\treturn int(n), successDirs, fmt.Errorf(\"[METRICSTORE]> %d errors during binary checkpoint (%d successes)\", errs, n)\n\t}\n\treturn int(n), successDirs, nil\n}\n\n// toCheckpointBinary writes a binary snapshot file for a single host-level node.\n// Uses atomic rename (write to .tmp then rename) to avoid partial reads on crash.\nfunc (l *Level) toCheckpointBinary(dir string, from, to int64, m *MemoryStore) error {\n\tcf, err := l.toCheckpointFile(from, to, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cf == nil {\n\t\treturn ErrNoNewArchiveData\n\t}\n\n\tif err := os.MkdirAll(dir, CheckpointDirPerms); err != nil {\n\t\treturn fmt.Errorf(\"mkdir %s: %w\", dir, err)\n\t}\n\n\t// Write to a temp file first, then rename (atomic on POSIX).\n\ttmpPath := path.Join(dir, fmt.Sprintf(\"%d.bin.tmp\", from))\n\tfinalPath := path.Join(dir, fmt.Sprintf(\"%d.bin\", from))\n\n\tf, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, CheckpointFilePerms)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open binary snapshot %s: %w\", tmpPath, err)\n\t}\n\n\tbw := bufio.NewWriter(f)\n\tif err := writeBinarySnapshotFile(bw, cf); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn fmt.Errorf(\"write binary snapshot: %w\", err)\n\t}\n\tif err := bw.Flush(); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn err\n\t}\n\tf.Close()\n\n\treturn os.Rename(tmpPath, finalPath)\n}\n\n// writeBinarySnapshotFile writes the binary snapshot file header and level tree.\nfunc writeBinarySnapshotFile(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, snapFileMagic); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.From); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.To); err != nil {\n\t\treturn err\n\t}\n\treturn writeBinaryLevel(w, cf)\n}\n\n// writeBinaryLevel recursively writes a CheckpointFile level in binary format.\nfunc writeBinaryLevel(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Metrics))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, metric := range cf.Metrics {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Frequency); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Start); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, uint32(len(metric.Data))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, v := range metric.Data {\n\t\t\tif err := binary.Write(w, binary.LittleEndian, math.Float32bits(float32(v))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Children))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, child := range cf.Children {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writeBinaryLevel(w, child); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// writeString16 writes a 2-byte length-prefixed string to w.\nfunc writeString16(w io.Writer, s string) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint16(len(s))); err != nil {\n\t\treturn err\n\t}\n\t_, err := io.WriteString(w, s)\n\treturn err\n}\n\n// loadBinaryFile reads a binary snapshot file and loads data into the Level tree.\n// The retention check (from) is applied to the file's 'to' timestamp.\nfunc (l *Level) loadBinaryFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\tvar magic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &magic); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read magic: %w\", err)\n\t}\n\tif magic != snapFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: invalid magic 0x%08X (expected 0x%08X)\", magic, snapFileMagic)\n\t}\n\n\tvar fileFrom, fileTo int64\n\tif err := binary.Read(br, binary.LittleEndian, &fileFrom); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read from: %w\", err)\n\t}\n\tif err := binary.Read(br, binary.LittleEndian, &fileTo); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read to: %w\", err)\n\t}\n\n\tif fileTo != 0 && fileTo < from {\n\t\treturn nil // File is older than retention window, skip it\n\t}\n\n\tcf, err := readBinaryLevel(br)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read level tree: %w\", err)\n\t}\n\tcf.From = fileFrom\n\tcf.To = fileTo\n\n\treturn l.loadFile(cf, m)\n}\n\n// readBinaryLevel recursively reads a level from the binary snapshot format.\nfunc readBinaryLevel(r io.Reader) (*CheckpointFile, error) {\n\tcf := &CheckpointFile{\n\t\tMetrics: make(map[string]*CheckpointMetrics),\n\t\tChildren: make(map[string]*CheckpointFile),\n\t}\n\n\tvar numMetrics uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numMetrics); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_metrics: %w\", err)\n\t}\n\n\tfor range numMetrics {\n\t\tname, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read metric name: %w\", err)\n\t\t}\n\n\t\tvar freq, start int64\n\t\tif err := binary.Read(r, binary.LittleEndian, &freq); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read frequency for %s: %w\", name, err)\n\t\t}\n\t\tif err := binary.Read(r, binary.LittleEndian, &start); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read start for %s: %w\", name, err)\n\t\t}\n\n\t\tvar numValues uint32\n\t\tif err := binary.Read(r, binary.LittleEndian, &numValues); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read num_values for %s: %w\", name, err)\n\t\t}\n\n\t\tdata := make([]schema.Float, numValues)\n\t\tfor i := range numValues {\n\t\t\tvar bits uint32\n\t\t\tif err := binary.Read(r, binary.LittleEndian, &bits); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"read value[%d] for %s: %w\", i, name, err)\n\t\t\t}\n\t\t\tdata[i] = schema.Float(math.Float32frombits(bits))\n\t\t}\n\n\t\tcf.Metrics[name] = &CheckpointMetrics{\n\t\t\tFrequency: freq,\n\t\t\tStart: start,\n\t\t\tData: data,\n\t\t}\n\t}\n\n\tvar numChildren uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numChildren); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_children: %w\", err)\n\t}\n\n\tfor range numChildren {\n\t\tchildName, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child name: %w\", err)\n\t\t}\n\n\t\tchild, err := readBinaryLevel(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child %s: %w\", childName, err)\n\t\t}\n\t\tcf.Children[childName] = child\n\t}\n\n\treturn cf, nil\n}\n\n// readString16 reads a 2-byte length-prefixed string from r.\nfunc readString16(r io.Reader) (string, error) {\n\tvar sLen uint16\n\tif err := binary.Read(r, binary.LittleEndian, &sLen); err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, sLen)\n\tif _, err := io.ReadFull(r, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n","numLines":832,"startLine":1,"totalLines":832}},"sourceToolAssistantUUID":"53cacb9b-842f-4b11-adeb-ae3f42fafd4a","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"311973a6-2ed6-45c9-8815-188a98dee868","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01XZzrun9oNQmo8YoM39V67m","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01PtLUrnJXjXdSBqyJaBpYkt","name":"Read","input":{"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/lineprotocol.go"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":11338,"cache_read_input_tokens":8666,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":11338},"output_tokens":10,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zeJVxWMXaD6uiZvMX5","type":"assistant","uuid":"89e8ab32-1c9d-4c0d-b4c3-a3d9fad1a16b","timestamp":"2026-03-18T05:29:23.580Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"89e8ab32-1c9d-4c0d-b4c3-a3d9fad1a16b","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Read","command":"callback"},"parentToolUseID":"toolu_01PtLUrnJXjXdSBqyJaBpYkt","toolUseID":"toolu_01PtLUrnJXjXdSBqyJaBpYkt","timestamp":"2026-03-18T05:29:23.586Z","uuid":"1139b273-bd58-4093-85c6-7daa218522e7","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"89e8ab32-1c9d-4c0d-b4c3-a3d9fad1a16b","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01PtLUrnJXjXdSBqyJaBpYkt","type":"tool_result","content":" 1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n 2→// All rights reserved. This file is part of cc-backend.\n 3→// Use of this source code is governed by a MIT-style\n 4→// license that can be found in the LICENSE file.\n 5→\n 6→// This file implements ingestion of InfluxDB line-protocol metric data received\n 7→// over NATS. Each line encodes one metric sample with the following structure:\n 8→//\n 9→//\t<measurement>[,cluster=<c>][,hostname=<h>][,type=<t>][,type-id=<id>][,subtype=<s>][,stype-id=<id>] value=<v> [<timestamp>]\n 10→//\n 11→// The measurement name identifies the metric (e.g. \"cpu_load\"). Tags provide\n 12→// routing information (cluster, host) and optional sub-device selectors (type,\n 13→// subtype). Only one field is expected per line: \"value\".\n 14→//\n 15→// After decoding, each sample is:\n 16→// 1. Written to the in-memory store via ms.WriteToLevel.\n 17→// 2. If the checkpoint format is \"wal\", also forwarded to the WAL staging\n 18→// goroutine via the WALMessages channel for durable write-ahead logging.\n 19→package metricstore\n 20→\n 21→import (\n 22→\t\"bytes\"\n 23→\t\"context\"\n 24→\t\"fmt\"\n 25→\t\"sync\"\n 26→\t\"sync/atomic\"\n 27→\t\"time\"\n 28→\n 29→\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n 30→\t\"github.com/ClusterCockpit/cc-lib/v2/nats\"\n 31→\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n 32→\t\"github.com/ClusterCockpit/cc-line-protocol/v2/lineprotocol\"\n 33→)\n 34→\n 35→// ReceiveNats subscribes to all configured NATS subjects and feeds incoming\n 36→// line-protocol messages into the MemoryStore.\n 37→//\n 38→// When workers > 1 a pool of goroutines drains a shared channel so that\n 39→// multiple messages can be decoded in parallel. With workers == 1 the NATS\n 40→// callback decodes inline (no channel overhead, lower latency).\n 41→//\n 42→// The function blocks until ctx is cancelled and all worker goroutines have\n 43→// finished. It returns nil when the NATS client is not configured; callers\n 44→// should treat that as a no-op rather than an error.\n 45→func ReceiveNats(ms *MemoryStore,\n 46→\tworkers int,\n 47→\tctx context.Context,\n 48→) error {\n 49→\tnc := nats.GetClient()\n 50→\n 51→\tif nc == nil {\n 52→\t\tcclog.Warn(\"NATS client not initialized\")\n 53→\t\treturn nil\n 54→\t}\n 55→\n 56→\tvar wg sync.WaitGroup\n 57→\tmsgs := make(chan []byte, max(workers*256, 8192))\n 58→\n 59→\tfor _, sc := range *Keys.Subscriptions {\n 60→\t\tclusterTag := sc.ClusterTag\n 61→\t\tif workers > 1 {\n 62→\t\t\twg.Add(workers)\n 63→\n 64→\t\t\tfor range workers {\n 65→\t\t\t\tgo func() {\n 66→\t\t\t\t\tdefer wg.Done()\n 67→\t\t\t\t\tfor m := range msgs {\n 68→\t\t\t\t\t\tdec := lineprotocol.NewDecoderWithBytes(m)\n 69→\t\t\t\t\t\tif err := DecodeLine(dec, ms, clusterTag); err != nil {\n 70→\t\t\t\t\t\t\tcclog.Errorf(\"error: %s\", err.Error())\n 71→\t\t\t\t\t\t}\n 72→\t\t\t\t\t}\n 73→\t\t\t\t}()\n 74→\t\t\t}\n 75→\n 76→\t\t\tnc.Subscribe(sc.SubscribeTo, func(subject string, data []byte) {\n 77→\t\t\t\tselect {\n 78→\t\t\t\tcase msgs <- data:\n 79→\t\t\t\tcase <-ctx.Done():\n 80→\t\t\t\t}\n 81→\t\t\t})\n 82→\t\t} else {\n 83→\t\t\tnc.Subscribe(sc.SubscribeTo, func(subject string, data []byte) {\n 84→\t\t\t\tdec := lineprotocol.NewDecoderWithBytes(data)\n 85→\t\t\t\tif err := DecodeLine(dec, ms, clusterTag); err != nil {\n 86→\t\t\t\t\tcclog.Errorf(\"error: %s\", err.Error())\n 87→\t\t\t\t}\n 88→\t\t\t})\n 89→\t\t}\n 90→\t\tcclog.Infof(\"NATS subscription to '%s' established\", sc.SubscribeTo)\n 91→\t}\n 92→\n 93→\tgo func() {\n 94→\t\t<-ctx.Done()\n 95→\t\tclose(msgs)\n 96→\t}()\n 97→\n 98→\twg.Wait()\n 99→\n 100→\treturn nil\n 101→}\n 102→\n 103→// reorder prepends prefix to buf in-place when buf has enough spare capacity,\n 104→// avoiding an allocation. Falls back to a regular append otherwise.\n 105→//\n 106→// It is used to assemble the \"type<type-id>\" and \"subtype<stype-id>\" selector\n 107→// strings when the type tag arrives before the type-id tag in the line, so the\n 108→// two byte slices need to be concatenated in tag-declaration order regardless\n 109→// of wire order.\n 110→func reorder(buf, prefix []byte) []byte {\n 111→\tn := len(prefix)\n 112→\tm := len(buf)\n 113→\tif cap(buf) < m+n {\n 114→\t\treturn append(prefix[:n:n], buf...)\n 115→\t} else {\n 116→\t\tbuf = buf[:n+m]\n 117→\t\tfor i := m - 1; i >= 0; i-- {\n 118→\t\t\tbuf[i+n] = buf[i]\n 119→\t\t}\n 120→\t\tfor i := range n {\n 121→\t\t\tbuf[i] = prefix[i]\n 122→\t\t}\n 123→\t\treturn buf\n 124→\t}\n 125→}\n 126→\n 127→// walDropped counts WAL messages dropped due to a full channel.\n 128→// Logged periodically; not critical since binary snapshots capture the data.\n 129→var walDropped atomic.Int64\n 130→\n 131→// decodeState holds the per-call scratch buffers used by DecodeLine.\n 132→// Instances are recycled via decodeStatePool to avoid repeated allocations\n 133→// during high-throughput ingestion.\n 134→type decodeState struct {\n 135→\t// metricBuf holds a copy of the current measurement name (line-protocol\n 136→\t// measurement field). Copied because dec.Measurement() returns a slice\n 137→\t// that is invalidated by the next decoder call.\n 138→\tmetricBuf []byte\n 139→\n 140→\t// selector is the sub-device path passed to WriteToLevel and WALMessage\n 141→\t// (e.g. [\"socket0\"] or [\"socket0\", \"memctrl1\"]). Reused across lines.\n 142→\tselector []string\n 143→\n 144→\t// typeBuf accumulates the concatenated \"type\"+\"type-id\" tag value for the\n 145→\t// current line. Reset at the start of each line's tag-decode loop.\n 146→\ttypeBuf []byte\n 147→\n 148→\t// subTypeBuf accumulates the concatenated \"subtype\"+\"stype-id\" tag value.\n 149→\t// Reset at the start of each line's tag-decode loop.\n 150→\tsubTypeBuf []byte\n 151→\n 152→\t// prevTypeBytes / prevTypeStr cache the last seen typeBuf content and its\n 153→\t// string conversion. Because consecutive lines in a batch typically address\n 154→\t// the same sub-device, the cache hit rate is very high and avoids\n 155→\t// repeated []byte→string allocations.\n 156→\tprevTypeBytes []byte\n 157→\tprevTypeStr string\n 158→\n 159→\t// prevSubTypeBytes / prevSubTypeStr are the same cache for the subtype.\n 160→\tprevSubTypeBytes []byte\n 161→\tprevSubTypeStr string\n 162→}\n 163→\n 164→// decodeStatePool recycles decodeState values across DecodeLine calls to\n 165→// reduce GC pressure during sustained metric ingestion.\n 166→var decodeStatePool = sync.Pool{\n 167→\tNew: func() any {\n 168→\t\treturn &decodeState{\n 169→\t\t\tmetricBuf: make([]byte, 0, 16),\n 170→\t\t\tselector: make([]string, 0, 4),\n 171→\t\t\ttypeBuf: make([]byte, 0, 16),\n 172→\t\t\tsubTypeBuf: make([]byte, 0, 16),\n 173→\t\t}\n 174→\t},\n 175→}\n 176→\n 177→// DecodeLine reads all lines from dec (InfluxDB line-protocol) and writes each\n 178→// decoded metric sample into ms.\n 179→//\n 180→// clusterDefault is used as the cluster name for lines that do not carry a\n 181→// \"cluster\" tag. Callers typically supply the ClusterTag value from the NATS\n 182→// subscription configuration.\n 183→//\n 184→// Performance notes:\n 185→// - A decodeState is obtained from decodeStatePool to reuse scratch buffers.\n 186→// - The Level pointer (host-level node in the metric tree) is cached across\n 187→// consecutive lines that share the same cluster+host pair to avoid\n 188→// repeated lock acquisitions on the root and cluster levels.\n 189→// - []byte→string conversions for type/subtype selectors are cached via\n 190→// prevType*/prevSubType* fields because batches typically repeat the same\n 191→// sub-device identifiers.\n 192→// - Timestamp parsing tries Second precision first; if that fails it retries\n 193→// Millisecond, Microsecond, and Nanosecond in turn. A missing timestamp\n 194→// falls back to time.Now().\n 195→//\n 196→// When the checkpoint format is \"wal\" each successfully decoded sample is also\n 197→// sent to WALMessages so the WAL staging goroutine can persist it durably\n 198→// before the next binary snapshot.\n 199→func DecodeLine(dec *lineprotocol.Decoder,\n 200→\tms *MemoryStore,\n 201→\tclusterDefault string,\n 202→) error {\n 203→\t// Reduce allocations in loop:\n 204→\tt := time.Now()\n 205→\tmetric := Metric{}\n 206→\tst := decodeStatePool.Get().(*decodeState)\n 207→\tdefer decodeStatePool.Put(st)\n 208→\n 209→\t// Optimize for the case where all lines in a \"batch\" are about the same\n 210→\t// cluster and host. By using `WriteToLevel` (level = host), we do not need\n 211→\t// to take the root- and cluster-level lock as often.\n 212→\tvar lvl *Level = nil\n 213→\tprevCluster, prevHost := \"\", \"\"\n 214→\n 215→\tvar ok bool\n 216→\tfor dec.Next() {\n 217→\t\trawmeasurement, err := dec.Measurement()\n 218→\t\tif err != nil {\n 219→\t\t\treturn err\n 220→\t\t}\n 221→\n 222→\t\t// Needs to be copied because another call to dec.* would\n 223→\t\t// invalidate the returned slice.\n 224→\t\tst.metricBuf = append(st.metricBuf[:0], rawmeasurement...)\n 225→\n 226→\t\t// The go compiler optimizes map[string(byteslice)] lookups:\n 227→\t\tmetric.MetricConfig, ok = ms.Metrics[string(rawmeasurement)]\n 228→\t\tif !ok {\n 229→\t\t\tcontinue\n 230→\t\t}\n 231→\n 232→\t\tst.typeBuf, st.subTypeBuf = st.typeBuf[:0], st.subTypeBuf[:0]\n 233→\t\tcluster, host := clusterDefault, \"\"\n 234→\t\tfor {\n 235→\t\t\tkey, val, err := dec.NextTag()\n 236→\t\t\tif err != nil {\n 237→\t\t\t\treturn err\n 238→\t\t\t}\n 239→\t\t\tif key == nil {\n 240→\t\t\t\tbreak\n 241→\t\t\t}\n 242→\n 243→\t\t\t// The go compiler optimizes string([]byte{...}) == \"...\":\n 244→\t\t\tswitch string(key) {\n 245→\t\t\tcase \"cluster\":\n 246→\t\t\t\tif string(val) == prevCluster {\n 247→\t\t\t\t\tcluster = prevCluster\n 248→\t\t\t\t} else {\n 249→\t\t\t\t\tcluster = string(val)\n 250→\t\t\t\t\tlvl = nil\n 251→\t\t\t\t}\n 252→\t\t\tcase \"hostname\", \"host\":\n 253→\t\t\t\tif string(val) == prevHost {\n 254→\t\t\t\t\thost = prevHost\n 255→\t\t\t\t} else {\n 256→\t\t\t\t\thost = string(val)\n 257→\t\t\t\t\tlvl = nil\n 258→\t\t\t\t}\n 259→\t\t\tcase \"type\":\n 260→\t\t\t\tif string(val) == \"node\" {\n 261→\t\t\t\t\tbreak\n 262→\t\t\t\t}\n 263→\n 264→\t\t\t\t// We cannot be sure that the \"type\" tag comes before the \"type-id\" tag:\n 265→\t\t\t\tif len(st.typeBuf) == 0 {\n 266→\t\t\t\t\tst.typeBuf = append(st.typeBuf, val...)\n 267→\t\t\t\t} else {\n 268→\t\t\t\t\tst.typeBuf = reorder(st.typeBuf, val)\n 269→\t\t\t\t}\n 270→\t\t\tcase \"type-id\":\n 271→\t\t\t\tst.typeBuf = append(st.typeBuf, val...)\n 272→\t\t\tcase \"subtype\":\n 273→\t\t\t\t// We cannot be sure that the \"subtype\" tag comes before the \"stype-id\" tag:\n 274→\t\t\t\tif len(st.subTypeBuf) == 0 {\n 275→\t\t\t\t\tst.subTypeBuf = append(st.subTypeBuf, val...)\n 276→\t\t\t\t} else {\n 277→\t\t\t\t\tst.subTypeBuf = reorder(st.subTypeBuf, val)\n 278→\t\t\t\t}\n 279→\t\t\tcase \"stype-id\":\n 280→\t\t\t\tst.subTypeBuf = append(st.subTypeBuf, val...)\n 281→\t\t\tdefault:\n 282→\t\t\t}\n 283→\t\t}\n 284→\n 285→\t\t// If the cluster or host changed, the lvl was set to nil\n 286→\t\tif lvl == nil {\n 287→\t\t\tst.selector = st.selector[:2]\n 288→\t\t\tst.selector[0], st.selector[1] = cluster, host\n 289→\t\t\tlvl = ms.GetLevel(st.selector)\n 290→\t\t\tprevCluster, prevHost = cluster, host\n 291→\t\t}\n 292→\n 293→\t\t// subtypes: cache []byte→string conversions; messages in a batch typically\n 294→\t\t// share the same type/subtype so the hit rate is very high.\n 295→\t\tst.selector = st.selector[:0]\n 296→\t\tif len(st.typeBuf) > 0 {\n 297→\t\t\tif !bytes.Equal(st.typeBuf, st.prevTypeBytes) {\n 298→\t\t\t\tst.prevTypeBytes = append(st.prevTypeBytes[:0], st.typeBuf...)\n 299→\t\t\t\tst.prevTypeStr = string(st.typeBuf)\n 300→\t\t\t}\n 301→\t\t\tst.selector = append(st.selector, st.prevTypeStr)\n 302→\t\t\tif len(st.subTypeBuf) > 0 {\n 303→\t\t\t\tif !bytes.Equal(st.subTypeBuf, st.prevSubTypeBytes) {\n 304→\t\t\t\t\tst.prevSubTypeBytes = append(st.prevSubTypeBytes[:0], st.subTypeBuf...)\n 305→\t\t\t\t\tst.prevSubTypeStr = string(st.subTypeBuf)\n 306→\t\t\t\t}\n 307→\t\t\t\tst.selector = append(st.selector, st.prevSubTypeStr)\n 308→\t\t\t}\n 309→\t\t}\n 310→\n 311→\t\tfor {\n 312→\t\t\tkey, val, err := dec.NextField()\n 313→\t\t\tif err != nil {\n 314→\t\t\t\treturn err\n 315→\t\t\t}\n 316→\n 317→\t\t\tif key == nil {\n 318→\t\t\t\tbreak\n 319→\t\t\t}\n 320→\n 321→\t\t\tif string(key) != \"value\" {\n 322→\t\t\t\treturn fmt.Errorf(\"host %s: unknown field: '%s' (value: %#v)\", host, string(key), val)\n 323→\t\t\t}\n 324→\n 325→\t\t\tif val.Kind() == lineprotocol.Float {\n 326→\t\t\t\tmetric.Value = schema.Float(val.FloatV())\n 327→\t\t\t} else if val.Kind() == lineprotocol.Int {\n 328→\t\t\t\tmetric.Value = schema.Float(val.IntV())\n 329→\t\t\t} else if val.Kind() == lineprotocol.Uint {\n 330→\t\t\t\tmetric.Value = schema.Float(val.UintV())\n 331→\t\t\t} else {\n 332→\t\t\t\treturn fmt.Errorf(\"host %s: unsupported value type in message: %s\", host, val.Kind().String())\n 333→\t\t\t}\n 334→\t\t}\n 335→\n 336→\t\tif t, err = dec.Time(lineprotocol.Second, t); err != nil {\n 337→\t\t\tt = time.Now()\n 338→\t\t\tif t, err = dec.Time(lineprotocol.Millisecond, t); err != nil {\n 339→\t\t\t\tt = time.Now()\n 340→\t\t\t\tif t, err = dec.Time(lineprotocol.Microsecond, t); err != nil {\n 341→\t\t\t\t\tt = time.Now()\n 342→\t\t\t\t\tif t, err = dec.Time(lineprotocol.Nanosecond, t); err != nil {\n 343→\t\t\t\t\t\treturn fmt.Errorf(\"host %s: timestamp : %#v with error : %#v\", host, t, err.Error())\n 344→\t\t\t\t\t}\n 345→\t\t\t\t}\n 346→\t\t\t}\n 347→\t\t}\n 348→\n 349→\t\tif err != nil {\n 350→\t\t\treturn fmt.Errorf(\"host %s: timestamp : %#v with error : %#v\", host, t, err.Error())\n 351→\t\t}\n 352→\n 353→\t\ttime := t.Unix()\n 354→\n 355→\t\tif Keys.Checkpoints.FileFormat == \"wal\" {\n 356→\t\t\tmsg := &WALMessage{\n 357→\t\t\t\tMetricName: string(st.metricBuf),\n 358→\t\t\t\tCluster: cluster,\n 359→\t\t\t\tNode: host,\n 360→\t\t\t\tSelector: append([]string{}, st.selector...),\n 361→\t\t\t\tValue: metric.Value,\n 362→\t\t\t\tTimestamp: time,\n 363→\t\t\t}\n 364→\t\t\tselect {\n 365→\t\t\tcase WALMessages <- msg:\n 366→\t\t\tdefault:\n 367→\t\t\t\t// WAL channel full — metric is written to memory store but not WAL.\n 368→\t\t\t\t// Next binary snapshot will capture it.\n 369→\t\t\t\tif dropped := walDropped.Add(1); dropped%10000 == 1 {\n 370→\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> WAL channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)\n 371→\t\t\t\t}\n 372→\t\t\t}\n 373→\t\t}\n 374→\n 375→\t\tif err := ms.WriteToLevel(lvl, st.selector, time, []Metric{metric}); err != nil {\n 376→\t\t\tcclog.Warnf(\"write error for host %s metric %s at ts %d: %s\", host, string(st.metricBuf), time, err.Error())\n 377→\t\t\tcontinue\n 378→\t\t}\n 379→\t}\n 380→\treturn nil\n 381→}\n 382→"}]},"uuid":"b32930de-19da-45b1-b574-3e7fd25bbefa","timestamp":"2026-03-18T05:29:23.586Z","toolUseResult":{"type":"text","file":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/lineprotocol.go","content":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// This file implements ingestion of InfluxDB line-protocol metric data received\n// over NATS. Each line encodes one metric sample with the following structure:\n//\n//\t<measurement>[,cluster=<c>][,hostname=<h>][,type=<t>][,type-id=<id>][,subtype=<s>][,stype-id=<id>] value=<v> [<timestamp>]\n//\n// The measurement name identifies the metric (e.g. \"cpu_load\"). Tags provide\n// routing information (cluster, host) and optional sub-device selectors (type,\n// subtype). Only one field is expected per line: \"value\".\n//\n// After decoding, each sample is:\n// 1. Written to the in-memory store via ms.WriteToLevel.\n// 2. If the checkpoint format is \"wal\", also forwarded to the WAL staging\n// goroutine via the WALMessages channel for durable write-ahead logging.\npackage metricstore\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/nats\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n\t\"github.com/ClusterCockpit/cc-line-protocol/v2/lineprotocol\"\n)\n\n// ReceiveNats subscribes to all configured NATS subjects and feeds incoming\n// line-protocol messages into the MemoryStore.\n//\n// When workers > 1 a pool of goroutines drains a shared channel so that\n// multiple messages can be decoded in parallel. With workers == 1 the NATS\n// callback decodes inline (no channel overhead, lower latency).\n//\n// The function blocks until ctx is cancelled and all worker goroutines have\n// finished. It returns nil when the NATS client is not configured; callers\n// should treat that as a no-op rather than an error.\nfunc ReceiveNats(ms *MemoryStore,\n\tworkers int,\n\tctx context.Context,\n) error {\n\tnc := nats.GetClient()\n\n\tif nc == nil {\n\t\tcclog.Warn(\"NATS client not initialized\")\n\t\treturn nil\n\t}\n\n\tvar wg sync.WaitGroup\n\tmsgs := make(chan []byte, max(workers*256, 8192))\n\n\tfor _, sc := range *Keys.Subscriptions {\n\t\tclusterTag := sc.ClusterTag\n\t\tif workers > 1 {\n\t\t\twg.Add(workers)\n\n\t\t\tfor range workers {\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tfor m := range msgs {\n\t\t\t\t\t\tdec := lineprotocol.NewDecoderWithBytes(m)\n\t\t\t\t\t\tif err := DecodeLine(dec, ms, clusterTag); err != nil {\n\t\t\t\t\t\t\tcclog.Errorf(\"error: %s\", err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\tnc.Subscribe(sc.SubscribeTo, func(subject string, data []byte) {\n\t\t\t\tselect {\n\t\t\t\tcase msgs <- data:\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t}\n\t\t\t})\n\t\t} else {\n\t\t\tnc.Subscribe(sc.SubscribeTo, func(subject string, data []byte) {\n\t\t\t\tdec := lineprotocol.NewDecoderWithBytes(data)\n\t\t\t\tif err := DecodeLine(dec, ms, clusterTag); err != nil {\n\t\t\t\t\tcclog.Errorf(\"error: %s\", err.Error())\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tcclog.Infof(\"NATS subscription to '%s' established\", sc.SubscribeTo)\n\t}\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tclose(msgs)\n\t}()\n\n\twg.Wait()\n\n\treturn nil\n}\n\n// reorder prepends prefix to buf in-place when buf has enough spare capacity,\n// avoiding an allocation. Falls back to a regular append otherwise.\n//\n// It is used to assemble the \"type<type-id>\" and \"subtype<stype-id>\" selector\n// strings when the type tag arrives before the type-id tag in the line, so the\n// two byte slices need to be concatenated in tag-declaration order regardless\n// of wire order.\nfunc reorder(buf, prefix []byte) []byte {\n\tn := len(prefix)\n\tm := len(buf)\n\tif cap(buf) < m+n {\n\t\treturn append(prefix[:n:n], buf...)\n\t} else {\n\t\tbuf = buf[:n+m]\n\t\tfor i := m - 1; i >= 0; i-- {\n\t\t\tbuf[i+n] = buf[i]\n\t\t}\n\t\tfor i := range n {\n\t\t\tbuf[i] = prefix[i]\n\t\t}\n\t\treturn buf\n\t}\n}\n\n// walDropped counts WAL messages dropped due to a full channel.\n// Logged periodically; not critical since binary snapshots capture the data.\nvar walDropped atomic.Int64\n\n// decodeState holds the per-call scratch buffers used by DecodeLine.\n// Instances are recycled via decodeStatePool to avoid repeated allocations\n// during high-throughput ingestion.\ntype decodeState struct {\n\t// metricBuf holds a copy of the current measurement name (line-protocol\n\t// measurement field). Copied because dec.Measurement() returns a slice\n\t// that is invalidated by the next decoder call.\n\tmetricBuf []byte\n\n\t// selector is the sub-device path passed to WriteToLevel and WALMessage\n\t// (e.g. [\"socket0\"] or [\"socket0\", \"memctrl1\"]). Reused across lines.\n\tselector []string\n\n\t// typeBuf accumulates the concatenated \"type\"+\"type-id\" tag value for the\n\t// current line. Reset at the start of each line's tag-decode loop.\n\ttypeBuf []byte\n\n\t// subTypeBuf accumulates the concatenated \"subtype\"+\"stype-id\" tag value.\n\t// Reset at the start of each line's tag-decode loop.\n\tsubTypeBuf []byte\n\n\t// prevTypeBytes / prevTypeStr cache the last seen typeBuf content and its\n\t// string conversion. Because consecutive lines in a batch typically address\n\t// the same sub-device, the cache hit rate is very high and avoids\n\t// repeated []byte→string allocations.\n\tprevTypeBytes []byte\n\tprevTypeStr string\n\n\t// prevSubTypeBytes / prevSubTypeStr are the same cache for the subtype.\n\tprevSubTypeBytes []byte\n\tprevSubTypeStr string\n}\n\n// decodeStatePool recycles decodeState values across DecodeLine calls to\n// reduce GC pressure during sustained metric ingestion.\nvar decodeStatePool = sync.Pool{\n\tNew: func() any {\n\t\treturn &decodeState{\n\t\t\tmetricBuf: make([]byte, 0, 16),\n\t\t\tselector: make([]string, 0, 4),\n\t\t\ttypeBuf: make([]byte, 0, 16),\n\t\t\tsubTypeBuf: make([]byte, 0, 16),\n\t\t}\n\t},\n}\n\n// DecodeLine reads all lines from dec (InfluxDB line-protocol) and writes each\n// decoded metric sample into ms.\n//\n// clusterDefault is used as the cluster name for lines that do not carry a\n// \"cluster\" tag. Callers typically supply the ClusterTag value from the NATS\n// subscription configuration.\n//\n// Performance notes:\n// - A decodeState is obtained from decodeStatePool to reuse scratch buffers.\n// - The Level pointer (host-level node in the metric tree) is cached across\n// consecutive lines that share the same cluster+host pair to avoid\n// repeated lock acquisitions on the root and cluster levels.\n// - []byte→string conversions for type/subtype selectors are cached via\n// prevType*/prevSubType* fields because batches typically repeat the same\n// sub-device identifiers.\n// - Timestamp parsing tries Second precision first; if that fails it retries\n// Millisecond, Microsecond, and Nanosecond in turn. A missing timestamp\n// falls back to time.Now().\n//\n// When the checkpoint format is \"wal\" each successfully decoded sample is also\n// sent to WALMessages so the WAL staging goroutine can persist it durably\n// before the next binary snapshot.\nfunc DecodeLine(dec *lineprotocol.Decoder,\n\tms *MemoryStore,\n\tclusterDefault string,\n) error {\n\t// Reduce allocations in loop:\n\tt := time.Now()\n\tmetric := Metric{}\n\tst := decodeStatePool.Get().(*decodeState)\n\tdefer decodeStatePool.Put(st)\n\n\t// Optimize for the case where all lines in a \"batch\" are about the same\n\t// cluster and host. By using `WriteToLevel` (level = host), we do not need\n\t// to take the root- and cluster-level lock as often.\n\tvar lvl *Level = nil\n\tprevCluster, prevHost := \"\", \"\"\n\n\tvar ok bool\n\tfor dec.Next() {\n\t\trawmeasurement, err := dec.Measurement()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Needs to be copied because another call to dec.* would\n\t\t// invalidate the returned slice.\n\t\tst.metricBuf = append(st.metricBuf[:0], rawmeasurement...)\n\n\t\t// The go compiler optimizes map[string(byteslice)] lookups:\n\t\tmetric.MetricConfig, ok = ms.Metrics[string(rawmeasurement)]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tst.typeBuf, st.subTypeBuf = st.typeBuf[:0], st.subTypeBuf[:0]\n\t\tcluster, host := clusterDefault, \"\"\n\t\tfor {\n\t\t\tkey, val, err := dec.NextTag()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif key == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// The go compiler optimizes string([]byte{...}) == \"...\":\n\t\t\tswitch string(key) {\n\t\t\tcase \"cluster\":\n\t\t\t\tif string(val) == prevCluster {\n\t\t\t\t\tcluster = prevCluster\n\t\t\t\t} else {\n\t\t\t\t\tcluster = string(val)\n\t\t\t\t\tlvl = nil\n\t\t\t\t}\n\t\t\tcase \"hostname\", \"host\":\n\t\t\t\tif string(val) == prevHost {\n\t\t\t\t\thost = prevHost\n\t\t\t\t} else {\n\t\t\t\t\thost = string(val)\n\t\t\t\t\tlvl = nil\n\t\t\t\t}\n\t\t\tcase \"type\":\n\t\t\t\tif string(val) == \"node\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// We cannot be sure that the \"type\" tag comes before the \"type-id\" tag:\n\t\t\t\tif len(st.typeBuf) == 0 {\n\t\t\t\t\tst.typeBuf = append(st.typeBuf, val...)\n\t\t\t\t} else {\n\t\t\t\t\tst.typeBuf = reorder(st.typeBuf, val)\n\t\t\t\t}\n\t\t\tcase \"type-id\":\n\t\t\t\tst.typeBuf = append(st.typeBuf, val...)\n\t\t\tcase \"subtype\":\n\t\t\t\t// We cannot be sure that the \"subtype\" tag comes before the \"stype-id\" tag:\n\t\t\t\tif len(st.subTypeBuf) == 0 {\n\t\t\t\t\tst.subTypeBuf = append(st.subTypeBuf, val...)\n\t\t\t\t} else {\n\t\t\t\t\tst.subTypeBuf = reorder(st.subTypeBuf, val)\n\t\t\t\t}\n\t\t\tcase \"stype-id\":\n\t\t\t\tst.subTypeBuf = append(st.subTypeBuf, val...)\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\n\t\t// If the cluster or host changed, the lvl was set to nil\n\t\tif lvl == nil {\n\t\t\tst.selector = st.selector[:2]\n\t\t\tst.selector[0], st.selector[1] = cluster, host\n\t\t\tlvl = ms.GetLevel(st.selector)\n\t\t\tprevCluster, prevHost = cluster, host\n\t\t}\n\n\t\t// subtypes: cache []byte→string conversions; messages in a batch typically\n\t\t// share the same type/subtype so the hit rate is very high.\n\t\tst.selector = st.selector[:0]\n\t\tif len(st.typeBuf) > 0 {\n\t\t\tif !bytes.Equal(st.typeBuf, st.prevTypeBytes) {\n\t\t\t\tst.prevTypeBytes = append(st.prevTypeBytes[:0], st.typeBuf...)\n\t\t\t\tst.prevTypeStr = string(st.typeBuf)\n\t\t\t}\n\t\t\tst.selector = append(st.selector, st.prevTypeStr)\n\t\t\tif len(st.subTypeBuf) > 0 {\n\t\t\t\tif !bytes.Equal(st.subTypeBuf, st.prevSubTypeBytes) {\n\t\t\t\t\tst.prevSubTypeBytes = append(st.prevSubTypeBytes[:0], st.subTypeBuf...)\n\t\t\t\t\tst.prevSubTypeStr = string(st.subTypeBuf)\n\t\t\t\t}\n\t\t\t\tst.selector = append(st.selector, st.prevSubTypeStr)\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tkey, val, err := dec.NextField()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif key == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif string(key) != \"value\" {\n\t\t\t\treturn fmt.Errorf(\"host %s: unknown field: '%s' (value: %#v)\", host, string(key), val)\n\t\t\t}\n\n\t\t\tif val.Kind() == lineprotocol.Float {\n\t\t\t\tmetric.Value = schema.Float(val.FloatV())\n\t\t\t} else if val.Kind() == lineprotocol.Int {\n\t\t\t\tmetric.Value = schema.Float(val.IntV())\n\t\t\t} else if val.Kind() == lineprotocol.Uint {\n\t\t\t\tmetric.Value = schema.Float(val.UintV())\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"host %s: unsupported value type in message: %s\", host, val.Kind().String())\n\t\t\t}\n\t\t}\n\n\t\tif t, err = dec.Time(lineprotocol.Second, t); err != nil {\n\t\t\tt = time.Now()\n\t\t\tif t, err = dec.Time(lineprotocol.Millisecond, t); err != nil {\n\t\t\t\tt = time.Now()\n\t\t\t\tif t, err = dec.Time(lineprotocol.Microsecond, t); err != nil {\n\t\t\t\t\tt = time.Now()\n\t\t\t\t\tif t, err = dec.Time(lineprotocol.Nanosecond, t); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"host %s: timestamp : %#v with error : %#v\", host, t, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"host %s: timestamp : %#v with error : %#v\", host, t, err.Error())\n\t\t}\n\n\t\ttime := t.Unix()\n\n\t\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\t\tmsg := &WALMessage{\n\t\t\t\tMetricName: string(st.metricBuf),\n\t\t\t\tCluster: cluster,\n\t\t\t\tNode: host,\n\t\t\t\tSelector: append([]string{}, st.selector...),\n\t\t\t\tValue: metric.Value,\n\t\t\t\tTimestamp: time,\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase WALMessages <- msg:\n\t\t\tdefault:\n\t\t\t\t// WAL channel full — metric is written to memory store but not WAL.\n\t\t\t\t// Next binary snapshot will capture it.\n\t\t\t\tif dropped := walDropped.Add(1); dropped%10000 == 1 {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> WAL channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err := ms.WriteToLevel(lvl, st.selector, time, []Metric{metric}); err != nil {\n\t\t\tcclog.Warnf(\"write error for host %s metric %s at ts %d: %s\", host, string(st.metricBuf), time, err.Error())\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}\n","numLines":382,"startLine":1,"totalLines":382}},"sourceToolAssistantUUID":"89e8ab32-1c9d-4c0d-b4c3-a3d9fad1a16b","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"b32930de-19da-45b1-b574-3e7fd25bbefa","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01XZzrun9oNQmo8YoM39V67m","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_012X88QcakG9hKNwYLbzPDDG","name":"Read","input":{"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/metricstore.go"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":11338,"cache_read_input_tokens":8666,"output_tokens":243,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":11338,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zeJVxWMXaD6uiZvMX5","type":"assistant","uuid":"857ea268-ae28-4dde-bae7-4a938c7bfc2c","timestamp":"2026-03-18T05:29:23.870Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"857ea268-ae28-4dde-bae7-4a938c7bfc2c","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Read","command":"callback"},"parentToolUseID":"toolu_012X88QcakG9hKNwYLbzPDDG","toolUseID":"toolu_012X88QcakG9hKNwYLbzPDDG","timestamp":"2026-03-18T05:29:24.073Z","uuid":"d08b51ca-1577-4630-b420-e4cf779fb853","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"857ea268-ae28-4dde-bae7-4a938c7bfc2c","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_012X88QcakG9hKNwYLbzPDDG","type":"tool_result","content":" 1→// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n 2→// All rights reserved. This file is part of cc-backend.\n 3→// Use of this source code is governed by a MIT-style\n 4→// license that can be found in the LICENSE file.\n 5→\n 6→// Package metricstore provides an efficient in-memory time-series metric storage system\n 7→// with support for hierarchical data organization, checkpointing, and archiving.\n 8→//\n 9→// The package organizes metrics in a tree structure (cluster → host → component) and\n 10→// provides concurrent read/write access to metric data with configurable aggregation strategies.\n 11→// Background goroutines handle periodic checkpointing (JSON or Avro format), archiving old data,\n 12→// and enforcing retention policies.\n 13→//\n 14→// Key features:\n 15→// - In-memory metric storage with configurable retention\n 16→// - Hierarchical data organization (selectors)\n 17→// - Concurrent checkpoint/archive workers\n 18→// - Support for sum and average aggregation\n 19→// - NATS integration for metric ingestion\n 20→package metricstore\n 21→\n 22→import (\n 23→\t\"bytes\"\n 24→\t\"context\"\n 25→\t\"encoding/json\"\n 26→\t\"errors\"\n 27→\t\"fmt\"\n 28→\t\"runtime\"\n 29→\t\"runtime/debug\"\n 30→\t\"slices\"\n 31→\t\"sync\"\n 32→\t\"time\"\n 33→\n 34→\t\"github.com/ClusterCockpit/cc-backend/internal/config\"\n 35→\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n 36→\t\"github.com/ClusterCockpit/cc-lib/v2/resampler\"\n 37→\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n 38→\t\"github.com/ClusterCockpit/cc-lib/v2/util\"\n 39→)\n 40→\n 41→// GlobalState holds the global state for the metric store with thread-safe access.\n 42→type GlobalState struct {\n 43→\tmu sync.RWMutex\n 44→\tlastRetentionTime int64\n 45→\tselectorsExcluded bool\n 46→}\n 47→\n 48→var (\n 49→\tsingleton sync.Once\n 50→\tmsInstance *MemoryStore\n 51→\t// shutdownFunc stores the context cancellation function created in Init\n 52→\t// and is called during Shutdown to cancel all background goroutines\n 53→\tshutdownFunc context.CancelFunc\n 54→\tshutdownFuncMu sync.Mutex // Protects shutdownFunc from concurrent access\n 55→\t// Create a global instance\n 56→\tstate = &GlobalState{}\n 57→)\n 58→\n 59→// NodeProvider provides information about nodes currently in use by running jobs.\n 60→//\n 61→// This interface allows metricstore to query job information without directly\n 62→// depending on the repository package, breaking the import cycle.\n 63→//\n 64→// Implementations should return nodes that are actively processing jobs started\n 65→// before the given timestamp. These nodes will be excluded from retention-based\n 66→// garbage collection to prevent data loss for jobs that are still running or\n 67→// recently completed.\n 68→type NodeProvider interface {\n 69→\t// GetUsedNodes returns a map of cluster names to sorted lists of unique hostnames\n 70→\t// that are currently in use by jobs that started before the given timestamp.\n 71→\t//\n 72→\t// Parameters:\n 73→\t// - ts: Unix timestamp threshold - returns nodes with jobs started before this time\n 74→\t//\n 75→\t// Returns:\n 76→\t// - Map of cluster names to lists of node hostnames that should be excluded from garbage collection\n 77→\t// - Error if the query fails\n 78→\tGetUsedNodes(ts int64) (map[string][]string, error)\n 79→}\n 80→\n 81→// Metric represents a single metric data point to be written to the store.\n 82→type Metric struct {\n 83→\tName string\n 84→\tValue schema.Float\n 85→\t// MetricConfig contains frequency and aggregation settings for this metric.\n 86→\t// If Frequency is 0, configuration will be looked up from MemoryStore.Metrics during Write().\n 87→\tMetricConfig MetricConfig\n 88→}\n 89→\n 90→// MemoryStore is the main in-memory time-series metric storage implementation.\n 91→//\n 92→// It organizes metrics in a hierarchical tree structure where each level represents\n 93→// a component of the system hierarchy (e.g., cluster → host → CPU). Each level can\n 94→// store multiple metrics as time-series buffers.\n 95→//\n 96→// The store is initialized as a singleton via InitMetrics() and accessed via GetMemoryStore().\n 97→// All public methods are safe for concurrent use.\n 98→type MemoryStore struct {\n 99→\tMetrics map[string]MetricConfig\n 100→\troot Level\n 101→\tnodeProvider NodeProvider\n 102→}\n 103→\n 104→// Init initializes the metric store from configuration and starts background workers.\n 105→//\n 106→// This function must be called exactly once before any other metricstore operations.\n 107→// It performs the following initialization steps:\n 108→// 1. Validates and decodes the metric store configuration\n 109→// 2. Configures worker pool size (defaults to NumCPU/2+1, max 10)\n 110→// 3. Loads metric configurations from all registered clusters\n 111→// 4. Restores checkpoints within the retention window\n 112→// 5. Starts background workers for retention, checkpointing, archiving, and monitoring\n 113→// 6. Optionally subscribes to NATS for real-time metric ingestion\n 114→//\n 115→// Parameters:\n 116→// - rawConfig: JSON configuration for the metric store (see MetricStoreConfig)\n 117→// - wg: WaitGroup that will be incremented for each background goroutine started\n 118→//\n 119→// The function will call cclog.Fatal on critical errors during initialization.\n 120→// Use Shutdown() to cleanly stop all background workers started by Init().\n 121→//\n 122→// Note: Signal handling must be implemented by the caller. Call Shutdown() when\n 123→// receiving termination signals to ensure checkpoint data is persisted.\n 124→func Init(rawConfig json.RawMessage, metrics map[string]MetricConfig, wg *sync.WaitGroup) {\n 125→\tstartupTime := time.Now()\n 126→\n 127→\tif rawConfig != nil {\n 128→\t\tconfig.Validate(configSchema, rawConfig)\n 129→\t\tdec := json.NewDecoder(bytes.NewReader(rawConfig))\n 130→\t\tdec.DisallowUnknownFields()\n 131→\t\tif err := dec.Decode(&Keys); err != nil {\n 132→\t\t\tcclog.Abortf(\"[METRICSTORE]> Metric Store Config Init: Could not decode config file '%s'.\\nError: %s\\n\", rawConfig, err.Error())\n 133→\t\t}\n 134→\t}\n 135→\n 136→\t// Set NumWorkers from config or use default\n 137→\tif Keys.NumWorkers <= 0 {\n 138→\t\tKeys.NumWorkers = min(runtime.NumCPU()/2+1, DefaultMaxWorkers)\n 139→\t}\n 140→\tcclog.Debugf(\"[METRICSTORE]> Using %d workers for checkpoint/archive operations\\n\", Keys.NumWorkers)\n 141→\n 142→\t// Pass the config.MetricStoreKeys\n 143→\tInitMetrics(metrics)\n 144→\n 145→\tms := GetMemoryStore()\n 146→\n 147→\td, err := time.ParseDuration(Keys.RetentionInMemory)\n 148→\tif err != nil {\n 149→\t\tcclog.Fatal(err)\n 150→\t}\n 151→\n 152→\trestoreFrom := startupTime.Add(-d)\n 153→\tcclog.Infof(\"[METRICSTORE]> Loading checkpoints newer than %s\\n\", restoreFrom.Format(time.RFC3339))\n 154→\tfiles, err := ms.FromCheckpointFiles(Keys.Checkpoints.RootDir, restoreFrom.Unix())\n 155→\tloadedData := ms.SizeInBytes() / 1024 / 1024 // In MB\n 156→\tif err != nil {\n 157→\t\tcclog.Fatalf(\"[METRICSTORE]> Loading checkpoints failed: %s\\n\", err.Error())\n 158→\t} else {\n 159→\t\tcclog.Infof(\"[METRICSTORE]> Checkpoints loaded (%d files, %d MB, that took %fs)\\n\", files, loadedData, time.Since(startupTime).Seconds())\n 160→\t}\n 161→\n 162→\t// Try to use less memory by forcing a GC run here and then\n 163→\t// lowering the target percentage. The default of 100 means\n 164→\t// that only once the ratio of new allocations execeds the\n 165→\t// previously active heap, a GC is triggered.\n 166→\t// Forcing a GC here will set the \"previously active heap\"\n 167→\t// to a minumum.\n 168→\t// runtime.GC()\n 169→\n 170→\tctx, shutdown := context.WithCancel(context.Background())\n 171→\n 172→\tRetention(wg, ctx)\n 173→\tCheckpointing(wg, ctx)\n 174→\tCleanUp(wg, ctx)\n 175→\tWALStaging(wg, ctx)\n 176→\tMemoryUsageTracker(wg, ctx)\n 177→\n 178→\t// Note: Signal handling has been removed from this function.\n 179→\t// The caller is responsible for handling shutdown signals and calling\n 180→\t// the shutdown() function when appropriate.\n 181→\t// Store the shutdown function for later use by Shutdown()\n 182→\tshutdownFuncMu.Lock()\n 183→\tshutdownFunc = shutdown\n 184→\tshutdownFuncMu.Unlock()\n 185→\n 186→\tif Keys.Subscriptions != nil {\n 187→\t\terr = ReceiveNats(ms, Keys.NumWorkers, ctx)\n 188→\t\tif err != nil {\n 189→\t\t\tcclog.Fatal(err)\n 190→\t\t}\n 191→\t}\n 192→}\n 193→\n 194→// InitMetrics initializes the singleton MemoryStore instance with the given metric configurations.\n 195→//\n 196→// This function must be called before GetMemoryStore() and can only be called once due to\n 197→// the singleton pattern. It assigns each metric an internal offset for efficient buffer indexing.\n 198→//\n 199→// Parameters:\n 200→// - metrics: Map of metric names to their configurations (frequency and aggregation strategy)\n 201→//\n 202→// Panics if any metric has Frequency == 0, which indicates an invalid configuration.\n 203→//\n 204→// After this call, the global msInstance is ready for use via GetMemoryStore().\n 205→func InitMetrics(metrics map[string]MetricConfig) {\n 206→\tsingleton.Do(func() {\n 207→\t\toffset := 0\n 208→\t\tfor key, cfg := range metrics {\n 209→\t\t\tif cfg.Frequency == 0 {\n 210→\t\t\t\tpanic(\"[METRICSTORE]> invalid frequency\")\n 211→\t\t\t}\n 212→\n 213→\t\t\tmetrics[key] = MetricConfig{\n 214→\t\t\t\tFrequency: cfg.Frequency,\n 215→\t\t\t\tAggregation: cfg.Aggregation,\n 216→\t\t\t\toffset: offset,\n 217→\t\t\t}\n 218→\t\t\toffset += 1\n 219→\t\t}\n 220→\n 221→\t\tmsInstance = &MemoryStore{\n 222→\t\t\troot: Level{\n 223→\t\t\t\tmetrics: make([]*buffer, len(metrics)),\n 224→\t\t\t\tchildren: make(map[string]*Level),\n 225→\t\t\t},\n 226→\t\t\tMetrics: metrics,\n 227→\t\t}\n 228→\t})\n 229→}\n 230→\n 231→// GetMemoryStore returns the singleton MemoryStore instance.\n 232→//\n 233→// Returns the initialized MemoryStore singleton. Calls cclog.Fatal if InitMetrics() was not called first.\n 234→//\n 235→// This function is safe for concurrent use after initialization.\n 236→func GetMemoryStore() *MemoryStore {\n 237→\tif msInstance == nil {\n 238→\t\tcclog.Warnf(\"[METRICSTORE]> MemoryStore not initialized!\")\n 239→\t}\n 240→\n 241→\treturn msInstance\n 242→}\n 243→\n 244→func (ms *MemoryStore) GetMetricFrequency(metricName string) (int64, error) {\n 245→\tif metric, ok := ms.Metrics[metricName]; ok {\n 246→\t\treturn metric.Frequency, nil\n 247→\t}\n 248→\treturn 0, fmt.Errorf(\"[METRICSTORE]> metric %s not found\", metricName)\n 249→}\n 250→\n 251→// SetNodeProvider sets the NodeProvider implementation for the MemoryStore.\n 252→// This must be called during initialization to provide job state information\n 253→// for selective buffer retention during Free operations.\n 254→// If not set, the Free function will fall back to freeing all buffers.\n 255→func (ms *MemoryStore) SetNodeProvider(provider NodeProvider) {\n 256→\tms.nodeProvider = provider\n 257→}\n 258→\n 259→// Shutdown performs a graceful shutdown of the metric store.\n 260→//\n 261→// This function cancels all background goroutines started by Init() and writes\n 262→// a final checkpoint to disk before returning. It should be called when the\n 263→// application receives a termination signal.\n 264→//\n 265→// The function will:\n 266→// 1. Cancel the context to stop all background workers\n 267→// 2. Close the WAL messages channel if using WAL format\n 268→// 3. Write a final checkpoint to preserve in-memory data\n 269→// 4. Log any errors encountered during shutdown\n 270→//\n 271→// Note: This function blocks until the final checkpoint is written.\n 272→func Shutdown() {\n 273→\tshutdownFuncMu.Lock()\n 274→\tdefer shutdownFuncMu.Unlock()\n 275→\tif shutdownFunc != nil {\n 276→\t\tshutdownFunc()\n 277→\t}\n 278→\n 279→\tif Keys.Checkpoints.FileFormat == \"wal\" {\n 280→\t\tclose(WALMessages)\n 281→\t}\n 282→\n 283→\tcclog.Infof(\"[METRICSTORE]> Writing to '%s'...\\n\", Keys.Checkpoints.RootDir)\n 284→\tvar files int\n 285→\tvar err error\n 286→\n 287→\tms := GetMemoryStore()\n 288→\n 289→\tlastCheckpointMu.Lock()\n 290→\tfrom := lastCheckpoint\n 291→\tlastCheckpointMu.Unlock()\n 292→\n 293→\tif Keys.Checkpoints.FileFormat == \"wal\" {\n 294→\t\tvar hostDirs []string\n 295→\t\tfiles, hostDirs, err = ms.ToCheckpointWAL(Keys.Checkpoints.RootDir, from.Unix(), time.Now().Unix())\n 296→\t\tif err == nil {\n 297→\t\t\tRotateWALFilesAfterShutdown(hostDirs)\n 298→\t\t}\n 299→\t} else {\n 300→\t\tfiles, err = ms.ToCheckpoint(Keys.Checkpoints.RootDir, from.Unix(), time.Now().Unix())\n 301→\t}\n 302→\n 303→\tif err != nil {\n 304→\t\tcclog.Errorf(\"[METRICSTORE]> Writing checkpoint failed: %s\\n\", err.Error())\n 305→\t}\n 306→\tcclog.Infof(\"[METRICSTORE]> Done! (%d files written)\\n\", files)\n 307→}\n 308→\n 309→// Retention starts a background goroutine that periodically frees old metric data.\n 310→//\n 311→// This worker runs at half the retention interval and calls Free() to remove buffers\n 312→// older than the configured retention time. It respects the NodeProvider to preserve\n 313→// data for nodes with active jobs.\n 314→//\n 315→// Parameters:\n 316→// - wg: WaitGroup to signal completion when context is cancelled\n 317→// - ctx: Context for cancellation signal\n 318→//\n 319→// The goroutine exits when ctx is cancelled.\n 320→func Retention(wg *sync.WaitGroup, ctx context.Context) {\n 321→\tms := GetMemoryStore()\n 322→\n 323→\twg.Go(func() {\n 324→\t\td, err := time.ParseDuration(Keys.RetentionInMemory)\n 325→\t\tif err != nil {\n 326→\t\t\tcclog.Fatal(err)\n 327→\t\t}\n 328→\t\tif d <= 0 {\n 329→\t\t\treturn\n 330→\t\t}\n 331→\n 332→\t\ttickInterval := d / 2\n 333→\t\tif tickInterval <= 0 {\n 334→\t\t\treturn\n 335→\t\t}\n 336→\t\tticker := time.NewTicker(tickInterval)\n 337→\t\tdefer ticker.Stop()\n 338→\n 339→\t\tfor {\n 340→\t\t\tselect {\n 341→\t\t\tcase <-ctx.Done():\n 342→\t\t\t\treturn\n 343→\t\t\tcase <-ticker.C:\n 344→\t\t\t\tstate.mu.Lock()\n 345→\n 346→\t\t\t\tt := time.Now().Add(-d)\n 347→\n 348→\t\t\t\tstate.lastRetentionTime = t.Unix()\n 349→\n 350→\t\t\t\tcclog.Infof(\"[METRICSTORE]> start freeing buffers (older than %s)...\\n\", t.Format(time.RFC3339))\n 351→\n 352→\t\t\t\tfreed, err := Free(ms, t)\n 353→\t\t\t\tif err != nil {\n 354→\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> freeing up buffers failed: %s\\n\", err.Error())\n 355→\t\t\t\t} else {\n 356→\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> done: %d buffers freed\\n\", freed)\n 357→\t\t\t\t}\n 358→\n 359→\t\t\t\tstate.mu.Unlock()\n 360→\n 361→\t\t\t\t// Clean up the buffer pool\n 362→\t\t\t\tbufferPool.Clean(state.lastRetentionTime)\n 363→\t\t\t}\n 364→\t\t}\n 365→\t})\n 366→}\n 367→\n 368→// MemoryUsageTracker starts a background goroutine that monitors memory usage.\n 369→//\n 370→// This worker checks actual process memory usage (via runtime.MemStats) periodically\n 371→// and force-frees buffers if memory exceeds the configured cap. It uses FreeOSMemory()\n 372→// to return memory to the OS after freeing buffers, avoiding aggressive GC that causes\n 373→// performance issues.\n 374→//\n 375→// The tracker logs both actual memory usage (heap allocated) and metric data size for\n 376→// visibility into memory overhead from Go runtime structures and allocations.\n 377→//\n 378→// Parameters:\n 379→// - wg: WaitGroup to signal completion when context is cancelled\n 380→// - ctx: Context for cancellation signal\n 381→//\n 382→// The goroutine exits when ctx is cancelled.\n 383→func MemoryUsageTracker(wg *sync.WaitGroup, ctx context.Context) {\n 384→\tms := GetMemoryStore()\n 385→\n 386→\twg.Go(func() {\n 387→\t\tnormalInterval := DefaultMemoryUsageTrackerInterval\n 388→\t\tfastInterval := 30 * time.Second\n 389→\n 390→\t\tif normalInterval <= 0 {\n 391→\t\t\treturn\n 392→\t\t}\n 393→\n 394→\t\tticker := time.NewTicker(normalInterval)\n 395→\t\tdefer ticker.Stop()\n 396→\t\tcurrentInterval := normalInterval\n 397→\n 398→\t\tfor {\n 399→\t\t\tselect {\n 400→\t\t\tcase <-ctx.Done():\n 401→\t\t\t\treturn\n 402→\t\t\tcase <-ticker.C:\n 403→\t\t\t\tvar mem runtime.MemStats\n 404→\t\t\t\truntime.ReadMemStats(&mem)\n 405→\t\t\t\tactualMemoryGB := float64(mem.Alloc) / 1e9\n 406→\t\t\t\tmetricDataGB := ms.SizeInGB()\n 407→\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory usage: %.2f GB actual (%.2f GB metric data)\", actualMemoryGB, metricDataGB)\n 408→\n 409→\t\t\t\tfreedExcluded := 0\n 410→\t\t\t\tfreedEmergency := 0\n 411→\t\t\t\tvar err error\n 412→\n 413→\t\t\t\tstate.mu.RLock()\n 414→\t\t\t\tlastRetention := state.lastRetentionTime\n 415→\t\t\t\tselectorsExcluded := state.selectorsExcluded\n 416→\t\t\t\tstate.mu.RUnlock()\n 417→\n 418→\t\t\t\tif lastRetention != 0 && selectorsExcluded {\n 419→\t\t\t\t\tfreedExcluded, err = ms.Free(nil, lastRetention)\n 420→\t\t\t\t\tif err != nil {\n 421→\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> error while force-freeing the excluded buffers: %s\", err)\n 422→\t\t\t\t\t}\n 423→\n 424→\t\t\t\t\tif freedExcluded > 0 {\n 425→\t\t\t\t\t\tdebug.FreeOSMemory()\n 426→\t\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> done: %d excluded buffers force-freed\", freedExcluded)\n 427→\t\t\t\t\t}\n 428→\t\t\t\t}\n 429→\n 430→\t\t\t\truntime.ReadMemStats(&mem)\n 431→\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n 432→\n 433→\t\t\t\tif actualMemoryGB > float64(Keys.MemoryCap) {\n 434→\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> memory usage %.2f GB exceeds cap %d GB, starting emergency buffer freeing\", actualMemoryGB, Keys.MemoryCap)\n 435→\n 436→\t\t\t\t\t// Use progressive time-based Free with increasing threshold\n 437→\t\t\t\t\t// instead of ForceFree loop — fewer tree traversals, more effective\n 438→\t\t\t\t\td, parseErr := time.ParseDuration(Keys.RetentionInMemory)\n 439→\t\t\t\t\tif parseErr != nil {\n 440→\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> cannot parse retention duration: %s\", parseErr)\n 441→\t\t\t\t\t} else {\n 442→\t\t\t\t\t\tthresholds := []float64{0.75, 0.5, 0.25}\n 443→\t\t\t\t\t\tfor _, fraction := range thresholds {\n 444→\t\t\t\t\t\t\tthreshold := time.Now().Add(-time.Duration(float64(d) * fraction))\n 445→\t\t\t\t\t\t\tfreed, freeErr := ms.Free(nil, threshold.Unix())\n 446→\t\t\t\t\t\t\tif freeErr != nil {\n 447→\t\t\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> error while freeing buffers at %.0f%% retention: %s\", fraction*100, freeErr)\n 448→\t\t\t\t\t\t\t}\n 449→\t\t\t\t\t\t\tfreedEmergency += freed\n 450→\n 451→\t\t\t\t\t\t\tbufferPool.Clear()\n 452→\t\t\t\t\t\t\truntime.GC()\n 453→\t\t\t\t\t\t\truntime.ReadMemStats(&mem)\n 454→\t\t\t\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n 455→\n 456→\t\t\t\t\t\t\tif actualMemoryGB < float64(Keys.MemoryCap) {\n 457→\t\t\t\t\t\t\t\tbreak\n 458→\t\t\t\t\t\t\t}\n 459→\t\t\t\t\t\t}\n 460→\t\t\t\t\t}\n 461→\n 462→\t\t\t\t\tbufferPool.Clear()\n 463→\t\t\t\t\tdebug.FreeOSMemory()\n 464→\n 465→\t\t\t\t\truntime.ReadMemStats(&mem)\n 466→\t\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n 467→\n 468→\t\t\t\t\tif actualMemoryGB >= float64(Keys.MemoryCap) {\n 469→\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> after emergency frees (%d buffers), memory usage %.2f GB still at/above cap %d GB\", freedEmergency, actualMemoryGB, Keys.MemoryCap)\n 470→\t\t\t\t\t} else {\n 471→\t\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> emergency freeing complete: %d buffers freed, memory now %.2f GB\", freedEmergency, actualMemoryGB)\n 472→\t\t\t\t\t}\n 473→\t\t\t\t}\n 474→\n 475→\t\t\t\t// Adaptive ticker: check more frequently when memory is high\n 476→\t\t\t\tmemoryRatio := actualMemoryGB / float64(Keys.MemoryCap)\n 477→\t\t\t\tif memoryRatio > 0.8 && currentInterval != fastInterval {\n 478→\t\t\t\t\tticker.Reset(fastInterval)\n 479→\t\t\t\t\tcurrentInterval = fastInterval\n 480→\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory at %.0f%% of cap, switching to fast check interval (30s)\", memoryRatio*100)\n 481→\t\t\t\t} else if memoryRatio <= 0.8 && currentInterval != normalInterval {\n 482→\t\t\t\t\tticker.Reset(normalInterval)\n 483→\t\t\t\t\tcurrentInterval = normalInterval\n 484→\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory at %.0f%% of cap, switching to normal check interval\", memoryRatio*100)\n 485→\t\t\t\t}\n 486→\t\t\t}\n 487→\t\t}\n 488→\t})\n 489→}\n 490→\n 491→// Free removes metric data older than the given time while preserving data for active nodes.\n 492→//\n 493→// This function implements intelligent retention by consulting the NodeProvider (if configured)\n 494→// to determine which nodes are currently in use by running jobs. Data for these nodes is\n 495→// preserved even if older than the retention time.\n 496→//\n 497→// Parameters:\n 498→// - ms: The MemoryStore instance\n 499→// - t: Time threshold - buffers with data older than this will be freed\n 500→//\n 501→// Returns:\n 502→// - Number of buffers freed\n 503→// - Error if NodeProvider query fails\n 504→//\n 505→// Behavior:\n 506→// - If no NodeProvider is set: frees all buffers older than t\n 507→// - If NodeProvider returns empty map: frees all buffers older than t\n 508→// - Otherwise: preserves buffers for nodes returned by GetUsedNodes(), frees others\n 509→func Free(ms *MemoryStore, t time.Time) (int, error) {\n 510→\t// If no NodeProvider is configured, free all buffers older than t\n 511→\tif ms.nodeProvider == nil {\n 512→\t\treturn ms.Free(nil, t.Unix())\n 513→\t}\n 514→\n 515→\texcludeSelectors, err := ms.nodeProvider.GetUsedNodes(t.Unix())\n 516→\tif err != nil {\n 517→\t\treturn 0, err\n 518→\t}\n 519→\n 520→\tswitch lenMap := len(excludeSelectors); lenMap {\n 521→\n 522→\t// If the length of the map returned by GetUsedNodes() is 0,\n 523→\t// then use default Free method with nil selector\n 524→\tcase 0:\n 525→\t\tstate.selectorsExcluded = false\n 526→\t\treturn ms.Free(nil, t.Unix())\n 527→\n 528→\t// Else formulate selectors, exclude those from the map\n 529→\t// and free the rest of the selectors\n 530→\tdefault:\n 531→\t\tstate.selectorsExcluded = true\n 532→\t\tselectors := GetSelectors(ms, excludeSelectors)\n 533→\t\treturn FreeSelected(ms, selectors, t)\n 534→\t}\n 535→}\n 536→\n 537→// FreeSelected frees buffers for specific selectors while preserving others.\n 538→//\n 539→// This function is used when we want to retain some specific nodes beyond the retention time.\n 540→// It iterates through the provided selectors and frees their associated buffers.\n 541→//\n 542→// Parameters:\n 543→// - ms: The MemoryStore instance\n 544→// - selectors: List of selector paths to free (e.g., [[\"cluster1\", \"node1\"], [\"cluster2\", \"node2\"]])\n 545→// - t: Time threshold for freeing buffers\n 546→//\n 547→// Returns the total number of buffers freed and any error encountered.\n 548→func FreeSelected(ms *MemoryStore, selectors [][]string, t time.Time) (int, error) {\n 549→\tfreed := 0\n 550→\n 551→\tfor _, selector := range selectors {\n 552→\n 553→\t\tfreedBuffers, err := ms.Free(selector, t.Unix())\n 554→\t\tif err != nil {\n 555→\t\t\tcclog.Errorf(\"error while freeing selected buffers: %#v\", err)\n 556→\t\t}\n 557→\t\tfreed += freedBuffers\n 558→\n 559→\t}\n 560→\n 561→\treturn freed, nil\n 562→}\n 563→\n 564→// GetSelectors returns all selectors at depth 2 (cluster/node level) that are NOT in the exclusion map.\n 565→//\n 566→// This function generates a list of selectors whose buffers should be freed by excluding\n 567→// selectors that correspond to nodes currently in use by running jobs.\n 568→//\n 569→// Parameters:\n 570→// - ms: The MemoryStore instance\n 571→// - excludeSelectors: Map of cluster names to node hostnames that should NOT be freed\n 572→//\n 573→// Returns a list of selectors ([]string paths) that can be safely freed.\n 574→//\n 575→// Example:\n 576→//\n 577→//\tIf the tree has paths [\"emmy\", \"node001\"] and [\"emmy\", \"node002\"],\n 578→//\tand excludeSelectors contains {\"emmy\": [\"node001\"]},\n 579→//\tthen only [[\"emmy\", \"node002\"]] is returned.\n 580→func GetSelectors(ms *MemoryStore, excludeSelectors map[string][]string) [][]string {\n 581→\tallSelectors := ms.GetPaths(2)\n 582→\n 583→\tfilteredSelectors := make([][]string, 0, len(allSelectors))\n 584→\n 585→\tfor _, path := range allSelectors {\n 586→\t\tif len(path) < 2 {\n 587→\t\t\tcontinue\n 588→\t\t}\n 589→\n 590→\t\tkey := path[0] // The \"Key\" (Level 1)\n 591→\t\tvalue := path[1] // The \"Value\" (Level 2)\n 592→\n 593→\t\texclude := false\n 594→\n 595→\t\t// Check if the key exists in our exclusion map\n 596→\t\tif excludedValues, exists := excludeSelectors[key]; exists {\n 597→\t\t\t// The key exists, now check if the specific value is in the exclusion list\n 598→\t\t\tif slices.Contains(excludedValues, value) {\n 599→\t\t\t\texclude = true\n 600→\t\t\t}\n 601→\t\t}\n 602→\n 603→\t\tif !exclude {\n 604→\t\t\tfilteredSelectors = append(filteredSelectors, path)\n 605→\t\t}\n 606→\t}\n 607→\n 608→\treturn filteredSelectors\n 609→}\n 610→\n 611→// GetPaths returns a list of lists (paths) to the specified depth.\n 612→func (ms *MemoryStore) GetPaths(targetDepth int) [][]string {\n 613→\tvar results [][]string\n 614→\n 615→\t// Start recursion. Initial path is empty.\n 616→\t// We treat Root as depth 0.\n 617→\tms.root.collectPaths(0, targetDepth, []string{}, &results)\n 618→\n 619→\treturn results\n 620→}\n 621→\n 622→// Write all values in `metrics` to the level specified by `selector` for time `ts`.\n 623→// Look at `findLevelOrCreate` for how selectors work.\n 624→func (m *MemoryStore) Write(selector []string, ts int64, metrics []Metric) error {\n 625→\tvar ok bool\n 626→\tfor i, metric := range metrics {\n 627→\t\tif metric.MetricConfig.Frequency == 0 {\n 628→\t\t\tmetric.MetricConfig, ok = m.Metrics[metric.Name]\n 629→\t\t\tif !ok {\n 630→\t\t\t\tcclog.Debugf(\"[METRICSTORE]> Unknown metric '%s' in Write() - skipping\", metric.Name)\n 631→\t\t\t\tmetric.MetricConfig.Frequency = 0\n 632→\t\t\t}\n 633→\t\t\tmetrics[i] = metric\n 634→\t\t}\n 635→\t}\n 636→\n 637→\treturn m.WriteToLevel(&m.root, selector, ts, metrics)\n 638→}\n 639→\n 640→func (m *MemoryStore) GetLevel(selector []string) *Level {\n 641→\treturn m.root.findLevelOrCreate(selector, len(m.Metrics))\n 642→}\n 643→\n 644→// WriteToLevel assumes that `minfo` in `metrics` is filled in\n 645→func (m *MemoryStore) WriteToLevel(l *Level, selector []string, ts int64, metrics []Metric) error {\n 646→\tl = l.findLevelOrCreate(selector, len(m.Metrics))\n 647→\tl.lock.Lock()\n 648→\tdefer l.lock.Unlock()\n 649→\n 650→\tfor _, metric := range metrics {\n 651→\t\tif metric.MetricConfig.Frequency == 0 {\n 652→\t\t\tcontinue\n 653→\t\t}\n 654→\n 655→\t\tb := l.metrics[metric.MetricConfig.offset]\n 656→\t\tif b == nil {\n 657→\t\t\t// First write to this metric and level\n 658→\t\t\tb = newBuffer(ts, metric.MetricConfig.Frequency)\n 659→\t\t\tl.metrics[metric.MetricConfig.offset] = b\n 660→\t\t}\n 661→\n 662→\t\tnb, err := b.write(ts, metric.Value)\n 663→\t\tif err != nil {\n 664→\t\t\treturn err\n 665→\t\t}\n 666→\n 667→\t\t// Last write created a new buffer...\n 668→\t\tif b != nb {\n 669→\t\t\tl.metrics[metric.MetricConfig.offset] = nb\n 670→\t\t}\n 671→\t}\n 672→\treturn nil\n 673→}\n 674→\n 675→// Read returns all values for metric `metric` from `from` to `to` for the selected level(s).\n 676→// If the level does not hold the metric itself, the data will be aggregated recursively from the children.\n 677→// The second and third return value are the actual from/to for the data. Those can be different from\n 678→// the range asked for if no data was available.\n 679→func (m *MemoryStore) Read(selector util.Selector, metric string, from, to, resolution int64) ([]schema.Float, int64, int64, int64, error) {\n 680→\tif from > to {\n 681→\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> invalid time range\")\n 682→\t}\n 683→\n 684→\tminfo, ok := m.Metrics[metric]\n 685→\tif !ok {\n 686→\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> unknown metric: \" + metric)\n 687→\t}\n 688→\n 689→\tn, data := 0, make([]schema.Float, (to-from)/minfo.Frequency+1)\n 690→\n 691→\terr := m.root.findBuffers(selector, minfo.offset, func(b *buffer) error {\n 692→\t\tcdata, cfrom, cto, err := b.read(from, to, data)\n 693→\t\tif err != nil {\n 694→\t\t\treturn err\n 695→\t\t}\n 696→\n 697→\t\tif n == 0 {\n 698→\t\t\tfrom, to = cfrom, cto\n 699→\t\t} else if from != cfrom || to != cto || len(data) != len(cdata) {\n 700→\t\t\tmissingfront, missingback := int((from-cfrom)/minfo.Frequency), int((to-cto)/minfo.Frequency)\n 701→\t\t\tif missingfront != 0 {\n 702→\t\t\t\treturn ErrDataDoesNotAlign\n 703→\t\t\t}\n 704→\n 705→\t\t\tnewlen := len(cdata) - missingback\n 706→\t\t\tif newlen < 1 {\n 707→\t\t\t\treturn ErrDataDoesNotAlign\n 708→\t\t\t}\n 709→\t\t\tcdata = cdata[0:newlen]\n 710→\t\t\tif len(cdata) != len(data) {\n 711→\t\t\t\treturn ErrDataDoesNotAlign\n 712→\t\t\t}\n 713→\n 714→\t\t\tfrom, to = cfrom, cto\n 715→\t\t}\n 716→\n 717→\t\tdata = cdata\n 718→\t\tn += 1\n 719→\t\treturn nil\n 720→\t})\n 721→\n 722→\tif err != nil {\n 723→\t\treturn nil, 0, 0, 0, err\n 724→\t} else if n == 0 {\n 725→\t\treturn nil, 0, 0, 0, ErrNoHostOrMetric\n 726→\t} else if n > 1 {\n 727→\t\tif minfo.Aggregation == AvgAggregation {\n 728→\t\t\tnormalize := 1. / schema.Float(n)\n 729→\t\t\tfor i := 0; i < len(data); i++ {\n 730→\t\t\t\tdata[i] *= normalize\n 731→\t\t\t}\n 732→\t\t} else if minfo.Aggregation != SumAggregation {\n 733→\t\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> invalid aggregation\")\n 734→\t\t}\n 735→\t}\n 736→\n 737→\tdata, resolution, err = resampler.LargestTriangleThreeBucket(data, minfo.Frequency, resolution)\n 738→\tif err != nil {\n 739→\t\treturn nil, 0, 0, 0, err\n 740→\t}\n 741→\n 742→\treturn data, from, to, resolution, nil\n 743→}\n 744→\n 745→// Free releases all buffers for the selected level and all its children that\n 746→// contain only values older than `t`.\n 747→func (m *MemoryStore) Free(selector []string, t int64) (int, error) {\n 748→\treturn m.GetLevel(selector).free(t)\n 749→}\n 750→\n 751→// ForceFree unconditionally removes the oldest buffer from each metric chain.\n 752→func (m *MemoryStore) ForceFree() (int, error) {\n 753→\treturn m.GetLevel(nil).forceFree()\n 754→}\n 755→\n 756→func (m *MemoryStore) FreeAll() error {\n 757→\tm.root.lock.Lock()\n 758→\tdefer m.root.lock.Unlock()\n 759→\n 760→\tfor k := range m.root.children {\n 761→\t\tdelete(m.root.children, k)\n 762→\t}\n 763→\n 764→\treturn nil\n 765→}\n 766→\n 767→func (m *MemoryStore) SizeInBytes() int64 {\n 768→\treturn m.root.sizeInBytes()\n 769→}\n 770→\n 771→func (m *MemoryStore) SizeInGB() float64 {\n 772→\treturn float64(m.root.sizeInBytes()) / 1e9\n 773→}\n 774→\n 775→// ListChildren , given a selector, returns a list of all children of the level\n 776→// selected.\n 777→func (m *MemoryStore) ListChildren(selector []string) []string {\n 778→\tlvl := &m.root\n 779→\tfor lvl != nil && len(selector) != 0 {\n 780→\t\tlvl.lock.RLock()\n 781→\t\tnext := lvl.children[selector[0]]\n 782→\t\tlvl.lock.RUnlock()\n 783→\t\tlvl = next\n 784→\t\tselector = selector[1:]\n 785→\t}\n 786→\n 787→\tif lvl == nil {\n 788→\t\treturn nil\n 789→\t}\n 790→\n 791→\tlvl.lock.RLock()\n 792→\tdefer lvl.lock.RUnlock()\n 793→\n 794→\tchildren := make([]string, 0, len(lvl.children))\n 795→\tfor child := range lvl.children {\n 796→\t\tchildren = append(children, child)\n 797→\t}\n 798→\n 799→\treturn children\n 800→}\n 801→"}]},"uuid":"0f4c1787-87de-49e0-99d1-bfbd5aed3be2","timestamp":"2026-03-18T05:29:24.072Z","toolUseResult":{"type":"text","file":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/metricstore.go","content":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides an efficient in-memory time-series metric storage system\n// with support for hierarchical data organization, checkpointing, and archiving.\n//\n// The package organizes metrics in a tree structure (cluster → host → component) and\n// provides concurrent read/write access to metric data with configurable aggregation strategies.\n// Background goroutines handle periodic checkpointing (JSON or Avro format), archiving old data,\n// and enforcing retention policies.\n//\n// Key features:\n// - In-memory metric storage with configurable retention\n// - Hierarchical data organization (selectors)\n// - Concurrent checkpoint/archive workers\n// - Support for sum and average aggregation\n// - NATS integration for metric ingestion\npackage metricstore\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"slices\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ClusterCockpit/cc-backend/internal/config\"\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/resampler\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/util\"\n)\n\n// GlobalState holds the global state for the metric store with thread-safe access.\ntype GlobalState struct {\n\tmu sync.RWMutex\n\tlastRetentionTime int64\n\tselectorsExcluded bool\n}\n\nvar (\n\tsingleton sync.Once\n\tmsInstance *MemoryStore\n\t// shutdownFunc stores the context cancellation function created in Init\n\t// and is called during Shutdown to cancel all background goroutines\n\tshutdownFunc context.CancelFunc\n\tshutdownFuncMu sync.Mutex // Protects shutdownFunc from concurrent access\n\t// Create a global instance\n\tstate = &GlobalState{}\n)\n\n// NodeProvider provides information about nodes currently in use by running jobs.\n//\n// This interface allows metricstore to query job information without directly\n// depending on the repository package, breaking the import cycle.\n//\n// Implementations should return nodes that are actively processing jobs started\n// before the given timestamp. These nodes will be excluded from retention-based\n// garbage collection to prevent data loss for jobs that are still running or\n// recently completed.\ntype NodeProvider interface {\n\t// GetUsedNodes returns a map of cluster names to sorted lists of unique hostnames\n\t// that are currently in use by jobs that started before the given timestamp.\n\t//\n\t// Parameters:\n\t// - ts: Unix timestamp threshold - returns nodes with jobs started before this time\n\t//\n\t// Returns:\n\t// - Map of cluster names to lists of node hostnames that should be excluded from garbage collection\n\t// - Error if the query fails\n\tGetUsedNodes(ts int64) (map[string][]string, error)\n}\n\n// Metric represents a single metric data point to be written to the store.\ntype Metric struct {\n\tName string\n\tValue schema.Float\n\t// MetricConfig contains frequency and aggregation settings for this metric.\n\t// If Frequency is 0, configuration will be looked up from MemoryStore.Metrics during Write().\n\tMetricConfig MetricConfig\n}\n\n// MemoryStore is the main in-memory time-series metric storage implementation.\n//\n// It organizes metrics in a hierarchical tree structure where each level represents\n// a component of the system hierarchy (e.g., cluster → host → CPU). Each level can\n// store multiple metrics as time-series buffers.\n//\n// The store is initialized as a singleton via InitMetrics() and accessed via GetMemoryStore().\n// All public methods are safe for concurrent use.\ntype MemoryStore struct {\n\tMetrics map[string]MetricConfig\n\troot Level\n\tnodeProvider NodeProvider\n}\n\n// Init initializes the metric store from configuration and starts background workers.\n//\n// This function must be called exactly once before any other metricstore operations.\n// It performs the following initialization steps:\n// 1. Validates and decodes the metric store configuration\n// 2. Configures worker pool size (defaults to NumCPU/2+1, max 10)\n// 3. Loads metric configurations from all registered clusters\n// 4. Restores checkpoints within the retention window\n// 5. Starts background workers for retention, checkpointing, archiving, and monitoring\n// 6. Optionally subscribes to NATS for real-time metric ingestion\n//\n// Parameters:\n// - rawConfig: JSON configuration for the metric store (see MetricStoreConfig)\n// - wg: WaitGroup that will be incremented for each background goroutine started\n//\n// The function will call cclog.Fatal on critical errors during initialization.\n// Use Shutdown() to cleanly stop all background workers started by Init().\n//\n// Note: Signal handling must be implemented by the caller. Call Shutdown() when\n// receiving termination signals to ensure checkpoint data is persisted.\nfunc Init(rawConfig json.RawMessage, metrics map[string]MetricConfig, wg *sync.WaitGroup) {\n\tstartupTime := time.Now()\n\n\tif rawConfig != nil {\n\t\tconfig.Validate(configSchema, rawConfig)\n\t\tdec := json.NewDecoder(bytes.NewReader(rawConfig))\n\t\tdec.DisallowUnknownFields()\n\t\tif err := dec.Decode(&Keys); err != nil {\n\t\t\tcclog.Abortf(\"[METRICSTORE]> Metric Store Config Init: Could not decode config file '%s'.\\nError: %s\\n\", rawConfig, err.Error())\n\t\t}\n\t}\n\n\t// Set NumWorkers from config or use default\n\tif Keys.NumWorkers <= 0 {\n\t\tKeys.NumWorkers = min(runtime.NumCPU()/2+1, DefaultMaxWorkers)\n\t}\n\tcclog.Debugf(\"[METRICSTORE]> Using %d workers for checkpoint/archive operations\\n\", Keys.NumWorkers)\n\n\t// Pass the config.MetricStoreKeys\n\tInitMetrics(metrics)\n\n\tms := GetMemoryStore()\n\n\td, err := time.ParseDuration(Keys.RetentionInMemory)\n\tif err != nil {\n\t\tcclog.Fatal(err)\n\t}\n\n\trestoreFrom := startupTime.Add(-d)\n\tcclog.Infof(\"[METRICSTORE]> Loading checkpoints newer than %s\\n\", restoreFrom.Format(time.RFC3339))\n\tfiles, err := ms.FromCheckpointFiles(Keys.Checkpoints.RootDir, restoreFrom.Unix())\n\tloadedData := ms.SizeInBytes() / 1024 / 1024 // In MB\n\tif err != nil {\n\t\tcclog.Fatalf(\"[METRICSTORE]> Loading checkpoints failed: %s\\n\", err.Error())\n\t} else {\n\t\tcclog.Infof(\"[METRICSTORE]> Checkpoints loaded (%d files, %d MB, that took %fs)\\n\", files, loadedData, time.Since(startupTime).Seconds())\n\t}\n\n\t// Try to use less memory by forcing a GC run here and then\n\t// lowering the target percentage. The default of 100 means\n\t// that only once the ratio of new allocations execeds the\n\t// previously active heap, a GC is triggered.\n\t// Forcing a GC here will set the \"previously active heap\"\n\t// to a minumum.\n\t// runtime.GC()\n\n\tctx, shutdown := context.WithCancel(context.Background())\n\n\tRetention(wg, ctx)\n\tCheckpointing(wg, ctx)\n\tCleanUp(wg, ctx)\n\tWALStaging(wg, ctx)\n\tMemoryUsageTracker(wg, ctx)\n\n\t// Note: Signal handling has been removed from this function.\n\t// The caller is responsible for handling shutdown signals and calling\n\t// the shutdown() function when appropriate.\n\t// Store the shutdown function for later use by Shutdown()\n\tshutdownFuncMu.Lock()\n\tshutdownFunc = shutdown\n\tshutdownFuncMu.Unlock()\n\n\tif Keys.Subscriptions != nil {\n\t\terr = ReceiveNats(ms, Keys.NumWorkers, ctx)\n\t\tif err != nil {\n\t\t\tcclog.Fatal(err)\n\t\t}\n\t}\n}\n\n// InitMetrics initializes the singleton MemoryStore instance with the given metric configurations.\n//\n// This function must be called before GetMemoryStore() and can only be called once due to\n// the singleton pattern. It assigns each metric an internal offset for efficient buffer indexing.\n//\n// Parameters:\n// - metrics: Map of metric names to their configurations (frequency and aggregation strategy)\n//\n// Panics if any metric has Frequency == 0, which indicates an invalid configuration.\n//\n// After this call, the global msInstance is ready for use via GetMemoryStore().\nfunc InitMetrics(metrics map[string]MetricConfig) {\n\tsingleton.Do(func() {\n\t\toffset := 0\n\t\tfor key, cfg := range metrics {\n\t\t\tif cfg.Frequency == 0 {\n\t\t\t\tpanic(\"[METRICSTORE]> invalid frequency\")\n\t\t\t}\n\n\t\t\tmetrics[key] = MetricConfig{\n\t\t\t\tFrequency: cfg.Frequency,\n\t\t\t\tAggregation: cfg.Aggregation,\n\t\t\t\toffset: offset,\n\t\t\t}\n\t\t\toffset += 1\n\t\t}\n\n\t\tmsInstance = &MemoryStore{\n\t\t\troot: Level{\n\t\t\t\tmetrics: make([]*buffer, len(metrics)),\n\t\t\t\tchildren: make(map[string]*Level),\n\t\t\t},\n\t\t\tMetrics: metrics,\n\t\t}\n\t})\n}\n\n// GetMemoryStore returns the singleton MemoryStore instance.\n//\n// Returns the initialized MemoryStore singleton. Calls cclog.Fatal if InitMetrics() was not called first.\n//\n// This function is safe for concurrent use after initialization.\nfunc GetMemoryStore() *MemoryStore {\n\tif msInstance == nil {\n\t\tcclog.Warnf(\"[METRICSTORE]> MemoryStore not initialized!\")\n\t}\n\n\treturn msInstance\n}\n\nfunc (ms *MemoryStore) GetMetricFrequency(metricName string) (int64, error) {\n\tif metric, ok := ms.Metrics[metricName]; ok {\n\t\treturn metric.Frequency, nil\n\t}\n\treturn 0, fmt.Errorf(\"[METRICSTORE]> metric %s not found\", metricName)\n}\n\n// SetNodeProvider sets the NodeProvider implementation for the MemoryStore.\n// This must be called during initialization to provide job state information\n// for selective buffer retention during Free operations.\n// If not set, the Free function will fall back to freeing all buffers.\nfunc (ms *MemoryStore) SetNodeProvider(provider NodeProvider) {\n\tms.nodeProvider = provider\n}\n\n// Shutdown performs a graceful shutdown of the metric store.\n//\n// This function cancels all background goroutines started by Init() and writes\n// a final checkpoint to disk before returning. It should be called when the\n// application receives a termination signal.\n//\n// The function will:\n// 1. Cancel the context to stop all background workers\n// 2. Close the WAL messages channel if using WAL format\n// 3. Write a final checkpoint to preserve in-memory data\n// 4. Log any errors encountered during shutdown\n//\n// Note: This function blocks until the final checkpoint is written.\nfunc Shutdown() {\n\tshutdownFuncMu.Lock()\n\tdefer shutdownFuncMu.Unlock()\n\tif shutdownFunc != nil {\n\t\tshutdownFunc()\n\t}\n\n\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tclose(WALMessages)\n\t}\n\n\tcclog.Infof(\"[METRICSTORE]> Writing to '%s'...\\n\", Keys.Checkpoints.RootDir)\n\tvar files int\n\tvar err error\n\n\tms := GetMemoryStore()\n\n\tlastCheckpointMu.Lock()\n\tfrom := lastCheckpoint\n\tlastCheckpointMu.Unlock()\n\n\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tvar hostDirs []string\n\t\tfiles, hostDirs, err = ms.ToCheckpointWAL(Keys.Checkpoints.RootDir, from.Unix(), time.Now().Unix())\n\t\tif err == nil {\n\t\t\tRotateWALFilesAfterShutdown(hostDirs)\n\t\t}\n\t} else {\n\t\tfiles, err = ms.ToCheckpoint(Keys.Checkpoints.RootDir, from.Unix(), time.Now().Unix())\n\t}\n\n\tif err != nil {\n\t\tcclog.Errorf(\"[METRICSTORE]> Writing checkpoint failed: %s\\n\", err.Error())\n\t}\n\tcclog.Infof(\"[METRICSTORE]> Done! (%d files written)\\n\", files)\n}\n\n// Retention starts a background goroutine that periodically frees old metric data.\n//\n// This worker runs at half the retention interval and calls Free() to remove buffers\n// older than the configured retention time. It respects the NodeProvider to preserve\n// data for nodes with active jobs.\n//\n// Parameters:\n// - wg: WaitGroup to signal completion when context is cancelled\n// - ctx: Context for cancellation signal\n//\n// The goroutine exits when ctx is cancelled.\nfunc Retention(wg *sync.WaitGroup, ctx context.Context) {\n\tms := GetMemoryStore()\n\n\twg.Go(func() {\n\t\td, err := time.ParseDuration(Keys.RetentionInMemory)\n\t\tif err != nil {\n\t\t\tcclog.Fatal(err)\n\t\t}\n\t\tif d <= 0 {\n\t\t\treturn\n\t\t}\n\n\t\ttickInterval := d / 2\n\t\tif tickInterval <= 0 {\n\t\t\treturn\n\t\t}\n\t\tticker := time.NewTicker(tickInterval)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tstate.mu.Lock()\n\n\t\t\t\tt := time.Now().Add(-d)\n\n\t\t\t\tstate.lastRetentionTime = t.Unix()\n\n\t\t\t\tcclog.Infof(\"[METRICSTORE]> start freeing buffers (older than %s)...\\n\", t.Format(time.RFC3339))\n\n\t\t\t\tfreed, err := Free(ms, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> freeing up buffers failed: %s\\n\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> done: %d buffers freed\\n\", freed)\n\t\t\t\t}\n\n\t\t\t\tstate.mu.Unlock()\n\n\t\t\t\t// Clean up the buffer pool\n\t\t\t\tbufferPool.Clean(state.lastRetentionTime)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// MemoryUsageTracker starts a background goroutine that monitors memory usage.\n//\n// This worker checks actual process memory usage (via runtime.MemStats) periodically\n// and force-frees buffers if memory exceeds the configured cap. It uses FreeOSMemory()\n// to return memory to the OS after freeing buffers, avoiding aggressive GC that causes\n// performance issues.\n//\n// The tracker logs both actual memory usage (heap allocated) and metric data size for\n// visibility into memory overhead from Go runtime structures and allocations.\n//\n// Parameters:\n// - wg: WaitGroup to signal completion when context is cancelled\n// - ctx: Context for cancellation signal\n//\n// The goroutine exits when ctx is cancelled.\nfunc MemoryUsageTracker(wg *sync.WaitGroup, ctx context.Context) {\n\tms := GetMemoryStore()\n\n\twg.Go(func() {\n\t\tnormalInterval := DefaultMemoryUsageTrackerInterval\n\t\tfastInterval := 30 * time.Second\n\n\t\tif normalInterval <= 0 {\n\t\t\treturn\n\t\t}\n\n\t\tticker := time.NewTicker(normalInterval)\n\t\tdefer ticker.Stop()\n\t\tcurrentInterval := normalInterval\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tvar mem runtime.MemStats\n\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\tactualMemoryGB := float64(mem.Alloc) / 1e9\n\t\t\t\tmetricDataGB := ms.SizeInGB()\n\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory usage: %.2f GB actual (%.2f GB metric data)\", actualMemoryGB, metricDataGB)\n\n\t\t\t\tfreedExcluded := 0\n\t\t\t\tfreedEmergency := 0\n\t\t\t\tvar err error\n\n\t\t\t\tstate.mu.RLock()\n\t\t\t\tlastRetention := state.lastRetentionTime\n\t\t\t\tselectorsExcluded := state.selectorsExcluded\n\t\t\t\tstate.mu.RUnlock()\n\n\t\t\t\tif lastRetention != 0 && selectorsExcluded {\n\t\t\t\t\tfreedExcluded, err = ms.Free(nil, lastRetention)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> error while force-freeing the excluded buffers: %s\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tif freedExcluded > 0 {\n\t\t\t\t\t\tdebug.FreeOSMemory()\n\t\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> done: %d excluded buffers force-freed\", freedExcluded)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n\n\t\t\t\tif actualMemoryGB > float64(Keys.MemoryCap) {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> memory usage %.2f GB exceeds cap %d GB, starting emergency buffer freeing\", actualMemoryGB, Keys.MemoryCap)\n\n\t\t\t\t\t// Use progressive time-based Free with increasing threshold\n\t\t\t\t\t// instead of ForceFree loop — fewer tree traversals, more effective\n\t\t\t\t\td, parseErr := time.ParseDuration(Keys.RetentionInMemory)\n\t\t\t\t\tif parseErr != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> cannot parse retention duration: %s\", parseErr)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthresholds := []float64{0.75, 0.5, 0.25}\n\t\t\t\t\t\tfor _, fraction := range thresholds {\n\t\t\t\t\t\t\tthreshold := time.Now().Add(-time.Duration(float64(d) * fraction))\n\t\t\t\t\t\t\tfreed, freeErr := ms.Free(nil, threshold.Unix())\n\t\t\t\t\t\t\tif freeErr != nil {\n\t\t\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> error while freeing buffers at %.0f%% retention: %s\", fraction*100, freeErr)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfreedEmergency += freed\n\n\t\t\t\t\t\t\tbufferPool.Clear()\n\t\t\t\t\t\t\truntime.GC()\n\t\t\t\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n\n\t\t\t\t\t\t\tif actualMemoryGB < float64(Keys.MemoryCap) {\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbufferPool.Clear()\n\t\t\t\t\tdebug.FreeOSMemory()\n\n\t\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n\n\t\t\t\t\tif actualMemoryGB >= float64(Keys.MemoryCap) {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> after emergency frees (%d buffers), memory usage %.2f GB still at/above cap %d GB\", freedEmergency, actualMemoryGB, Keys.MemoryCap)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> emergency freeing complete: %d buffers freed, memory now %.2f GB\", freedEmergency, actualMemoryGB)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Adaptive ticker: check more frequently when memory is high\n\t\t\t\tmemoryRatio := actualMemoryGB / float64(Keys.MemoryCap)\n\t\t\t\tif memoryRatio > 0.8 && currentInterval != fastInterval {\n\t\t\t\t\tticker.Reset(fastInterval)\n\t\t\t\t\tcurrentInterval = fastInterval\n\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory at %.0f%% of cap, switching to fast check interval (30s)\", memoryRatio*100)\n\t\t\t\t} else if memoryRatio <= 0.8 && currentInterval != normalInterval {\n\t\t\t\t\tticker.Reset(normalInterval)\n\t\t\t\t\tcurrentInterval = normalInterval\n\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory at %.0f%% of cap, switching to normal check interval\", memoryRatio*100)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}\n\n// Free removes metric data older than the given time while preserving data for active nodes.\n//\n// This function implements intelligent retention by consulting the NodeProvider (if configured)\n// to determine which nodes are currently in use by running jobs. Data for these nodes is\n// preserved even if older than the retention time.\n//\n// Parameters:\n// - ms: The MemoryStore instance\n// - t: Time threshold - buffers with data older than this will be freed\n//\n// Returns:\n// - Number of buffers freed\n// - Error if NodeProvider query fails\n//\n// Behavior:\n// - If no NodeProvider is set: frees all buffers older than t\n// - If NodeProvider returns empty map: frees all buffers older than t\n// - Otherwise: preserves buffers for nodes returned by GetUsedNodes(), frees others\nfunc Free(ms *MemoryStore, t time.Time) (int, error) {\n\t// If no NodeProvider is configured, free all buffers older than t\n\tif ms.nodeProvider == nil {\n\t\treturn ms.Free(nil, t.Unix())\n\t}\n\n\texcludeSelectors, err := ms.nodeProvider.GetUsedNodes(t.Unix())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tswitch lenMap := len(excludeSelectors); lenMap {\n\n\t// If the length of the map returned by GetUsedNodes() is 0,\n\t// then use default Free method with nil selector\n\tcase 0:\n\t\tstate.selectorsExcluded = false\n\t\treturn ms.Free(nil, t.Unix())\n\n\t// Else formulate selectors, exclude those from the map\n\t// and free the rest of the selectors\n\tdefault:\n\t\tstate.selectorsExcluded = true\n\t\tselectors := GetSelectors(ms, excludeSelectors)\n\t\treturn FreeSelected(ms, selectors, t)\n\t}\n}\n\n// FreeSelected frees buffers for specific selectors while preserving others.\n//\n// This function is used when we want to retain some specific nodes beyond the retention time.\n// It iterates through the provided selectors and frees their associated buffers.\n//\n// Parameters:\n// - ms: The MemoryStore instance\n// - selectors: List of selector paths to free (e.g., [[\"cluster1\", \"node1\"], [\"cluster2\", \"node2\"]])\n// - t: Time threshold for freeing buffers\n//\n// Returns the total number of buffers freed and any error encountered.\nfunc FreeSelected(ms *MemoryStore, selectors [][]string, t time.Time) (int, error) {\n\tfreed := 0\n\n\tfor _, selector := range selectors {\n\n\t\tfreedBuffers, err := ms.Free(selector, t.Unix())\n\t\tif err != nil {\n\t\t\tcclog.Errorf(\"error while freeing selected buffers: %#v\", err)\n\t\t}\n\t\tfreed += freedBuffers\n\n\t}\n\n\treturn freed, nil\n}\n\n// GetSelectors returns all selectors at depth 2 (cluster/node level) that are NOT in the exclusion map.\n//\n// This function generates a list of selectors whose buffers should be freed by excluding\n// selectors that correspond to nodes currently in use by running jobs.\n//\n// Parameters:\n// - ms: The MemoryStore instance\n// - excludeSelectors: Map of cluster names to node hostnames that should NOT be freed\n//\n// Returns a list of selectors ([]string paths) that can be safely freed.\n//\n// Example:\n//\n//\tIf the tree has paths [\"emmy\", \"node001\"] and [\"emmy\", \"node002\"],\n//\tand excludeSelectors contains {\"emmy\": [\"node001\"]},\n//\tthen only [[\"emmy\", \"node002\"]] is returned.\nfunc GetSelectors(ms *MemoryStore, excludeSelectors map[string][]string) [][]string {\n\tallSelectors := ms.GetPaths(2)\n\n\tfilteredSelectors := make([][]string, 0, len(allSelectors))\n\n\tfor _, path := range allSelectors {\n\t\tif len(path) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := path[0] // The \"Key\" (Level 1)\n\t\tvalue := path[1] // The \"Value\" (Level 2)\n\n\t\texclude := false\n\n\t\t// Check if the key exists in our exclusion map\n\t\tif excludedValues, exists := excludeSelectors[key]; exists {\n\t\t\t// The key exists, now check if the specific value is in the exclusion list\n\t\t\tif slices.Contains(excludedValues, value) {\n\t\t\t\texclude = true\n\t\t\t}\n\t\t}\n\n\t\tif !exclude {\n\t\t\tfilteredSelectors = append(filteredSelectors, path)\n\t\t}\n\t}\n\n\treturn filteredSelectors\n}\n\n// GetPaths returns a list of lists (paths) to the specified depth.\nfunc (ms *MemoryStore) GetPaths(targetDepth int) [][]string {\n\tvar results [][]string\n\n\t// Start recursion. Initial path is empty.\n\t// We treat Root as depth 0.\n\tms.root.collectPaths(0, targetDepth, []string{}, &results)\n\n\treturn results\n}\n\n// Write all values in `metrics` to the level specified by `selector` for time `ts`.\n// Look at `findLevelOrCreate` for how selectors work.\nfunc (m *MemoryStore) Write(selector []string, ts int64, metrics []Metric) error {\n\tvar ok bool\n\tfor i, metric := range metrics {\n\t\tif metric.MetricConfig.Frequency == 0 {\n\t\t\tmetric.MetricConfig, ok = m.Metrics[metric.Name]\n\t\t\tif !ok {\n\t\t\t\tcclog.Debugf(\"[METRICSTORE]> Unknown metric '%s' in Write() - skipping\", metric.Name)\n\t\t\t\tmetric.MetricConfig.Frequency = 0\n\t\t\t}\n\t\t\tmetrics[i] = metric\n\t\t}\n\t}\n\n\treturn m.WriteToLevel(&m.root, selector, ts, metrics)\n}\n\nfunc (m *MemoryStore) GetLevel(selector []string) *Level {\n\treturn m.root.findLevelOrCreate(selector, len(m.Metrics))\n}\n\n// WriteToLevel assumes that `minfo` in `metrics` is filled in\nfunc (m *MemoryStore) WriteToLevel(l *Level, selector []string, ts int64, metrics []Metric) error {\n\tl = l.findLevelOrCreate(selector, len(m.Metrics))\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tfor _, metric := range metrics {\n\t\tif metric.MetricConfig.Frequency == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tb := l.metrics[metric.MetricConfig.offset]\n\t\tif b == nil {\n\t\t\t// First write to this metric and level\n\t\t\tb = newBuffer(ts, metric.MetricConfig.Frequency)\n\t\t\tl.metrics[metric.MetricConfig.offset] = b\n\t\t}\n\n\t\tnb, err := b.write(ts, metric.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Last write created a new buffer...\n\t\tif b != nb {\n\t\t\tl.metrics[metric.MetricConfig.offset] = nb\n\t\t}\n\t}\n\treturn nil\n}\n\n// Read returns all values for metric `metric` from `from` to `to` for the selected level(s).\n// If the level does not hold the metric itself, the data will be aggregated recursively from the children.\n// The second and third return value are the actual from/to for the data. Those can be different from\n// the range asked for if no data was available.\nfunc (m *MemoryStore) Read(selector util.Selector, metric string, from, to, resolution int64) ([]schema.Float, int64, int64, int64, error) {\n\tif from > to {\n\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> invalid time range\")\n\t}\n\n\tminfo, ok := m.Metrics[metric]\n\tif !ok {\n\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> unknown metric: \" + metric)\n\t}\n\n\tn, data := 0, make([]schema.Float, (to-from)/minfo.Frequency+1)\n\n\terr := m.root.findBuffers(selector, minfo.offset, func(b *buffer) error {\n\t\tcdata, cfrom, cto, err := b.read(from, to, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif n == 0 {\n\t\t\tfrom, to = cfrom, cto\n\t\t} else if from != cfrom || to != cto || len(data) != len(cdata) {\n\t\t\tmissingfront, missingback := int((from-cfrom)/minfo.Frequency), int((to-cto)/minfo.Frequency)\n\t\t\tif missingfront != 0 {\n\t\t\t\treturn ErrDataDoesNotAlign\n\t\t\t}\n\n\t\t\tnewlen := len(cdata) - missingback\n\t\t\tif newlen < 1 {\n\t\t\t\treturn ErrDataDoesNotAlign\n\t\t\t}\n\t\t\tcdata = cdata[0:newlen]\n\t\t\tif len(cdata) != len(data) {\n\t\t\t\treturn ErrDataDoesNotAlign\n\t\t\t}\n\n\t\t\tfrom, to = cfrom, cto\n\t\t}\n\n\t\tdata = cdata\n\t\tn += 1\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, 0, 0, 0, err\n\t} else if n == 0 {\n\t\treturn nil, 0, 0, 0, ErrNoHostOrMetric\n\t} else if n > 1 {\n\t\tif minfo.Aggregation == AvgAggregation {\n\t\t\tnormalize := 1. / schema.Float(n)\n\t\t\tfor i := 0; i < len(data); i++ {\n\t\t\t\tdata[i] *= normalize\n\t\t\t}\n\t\t} else if minfo.Aggregation != SumAggregation {\n\t\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> invalid aggregation\")\n\t\t}\n\t}\n\n\tdata, resolution, err = resampler.LargestTriangleThreeBucket(data, minfo.Frequency, resolution)\n\tif err != nil {\n\t\treturn nil, 0, 0, 0, err\n\t}\n\n\treturn data, from, to, resolution, nil\n}\n\n// Free releases all buffers for the selected level and all its children that\n// contain only values older than `t`.\nfunc (m *MemoryStore) Free(selector []string, t int64) (int, error) {\n\treturn m.GetLevel(selector).free(t)\n}\n\n// ForceFree unconditionally removes the oldest buffer from each metric chain.\nfunc (m *MemoryStore) ForceFree() (int, error) {\n\treturn m.GetLevel(nil).forceFree()\n}\n\nfunc (m *MemoryStore) FreeAll() error {\n\tm.root.lock.Lock()\n\tdefer m.root.lock.Unlock()\n\n\tfor k := range m.root.children {\n\t\tdelete(m.root.children, k)\n\t}\n\n\treturn nil\n}\n\nfunc (m *MemoryStore) SizeInBytes() int64 {\n\treturn m.root.sizeInBytes()\n}\n\nfunc (m *MemoryStore) SizeInGB() float64 {\n\treturn float64(m.root.sizeInBytes()) / 1e9\n}\n\n// ListChildren , given a selector, returns a list of all children of the level\n// selected.\nfunc (m *MemoryStore) ListChildren(selector []string) []string {\n\tlvl := &m.root\n\tfor lvl != nil && len(selector) != 0 {\n\t\tlvl.lock.RLock()\n\t\tnext := lvl.children[selector[0]]\n\t\tlvl.lock.RUnlock()\n\t\tlvl = next\n\t\tselector = selector[1:]\n\t}\n\n\tif lvl == nil {\n\t\treturn nil\n\t}\n\n\tlvl.lock.RLock()\n\tdefer lvl.lock.RUnlock()\n\n\tchildren := make([]string, 0, len(lvl.children))\n\tfor child := range lvl.children {\n\t\tchildren = append(children, child)\n\t}\n\n\treturn children\n}\n","numLines":801,"startLine":1,"totalLines":801}},"sourceToolAssistantUUID":"857ea268-ae28-4dde-bae7-4a938c7bfc2c","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"0f4c1787-87de-49e0-99d1-bfbd5aed3be2","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_011vAFAxQhh95zTJvnKjDEJR","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"","signature":"EsMCCkYICxgCKkA+CwjXaYDWYs/Ci0kH8b5ZKsagA/lPEmjy1kUMpirD7/2UqLJW18KQ4qbKhhMwHVJzet6KOjUjqQmdyVMCH7j6EgwiHMqSNhdV89X5Y6waDEtrFnDIqQ5oph5aiSIwmJM6WoZWwVvbWTjvCF7jiptrdY/hU2/CIY4tS09p0iBzA4AxyBRXDhdYbmi5aLm6KqoBWmSqjFxHbPxL2zgfq8kik4fJT7nxsojWbSoq0/OIIhHrVqF+cVt/Jc6SeRLCY5ujyPVfnV+a0T/lDvOsegVo+CvH0bhuV/Zosn9jHEg/H/CzhQRJxS6/C4RBRjaDEp1k2hdGhxcid8lQYv6qoWHh9KmOkRtc7+1nUvRAAR4JeRgBmEjQtXohcfTj+dQ1MubeBrvvwy6dUVldu7B6QD1UfPokP75KUsv/PGQYAQ=="}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":27811,"cache_read_input_tokens":20004,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":27811},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zeeCNxTqTX7vFLCZsV","type":"assistant","uuid":"520f5619-f54b-4aee-9915-224dfacfba2b","timestamp":"2026-03-18T05:29:27.753Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"520f5619-f54b-4aee-9915-224dfacfba2b","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_011vAFAxQhh95zTJvnKjDEJR","type":"message","role":"assistant","content":[{"type":"text","text":"Now I have a clear picture of the codebase. Let me implement the sharded WAL writers."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":27811,"cache_read_input_tokens":20004,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":27811},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zeeCNxTqTX7vFLCZsV","type":"assistant","uuid":"3922f670-9124-495a-bda6-919c510663b1","timestamp":"2026-03-18T05:29:28.122Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"3922f670-9124-495a-bda6-919c510663b1","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_011vAFAxQhh95zTJvnKjDEJR","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01H9DC1JrHbciErchn7EYLzS","name":"Grep","input":{"pattern":"WALMessages|WALStaging|walRotateCh","path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore","output_mode":"content"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":27811,"cache_read_input_tokens":20004,"output_tokens":197,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":27811,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zeeCNxTqTX7vFLCZsV","type":"assistant","uuid":"5fc193e2-da36-4047-b725-e58c469dc962","timestamp":"2026-03-18T05:29:29.948Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"5fc193e2-da36-4047-b725-e58c469dc962","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Grep","command":"callback"},"parentToolUseID":"toolu_01H9DC1JrHbciErchn7EYLzS","toolUseID":"toolu_01H9DC1JrHbciErchn7EYLzS","timestamp":"2026-03-18T05:29:29.980Z","uuid":"90c3bb41-d3ef-4a72-a8b9-b002f60ff1c2","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"5fc193e2-da36-4047-b725-e58c469dc962","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01H9DC1JrHbciErchn7EYLzS","type":"tool_result","content":"pkg/metricstore/metricstore.go:175:\tWALStaging(wg, ctx)\npkg/metricstore/metricstore.go:280:\t\tclose(WALMessages)\npkg/metricstore/walCheckpoint.go:18://\t └─► WALMessages channel\npkg/metricstore/walCheckpoint.go:21://\t WALStaging goroutine\npkg/metricstore/walCheckpoint.go:28://\t 2. Signal WALStaging to truncate current.wal per host\npkg/metricstore/walCheckpoint.go:83:// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\npkg/metricstore/walCheckpoint.go:85:var WALMessages = make(chan *WALMessage, 65536)\npkg/metricstore/walCheckpoint.go:87:// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\npkg/metricstore/walCheckpoint.go:89:var walRotateCh = make(chan walRotateReq, 256)\npkg/metricstore/walCheckpoint.go:115:// WALStaging starts a background goroutine that receives WALMessage items\npkg/metricstore/walCheckpoint.go:118:func WALStaging(wg *sync.WaitGroup, ctx context.Context) {\npkg/metricstore/walCheckpoint.go:200:\t\t\t\tcase msg, ok := <-WALMessages:\npkg/metricstore/walCheckpoint.go:205:\t\t\t\tcase req := <-walRotateCh:\npkg/metricstore/walCheckpoint.go:224:\t\t\tcase msg, ok := <-WALMessages:\npkg/metricstore/walCheckpoint.go:233:\t\t\t\t\tcase msg, ok := <-WALMessages:\npkg/metricstore/walCheckpoint.go:238:\t\t\t\t\tcase req := <-walRotateCh:\npkg/metricstore/walCheckpoint.go:251:\t\t\tcase req := <-walRotateCh:\npkg/metricstore/walCheckpoint.go:264:\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\npkg/metricstore/lineprotocol.go:18:// goroutine via the WALMessages channel for durable write-ahead logging.\npkg/metricstore/lineprotocol.go:197:// sent to WALMessages so the WAL staging goroutine can persist it durably\npkg/metricstore/lineprotocol.go:365:\t\t\tcase WALMessages <- msg:"}]},"uuid":"27b24b0f-0689-4001-8872-1341a2f13ba7","timestamp":"2026-03-18T05:29:29.979Z","toolUseResult":{"mode":"content","numFiles":0,"filenames":[],"content":"pkg/metricstore/metricstore.go:175:\tWALStaging(wg, ctx)\npkg/metricstore/metricstore.go:280:\t\tclose(WALMessages)\npkg/metricstore/walCheckpoint.go:18://\t └─► WALMessages channel\npkg/metricstore/walCheckpoint.go:21://\t WALStaging goroutine\npkg/metricstore/walCheckpoint.go:28://\t 2. Signal WALStaging to truncate current.wal per host\npkg/metricstore/walCheckpoint.go:83:// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\npkg/metricstore/walCheckpoint.go:85:var WALMessages = make(chan *WALMessage, 65536)\npkg/metricstore/walCheckpoint.go:87:// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\npkg/metricstore/walCheckpoint.go:89:var walRotateCh = make(chan walRotateReq, 256)\npkg/metricstore/walCheckpoint.go:115:// WALStaging starts a background goroutine that receives WALMessage items\npkg/metricstore/walCheckpoint.go:118:func WALStaging(wg *sync.WaitGroup, ctx context.Context) {\npkg/metricstore/walCheckpoint.go:200:\t\t\t\tcase msg, ok := <-WALMessages:\npkg/metricstore/walCheckpoint.go:205:\t\t\t\tcase req := <-walRotateCh:\npkg/metricstore/walCheckpoint.go:224:\t\t\tcase msg, ok := <-WALMessages:\npkg/metricstore/walCheckpoint.go:233:\t\t\t\t\tcase msg, ok := <-WALMessages:\npkg/metricstore/walCheckpoint.go:238:\t\t\t\t\tcase req := <-walRotateCh:\npkg/metricstore/walCheckpoint.go:251:\t\t\tcase req := <-walRotateCh:\npkg/metricstore/walCheckpoint.go:264:\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\npkg/metricstore/lineprotocol.go:18:// goroutine via the WALMessages channel for durable write-ahead logging.\npkg/metricstore/lineprotocol.go:197:// sent to WALMessages so the WAL staging goroutine can persist it durably\npkg/metricstore/lineprotocol.go:365:\t\t\tcase WALMessages <- msg:","numLines":21},"sourceToolAssistantUUID":"5fc193e2-da36-4047-b725-e58c469dc962","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"27b24b0f-0689-4001-8872-1341a2f13ba7","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01L2CTrZqBckxAj7nJh2bTQL","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01PFTFq7xFn961LUashCuZXp","name":"Grep","input":{"pattern":"WALMessages|WALStaging|walRotateCh|RotateWALFiles","path":"/Users/jan/prg/ClusterCockpit/cc-backend","output_mode":"files_with_matches","glob":"*_test.go"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":835,"cache_read_input_tokens":47815,"output_tokens":150,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":835,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zf5GWALkSieaKQLiEF","type":"assistant","uuid":"dc3bb873-4ad5-40a2-bb56-e3b8df2ce204","timestamp":"2026-03-18T05:29:33.368Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"dc3bb873-4ad5-40a2-bb56-e3b8df2ce204","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Grep","command":"callback"},"parentToolUseID":"toolu_01PFTFq7xFn961LUashCuZXp","toolUseID":"toolu_01PFTFq7xFn961LUashCuZXp","timestamp":"2026-03-18T05:29:33.408Z","uuid":"566d0f84-3988-4f39-bb59-e00194bd726d","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"dc3bb873-4ad5-40a2-bb56-e3b8df2ce204","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01PFTFq7xFn961LUashCuZXp","type":"tool_result","content":"No files found"}]},"uuid":"6bd3b4f7-0b6c-460d-8e86-f5f3d690e047","timestamp":"2026-03-18T05:29:33.408Z","toolUseResult":{"mode":"files_with_matches","filenames":[],"numFiles":0},"sourceToolAssistantUUID":"dc3bb873-4ad5-40a2-bb56-e3b8df2ce204","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"6bd3b4f7-0b6c-460d-8e86-f5f3d690e047","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01GGXaq6WuX7bN9wE4okb7Ww","type":"message","role":"assistant","content":[{"type":"text","text":"Good, no tests directly reference these. Now let me implement the changes.\n\n**Change 1 & 2 & 4: Sharded WAL writers + direct record writing + shard-aware rotation in `walCheckpoint.go`**"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":165,"cache_read_input_tokens":48650,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":165},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zfKy3Jh3iefbZ2kYVS","type":"assistant","uuid":"9c65ea61-314c-491b-a9de-ce8343ce45a2","timestamp":"2026-03-18T05:29:42.408Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"9c65ea61-314c-491b-a9de-ce8343ce45a2","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01GGXaq6WuX7bN9wE4okb7Ww","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_012b7pKcrDK56sJpbYkfEj2i","name":"Edit","input":{"replace_all":false,"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","old_string":"import (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)","new_string":"import (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":165,"cache_read_input_tokens":48650,"output_tokens":418,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":165,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zfKy3Jh3iefbZ2kYVS","type":"assistant","uuid":"0b6218a5-96c5-4d0c-b0c6-8461ff1f8ad3","timestamp":"2026-03-18T05:29:45.029Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"type":"file-history-snapshot","messageId":"0b6218a5-96c5-4d0c-b0c6-8461ff1f8ad3","snapshot":{"messageId":"e61b6d31-15d1-4b25-a4d5-dc4c0ddd1260","trackedFileBackups":{"pkg/metricstore/walCheckpoint.go":{"backupFileName":"f5b5b4bac0274f50@v1","version":1,"backupTime":"2026-03-18T05:29:45.041Z"}},"timestamp":"2026-03-18T05:29:19.393Z"},"isSnapshotUpdate":true}
{"parentUuid":"0b6218a5-96c5-4d0c-b0c6-8461ff1f8ad3","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Edit","command":"callback"},"parentToolUseID":"toolu_012b7pKcrDK56sJpbYkfEj2i","toolUseID":"toolu_012b7pKcrDK56sJpbYkfEj2i","timestamp":"2026-03-18T05:29:45.044Z","uuid":"4773bed0-34c9-447c-af12-004c71598ec1","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"0b6218a5-96c5-4d0c-b0c6-8461ff1f8ad3","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_012b7pKcrDK56sJpbYkfEj2i","type":"tool_result","content":"The file /Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go has been updated successfully."}]},"uuid":"ff720ed1-6bda-4b49-a116-ab8d7cf83e47","timestamp":"2026-03-18T05:29:45.044Z","toolUseResult":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","oldString":"import (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)","newString":"import (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)","originalFile":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides walCheckpoint.go: WAL-based checkpoint implementation.\n//\n// This replaces the Avro shadow tree with an append-only Write-Ahead Log (WAL)\n// per host, eliminating the extra memory overhead of the AvroStore and providing\n// truly continuous (per-write) crash safety.\n//\n// # Architecture\n//\n//\tMetric write (DecodeLine)\n//\t │\n//\t ├─► WriteToLevel() → main MemoryStore (unchanged)\n//\t │\n//\t └─► WALMessages channel\n//\t │\n//\t ▼\n//\t WALStaging goroutine\n//\t │\n//\t ▼\n//\t checkpoints/cluster/host/current.wal (append-only, binary)\n//\n//\tPeriodic checkpoint (Checkpointing goroutine):\n//\t 1. Write <timestamp>.bin snapshot (column-oriented, from main tree)\n//\t 2. Signal WALStaging to truncate current.wal per host\n//\n//\tOn restart (FromCheckpoint):\n//\t 1. Load most recent <timestamp>.bin snapshot\n//\t 2. Replay current.wal (overwrite-safe: buffer.write handles duplicate timestamps)\n//\n// # WAL Record Format\n//\n//\t[4B magic 0xCC1DA7A1][4B payload_len][payload][4B CRC32]\n//\n//\tpayload:\n//\t [8B timestamp int64]\n//\t [2B metric_name_len uint16][N metric name bytes]\n//\t [1B selector_count uint8]\n//\t per selector: [1B selector_len uint8][M selector bytes]\n//\t [4B value float32 bits]\n//\n// # Binary Snapshot Format\n//\n//\t[4B magic 0xCC5B0001][8B from int64][8B to int64]\n//\tLevel tree (recursive):\n//\t [4B num_metrics uint32]\n//\t per metric:\n//\t [2B name_len uint16][N name bytes]\n//\t [8B frequency int64][8B start int64]\n//\t [4B num_values uint32][num_values × 4B float32]\n//\t [4B num_children uint32]\n//\t per child: [2B name_len uint16][N name bytes] + Level (recursive)\npackage metricstore\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)\n\n// Magic numbers for binary formats.\nconst (\n\twalFileMagic = uint32(0xCC1DA701) // WAL file header magic\n\twalRecordMagic = uint32(0xCC1DA7A1) // WAL record magic\n\tsnapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic\n)\n\n// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\n// Buffered to allow burst writes without blocking the metric ingestion path.\nvar WALMessages = make(chan *WALMessage, 65536)\n\n// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\n// (close, delete, reopen) after a binary snapshot has been written.\nvar walRotateCh = make(chan walRotateReq, 256)\n\n// WALMessage represents a single metric write to be appended to the WAL.\n// Cluster and Node are NOT stored in the WAL record (inferred from file path).\ntype WALMessage struct {\n\tMetricName string\n\tCluster string\n\tNode string\n\tSelector []string\n\tValue schema.Float\n\tTimestamp int64\n}\n\n// walRotateReq requests WAL file rotation for a specific host directory.\n// The done channel is closed by the WAL goroutine when rotation is complete.\ntype walRotateReq struct {\n\thostDir string\n\tdone chan struct{}\n}\n\n// walFileState holds an open WAL file handle and buffered writer for one host directory.\ntype walFileState struct {\n\tf *os.File\n\tw *bufio.Writer\n}\n\n// WALStaging starts a background goroutine that receives WALMessage items\n// and appends binary WAL records to per-host current.wal files.\n// Also handles WAL rotation requests from the checkpoint goroutine.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\twg.Go(func() {\n\t\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\t\treturn\n\t\t}\n\n\t\thostFiles := make(map[string]*walFileState)\n\n\t\tdefer func() {\n\t\t\tfor _, ws := range hostFiles {\n\t\t\t\tif ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\tws, ok := hostFiles[hostDir]\n\t\t\tif ok {\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\tif err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t// Write file header magic if file is new (empty).\n\t\t\tinfo, err := f.Stat()\n\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\tvar hdr [4]byte\n\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\tf.Close()\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws = &walFileState{f: f, w: w}\n\t\t\thostFiles[hostDir] = ws\n\t\t\treturn ws\n\t\t}\n\n\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\tif ws == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := writeWALRecord(ws.w, msg); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tprocessRotate := func(req walRotateReq) {\n\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\tif ok && ws.f != nil {\n\t\t\t\tws.w.Flush()\n\t\t\t\tws.f.Close()\n\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t}\n\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t}\n\t\t\tclose(req.done)\n\t\t}\n\n\t\tdrain := func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\tdefault:\n\t\t\t\t\t// Flush all buffered writers after draining remaining messages.\n\t\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tdrain()\n\t\t\t\treturn\n\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\tfor range 256 {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tflushed:\n\t\t\t\t// Flush all buffered writers after processing the batch.\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase req := <-walRotateCh:\n\t\t\t\tprocessRotate(req)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFiles(hostDirs []string) {\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFilesAfterShutdown(hostDirs []string) {\n\tfor _, dir := range hostDirs {\n\t\twalPath := path.Join(dir, \"current.wal\")\n\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t}\n\t}\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {\n\tsize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tsize += 1 + len(s)\n\t}\n\n\tbuf := make([]byte, 0, size)\n\n\t// Timestamp (8 bytes, little-endian int64)\n\tvar ts [8]byte\n\tbinary.LittleEndian.PutUint64(ts[:], uint64(msg.Timestamp))\n\tbuf = append(buf, ts[:]...)\n\n\t// Metric name (2-byte length prefix + bytes)\n\tvar mLen [2]byte\n\tbinary.LittleEndian.PutUint16(mLen[:], uint16(len(msg.MetricName)))\n\tbuf = append(buf, mLen[:]...)\n\tbuf = append(buf, msg.MetricName...)\n\n\t// Selector count (1 byte)\n\tbuf = append(buf, byte(len(msg.Selector)))\n\n\t// Selectors (1-byte length prefix + bytes each)\n\tfor _, sel := range msg.Selector {\n\t\tbuf = append(buf, byte(len(sel)))\n\t\tbuf = append(buf, sel...)\n\t}\n\n\t// Value (4 bytes, float32 bit representation)\n\tvar val [4]byte\n\tbinary.LittleEndian.PutUint32(val[:], math.Float32bits(float32(msg.Value)))\n\tbuf = append(buf, val[:]...)\n\n\treturn buf\n}\n\n// writeWALRecord appends a binary WAL record to the writer.\n// Format: [4B magic][4B payload_len][payload][4B CRC32]\nfunc writeWALRecord(w io.Writer, msg *WALMessage) error {\n\tpayload := buildWALPayload(msg)\n\tcrc := crc32.ChecksumIEEE(payload)\n\n\trecord := make([]byte, 0, 4+4+len(payload)+4)\n\n\tvar magic [4]byte\n\tbinary.LittleEndian.PutUint32(magic[:], walRecordMagic)\n\trecord = append(record, magic[:]...)\n\n\tvar pLen [4]byte\n\tbinary.LittleEndian.PutUint32(pLen[:], uint32(len(payload)))\n\trecord = append(record, pLen[:]...)\n\n\trecord = append(record, payload...)\n\n\tvar crcBytes [4]byte\n\tbinary.LittleEndian.PutUint32(crcBytes[:], crc)\n\trecord = append(record, crcBytes[:]...)\n\n\t_, err := w.Write(record)\n\treturn err\n}\n\n// readWALRecord reads one WAL record from the reader.\n// Returns (nil, nil) on clean EOF. Returns error on data corruption.\n// A CRC mismatch indicates a truncated trailing record (expected on crash).\nfunc readWALRecord(r io.Reader) (*WALMessage, error) {\n\tvar magic uint32\n\tif err := binary.Read(r, binary.LittleEndian, &magic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil, nil // Clean EOF\n\t\t}\n\t\treturn nil, fmt.Errorf(\"read record magic: %w\", err)\n\t}\n\n\tif magic != walRecordMagic {\n\t\treturn nil, fmt.Errorf(\"invalid record magic 0x%08X (expected 0x%08X)\", magic, walRecordMagic)\n\t}\n\n\tvar payloadLen uint32\n\tif err := binary.Read(r, binary.LittleEndian, &payloadLen); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload length: %w\", err)\n\t}\n\n\tif payloadLen > 1<<20 { // 1 MB sanity limit\n\t\treturn nil, fmt.Errorf(\"record payload too large: %d bytes\", payloadLen)\n\t}\n\n\tpayload := make([]byte, payloadLen)\n\tif _, err := io.ReadFull(r, payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload: %w\", err)\n\t}\n\n\tvar storedCRC uint32\n\tif err := binary.Read(r, binary.LittleEndian, &storedCRC); err != nil {\n\t\treturn nil, fmt.Errorf(\"read CRC: %w\", err)\n\t}\n\n\tif crc32.ChecksumIEEE(payload) != storedCRC {\n\t\treturn nil, fmt.Errorf(\"CRC mismatch (truncated write or corruption)\")\n\t}\n\n\treturn parseWALPayload(payload)\n}\n\n// parseWALPayload decodes a binary payload into a WALMessage.\nfunc parseWALPayload(payload []byte) (*WALMessage, error) {\n\tif len(payload) < 8+2+1+4 {\n\t\treturn nil, fmt.Errorf(\"payload too short: %d bytes\", len(payload))\n\t}\n\n\toffset := 0\n\n\t// Timestamp (8 bytes)\n\tts := int64(binary.LittleEndian.Uint64(payload[offset : offset+8]))\n\toffset += 8\n\n\t// Metric name (2-byte length + bytes)\n\tif offset+2 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name length overflows payload\")\n\t}\n\tmLen := int(binary.LittleEndian.Uint16(payload[offset : offset+2]))\n\toffset += 2\n\n\tif offset+mLen > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name overflows payload\")\n\t}\n\tmetricName := string(payload[offset : offset+mLen])\n\toffset += mLen\n\n\t// Selector count (1 byte)\n\tif offset >= len(payload) {\n\t\treturn nil, fmt.Errorf(\"selector count overflows payload\")\n\t}\n\tselCount := int(payload[offset])\n\toffset++\n\n\tselectors := make([]string, selCount)\n\tfor i := range selCount {\n\t\tif offset >= len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] length overflows payload\", i)\n\t\t}\n\t\tsLen := int(payload[offset])\n\t\toffset++\n\n\t\tif offset+sLen > len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] data overflows payload\", i)\n\t\t}\n\t\tselectors[i] = string(payload[offset : offset+sLen])\n\t\toffset += sLen\n\t}\n\n\t// Value (4 bytes, float32 bits)\n\tif offset+4 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"value overflows payload\")\n\t}\n\tbits := binary.LittleEndian.Uint32(payload[offset : offset+4])\n\tvalue := schema.Float(math.Float32frombits(bits))\n\n\treturn &WALMessage{\n\t\tMetricName: metricName,\n\t\tTimestamp: ts,\n\t\tSelector: selectors,\n\t\tValue: value,\n\t}, nil\n}\n\n// loadWALFile reads a WAL file and replays all valid records into the Level tree.\n// l is the host-level node. Corrupt or partial trailing records are silently skipped\n// (expected on crash). Records older than 'from' are skipped.\nfunc (l *Level) loadWALFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\t// Verify file header magic.\n\tvar fileMagic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &fileMagic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil // Empty file, no data\n\t\t}\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: read file header: %w\", err)\n\t}\n\n\tif fileMagic != walFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: invalid file magic 0x%08X (expected 0x%08X)\", fileMagic, walFileMagic)\n\t}\n\n\t// Cache level lookups to avoid repeated tree traversal.\n\tlvlCache := make(map[string]*Level)\n\n\tfor {\n\t\tmsg, err := readWALRecord(br)\n\t\tif err != nil {\n\t\t\t// Truncated trailing record is expected after a crash; stop replaying.\n\t\t\tcclog.Debugf(\"[METRICSTORE]> WAL: stopping replay at corrupted/partial record: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tif msg == nil {\n\t\t\tbreak // Clean EOF\n\t\t}\n\n\t\tif msg.Timestamp < from {\n\t\t\tcontinue // Older than retention window\n\t\t}\n\n\t\tminfo, ok := m.Metrics[msg.MetricName]\n\t\tif !ok {\n\t\t\tcontinue // Unknown metric (config may have changed)\n\t\t}\n\n\t\t// Cache key is the null-separated selector path.\n\t\tcacheKey := joinSelector(msg.Selector)\n\t\tlvl, ok := lvlCache[cacheKey]\n\t\tif !ok {\n\t\t\tlvl = l.findLevelOrCreate(msg.Selector, len(m.Metrics))\n\t\t\tlvlCache[cacheKey] = lvl\n\t\t}\n\n\t\t// Write directly to the buffer, same as WriteToLevel but without the\n\t\t// global level lookup (we already have the right level).\n\t\tlvl.lock.Lock()\n\t\tb := lvl.metrics[minfo.offset]\n\t\tif b == nil {\n\t\t\tb = newBuffer(msg.Timestamp, minfo.Frequency)\n\t\t\tlvl.metrics[minfo.offset] = b\n\t\t}\n\t\tnb, writeErr := b.write(msg.Timestamp, msg.Value)\n\t\tif writeErr == nil && b != nb {\n\t\t\tlvl.metrics[minfo.offset] = nb\n\t\t}\n\t\t// Ignore write errors for timestamps before buffer start (can happen when\n\t\t// replaying WAL entries that predate a loaded snapshot's start time).\n\t\tlvl.lock.Unlock()\n\t}\n\n\treturn nil\n}\n\n// joinSelector builds a cache key from a selector slice using null bytes as separators.\nfunc joinSelector(sel []string) string {\n\tif len(sel) == 0 {\n\t\treturn \"\"\n\t}\n\tvar result strings.Builder\n\tresult.WriteString(sel[0])\n\tfor i := 1; i < len(sel); i++ {\n\t\tresult.WriteString(\"\\x00\" + sel[i])\n\t}\n\treturn result.String()\n}\n\n// ToCheckpointWAL writes binary snapshot files for all hosts in parallel.\n// Returns the number of files written, the list of host directories that were\n// successfully checkpointed (for WAL rotation), and any errors.\nfunc (m *MemoryStore) ToCheckpointWAL(dir string, from, to int64) (int, []string, error) {\n\t// Collect all cluster/host pairs.\n\tm.root.lock.RLock()\n\ttotalHosts := 0\n\tfor _, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\ttotalHosts += len(l1.children)\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\tlevels := make([]*Level, 0, totalHosts)\n\tselectors := make([][]string, 0, totalHosts)\n\n\tm.root.lock.RLock()\n\tfor sel1, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\tfor sel2, l2 := range l1.children {\n\t\t\tlevels = append(levels, l2)\n\t\t\tselectors = append(selectors, []string{sel1, sel2})\n\t\t}\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\ttype workItem struct {\n\t\tlevel *Level\n\t\thostDir string\n\t\tselector []string\n\t}\n\n\tn, errs := int32(0), int32(0)\n\tvar successDirs []string\n\tvar successMu sync.Mutex\n\n\tvar wg sync.WaitGroup\n\twg.Add(Keys.NumWorkers)\n\twork := make(chan workItem, Keys.NumWorkers*2)\n\n\tfor range Keys.NumWorkers {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor wi := range work {\n\t\t\t\terr := wi.level.toCheckpointBinary(wi.hostDir, from, to, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == ErrNoNewArchiveData {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> binary checkpoint error for %s: %v\", wi.hostDir, err)\n\t\t\t\t\tatomic.AddInt32(&errs, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.AddInt32(&n, 1)\n\t\t\t\t\tsuccessMu.Lock()\n\t\t\t\t\tsuccessDirs = append(successDirs, wi.hostDir)\n\t\t\t\t\tsuccessMu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor i := range levels {\n\t\thostDir := path.Join(dir, path.Join(selectors[i]...))\n\t\twork <- workItem{\n\t\t\tlevel: levels[i],\n\t\t\thostDir: hostDir,\n\t\t\tselector: selectors[i],\n\t\t}\n\t}\n\tclose(work)\n\twg.Wait()\n\n\tif errs > 0 {\n\t\treturn int(n), successDirs, fmt.Errorf(\"[METRICSTORE]> %d errors during binary checkpoint (%d successes)\", errs, n)\n\t}\n\treturn int(n), successDirs, nil\n}\n\n// toCheckpointBinary writes a binary snapshot file for a single host-level node.\n// Uses atomic rename (write to .tmp then rename) to avoid partial reads on crash.\nfunc (l *Level) toCheckpointBinary(dir string, from, to int64, m *MemoryStore) error {\n\tcf, err := l.toCheckpointFile(from, to, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cf == nil {\n\t\treturn ErrNoNewArchiveData\n\t}\n\n\tif err := os.MkdirAll(dir, CheckpointDirPerms); err != nil {\n\t\treturn fmt.Errorf(\"mkdir %s: %w\", dir, err)\n\t}\n\n\t// Write to a temp file first, then rename (atomic on POSIX).\n\ttmpPath := path.Join(dir, fmt.Sprintf(\"%d.bin.tmp\", from))\n\tfinalPath := path.Join(dir, fmt.Sprintf(\"%d.bin\", from))\n\n\tf, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, CheckpointFilePerms)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open binary snapshot %s: %w\", tmpPath, err)\n\t}\n\n\tbw := bufio.NewWriter(f)\n\tif err := writeBinarySnapshotFile(bw, cf); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn fmt.Errorf(\"write binary snapshot: %w\", err)\n\t}\n\tif err := bw.Flush(); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn err\n\t}\n\tf.Close()\n\n\treturn os.Rename(tmpPath, finalPath)\n}\n\n// writeBinarySnapshotFile writes the binary snapshot file header and level tree.\nfunc writeBinarySnapshotFile(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, snapFileMagic); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.From); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.To); err != nil {\n\t\treturn err\n\t}\n\treturn writeBinaryLevel(w, cf)\n}\n\n// writeBinaryLevel recursively writes a CheckpointFile level in binary format.\nfunc writeBinaryLevel(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Metrics))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, metric := range cf.Metrics {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Frequency); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Start); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, uint32(len(metric.Data))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, v := range metric.Data {\n\t\t\tif err := binary.Write(w, binary.LittleEndian, math.Float32bits(float32(v))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Children))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, child := range cf.Children {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writeBinaryLevel(w, child); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// writeString16 writes a 2-byte length-prefixed string to w.\nfunc writeString16(w io.Writer, s string) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint16(len(s))); err != nil {\n\t\treturn err\n\t}\n\t_, err := io.WriteString(w, s)\n\treturn err\n}\n\n// loadBinaryFile reads a binary snapshot file and loads data into the Level tree.\n// The retention check (from) is applied to the file's 'to' timestamp.\nfunc (l *Level) loadBinaryFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\tvar magic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &magic); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read magic: %w\", err)\n\t}\n\tif magic != snapFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: invalid magic 0x%08X (expected 0x%08X)\", magic, snapFileMagic)\n\t}\n\n\tvar fileFrom, fileTo int64\n\tif err := binary.Read(br, binary.LittleEndian, &fileFrom); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read from: %w\", err)\n\t}\n\tif err := binary.Read(br, binary.LittleEndian, &fileTo); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read to: %w\", err)\n\t}\n\n\tif fileTo != 0 && fileTo < from {\n\t\treturn nil // File is older than retention window, skip it\n\t}\n\n\tcf, err := readBinaryLevel(br)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read level tree: %w\", err)\n\t}\n\tcf.From = fileFrom\n\tcf.To = fileTo\n\n\treturn l.loadFile(cf, m)\n}\n\n// readBinaryLevel recursively reads a level from the binary snapshot format.\nfunc readBinaryLevel(r io.Reader) (*CheckpointFile, error) {\n\tcf := &CheckpointFile{\n\t\tMetrics: make(map[string]*CheckpointMetrics),\n\t\tChildren: make(map[string]*CheckpointFile),\n\t}\n\n\tvar numMetrics uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numMetrics); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_metrics: %w\", err)\n\t}\n\n\tfor range numMetrics {\n\t\tname, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read metric name: %w\", err)\n\t\t}\n\n\t\tvar freq, start int64\n\t\tif err := binary.Read(r, binary.LittleEndian, &freq); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read frequency for %s: %w\", name, err)\n\t\t}\n\t\tif err := binary.Read(r, binary.LittleEndian, &start); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read start for %s: %w\", name, err)\n\t\t}\n\n\t\tvar numValues uint32\n\t\tif err := binary.Read(r, binary.LittleEndian, &numValues); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read num_values for %s: %w\", name, err)\n\t\t}\n\n\t\tdata := make([]schema.Float, numValues)\n\t\tfor i := range numValues {\n\t\t\tvar bits uint32\n\t\t\tif err := binary.Read(r, binary.LittleEndian, &bits); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"read value[%d] for %s: %w\", i, name, err)\n\t\t\t}\n\t\t\tdata[i] = schema.Float(math.Float32frombits(bits))\n\t\t}\n\n\t\tcf.Metrics[name] = &CheckpointMetrics{\n\t\t\tFrequency: freq,\n\t\t\tStart: start,\n\t\t\tData: data,\n\t\t}\n\t}\n\n\tvar numChildren uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numChildren); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_children: %w\", err)\n\t}\n\n\tfor range numChildren {\n\t\tchildName, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child name: %w\", err)\n\t\t}\n\n\t\tchild, err := readBinaryLevel(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child %s: %w\", childName, err)\n\t\t}\n\t\tcf.Children[childName] = child\n\t}\n\n\treturn cf, nil\n}\n\n// readString16 reads a 2-byte length-prefixed string from r.\nfunc readString16(r io.Reader) (string, error) {\n\tvar sLen uint16\n\tif err := binary.Read(r, binary.LittleEndian, &sLen); err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, sLen)\n\tif _, err := io.ReadFull(r, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n","structuredPatch":[{"oldStart":61,"oldLines":6,"newStart":61,"newLines":7,"lines":[" \"encoding/binary\""," \"fmt\""," \"hash/crc32\"","+ \"hash/fnv\""," \"io\""," \"math\""," \"os\""]}],"userModified":false,"replaceAll":false},"sourceToolAssistantUUID":"0b6218a5-96c5-4d0c-b0c6-8461ff1f8ad3","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"ff720ed1-6bda-4b49-a116-ab8d7cf83e47","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01A5rGkeiikWFoidNZ4oLCpG","type":"message","role":"assistant","content":[{"type":"text","text":"Now replace the global channel declarations and add sharding infrastructure:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":484,"cache_read_input_tokens":48815,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":484},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zgBhVSKmdB568Uzv44","type":"assistant","uuid":"63c31566-f5e1-4e7f-8c97-19edfd2c619b","timestamp":"2026-03-18T05:29:46.962Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"63c31566-f5e1-4e7f-8c97-19edfd2c619b","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01A5rGkeiikWFoidNZ4oLCpG","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01SDcN43wiQJtT2atoNnpRDs","name":"Edit","input":{"replace_all":false,"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","old_string":"// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\n// Buffered to allow burst writes without blocking the metric ingestion path.\nvar WALMessages = make(chan *WALMessage, 65536)\n\n// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\n// (close, delete, reopen) after a binary snapshot has been written.\nvar walRotateCh = make(chan walRotateReq, 256)","new_string":"// walShardChs holds per-shard channels for WAL messages.\n// Initialized by WALStaging; nil when WAL is not active.\nvar walShardChs []chan *WALMessage\n\n// walShardRotateChs holds per-shard channels for WAL rotation requests.\nvar walShardRotateChs []chan walRotateReq\n\n// walNumShards stores the number of shards (set during WALStaging init).\nvar walNumShards int"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":484,"cache_read_input_tokens":48815,"output_tokens":356,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":484,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zgBhVSKmdB568Uzv44","type":"assistant","uuid":"69377157-45d8-4c04-b32f-f1ddb534194e","timestamp":"2026-03-18T05:29:51.982Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"69377157-45d8-4c04-b32f-f1ddb534194e","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Edit","command":"callback"},"parentToolUseID":"toolu_01SDcN43wiQJtT2atoNnpRDs","toolUseID":"toolu_01SDcN43wiQJtT2atoNnpRDs","timestamp":"2026-03-18T05:29:52.011Z","uuid":"b225055d-6992-4231-84d1-f58a442d9c17","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"69377157-45d8-4c04-b32f-f1ddb534194e","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01SDcN43wiQJtT2atoNnpRDs","type":"tool_result","content":"The file /Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go has been updated successfully."}]},"uuid":"737d5132-6e8a-4223-9217-3aff0eabc3cf","timestamp":"2026-03-18T05:29:52.011Z","toolUseResult":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","oldString":"// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\n// Buffered to allow burst writes without blocking the metric ingestion path.\nvar WALMessages = make(chan *WALMessage, 65536)\n\n// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\n// (close, delete, reopen) after a binary snapshot has been written.\nvar walRotateCh = make(chan walRotateReq, 256)","newString":"// walShardChs holds per-shard channels for WAL messages.\n// Initialized by WALStaging; nil when WAL is not active.\nvar walShardChs []chan *WALMessage\n\n// walShardRotateChs holds per-shard channels for WAL rotation requests.\nvar walShardRotateChs []chan walRotateReq\n\n// walNumShards stores the number of shards (set during WALStaging init).\nvar walNumShards int","originalFile":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides walCheckpoint.go: WAL-based checkpoint implementation.\n//\n// This replaces the Avro shadow tree with an append-only Write-Ahead Log (WAL)\n// per host, eliminating the extra memory overhead of the AvroStore and providing\n// truly continuous (per-write) crash safety.\n//\n// # Architecture\n//\n//\tMetric write (DecodeLine)\n//\t │\n//\t ├─► WriteToLevel() → main MemoryStore (unchanged)\n//\t │\n//\t └─► WALMessages channel\n//\t │\n//\t ▼\n//\t WALStaging goroutine\n//\t │\n//\t ▼\n//\t checkpoints/cluster/host/current.wal (append-only, binary)\n//\n//\tPeriodic checkpoint (Checkpointing goroutine):\n//\t 1. Write <timestamp>.bin snapshot (column-oriented, from main tree)\n//\t 2. Signal WALStaging to truncate current.wal per host\n//\n//\tOn restart (FromCheckpoint):\n//\t 1. Load most recent <timestamp>.bin snapshot\n//\t 2. Replay current.wal (overwrite-safe: buffer.write handles duplicate timestamps)\n//\n// # WAL Record Format\n//\n//\t[4B magic 0xCC1DA7A1][4B payload_len][payload][4B CRC32]\n//\n//\tpayload:\n//\t [8B timestamp int64]\n//\t [2B metric_name_len uint16][N metric name bytes]\n//\t [1B selector_count uint8]\n//\t per selector: [1B selector_len uint8][M selector bytes]\n//\t [4B value float32 bits]\n//\n// # Binary Snapshot Format\n//\n//\t[4B magic 0xCC5B0001][8B from int64][8B to int64]\n//\tLevel tree (recursive):\n//\t [4B num_metrics uint32]\n//\t per metric:\n//\t [2B name_len uint16][N name bytes]\n//\t [8B frequency int64][8B start int64]\n//\t [4B num_values uint32][num_values × 4B float32]\n//\t [4B num_children uint32]\n//\t per child: [2B name_len uint16][N name bytes] + Level (recursive)\npackage metricstore\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)\n\n// Magic numbers for binary formats.\nconst (\n\twalFileMagic = uint32(0xCC1DA701) // WAL file header magic\n\twalRecordMagic = uint32(0xCC1DA7A1) // WAL record magic\n\tsnapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic\n)\n\n// WALMessages is the channel for sending metric writes to the WAL staging goroutine.\n// Buffered to allow burst writes without blocking the metric ingestion path.\nvar WALMessages = make(chan *WALMessage, 65536)\n\n// walRotateCh is used by the checkpoint goroutine to request WAL file rotation\n// (close, delete, reopen) after a binary snapshot has been written.\nvar walRotateCh = make(chan walRotateReq, 256)\n\n// WALMessage represents a single metric write to be appended to the WAL.\n// Cluster and Node are NOT stored in the WAL record (inferred from file path).\ntype WALMessage struct {\n\tMetricName string\n\tCluster string\n\tNode string\n\tSelector []string\n\tValue schema.Float\n\tTimestamp int64\n}\n\n// walRotateReq requests WAL file rotation for a specific host directory.\n// The done channel is closed by the WAL goroutine when rotation is complete.\ntype walRotateReq struct {\n\thostDir string\n\tdone chan struct{}\n}\n\n// walFileState holds an open WAL file handle and buffered writer for one host directory.\ntype walFileState struct {\n\tf *os.File\n\tw *bufio.Writer\n}\n\n// WALStaging starts a background goroutine that receives WALMessage items\n// and appends binary WAL records to per-host current.wal files.\n// Also handles WAL rotation requests from the checkpoint goroutine.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\twg.Go(func() {\n\t\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\t\treturn\n\t\t}\n\n\t\thostFiles := make(map[string]*walFileState)\n\n\t\tdefer func() {\n\t\t\tfor _, ws := range hostFiles {\n\t\t\t\tif ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\tws, ok := hostFiles[hostDir]\n\t\t\tif ok {\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\tif err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t// Write file header magic if file is new (empty).\n\t\t\tinfo, err := f.Stat()\n\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\tvar hdr [4]byte\n\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\tf.Close()\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws = &walFileState{f: f, w: w}\n\t\t\thostFiles[hostDir] = ws\n\t\t\treturn ws\n\t\t}\n\n\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\tif ws == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := writeWALRecord(ws.w, msg); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tprocessRotate := func(req walRotateReq) {\n\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\tif ok && ws.f != nil {\n\t\t\t\tws.w.Flush()\n\t\t\t\tws.f.Close()\n\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t}\n\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t}\n\t\t\tclose(req.done)\n\t\t}\n\n\t\tdrain := func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\tdefault:\n\t\t\t\t\t// Flush all buffered writers after draining remaining messages.\n\t\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tdrain()\n\t\t\t\treturn\n\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\tfor range 256 {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tflushed:\n\t\t\t\t// Flush all buffered writers after processing the batch.\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase req := <-walRotateCh:\n\t\t\t\tprocessRotate(req)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFiles(hostDirs []string) {\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFilesAfterShutdown(hostDirs []string) {\n\tfor _, dir := range hostDirs {\n\t\twalPath := path.Join(dir, \"current.wal\")\n\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t}\n\t}\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {\n\tsize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tsize += 1 + len(s)\n\t}\n\n\tbuf := make([]byte, 0, size)\n\n\t// Timestamp (8 bytes, little-endian int64)\n\tvar ts [8]byte\n\tbinary.LittleEndian.PutUint64(ts[:], uint64(msg.Timestamp))\n\tbuf = append(buf, ts[:]...)\n\n\t// Metric name (2-byte length prefix + bytes)\n\tvar mLen [2]byte\n\tbinary.LittleEndian.PutUint16(mLen[:], uint16(len(msg.MetricName)))\n\tbuf = append(buf, mLen[:]...)\n\tbuf = append(buf, msg.MetricName...)\n\n\t// Selector count (1 byte)\n\tbuf = append(buf, byte(len(msg.Selector)))\n\n\t// Selectors (1-byte length prefix + bytes each)\n\tfor _, sel := range msg.Selector {\n\t\tbuf = append(buf, byte(len(sel)))\n\t\tbuf = append(buf, sel...)\n\t}\n\n\t// Value (4 bytes, float32 bit representation)\n\tvar val [4]byte\n\tbinary.LittleEndian.PutUint32(val[:], math.Float32bits(float32(msg.Value)))\n\tbuf = append(buf, val[:]...)\n\n\treturn buf\n}\n\n// writeWALRecord appends a binary WAL record to the writer.\n// Format: [4B magic][4B payload_len][payload][4B CRC32]\nfunc writeWALRecord(w io.Writer, msg *WALMessage) error {\n\tpayload := buildWALPayload(msg)\n\tcrc := crc32.ChecksumIEEE(payload)\n\n\trecord := make([]byte, 0, 4+4+len(payload)+4)\n\n\tvar magic [4]byte\n\tbinary.LittleEndian.PutUint32(magic[:], walRecordMagic)\n\trecord = append(record, magic[:]...)\n\n\tvar pLen [4]byte\n\tbinary.LittleEndian.PutUint32(pLen[:], uint32(len(payload)))\n\trecord = append(record, pLen[:]...)\n\n\trecord = append(record, payload...)\n\n\tvar crcBytes [4]byte\n\tbinary.LittleEndian.PutUint32(crcBytes[:], crc)\n\trecord = append(record, crcBytes[:]...)\n\n\t_, err := w.Write(record)\n\treturn err\n}\n\n// readWALRecord reads one WAL record from the reader.\n// Returns (nil, nil) on clean EOF. Returns error on data corruption.\n// A CRC mismatch indicates a truncated trailing record (expected on crash).\nfunc readWALRecord(r io.Reader) (*WALMessage, error) {\n\tvar magic uint32\n\tif err := binary.Read(r, binary.LittleEndian, &magic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil, nil // Clean EOF\n\t\t}\n\t\treturn nil, fmt.Errorf(\"read record magic: %w\", err)\n\t}\n\n\tif magic != walRecordMagic {\n\t\treturn nil, fmt.Errorf(\"invalid record magic 0x%08X (expected 0x%08X)\", magic, walRecordMagic)\n\t}\n\n\tvar payloadLen uint32\n\tif err := binary.Read(r, binary.LittleEndian, &payloadLen); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload length: %w\", err)\n\t}\n\n\tif payloadLen > 1<<20 { // 1 MB sanity limit\n\t\treturn nil, fmt.Errorf(\"record payload too large: %d bytes\", payloadLen)\n\t}\n\n\tpayload := make([]byte, payloadLen)\n\tif _, err := io.ReadFull(r, payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload: %w\", err)\n\t}\n\n\tvar storedCRC uint32\n\tif err := binary.Read(r, binary.LittleEndian, &storedCRC); err != nil {\n\t\treturn nil, fmt.Errorf(\"read CRC: %w\", err)\n\t}\n\n\tif crc32.ChecksumIEEE(payload) != storedCRC {\n\t\treturn nil, fmt.Errorf(\"CRC mismatch (truncated write or corruption)\")\n\t}\n\n\treturn parseWALPayload(payload)\n}\n\n// parseWALPayload decodes a binary payload into a WALMessage.\nfunc parseWALPayload(payload []byte) (*WALMessage, error) {\n\tif len(payload) < 8+2+1+4 {\n\t\treturn nil, fmt.Errorf(\"payload too short: %d bytes\", len(payload))\n\t}\n\n\toffset := 0\n\n\t// Timestamp (8 bytes)\n\tts := int64(binary.LittleEndian.Uint64(payload[offset : offset+8]))\n\toffset += 8\n\n\t// Metric name (2-byte length + bytes)\n\tif offset+2 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name length overflows payload\")\n\t}\n\tmLen := int(binary.LittleEndian.Uint16(payload[offset : offset+2]))\n\toffset += 2\n\n\tif offset+mLen > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name overflows payload\")\n\t}\n\tmetricName := string(payload[offset : offset+mLen])\n\toffset += mLen\n\n\t// Selector count (1 byte)\n\tif offset >= len(payload) {\n\t\treturn nil, fmt.Errorf(\"selector count overflows payload\")\n\t}\n\tselCount := int(payload[offset])\n\toffset++\n\n\tselectors := make([]string, selCount)\n\tfor i := range selCount {\n\t\tif offset >= len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] length overflows payload\", i)\n\t\t}\n\t\tsLen := int(payload[offset])\n\t\toffset++\n\n\t\tif offset+sLen > len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] data overflows payload\", i)\n\t\t}\n\t\tselectors[i] = string(payload[offset : offset+sLen])\n\t\toffset += sLen\n\t}\n\n\t// Value (4 bytes, float32 bits)\n\tif offset+4 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"value overflows payload\")\n\t}\n\tbits := binary.LittleEndian.Uint32(payload[offset : offset+4])\n\tvalue := schema.Float(math.Float32frombits(bits))\n\n\treturn &WALMessage{\n\t\tMetricName: metricName,\n\t\tTimestamp: ts,\n\t\tSelector: selectors,\n\t\tValue: value,\n\t}, nil\n}\n\n// loadWALFile reads a WAL file and replays all valid records into the Level tree.\n// l is the host-level node. Corrupt or partial trailing records are silently skipped\n// (expected on crash). Records older than 'from' are skipped.\nfunc (l *Level) loadWALFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\t// Verify file header magic.\n\tvar fileMagic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &fileMagic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil // Empty file, no data\n\t\t}\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: read file header: %w\", err)\n\t}\n\n\tif fileMagic != walFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: invalid file magic 0x%08X (expected 0x%08X)\", fileMagic, walFileMagic)\n\t}\n\n\t// Cache level lookups to avoid repeated tree traversal.\n\tlvlCache := make(map[string]*Level)\n\n\tfor {\n\t\tmsg, err := readWALRecord(br)\n\t\tif err != nil {\n\t\t\t// Truncated trailing record is expected after a crash; stop replaying.\n\t\t\tcclog.Debugf(\"[METRICSTORE]> WAL: stopping replay at corrupted/partial record: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tif msg == nil {\n\t\t\tbreak // Clean EOF\n\t\t}\n\n\t\tif msg.Timestamp < from {\n\t\t\tcontinue // Older than retention window\n\t\t}\n\n\t\tminfo, ok := m.Metrics[msg.MetricName]\n\t\tif !ok {\n\t\t\tcontinue // Unknown metric (config may have changed)\n\t\t}\n\n\t\t// Cache key is the null-separated selector path.\n\t\tcacheKey := joinSelector(msg.Selector)\n\t\tlvl, ok := lvlCache[cacheKey]\n\t\tif !ok {\n\t\t\tlvl = l.findLevelOrCreate(msg.Selector, len(m.Metrics))\n\t\t\tlvlCache[cacheKey] = lvl\n\t\t}\n\n\t\t// Write directly to the buffer, same as WriteToLevel but without the\n\t\t// global level lookup (we already have the right level).\n\t\tlvl.lock.Lock()\n\t\tb := lvl.metrics[minfo.offset]\n\t\tif b == nil {\n\t\t\tb = newBuffer(msg.Timestamp, minfo.Frequency)\n\t\t\tlvl.metrics[minfo.offset] = b\n\t\t}\n\t\tnb, writeErr := b.write(msg.Timestamp, msg.Value)\n\t\tif writeErr == nil && b != nb {\n\t\t\tlvl.metrics[minfo.offset] = nb\n\t\t}\n\t\t// Ignore write errors for timestamps before buffer start (can happen when\n\t\t// replaying WAL entries that predate a loaded snapshot's start time).\n\t\tlvl.lock.Unlock()\n\t}\n\n\treturn nil\n}\n\n// joinSelector builds a cache key from a selector slice using null bytes as separators.\nfunc joinSelector(sel []string) string {\n\tif len(sel) == 0 {\n\t\treturn \"\"\n\t}\n\tvar result strings.Builder\n\tresult.WriteString(sel[0])\n\tfor i := 1; i < len(sel); i++ {\n\t\tresult.WriteString(\"\\x00\" + sel[i])\n\t}\n\treturn result.String()\n}\n\n// ToCheckpointWAL writes binary snapshot files for all hosts in parallel.\n// Returns the number of files written, the list of host directories that were\n// successfully checkpointed (for WAL rotation), and any errors.\nfunc (m *MemoryStore) ToCheckpointWAL(dir string, from, to int64) (int, []string, error) {\n\t// Collect all cluster/host pairs.\n\tm.root.lock.RLock()\n\ttotalHosts := 0\n\tfor _, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\ttotalHosts += len(l1.children)\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\tlevels := make([]*Level, 0, totalHosts)\n\tselectors := make([][]string, 0, totalHosts)\n\n\tm.root.lock.RLock()\n\tfor sel1, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\tfor sel2, l2 := range l1.children {\n\t\t\tlevels = append(levels, l2)\n\t\t\tselectors = append(selectors, []string{sel1, sel2})\n\t\t}\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\ttype workItem struct {\n\t\tlevel *Level\n\t\thostDir string\n\t\tselector []string\n\t}\n\n\tn, errs := int32(0), int32(0)\n\tvar successDirs []string\n\tvar successMu sync.Mutex\n\n\tvar wg sync.WaitGroup\n\twg.Add(Keys.NumWorkers)\n\twork := make(chan workItem, Keys.NumWorkers*2)\n\n\tfor range Keys.NumWorkers {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor wi := range work {\n\t\t\t\terr := wi.level.toCheckpointBinary(wi.hostDir, from, to, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == ErrNoNewArchiveData {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> binary checkpoint error for %s: %v\", wi.hostDir, err)\n\t\t\t\t\tatomic.AddInt32(&errs, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.AddInt32(&n, 1)\n\t\t\t\t\tsuccessMu.Lock()\n\t\t\t\t\tsuccessDirs = append(successDirs, wi.hostDir)\n\t\t\t\t\tsuccessMu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor i := range levels {\n\t\thostDir := path.Join(dir, path.Join(selectors[i]...))\n\t\twork <- workItem{\n\t\t\tlevel: levels[i],\n\t\t\thostDir: hostDir,\n\t\t\tselector: selectors[i],\n\t\t}\n\t}\n\tclose(work)\n\twg.Wait()\n\n\tif errs > 0 {\n\t\treturn int(n), successDirs, fmt.Errorf(\"[METRICSTORE]> %d errors during binary checkpoint (%d successes)\", errs, n)\n\t}\n\treturn int(n), successDirs, nil\n}\n\n// toCheckpointBinary writes a binary snapshot file for a single host-level node.\n// Uses atomic rename (write to .tmp then rename) to avoid partial reads on crash.\nfunc (l *Level) toCheckpointBinary(dir string, from, to int64, m *MemoryStore) error {\n\tcf, err := l.toCheckpointFile(from, to, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cf == nil {\n\t\treturn ErrNoNewArchiveData\n\t}\n\n\tif err := os.MkdirAll(dir, CheckpointDirPerms); err != nil {\n\t\treturn fmt.Errorf(\"mkdir %s: %w\", dir, err)\n\t}\n\n\t// Write to a temp file first, then rename (atomic on POSIX).\n\ttmpPath := path.Join(dir, fmt.Sprintf(\"%d.bin.tmp\", from))\n\tfinalPath := path.Join(dir, fmt.Sprintf(\"%d.bin\", from))\n\n\tf, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, CheckpointFilePerms)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open binary snapshot %s: %w\", tmpPath, err)\n\t}\n\n\tbw := bufio.NewWriter(f)\n\tif err := writeBinarySnapshotFile(bw, cf); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn fmt.Errorf(\"write binary snapshot: %w\", err)\n\t}\n\tif err := bw.Flush(); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn err\n\t}\n\tf.Close()\n\n\treturn os.Rename(tmpPath, finalPath)\n}\n\n// writeBinarySnapshotFile writes the binary snapshot file header and level tree.\nfunc writeBinarySnapshotFile(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, snapFileMagic); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.From); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.To); err != nil {\n\t\treturn err\n\t}\n\treturn writeBinaryLevel(w, cf)\n}\n\n// writeBinaryLevel recursively writes a CheckpointFile level in binary format.\nfunc writeBinaryLevel(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Metrics))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, metric := range cf.Metrics {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Frequency); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Start); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, uint32(len(metric.Data))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, v := range metric.Data {\n\t\t\tif err := binary.Write(w, binary.LittleEndian, math.Float32bits(float32(v))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Children))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, child := range cf.Children {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writeBinaryLevel(w, child); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// writeString16 writes a 2-byte length-prefixed string to w.\nfunc writeString16(w io.Writer, s string) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint16(len(s))); err != nil {\n\t\treturn err\n\t}\n\t_, err := io.WriteString(w, s)\n\treturn err\n}\n\n// loadBinaryFile reads a binary snapshot file and loads data into the Level tree.\n// The retention check (from) is applied to the file's 'to' timestamp.\nfunc (l *Level) loadBinaryFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\tvar magic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &magic); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read magic: %w\", err)\n\t}\n\tif magic != snapFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: invalid magic 0x%08X (expected 0x%08X)\", magic, snapFileMagic)\n\t}\n\n\tvar fileFrom, fileTo int64\n\tif err := binary.Read(br, binary.LittleEndian, &fileFrom); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read from: %w\", err)\n\t}\n\tif err := binary.Read(br, binary.LittleEndian, &fileTo); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read to: %w\", err)\n\t}\n\n\tif fileTo != 0 && fileTo < from {\n\t\treturn nil // File is older than retention window, skip it\n\t}\n\n\tcf, err := readBinaryLevel(br)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read level tree: %w\", err)\n\t}\n\tcf.From = fileFrom\n\tcf.To = fileTo\n\n\treturn l.loadFile(cf, m)\n}\n\n// readBinaryLevel recursively reads a level from the binary snapshot format.\nfunc readBinaryLevel(r io.Reader) (*CheckpointFile, error) {\n\tcf := &CheckpointFile{\n\t\tMetrics: make(map[string]*CheckpointMetrics),\n\t\tChildren: make(map[string]*CheckpointFile),\n\t}\n\n\tvar numMetrics uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numMetrics); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_metrics: %w\", err)\n\t}\n\n\tfor range numMetrics {\n\t\tname, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read metric name: %w\", err)\n\t\t}\n\n\t\tvar freq, start int64\n\t\tif err := binary.Read(r, binary.LittleEndian, &freq); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read frequency for %s: %w\", name, err)\n\t\t}\n\t\tif err := binary.Read(r, binary.LittleEndian, &start); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read start for %s: %w\", name, err)\n\t\t}\n\n\t\tvar numValues uint32\n\t\tif err := binary.Read(r, binary.LittleEndian, &numValues); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read num_values for %s: %w\", name, err)\n\t\t}\n\n\t\tdata := make([]schema.Float, numValues)\n\t\tfor i := range numValues {\n\t\t\tvar bits uint32\n\t\t\tif err := binary.Read(r, binary.LittleEndian, &bits); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"read value[%d] for %s: %w\", i, name, err)\n\t\t\t}\n\t\t\tdata[i] = schema.Float(math.Float32frombits(bits))\n\t\t}\n\n\t\tcf.Metrics[name] = &CheckpointMetrics{\n\t\t\tFrequency: freq,\n\t\t\tStart: start,\n\t\t\tData: data,\n\t\t}\n\t}\n\n\tvar numChildren uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numChildren); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_children: %w\", err)\n\t}\n\n\tfor range numChildren {\n\t\tchildName, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child name: %w\", err)\n\t\t}\n\n\t\tchild, err := readBinaryLevel(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child %s: %w\", childName, err)\n\t\t}\n\t\tcf.Children[childName] = child\n\t}\n\n\treturn cf, nil\n}\n\n// readString16 reads a 2-byte length-prefixed string from r.\nfunc readString16(r io.Reader) (string, error) {\n\tvar sLen uint16\n\tif err := binary.Read(r, binary.LittleEndian, &sLen); err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, sLen)\n\tif _, err := io.ReadFull(r, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n","structuredPatch":[{"oldStart":81,"oldLines":14,"newStart":81,"newLines":16,"lines":[" snapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic"," )"," ","-// WALMessages is the channel for sending metric writes to the WAL staging goroutine.","-// Buffered to allow burst writes without blocking the metric ingestion path.","-var WALMessages = make(chan *WALMessage, 65536)","+// walShardChs holds per-shard channels for WAL messages.","+// Initialized by WALStaging; nil when WAL is not active.","+var walShardChs []chan *WALMessage"," ","-// walRotateCh is used by the checkpoint goroutine to request WAL file rotation","-// (close, delete, reopen) after a binary snapshot has been written.","-var walRotateCh = make(chan walRotateReq, 256)","+// walShardRotateChs holds per-shard channels for WAL rotation requests.","+var walShardRotateChs []chan walRotateReq"," ","+// walNumShards stores the number of shards (set during WALStaging init).","+var walNumShards int","+"," // WALMessage represents a single metric write to be appended to the WAL."," // Cluster and Node are NOT stored in the WAL record (inferred from file path)."," type WALMessage struct {"]}],"userModified":false,"replaceAll":false},"sourceToolAssistantUUID":"69377157-45d8-4c04-b32f-f1ddb534194e","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"737d5132-6e8a-4223-9217-3aff0eabc3cf","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01UkiNmp2ojYLjXiiABq4CBe","type":"message","role":"assistant","content":[{"type":"text","text":"Now replace the `WALStaging` function with the sharded version:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":605,"cache_read_input_tokens":49299,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":605},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zghVNv1GdSuBA5fT7i","type":"assistant","uuid":"42bedadd-e697-4576-b1a1-7f7472f588b7","timestamp":"2026-03-18T05:29:54.980Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"42bedadd-e697-4576-b1a1-7f7472f588b7","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01UkiNmp2ojYLjXiiABq4CBe","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01KuNHaxhouA5V546M6CKh2e","name":"Edit","input":{"replace_all":false,"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","old_string":"// WALStaging starts a background goroutine that receives WALMessage items\n// and appends binary WAL records to per-host current.wal files.\n// Also handles WAL rotation requests from the checkpoint goroutine.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\twg.Go(func() {\n\t\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\t\treturn\n\t\t}\n\n\t\thostFiles := make(map[string]*walFileState)\n\n\t\tdefer func() {\n\t\t\tfor _, ws := range hostFiles {\n\t\t\t\tif ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\tws, ok := hostFiles[hostDir]\n\t\t\tif ok {\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\tif err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t// Write file header magic if file is new (empty).\n\t\t\tinfo, err := f.Stat()\n\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\tvar hdr [4]byte\n\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\tf.Close()\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws = &walFileState{f: f, w: w}\n\t\t\thostFiles[hostDir] = ws\n\t\t\treturn ws\n\t\t}\n\n\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\tif ws == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := writeWALRecord(ws.w, msg); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tprocessRotate := func(req walRotateReq) {\n\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\tif ok && ws.f != nil {\n\t\t\t\tws.w.Flush()\n\t\t\t\tws.f.Close()\n\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t}\n\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t}\n\t\t\tclose(req.done)\n\t\t}\n\n\t\tdrain := func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\tdefault:\n\t\t\t\t\t// Flush all buffered writers after draining remaining messages.\n\t\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tdrain()\n\t\t\t\treturn\n\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\tfor range 256 {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tflushed:\n\t\t\t\t// Flush all buffered writers after processing the batch.\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase req := <-walRotateCh:\n\t\t\t\tprocessRotate(req)\n\t\t\t}\n\t\t}\n\t})\n}","new_string":"// walShardIndex computes which shard a message belongs to based on cluster+node.\n// Uses FNV-1a hash for fast, well-distributed mapping.\nfunc walShardIndex(cluster, node string) int {\n\th := fnv.New32a()\n\th.Write([]byte(cluster))\n\th.Write([]byte{0})\n\th.Write([]byte(node))\n\treturn int(h.Sum32()) % walNumShards\n}\n\n// SendWALMessage routes a WAL message to the appropriate shard channel.\n// Returns false if the channel is full (message dropped).\nfunc SendWALMessage(msg *WALMessage) bool {\n\tif walShardChs == nil {\n\t\treturn false\n\t}\n\tshard := walShardIndex(msg.Cluster, msg.Node)\n\tselect {\n\tcase walShardChs[shard] <- msg:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// WALStaging starts N sharded background goroutines that receive WALMessage items\n// and append binary WAL records to per-host current.wal files.\n// Each shard owns a subset of hosts (determined by hash of cluster+node),\n// parallelizing serialization and I/O while keeping per-host writes serial.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\treturn\n\t}\n\n\twalNumShards = max(Keys.NumWorkers, 1)\n\tchBufSize := max(65536/walNumShards, 1024)\n\n\twalShardChs = make([]chan *WALMessage, walNumShards)\n\twalShardRotateChs = make([]chan walRotateReq, walNumShards)\n\n\tfor i := range walNumShards {\n\t\twalShardChs[i] = make(chan *WALMessage, chBufSize)\n\t\twalShardRotateChs[i] = make(chan walRotateReq, 64)\n\t}\n\n\tfor i := range walNumShards {\n\t\tmsgCh := walShardChs[i]\n\t\trotateCh := walShardRotateChs[i]\n\n\t\twg.Go(func() {\n\t\t\thostFiles := make(map[string]*walFileState)\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\tws.f.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\t\tws, ok := hostFiles[hostDir]\n\t\t\t\tif ok {\n\t\t\t\t\treturn ws\n\t\t\t\t}\n\n\t\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t\t// Write file header magic if file is new (empty).\n\t\t\t\tinfo, err := f.Stat()\n\t\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\t\tvar hdr [4]byte\n\t\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\t\tf.Close()\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tws = &walFileState{f: f, w: w}\n\t\t\t\thostFiles[hostDir] = ws\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\t\tif ws == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := writeWALRecordDirect(ws.w, msg); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprocessRotate := func(req walRotateReq) {\n\t\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\t\tif ok && ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t\t}\n\t\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t\t}\n\t\t\t\tclose(req.done)\n\t\t\t}\n\n\t\t\tflushAll := func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdrain := func() {\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tflushAll()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tdrain()\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\t\tfor range 256 {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tflushed:\n\t\t\t\t\tflushAll()\n\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":605,"cache_read_input_tokens":49299,"output_tokens":3031,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":605,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zghVNv1GdSuBA5fT7i","type":"assistant","uuid":"204ce3a2-a499-4c2d-9ae9-1b3453c4603d","timestamp":"2026-03-18T05:30:26.596Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"204ce3a2-a499-4c2d-9ae9-1b3453c4603d","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Edit","command":"callback"},"parentToolUseID":"toolu_01KuNHaxhouA5V546M6CKh2e","toolUseID":"toolu_01KuNHaxhouA5V546M6CKh2e","timestamp":"2026-03-18T05:30:26.619Z","uuid":"e0dbc7f1-f7be-4876-87f5-1c1e89223084","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"204ce3a2-a499-4c2d-9ae9-1b3453c4603d","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01KuNHaxhouA5V546M6CKh2e","type":"tool_result","content":"The file /Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go has been updated successfully."}]},"uuid":"28929730-3cd1-4a1c-83da-2d5bd6de5ced","timestamp":"2026-03-18T05:30:26.619Z","toolUseResult":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","oldString":"// WALStaging starts a background goroutine that receives WALMessage items\n// and appends binary WAL records to per-host current.wal files.\n// Also handles WAL rotation requests from the checkpoint goroutine.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\twg.Go(func() {\n\t\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\t\treturn\n\t\t}\n\n\t\thostFiles := make(map[string]*walFileState)\n\n\t\tdefer func() {\n\t\t\tfor _, ws := range hostFiles {\n\t\t\t\tif ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\tws, ok := hostFiles[hostDir]\n\t\t\tif ok {\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\tif err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t// Write file header magic if file is new (empty).\n\t\t\tinfo, err := f.Stat()\n\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\tvar hdr [4]byte\n\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\tf.Close()\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws = &walFileState{f: f, w: w}\n\t\t\thostFiles[hostDir] = ws\n\t\t\treturn ws\n\t\t}\n\n\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\tif ws == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := writeWALRecord(ws.w, msg); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tprocessRotate := func(req walRotateReq) {\n\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\tif ok && ws.f != nil {\n\t\t\t\tws.w.Flush()\n\t\t\t\tws.f.Close()\n\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t}\n\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t}\n\t\t\tclose(req.done)\n\t\t}\n\n\t\tdrain := func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\tdefault:\n\t\t\t\t\t// Flush all buffered writers after draining remaining messages.\n\t\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tdrain()\n\t\t\t\treturn\n\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\tfor range 256 {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tflushed:\n\t\t\t\t// Flush all buffered writers after processing the batch.\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase req := <-walRotateCh:\n\t\t\t\tprocessRotate(req)\n\t\t\t}\n\t\t}\n\t})\n}","newString":"// walShardIndex computes which shard a message belongs to based on cluster+node.\n// Uses FNV-1a hash for fast, well-distributed mapping.\nfunc walShardIndex(cluster, node string) int {\n\th := fnv.New32a()\n\th.Write([]byte(cluster))\n\th.Write([]byte{0})\n\th.Write([]byte(node))\n\treturn int(h.Sum32()) % walNumShards\n}\n\n// SendWALMessage routes a WAL message to the appropriate shard channel.\n// Returns false if the channel is full (message dropped).\nfunc SendWALMessage(msg *WALMessage) bool {\n\tif walShardChs == nil {\n\t\treturn false\n\t}\n\tshard := walShardIndex(msg.Cluster, msg.Node)\n\tselect {\n\tcase walShardChs[shard] <- msg:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// WALStaging starts N sharded background goroutines that receive WALMessage items\n// and append binary WAL records to per-host current.wal files.\n// Each shard owns a subset of hosts (determined by hash of cluster+node),\n// parallelizing serialization and I/O while keeping per-host writes serial.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\treturn\n\t}\n\n\twalNumShards = max(Keys.NumWorkers, 1)\n\tchBufSize := max(65536/walNumShards, 1024)\n\n\twalShardChs = make([]chan *WALMessage, walNumShards)\n\twalShardRotateChs = make([]chan walRotateReq, walNumShards)\n\n\tfor i := range walNumShards {\n\t\twalShardChs[i] = make(chan *WALMessage, chBufSize)\n\t\twalShardRotateChs[i] = make(chan walRotateReq, 64)\n\t}\n\n\tfor i := range walNumShards {\n\t\tmsgCh := walShardChs[i]\n\t\trotateCh := walShardRotateChs[i]\n\n\t\twg.Go(func() {\n\t\t\thostFiles := make(map[string]*walFileState)\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\tws.f.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\t\tws, ok := hostFiles[hostDir]\n\t\t\t\tif ok {\n\t\t\t\t\treturn ws\n\t\t\t\t}\n\n\t\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t\t// Write file header magic if file is new (empty).\n\t\t\t\tinfo, err := f.Stat()\n\t\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\t\tvar hdr [4]byte\n\t\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\t\tf.Close()\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tws = &walFileState{f: f, w: w}\n\t\t\t\thostFiles[hostDir] = ws\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\t\tif ws == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := writeWALRecordDirect(ws.w, msg); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprocessRotate := func(req walRotateReq) {\n\t\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\t\tif ok && ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t\t}\n\t\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t\t}\n\t\t\t\tclose(req.done)\n\t\t\t}\n\n\t\t\tflushAll := func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdrain := func() {\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tflushAll()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tdrain()\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\t\tfor range 256 {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tflushed:\n\t\t\t\t\tflushAll()\n\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}","originalFile":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides walCheckpoint.go: WAL-based checkpoint implementation.\n//\n// This replaces the Avro shadow tree with an append-only Write-Ahead Log (WAL)\n// per host, eliminating the extra memory overhead of the AvroStore and providing\n// truly continuous (per-write) crash safety.\n//\n// # Architecture\n//\n//\tMetric write (DecodeLine)\n//\t │\n//\t ├─► WriteToLevel() → main MemoryStore (unchanged)\n//\t │\n//\t └─► WALMessages channel\n//\t │\n//\t ▼\n//\t WALStaging goroutine\n//\t │\n//\t ▼\n//\t checkpoints/cluster/host/current.wal (append-only, binary)\n//\n//\tPeriodic checkpoint (Checkpointing goroutine):\n//\t 1. Write <timestamp>.bin snapshot (column-oriented, from main tree)\n//\t 2. Signal WALStaging to truncate current.wal per host\n//\n//\tOn restart (FromCheckpoint):\n//\t 1. Load most recent <timestamp>.bin snapshot\n//\t 2. Replay current.wal (overwrite-safe: buffer.write handles duplicate timestamps)\n//\n// # WAL Record Format\n//\n//\t[4B magic 0xCC1DA7A1][4B payload_len][payload][4B CRC32]\n//\n//\tpayload:\n//\t [8B timestamp int64]\n//\t [2B metric_name_len uint16][N metric name bytes]\n//\t [1B selector_count uint8]\n//\t per selector: [1B selector_len uint8][M selector bytes]\n//\t [4B value float32 bits]\n//\n// # Binary Snapshot Format\n//\n//\t[4B magic 0xCC5B0001][8B from int64][8B to int64]\n//\tLevel tree (recursive):\n//\t [4B num_metrics uint32]\n//\t per metric:\n//\t [2B name_len uint16][N name bytes]\n//\t [8B frequency int64][8B start int64]\n//\t [4B num_values uint32][num_values × 4B float32]\n//\t [4B num_children uint32]\n//\t per child: [2B name_len uint16][N name bytes] + Level (recursive)\npackage metricstore\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)\n\n// Magic numbers for binary formats.\nconst (\n\twalFileMagic = uint32(0xCC1DA701) // WAL file header magic\n\twalRecordMagic = uint32(0xCC1DA7A1) // WAL record magic\n\tsnapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic\n)\n\n// walShardChs holds per-shard channels for WAL messages.\n// Initialized by WALStaging; nil when WAL is not active.\nvar walShardChs []chan *WALMessage\n\n// walShardRotateChs holds per-shard channels for WAL rotation requests.\nvar walShardRotateChs []chan walRotateReq\n\n// walNumShards stores the number of shards (set during WALStaging init).\nvar walNumShards int\n\n// WALMessage represents a single metric write to be appended to the WAL.\n// Cluster and Node are NOT stored in the WAL record (inferred from file path).\ntype WALMessage struct {\n\tMetricName string\n\tCluster string\n\tNode string\n\tSelector []string\n\tValue schema.Float\n\tTimestamp int64\n}\n\n// walRotateReq requests WAL file rotation for a specific host directory.\n// The done channel is closed by the WAL goroutine when rotation is complete.\ntype walRotateReq struct {\n\thostDir string\n\tdone chan struct{}\n}\n\n// walFileState holds an open WAL file handle and buffered writer for one host directory.\ntype walFileState struct {\n\tf *os.File\n\tw *bufio.Writer\n}\n\n// WALStaging starts a background goroutine that receives WALMessage items\n// and appends binary WAL records to per-host current.wal files.\n// Also handles WAL rotation requests from the checkpoint goroutine.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\twg.Go(func() {\n\t\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\t\treturn\n\t\t}\n\n\t\thostFiles := make(map[string]*walFileState)\n\n\t\tdefer func() {\n\t\t\tfor _, ws := range hostFiles {\n\t\t\t\tif ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\tws, ok := hostFiles[hostDir]\n\t\t\tif ok {\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\tif err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t// Write file header magic if file is new (empty).\n\t\t\tinfo, err := f.Stat()\n\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\tvar hdr [4]byte\n\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\tf.Close()\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws = &walFileState{f: f, w: w}\n\t\t\thostFiles[hostDir] = ws\n\t\t\treturn ws\n\t\t}\n\n\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\tif ws == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := writeWALRecord(ws.w, msg); err != nil {\n\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t}\n\t\t}\n\n\t\tprocessRotate := func(req walRotateReq) {\n\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\tif ok && ws.f != nil {\n\t\t\t\tws.w.Flush()\n\t\t\t\tws.f.Close()\n\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t}\n\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t}\n\t\t\tclose(req.done)\n\t\t}\n\n\t\tdrain := func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\tdefault:\n\t\t\t\t\t// Flush all buffered writers after draining remaining messages.\n\t\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tdrain()\n\t\t\t\treturn\n\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\tfor range 256 {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-WALMessages:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-walRotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tflushed:\n\t\t\t\t// Flush all buffered writers after processing the batch.\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase req := <-walRotateCh:\n\t\t\t\tprocessRotate(req)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFiles(hostDirs []string) {\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFilesAfterShutdown(hostDirs []string) {\n\tfor _, dir := range hostDirs {\n\t\twalPath := path.Join(dir, \"current.wal\")\n\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t}\n\t}\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {\n\tsize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tsize += 1 + len(s)\n\t}\n\n\tbuf := make([]byte, 0, size)\n\n\t// Timestamp (8 bytes, little-endian int64)\n\tvar ts [8]byte\n\tbinary.LittleEndian.PutUint64(ts[:], uint64(msg.Timestamp))\n\tbuf = append(buf, ts[:]...)\n\n\t// Metric name (2-byte length prefix + bytes)\n\tvar mLen [2]byte\n\tbinary.LittleEndian.PutUint16(mLen[:], uint16(len(msg.MetricName)))\n\tbuf = append(buf, mLen[:]...)\n\tbuf = append(buf, msg.MetricName...)\n\n\t// Selector count (1 byte)\n\tbuf = append(buf, byte(len(msg.Selector)))\n\n\t// Selectors (1-byte length prefix + bytes each)\n\tfor _, sel := range msg.Selector {\n\t\tbuf = append(buf, byte(len(sel)))\n\t\tbuf = append(buf, sel...)\n\t}\n\n\t// Value (4 bytes, float32 bit representation)\n\tvar val [4]byte\n\tbinary.LittleEndian.PutUint32(val[:], math.Float32bits(float32(msg.Value)))\n\tbuf = append(buf, val[:]...)\n\n\treturn buf\n}\n\n// writeWALRecord appends a binary WAL record to the writer.\n// Format: [4B magic][4B payload_len][payload][4B CRC32]\nfunc writeWALRecord(w io.Writer, msg *WALMessage) error {\n\tpayload := buildWALPayload(msg)\n\tcrc := crc32.ChecksumIEEE(payload)\n\n\trecord := make([]byte, 0, 4+4+len(payload)+4)\n\n\tvar magic [4]byte\n\tbinary.LittleEndian.PutUint32(magic[:], walRecordMagic)\n\trecord = append(record, magic[:]...)\n\n\tvar pLen [4]byte\n\tbinary.LittleEndian.PutUint32(pLen[:], uint32(len(payload)))\n\trecord = append(record, pLen[:]...)\n\n\trecord = append(record, payload...)\n\n\tvar crcBytes [4]byte\n\tbinary.LittleEndian.PutUint32(crcBytes[:], crc)\n\trecord = append(record, crcBytes[:]...)\n\n\t_, err := w.Write(record)\n\treturn err\n}\n\n// readWALRecord reads one WAL record from the reader.\n// Returns (nil, nil) on clean EOF. Returns error on data corruption.\n// A CRC mismatch indicates a truncated trailing record (expected on crash).\nfunc readWALRecord(r io.Reader) (*WALMessage, error) {\n\tvar magic uint32\n\tif err := binary.Read(r, binary.LittleEndian, &magic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil, nil // Clean EOF\n\t\t}\n\t\treturn nil, fmt.Errorf(\"read record magic: %w\", err)\n\t}\n\n\tif magic != walRecordMagic {\n\t\treturn nil, fmt.Errorf(\"invalid record magic 0x%08X (expected 0x%08X)\", magic, walRecordMagic)\n\t}\n\n\tvar payloadLen uint32\n\tif err := binary.Read(r, binary.LittleEndian, &payloadLen); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload length: %w\", err)\n\t}\n\n\tif payloadLen > 1<<20 { // 1 MB sanity limit\n\t\treturn nil, fmt.Errorf(\"record payload too large: %d bytes\", payloadLen)\n\t}\n\n\tpayload := make([]byte, payloadLen)\n\tif _, err := io.ReadFull(r, payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload: %w\", err)\n\t}\n\n\tvar storedCRC uint32\n\tif err := binary.Read(r, binary.LittleEndian, &storedCRC); err != nil {\n\t\treturn nil, fmt.Errorf(\"read CRC: %w\", err)\n\t}\n\n\tif crc32.ChecksumIEEE(payload) != storedCRC {\n\t\treturn nil, fmt.Errorf(\"CRC mismatch (truncated write or corruption)\")\n\t}\n\n\treturn parseWALPayload(payload)\n}\n\n// parseWALPayload decodes a binary payload into a WALMessage.\nfunc parseWALPayload(payload []byte) (*WALMessage, error) {\n\tif len(payload) < 8+2+1+4 {\n\t\treturn nil, fmt.Errorf(\"payload too short: %d bytes\", len(payload))\n\t}\n\n\toffset := 0\n\n\t// Timestamp (8 bytes)\n\tts := int64(binary.LittleEndian.Uint64(payload[offset : offset+8]))\n\toffset += 8\n\n\t// Metric name (2-byte length + bytes)\n\tif offset+2 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name length overflows payload\")\n\t}\n\tmLen := int(binary.LittleEndian.Uint16(payload[offset : offset+2]))\n\toffset += 2\n\n\tif offset+mLen > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name overflows payload\")\n\t}\n\tmetricName := string(payload[offset : offset+mLen])\n\toffset += mLen\n\n\t// Selector count (1 byte)\n\tif offset >= len(payload) {\n\t\treturn nil, fmt.Errorf(\"selector count overflows payload\")\n\t}\n\tselCount := int(payload[offset])\n\toffset++\n\n\tselectors := make([]string, selCount)\n\tfor i := range selCount {\n\t\tif offset >= len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] length overflows payload\", i)\n\t\t}\n\t\tsLen := int(payload[offset])\n\t\toffset++\n\n\t\tif offset+sLen > len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] data overflows payload\", i)\n\t\t}\n\t\tselectors[i] = string(payload[offset : offset+sLen])\n\t\toffset += sLen\n\t}\n\n\t// Value (4 bytes, float32 bits)\n\tif offset+4 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"value overflows payload\")\n\t}\n\tbits := binary.LittleEndian.Uint32(payload[offset : offset+4])\n\tvalue := schema.Float(math.Float32frombits(bits))\n\n\treturn &WALMessage{\n\t\tMetricName: metricName,\n\t\tTimestamp: ts,\n\t\tSelector: selectors,\n\t\tValue: value,\n\t}, nil\n}\n\n// loadWALFile reads a WAL file and replays all valid records into the Level tree.\n// l is the host-level node. Corrupt or partial trailing records are silently skipped\n// (expected on crash). Records older than 'from' are skipped.\nfunc (l *Level) loadWALFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\t// Verify file header magic.\n\tvar fileMagic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &fileMagic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil // Empty file, no data\n\t\t}\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: read file header: %w\", err)\n\t}\n\n\tif fileMagic != walFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: invalid file magic 0x%08X (expected 0x%08X)\", fileMagic, walFileMagic)\n\t}\n\n\t// Cache level lookups to avoid repeated tree traversal.\n\tlvlCache := make(map[string]*Level)\n\n\tfor {\n\t\tmsg, err := readWALRecord(br)\n\t\tif err != nil {\n\t\t\t// Truncated trailing record is expected after a crash; stop replaying.\n\t\t\tcclog.Debugf(\"[METRICSTORE]> WAL: stopping replay at corrupted/partial record: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tif msg == nil {\n\t\t\tbreak // Clean EOF\n\t\t}\n\n\t\tif msg.Timestamp < from {\n\t\t\tcontinue // Older than retention window\n\t\t}\n\n\t\tminfo, ok := m.Metrics[msg.MetricName]\n\t\tif !ok {\n\t\t\tcontinue // Unknown metric (config may have changed)\n\t\t}\n\n\t\t// Cache key is the null-separated selector path.\n\t\tcacheKey := joinSelector(msg.Selector)\n\t\tlvl, ok := lvlCache[cacheKey]\n\t\tif !ok {\n\t\t\tlvl = l.findLevelOrCreate(msg.Selector, len(m.Metrics))\n\t\t\tlvlCache[cacheKey] = lvl\n\t\t}\n\n\t\t// Write directly to the buffer, same as WriteToLevel but without the\n\t\t// global level lookup (we already have the right level).\n\t\tlvl.lock.Lock()\n\t\tb := lvl.metrics[minfo.offset]\n\t\tif b == nil {\n\t\t\tb = newBuffer(msg.Timestamp, minfo.Frequency)\n\t\t\tlvl.metrics[minfo.offset] = b\n\t\t}\n\t\tnb, writeErr := b.write(msg.Timestamp, msg.Value)\n\t\tif writeErr == nil && b != nb {\n\t\t\tlvl.metrics[minfo.offset] = nb\n\t\t}\n\t\t// Ignore write errors for timestamps before buffer start (can happen when\n\t\t// replaying WAL entries that predate a loaded snapshot's start time).\n\t\tlvl.lock.Unlock()\n\t}\n\n\treturn nil\n}\n\n// joinSelector builds a cache key from a selector slice using null bytes as separators.\nfunc joinSelector(sel []string) string {\n\tif len(sel) == 0 {\n\t\treturn \"\"\n\t}\n\tvar result strings.Builder\n\tresult.WriteString(sel[0])\n\tfor i := 1; i < len(sel); i++ {\n\t\tresult.WriteString(\"\\x00\" + sel[i])\n\t}\n\treturn result.String()\n}\n\n// ToCheckpointWAL writes binary snapshot files for all hosts in parallel.\n// Returns the number of files written, the list of host directories that were\n// successfully checkpointed (for WAL rotation), and any errors.\nfunc (m *MemoryStore) ToCheckpointWAL(dir string, from, to int64) (int, []string, error) {\n\t// Collect all cluster/host pairs.\n\tm.root.lock.RLock()\n\ttotalHosts := 0\n\tfor _, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\ttotalHosts += len(l1.children)\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\tlevels := make([]*Level, 0, totalHosts)\n\tselectors := make([][]string, 0, totalHosts)\n\n\tm.root.lock.RLock()\n\tfor sel1, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\tfor sel2, l2 := range l1.children {\n\t\t\tlevels = append(levels, l2)\n\t\t\tselectors = append(selectors, []string{sel1, sel2})\n\t\t}\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\ttype workItem struct {\n\t\tlevel *Level\n\t\thostDir string\n\t\tselector []string\n\t}\n\n\tn, errs := int32(0), int32(0)\n\tvar successDirs []string\n\tvar successMu sync.Mutex\n\n\tvar wg sync.WaitGroup\n\twg.Add(Keys.NumWorkers)\n\twork := make(chan workItem, Keys.NumWorkers*2)\n\n\tfor range Keys.NumWorkers {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor wi := range work {\n\t\t\t\terr := wi.level.toCheckpointBinary(wi.hostDir, from, to, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == ErrNoNewArchiveData {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> binary checkpoint error for %s: %v\", wi.hostDir, err)\n\t\t\t\t\tatomic.AddInt32(&errs, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.AddInt32(&n, 1)\n\t\t\t\t\tsuccessMu.Lock()\n\t\t\t\t\tsuccessDirs = append(successDirs, wi.hostDir)\n\t\t\t\t\tsuccessMu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor i := range levels {\n\t\thostDir := path.Join(dir, path.Join(selectors[i]...))\n\t\twork <- workItem{\n\t\t\tlevel: levels[i],\n\t\t\thostDir: hostDir,\n\t\t\tselector: selectors[i],\n\t\t}\n\t}\n\tclose(work)\n\twg.Wait()\n\n\tif errs > 0 {\n\t\treturn int(n), successDirs, fmt.Errorf(\"[METRICSTORE]> %d errors during binary checkpoint (%d successes)\", errs, n)\n\t}\n\treturn int(n), successDirs, nil\n}\n\n// toCheckpointBinary writes a binary snapshot file for a single host-level node.\n// Uses atomic rename (write to .tmp then rename) to avoid partial reads on crash.\nfunc (l *Level) toCheckpointBinary(dir string, from, to int64, m *MemoryStore) error {\n\tcf, err := l.toCheckpointFile(from, to, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cf == nil {\n\t\treturn ErrNoNewArchiveData\n\t}\n\n\tif err := os.MkdirAll(dir, CheckpointDirPerms); err != nil {\n\t\treturn fmt.Errorf(\"mkdir %s: %w\", dir, err)\n\t}\n\n\t// Write to a temp file first, then rename (atomic on POSIX).\n\ttmpPath := path.Join(dir, fmt.Sprintf(\"%d.bin.tmp\", from))\n\tfinalPath := path.Join(dir, fmt.Sprintf(\"%d.bin\", from))\n\n\tf, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, CheckpointFilePerms)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open binary snapshot %s: %w\", tmpPath, err)\n\t}\n\n\tbw := bufio.NewWriter(f)\n\tif err := writeBinarySnapshotFile(bw, cf); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn fmt.Errorf(\"write binary snapshot: %w\", err)\n\t}\n\tif err := bw.Flush(); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn err\n\t}\n\tf.Close()\n\n\treturn os.Rename(tmpPath, finalPath)\n}\n\n// writeBinarySnapshotFile writes the binary snapshot file header and level tree.\nfunc writeBinarySnapshotFile(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, snapFileMagic); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.From); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.To); err != nil {\n\t\treturn err\n\t}\n\treturn writeBinaryLevel(w, cf)\n}\n\n// writeBinaryLevel recursively writes a CheckpointFile level in binary format.\nfunc writeBinaryLevel(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Metrics))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, metric := range cf.Metrics {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Frequency); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Start); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, uint32(len(metric.Data))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, v := range metric.Data {\n\t\t\tif err := binary.Write(w, binary.LittleEndian, math.Float32bits(float32(v))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Children))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, child := range cf.Children {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writeBinaryLevel(w, child); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// writeString16 writes a 2-byte length-prefixed string to w.\nfunc writeString16(w io.Writer, s string) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint16(len(s))); err != nil {\n\t\treturn err\n\t}\n\t_, err := io.WriteString(w, s)\n\treturn err\n}\n\n// loadBinaryFile reads a binary snapshot file and loads data into the Level tree.\n// The retention check (from) is applied to the file's 'to' timestamp.\nfunc (l *Level) loadBinaryFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\tvar magic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &magic); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read magic: %w\", err)\n\t}\n\tif magic != snapFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: invalid magic 0x%08X (expected 0x%08X)\", magic, snapFileMagic)\n\t}\n\n\tvar fileFrom, fileTo int64\n\tif err := binary.Read(br, binary.LittleEndian, &fileFrom); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read from: %w\", err)\n\t}\n\tif err := binary.Read(br, binary.LittleEndian, &fileTo); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read to: %w\", err)\n\t}\n\n\tif fileTo != 0 && fileTo < from {\n\t\treturn nil // File is older than retention window, skip it\n\t}\n\n\tcf, err := readBinaryLevel(br)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read level tree: %w\", err)\n\t}\n\tcf.From = fileFrom\n\tcf.To = fileTo\n\n\treturn l.loadFile(cf, m)\n}\n\n// readBinaryLevel recursively reads a level from the binary snapshot format.\nfunc readBinaryLevel(r io.Reader) (*CheckpointFile, error) {\n\tcf := &CheckpointFile{\n\t\tMetrics: make(map[string]*CheckpointMetrics),\n\t\tChildren: make(map[string]*CheckpointFile),\n\t}\n\n\tvar numMetrics uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numMetrics); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_metrics: %w\", err)\n\t}\n\n\tfor range numMetrics {\n\t\tname, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read metric name: %w\", err)\n\t\t}\n\n\t\tvar freq, start int64\n\t\tif err := binary.Read(r, binary.LittleEndian, &freq); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read frequency for %s: %w\", name, err)\n\t\t}\n\t\tif err := binary.Read(r, binary.LittleEndian, &start); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read start for %s: %w\", name, err)\n\t\t}\n\n\t\tvar numValues uint32\n\t\tif err := binary.Read(r, binary.LittleEndian, &numValues); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read num_values for %s: %w\", name, err)\n\t\t}\n\n\t\tdata := make([]schema.Float, numValues)\n\t\tfor i := range numValues {\n\t\t\tvar bits uint32\n\t\t\tif err := binary.Read(r, binary.LittleEndian, &bits); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"read value[%d] for %s: %w\", i, name, err)\n\t\t\t}\n\t\t\tdata[i] = schema.Float(math.Float32frombits(bits))\n\t\t}\n\n\t\tcf.Metrics[name] = &CheckpointMetrics{\n\t\t\tFrequency: freq,\n\t\t\tStart: start,\n\t\t\tData: data,\n\t\t}\n\t}\n\n\tvar numChildren uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numChildren); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_children: %w\", err)\n\t}\n\n\tfor range numChildren {\n\t\tchildName, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child name: %w\", err)\n\t\t}\n\n\t\tchild, err := readBinaryLevel(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child %s: %w\", childName, err)\n\t\t}\n\t\tcf.Children[childName] = child\n\t}\n\n\treturn cf, nil\n}\n\n// readString16 reads a 2-byte length-prefixed string from r.\nfunc readString16(r io.Reader) (string, error) {\n\tvar sLen uint16\n\tif err := binary.Read(r, binary.LittleEndian, &sLen); err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, sLen)\n\tif _, err := io.ReadFull(r, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n","structuredPatch":[{"oldStart":115,"oldLines":147,"newStart":115,"newLines":187,"lines":[" w *bufio.Writer"," }"," ","-// WALStaging starts a background goroutine that receives WALMessage items","-// and appends binary WAL records to per-host current.wal files.","-// Also handles WAL rotation requests from the checkpoint goroutine.","+// walShardIndex computes which shard a message belongs to based on cluster+node.","+// Uses FNV-1a hash for fast, well-distributed mapping.","+func walShardIndex(cluster, node string) int {","+ h := fnv.New32a()","+ h.Write([]byte(cluster))","+ h.Write([]byte{0})","+ h.Write([]byte(node))","+ return int(h.Sum32()) % walNumShards","+}","+","+// SendWALMessage routes a WAL message to the appropriate shard channel.","+// Returns false if the channel is full (message dropped).","+func SendWALMessage(msg *WALMessage) bool {","+ if walShardChs == nil {","+ return false","+ }","+ shard := walShardIndex(msg.Cluster, msg.Node)","+ select {","+ case walShardChs[shard] <- msg:","+ return true","+ default:","+ return false","+ }","+}","+","+// WALStaging starts N sharded background goroutines that receive WALMessage items","+// and append binary WAL records to per-host current.wal files.","+// Each shard owns a subset of hosts (determined by hash of cluster+node),","+// parallelizing serialization and I/O while keeping per-host writes serial."," func WALStaging(wg *sync.WaitGroup, ctx context.Context) {","- wg.Go(func() {","- if Keys.Checkpoints.FileFormat == \"json\" {","- return","- }","+ if Keys.Checkpoints.FileFormat == \"json\" {","+ return","+ }"," ","- hostFiles := make(map[string]*walFileState)","+ walNumShards = max(Keys.NumWorkers, 1)","+ chBufSize := max(65536/walNumShards, 1024)"," ","- defer func() {","- for _, ws := range hostFiles {","- if ws.f != nil {","- ws.w.Flush()","- ws.f.Close()","- }","- }","- }()","+ walShardChs = make([]chan *WALMessage, walNumShards)","+ walShardRotateChs = make([]chan walRotateReq, walNumShards)"," ","- getOrOpenWAL := func(hostDir string) *walFileState {","- ws, ok := hostFiles[hostDir]","- if ok {","- return ws","- }","+ for i := range walNumShards {","+ walShardChs[i] = make(chan *WALMessage, chBufSize)","+ walShardRotateChs[i] = make(chan walRotateReq, 64)","+ }"," ","- if err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {","- cclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)","- return nil","- }","+ for i := range walNumShards {","+ msgCh := walShardChs[i]","+ rotateCh := walShardRotateChs[i]"," ","- walPath := path.Join(hostDir, \"current.wal\")","- f, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)","- if err != nil {","- cclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)","- return nil","- }","+ wg.Go(func() {","+ hostFiles := make(map[string]*walFileState)"," ","- w := bufio.NewWriter(f)","+ defer func() {","+ for _, ws := range hostFiles {","+ if ws.f != nil {","+ ws.w.Flush()","+ ws.f.Close()","+ }","+ }","+ }()"," ","- // Write file header magic if file is new (empty).","- info, err := f.Stat()","- if err == nil && info.Size() == 0 {","- var hdr [4]byte","- binary.LittleEndian.PutUint32(hdr[:], walFileMagic)","- if _, err := w.Write(hdr[:]); err != nil {","- cclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)","- f.Close()","+ getOrOpenWAL := func(hostDir string) *walFileState {","+ ws, ok := hostFiles[hostDir]","+ if ok {","+ return ws","+ }","+","+ if err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {","+ cclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)"," return nil"," }","- }"," ","- ws = &walFileState{f: f, w: w}","- hostFiles[hostDir] = ws","- return ws","- }","+ walPath := path.Join(hostDir, \"current.wal\")","+ f, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)","+ if err != nil {","+ cclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)","+ return nil","+ }"," ","- processMsg := func(msg *WALMessage) {","- hostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)","- ws := getOrOpenWAL(hostDir)","- if ws == nil {","- return","+ w := bufio.NewWriter(f)","+","+ // Write file header magic if file is new (empty).","+ info, err := f.Stat()","+ if err == nil && info.Size() == 0 {","+ var hdr [4]byte","+ binary.LittleEndian.PutUint32(hdr[:], walFileMagic)","+ if _, err := w.Write(hdr[:]); err != nil {","+ cclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)","+ f.Close()","+ return nil","+ }","+ }","+","+ ws = &walFileState{f: f, w: w}","+ hostFiles[hostDir] = ws","+ return ws"," }","- if err := writeWALRecord(ws.w, msg); err != nil {","- cclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)","- }","- }"," ","- processRotate := func(req walRotateReq) {","- ws, ok := hostFiles[req.hostDir]","- if ok && ws.f != nil {","- ws.w.Flush()","- ws.f.Close()","- walPath := path.Join(req.hostDir, \"current.wal\")","- if err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {","- cclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)","+ processMsg := func(msg *WALMessage) {","+ hostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)","+ ws := getOrOpenWAL(hostDir)","+ if ws == nil {","+ return"," }","- delete(hostFiles, req.hostDir)","+ if err := writeWALRecordDirect(ws.w, msg); err != nil {","+ cclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)","+ }"," }","- close(req.done)","- }"," ","- drain := func() {","- for {","- select {","- case msg, ok := <-WALMessages:","- if !ok {","- return","+ processRotate := func(req walRotateReq) {","+ ws, ok := hostFiles[req.hostDir]","+ if ok && ws.f != nil {","+ ws.w.Flush()","+ ws.f.Close()","+ walPath := path.Join(req.hostDir, \"current.wal\")","+ if err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {","+ cclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)"," }","- processMsg(msg)","- case req := <-walRotateCh:","- processRotate(req)","- default:","- // Flush all buffered writers after draining remaining messages.","- for _, ws := range hostFiles {","- if ws.f != nil {","- ws.w.Flush()","- }","- }","- return","+ delete(hostFiles, req.hostDir)"," }","+ close(req.done)"," }","- }"," ","- for {","- select {","- case <-ctx.Done():","- drain()","- return","- case msg, ok := <-WALMessages:","- if !ok {","- return","+ flushAll := func() {","+ for _, ws := range hostFiles {","+ if ws.f != nil {","+ ws.w.Flush()","+ }"," }","- processMsg(msg)","+ }"," ","- // Drain up to 256 more messages without blocking to batch writes.","- for range 256 {","+ drain := func() {","+ for {"," select {","- case msg, ok := <-WALMessages:","+ case msg, ok := <-msgCh:"," if !ok {"," return"," }"," processMsg(msg)","- case req := <-walRotateCh:","+ case req := <-rotateCh:"," processRotate(req)"," default:","- goto flushed","+ flushAll()","+ return"," }"," }","- flushed:","- // Flush all buffered writers after processing the batch.","- for _, ws := range hostFiles {","- if ws.f != nil {","- ws.w.Flush()","+ }","+","+ for {","+ select {","+ case <-ctx.Done():","+ drain()","+ return","+ case msg, ok := <-msgCh:","+ if !ok {","+ return"," }","+ processMsg(msg)","+","+ // Drain up to 256 more messages without blocking to batch writes.","+ for range 256 {","+ select {","+ case msg, ok := <-msgCh:","+ if !ok {","+ return","+ }","+ processMsg(msg)","+ case req := <-rotateCh:","+ processRotate(req)","+ default:","+ goto flushed","+ }","+ }","+ flushed:","+ flushAll()","+ case req := <-rotateCh:","+ processRotate(req)"," }","- case req := <-walRotateCh:","- processRotate(req)"," }","- }","- })","+ })","+ }"," }"," "," // RotateWALFiles sends rotation requests for the given host directories"]}],"userModified":false,"replaceAll":false},"sourceToolAssistantUUID":"204ce3a2-a499-4c2d-9ae9-1b3453c4603d","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"28929730-3cd1-4a1c-83da-2d5bd6de5ced","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01BjFwytjUNYNgF69CEZNksH","type":"message","role":"assistant","content":[{"type":"text","text":"Now update `RotateWALFiles` to route to the correct shard:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":3392,"cache_read_input_tokens":49904,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":3392},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zjFbiq9372kdBLYupK","type":"assistant","uuid":"2c03a0ca-ccd9-48af-b4c2-54475392aaf1","timestamp":"2026-03-18T05:30:29.152Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"2c03a0ca-ccd9-48af-b4c2-54475392aaf1","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01BjFwytjUNYNgF69CEZNksH","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01QgzcZpFsV25p6NfcocyaYM","name":"Edit","input":{"replace_all":false,"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","old_string":"// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFiles(hostDirs []string) {\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}","new_string":"// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete. Each request is routed to the\n// shard that owns the host directory.\nfunc RotateWALFiles(hostDirs []string) {\n\tif walShardRotateChs == nil {\n\t\treturn\n\t}\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\t// Extract cluster/node from hostDir to find the right shard.\n\t\t// hostDir = rootDir/cluster/node\n\t\tshard := walShardIndexFromDir(dir)\n\t\twalShardRotateChs[shard] <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// walShardIndexFromDir extracts cluster and node from a host directory path\n// and returns the shard index. The path format is: rootDir/cluster/node\nfunc walShardIndexFromDir(hostDir string) int {\n\t// hostDir = .../cluster/node — extract last two path components\n\tnode := path.Base(hostDir)\n\tcluster := path.Base(path.Dir(hostDir))\n\treturn walShardIndex(cluster, node)\n}"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":3392,"cache_read_input_tokens":49904,"output_tokens":621,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":3392,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zjFbiq9372kdBLYupK","type":"assistant","uuid":"0ce64c54-23cb-44f4-a275-cffc1dd20aee","timestamp":"2026-03-18T05:30:36.445Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"0ce64c54-23cb-44f4-a275-cffc1dd20aee","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Edit","command":"callback"},"parentToolUseID":"toolu_01QgzcZpFsV25p6NfcocyaYM","toolUseID":"toolu_01QgzcZpFsV25p6NfcocyaYM","timestamp":"2026-03-18T05:30:36.466Z","uuid":"c8e4bf99-01ab-4b29-95e0-457ac3479c49","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"0ce64c54-23cb-44f4-a275-cffc1dd20aee","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01QgzcZpFsV25p6NfcocyaYM","type":"tool_result","content":"The file /Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go has been updated successfully."}]},"uuid":"4872a2fa-0de1-40b0-b124-06a9ddc39708","timestamp":"2026-03-18T05:30:36.466Z","toolUseResult":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","oldString":"// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFiles(hostDirs []string) {\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}","newString":"// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete. Each request is routed to the\n// shard that owns the host directory.\nfunc RotateWALFiles(hostDirs []string) {\n\tif walShardRotateChs == nil {\n\t\treturn\n\t}\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\t// Extract cluster/node from hostDir to find the right shard.\n\t\t// hostDir = rootDir/cluster/node\n\t\tshard := walShardIndexFromDir(dir)\n\t\twalShardRotateChs[shard] <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// walShardIndexFromDir extracts cluster and node from a host directory path\n// and returns the shard index. The path format is: rootDir/cluster/node\nfunc walShardIndexFromDir(hostDir string) int {\n\t// hostDir = .../cluster/node — extract last two path components\n\tnode := path.Base(hostDir)\n\tcluster := path.Base(path.Dir(hostDir))\n\treturn walShardIndex(cluster, node)\n}","originalFile":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides walCheckpoint.go: WAL-based checkpoint implementation.\n//\n// This replaces the Avro shadow tree with an append-only Write-Ahead Log (WAL)\n// per host, eliminating the extra memory overhead of the AvroStore and providing\n// truly continuous (per-write) crash safety.\n//\n// # Architecture\n//\n//\tMetric write (DecodeLine)\n//\t │\n//\t ├─► WriteToLevel() → main MemoryStore (unchanged)\n//\t │\n//\t └─► WALMessages channel\n//\t │\n//\t ▼\n//\t WALStaging goroutine\n//\t │\n//\t ▼\n//\t checkpoints/cluster/host/current.wal (append-only, binary)\n//\n//\tPeriodic checkpoint (Checkpointing goroutine):\n//\t 1. Write <timestamp>.bin snapshot (column-oriented, from main tree)\n//\t 2. Signal WALStaging to truncate current.wal per host\n//\n//\tOn restart (FromCheckpoint):\n//\t 1. Load most recent <timestamp>.bin snapshot\n//\t 2. Replay current.wal (overwrite-safe: buffer.write handles duplicate timestamps)\n//\n// # WAL Record Format\n//\n//\t[4B magic 0xCC1DA7A1][4B payload_len][payload][4B CRC32]\n//\n//\tpayload:\n//\t [8B timestamp int64]\n//\t [2B metric_name_len uint16][N metric name bytes]\n//\t [1B selector_count uint8]\n//\t per selector: [1B selector_len uint8][M selector bytes]\n//\t [4B value float32 bits]\n//\n// # Binary Snapshot Format\n//\n//\t[4B magic 0xCC5B0001][8B from int64][8B to int64]\n//\tLevel tree (recursive):\n//\t [4B num_metrics uint32]\n//\t per metric:\n//\t [2B name_len uint16][N name bytes]\n//\t [8B frequency int64][8B start int64]\n//\t [4B num_values uint32][num_values × 4B float32]\n//\t [4B num_children uint32]\n//\t per child: [2B name_len uint16][N name bytes] + Level (recursive)\npackage metricstore\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)\n\n// Magic numbers for binary formats.\nconst (\n\twalFileMagic = uint32(0xCC1DA701) // WAL file header magic\n\twalRecordMagic = uint32(0xCC1DA7A1) // WAL record magic\n\tsnapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic\n)\n\n// walShardChs holds per-shard channels for WAL messages.\n// Initialized by WALStaging; nil when WAL is not active.\nvar walShardChs []chan *WALMessage\n\n// walShardRotateChs holds per-shard channels for WAL rotation requests.\nvar walShardRotateChs []chan walRotateReq\n\n// walNumShards stores the number of shards (set during WALStaging init).\nvar walNumShards int\n\n// WALMessage represents a single metric write to be appended to the WAL.\n// Cluster and Node are NOT stored in the WAL record (inferred from file path).\ntype WALMessage struct {\n\tMetricName string\n\tCluster string\n\tNode string\n\tSelector []string\n\tValue schema.Float\n\tTimestamp int64\n}\n\n// walRotateReq requests WAL file rotation for a specific host directory.\n// The done channel is closed by the WAL goroutine when rotation is complete.\ntype walRotateReq struct {\n\thostDir string\n\tdone chan struct{}\n}\n\n// walFileState holds an open WAL file handle and buffered writer for one host directory.\ntype walFileState struct {\n\tf *os.File\n\tw *bufio.Writer\n}\n\n// walShardIndex computes which shard a message belongs to based on cluster+node.\n// Uses FNV-1a hash for fast, well-distributed mapping.\nfunc walShardIndex(cluster, node string) int {\n\th := fnv.New32a()\n\th.Write([]byte(cluster))\n\th.Write([]byte{0})\n\th.Write([]byte(node))\n\treturn int(h.Sum32()) % walNumShards\n}\n\n// SendWALMessage routes a WAL message to the appropriate shard channel.\n// Returns false if the channel is full (message dropped).\nfunc SendWALMessage(msg *WALMessage) bool {\n\tif walShardChs == nil {\n\t\treturn false\n\t}\n\tshard := walShardIndex(msg.Cluster, msg.Node)\n\tselect {\n\tcase walShardChs[shard] <- msg:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// WALStaging starts N sharded background goroutines that receive WALMessage items\n// and append binary WAL records to per-host current.wal files.\n// Each shard owns a subset of hosts (determined by hash of cluster+node),\n// parallelizing serialization and I/O while keeping per-host writes serial.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\treturn\n\t}\n\n\twalNumShards = max(Keys.NumWorkers, 1)\n\tchBufSize := max(65536/walNumShards, 1024)\n\n\twalShardChs = make([]chan *WALMessage, walNumShards)\n\twalShardRotateChs = make([]chan walRotateReq, walNumShards)\n\n\tfor i := range walNumShards {\n\t\twalShardChs[i] = make(chan *WALMessage, chBufSize)\n\t\twalShardRotateChs[i] = make(chan walRotateReq, 64)\n\t}\n\n\tfor i := range walNumShards {\n\t\tmsgCh := walShardChs[i]\n\t\trotateCh := walShardRotateChs[i]\n\n\t\twg.Go(func() {\n\t\t\thostFiles := make(map[string]*walFileState)\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\tws.f.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\t\tws, ok := hostFiles[hostDir]\n\t\t\t\tif ok {\n\t\t\t\t\treturn ws\n\t\t\t\t}\n\n\t\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t\t// Write file header magic if file is new (empty).\n\t\t\t\tinfo, err := f.Stat()\n\t\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\t\tvar hdr [4]byte\n\t\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\t\tf.Close()\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tws = &walFileState{f: f, w: w}\n\t\t\t\thostFiles[hostDir] = ws\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\t\tif ws == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := writeWALRecordDirect(ws.w, msg); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprocessRotate := func(req walRotateReq) {\n\t\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\t\tif ok && ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t\t}\n\t\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t\t}\n\t\t\t\tclose(req.done)\n\t\t\t}\n\n\t\t\tflushAll := func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdrain := func() {\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tflushAll()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tdrain()\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\t\tfor range 256 {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tflushed:\n\t\t\t\t\tflushAll()\n\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFiles(hostDirs []string) {\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\twalRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFilesAfterShutdown(hostDirs []string) {\n\tfor _, dir := range hostDirs {\n\t\twalPath := path.Join(dir, \"current.wal\")\n\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t}\n\t}\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {\n\tsize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tsize += 1 + len(s)\n\t}\n\n\tbuf := make([]byte, 0, size)\n\n\t// Timestamp (8 bytes, little-endian int64)\n\tvar ts [8]byte\n\tbinary.LittleEndian.PutUint64(ts[:], uint64(msg.Timestamp))\n\tbuf = append(buf, ts[:]...)\n\n\t// Metric name (2-byte length prefix + bytes)\n\tvar mLen [2]byte\n\tbinary.LittleEndian.PutUint16(mLen[:], uint16(len(msg.MetricName)))\n\tbuf = append(buf, mLen[:]...)\n\tbuf = append(buf, msg.MetricName...)\n\n\t// Selector count (1 byte)\n\tbuf = append(buf, byte(len(msg.Selector)))\n\n\t// Selectors (1-byte length prefix + bytes each)\n\tfor _, sel := range msg.Selector {\n\t\tbuf = append(buf, byte(len(sel)))\n\t\tbuf = append(buf, sel...)\n\t}\n\n\t// Value (4 bytes, float32 bit representation)\n\tvar val [4]byte\n\tbinary.LittleEndian.PutUint32(val[:], math.Float32bits(float32(msg.Value)))\n\tbuf = append(buf, val[:]...)\n\n\treturn buf\n}\n\n// writeWALRecord appends a binary WAL record to the writer.\n// Format: [4B magic][4B payload_len][payload][4B CRC32]\nfunc writeWALRecord(w io.Writer, msg *WALMessage) error {\n\tpayload := buildWALPayload(msg)\n\tcrc := crc32.ChecksumIEEE(payload)\n\n\trecord := make([]byte, 0, 4+4+len(payload)+4)\n\n\tvar magic [4]byte\n\tbinary.LittleEndian.PutUint32(magic[:], walRecordMagic)\n\trecord = append(record, magic[:]...)\n\n\tvar pLen [4]byte\n\tbinary.LittleEndian.PutUint32(pLen[:], uint32(len(payload)))\n\trecord = append(record, pLen[:]...)\n\n\trecord = append(record, payload...)\n\n\tvar crcBytes [4]byte\n\tbinary.LittleEndian.PutUint32(crcBytes[:], crc)\n\trecord = append(record, crcBytes[:]...)\n\n\t_, err := w.Write(record)\n\treturn err\n}\n\n// readWALRecord reads one WAL record from the reader.\n// Returns (nil, nil) on clean EOF. Returns error on data corruption.\n// A CRC mismatch indicates a truncated trailing record (expected on crash).\nfunc readWALRecord(r io.Reader) (*WALMessage, error) {\n\tvar magic uint32\n\tif err := binary.Read(r, binary.LittleEndian, &magic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil, nil // Clean EOF\n\t\t}\n\t\treturn nil, fmt.Errorf(\"read record magic: %w\", err)\n\t}\n\n\tif magic != walRecordMagic {\n\t\treturn nil, fmt.Errorf(\"invalid record magic 0x%08X (expected 0x%08X)\", magic, walRecordMagic)\n\t}\n\n\tvar payloadLen uint32\n\tif err := binary.Read(r, binary.LittleEndian, &payloadLen); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload length: %w\", err)\n\t}\n\n\tif payloadLen > 1<<20 { // 1 MB sanity limit\n\t\treturn nil, fmt.Errorf(\"record payload too large: %d bytes\", payloadLen)\n\t}\n\n\tpayload := make([]byte, payloadLen)\n\tif _, err := io.ReadFull(r, payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload: %w\", err)\n\t}\n\n\tvar storedCRC uint32\n\tif err := binary.Read(r, binary.LittleEndian, &storedCRC); err != nil {\n\t\treturn nil, fmt.Errorf(\"read CRC: %w\", err)\n\t}\n\n\tif crc32.ChecksumIEEE(payload) != storedCRC {\n\t\treturn nil, fmt.Errorf(\"CRC mismatch (truncated write or corruption)\")\n\t}\n\n\treturn parseWALPayload(payload)\n}\n\n// parseWALPayload decodes a binary payload into a WALMessage.\nfunc parseWALPayload(payload []byte) (*WALMessage, error) {\n\tif len(payload) < 8+2+1+4 {\n\t\treturn nil, fmt.Errorf(\"payload too short: %d bytes\", len(payload))\n\t}\n\n\toffset := 0\n\n\t// Timestamp (8 bytes)\n\tts := int64(binary.LittleEndian.Uint64(payload[offset : offset+8]))\n\toffset += 8\n\n\t// Metric name (2-byte length + bytes)\n\tif offset+2 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name length overflows payload\")\n\t}\n\tmLen := int(binary.LittleEndian.Uint16(payload[offset : offset+2]))\n\toffset += 2\n\n\tif offset+mLen > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name overflows payload\")\n\t}\n\tmetricName := string(payload[offset : offset+mLen])\n\toffset += mLen\n\n\t// Selector count (1 byte)\n\tif offset >= len(payload) {\n\t\treturn nil, fmt.Errorf(\"selector count overflows payload\")\n\t}\n\tselCount := int(payload[offset])\n\toffset++\n\n\tselectors := make([]string, selCount)\n\tfor i := range selCount {\n\t\tif offset >= len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] length overflows payload\", i)\n\t\t}\n\t\tsLen := int(payload[offset])\n\t\toffset++\n\n\t\tif offset+sLen > len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] data overflows payload\", i)\n\t\t}\n\t\tselectors[i] = string(payload[offset : offset+sLen])\n\t\toffset += sLen\n\t}\n\n\t// Value (4 bytes, float32 bits)\n\tif offset+4 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"value overflows payload\")\n\t}\n\tbits := binary.LittleEndian.Uint32(payload[offset : offset+4])\n\tvalue := schema.Float(math.Float32frombits(bits))\n\n\treturn &WALMessage{\n\t\tMetricName: metricName,\n\t\tTimestamp: ts,\n\t\tSelector: selectors,\n\t\tValue: value,\n\t}, nil\n}\n\n// loadWALFile reads a WAL file and replays all valid records into the Level tree.\n// l is the host-level node. Corrupt or partial trailing records are silently skipped\n// (expected on crash). Records older than 'from' are skipped.\nfunc (l *Level) loadWALFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\t// Verify file header magic.\n\tvar fileMagic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &fileMagic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil // Empty file, no data\n\t\t}\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: read file header: %w\", err)\n\t}\n\n\tif fileMagic != walFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: invalid file magic 0x%08X (expected 0x%08X)\", fileMagic, walFileMagic)\n\t}\n\n\t// Cache level lookups to avoid repeated tree traversal.\n\tlvlCache := make(map[string]*Level)\n\n\tfor {\n\t\tmsg, err := readWALRecord(br)\n\t\tif err != nil {\n\t\t\t// Truncated trailing record is expected after a crash; stop replaying.\n\t\t\tcclog.Debugf(\"[METRICSTORE]> WAL: stopping replay at corrupted/partial record: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tif msg == nil {\n\t\t\tbreak // Clean EOF\n\t\t}\n\n\t\tif msg.Timestamp < from {\n\t\t\tcontinue // Older than retention window\n\t\t}\n\n\t\tminfo, ok := m.Metrics[msg.MetricName]\n\t\tif !ok {\n\t\t\tcontinue // Unknown metric (config may have changed)\n\t\t}\n\n\t\t// Cache key is the null-separated selector path.\n\t\tcacheKey := joinSelector(msg.Selector)\n\t\tlvl, ok := lvlCache[cacheKey]\n\t\tif !ok {\n\t\t\tlvl = l.findLevelOrCreate(msg.Selector, len(m.Metrics))\n\t\t\tlvlCache[cacheKey] = lvl\n\t\t}\n\n\t\t// Write directly to the buffer, same as WriteToLevel but without the\n\t\t// global level lookup (we already have the right level).\n\t\tlvl.lock.Lock()\n\t\tb := lvl.metrics[minfo.offset]\n\t\tif b == nil {\n\t\t\tb = newBuffer(msg.Timestamp, minfo.Frequency)\n\t\t\tlvl.metrics[minfo.offset] = b\n\t\t}\n\t\tnb, writeErr := b.write(msg.Timestamp, msg.Value)\n\t\tif writeErr == nil && b != nb {\n\t\t\tlvl.metrics[minfo.offset] = nb\n\t\t}\n\t\t// Ignore write errors for timestamps before buffer start (can happen when\n\t\t// replaying WAL entries that predate a loaded snapshot's start time).\n\t\tlvl.lock.Unlock()\n\t}\n\n\treturn nil\n}\n\n// joinSelector builds a cache key from a selector slice using null bytes as separators.\nfunc joinSelector(sel []string) string {\n\tif len(sel) == 0 {\n\t\treturn \"\"\n\t}\n\tvar result strings.Builder\n\tresult.WriteString(sel[0])\n\tfor i := 1; i < len(sel); i++ {\n\t\tresult.WriteString(\"\\x00\" + sel[i])\n\t}\n\treturn result.String()\n}\n\n// ToCheckpointWAL writes binary snapshot files for all hosts in parallel.\n// Returns the number of files written, the list of host directories that were\n// successfully checkpointed (for WAL rotation), and any errors.\nfunc (m *MemoryStore) ToCheckpointWAL(dir string, from, to int64) (int, []string, error) {\n\t// Collect all cluster/host pairs.\n\tm.root.lock.RLock()\n\ttotalHosts := 0\n\tfor _, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\ttotalHosts += len(l1.children)\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\tlevels := make([]*Level, 0, totalHosts)\n\tselectors := make([][]string, 0, totalHosts)\n\n\tm.root.lock.RLock()\n\tfor sel1, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\tfor sel2, l2 := range l1.children {\n\t\t\tlevels = append(levels, l2)\n\t\t\tselectors = append(selectors, []string{sel1, sel2})\n\t\t}\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\ttype workItem struct {\n\t\tlevel *Level\n\t\thostDir string\n\t\tselector []string\n\t}\n\n\tn, errs := int32(0), int32(0)\n\tvar successDirs []string\n\tvar successMu sync.Mutex\n\n\tvar wg sync.WaitGroup\n\twg.Add(Keys.NumWorkers)\n\twork := make(chan workItem, Keys.NumWorkers*2)\n\n\tfor range Keys.NumWorkers {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor wi := range work {\n\t\t\t\terr := wi.level.toCheckpointBinary(wi.hostDir, from, to, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == ErrNoNewArchiveData {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> binary checkpoint error for %s: %v\", wi.hostDir, err)\n\t\t\t\t\tatomic.AddInt32(&errs, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.AddInt32(&n, 1)\n\t\t\t\t\tsuccessMu.Lock()\n\t\t\t\t\tsuccessDirs = append(successDirs, wi.hostDir)\n\t\t\t\t\tsuccessMu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor i := range levels {\n\t\thostDir := path.Join(dir, path.Join(selectors[i]...))\n\t\twork <- workItem{\n\t\t\tlevel: levels[i],\n\t\t\thostDir: hostDir,\n\t\t\tselector: selectors[i],\n\t\t}\n\t}\n\tclose(work)\n\twg.Wait()\n\n\tif errs > 0 {\n\t\treturn int(n), successDirs, fmt.Errorf(\"[METRICSTORE]> %d errors during binary checkpoint (%d successes)\", errs, n)\n\t}\n\treturn int(n), successDirs, nil\n}\n\n// toCheckpointBinary writes a binary snapshot file for a single host-level node.\n// Uses atomic rename (write to .tmp then rename) to avoid partial reads on crash.\nfunc (l *Level) toCheckpointBinary(dir string, from, to int64, m *MemoryStore) error {\n\tcf, err := l.toCheckpointFile(from, to, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cf == nil {\n\t\treturn ErrNoNewArchiveData\n\t}\n\n\tif err := os.MkdirAll(dir, CheckpointDirPerms); err != nil {\n\t\treturn fmt.Errorf(\"mkdir %s: %w\", dir, err)\n\t}\n\n\t// Write to a temp file first, then rename (atomic on POSIX).\n\ttmpPath := path.Join(dir, fmt.Sprintf(\"%d.bin.tmp\", from))\n\tfinalPath := path.Join(dir, fmt.Sprintf(\"%d.bin\", from))\n\n\tf, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, CheckpointFilePerms)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open binary snapshot %s: %w\", tmpPath, err)\n\t}\n\n\tbw := bufio.NewWriter(f)\n\tif err := writeBinarySnapshotFile(bw, cf); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn fmt.Errorf(\"write binary snapshot: %w\", err)\n\t}\n\tif err := bw.Flush(); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn err\n\t}\n\tf.Close()\n\n\treturn os.Rename(tmpPath, finalPath)\n}\n\n// writeBinarySnapshotFile writes the binary snapshot file header and level tree.\nfunc writeBinarySnapshotFile(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, snapFileMagic); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.From); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.To); err != nil {\n\t\treturn err\n\t}\n\treturn writeBinaryLevel(w, cf)\n}\n\n// writeBinaryLevel recursively writes a CheckpointFile level in binary format.\nfunc writeBinaryLevel(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Metrics))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, metric := range cf.Metrics {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Frequency); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Start); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, uint32(len(metric.Data))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, v := range metric.Data {\n\t\t\tif err := binary.Write(w, binary.LittleEndian, math.Float32bits(float32(v))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Children))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, child := range cf.Children {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writeBinaryLevel(w, child); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// writeString16 writes a 2-byte length-prefixed string to w.\nfunc writeString16(w io.Writer, s string) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint16(len(s))); err != nil {\n\t\treturn err\n\t}\n\t_, err := io.WriteString(w, s)\n\treturn err\n}\n\n// loadBinaryFile reads a binary snapshot file and loads data into the Level tree.\n// The retention check (from) is applied to the file's 'to' timestamp.\nfunc (l *Level) loadBinaryFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\tvar magic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &magic); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read magic: %w\", err)\n\t}\n\tif magic != snapFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: invalid magic 0x%08X (expected 0x%08X)\", magic, snapFileMagic)\n\t}\n\n\tvar fileFrom, fileTo int64\n\tif err := binary.Read(br, binary.LittleEndian, &fileFrom); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read from: %w\", err)\n\t}\n\tif err := binary.Read(br, binary.LittleEndian, &fileTo); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read to: %w\", err)\n\t}\n\n\tif fileTo != 0 && fileTo < from {\n\t\treturn nil // File is older than retention window, skip it\n\t}\n\n\tcf, err := readBinaryLevel(br)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read level tree: %w\", err)\n\t}\n\tcf.From = fileFrom\n\tcf.To = fileTo\n\n\treturn l.loadFile(cf, m)\n}\n\n// readBinaryLevel recursively reads a level from the binary snapshot format.\nfunc readBinaryLevel(r io.Reader) (*CheckpointFile, error) {\n\tcf := &CheckpointFile{\n\t\tMetrics: make(map[string]*CheckpointMetrics),\n\t\tChildren: make(map[string]*CheckpointFile),\n\t}\n\n\tvar numMetrics uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numMetrics); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_metrics: %w\", err)\n\t}\n\n\tfor range numMetrics {\n\t\tname, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read metric name: %w\", err)\n\t\t}\n\n\t\tvar freq, start int64\n\t\tif err := binary.Read(r, binary.LittleEndian, &freq); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read frequency for %s: %w\", name, err)\n\t\t}\n\t\tif err := binary.Read(r, binary.LittleEndian, &start); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read start for %s: %w\", name, err)\n\t\t}\n\n\t\tvar numValues uint32\n\t\tif err := binary.Read(r, binary.LittleEndian, &numValues); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read num_values for %s: %w\", name, err)\n\t\t}\n\n\t\tdata := make([]schema.Float, numValues)\n\t\tfor i := range numValues {\n\t\t\tvar bits uint32\n\t\t\tif err := binary.Read(r, binary.LittleEndian, &bits); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"read value[%d] for %s: %w\", i, name, err)\n\t\t\t}\n\t\t\tdata[i] = schema.Float(math.Float32frombits(bits))\n\t\t}\n\n\t\tcf.Metrics[name] = &CheckpointMetrics{\n\t\t\tFrequency: freq,\n\t\t\tStart: start,\n\t\t\tData: data,\n\t\t}\n\t}\n\n\tvar numChildren uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numChildren); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_children: %w\", err)\n\t}\n\n\tfor range numChildren {\n\t\tchildName, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child name: %w\", err)\n\t\t}\n\n\t\tchild, err := readBinaryLevel(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child %s: %w\", childName, err)\n\t\t}\n\t\tcf.Children[childName] = child\n\t}\n\n\treturn cf, nil\n}\n\n// readString16 reads a 2-byte length-prefixed string from r.\nfunc readString16(r io.Reader) (string, error) {\n\tvar sLen uint16\n\tif err := binary.Read(r, binary.LittleEndian, &sLen); err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, sLen)\n\tif _, err := io.ReadFull(r, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n","structuredPatch":[{"oldStart":299,"oldLines":18,"newStart":299,"newLines":34,"lines":[" }"," "," // RotateWALFiles sends rotation requests for the given host directories","-// and blocks until all rotations complete.","+// and blocks until all rotations complete. Each request is routed to the","+// shard that owns the host directory."," func RotateWALFiles(hostDirs []string) {","+ if walShardRotateChs == nil {","+ return","+ }"," dones := make([]chan struct{}, len(hostDirs))"," for i, dir := range hostDirs {"," dones[i] = make(chan struct{})","- walRotateCh <- walRotateReq{hostDir: dir, done: dones[i]}","+ // Extract cluster/node from hostDir to find the right shard.","+ // hostDir = rootDir/cluster/node","+ shard := walShardIndexFromDir(dir)","+ walShardRotateChs[shard] <- walRotateReq{hostDir: dir, done: dones[i]}"," }"," for _, done := range dones {"," <-done"," }"," }"," ","+// walShardIndexFromDir extracts cluster and node from a host directory path","+// and returns the shard index. The path format is: rootDir/cluster/node","+func walShardIndexFromDir(hostDir string) int {","+ // hostDir = .../cluster/node — extract last two path components","+ node := path.Base(hostDir)","+ cluster := path.Base(path.Dir(hostDir))","+ return walShardIndex(cluster, node)","+}","+"," // RotateWALFiles sends rotation requests for the given host directories"," // and blocks until all rotations complete."," func RotateWALFilesAfterShutdown(hostDirs []string) {"]}],"userModified":false,"replaceAll":false},"sourceToolAssistantUUID":"0ce64c54-23cb-44f4-a275-cffc1dd20aee","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"4872a2fa-0de1-40b0-b124-06a9ddc39708","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01KiUxaJ4RLLRmWSo6k4cSVL","type":"message","role":"assistant","content":[{"type":"text","text":"Now add the `writeWALRecordDirect` function that encodes directly into the `bufio.Writer` without allocations:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":770,"cache_read_input_tokens":53296,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":770},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zjyhXsvzM9MocBYdfX","type":"assistant","uuid":"a01954d9-d677-4779-88be-7d5b2d80e7ec","timestamp":"2026-03-18T05:30:38.850Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"a01954d9-d677-4779-88be-7d5b2d80e7ec","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01KiUxaJ4RLLRmWSo6k4cSVL","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01MK7wWVzyNRujJqPZ4AdhUm","name":"Edit","input":{"replace_all":false,"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","old_string":"// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {","new_string":"// writeWALRecordDirect encodes a WAL record directly into the bufio.Writer,\n// avoiding heap allocations by using a stack-allocated scratch buffer for\n// the fixed-size header/trailer and computing CRC inline.\nfunc writeWALRecordDirect(w *bufio.Writer, msg *WALMessage) error {\n\t// Compute payload size.\n\tpayloadSize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tpayloadSize += 1 + len(s)\n\t}\n\n\t// Write magic + payload length (8 bytes header).\n\tvar hdr [8]byte\n\tbinary.LittleEndian.PutUint32(hdr[0:4], walRecordMagic)\n\tbinary.LittleEndian.PutUint32(hdr[4:8], uint32(payloadSize))\n\tif _, err := w.Write(hdr[:]); err != nil {\n\t\treturn err\n\t}\n\n\t// We need to compute CRC over the payload as we write it.\n\tcrc := crc32.NewIEEE()\n\n\t// Timestamp (8 bytes).\n\tvar scratch [8]byte\n\tbinary.LittleEndian.PutUint64(scratch[:8], uint64(msg.Timestamp))\n\tcrc.Write(scratch[:8])\n\tif _, err := w.Write(scratch[:8]); err != nil {\n\t\treturn err\n\t}\n\n\t// Metric name length (2 bytes) + metric name.\n\tbinary.LittleEndian.PutUint16(scratch[:2], uint16(len(msg.MetricName)))\n\tcrc.Write(scratch[:2])\n\tif _, err := w.Write(scratch[:2]); err != nil {\n\t\treturn err\n\t}\n\tnameBytes := []byte(msg.MetricName)\n\tcrc.Write(nameBytes)\n\tif _, err := w.Write(nameBytes); err != nil {\n\t\treturn err\n\t}\n\n\t// Selector count (1 byte).\n\tscratch[0] = byte(len(msg.Selector))\n\tcrc.Write(scratch[:1])\n\tif _, err := w.Write(scratch[:1]); err != nil {\n\t\treturn err\n\t}\n\n\t// Selectors (1-byte length + bytes each).\n\tfor _, sel := range msg.Selector {\n\t\tscratch[0] = byte(len(sel))\n\t\tcrc.Write(scratch[:1])\n\t\tif _, err := w.Write(scratch[:1]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tselBytes := []byte(sel)\n\t\tcrc.Write(selBytes)\n\t\tif _, err := w.Write(selBytes); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Value (4 bytes, float32 bits).\n\tbinary.LittleEndian.PutUint32(scratch[:4], math.Float32bits(float32(msg.Value)))\n\tcrc.Write(scratch[:4])\n\tif _, err := w.Write(scratch[:4]); err != nil {\n\t\treturn err\n\t}\n\n\t// CRC32 (4 bytes).\n\tbinary.LittleEndian.PutUint32(scratch[:4], crc.Sum32())\n\t_, err := w.Write(scratch[:4])\n\treturn err\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":770,"cache_read_input_tokens":53296,"output_tokens":1086,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":770,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zjyhXsvzM9MocBYdfX","type":"assistant","uuid":"3829bf65-3ef2-4147-997a-93067d16f856","timestamp":"2026-03-18T05:30:50.704Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"3829bf65-3ef2-4147-997a-93067d16f856","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Edit","command":"callback"},"parentToolUseID":"toolu_01MK7wWVzyNRujJqPZ4AdhUm","toolUseID":"toolu_01MK7wWVzyNRujJqPZ4AdhUm","timestamp":"2026-03-18T05:30:50.739Z","uuid":"95cf14ba-74c6-4b48-b1b7-a6ac77bb54fd","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"3829bf65-3ef2-4147-997a-93067d16f856","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01MK7wWVzyNRujJqPZ4AdhUm","type":"tool_result","content":"The file /Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go has been updated successfully."}]},"uuid":"f516e388-967e-426b-8ce5-d27bb7de30f8","timestamp":"2026-03-18T05:30:50.739Z","toolUseResult":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/walCheckpoint.go","oldString":"// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {","newString":"// writeWALRecordDirect encodes a WAL record directly into the bufio.Writer,\n// avoiding heap allocations by using a stack-allocated scratch buffer for\n// the fixed-size header/trailer and computing CRC inline.\nfunc writeWALRecordDirect(w *bufio.Writer, msg *WALMessage) error {\n\t// Compute payload size.\n\tpayloadSize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tpayloadSize += 1 + len(s)\n\t}\n\n\t// Write magic + payload length (8 bytes header).\n\tvar hdr [8]byte\n\tbinary.LittleEndian.PutUint32(hdr[0:4], walRecordMagic)\n\tbinary.LittleEndian.PutUint32(hdr[4:8], uint32(payloadSize))\n\tif _, err := w.Write(hdr[:]); err != nil {\n\t\treturn err\n\t}\n\n\t// We need to compute CRC over the payload as we write it.\n\tcrc := crc32.NewIEEE()\n\n\t// Timestamp (8 bytes).\n\tvar scratch [8]byte\n\tbinary.LittleEndian.PutUint64(scratch[:8], uint64(msg.Timestamp))\n\tcrc.Write(scratch[:8])\n\tif _, err := w.Write(scratch[:8]); err != nil {\n\t\treturn err\n\t}\n\n\t// Metric name length (2 bytes) + metric name.\n\tbinary.LittleEndian.PutUint16(scratch[:2], uint16(len(msg.MetricName)))\n\tcrc.Write(scratch[:2])\n\tif _, err := w.Write(scratch[:2]); err != nil {\n\t\treturn err\n\t}\n\tnameBytes := []byte(msg.MetricName)\n\tcrc.Write(nameBytes)\n\tif _, err := w.Write(nameBytes); err != nil {\n\t\treturn err\n\t}\n\n\t// Selector count (1 byte).\n\tscratch[0] = byte(len(msg.Selector))\n\tcrc.Write(scratch[:1])\n\tif _, err := w.Write(scratch[:1]); err != nil {\n\t\treturn err\n\t}\n\n\t// Selectors (1-byte length + bytes each).\n\tfor _, sel := range msg.Selector {\n\t\tscratch[0] = byte(len(sel))\n\t\tcrc.Write(scratch[:1])\n\t\tif _, err := w.Write(scratch[:1]); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tselBytes := []byte(sel)\n\t\tcrc.Write(selBytes)\n\t\tif _, err := w.Write(selBytes); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Value (4 bytes, float32 bits).\n\tbinary.LittleEndian.PutUint32(scratch[:4], math.Float32bits(float32(msg.Value)))\n\tcrc.Write(scratch[:4])\n\tif _, err := w.Write(scratch[:4]); err != nil {\n\t\treturn err\n\t}\n\n\t// CRC32 (4 bytes).\n\tbinary.LittleEndian.PutUint32(scratch[:4], crc.Sum32())\n\t_, err := w.Write(scratch[:4])\n\treturn err\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {","originalFile":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides walCheckpoint.go: WAL-based checkpoint implementation.\n//\n// This replaces the Avro shadow tree with an append-only Write-Ahead Log (WAL)\n// per host, eliminating the extra memory overhead of the AvroStore and providing\n// truly continuous (per-write) crash safety.\n//\n// # Architecture\n//\n//\tMetric write (DecodeLine)\n//\t │\n//\t ├─► WriteToLevel() → main MemoryStore (unchanged)\n//\t │\n//\t └─► WALMessages channel\n//\t │\n//\t ▼\n//\t WALStaging goroutine\n//\t │\n//\t ▼\n//\t checkpoints/cluster/host/current.wal (append-only, binary)\n//\n//\tPeriodic checkpoint (Checkpointing goroutine):\n//\t 1. Write <timestamp>.bin snapshot (column-oriented, from main tree)\n//\t 2. Signal WALStaging to truncate current.wal per host\n//\n//\tOn restart (FromCheckpoint):\n//\t 1. Load most recent <timestamp>.bin snapshot\n//\t 2. Replay current.wal (overwrite-safe: buffer.write handles duplicate timestamps)\n//\n// # WAL Record Format\n//\n//\t[4B magic 0xCC1DA7A1][4B payload_len][payload][4B CRC32]\n//\n//\tpayload:\n//\t [8B timestamp int64]\n//\t [2B metric_name_len uint16][N metric name bytes]\n//\t [1B selector_count uint8]\n//\t per selector: [1B selector_len uint8][M selector bytes]\n//\t [4B value float32 bits]\n//\n// # Binary Snapshot Format\n//\n//\t[4B magic 0xCC5B0001][8B from int64][8B to int64]\n//\tLevel tree (recursive):\n//\t [4B num_metrics uint32]\n//\t per metric:\n//\t [2B name_len uint16][N name bytes]\n//\t [8B frequency int64][8B start int64]\n//\t [4B num_values uint32][num_values × 4B float32]\n//\t [4B num_children uint32]\n//\t per child: [2B name_len uint16][N name bytes] + Level (recursive)\npackage metricstore\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"hash/fnv\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n)\n\n// Magic numbers for binary formats.\nconst (\n\twalFileMagic = uint32(0xCC1DA701) // WAL file header magic\n\twalRecordMagic = uint32(0xCC1DA7A1) // WAL record magic\n\tsnapFileMagic = uint32(0xCC5B0001) // Binary snapshot magic\n)\n\n// walShardChs holds per-shard channels for WAL messages.\n// Initialized by WALStaging; nil when WAL is not active.\nvar walShardChs []chan *WALMessage\n\n// walShardRotateChs holds per-shard channels for WAL rotation requests.\nvar walShardRotateChs []chan walRotateReq\n\n// walNumShards stores the number of shards (set during WALStaging init).\nvar walNumShards int\n\n// WALMessage represents a single metric write to be appended to the WAL.\n// Cluster and Node are NOT stored in the WAL record (inferred from file path).\ntype WALMessage struct {\n\tMetricName string\n\tCluster string\n\tNode string\n\tSelector []string\n\tValue schema.Float\n\tTimestamp int64\n}\n\n// walRotateReq requests WAL file rotation for a specific host directory.\n// The done channel is closed by the WAL goroutine when rotation is complete.\ntype walRotateReq struct {\n\thostDir string\n\tdone chan struct{}\n}\n\n// walFileState holds an open WAL file handle and buffered writer for one host directory.\ntype walFileState struct {\n\tf *os.File\n\tw *bufio.Writer\n}\n\n// walShardIndex computes which shard a message belongs to based on cluster+node.\n// Uses FNV-1a hash for fast, well-distributed mapping.\nfunc walShardIndex(cluster, node string) int {\n\th := fnv.New32a()\n\th.Write([]byte(cluster))\n\th.Write([]byte{0})\n\th.Write([]byte(node))\n\treturn int(h.Sum32()) % walNumShards\n}\n\n// SendWALMessage routes a WAL message to the appropriate shard channel.\n// Returns false if the channel is full (message dropped).\nfunc SendWALMessage(msg *WALMessage) bool {\n\tif walShardChs == nil {\n\t\treturn false\n\t}\n\tshard := walShardIndex(msg.Cluster, msg.Node)\n\tselect {\n\tcase walShardChs[shard] <- msg:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n// WALStaging starts N sharded background goroutines that receive WALMessage items\n// and append binary WAL records to per-host current.wal files.\n// Each shard owns a subset of hosts (determined by hash of cluster+node),\n// parallelizing serialization and I/O while keeping per-host writes serial.\nfunc WALStaging(wg *sync.WaitGroup, ctx context.Context) {\n\tif Keys.Checkpoints.FileFormat == \"json\" {\n\t\treturn\n\t}\n\n\twalNumShards = max(Keys.NumWorkers, 1)\n\tchBufSize := max(65536/walNumShards, 1024)\n\n\twalShardChs = make([]chan *WALMessage, walNumShards)\n\twalShardRotateChs = make([]chan walRotateReq, walNumShards)\n\n\tfor i := range walNumShards {\n\t\twalShardChs[i] = make(chan *WALMessage, chBufSize)\n\t\twalShardRotateChs[i] = make(chan walRotateReq, 64)\n\t}\n\n\tfor i := range walNumShards {\n\t\tmsgCh := walShardChs[i]\n\t\trotateCh := walShardRotateChs[i]\n\n\t\twg.Go(func() {\n\t\t\thostFiles := make(map[string]*walFileState)\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t\tws.f.Close()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tgetOrOpenWAL := func(hostDir string) *walFileState {\n\t\t\t\tws, ok := hostFiles[hostDir]\n\t\t\t\tif ok {\n\t\t\t\t\treturn ws\n\t\t\t\t}\n\n\t\t\t\tif err := os.MkdirAll(hostDir, CheckpointDirPerms); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: mkdir %s: %v\", hostDir, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\twalPath := path.Join(hostDir, \"current.wal\")\n\t\t\t\tf, err := os.OpenFile(walPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, CheckpointFilePerms)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: open %s: %v\", walPath, err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tw := bufio.NewWriter(f)\n\n\t\t\t\t// Write file header magic if file is new (empty).\n\t\t\t\tinfo, err := f.Stat()\n\t\t\t\tif err == nil && info.Size() == 0 {\n\t\t\t\t\tvar hdr [4]byte\n\t\t\t\t\tbinary.LittleEndian.PutUint32(hdr[:], walFileMagic)\n\t\t\t\t\tif _, err := w.Write(hdr[:]); err != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write header %s: %v\", walPath, err)\n\t\t\t\t\t\tf.Close()\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tws = &walFileState{f: f, w: w}\n\t\t\t\thostFiles[hostDir] = ws\n\t\t\t\treturn ws\n\t\t\t}\n\n\t\t\tprocessMsg := func(msg *WALMessage) {\n\t\t\t\thostDir := path.Join(Keys.Checkpoints.RootDir, msg.Cluster, msg.Node)\n\t\t\t\tws := getOrOpenWAL(hostDir)\n\t\t\t\tif ws == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := writeWALRecordDirect(ws.w, msg); err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: write record: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tprocessRotate := func(req walRotateReq) {\n\t\t\t\tws, ok := hostFiles[req.hostDir]\n\t\t\t\tif ok && ws.f != nil {\n\t\t\t\t\tws.w.Flush()\n\t\t\t\t\tws.f.Close()\n\t\t\t\t\twalPath := path.Join(req.hostDir, \"current.wal\")\n\t\t\t\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t\t\t\t}\n\t\t\t\t\tdelete(hostFiles, req.hostDir)\n\t\t\t\t}\n\t\t\t\tclose(req.done)\n\t\t\t}\n\n\t\t\tflushAll := func() {\n\t\t\t\tfor _, ws := range hostFiles {\n\t\t\t\t\tif ws.f != nil {\n\t\t\t\t\t\tws.w.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdrain := func() {\n\t\t\t\tfor {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tflushAll()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tdrain()\n\t\t\t\t\treturn\n\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tprocessMsg(msg)\n\n\t\t\t\t\t// Drain up to 256 more messages without blocking to batch writes.\n\t\t\t\t\tfor range 256 {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase msg, ok := <-msgCh:\n\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tprocessMsg(msg)\n\t\t\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\t\t\tprocessRotate(req)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tgoto flushed\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tflushed:\n\t\t\t\t\tflushAll()\n\t\t\t\tcase req := <-rotateCh:\n\t\t\t\t\tprocessRotate(req)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete. Each request is routed to the\n// shard that owns the host directory.\nfunc RotateWALFiles(hostDirs []string) {\n\tif walShardRotateChs == nil {\n\t\treturn\n\t}\n\tdones := make([]chan struct{}, len(hostDirs))\n\tfor i, dir := range hostDirs {\n\t\tdones[i] = make(chan struct{})\n\t\t// Extract cluster/node from hostDir to find the right shard.\n\t\t// hostDir = rootDir/cluster/node\n\t\tshard := walShardIndexFromDir(dir)\n\t\twalShardRotateChs[shard] <- walRotateReq{hostDir: dir, done: dones[i]}\n\t}\n\tfor _, done := range dones {\n\t\t<-done\n\t}\n}\n\n// walShardIndexFromDir extracts cluster and node from a host directory path\n// and returns the shard index. The path format is: rootDir/cluster/node\nfunc walShardIndexFromDir(hostDir string) int {\n\t// hostDir = .../cluster/node — extract last two path components\n\tnode := path.Base(hostDir)\n\tcluster := path.Base(path.Dir(hostDir))\n\treturn walShardIndex(cluster, node)\n}\n\n// RotateWALFiles sends rotation requests for the given host directories\n// and blocks until all rotations complete.\nfunc RotateWALFilesAfterShutdown(hostDirs []string) {\n\tfor _, dir := range hostDirs {\n\t\twalPath := path.Join(dir, \"current.wal\")\n\t\tif err := os.Remove(walPath); err != nil && !os.IsNotExist(err) {\n\t\t\tcclog.Errorf(\"[METRICSTORE]> WAL: remove %s: %v\", walPath, err)\n\t\t}\n\t}\n}\n\n// buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC).\nfunc buildWALPayload(msg *WALMessage) []byte {\n\tsize := 8 + 2 + len(msg.MetricName) + 1 + 4\n\tfor _, s := range msg.Selector {\n\t\tsize += 1 + len(s)\n\t}\n\n\tbuf := make([]byte, 0, size)\n\n\t// Timestamp (8 bytes, little-endian int64)\n\tvar ts [8]byte\n\tbinary.LittleEndian.PutUint64(ts[:], uint64(msg.Timestamp))\n\tbuf = append(buf, ts[:]...)\n\n\t// Metric name (2-byte length prefix + bytes)\n\tvar mLen [2]byte\n\tbinary.LittleEndian.PutUint16(mLen[:], uint16(len(msg.MetricName)))\n\tbuf = append(buf, mLen[:]...)\n\tbuf = append(buf, msg.MetricName...)\n\n\t// Selector count (1 byte)\n\tbuf = append(buf, byte(len(msg.Selector)))\n\n\t// Selectors (1-byte length prefix + bytes each)\n\tfor _, sel := range msg.Selector {\n\t\tbuf = append(buf, byte(len(sel)))\n\t\tbuf = append(buf, sel...)\n\t}\n\n\t// Value (4 bytes, float32 bit representation)\n\tvar val [4]byte\n\tbinary.LittleEndian.PutUint32(val[:], math.Float32bits(float32(msg.Value)))\n\tbuf = append(buf, val[:]...)\n\n\treturn buf\n}\n\n// writeWALRecord appends a binary WAL record to the writer.\n// Format: [4B magic][4B payload_len][payload][4B CRC32]\nfunc writeWALRecord(w io.Writer, msg *WALMessage) error {\n\tpayload := buildWALPayload(msg)\n\tcrc := crc32.ChecksumIEEE(payload)\n\n\trecord := make([]byte, 0, 4+4+len(payload)+4)\n\n\tvar magic [4]byte\n\tbinary.LittleEndian.PutUint32(magic[:], walRecordMagic)\n\trecord = append(record, magic[:]...)\n\n\tvar pLen [4]byte\n\tbinary.LittleEndian.PutUint32(pLen[:], uint32(len(payload)))\n\trecord = append(record, pLen[:]...)\n\n\trecord = append(record, payload...)\n\n\tvar crcBytes [4]byte\n\tbinary.LittleEndian.PutUint32(crcBytes[:], crc)\n\trecord = append(record, crcBytes[:]...)\n\n\t_, err := w.Write(record)\n\treturn err\n}\n\n// readWALRecord reads one WAL record from the reader.\n// Returns (nil, nil) on clean EOF. Returns error on data corruption.\n// A CRC mismatch indicates a truncated trailing record (expected on crash).\nfunc readWALRecord(r io.Reader) (*WALMessage, error) {\n\tvar magic uint32\n\tif err := binary.Read(r, binary.LittleEndian, &magic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil, nil // Clean EOF\n\t\t}\n\t\treturn nil, fmt.Errorf(\"read record magic: %w\", err)\n\t}\n\n\tif magic != walRecordMagic {\n\t\treturn nil, fmt.Errorf(\"invalid record magic 0x%08X (expected 0x%08X)\", magic, walRecordMagic)\n\t}\n\n\tvar payloadLen uint32\n\tif err := binary.Read(r, binary.LittleEndian, &payloadLen); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload length: %w\", err)\n\t}\n\n\tif payloadLen > 1<<20 { // 1 MB sanity limit\n\t\treturn nil, fmt.Errorf(\"record payload too large: %d bytes\", payloadLen)\n\t}\n\n\tpayload := make([]byte, payloadLen)\n\tif _, err := io.ReadFull(r, payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"read payload: %w\", err)\n\t}\n\n\tvar storedCRC uint32\n\tif err := binary.Read(r, binary.LittleEndian, &storedCRC); err != nil {\n\t\treturn nil, fmt.Errorf(\"read CRC: %w\", err)\n\t}\n\n\tif crc32.ChecksumIEEE(payload) != storedCRC {\n\t\treturn nil, fmt.Errorf(\"CRC mismatch (truncated write or corruption)\")\n\t}\n\n\treturn parseWALPayload(payload)\n}\n\n// parseWALPayload decodes a binary payload into a WALMessage.\nfunc parseWALPayload(payload []byte) (*WALMessage, error) {\n\tif len(payload) < 8+2+1+4 {\n\t\treturn nil, fmt.Errorf(\"payload too short: %d bytes\", len(payload))\n\t}\n\n\toffset := 0\n\n\t// Timestamp (8 bytes)\n\tts := int64(binary.LittleEndian.Uint64(payload[offset : offset+8]))\n\toffset += 8\n\n\t// Metric name (2-byte length + bytes)\n\tif offset+2 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name length overflows payload\")\n\t}\n\tmLen := int(binary.LittleEndian.Uint16(payload[offset : offset+2]))\n\toffset += 2\n\n\tif offset+mLen > len(payload) {\n\t\treturn nil, fmt.Errorf(\"metric name overflows payload\")\n\t}\n\tmetricName := string(payload[offset : offset+mLen])\n\toffset += mLen\n\n\t// Selector count (1 byte)\n\tif offset >= len(payload) {\n\t\treturn nil, fmt.Errorf(\"selector count overflows payload\")\n\t}\n\tselCount := int(payload[offset])\n\toffset++\n\n\tselectors := make([]string, selCount)\n\tfor i := range selCount {\n\t\tif offset >= len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] length overflows payload\", i)\n\t\t}\n\t\tsLen := int(payload[offset])\n\t\toffset++\n\n\t\tif offset+sLen > len(payload) {\n\t\t\treturn nil, fmt.Errorf(\"selector[%d] data overflows payload\", i)\n\t\t}\n\t\tselectors[i] = string(payload[offset : offset+sLen])\n\t\toffset += sLen\n\t}\n\n\t// Value (4 bytes, float32 bits)\n\tif offset+4 > len(payload) {\n\t\treturn nil, fmt.Errorf(\"value overflows payload\")\n\t}\n\tbits := binary.LittleEndian.Uint32(payload[offset : offset+4])\n\tvalue := schema.Float(math.Float32frombits(bits))\n\n\treturn &WALMessage{\n\t\tMetricName: metricName,\n\t\tTimestamp: ts,\n\t\tSelector: selectors,\n\t\tValue: value,\n\t}, nil\n}\n\n// loadWALFile reads a WAL file and replays all valid records into the Level tree.\n// l is the host-level node. Corrupt or partial trailing records are silently skipped\n// (expected on crash). Records older than 'from' are skipped.\nfunc (l *Level) loadWALFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\t// Verify file header magic.\n\tvar fileMagic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &fileMagic); err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn nil // Empty file, no data\n\t\t}\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: read file header: %w\", err)\n\t}\n\n\tif fileMagic != walFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> WAL: invalid file magic 0x%08X (expected 0x%08X)\", fileMagic, walFileMagic)\n\t}\n\n\t// Cache level lookups to avoid repeated tree traversal.\n\tlvlCache := make(map[string]*Level)\n\n\tfor {\n\t\tmsg, err := readWALRecord(br)\n\t\tif err != nil {\n\t\t\t// Truncated trailing record is expected after a crash; stop replaying.\n\t\t\tcclog.Debugf(\"[METRICSTORE]> WAL: stopping replay at corrupted/partial record: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tif msg == nil {\n\t\t\tbreak // Clean EOF\n\t\t}\n\n\t\tif msg.Timestamp < from {\n\t\t\tcontinue // Older than retention window\n\t\t}\n\n\t\tminfo, ok := m.Metrics[msg.MetricName]\n\t\tif !ok {\n\t\t\tcontinue // Unknown metric (config may have changed)\n\t\t}\n\n\t\t// Cache key is the null-separated selector path.\n\t\tcacheKey := joinSelector(msg.Selector)\n\t\tlvl, ok := lvlCache[cacheKey]\n\t\tif !ok {\n\t\t\tlvl = l.findLevelOrCreate(msg.Selector, len(m.Metrics))\n\t\t\tlvlCache[cacheKey] = lvl\n\t\t}\n\n\t\t// Write directly to the buffer, same as WriteToLevel but without the\n\t\t// global level lookup (we already have the right level).\n\t\tlvl.lock.Lock()\n\t\tb := lvl.metrics[minfo.offset]\n\t\tif b == nil {\n\t\t\tb = newBuffer(msg.Timestamp, minfo.Frequency)\n\t\t\tlvl.metrics[minfo.offset] = b\n\t\t}\n\t\tnb, writeErr := b.write(msg.Timestamp, msg.Value)\n\t\tif writeErr == nil && b != nb {\n\t\t\tlvl.metrics[minfo.offset] = nb\n\t\t}\n\t\t// Ignore write errors for timestamps before buffer start (can happen when\n\t\t// replaying WAL entries that predate a loaded snapshot's start time).\n\t\tlvl.lock.Unlock()\n\t}\n\n\treturn nil\n}\n\n// joinSelector builds a cache key from a selector slice using null bytes as separators.\nfunc joinSelector(sel []string) string {\n\tif len(sel) == 0 {\n\t\treturn \"\"\n\t}\n\tvar result strings.Builder\n\tresult.WriteString(sel[0])\n\tfor i := 1; i < len(sel); i++ {\n\t\tresult.WriteString(\"\\x00\" + sel[i])\n\t}\n\treturn result.String()\n}\n\n// ToCheckpointWAL writes binary snapshot files for all hosts in parallel.\n// Returns the number of files written, the list of host directories that were\n// successfully checkpointed (for WAL rotation), and any errors.\nfunc (m *MemoryStore) ToCheckpointWAL(dir string, from, to int64) (int, []string, error) {\n\t// Collect all cluster/host pairs.\n\tm.root.lock.RLock()\n\ttotalHosts := 0\n\tfor _, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\ttotalHosts += len(l1.children)\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\tlevels := make([]*Level, 0, totalHosts)\n\tselectors := make([][]string, 0, totalHosts)\n\n\tm.root.lock.RLock()\n\tfor sel1, l1 := range m.root.children {\n\t\tl1.lock.RLock()\n\t\tfor sel2, l2 := range l1.children {\n\t\t\tlevels = append(levels, l2)\n\t\t\tselectors = append(selectors, []string{sel1, sel2})\n\t\t}\n\t\tl1.lock.RUnlock()\n\t}\n\tm.root.lock.RUnlock()\n\n\ttype workItem struct {\n\t\tlevel *Level\n\t\thostDir string\n\t\tselector []string\n\t}\n\n\tn, errs := int32(0), int32(0)\n\tvar successDirs []string\n\tvar successMu sync.Mutex\n\n\tvar wg sync.WaitGroup\n\twg.Add(Keys.NumWorkers)\n\twork := make(chan workItem, Keys.NumWorkers*2)\n\n\tfor range Keys.NumWorkers {\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor wi := range work {\n\t\t\t\terr := wi.level.toCheckpointBinary(wi.hostDir, from, to, m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == ErrNoNewArchiveData {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> binary checkpoint error for %s: %v\", wi.hostDir, err)\n\t\t\t\t\tatomic.AddInt32(&errs, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.AddInt32(&n, 1)\n\t\t\t\t\tsuccessMu.Lock()\n\t\t\t\t\tsuccessDirs = append(successDirs, wi.hostDir)\n\t\t\t\t\tsuccessMu.Unlock()\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor i := range levels {\n\t\thostDir := path.Join(dir, path.Join(selectors[i]...))\n\t\twork <- workItem{\n\t\t\tlevel: levels[i],\n\t\t\thostDir: hostDir,\n\t\t\tselector: selectors[i],\n\t\t}\n\t}\n\tclose(work)\n\twg.Wait()\n\n\tif errs > 0 {\n\t\treturn int(n), successDirs, fmt.Errorf(\"[METRICSTORE]> %d errors during binary checkpoint (%d successes)\", errs, n)\n\t}\n\treturn int(n), successDirs, nil\n}\n\n// toCheckpointBinary writes a binary snapshot file for a single host-level node.\n// Uses atomic rename (write to .tmp then rename) to avoid partial reads on crash.\nfunc (l *Level) toCheckpointBinary(dir string, from, to int64, m *MemoryStore) error {\n\tcf, err := l.toCheckpointFile(from, to, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cf == nil {\n\t\treturn ErrNoNewArchiveData\n\t}\n\n\tif err := os.MkdirAll(dir, CheckpointDirPerms); err != nil {\n\t\treturn fmt.Errorf(\"mkdir %s: %w\", dir, err)\n\t}\n\n\t// Write to a temp file first, then rename (atomic on POSIX).\n\ttmpPath := path.Join(dir, fmt.Sprintf(\"%d.bin.tmp\", from))\n\tfinalPath := path.Join(dir, fmt.Sprintf(\"%d.bin\", from))\n\n\tf, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, CheckpointFilePerms)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"open binary snapshot %s: %w\", tmpPath, err)\n\t}\n\n\tbw := bufio.NewWriter(f)\n\tif err := writeBinarySnapshotFile(bw, cf); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn fmt.Errorf(\"write binary snapshot: %w\", err)\n\t}\n\tif err := bw.Flush(); err != nil {\n\t\tf.Close()\n\t\tos.Remove(tmpPath)\n\t\treturn err\n\t}\n\tf.Close()\n\n\treturn os.Rename(tmpPath, finalPath)\n}\n\n// writeBinarySnapshotFile writes the binary snapshot file header and level tree.\nfunc writeBinarySnapshotFile(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, snapFileMagic); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.From); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Write(w, binary.LittleEndian, cf.To); err != nil {\n\t\treturn err\n\t}\n\treturn writeBinaryLevel(w, cf)\n}\n\n// writeBinaryLevel recursively writes a CheckpointFile level in binary format.\nfunc writeBinaryLevel(w io.Writer, cf *CheckpointFile) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Metrics))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, metric := range cf.Metrics {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Frequency); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, metric.Start); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := binary.Write(w, binary.LittleEndian, uint32(len(metric.Data))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, v := range metric.Data {\n\t\t\tif err := binary.Write(w, binary.LittleEndian, math.Float32bits(float32(v))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := binary.Write(w, binary.LittleEndian, uint32(len(cf.Children))); err != nil {\n\t\treturn err\n\t}\n\n\tfor name, child := range cf.Children {\n\t\tif err := writeString16(w, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := writeBinaryLevel(w, child); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// writeString16 writes a 2-byte length-prefixed string to w.\nfunc writeString16(w io.Writer, s string) error {\n\tif err := binary.Write(w, binary.LittleEndian, uint16(len(s))); err != nil {\n\t\treturn err\n\t}\n\t_, err := io.WriteString(w, s)\n\treturn err\n}\n\n// loadBinaryFile reads a binary snapshot file and loads data into the Level tree.\n// The retention check (from) is applied to the file's 'to' timestamp.\nfunc (l *Level) loadBinaryFile(m *MemoryStore, f *os.File, from int64) error {\n\tbr := bufio.NewReader(f)\n\n\tvar magic uint32\n\tif err := binary.Read(br, binary.LittleEndian, &magic); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read magic: %w\", err)\n\t}\n\tif magic != snapFileMagic {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: invalid magic 0x%08X (expected 0x%08X)\", magic, snapFileMagic)\n\t}\n\n\tvar fileFrom, fileTo int64\n\tif err := binary.Read(br, binary.LittleEndian, &fileFrom); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read from: %w\", err)\n\t}\n\tif err := binary.Read(br, binary.LittleEndian, &fileTo); err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read to: %w\", err)\n\t}\n\n\tif fileTo != 0 && fileTo < from {\n\t\treturn nil // File is older than retention window, skip it\n\t}\n\n\tcf, err := readBinaryLevel(br)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[METRICSTORE]> binary snapshot: read level tree: %w\", err)\n\t}\n\tcf.From = fileFrom\n\tcf.To = fileTo\n\n\treturn l.loadFile(cf, m)\n}\n\n// readBinaryLevel recursively reads a level from the binary snapshot format.\nfunc readBinaryLevel(r io.Reader) (*CheckpointFile, error) {\n\tcf := &CheckpointFile{\n\t\tMetrics: make(map[string]*CheckpointMetrics),\n\t\tChildren: make(map[string]*CheckpointFile),\n\t}\n\n\tvar numMetrics uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numMetrics); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_metrics: %w\", err)\n\t}\n\n\tfor range numMetrics {\n\t\tname, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read metric name: %w\", err)\n\t\t}\n\n\t\tvar freq, start int64\n\t\tif err := binary.Read(r, binary.LittleEndian, &freq); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read frequency for %s: %w\", name, err)\n\t\t}\n\t\tif err := binary.Read(r, binary.LittleEndian, &start); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read start for %s: %w\", name, err)\n\t\t}\n\n\t\tvar numValues uint32\n\t\tif err := binary.Read(r, binary.LittleEndian, &numValues); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read num_values for %s: %w\", name, err)\n\t\t}\n\n\t\tdata := make([]schema.Float, numValues)\n\t\tfor i := range numValues {\n\t\t\tvar bits uint32\n\t\t\tif err := binary.Read(r, binary.LittleEndian, &bits); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"read value[%d] for %s: %w\", i, name, err)\n\t\t\t}\n\t\t\tdata[i] = schema.Float(math.Float32frombits(bits))\n\t\t}\n\n\t\tcf.Metrics[name] = &CheckpointMetrics{\n\t\t\tFrequency: freq,\n\t\t\tStart: start,\n\t\t\tData: data,\n\t\t}\n\t}\n\n\tvar numChildren uint32\n\tif err := binary.Read(r, binary.LittleEndian, &numChildren); err != nil {\n\t\treturn nil, fmt.Errorf(\"read num_children: %w\", err)\n\t}\n\n\tfor range numChildren {\n\t\tchildName, err := readString16(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child name: %w\", err)\n\t\t}\n\n\t\tchild, err := readBinaryLevel(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"read child %s: %w\", childName, err)\n\t\t}\n\t\tcf.Children[childName] = child\n\t}\n\n\treturn cf, nil\n}\n\n// readString16 reads a 2-byte length-prefixed string from r.\nfunc readString16(r io.Reader) (string, error) {\n\tvar sLen uint16\n\tif err := binary.Read(r, binary.LittleEndian, &sLen); err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf := make([]byte, sLen)\n\tif _, err := io.ReadFull(r, buf); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(buf), nil\n}\n","structuredPatch":[{"oldStart":338,"oldLines":6,"newStart":338,"newLines":81,"lines":[" }"," }"," ","+// writeWALRecordDirect encodes a WAL record directly into the bufio.Writer,","+// avoiding heap allocations by using a stack-allocated scratch buffer for","+// the fixed-size header/trailer and computing CRC inline.","+func writeWALRecordDirect(w *bufio.Writer, msg *WALMessage) error {","+ // Compute payload size.","+ payloadSize := 8 + 2 + len(msg.MetricName) + 1 + 4","+ for _, s := range msg.Selector {","+ payloadSize += 1 + len(s)","+ }","+","+ // Write magic + payload length (8 bytes header).","+ var hdr [8]byte","+ binary.LittleEndian.PutUint32(hdr[0:4], walRecordMagic)","+ binary.LittleEndian.PutUint32(hdr[4:8], uint32(payloadSize))","+ if _, err := w.Write(hdr[:]); err != nil {","+ return err","+ }","+","+ // We need to compute CRC over the payload as we write it.","+ crc := crc32.NewIEEE()","+","+ // Timestamp (8 bytes).","+ var scratch [8]byte","+ binary.LittleEndian.PutUint64(scratch[:8], uint64(msg.Timestamp))","+ crc.Write(scratch[:8])","+ if _, err := w.Write(scratch[:8]); err != nil {","+ return err","+ }","+","+ // Metric name length (2 bytes) + metric name.","+ binary.LittleEndian.PutUint16(scratch[:2], uint16(len(msg.MetricName)))","+ crc.Write(scratch[:2])","+ if _, err := w.Write(scratch[:2]); err != nil {","+ return err","+ }","+ nameBytes := []byte(msg.MetricName)","+ crc.Write(nameBytes)","+ if _, err := w.Write(nameBytes); err != nil {","+ return err","+ }","+","+ // Selector count (1 byte).","+ scratch[0] = byte(len(msg.Selector))","+ crc.Write(scratch[:1])","+ if _, err := w.Write(scratch[:1]); err != nil {","+ return err","+ }","+","+ // Selectors (1-byte length + bytes each).","+ for _, sel := range msg.Selector {","+ scratch[0] = byte(len(sel))","+ crc.Write(scratch[:1])","+ if _, err := w.Write(scratch[:1]); err != nil {","+ return err","+ }","+ selBytes := []byte(sel)","+ crc.Write(selBytes)","+ if _, err := w.Write(selBytes); err != nil {","+ return err","+ }","+ }","+","+ // Value (4 bytes, float32 bits).","+ binary.LittleEndian.PutUint32(scratch[:4], math.Float32bits(float32(msg.Value)))","+ crc.Write(scratch[:4])","+ if _, err := w.Write(scratch[:4]); err != nil {","+ return err","+ }","+","+ // CRC32 (4 bytes).","+ binary.LittleEndian.PutUint32(scratch[:4], crc.Sum32())","+ _, err := w.Write(scratch[:4])","+ return err","+}","+"," // buildWALPayload encodes a WALMessage into a binary payload (without magic/length/CRC)."," func buildWALPayload(msg *WALMessage) []byte {"," size := 8 + 2 + len(msg.MetricName) + 1 + 4"]}],"userModified":false,"replaceAll":false},"sourceToolAssistantUUID":"3829bf65-3ef2-4147-997a-93067d16f856","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"f516e388-967e-426b-8ce5-d27bb7de30f8","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01MwDtX2EXWLeY2GyMf3bPBz","type":"message","role":"assistant","content":[{"type":"text","text":"Now update `lineprotocol.go` to use `SendWALMessage` instead of the old channel:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1133,"cache_read_input_tokens":54066,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":1133},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zm2h9ACaUXjNCvZnA9","type":"assistant","uuid":"81698871-f318-433a-a9c1-73deaba8627d","timestamp":"2026-03-18T05:30:55.034Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"81698871-f318-433a-a9c1-73deaba8627d","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01MwDtX2EXWLeY2GyMf3bPBz","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01DFf2yUQMVDgkrySkR8wNCm","name":"Edit","input":{"replace_all":false,"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/lineprotocol.go","old_string":"\t\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\t\tmsg := &WALMessage{\n\t\t\t\tMetricName: string(st.metricBuf),\n\t\t\t\tCluster: cluster,\n\t\t\t\tNode: host,\n\t\t\t\tSelector: append([]string{}, st.selector...),\n\t\t\t\tValue: metric.Value,\n\t\t\t\tTimestamp: time,\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase WALMessages <- msg:\n\t\t\tdefault:\n\t\t\t\t// WAL channel full — metric is written to memory store but not WAL.\n\t\t\t\t// Next binary snapshot will capture it.\n\t\t\t\tif dropped := walDropped.Add(1); dropped%10000 == 1 {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> WAL channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)\n\t\t\t\t}\n\t\t\t}\n\t\t}","new_string":"\t\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\t\tmsg := &WALMessage{\n\t\t\t\tMetricName: string(st.metricBuf),\n\t\t\t\tCluster: cluster,\n\t\t\t\tNode: host,\n\t\t\t\tSelector: append([]string{}, st.selector...),\n\t\t\t\tValue: metric.Value,\n\t\t\t\tTimestamp: time,\n\t\t\t}\n\t\t\tif !SendWALMessage(msg) {\n\t\t\t\t// WAL shard channel full — metric is written to memory store but not WAL.\n\t\t\t\t// Next binary snapshot will capture it.\n\t\t\t\tif dropped := walDropped.Add(1); dropped%10000 == 1 {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> WAL shard channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)\n\t\t\t\t}\n\t\t\t}\n\t\t}"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":1133,"cache_read_input_tokens":54066,"output_tokens":577,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":1133,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zm2h9ACaUXjNCvZnA9","type":"assistant","uuid":"72101529-3598-4ee8-81de-3e5f77a78e1e","timestamp":"2026-03-18T05:31:02.152Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"type":"file-history-snapshot","messageId":"72101529-3598-4ee8-81de-3e5f77a78e1e","snapshot":{"messageId":"e61b6d31-15d1-4b25-a4d5-dc4c0ddd1260","trackedFileBackups":{"pkg/metricstore/walCheckpoint.go":{"backupFileName":"f5b5b4bac0274f50@v1","version":1,"backupTime":"2026-03-18T05:29:45.041Z"},"pkg/metricstore/lineprotocol.go":{"backupFileName":"90dc6599471442f6@v1","version":1,"backupTime":"2026-03-18T05:31:02.178Z"}},"timestamp":"2026-03-18T05:29:19.393Z"},"isSnapshotUpdate":true}
{"parentUuid":"72101529-3598-4ee8-81de-3e5f77a78e1e","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Edit","command":"callback"},"parentToolUseID":"toolu_01DFf2yUQMVDgkrySkR8wNCm","toolUseID":"toolu_01DFf2yUQMVDgkrySkR8wNCm","timestamp":"2026-03-18T05:31:02.181Z","uuid":"7e92b110-1875-4ed6-917e-92bc0832febe","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"72101529-3598-4ee8-81de-3e5f77a78e1e","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01DFf2yUQMVDgkrySkR8wNCm","type":"tool_result","content":"The file /Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/lineprotocol.go has been updated successfully."}]},"uuid":"69e6c8e8-7232-4b5e-8bdc-1ac294f4b8b0","timestamp":"2026-03-18T05:31:02.181Z","toolUseResult":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/lineprotocol.go","oldString":"\t\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\t\tmsg := &WALMessage{\n\t\t\t\tMetricName: string(st.metricBuf),\n\t\t\t\tCluster: cluster,\n\t\t\t\tNode: host,\n\t\t\t\tSelector: append([]string{}, st.selector...),\n\t\t\t\tValue: metric.Value,\n\t\t\t\tTimestamp: time,\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase WALMessages <- msg:\n\t\t\tdefault:\n\t\t\t\t// WAL channel full — metric is written to memory store but not WAL.\n\t\t\t\t// Next binary snapshot will capture it.\n\t\t\t\tif dropped := walDropped.Add(1); dropped%10000 == 1 {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> WAL channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)\n\t\t\t\t}\n\t\t\t}\n\t\t}","newString":"\t\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\t\tmsg := &WALMessage{\n\t\t\t\tMetricName: string(st.metricBuf),\n\t\t\t\tCluster: cluster,\n\t\t\t\tNode: host,\n\t\t\t\tSelector: append([]string{}, st.selector...),\n\t\t\t\tValue: metric.Value,\n\t\t\t\tTimestamp: time,\n\t\t\t}\n\t\t\tif !SendWALMessage(msg) {\n\t\t\t\t// WAL shard channel full — metric is written to memory store but not WAL.\n\t\t\t\t// Next binary snapshot will capture it.\n\t\t\t\tif dropped := walDropped.Add(1); dropped%10000 == 1 {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> WAL shard channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)\n\t\t\t\t}\n\t\t\t}\n\t\t}","originalFile":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// This file implements ingestion of InfluxDB line-protocol metric data received\n// over NATS. Each line encodes one metric sample with the following structure:\n//\n//\t<measurement>[,cluster=<c>][,hostname=<h>][,type=<t>][,type-id=<id>][,subtype=<s>][,stype-id=<id>] value=<v> [<timestamp>]\n//\n// The measurement name identifies the metric (e.g. \"cpu_load\"). Tags provide\n// routing information (cluster, host) and optional sub-device selectors (type,\n// subtype). Only one field is expected per line: \"value\".\n//\n// After decoding, each sample is:\n// 1. Written to the in-memory store via ms.WriteToLevel.\n// 2. If the checkpoint format is \"wal\", also forwarded to the WAL staging\n// goroutine via the WALMessages channel for durable write-ahead logging.\npackage metricstore\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/nats\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n\t\"github.com/ClusterCockpit/cc-line-protocol/v2/lineprotocol\"\n)\n\n// ReceiveNats subscribes to all configured NATS subjects and feeds incoming\n// line-protocol messages into the MemoryStore.\n//\n// When workers > 1 a pool of goroutines drains a shared channel so that\n// multiple messages can be decoded in parallel. With workers == 1 the NATS\n// callback decodes inline (no channel overhead, lower latency).\n//\n// The function blocks until ctx is cancelled and all worker goroutines have\n// finished. It returns nil when the NATS client is not configured; callers\n// should treat that as a no-op rather than an error.\nfunc ReceiveNats(ms *MemoryStore,\n\tworkers int,\n\tctx context.Context,\n) error {\n\tnc := nats.GetClient()\n\n\tif nc == nil {\n\t\tcclog.Warn(\"NATS client not initialized\")\n\t\treturn nil\n\t}\n\n\tvar wg sync.WaitGroup\n\tmsgs := make(chan []byte, max(workers*256, 8192))\n\n\tfor _, sc := range *Keys.Subscriptions {\n\t\tclusterTag := sc.ClusterTag\n\t\tif workers > 1 {\n\t\t\twg.Add(workers)\n\n\t\t\tfor range workers {\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tfor m := range msgs {\n\t\t\t\t\t\tdec := lineprotocol.NewDecoderWithBytes(m)\n\t\t\t\t\t\tif err := DecodeLine(dec, ms, clusterTag); err != nil {\n\t\t\t\t\t\t\tcclog.Errorf(\"error: %s\", err.Error())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\tnc.Subscribe(sc.SubscribeTo, func(subject string, data []byte) {\n\t\t\t\tselect {\n\t\t\t\tcase msgs <- data:\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t}\n\t\t\t})\n\t\t} else {\n\t\t\tnc.Subscribe(sc.SubscribeTo, func(subject string, data []byte) {\n\t\t\t\tdec := lineprotocol.NewDecoderWithBytes(data)\n\t\t\t\tif err := DecodeLine(dec, ms, clusterTag); err != nil {\n\t\t\t\t\tcclog.Errorf(\"error: %s\", err.Error())\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tcclog.Infof(\"NATS subscription to '%s' established\", sc.SubscribeTo)\n\t}\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tclose(msgs)\n\t}()\n\n\twg.Wait()\n\n\treturn nil\n}\n\n// reorder prepends prefix to buf in-place when buf has enough spare capacity,\n// avoiding an allocation. Falls back to a regular append otherwise.\n//\n// It is used to assemble the \"type<type-id>\" and \"subtype<stype-id>\" selector\n// strings when the type tag arrives before the type-id tag in the line, so the\n// two byte slices need to be concatenated in tag-declaration order regardless\n// of wire order.\nfunc reorder(buf, prefix []byte) []byte {\n\tn := len(prefix)\n\tm := len(buf)\n\tif cap(buf) < m+n {\n\t\treturn append(prefix[:n:n], buf...)\n\t} else {\n\t\tbuf = buf[:n+m]\n\t\tfor i := m - 1; i >= 0; i-- {\n\t\t\tbuf[i+n] = buf[i]\n\t\t}\n\t\tfor i := range n {\n\t\t\tbuf[i] = prefix[i]\n\t\t}\n\t\treturn buf\n\t}\n}\n\n// walDropped counts WAL messages dropped due to a full channel.\n// Logged periodically; not critical since binary snapshots capture the data.\nvar walDropped atomic.Int64\n\n// decodeState holds the per-call scratch buffers used by DecodeLine.\n// Instances are recycled via decodeStatePool to avoid repeated allocations\n// during high-throughput ingestion.\ntype decodeState struct {\n\t// metricBuf holds a copy of the current measurement name (line-protocol\n\t// measurement field). Copied because dec.Measurement() returns a slice\n\t// that is invalidated by the next decoder call.\n\tmetricBuf []byte\n\n\t// selector is the sub-device path passed to WriteToLevel and WALMessage\n\t// (e.g. [\"socket0\"] or [\"socket0\", \"memctrl1\"]). Reused across lines.\n\tselector []string\n\n\t// typeBuf accumulates the concatenated \"type\"+\"type-id\" tag value for the\n\t// current line. Reset at the start of each line's tag-decode loop.\n\ttypeBuf []byte\n\n\t// subTypeBuf accumulates the concatenated \"subtype\"+\"stype-id\" tag value.\n\t// Reset at the start of each line's tag-decode loop.\n\tsubTypeBuf []byte\n\n\t// prevTypeBytes / prevTypeStr cache the last seen typeBuf content and its\n\t// string conversion. Because consecutive lines in a batch typically address\n\t// the same sub-device, the cache hit rate is very high and avoids\n\t// repeated []byte→string allocations.\n\tprevTypeBytes []byte\n\tprevTypeStr string\n\n\t// prevSubTypeBytes / prevSubTypeStr are the same cache for the subtype.\n\tprevSubTypeBytes []byte\n\tprevSubTypeStr string\n}\n\n// decodeStatePool recycles decodeState values across DecodeLine calls to\n// reduce GC pressure during sustained metric ingestion.\nvar decodeStatePool = sync.Pool{\n\tNew: func() any {\n\t\treturn &decodeState{\n\t\t\tmetricBuf: make([]byte, 0, 16),\n\t\t\tselector: make([]string, 0, 4),\n\t\t\ttypeBuf: make([]byte, 0, 16),\n\t\t\tsubTypeBuf: make([]byte, 0, 16),\n\t\t}\n\t},\n}\n\n// DecodeLine reads all lines from dec (InfluxDB line-protocol) and writes each\n// decoded metric sample into ms.\n//\n// clusterDefault is used as the cluster name for lines that do not carry a\n// \"cluster\" tag. Callers typically supply the ClusterTag value from the NATS\n// subscription configuration.\n//\n// Performance notes:\n// - A decodeState is obtained from decodeStatePool to reuse scratch buffers.\n// - The Level pointer (host-level node in the metric tree) is cached across\n// consecutive lines that share the same cluster+host pair to avoid\n// repeated lock acquisitions on the root and cluster levels.\n// - []byte→string conversions for type/subtype selectors are cached via\n// prevType*/prevSubType* fields because batches typically repeat the same\n// sub-device identifiers.\n// - Timestamp parsing tries Second precision first; if that fails it retries\n// Millisecond, Microsecond, and Nanosecond in turn. A missing timestamp\n// falls back to time.Now().\n//\n// When the checkpoint format is \"wal\" each successfully decoded sample is also\n// sent to WALMessages so the WAL staging goroutine can persist it durably\n// before the next binary snapshot.\nfunc DecodeLine(dec *lineprotocol.Decoder,\n\tms *MemoryStore,\n\tclusterDefault string,\n) error {\n\t// Reduce allocations in loop:\n\tt := time.Now()\n\tmetric := Metric{}\n\tst := decodeStatePool.Get().(*decodeState)\n\tdefer decodeStatePool.Put(st)\n\n\t// Optimize for the case where all lines in a \"batch\" are about the same\n\t// cluster and host. By using `WriteToLevel` (level = host), we do not need\n\t// to take the root- and cluster-level lock as often.\n\tvar lvl *Level = nil\n\tprevCluster, prevHost := \"\", \"\"\n\n\tvar ok bool\n\tfor dec.Next() {\n\t\trawmeasurement, err := dec.Measurement()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Needs to be copied because another call to dec.* would\n\t\t// invalidate the returned slice.\n\t\tst.metricBuf = append(st.metricBuf[:0], rawmeasurement...)\n\n\t\t// The go compiler optimizes map[string(byteslice)] lookups:\n\t\tmetric.MetricConfig, ok = ms.Metrics[string(rawmeasurement)]\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tst.typeBuf, st.subTypeBuf = st.typeBuf[:0], st.subTypeBuf[:0]\n\t\tcluster, host := clusterDefault, \"\"\n\t\tfor {\n\t\t\tkey, val, err := dec.NextTag()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif key == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// The go compiler optimizes string([]byte{...}) == \"...\":\n\t\t\tswitch string(key) {\n\t\t\tcase \"cluster\":\n\t\t\t\tif string(val) == prevCluster {\n\t\t\t\t\tcluster = prevCluster\n\t\t\t\t} else {\n\t\t\t\t\tcluster = string(val)\n\t\t\t\t\tlvl = nil\n\t\t\t\t}\n\t\t\tcase \"hostname\", \"host\":\n\t\t\t\tif string(val) == prevHost {\n\t\t\t\t\thost = prevHost\n\t\t\t\t} else {\n\t\t\t\t\thost = string(val)\n\t\t\t\t\tlvl = nil\n\t\t\t\t}\n\t\t\tcase \"type\":\n\t\t\t\tif string(val) == \"node\" {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// We cannot be sure that the \"type\" tag comes before the \"type-id\" tag:\n\t\t\t\tif len(st.typeBuf) == 0 {\n\t\t\t\t\tst.typeBuf = append(st.typeBuf, val...)\n\t\t\t\t} else {\n\t\t\t\t\tst.typeBuf = reorder(st.typeBuf, val)\n\t\t\t\t}\n\t\t\tcase \"type-id\":\n\t\t\t\tst.typeBuf = append(st.typeBuf, val...)\n\t\t\tcase \"subtype\":\n\t\t\t\t// We cannot be sure that the \"subtype\" tag comes before the \"stype-id\" tag:\n\t\t\t\tif len(st.subTypeBuf) == 0 {\n\t\t\t\t\tst.subTypeBuf = append(st.subTypeBuf, val...)\n\t\t\t\t} else {\n\t\t\t\t\tst.subTypeBuf = reorder(st.subTypeBuf, val)\n\t\t\t\t}\n\t\t\tcase \"stype-id\":\n\t\t\t\tst.subTypeBuf = append(st.subTypeBuf, val...)\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\n\t\t// If the cluster or host changed, the lvl was set to nil\n\t\tif lvl == nil {\n\t\t\tst.selector = st.selector[:2]\n\t\t\tst.selector[0], st.selector[1] = cluster, host\n\t\t\tlvl = ms.GetLevel(st.selector)\n\t\t\tprevCluster, prevHost = cluster, host\n\t\t}\n\n\t\t// subtypes: cache []byte→string conversions; messages in a batch typically\n\t\t// share the same type/subtype so the hit rate is very high.\n\t\tst.selector = st.selector[:0]\n\t\tif len(st.typeBuf) > 0 {\n\t\t\tif !bytes.Equal(st.typeBuf, st.prevTypeBytes) {\n\t\t\t\tst.prevTypeBytes = append(st.prevTypeBytes[:0], st.typeBuf...)\n\t\t\t\tst.prevTypeStr = string(st.typeBuf)\n\t\t\t}\n\t\t\tst.selector = append(st.selector, st.prevTypeStr)\n\t\t\tif len(st.subTypeBuf) > 0 {\n\t\t\t\tif !bytes.Equal(st.subTypeBuf, st.prevSubTypeBytes) {\n\t\t\t\t\tst.prevSubTypeBytes = append(st.prevSubTypeBytes[:0], st.subTypeBuf...)\n\t\t\t\t\tst.prevSubTypeStr = string(st.subTypeBuf)\n\t\t\t\t}\n\t\t\t\tst.selector = append(st.selector, st.prevSubTypeStr)\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tkey, val, err := dec.NextField()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif key == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif string(key) != \"value\" {\n\t\t\t\treturn fmt.Errorf(\"host %s: unknown field: '%s' (value: %#v)\", host, string(key), val)\n\t\t\t}\n\n\t\t\tif val.Kind() == lineprotocol.Float {\n\t\t\t\tmetric.Value = schema.Float(val.FloatV())\n\t\t\t} else if val.Kind() == lineprotocol.Int {\n\t\t\t\tmetric.Value = schema.Float(val.IntV())\n\t\t\t} else if val.Kind() == lineprotocol.Uint {\n\t\t\t\tmetric.Value = schema.Float(val.UintV())\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"host %s: unsupported value type in message: %s\", host, val.Kind().String())\n\t\t\t}\n\t\t}\n\n\t\tif t, err = dec.Time(lineprotocol.Second, t); err != nil {\n\t\t\tt = time.Now()\n\t\t\tif t, err = dec.Time(lineprotocol.Millisecond, t); err != nil {\n\t\t\t\tt = time.Now()\n\t\t\t\tif t, err = dec.Time(lineprotocol.Microsecond, t); err != nil {\n\t\t\t\t\tt = time.Now()\n\t\t\t\t\tif t, err = dec.Time(lineprotocol.Nanosecond, t); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"host %s: timestamp : %#v with error : %#v\", host, t, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"host %s: timestamp : %#v with error : %#v\", host, t, err.Error())\n\t\t}\n\n\t\ttime := t.Unix()\n\n\t\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\t\tmsg := &WALMessage{\n\t\t\t\tMetricName: string(st.metricBuf),\n\t\t\t\tCluster: cluster,\n\t\t\t\tNode: host,\n\t\t\t\tSelector: append([]string{}, st.selector...),\n\t\t\t\tValue: metric.Value,\n\t\t\t\tTimestamp: time,\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase WALMessages <- msg:\n\t\t\tdefault:\n\t\t\t\t// WAL channel full — metric is written to memory store but not WAL.\n\t\t\t\t// Next binary snapshot will capture it.\n\t\t\t\tif dropped := walDropped.Add(1); dropped%10000 == 1 {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> WAL channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err := ms.WriteToLevel(lvl, st.selector, time, []Metric{metric}); err != nil {\n\t\t\tcclog.Warnf(\"write error for host %s metric %s at ts %d: %s\", host, string(st.metricBuf), time, err.Error())\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}\n","structuredPatch":[{"oldStart":361,"oldLines":13,"newStart":361,"newLines":11,"lines":[" Value: metric.Value,"," Timestamp: time,"," }","- select {","- case WALMessages <- msg:","- default:","- // WAL channel full — metric is written to memory store but not WAL.","+ if !SendWALMessage(msg) {","+ // WAL shard channel full — metric is written to memory store but not WAL."," // Next binary snapshot will capture it."," if dropped := walDropped.Add(1); dropped%10000 == 1 {","- cclog.Warnf(\"[METRICSTORE]> WAL channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)","+ cclog.Warnf(\"[METRICSTORE]> WAL shard channel full, dropped %d messages (data safe in memory, next snapshot will capture)\", dropped)"," }"," }"," }"]}],"userModified":false,"replaceAll":false},"sourceToolAssistantUUID":"72101529-3598-4ee8-81de-3e5f77a78e1e","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"69e6c8e8-7232-4b5e-8bdc-1ac294f4b8b0","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_0122MLmJz5tkKNim7d6KYZQH","type":"message","role":"assistant","content":[{"type":"text","text":"Now update `Shutdown` in `metricstore.go` to close all shard channels:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":625,"cache_read_input_tokens":55199,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":625},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zmsfCJwR6BxpUYNn4p","type":"assistant","uuid":"7ab452d8-ff08-4279-8409-ec7baa91a7e0","timestamp":"2026-03-18T05:31:04.230Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"7ab452d8-ff08-4279-8409-ec7baa91a7e0","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_0122MLmJz5tkKNim7d6KYZQH","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01EodQprLiM3RCyDobMT3d1u","name":"Edit","input":{"replace_all":false,"file_path":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/metricstore.go","old_string":"\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tclose(WALMessages)\n\t}","new_string":"\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tfor _, ch := range walShardChs {\n\t\t\tclose(ch)\n\t\t}\n\t}"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":625,"cache_read_input_tokens":55199,"output_tokens":224,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":625,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zmsfCJwR6BxpUYNn4p","type":"assistant","uuid":"017c0be7-76a0-498d-9354-21ea8abfce53","timestamp":"2026-03-18T05:31:05.515Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"type":"file-history-snapshot","messageId":"017c0be7-76a0-498d-9354-21ea8abfce53","snapshot":{"messageId":"e61b6d31-15d1-4b25-a4d5-dc4c0ddd1260","trackedFileBackups":{"pkg/metricstore/walCheckpoint.go":{"backupFileName":"f5b5b4bac0274f50@v1","version":1,"backupTime":"2026-03-18T05:29:45.041Z"},"pkg/metricstore/lineprotocol.go":{"backupFileName":"90dc6599471442f6@v1","version":1,"backupTime":"2026-03-18T05:31:02.178Z"},"pkg/metricstore/metricstore.go":{"backupFileName":"9d6c8b589b687438@v1","version":1,"backupTime":"2026-03-18T05:31:05.554Z"}},"timestamp":"2026-03-18T05:29:19.393Z"},"isSnapshotUpdate":true}
{"parentUuid":"017c0be7-76a0-498d-9354-21ea8abfce53","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"PostToolUse","hookName":"PostToolUse:Edit","command":"callback"},"parentToolUseID":"toolu_01EodQprLiM3RCyDobMT3d1u","toolUseID":"toolu_01EodQprLiM3RCyDobMT3d1u","timestamp":"2026-03-18T05:31:05.557Z","uuid":"107565ba-13f3-4404-8654-311f911d8abe","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"017c0be7-76a0-498d-9354-21ea8abfce53","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01EodQprLiM3RCyDobMT3d1u","type":"tool_result","content":"The file /Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/metricstore.go has been updated successfully."}]},"uuid":"59ac1522-b87a-45f0-87b8-93fb72fd6a78","timestamp":"2026-03-18T05:31:05.557Z","toolUseResult":{"filePath":"/Users/jan/prg/ClusterCockpit/cc-backend/pkg/metricstore/metricstore.go","oldString":"\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tclose(WALMessages)\n\t}","newString":"\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tfor _, ch := range walShardChs {\n\t\t\tclose(ch)\n\t\t}\n\t}","originalFile":"// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.\n// All rights reserved. This file is part of cc-backend.\n// Use of this source code is governed by a MIT-style\n// license that can be found in the LICENSE file.\n\n// Package metricstore provides an efficient in-memory time-series metric storage system\n// with support for hierarchical data organization, checkpointing, and archiving.\n//\n// The package organizes metrics in a tree structure (cluster → host → component) and\n// provides concurrent read/write access to metric data with configurable aggregation strategies.\n// Background goroutines handle periodic checkpointing (JSON or Avro format), archiving old data,\n// and enforcing retention policies.\n//\n// Key features:\n// - In-memory metric storage with configurable retention\n// - Hierarchical data organization (selectors)\n// - Concurrent checkpoint/archive workers\n// - Support for sum and average aggregation\n// - NATS integration for metric ingestion\npackage metricstore\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"runtime/debug\"\n\t\"slices\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ClusterCockpit/cc-backend/internal/config\"\n\tcclog \"github.com/ClusterCockpit/cc-lib/v2/ccLogger\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/resampler\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/schema\"\n\t\"github.com/ClusterCockpit/cc-lib/v2/util\"\n)\n\n// GlobalState holds the global state for the metric store with thread-safe access.\ntype GlobalState struct {\n\tmu sync.RWMutex\n\tlastRetentionTime int64\n\tselectorsExcluded bool\n}\n\nvar (\n\tsingleton sync.Once\n\tmsInstance *MemoryStore\n\t// shutdownFunc stores the context cancellation function created in Init\n\t// and is called during Shutdown to cancel all background goroutines\n\tshutdownFunc context.CancelFunc\n\tshutdownFuncMu sync.Mutex // Protects shutdownFunc from concurrent access\n\t// Create a global instance\n\tstate = &GlobalState{}\n)\n\n// NodeProvider provides information about nodes currently in use by running jobs.\n//\n// This interface allows metricstore to query job information without directly\n// depending on the repository package, breaking the import cycle.\n//\n// Implementations should return nodes that are actively processing jobs started\n// before the given timestamp. These nodes will be excluded from retention-based\n// garbage collection to prevent data loss for jobs that are still running or\n// recently completed.\ntype NodeProvider interface {\n\t// GetUsedNodes returns a map of cluster names to sorted lists of unique hostnames\n\t// that are currently in use by jobs that started before the given timestamp.\n\t//\n\t// Parameters:\n\t// - ts: Unix timestamp threshold - returns nodes with jobs started before this time\n\t//\n\t// Returns:\n\t// - Map of cluster names to lists of node hostnames that should be excluded from garbage collection\n\t// - Error if the query fails\n\tGetUsedNodes(ts int64) (map[string][]string, error)\n}\n\n// Metric represents a single metric data point to be written to the store.\ntype Metric struct {\n\tName string\n\tValue schema.Float\n\t// MetricConfig contains frequency and aggregation settings for this metric.\n\t// If Frequency is 0, configuration will be looked up from MemoryStore.Metrics during Write().\n\tMetricConfig MetricConfig\n}\n\n// MemoryStore is the main in-memory time-series metric storage implementation.\n//\n// It organizes metrics in a hierarchical tree structure where each level represents\n// a component of the system hierarchy (e.g., cluster → host → CPU). Each level can\n// store multiple metrics as time-series buffers.\n//\n// The store is initialized as a singleton via InitMetrics() and accessed via GetMemoryStore().\n// All public methods are safe for concurrent use.\ntype MemoryStore struct {\n\tMetrics map[string]MetricConfig\n\troot Level\n\tnodeProvider NodeProvider\n}\n\n// Init initializes the metric store from configuration and starts background workers.\n//\n// This function must be called exactly once before any other metricstore operations.\n// It performs the following initialization steps:\n// 1. Validates and decodes the metric store configuration\n// 2. Configures worker pool size (defaults to NumCPU/2+1, max 10)\n// 3. Loads metric configurations from all registered clusters\n// 4. Restores checkpoints within the retention window\n// 5. Starts background workers for retention, checkpointing, archiving, and monitoring\n// 6. Optionally subscribes to NATS for real-time metric ingestion\n//\n// Parameters:\n// - rawConfig: JSON configuration for the metric store (see MetricStoreConfig)\n// - wg: WaitGroup that will be incremented for each background goroutine started\n//\n// The function will call cclog.Fatal on critical errors during initialization.\n// Use Shutdown() to cleanly stop all background workers started by Init().\n//\n// Note: Signal handling must be implemented by the caller. Call Shutdown() when\n// receiving termination signals to ensure checkpoint data is persisted.\nfunc Init(rawConfig json.RawMessage, metrics map[string]MetricConfig, wg *sync.WaitGroup) {\n\tstartupTime := time.Now()\n\n\tif rawConfig != nil {\n\t\tconfig.Validate(configSchema, rawConfig)\n\t\tdec := json.NewDecoder(bytes.NewReader(rawConfig))\n\t\tdec.DisallowUnknownFields()\n\t\tif err := dec.Decode(&Keys); err != nil {\n\t\t\tcclog.Abortf(\"[METRICSTORE]> Metric Store Config Init: Could not decode config file '%s'.\\nError: %s\\n\", rawConfig, err.Error())\n\t\t}\n\t}\n\n\t// Set NumWorkers from config or use default\n\tif Keys.NumWorkers <= 0 {\n\t\tKeys.NumWorkers = min(runtime.NumCPU()/2+1, DefaultMaxWorkers)\n\t}\n\tcclog.Debugf(\"[METRICSTORE]> Using %d workers for checkpoint/archive operations\\n\", Keys.NumWorkers)\n\n\t// Pass the config.MetricStoreKeys\n\tInitMetrics(metrics)\n\n\tms := GetMemoryStore()\n\n\td, err := time.ParseDuration(Keys.RetentionInMemory)\n\tif err != nil {\n\t\tcclog.Fatal(err)\n\t}\n\n\trestoreFrom := startupTime.Add(-d)\n\tcclog.Infof(\"[METRICSTORE]> Loading checkpoints newer than %s\\n\", restoreFrom.Format(time.RFC3339))\n\tfiles, err := ms.FromCheckpointFiles(Keys.Checkpoints.RootDir, restoreFrom.Unix())\n\tloadedData := ms.SizeInBytes() / 1024 / 1024 // In MB\n\tif err != nil {\n\t\tcclog.Fatalf(\"[METRICSTORE]> Loading checkpoints failed: %s\\n\", err.Error())\n\t} else {\n\t\tcclog.Infof(\"[METRICSTORE]> Checkpoints loaded (%d files, %d MB, that took %fs)\\n\", files, loadedData, time.Since(startupTime).Seconds())\n\t}\n\n\t// Try to use less memory by forcing a GC run here and then\n\t// lowering the target percentage. The default of 100 means\n\t// that only once the ratio of new allocations execeds the\n\t// previously active heap, a GC is triggered.\n\t// Forcing a GC here will set the \"previously active heap\"\n\t// to a minumum.\n\t// runtime.GC()\n\n\tctx, shutdown := context.WithCancel(context.Background())\n\n\tRetention(wg, ctx)\n\tCheckpointing(wg, ctx)\n\tCleanUp(wg, ctx)\n\tWALStaging(wg, ctx)\n\tMemoryUsageTracker(wg, ctx)\n\n\t// Note: Signal handling has been removed from this function.\n\t// The caller is responsible for handling shutdown signals and calling\n\t// the shutdown() function when appropriate.\n\t// Store the shutdown function for later use by Shutdown()\n\tshutdownFuncMu.Lock()\n\tshutdownFunc = shutdown\n\tshutdownFuncMu.Unlock()\n\n\tif Keys.Subscriptions != nil {\n\t\terr = ReceiveNats(ms, Keys.NumWorkers, ctx)\n\t\tif err != nil {\n\t\t\tcclog.Fatal(err)\n\t\t}\n\t}\n}\n\n// InitMetrics initializes the singleton MemoryStore instance with the given metric configurations.\n//\n// This function must be called before GetMemoryStore() and can only be called once due to\n// the singleton pattern. It assigns each metric an internal offset for efficient buffer indexing.\n//\n// Parameters:\n// - metrics: Map of metric names to their configurations (frequency and aggregation strategy)\n//\n// Panics if any metric has Frequency == 0, which indicates an invalid configuration.\n//\n// After this call, the global msInstance is ready for use via GetMemoryStore().\nfunc InitMetrics(metrics map[string]MetricConfig) {\n\tsingleton.Do(func() {\n\t\toffset := 0\n\t\tfor key, cfg := range metrics {\n\t\t\tif cfg.Frequency == 0 {\n\t\t\t\tpanic(\"[METRICSTORE]> invalid frequency\")\n\t\t\t}\n\n\t\t\tmetrics[key] = MetricConfig{\n\t\t\t\tFrequency: cfg.Frequency,\n\t\t\t\tAggregation: cfg.Aggregation,\n\t\t\t\toffset: offset,\n\t\t\t}\n\t\t\toffset += 1\n\t\t}\n\n\t\tmsInstance = &MemoryStore{\n\t\t\troot: Level{\n\t\t\t\tmetrics: make([]*buffer, len(metrics)),\n\t\t\t\tchildren: make(map[string]*Level),\n\t\t\t},\n\t\t\tMetrics: metrics,\n\t\t}\n\t})\n}\n\n// GetMemoryStore returns the singleton MemoryStore instance.\n//\n// Returns the initialized MemoryStore singleton. Calls cclog.Fatal if InitMetrics() was not called first.\n//\n// This function is safe for concurrent use after initialization.\nfunc GetMemoryStore() *MemoryStore {\n\tif msInstance == nil {\n\t\tcclog.Warnf(\"[METRICSTORE]> MemoryStore not initialized!\")\n\t}\n\n\treturn msInstance\n}\n\nfunc (ms *MemoryStore) GetMetricFrequency(metricName string) (int64, error) {\n\tif metric, ok := ms.Metrics[metricName]; ok {\n\t\treturn metric.Frequency, nil\n\t}\n\treturn 0, fmt.Errorf(\"[METRICSTORE]> metric %s not found\", metricName)\n}\n\n// SetNodeProvider sets the NodeProvider implementation for the MemoryStore.\n// This must be called during initialization to provide job state information\n// for selective buffer retention during Free operations.\n// If not set, the Free function will fall back to freeing all buffers.\nfunc (ms *MemoryStore) SetNodeProvider(provider NodeProvider) {\n\tms.nodeProvider = provider\n}\n\n// Shutdown performs a graceful shutdown of the metric store.\n//\n// This function cancels all background goroutines started by Init() and writes\n// a final checkpoint to disk before returning. It should be called when the\n// application receives a termination signal.\n//\n// The function will:\n// 1. Cancel the context to stop all background workers\n// 2. Close the WAL messages channel if using WAL format\n// 3. Write a final checkpoint to preserve in-memory data\n// 4. Log any errors encountered during shutdown\n//\n// Note: This function blocks until the final checkpoint is written.\nfunc Shutdown() {\n\tshutdownFuncMu.Lock()\n\tdefer shutdownFuncMu.Unlock()\n\tif shutdownFunc != nil {\n\t\tshutdownFunc()\n\t}\n\n\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tclose(WALMessages)\n\t}\n\n\tcclog.Infof(\"[METRICSTORE]> Writing to '%s'...\\n\", Keys.Checkpoints.RootDir)\n\tvar files int\n\tvar err error\n\n\tms := GetMemoryStore()\n\n\tlastCheckpointMu.Lock()\n\tfrom := lastCheckpoint\n\tlastCheckpointMu.Unlock()\n\n\tif Keys.Checkpoints.FileFormat == \"wal\" {\n\t\tvar hostDirs []string\n\t\tfiles, hostDirs, err = ms.ToCheckpointWAL(Keys.Checkpoints.RootDir, from.Unix(), time.Now().Unix())\n\t\tif err == nil {\n\t\t\tRotateWALFilesAfterShutdown(hostDirs)\n\t\t}\n\t} else {\n\t\tfiles, err = ms.ToCheckpoint(Keys.Checkpoints.RootDir, from.Unix(), time.Now().Unix())\n\t}\n\n\tif err != nil {\n\t\tcclog.Errorf(\"[METRICSTORE]> Writing checkpoint failed: %s\\n\", err.Error())\n\t}\n\tcclog.Infof(\"[METRICSTORE]> Done! (%d files written)\\n\", files)\n}\n\n// Retention starts a background goroutine that periodically frees old metric data.\n//\n// This worker runs at half the retention interval and calls Free() to remove buffers\n// older than the configured retention time. It respects the NodeProvider to preserve\n// data for nodes with active jobs.\n//\n// Parameters:\n// - wg: WaitGroup to signal completion when context is cancelled\n// - ctx: Context for cancellation signal\n//\n// The goroutine exits when ctx is cancelled.\nfunc Retention(wg *sync.WaitGroup, ctx context.Context) {\n\tms := GetMemoryStore()\n\n\twg.Go(func() {\n\t\td, err := time.ParseDuration(Keys.RetentionInMemory)\n\t\tif err != nil {\n\t\t\tcclog.Fatal(err)\n\t\t}\n\t\tif d <= 0 {\n\t\t\treturn\n\t\t}\n\n\t\ttickInterval := d / 2\n\t\tif tickInterval <= 0 {\n\t\t\treturn\n\t\t}\n\t\tticker := time.NewTicker(tickInterval)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tstate.mu.Lock()\n\n\t\t\t\tt := time.Now().Add(-d)\n\n\t\t\t\tstate.lastRetentionTime = t.Unix()\n\n\t\t\t\tcclog.Infof(\"[METRICSTORE]> start freeing buffers (older than %s)...\\n\", t.Format(time.RFC3339))\n\n\t\t\t\tfreed, err := Free(ms, t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> freeing up buffers failed: %s\\n\", err.Error())\n\t\t\t\t} else {\n\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> done: %d buffers freed\\n\", freed)\n\t\t\t\t}\n\n\t\t\t\tstate.mu.Unlock()\n\n\t\t\t\t// Clean up the buffer pool\n\t\t\t\tbufferPool.Clean(state.lastRetentionTime)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// MemoryUsageTracker starts a background goroutine that monitors memory usage.\n//\n// This worker checks actual process memory usage (via runtime.MemStats) periodically\n// and force-frees buffers if memory exceeds the configured cap. It uses FreeOSMemory()\n// to return memory to the OS after freeing buffers, avoiding aggressive GC that causes\n// performance issues.\n//\n// The tracker logs both actual memory usage (heap allocated) and metric data size for\n// visibility into memory overhead from Go runtime structures and allocations.\n//\n// Parameters:\n// - wg: WaitGroup to signal completion when context is cancelled\n// - ctx: Context for cancellation signal\n//\n// The goroutine exits when ctx is cancelled.\nfunc MemoryUsageTracker(wg *sync.WaitGroup, ctx context.Context) {\n\tms := GetMemoryStore()\n\n\twg.Go(func() {\n\t\tnormalInterval := DefaultMemoryUsageTrackerInterval\n\t\tfastInterval := 30 * time.Second\n\n\t\tif normalInterval <= 0 {\n\t\t\treturn\n\t\t}\n\n\t\tticker := time.NewTicker(normalInterval)\n\t\tdefer ticker.Stop()\n\t\tcurrentInterval := normalInterval\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tvar mem runtime.MemStats\n\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\tactualMemoryGB := float64(mem.Alloc) / 1e9\n\t\t\t\tmetricDataGB := ms.SizeInGB()\n\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory usage: %.2f GB actual (%.2f GB metric data)\", actualMemoryGB, metricDataGB)\n\n\t\t\t\tfreedExcluded := 0\n\t\t\t\tfreedEmergency := 0\n\t\t\t\tvar err error\n\n\t\t\t\tstate.mu.RLock()\n\t\t\t\tlastRetention := state.lastRetentionTime\n\t\t\t\tselectorsExcluded := state.selectorsExcluded\n\t\t\t\tstate.mu.RUnlock()\n\n\t\t\t\tif lastRetention != 0 && selectorsExcluded {\n\t\t\t\t\tfreedExcluded, err = ms.Free(nil, lastRetention)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> error while force-freeing the excluded buffers: %s\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\tif freedExcluded > 0 {\n\t\t\t\t\t\tdebug.FreeOSMemory()\n\t\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> done: %d excluded buffers force-freed\", freedExcluded)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n\n\t\t\t\tif actualMemoryGB > float64(Keys.MemoryCap) {\n\t\t\t\t\tcclog.Warnf(\"[METRICSTORE]> memory usage %.2f GB exceeds cap %d GB, starting emergency buffer freeing\", actualMemoryGB, Keys.MemoryCap)\n\n\t\t\t\t\t// Use progressive time-based Free with increasing threshold\n\t\t\t\t\t// instead of ForceFree loop — fewer tree traversals, more effective\n\t\t\t\t\td, parseErr := time.ParseDuration(Keys.RetentionInMemory)\n\t\t\t\t\tif parseErr != nil {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> cannot parse retention duration: %s\", parseErr)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthresholds := []float64{0.75, 0.5, 0.25}\n\t\t\t\t\t\tfor _, fraction := range thresholds {\n\t\t\t\t\t\t\tthreshold := time.Now().Add(-time.Duration(float64(d) * fraction))\n\t\t\t\t\t\t\tfreed, freeErr := ms.Free(nil, threshold.Unix())\n\t\t\t\t\t\t\tif freeErr != nil {\n\t\t\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> error while freeing buffers at %.0f%% retention: %s\", fraction*100, freeErr)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfreedEmergency += freed\n\n\t\t\t\t\t\t\tbufferPool.Clear()\n\t\t\t\t\t\t\truntime.GC()\n\t\t\t\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n\n\t\t\t\t\t\t\tif actualMemoryGB < float64(Keys.MemoryCap) {\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbufferPool.Clear()\n\t\t\t\t\tdebug.FreeOSMemory()\n\n\t\t\t\t\truntime.ReadMemStats(&mem)\n\t\t\t\t\tactualMemoryGB = float64(mem.Alloc) / 1e9\n\n\t\t\t\t\tif actualMemoryGB >= float64(Keys.MemoryCap) {\n\t\t\t\t\t\tcclog.Errorf(\"[METRICSTORE]> after emergency frees (%d buffers), memory usage %.2f GB still at/above cap %d GB\", freedEmergency, actualMemoryGB, Keys.MemoryCap)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> emergency freeing complete: %d buffers freed, memory now %.2f GB\", freedEmergency, actualMemoryGB)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Adaptive ticker: check more frequently when memory is high\n\t\t\t\tmemoryRatio := actualMemoryGB / float64(Keys.MemoryCap)\n\t\t\t\tif memoryRatio > 0.8 && currentInterval != fastInterval {\n\t\t\t\t\tticker.Reset(fastInterval)\n\t\t\t\t\tcurrentInterval = fastInterval\n\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory at %.0f%% of cap, switching to fast check interval (30s)\", memoryRatio*100)\n\t\t\t\t} else if memoryRatio <= 0.8 && currentInterval != normalInterval {\n\t\t\t\t\tticker.Reset(normalInterval)\n\t\t\t\t\tcurrentInterval = normalInterval\n\t\t\t\t\tcclog.Infof(\"[METRICSTORE]> memory at %.0f%% of cap, switching to normal check interval\", memoryRatio*100)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}\n\n// Free removes metric data older than the given time while preserving data for active nodes.\n//\n// This function implements intelligent retention by consulting the NodeProvider (if configured)\n// to determine which nodes are currently in use by running jobs. Data for these nodes is\n// preserved even if older than the retention time.\n//\n// Parameters:\n// - ms: The MemoryStore instance\n// - t: Time threshold - buffers with data older than this will be freed\n//\n// Returns:\n// - Number of buffers freed\n// - Error if NodeProvider query fails\n//\n// Behavior:\n// - If no NodeProvider is set: frees all buffers older than t\n// - If NodeProvider returns empty map: frees all buffers older than t\n// - Otherwise: preserves buffers for nodes returned by GetUsedNodes(), frees others\nfunc Free(ms *MemoryStore, t time.Time) (int, error) {\n\t// If no NodeProvider is configured, free all buffers older than t\n\tif ms.nodeProvider == nil {\n\t\treturn ms.Free(nil, t.Unix())\n\t}\n\n\texcludeSelectors, err := ms.nodeProvider.GetUsedNodes(t.Unix())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tswitch lenMap := len(excludeSelectors); lenMap {\n\n\t// If the length of the map returned by GetUsedNodes() is 0,\n\t// then use default Free method with nil selector\n\tcase 0:\n\t\tstate.selectorsExcluded = false\n\t\treturn ms.Free(nil, t.Unix())\n\n\t// Else formulate selectors, exclude those from the map\n\t// and free the rest of the selectors\n\tdefault:\n\t\tstate.selectorsExcluded = true\n\t\tselectors := GetSelectors(ms, excludeSelectors)\n\t\treturn FreeSelected(ms, selectors, t)\n\t}\n}\n\n// FreeSelected frees buffers for specific selectors while preserving others.\n//\n// This function is used when we want to retain some specific nodes beyond the retention time.\n// It iterates through the provided selectors and frees their associated buffers.\n//\n// Parameters:\n// - ms: The MemoryStore instance\n// - selectors: List of selector paths to free (e.g., [[\"cluster1\", \"node1\"], [\"cluster2\", \"node2\"]])\n// - t: Time threshold for freeing buffers\n//\n// Returns the total number of buffers freed and any error encountered.\nfunc FreeSelected(ms *MemoryStore, selectors [][]string, t time.Time) (int, error) {\n\tfreed := 0\n\n\tfor _, selector := range selectors {\n\n\t\tfreedBuffers, err := ms.Free(selector, t.Unix())\n\t\tif err != nil {\n\t\t\tcclog.Errorf(\"error while freeing selected buffers: %#v\", err)\n\t\t}\n\t\tfreed += freedBuffers\n\n\t}\n\n\treturn freed, nil\n}\n\n// GetSelectors returns all selectors at depth 2 (cluster/node level) that are NOT in the exclusion map.\n//\n// This function generates a list of selectors whose buffers should be freed by excluding\n// selectors that correspond to nodes currently in use by running jobs.\n//\n// Parameters:\n// - ms: The MemoryStore instance\n// - excludeSelectors: Map of cluster names to node hostnames that should NOT be freed\n//\n// Returns a list of selectors ([]string paths) that can be safely freed.\n//\n// Example:\n//\n//\tIf the tree has paths [\"emmy\", \"node001\"] and [\"emmy\", \"node002\"],\n//\tand excludeSelectors contains {\"emmy\": [\"node001\"]},\n//\tthen only [[\"emmy\", \"node002\"]] is returned.\nfunc GetSelectors(ms *MemoryStore, excludeSelectors map[string][]string) [][]string {\n\tallSelectors := ms.GetPaths(2)\n\n\tfilteredSelectors := make([][]string, 0, len(allSelectors))\n\n\tfor _, path := range allSelectors {\n\t\tif len(path) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tkey := path[0] // The \"Key\" (Level 1)\n\t\tvalue := path[1] // The \"Value\" (Level 2)\n\n\t\texclude := false\n\n\t\t// Check if the key exists in our exclusion map\n\t\tif excludedValues, exists := excludeSelectors[key]; exists {\n\t\t\t// The key exists, now check if the specific value is in the exclusion list\n\t\t\tif slices.Contains(excludedValues, value) {\n\t\t\t\texclude = true\n\t\t\t}\n\t\t}\n\n\t\tif !exclude {\n\t\t\tfilteredSelectors = append(filteredSelectors, path)\n\t\t}\n\t}\n\n\treturn filteredSelectors\n}\n\n// GetPaths returns a list of lists (paths) to the specified depth.\nfunc (ms *MemoryStore) GetPaths(targetDepth int) [][]string {\n\tvar results [][]string\n\n\t// Start recursion. Initial path is empty.\n\t// We treat Root as depth 0.\n\tms.root.collectPaths(0, targetDepth, []string{}, &results)\n\n\treturn results\n}\n\n// Write all values in `metrics` to the level specified by `selector` for time `ts`.\n// Look at `findLevelOrCreate` for how selectors work.\nfunc (m *MemoryStore) Write(selector []string, ts int64, metrics []Metric) error {\n\tvar ok bool\n\tfor i, metric := range metrics {\n\t\tif metric.MetricConfig.Frequency == 0 {\n\t\t\tmetric.MetricConfig, ok = m.Metrics[metric.Name]\n\t\t\tif !ok {\n\t\t\t\tcclog.Debugf(\"[METRICSTORE]> Unknown metric '%s' in Write() - skipping\", metric.Name)\n\t\t\t\tmetric.MetricConfig.Frequency = 0\n\t\t\t}\n\t\t\tmetrics[i] = metric\n\t\t}\n\t}\n\n\treturn m.WriteToLevel(&m.root, selector, ts, metrics)\n}\n\nfunc (m *MemoryStore) GetLevel(selector []string) *Level {\n\treturn m.root.findLevelOrCreate(selector, len(m.Metrics))\n}\n\n// WriteToLevel assumes that `minfo` in `metrics` is filled in\nfunc (m *MemoryStore) WriteToLevel(l *Level, selector []string, ts int64, metrics []Metric) error {\n\tl = l.findLevelOrCreate(selector, len(m.Metrics))\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tfor _, metric := range metrics {\n\t\tif metric.MetricConfig.Frequency == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tb := l.metrics[metric.MetricConfig.offset]\n\t\tif b == nil {\n\t\t\t// First write to this metric and level\n\t\t\tb = newBuffer(ts, metric.MetricConfig.Frequency)\n\t\t\tl.metrics[metric.MetricConfig.offset] = b\n\t\t}\n\n\t\tnb, err := b.write(ts, metric.Value)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Last write created a new buffer...\n\t\tif b != nb {\n\t\t\tl.metrics[metric.MetricConfig.offset] = nb\n\t\t}\n\t}\n\treturn nil\n}\n\n// Read returns all values for metric `metric` from `from` to `to` for the selected level(s).\n// If the level does not hold the metric itself, the data will be aggregated recursively from the children.\n// The second and third return value are the actual from/to for the data. Those can be different from\n// the range asked for if no data was available.\nfunc (m *MemoryStore) Read(selector util.Selector, metric string, from, to, resolution int64) ([]schema.Float, int64, int64, int64, error) {\n\tif from > to {\n\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> invalid time range\")\n\t}\n\n\tminfo, ok := m.Metrics[metric]\n\tif !ok {\n\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> unknown metric: \" + metric)\n\t}\n\n\tn, data := 0, make([]schema.Float, (to-from)/minfo.Frequency+1)\n\n\terr := m.root.findBuffers(selector, minfo.offset, func(b *buffer) error {\n\t\tcdata, cfrom, cto, err := b.read(from, to, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif n == 0 {\n\t\t\tfrom, to = cfrom, cto\n\t\t} else if from != cfrom || to != cto || len(data) != len(cdata) {\n\t\t\tmissingfront, missingback := int((from-cfrom)/minfo.Frequency), int((to-cto)/minfo.Frequency)\n\t\t\tif missingfront != 0 {\n\t\t\t\treturn ErrDataDoesNotAlign\n\t\t\t}\n\n\t\t\tnewlen := len(cdata) - missingback\n\t\t\tif newlen < 1 {\n\t\t\t\treturn ErrDataDoesNotAlign\n\t\t\t}\n\t\t\tcdata = cdata[0:newlen]\n\t\t\tif len(cdata) != len(data) {\n\t\t\t\treturn ErrDataDoesNotAlign\n\t\t\t}\n\n\t\t\tfrom, to = cfrom, cto\n\t\t}\n\n\t\tdata = cdata\n\t\tn += 1\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, 0, 0, 0, err\n\t} else if n == 0 {\n\t\treturn nil, 0, 0, 0, ErrNoHostOrMetric\n\t} else if n > 1 {\n\t\tif minfo.Aggregation == AvgAggregation {\n\t\t\tnormalize := 1. / schema.Float(n)\n\t\t\tfor i := 0; i < len(data); i++ {\n\t\t\t\tdata[i] *= normalize\n\t\t\t}\n\t\t} else if minfo.Aggregation != SumAggregation {\n\t\t\treturn nil, 0, 0, 0, errors.New(\"[METRICSTORE]> invalid aggregation\")\n\t\t}\n\t}\n\n\tdata, resolution, err = resampler.LargestTriangleThreeBucket(data, minfo.Frequency, resolution)\n\tif err != nil {\n\t\treturn nil, 0, 0, 0, err\n\t}\n\n\treturn data, from, to, resolution, nil\n}\n\n// Free releases all buffers for the selected level and all its children that\n// contain only values older than `t`.\nfunc (m *MemoryStore) Free(selector []string, t int64) (int, error) {\n\treturn m.GetLevel(selector).free(t)\n}\n\n// ForceFree unconditionally removes the oldest buffer from each metric chain.\nfunc (m *MemoryStore) ForceFree() (int, error) {\n\treturn m.GetLevel(nil).forceFree()\n}\n\nfunc (m *MemoryStore) FreeAll() error {\n\tm.root.lock.Lock()\n\tdefer m.root.lock.Unlock()\n\n\tfor k := range m.root.children {\n\t\tdelete(m.root.children, k)\n\t}\n\n\treturn nil\n}\n\nfunc (m *MemoryStore) SizeInBytes() int64 {\n\treturn m.root.sizeInBytes()\n}\n\nfunc (m *MemoryStore) SizeInGB() float64 {\n\treturn float64(m.root.sizeInBytes()) / 1e9\n}\n\n// ListChildren , given a selector, returns a list of all children of the level\n// selected.\nfunc (m *MemoryStore) ListChildren(selector []string) []string {\n\tlvl := &m.root\n\tfor lvl != nil && len(selector) != 0 {\n\t\tlvl.lock.RLock()\n\t\tnext := lvl.children[selector[0]]\n\t\tlvl.lock.RUnlock()\n\t\tlvl = next\n\t\tselector = selector[1:]\n\t}\n\n\tif lvl == nil {\n\t\treturn nil\n\t}\n\n\tlvl.lock.RLock()\n\tdefer lvl.lock.RUnlock()\n\n\tchildren := make([]string, 0, len(lvl.children))\n\tfor child := range lvl.children {\n\t\tchildren = append(children, child)\n\t}\n\n\treturn children\n}\n","structuredPatch":[{"oldStart":277,"oldLines":7,"newStart":277,"newLines":9,"lines":[" }"," "," if Keys.Checkpoints.FileFormat == \"wal\" {","- close(WALMessages)","+ for _, ch := range walShardChs {","+ close(ch)","+ }"," }"," "," cclog.Infof(\"[METRICSTORE]> Writing to '%s'...\\n\", Keys.Checkpoints.RootDir)"]}],"userModified":false,"replaceAll":false},"sourceToolAssistantUUID":"017c0be7-76a0-498d-9354-21ea8abfce53","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"59ac1522-b87a-45f0-87b8-93fb72fd6a78","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01X7AnUfWCnnPJXLTEAZsZq1","type":"message","role":"assistant","content":[{"type":"text","text":"Now let's build to check for compile errors:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":382,"cache_read_input_tokens":55824,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":382},"output_tokens":4,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zn7yRN57FeDCAQrGXZ","type":"assistant","uuid":"3cc63bed-cb1e-4571-9fdc-e9056d6e6dc6","timestamp":"2026-03-18T05:31:07.607Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"3cc63bed-cb1e-4571-9fdc-e9056d6e6dc6","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01X7AnUfWCnnPJXLTEAZsZq1","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01BqTkZLKPSRL5EVSwyS4amt","name":"Bash","input":{"command":"go build ./pkg/metricstore/... 2>&1","description":"Build metricstore package"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":382,"cache_read_input_tokens":55824,"output_tokens":116,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":382,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zn7yRN57FeDCAQrGXZ","type":"assistant","uuid":"0881d0aa-92e5-4981-aa8f-4a64bc9a92fe","timestamp":"2026-03-18T05:31:08.383Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"0881d0aa-92e5-4981-aa8f-4a64bc9a92fe","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01BqTkZLKPSRL5EVSwyS4amt","type":"tool_result","content":"(Bash completed with no output)","is_error":false}]},"uuid":"188e34e8-55c1-4847-ae86-e6d827014360","timestamp":"2026-03-18T05:31:09.044Z","toolUseResult":{"stdout":"","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"sourceToolAssistantUUID":"0881d0aa-92e5-4981-aa8f-4a64bc9a92fe","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"188e34e8-55c1-4847-ae86-e6d827014360","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01GtHqLvX4q7LhS7YkRDp5ar","type":"message","role":"assistant","content":[{"type":"text","text":"Clean build. Let's also run the full project build and tests:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":186,"cache_read_input_tokens":56206,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":186},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9znSd6As8886ia3REp6","type":"assistant","uuid":"4668faaf-42c8-4025-bbee-a5b9706a433f","timestamp":"2026-03-18T05:31:13.817Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"4668faaf-42c8-4025-bbee-a5b9706a433f","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01GtHqLvX4q7LhS7YkRDp5ar","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_014Dh8dv6n9x9VXx8dAz4yUy","name":"Bash","input":{"command":"go build ./... 2>&1","description":"Build entire project"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":186,"cache_read_input_tokens":56206,"output_tokens":112,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":186,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9znSd6As8886ia3REp6","type":"assistant","uuid":"35c01ea0-0ac9-4510-94ed-4f2934ecac86","timestamp":"2026-03-18T05:31:14.472Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"35c01ea0-0ac9-4510-94ed-4f2934ecac86","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_014Dh8dv6n9x9VXx8dAz4yUy","type":"tool_result","content":"(Bash completed with no output)","is_error":false}]},"uuid":"22932b8b-24cf-491d-9a1a-5db7b0ce9cb8","timestamp":"2026-03-18T05:31:20.390Z","toolUseResult":{"stdout":"","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"sourceToolAssistantUUID":"35c01ea0-0ac9-4510-94ed-4f2934ecac86","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"22932b8b-24cf-491d-9a1a-5db7b0ce9cb8","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01PU5QNU3qgdkoczTqJpesVV","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01CrpCp8eYRQb1jcpTocPmrQ","name":"Bash","input":{"command":"go test ./pkg/metricstore/... 2>&1","description":"Run metricstore tests"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":111,"cache_read_input_tokens":56392,"output_tokens":86,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":111,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zoDKAgkyQSixe33nsW","type":"assistant","uuid":"499474fc-3f1d-4d77-8e74-b39d7755abfc","timestamp":"2026-03-18T05:31:22.167Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"499474fc-3f1d-4d77-8e74-b39d7755abfc","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01CrpCp8eYRQb1jcpTocPmrQ","type":"tool_result","content":"ok \tgithub.com/ClusterCockpit/cc-backend/pkg/metricstore\t0.535s","is_error":false}]},"uuid":"4d37f699-e42d-4bd7-bb4e-d95df2422dbb","timestamp":"2026-03-18T05:31:23.849Z","toolUseResult":{"stdout":"ok \tgithub.com/ClusterCockpit/cc-backend/pkg/metricstore\t0.535s","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"sourceToolAssistantUUID":"499474fc-3f1d-4d77-8e74-b39d7755abfc","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"4d37f699-e42d-4bd7-bb4e-d95df2422dbb","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01RSQmBwXa83kYfAiBkLVQdu","type":"message","role":"assistant","content":[{"type":"text","text":"All tests pass. Let me verify the final state of the changed files:"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":125,"cache_read_input_tokens":56503,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":125},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"}},"requestId":"req_011CZ9zoU6fYFKwwjxYpSvE6","type":"assistant","uuid":"542ed700-3c46-4ac9-b162-0b880d06cc03","timestamp":"2026-03-18T05:31:27.817Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"542ed700-3c46-4ac9-b162-0b880d06cc03","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_01RSQmBwXa83kYfAiBkLVQdu","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01ELxafpVje5dpr1LMyBZQ36","name":"Bash","input":{"command":"git diff --stat 2>&1","description":"Show changed files summary"},"caller":{"type":"direct"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":125,"cache_read_input_tokens":56503,"output_tokens":95,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":125,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zoU6fYFKwwjxYpSvE6","type":"assistant","uuid":"c8d546ed-a51f-408a-98ff-4ff66577d190","timestamp":"2026-03-18T05:31:28.076Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"c8d546ed-a51f-408a-98ff-4ff66577d190","isSidechain":false,"promptId":"53f7aeff-f280-4fa6-a195-55ff40087d7e","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01ELxafpVje5dpr1LMyBZQ36","type":"tool_result","content":" pkg/metricstore/lineprotocol.go | 8 +-\n pkg/metricstore/metricstore.go | 4 +-\n pkg/metricstore/walCheckpoint.go | 362 +++++++++++++++++++++++++++------------\n 3 files changed, 254 insertions(+), 120 deletions(-)","is_error":false}]},"uuid":"d95a6f2d-ee1e-446f-bb5c-075ee88f40aa","timestamp":"2026-03-18T05:31:28.138Z","toolUseResult":{"stdout":" pkg/metricstore/lineprotocol.go | 8 +-\n pkg/metricstore/metricstore.go | 4 +-\n pkg/metricstore/walCheckpoint.go | 362 +++++++++++++++++++++++++++------------\n 3 files changed, 254 insertions(+), 120 deletions(-)","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"sourceToolAssistantUUID":"c8d546ed-a51f-408a-98ff-4ff66577d190","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"d95a6f2d-ee1e-446f-bb5c-075ee88f40aa","isSidechain":false,"message":{"model":"claude-opus-4-6","id":"msg_018MviUYNEraK8d5wonXbnPx","type":"message","role":"assistant","content":[{"type":"text","text":"All changes compile and tests pass. Here's a summary of what was implemented:\n\n**Change 1 — Sharded WAL writer goroutines** (`walCheckpoint.go`):\n- Replaced single `WALMessages` channel + `WALStaging()` goroutine with `walNumShards` (= `NumWorkers`) independent shard goroutines\n- Each shard has its own channel (`walShardChs[i]`) and `hostFiles` map — zero contention between shards\n- Messages route to shards via `walShardIndex()` using FNV-1a hash of `cluster + \"\\0\" + node`, ensuring per-host writes stay serial\n- Per-shard channel buffer: `65536 / numShards` (min 1024) — same total memory budget\n\n**Change 2 — Zero-allocation record writing** (`walCheckpoint.go`):\n- Added `writeWALRecordDirect(w *bufio.Writer, msg)` that encodes the record directly into the `bufio.Writer` using a stack-allocated `[8]byte` scratch buffer and computes CRC inline via `crc32.NewIEEE()`\n- Eliminates both the `buildWALPayload()` and `writeWALRecord()` allocations from the hot path (old functions retained for tests/replay)\n\n**Change 3 — Route WAL sends to shards** (`lineprotocol.go`):\n- `SendWALMessage(msg)` replaces the direct channel send, routing to the correct shard\n\n**Change 4 — Shard-aware rotation** (`walCheckpoint.go`):\n- `RotateWALFiles` hashes the host directory to find the correct shard and sends the rotate request there via `walShardRotateChs[shard]`\n\n**Change 5 — Shutdown** (`metricstore.go`):\n- Closes all shard channels in a loop instead of closing a single `WALMessages` channel"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":1,"cache_creation_input_tokens":195,"cache_read_input_tokens":56628,"output_tokens":470,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":195,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"}},"requestId":"req_011CZ9zonTxkCowGYKgAqyvj","type":"assistant","uuid":"4d126e55-dda3-40ef-9b6a-bb99197021a0","timestamp":"2026-03-18T05:31:40.456Z","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}
{"parentUuid":"4d126e55-dda3-40ef-9b6a-bb99197021a0","isSidechain":false,"type":"progress","data":{"type":"hook_progress","hookEvent":"Stop","hookName":"Stop","command":"entire hooks claude-code stop"},"parentToolUseID":"6c3f6c97-377e-458c-afab-772a5580d6f7","toolUseID":"6c3f6c97-377e-458c-afab-772a5580d6f7","timestamp":"2026-03-18T05:31:40.489Z","uuid":"e337325c-27dc-4a0e-a26a-29bf24ef2200","userType":"external","entrypoint":"cli","cwd":"/Users/jan/prg/ClusterCockpit/cc-backend","sessionId":"734f1e28-b805-471f-8f2c-275878888543","version":"2.1.78","gitBranch":"hotfix","slug":"bright-wandering-flurry"}