From dfedc9bc8a2b33895c15be68b9b008a70843ec33 Mon Sep 17 00:00:00 2001 From: n30nex Date: Fri, 9 Oct 2026 13:05:38 -0400 Subject: [PATCH 1/2] perf(ingestor): yield between committed retention batches (#2151) --- cmd/ingestor/maintenance.go | 12 ++ cmd/ingestor/prune_chunked_test.go | 6 + cmd/ingestor/retention_fanout_test.go | 181 ++++++++++++++++++++++ cmd/ingestor/retention_profile_test.go | 205 +++++++++++++++++++++++++ 4 files changed, 404 insertions(+) create mode 100644 cmd/ingestor/retention_fanout_test.go create mode 100644 cmd/ingestor/retention_profile_test.go diff --git a/cmd/ingestor/maintenance.go b/cmd/ingestor/maintenance.go index 6ee0fe77d..5722f2c27 100644 --- a/cmd/ingestor/maintenance.go +++ b/cmd/ingestor/maintenance.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "log" + "runtime" "time" "github.com/meshcore-analyzer/dbschema" @@ -67,6 +68,12 @@ const ( // returned alongside it — those rows are gone, so reporting 0 would be // wrong. func (s *Store) PruneOldPackets(days int) (int64, error) { + return s.pruneOldPackets(days, runtime.Gosched) +} + +// The local scheduling action lets tests exercise ingestion at the committed +// batch boundary without replacing a global scheduler or writer lock. +func (s *Store) pruneOldPackets(days int, betweenBatches func()) (int64, error) { if days <= 0 { return 0, nil } @@ -97,6 +104,11 @@ func (s *Store) PruneOldPackets(days int) (int64, error) { if batch < pruneBatchTransmissions { break } + // A serial ingest consumer needs CPU to finish handling one packet and + // submit its next write. Yield after the commit and writer-lock release, + // before competing for another batch. This does not bound dense fanout + // inside a single transaction. + betweenBatches() } if total > 0 { log.Printf("[prune] deleted %d transmissions older than %d days", total, days) diff --git a/cmd/ingestor/prune_chunked_test.go b/cmd/ingestor/prune_chunked_test.go index a3be3261a..82e288c9f 100644 --- a/cmd/ingestor/prune_chunked_test.go +++ b/cmd/ingestor/prune_chunked_test.go @@ -279,6 +279,12 @@ func TestPruneAgedTransmissionIDsUsesFirstSeenIndex(t *testing.T) { if strings.Contains(plan, "SCAN transmissions") { t.Errorf("%s: plan scans transmissions, so the empty terminating batch walks the whole table under writerMu: %s", name, plan) } + if strings.Contains(plan, "SCAN observations") { + t.Errorf("%s: child work must seek by transmission or row ID, not scan observations: %s", name, plan) + } + if q != pruneAgedTransmissionIDs && !strings.Contains(plan, "transmission_id=?") { + t.Errorf("%s: child lookup does not use a transmission-key index: %s", name, plan) + } if strings.Contains(plan, "TEMP B-TREE") { t.Errorf("%s: plan sorts in a temp b-tree instead of walking the index in order: %s", name, plan) } diff --git a/cmd/ingestor/retention_fanout_test.go b/cmd/ingestor/retention_fanout_test.go new file mode 100644 index 000000000..de9ffda01 --- /dev/null +++ b/cmd/ingestor/retention_fanout_test.go @@ -0,0 +1,181 @@ +package main + +import ( + "context" + "fmt" + "strings" + "testing" + "time" +) + +// The action represents eligible ingestion at a cooperative scheduling point. +// It verifies actual native commits, the released writer mutex/pool, and a real +// foreground goroutine. The deadline only detects a leaked lock; no sleep or +// wall-clock speed threshold determines correctness. +func TestPruneYieldsAfterCommittedFullBatches(t *testing.T) { + s := openPruneStore(t, "yield.db") + const aged = pruneBatchTransmissions*2 + 7 + seedRetentionFanout(t, s, aged, aged) + yields := 0 + removed, err := s.pruneOldPackets(5, func() { + yields++ + if !writerMu.TryLock() { + t.Error("scheduling action still holds writerMu") + return + } + writerMu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + conn, err := s.db.Conn(ctx) + if err != nil { + t.Error("scheduling action still occupies the single DB connection", err) + return + } + var remaining int + err = conn.QueryRowContext(ctx, `SELECT count(*) FROM transmissions WHERE first_seen < '2021-01-01'`).Scan(&remaining) + conn.Close() + if err != nil || remaining != aged-yields*pruneBatchTransmissions { + t.Error("scheduling action preceded a committed full batch", remaining, err) + return + } + done := make(chan error, 1) + sequence := yields + go func() { + _, err := s.InsertTransmission(&PacketData{ + RawHex: "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976", + Hash: fmt.Sprint("scheduled-live-", sequence), Timestamp: time.Now().UTC().Format(time.RFC3339), + RouteType: 2, PayloadType: 2, PathJSON: "[]", DecodedJSON: "{}", + }) + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Error(err) + } + case <-ctx.Done(): + t.Error("foreground ingestion could not finish between committed batches") + } + }) + if err != nil || removed != aged { + t.Fatalf("removed=%d err=%v", removed, err) + } + if yields != 2 { + t.Errorf("scheduling action called %d times; want once after each of two full committed batches", yields) + } + if countRows(t, s, "transmissions") != 2 || countRows(t, s, "observations") != 2 { + t.Error("foreground rows were not ingested and preserved between batches") + } +} + +func TestPruneDoesNotYieldForDisabledEmptyOrFailedWork(t *testing.T) { + for _, days := range []int{0, -1, 5} { + t.Run(fmt.Sprint(days), func(t *testing.T) { + s := openPruneStore(t, "noop.db") + yields := 0 + n, err := s.pruneOldPackets(days, func() { yields++ }) + if err != nil || n != 0 || yields != 0 { + t.Fatalf("n=%d yields=%d err=%v", n, yields, err) + } + }) + } + t.Run("failed batch", func(t *testing.T) { + s := openPruneStore(t, "failed.db") + seedRetentionFanout(t, s, 1, 1) + if _, err := s.db.Exec(`CREATE TRIGGER fail_prune BEFORE DELETE ON observations BEGIN SELECT RAISE(ABORT,'blocked prune'); END`); err != nil { + t.Fatal(err) + } + yields := 0 + n, err := s.pruneOldPackets(5, func() { yields++ }) + if err == nil || n != 0 || yields != 0 { + t.Fatalf("n=%d yields=%d err=%v", n, yields, err) + } + if countRows(t, s, "transmissions") != 1 || countRows(t, s, "observations") != 1 { + t.Fatal("failed batch changed rows") + } + }) +} + +func TestPrunePreservesLateFreshArrivalsBetweenBatches(t *testing.T) { + s := openPruneStore(t, "late-arrival.db") + seedRetentionFanout(t, s, 251, 251) + yields := 0 + n, err := s.pruneOldPackets(5, func() { + yields++ + // Hash 1 was removed by the previous batch. Its new reception must get + // a fresh transmission identity and remain outside this fixed cutoff. + if _, err := s.InsertTransmission(&PacketData{Hash: "retention-1", RawHex: "00", Timestamp: time.Now().UTC().Format(time.RFC3339), PathJSON: "[]", DecodedJSON: "{}"}); err != nil { + t.Error(err) + } + }) + if err != nil || n != 251 || yields != 1 { + t.Fatalf("n=%d yields=%d err=%v", n, yields, err) + } + var id int64 + if err := s.db.QueryRow(`SELECT id FROM transmissions WHERE hash='retention-1'`).Scan(&id); err != nil || id <= 251 { + t.Fatal("late reception reused an expired identity or was lost", id, err) + } + var linked int + if err := s.db.QueryRow(`SELECT count(*) FROM observations WHERE transmission_id=?`, id).Scan(&linked); err != nil || linked != 1 { + t.Fatal("late observation lost/orphaned", linked, err) + } +} + +func TestPruneSkewedChildrenAndEmptyParentsPreservesFreshEvidence(t *testing.T) { + s := openPruneStore(t, "skewed.db") + seedRetentionFanout(t, s, 1, 2501) + tx, err := s.db.Begin() + if err != nil { + t.Fatal(err) + } + for id := 2; id <= 601; id++ { + if _, err := tx.Exec(`INSERT INTO transmissions(id,raw_hex,hash,first_seen) VALUES(?,'00',?,'2020-01-01T00:00:00Z')`, id, fmt.Sprint("empty-", id)); err != nil { + tx.Rollback() + t.Fatal(err) + } + } + if err := tx.Commit(); err != nil { + t.Fatal(err) + } + for _, stmt := range []string{ + `INSERT INTO transmissions(id,raw_hex,hash,first_seen) VALUES(701,'00','keep-fresh','2099-01-01T00:00:00Z')`, + `INSERT INTO observations(transmission_id,timestamp) VALUES(701,1),(701,2)`, + `INSERT INTO advert_route_evidence(tx_id,bit) VALUES(1,1),(1,2),(601,1),(701,1),(701,2)`, + } { + if _, err := s.db.Exec(stmt); err != nil { + t.Fatal(err) + } + } + removed, err := s.PruneOldPackets(5) + if err != nil || removed != 601 { + t.Fatalf("removed=%d err=%v", removed, err) + } + if countRows(t, s, "transmissions") != 1 || countRows(t, s, "observations") != 2 || countRows(t, s, "advert_route_evidence") != 2 { + t.Fatal("skewed retention lost fresh rows or left expired rows/evidence") + } + var evidence int + if err := s.db.QueryRow(`SELECT count(*) FROM advert_route_evidence WHERE tx_id=701`).Scan(&evidence); err != nil || evidence != 2 { + t.Fatal("fresh route evidence changed", err) + } +} + +func TestPruneFailureRollsBackOnlyCurrentBatch(t *testing.T) { + s := openPruneStore(t, "rollback.db") + seedRetentionFanout(t, s, 500, 1000) + if _, err := s.db.Exec(`CREATE TRIGGER fail_prune BEFORE DELETE ON observations WHEN OLD.transmission_id=251 BEGIN SELECT RAISE(ABORT,'retention test failure'); END`); err != nil { + t.Fatal(err) + } + removed, err := s.PruneOldPackets(5) + if removed != 250 || err == nil || !strings.Contains(err.Error(), "retention test failure") { + t.Fatalf("removed=%d err=%v", removed, err) + } + if countRows(t, s, "transmissions") != 250 || countRows(t, s, "observations") != 500 { + t.Fatal("failed batch was only partly rolled back or earlier progress lost") + } + if _, err := s.db.Exec(`DROP TRIGGER fail_prune`); err != nil { + t.Fatal(err) + } + if removed, err := s.PruneOldPackets(5); err != nil || removed != 250 { + t.Fatalf("retry removed=%d err=%v", removed, err) + } +} diff --git a/cmd/ingestor/retention_profile_test.go b/cmd/ingestor/retention_profile_test.go new file mode 100644 index 000000000..cabd16b81 --- /dev/null +++ b/cmd/ingestor/retention_profile_test.go @@ -0,0 +1,205 @@ +package main + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "path/filepath" + "sort" + "testing" + "time" + + "github.com/mattn/go-sqlite3" +) + +func seedRetentionFanout(tb testing.TB, s *Store, transmissions, observations int) { + tb.Helper() + s.WaitForAsyncMigrations() + tx, err := s.db.Begin() + if err != nil { + tb.Fatal(err) + } + defer tx.Rollback() + parents, err := tx.Prepare(`INSERT INTO transmissions(id,raw_hex,hash,first_seen,last_seen) VALUES(?,'00',?,'2020-01-01T00:00:00Z',1)`) + if err != nil { + tb.Fatal(err) + } + defer parents.Close() + children, err := tx.Prepare(`INSERT INTO observations(transmission_id,observer_idx,path_json,timestamp) VALUES(?,?,'[]',1)`) + if err != nil { + tb.Fatal(err) + } + defer children.Close() + for i := 1; i <= transmissions; i++ { + if _, err := parents.Exec(i, fmt.Sprint("retention-", i)); err != nil { + tb.Fatal(err) + } + } + for i := 0; i < observations; i++ { + if _, err := children.Exec(i%transmissions+1, i/transmissions); err != nil { + tb.Fatal(err) + } + } + if err := tx.Commit(); err != nil { + tb.Fatal(err) + } +} + +// A small open-loop schedule exposes queueing behind the real serial ingest +// caller. It is diagnostic, not a machine-speed pass/fail threshold. +func BenchmarkRetentionConcurrentIngest(b *testing.B) { + for _, fixture := range []struct { + name string + transmissions, observations int + }{{"typical16", 16000, 256000}, {"dense256", 500, 128000}, {"singleHot", 1, 64000}} { + b.Run(fixture.name, func(b *testing.B) { + for i := 0; i < b.N; i++ { + b.StopTimer() + s, err := OpenStore(filepath.Join(b.TempDir(), "retention-live.db")) + if err != nil { + b.Fatal(err) + } + seedRetentionFanout(b, s, fixture.transmissions, fixture.observations) + ResetWriterStatsForTest() + before := s.db.Stats() + const arrivals = 250 + waits := make([]float64, 0, arrivals) + completions := make([]float64, 0, arrivals) + done := make(chan error, 1) + var pruneElapsed time.Duration + b.StartTimer() + start := time.Now() + for n := 0; n < arrivals; n++ { + scheduled := start.Add(time.Duration(n) * 20 * time.Millisecond) + if delay := time.Until(scheduled); delay > 0 { + timer := time.NewTimer(delay) + <-timer.C + } + waits = append(waits, float64(time.Since(scheduled))/float64(time.Millisecond)) + if _, err := s.InsertTransmission(&PacketData{Hash: fmt.Sprintf("live-%d", n), RawHex: "00", Timestamp: time.Now().UTC().Format(time.RFC3339), PathJSON: "[]", DecodedJSON: "{}"}); err != nil { + b.Fatal(err) + } + completions = append(completions, float64(time.Since(scheduled))/float64(time.Millisecond)) + if n == 9 { + go func() { + began := time.Now() + deleted, err := s.PruneOldPackets(5) + pruneElapsed = time.Since(began) + if err == nil && deleted != int64(fixture.transmissions) { + err = fmt.Errorf("removed %d, want %d", deleted, fixture.transmissions) + } + done <- err + }() + } + } + if err := <-done; err != nil { + b.Fatal(err) + } + b.StopTimer() + after := s.db.Stats() + var parents, observations int + if err := s.db.QueryRow(`SELECT count(*) FROM transmissions`).Scan(&parents); err != nil { + b.Fatal(err) + } + if err := s.db.QueryRow(`SELECT count(*) FROM observations`).Scan(&observations); err != nil { + b.Fatal(err) + } + if parents != arrivals || observations != arrivals || s.Stats.WriteErrors.Load() != 0 { + b.Fatalf("live row loss/errors: tx=%d obs=%d errors=%d", parents, observations, s.Stats.WriteErrors.Load()) + } + sort.Float64s(waits) + sort.Float64s(completions) + result := struct { + RetentionMS, QueueP50MS, QueueP95MS, QueueMaxMS, CompletionP95MS float64 + PoolWaitCount int64 + PoolWaitMS float64 + Writers map[string]WriterStatsSnapshot + }{float64(pruneElapsed) / float64(time.Millisecond), waits[len(waits)/2], waits[(len(waits)*95-1)/100], waits[len(waits)-1], completions[(len(completions)*95-1)/100], after.WaitCount - before.WaitCount, float64(after.WaitDuration-before.WaitDuration) / float64(time.Millisecond), s.WriterStatsSnapshot()} + data, _ := json.Marshal(result) + b.Log(string(data)) + s.Close() + } + }) + } +} + +func retentionHooks(tb testing.TB, db *sql.DB, update func(int, string, string, int64), commit func() int, rollback func()) { + tb.Helper() + conn, err := db.Conn(context.Background()) + if err != nil { + tb.Fatal(err) + } + defer conn.Close() + if err := conn.Raw(func(driver any) error { + sqlite := driver.(*sqlite3.SQLiteConn) + sqlite.RegisterUpdateHook(update) + sqlite.RegisterCommitHook(commit) + sqlite.RegisterRollbackHook(rollback) + return nil + }); err != nil { + tb.Fatal(err) + } +} + +// Run explicitly with -run '^$' -bench BenchmarkRetentionFanout -benchtime=1x. +// Fixture creation stays outside the timer; all SQLite durability defaults stay +// at the production WriterDSN settings. No PostgreSQL server is involved. +func BenchmarkRetentionFanout(b *testing.B) { + for _, fixture := range []struct { + name string + transmissions, observations int + }{ + {"typical16", 16000, 256000}, + {"dense256", 500, 128000}, + {"singleHot", 1, 64000}, + } { + b.Run(fixture.name, func(b *testing.B) { + for n := 0; n < b.N; n++ { + b.StopTimer() + s, err := OpenStore(filepath.Join(b.TempDir(), "retention.db")) + if err != nil { + b.Fatal(err) + } + seedRetentionFanout(b, s, fixture.transmissions, fixture.observations) + var inBatch, maxBatch, deleted, batches int + retentionHooks(b, s.db, func(op int, _, table string, _ int64) { + if op == sqlite3.SQLITE_DELETE && table == "observations" { + inBatch++ + deleted++ + } + }, func() int { + if inBatch > maxBatch { + maxBatch = inBatch + } + inBatch = 0 + batches++ + return 0 + }, func() { inBatch = 0 }) + ResetWriterStatsForTest() + poolBefore := s.db.Stats() + b.StartTimer() + started := time.Now() + removed, err := s.PruneOldPackets(5) + elapsed := time.Since(started) + b.StopTimer() + poolAfter := s.db.Stats() + if err != nil || removed != int64(fixture.transmissions) || deleted != fixture.observations { + b.Fatalf("removed=%d deleted=%d err=%v", removed, deleted, err) + } + result := struct { + Fixture string `json:"fixture"` + ElapsedMS float64 `json:"elapsed_ms"` + MaxObservationDeletes, Commits int + PoolWaitCount int64 + PoolWaitMS float64 + Writer WriterStatsSnapshot + }{fixture.name, float64(elapsed) / float64(time.Millisecond), maxBatch, batches, poolAfter.WaitCount - poolBefore.WaitCount, float64(poolAfter.WaitDuration-poolBefore.WaitDuration) / float64(time.Millisecond), s.WriterStatsSnapshot()["prune_packets"]} + encoded, _ := json.Marshal(result) + b.Log(string(encoded)) + retentionHooks(b, s.db, nil, nil, nil) + s.Close() + } + }) + } +} From 307432370f8a7d9d623223beac1ba15fdd2d6546 Mon Sep 17 00:00:00 2001 From: n30nex Date: Tue, 20 Oct 2026 09:23:58 -0400 Subject: [PATCH 2/2] docs(perf): link historical retention profile from fork --- .../sqlite-retention-b5-2026-10-09.md | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 docs/performance/sqlite-retention-b5-2026-10-09.md diff --git a/docs/performance/sqlite-retention-b5-2026-10-09.md b/docs/performance/sqlite-retention-b5-2026-10-09.md new file mode 100644 index 000000000..8f9654f23 --- /dev/null +++ b/docs/performance/sqlite-retention-b5-2026-10-09.md @@ -0,0 +1,67 @@ +# SQLite retention scheduling: five-pair B comparison + +This report describes the October 9 comparison at the revisions pinned below. Its figures do not measure the rebased PR against current master. + +The yield between committed retention batches reduced queue-inclusive ingestion tails in this workload, with a service-time tradeoff. Additional-observation p95 was **5.0% lower** and p99 **8.1% lower** by median paired ratio; its service-time p99 was **29.1% higher**. Cleanup was **0.5% longer**. This supports a narrow scheduling benefit, not a general database or application speed claim. + +[Successful run 37975105215](https://github.com/Kpa-clawbot/CoreScope/actions/runs/37975105215), attempt 1; [primary artifact 11641718171](https://github.com/Kpa-clawbot/CoreScope/actions/runs/37975105215/artifacts/11641718171). + +## Scope and correctness + +- Baseline `9dbc287579a237ffa744dd0c91fa7227d09763ac`; candidate `b70a9f6bc4e78ab9f13f21e6bf063b48e986f109`; harness `1c5eb9d04436225460a530275764357c56b28461`. This is historical upstream SQLite before later #2147/#2155 changes. It does **not** measure the optional-backend candidate. +- Five alternating pairs on one Linux x86-64 Actions host; Go 1.27.2, CGO SQLite 3.53.4. Both legs used the same 3-CPU/6-GiB cgroup limit, 2-GiB packet-store setting, 3-GiB server and 512-MiB ingestor Go memory limits, WAL and synchronous=FULL. +- B contains 128,000 transmissions and 2,048,000 observations across 8 days. Full and hot-start background completion loaded the entire retained 7 days: 112,000 transmissions/1,792,000 observations, with zero startup evictions in every leg. +- Each leg ran 60s warmup plus 180s measured, at 50 ingest events/s and 20 HTTP requests/s. Retention started 135s into the measured window. All 120,000 replay events and 48,000 HTTP requests completed across 10 legs, with zero errors or drops. All 6,000 full-stream new-transmission sentinels per leg arrived exactly once; 4,500 per leg belong to the measured window. +- All 18 exported table count/digest records match within each pair before and after replay; post-replay parity excludes only the harness-declared volatile time columns. Each cleanup removed exactly 16,000 transmissions/256,000 observations; final durable totals were 118,000/1,802,200. The subsequent empty pass deleted nothing. +- Production hashes were independently recomputed from both Git archives; the complete harness hash and all 930 summary rows were independently reconciled. Replay sequence/class/hash identities, shared-clock schedules, SQL sample coverage and response digests also match. Raw SQLite databases are not in the public bundle: their byte-level immutability is a controller attestation, while the exported logical parity was independently checked. + +The failed run 37965218190, smoke artifacts and diagnostic runs are excluded. + +## Latency: separate queuing from work + +Times below are milliseconds. Absolute columns are medians of the five per-run quantiles; C/B is the median of five **within-pair** ratios, so it need not equal the ratio of those absolute medians. Quantiles use nearest rank. No events were pooled across runs; p99 is withheld below 1,000 samples per class/leg. + +| Metric | Samples/leg | Baseline median | Candidate median | Median C/B | Pair ratio range | +|---|---:|---:|---:|---:|---:| +| additional scheduled→complete p95 | 2,700 | 6,620.419 | 6,252.805 | 0.9503 (-5.0%) | 0.918–0.985 | +| additional scheduled→complete p99 | 2,700 | 13,037.450 | 12,025.582 | 0.9191 (-8.1%) | 0.903–0.936 | +| new scheduled→complete p95 | 4,500 | 6,717.353 | 6,233.006 | 0.9392 (-6.1%) | 0.880–0.983 | +| new scheduled→complete p99 | 4,500 | 12,934.441 | 12,177.854 | 0.9412 (-5.9%) | 0.922–0.961 | +| duplicate scheduled→complete p95 | 1,350 | 6,542.523 | 6,174.586 | 0.9420 (-5.8%) | 0.917–0.985 | +| duplicate scheduled→complete p99 | 1,350 | 13,088.091 | 12,159.148 | 0.9399 (-6.0%) | 0.901–0.960 | +| late scheduled→complete p95 | 450 | 6,658.226 | 6,135.665 | 0.9359 (-6.4%) | 0.897–0.959 | +| additional service p99 | 2,700 | 5.349 | 6.302 | 1.2914 (+29.1%) | 1.064–2.155 | +| new service p99 | 4,500 | 6.945 | 8.027 | 1.1582 (+15.8%) | 0.916–2.012 | +| duplicate service p99 | 1,350 | 3.651 | 5.182 | 1.3904 (+39.0%) | 1.235–1.639 | + +All five pairs improved scheduled-to-complete p95 for all four ingest classes, and p99 for the three classes with enough samples. Almost all of the additional-observation tail is waiting before the serial consumer starts work: its queue p95 ratio is 0.9503. Additional service p95 nevertheless rose 8.9%, and its service p99 worsened in all five pairs; duplicate service p99 also worsened in all five. Late has 450 measured samples/leg, so no p99 claim is made. + +Large stalls remain: additional-observation scheduled-to-complete maxima span 14.21–14.82s at baseline and 13.23–13.79s with the candidate. Both streams finished their scheduled work before the measured window ended; there was no post-window ingest or HTTP drain. The fixed offered load and zero drops do not establish higher throughput capacity. + +WebSocket first-receipt lag, measured from ingest completion rather than scheduling, improved at p95 (C/B 0.7230; 2,179.6→1,553.5ms absolute medians). Its p99 ratio was 0.9492, with a 0.842–1.142 pair range. These are signed differences; this run had no negative samples or duplicate receipts. + +HTTP was mixed. Scheduled-to-complete p95 ratios ranged from 0.9259 for `nodes_2000` to 1.0569 for `nodes_50`; `paths` was 1.0262 and `analytics_channels` 1.0202. `nodes_2000` varied 0.850–1.842 by pair and `healthz` 0.036–3.778, so neither supports a stable broad API claim. Every HTTP class had only 45–252 samples/leg: no HTTP p99 is reported. The 135 successful history-detail requests and 45 expected post-retention 404s per leg are separate classes, not failures. + +## Cleanup and resource cost + +| Measure | Baseline leg median | Candidate leg median | Median paired C/B | +|---|---:|---:|---:| +| Concurrent cleanup | 15.945s | 16.000s | 1.0049 (+0.5%) | +| Empty cleanup probe | 0.284ms | 0.297ms | 1.0221 (+2.2%) | +| Sampled cgroup memory peak | 3.972GiB | 3.998GiB | 1.0065 (+0.6%) | +| Sampled aggregate PSS peak | 2.869GiB | 2.886GiB | 1.0058 (+0.6%) | +| Sampled DB+WAL storage peak | 1.071GiB | 1.079GiB | 1.0004 (+0.0%) | +| Observed average CPU cores | 0.298 | 0.297 | 0.9873 | +| Device 8:0 write rate | 13.26MiB/s | 13.28MiB/s | 1.0010 | + +Cleanup was longer in four pairs, with C/B 0.993–1.021. The scheduling change does not bound a dense single transaction. Full-stream lock instrumentation (including warmup) recorded median maximum ingest lock waits of 596.9→463.5ms, but still hundreds of milliseconds. + +Resource gauges and counter deltas use only samples inside the 180s measured interval. Counter spans cover 178.43–179.47s because sampling is about 1 Hz; rates normalize by their actual span. Raw write-byte deltas rose 0.64% by paired median, while normalized write rate was nearly flat (+0.10%). Only device 8:0 was present; read-byte deltas were zero in this warm-cache run. Do not add duplicate layers when comparing other hosts. + +Measured sampled cgroup memory never exceeded 4.061GiB. The separately reset, FD-local **whole-leg** kernel peak reached 4.227GiB; it includes startup/warmup and is not a measured-window peak. All `memory.events` max/oom/oom_kill counters remained zero. Minimum observed disk free space was 71.89GiB. Cgroup memory includes file cache; aggregate PSS and RSS have different meanings. These observations establish neither a memory reduction nor a capacity guarantee. + +## Interpretation limits and reproducibility + +The manifest records identical production-server binary hashes between revisions. Startup and isolated SQL controls precede concurrent retention; their differences are not attributed to the ingestor scheduling change. Full-ready startup C/B was 0.9998; isolated channel-message SQL p95 was 1.0529. This comparison measures one fixed corpus/seed on one warm-cache host, five pairs and a short replay—not OS-cold startup, arbitrary fanout, long soak, saturation capacity, later upstream cache/locking changes, or PostgreSQL. + +Query plans were captured after replay/retention and cannot establish the initial workload plan. The [machine-readable summary](https://github.com/n30nex/CoreScope/blob/323b18d4221e83c9827b4722145e2a9d5b9d9599/docs/performance/sqlite-retention-b5-2026-10-09.json) includes every class/timing, per-pair absolute values and ratios, resource windows, settings, source hashes and raw-file hashes. Reproduce from the linked primary artifact using the pinned harness definitions: group measured events per class/leg, compute nearest-rank quantiles, then median the five candidate/baseline ratios. Resource deltas use each leg’s shared replay origin + 60s through origin + 240s.