Files
meshcore-analyzer/cmd/server/chunked_load_test.go
T
40f664c587 chore(#1859): gofmt sweep + gofmt/go vet CI gate (rebase of #1881) (#1941)
Rebase of #1881 by @SaarMesh-Bot onto current master. Their three
commits are preserved, two of them cherry-picked with authorship intact;
the sweep itself had to be regenerated. Opened as a new PR rather than
force-pushing their branch.

Closes #1881 once merged. Addresses parts 1 and 3 of #1859; part 2
landed as #1937.

## Why regenerated rather than merged

The sweep in #1881 was cut on 2026-09-02 07:13 and roughly forty PRs
landed after it, so it went `CONFLICTING/DIRTY`. Re-running `gofmt` on
current master is cheaper and less error-prone than resolving 72
conflicts that are all whitespace. The drift it fixes also grew in the
meantime: 66 files now, against 72 then, but spread differently.

## The three commits

1. **`style(#1859)`** — `gofmt -w` across the 14 modules. 66 files.
2. **`test(#1859)`** — @SaarMesh-Bot's fix for the one `go vet`
copylocks finding, `cmd/ingestor/coverage_boost_test.go`: the range
variable copied a `Config` embedding `sync.Once`. Cherry-picked
unchanged.
3. **`ci(#1859)`** — @SaarMesh-Bot's CI step that fails on gofmt drift
or vet findings, plus `.git-blame-ignore-revs`. Cherry-picked with one
change, noted in the commit message: the ignore file pointed at
`04bc80ee`, the sweep commit on their branch, which does not exist on
this base and would make `git blame --ignore-revs-file` error. Repointed
at `d3a02599`, the sweep here.

## Verification

The claim "formatting only" is checked twice rather than asserted:

- Every changed file is byte-identical to `gofmt(previous content)`. 0
of 66 deviate.
- With line comments and all whitespace stripped, 0 of 66 files differ,
so no code outside comments changed.

14 of the 66 also show doc-comment reflow. Since Go 1.19 `gofmt`
re-indents indented comment blocks to tabs and inserts a blank comment
line before them; the behavior matrix above `resolveHopWithContext` in
`cmd/ingestor/path_resolver.go` is a clear example. That is gofmt's own
output, not an edit, but it is worth naming because it makes the diff
look larger than "whitespace" suggests.

The gate was run locally exactly as the workflow runs it: `gofmt` clean,
and `go vet` clean in all 14 modules, including `cmd/ingestor` which is
what commit 2 fixes.

Suites: `cmd/server` ok (80.7s), `internal/packetpath` ok (2.3s),
`cmd/ingestor` passes except
`TestWriteStatsAtomic_SymlinkAtDestIsReplaced`, which fails identically
on bare master with "A required privilege is not held by the client"
(Windows symlink privilege on my host, not code).

## Sequencing

This should go last in the queue. The sweep touches 66 files, so merging
it before the remaining open Go PRs gives each of them a conflict about
nothing but formatting. After it lands the gate is active, and any PR
with drift fails CI until it runs `gofmt -w`.

Excluded from the sweep: the misnamed `Dockerfile.go`, which is a
Dockerfile that gofmt cannot parse (the workflow excludes it too), and
`docs/DEPLOYMENT.md`, which a case-insensitive filesystem surfaces as a
spurious modification against `docs/deployment.md` and is unrelated.

---------

Co-authored-by: SaarMesh-Bot <300107934+SaarMesh-Bot@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 18:52:03 +02:00

153 lines
4.6 KiB
Go

package main
// Issue #1009: chunked Load with early HTTP readiness.
//
// These tests gate three behaviors:
// (a) FirstChunkReady() unblocks BEFORE LoadChunked returns, so the
// HTTP listener can bind after the first chunk completes while
// remaining rows continue loading in the background.
// (b) loadStatusMiddleware stamps an X-CoreScope-Load-Status header
// with "loading" + progress while a load is in flight, flipping
// to "ready" once LoadComplete() reports true.
// (c) LoadChunked honors the configured chunkSize: the per-chunk
// progress callback fires once per chunk, so a 2500-row DB with
// chunkSize=1000 must yield 3 callbacks (1000 + 1000 + 500).
//
// Each subtest fails on an assertion (not a build error) when the
// production code is absent — that is the red-commit contract.
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
)
func openChunkedTestStore(t *testing.T, numTx int) *PacketStore {
t.Helper()
dir := t.TempDir()
dbPath := filepath.Join(dir, "chunked.db")
createTestDBAt(t, dbPath, numTx)
t.Cleanup(func() { os.RemoveAll(dir) })
db, err := OpenDB(dbPath)
if err != nil {
t.Fatalf("OpenDB: %v", err)
}
cfg := &PacketStoreConfig{}
return NewPacketStore(db, cfg)
}
// (a) FirstChunkReady fires before LoadChunked returns.
func TestLoadChunked_FirstChunkReadyBeforeComplete(t *testing.T) {
store := openChunkedTestStore(t, 2500)
defer store.db.conn.Close()
doneCh := make(chan error, 1)
go func() { doneCh <- store.LoadChunked(500) }()
select {
case <-store.FirstChunkReady():
// Good: first chunk signaled. Load may or may not have completed
// for tiny test DBs, but the gate must have fired without
// requiring the full load.
case err := <-doneCh:
// If load completed before we could observe the signal, the
// signal still must be closed.
if err != nil {
t.Fatalf("LoadChunked: %v", err)
}
select {
case <-store.FirstChunkReady():
default:
t.Fatal("FirstChunkReady channel must be closed after LoadChunked completes")
}
case <-time.After(10 * time.Second):
t.Fatal("FirstChunkReady did not fire within 10s — listener would never bind")
}
// Drain background completion.
select {
case err := <-doneCh:
if err != nil {
t.Fatalf("LoadChunked returned error: %v", err)
}
case <-time.After(30 * time.Second):
t.Fatal("LoadChunked never returned")
}
if !store.LoadComplete() {
t.Fatal("LoadComplete() must report true after LoadChunked returns")
}
}
// (b) Middleware stamps X-CoreScope-Load-Status correctly across the
//
// loading→ready transition.
func TestLoadStatusMiddleware_HeaderTransition(t *testing.T) {
store := openChunkedTestStore(t, 100)
defer store.db.conn.Close()
handler := loadStatusMiddleware(store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
// Pre-load: header must report "loading".
req := httptest.NewRequest("GET", "/api/healthz", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if got := w.Header().Get("X-CoreScope-Load-Status"); got == "" || got == "ready" {
t.Fatalf("expected loading status header before Load, got %q", got)
}
if err := store.LoadChunked(50); err != nil {
t.Fatalf("LoadChunked: %v", err)
}
// Post-load: header must report "ready".
req2 := httptest.NewRequest("GET", "/api/healthz", nil)
w2 := httptest.NewRecorder()
handler.ServeHTTP(w2, req2)
if got := w2.Header().Get("X-CoreScope-Load-Status"); got != "ready" {
t.Fatalf("expected X-CoreScope-Load-Status=ready after load, got %q", got)
}
}
// (c) LoadChunked honors the chunkSize argument — progress callback
//
// fires once per chunk.
func TestLoadChunked_ChunkSizeHonored(t *testing.T) {
store := openChunkedTestStore(t, 2500)
defer store.db.conn.Close()
var chunks []int
store.OnChunkLoaded(func(rowsThisChunk, totalRows int) {
chunks = append(chunks, rowsThisChunk)
})
if err := store.LoadChunked(1000); err != nil {
t.Fatalf("LoadChunked: %v", err)
}
if len(chunks) != 3 {
t.Fatalf("expected 3 chunks for 2500 rows @ chunkSize=1000, got %d (sizes=%v)", len(chunks), chunks)
}
if chunks[0] != 1000 || chunks[1] != 1000 || chunks[2] != 500 {
t.Fatalf("expected chunk sizes [1000,1000,500], got %v", chunks)
}
}
// (d) Config plumbing: DB.Load.ChunkSize threads through.
func TestConfig_DBLoadChunkSize(t *testing.T) {
c := &Config{}
if got := c.DBLoadChunkSize(); got != 10000 {
t.Fatalf("DBLoadChunkSize() default = %d, want 10000", got)
}
c.DB = &DBConfig{Load: &dbLoadConfig{ChunkSize: 2500}}
if got := c.DBLoadChunkSize(); got != 2500 {
t.Fatalf("DBLoadChunkSize() configured = %d, want 2500", got)
}
}