From ff9209344eec40c4ba3327e03182657845a8e0f0 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:01:37 -0800 Subject: [PATCH 1/3] fix(mcp): pgbot://baselines reads [] on an empty store, not null (#157) store.List builds its result with `var out []ListItem` and returns it nil when the snapshots table is empty; the resource marshalled that directly, so a fresh install answered resources/read with the JSON document `null` while the resource's contract (and a populated store) is an array. Normalise nil to an empty slice before marshalling. The CLI path (`pgbot baselines list`) already handled the empty case. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ cmd/pgbot/mcp.go | 4 ++++ cmd/pgbot/mcp_tools_test.go | 27 +++++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 428a0d7..178926f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,10 @@ separately by `model.SchemaVersion` (currently 1.5.0). Other platforms get "PgBot Monitor currently supports macOS only"; every other command is unchanged. The `--json` contract is unchanged. +### Fixed +- The `pgbot://baselines` MCP resource now reads as an empty JSON array (`[]`) + on a store with no snapshots, instead of JSON `null` (#157). + ## [0.10.0] - 2026-11-16 ### Added diff --git a/cmd/pgbot/mcp.go b/cmd/pgbot/mcp.go index 195de17..0fbec19 100644 --- a/cmd/pgbot/mcp.go +++ b/cmd/pgbot/mcp.go @@ -302,6 +302,10 @@ func pgbotResources() []mcp.Resource { if err != nil { return "", err } + if items == nil { + // An empty store is an empty array, not JSON null (#157). + items = []store.ListItem{} + } b, err := json.MarshalIndent(items, "", " ") if err != nil { return "", err diff --git a/cmd/pgbot/mcp_tools_test.go b/cmd/pgbot/mcp_tools_test.go index 58cdba6..8588146 100644 --- a/cmd/pgbot/mcp_tools_test.go +++ b/cmd/pgbot/mcp_tools_test.go @@ -129,3 +129,30 @@ func TestWhyTool(t *testing.T) { t.Error("the tool must carry its caveat note for the agent") } } + +// pgbot://baselines on a fresh store must be an empty JSON array, not null — +// the same shape as a populated store, so clients can iterate it (#157). +func TestBaselinesResource_emptyStoreIsArray(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + res := pgbotResources() + if len(res) != 1 || res[0].URI != "pgbot://baselines" { + t.Fatalf("unexpected resources: %+v", res) + } + out, err := res[0].Read(context.Background()) + if err != nil { + t.Fatal(err) + } + if strings.TrimSpace(out) != "[]" { + t.Fatalf("empty store should read as [], got %q", out) + } + + seedWhyFixture(t) + out, err = res[0].Read(context.Background()) + if err != nil { + t.Fatal(err) + } + var items []map[string]any + if err := json.Unmarshal([]byte(out), &items); err != nil || len(items) == 0 { + t.Fatalf("populated store should read as a non-empty array (err=%v): %s", err, out) + } +} From 7346b8988bce0d1483f52be7c5c8e1b2fb0d6fb9 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:04:15 -0800 Subject: [PATCH 2/3] perf(why): match table references without compiling a regexp per call (#142) referencesTable built `(?i)\b\b` with regexp.MustCompile on every call, and referencedTables calls it samples x tables for every shifted query, so one analysis compiled thousands of identical regexps (172 allocs per 8-table pass in the new benchmark). Replace it with a scan that implements the same semantics directly: Go's \b is an ASCII [0-9A-Za-z_] boundary and (?i) is Unicode simple case folding, so a rune-wise SimpleFold comparison plus a neighbouring-byte boundary check is exactly equivalent. Behaviour is deliberately unchanged (including that \b is ASCII-only, so non-ASCII names keep their current matching); the old regexp is kept in the test as an oracle, with table-driven cases and FuzzReferencesTable pinning equivalence (fuzzed ~620k inputs locally). TestReferencesTable_doesNotAllocate fails on the old code. BenchmarkReferencesTable (8 tables, M1 Pro): 42.6us/172 allocs -> 5.4us/0. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + internal/why/analyze.go | 82 +++++++++++++++++++- internal/why/references_table_test.go | 104 ++++++++++++++++++++++++++ 3 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 internal/why/references_table_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 178926f..f20e515 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,9 @@ separately by `model.SchemaVersion` (currently 1.5.0). ### Fixed - The `pgbot://baselines` MCP resource now reads as an empty JSON array (`[]`) on a store with no snapshots, instead of JSON `null` (#157). +- `pgbot why` no longer compiles a regexp for every query × table pair while + linking queries to tables; the matcher is an allocation-free scan with + identical results (~8× faster in the new benchmark) (#142). ## [0.10.0] - 2026-11-16 diff --git a/internal/why/analyze.go b/internal/why/analyze.go index 4a28138..7f87fb6 100644 --- a/internal/why/analyze.go +++ b/internal/why/analyze.go @@ -2,10 +2,11 @@ package why import ( "fmt" - "regexp" "sort" "strings" "time" + "unicode" + "unicode/utf8" "github.com/pgrundev/pgbot/internal/model" ) @@ -328,9 +329,84 @@ func referencedTables(samples []Sample, queryText string) []string { // referencesTable reports whether the normalized query text mentions the table // name as a whole identifier (word-bounded, case-insensitive). +// +// It is exactly `(?i)\b\b` (Go regexp semantics: \b is an +// ASCII [0-9A-Za-z_] boundary, (?i) is Unicode simple case folding) without +// compiling a regexp per call — it runs samples × tables × shifted queries +// (#142). FuzzReferencesTable pins the equivalence. func referencesTable(queryText, table string) bool { - re := regexp.MustCompile(`(?i)\b` + regexp.QuoteMeta(table) + `\b`) - return re.MatchString(queryText) + if table == "" { + // \b\b: any word boundary, i.e. any ASCII word byte in the text. + for i := 0; i < len(queryText); i++ { + if isASCIIWordByte(queryText[i]) { + return true + } + } + return false + } + for i := 0; i < len(queryText); { + if n, ok := foldPrefix(queryText[i:], table); ok && + atWordBoundary(queryText, i) && atWordBoundary(queryText, i+n) { + return true + } + if queryText[i] < utf8.RuneSelf { + i++ + } else { + _, w := utf8.DecodeRuneInString(queryText[i:]) + i += w + } + } + return false +} + +// foldPrefix reports whether s starts with t under Unicode simple case +// folding, returning the byte length of the matched prefix of s. +func foldPrefix(s, t string) (int, bool) { + i := 0 + for _, tr := range t { + if i >= len(s) { + return 0, false + } + sr, w := rune(s[i]), 1 + if sr >= utf8.RuneSelf { + sr, w = utf8.DecodeRuneInString(s[i:]) + } + if !equalFoldRune(sr, tr) { + return 0, false + } + i += w + } + return i, true +} + +// equalFoldRune is the regexp (?i) rune test: r and t are in the same +// unicode.SimpleFold orbit. +func equalFoldRune(r, t rune) bool { + if r == t { + return true + } + if r < utf8.RuneSelf && t < utf8.RuneSelf { + return r|0x20 == t|0x20 && r|0x20 >= 'a' && r|0x20 <= 'z' + } + for f := unicode.SimpleFold(t); f != t; f = unicode.SimpleFold(f) { + if f == r { + return true + } + } + return false +} + +// atWordBoundary is regexp's \b at byte offset i: exactly one side is an +// ASCII word character. Word characters are single bytes, so looking at the +// neighbouring bytes is enough (UTF-8 lead/continuation bytes are >= 0x80). +func atWordBoundary(s string, i int) bool { + before := i > 0 && isASCIIWordByte(s[i-1]) + after := i < len(s) && isASCIIWordByte(s[i]) + return before != after +} + +func isASCIIWordByte(c byte) bool { + return c == '_' || c >= '0' && c <= '9' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' } // tableGrowthPct is first-to-last relative growth of the table's total bytes. diff --git a/internal/why/references_table_test.go b/internal/why/references_table_test.go new file mode 100644 index 0000000..e93013b --- /dev/null +++ b/internal/why/references_table_test.go @@ -0,0 +1,104 @@ +package why + +import ( + "regexp" + "testing" + "unicode/utf8" +) + +// referencesTableRegexp is the original implementation, kept as the oracle: +// referencesTable must agree with it on every input (#142). +func referencesTableRegexp(queryText, table string) bool { + re := regexp.MustCompile(`(?i)\b` + regexp.QuoteMeta(table) + `\b`) + return re.MatchString(queryText) +} + +var referencesTableCases = []struct { + text, table string +}{ + {"SELECT * FROM orders WHERE id = $1", "orders"}, + {"select * from ORDERS where id = $1", "orders"}, + {"SELECT * FROM public.orders o", "orders"}, + {"SELECT * FROM order_items", "orders"}, + {"SELECT * FROM orders_archive", "orders"}, + {"SELECT * FROM preorders", "orders"}, + {"SELECT * FROM \"orders\"", "orders"}, + {"SELECT * FROM orders2", "orders"}, + {"orders", "orders"}, + {"", "orders"}, + {"SELECT 1", ""}, + {"", ""}, + {"!!!", ""}, + {"SELECT $1orders", "orders"}, + {"SELECT orders$1", "orders"}, + {"SELECT a.b FROM a.b", "a.b"}, + {"SELECT * FROM axb", "a.b"}, + {"SELECT * FROM ünïcode", "ünïcode"}, + {"SELECT * FROM xünïcode", "ünïcode"}, + {"SELECT * FROM ÜNÏCODE", "ünïcode"}, + {"SELECT * FROM Keys", "keys"}, // Kelvin sign folds to k + {"SELECT * FROM keyſ", "keys"}, // long s folds to s + {"SELECT * FROM \xffkeys", "keys"}, + {"SELECT * FROM t\xff", "t"}, + {"SELECT * FROM \xff", "�"}, + {"SELECT * FROM ordersorders", "orders"}, + {"SELECT * FROM ordersx orders", "orders"}, +} + +func TestReferencesTable_agreesWithRegexp(t *testing.T) { + for _, c := range referencesTableCases { + if got, want := referencesTable(c.text, c.table), referencesTableRegexp(c.text, c.table); got != want { + t.Errorf("referencesTable(%q, %q) = %v, regexp says %v", c.text, c.table, got, want) + } + } +} + +// referencedTables loops samples × tables for every shifted query, so the +// per-call matcher must not compile or allocate anything (#142). +func TestReferencesTable_doesNotAllocate(t *testing.T) { + allocs := testing.AllocsPerRun(100, func() { + for _, tbl := range benchTables { + referencesTable(benchQuery, tbl) + } + }) + if allocs != 0 { + t.Errorf("referencesTable allocated %.0f times per run, want 0", allocs) + } +} + +func FuzzReferencesTable(f *testing.F) { + for _, c := range referencesTableCases { + f.Add(c.text, c.table) + } + f.Fuzz(func(t *testing.T, text, table string) { + if !utf8.ValidString(table) { + t.Skip() // the regexp oracle panics on invalid UTF-8 patterns + } + if got, want := referencesTable(text, table), referencesTableRegexp(text, table); got != want { + t.Errorf("referencesTable(%q, %q) = %v, regexp says %v", text, table, got, want) + } + }) +} + +const benchQuery = `SELECT o.id, o.total, c.email FROM public.orders o JOIN customers c ON c.id = o.customer_id ` + + `LEFT JOIN order_items oi ON oi.order_id = o.id WHERE o.created_at > $1 AND c.region = $2 ORDER BY o.created_at DESC LIMIT $3` + +var benchTables = []string{"orders", "customers", "order_items", "payments", "shipments", "audit_log", "users", "sessions"} + +func BenchmarkReferencesTable(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, tbl := range benchTables { + referencesTable(benchQuery, tbl) + } + } +} + +func BenchmarkReferencesTableRegexp(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + for _, tbl := range benchTables { + referencesTableRegexp(benchQuery, tbl) + } + } +} From e9fd7d81f4f3f8cadc47227671b0219b35671920 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:07:45 -0800 Subject: [PATCH 3/3] fix(fk_unindexed): count an `fk_col IS NOT NULL` partial index as covering (#129) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit unindexed_fks.sql rejected every partial index (`indpred IS NULL`). That is right in general — a partial index does not contain every child row, and the RI check must find all of them — but too strict for the one predicate the RI lookup itself guarantees: the trigger queries `WHERE $1 OPERATOR(=) fk_col [AND ...]`, the operator is strict, so the clause implies `fk_col IS NOT NULL` and the planner uses an index with that predicate even in the generic plan (verified with auto_explain on PG 18: "Index Scan using c_parent" for the RI query during DELETE on the parent). Accept a partial index whose predicate, as deparsed by pg_get_expr, is a conjunction of ` IS NOT NULL` terms (any subset of the FK's columns, quoted names via quote_ident). Anything else — soft-delete predicates, IS NOT NULL mixed with other conditions, OR, other spellings — stays "not covering", so the change can only drop findings that were false positives. Still a pure catalog read. Integration test (PGBOT_TEST_SUPERUSER_DSN) proves the planner premise and the covered / not-covered cases; it fails on the old SQL. Ran green on PG 14 and PG 18. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + docs/findings/fk_unindexed.md | 8 +- .../fk_partial_index_integration_test.go | 107 ++++++++++++++++++ internal/collect/sql/unindexed_fks.sql | 20 +++- 4 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 internal/collect/fk_partial_index_integration_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f20e515..05e82a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,10 @@ separately by `model.SchemaVersion` (currently 1.5.0). - `pgbot why` no longer compiles a regexp for every query × table pair while linking queries to tables; the matcher is an allocation-free scan with identical results (~8× faster in the new benchmark) (#142). +- `fk_unindexed` now counts a partial index on the FK columns as covering when + its predicate is ` IS NOT NULL` (or an `AND` of those), which the + RI trigger's `WHERE $1 = fk_col` lookup implies. Partial indexes on any other + predicate (e.g. `deleted_at IS NULL`) are still reported (#129). ## [0.10.0] - 2026-11-16 diff --git a/docs/findings/fk_unindexed.md b/docs/findings/fk_unindexed.md index 67c3bb3..e0ab19d 100644 --- a/docs/findings/fk_unindexed.md +++ b/docs/findings/fk_unindexed.md @@ -93,8 +93,12 @@ the one relation you've reasoned about. actually `DELETE` or key-`UPDATE` parent rows. If you never do, the index only helps joins — real, but a lower priority than the RI-scan risk implies. - The coverage check is **structural leading-prefix** matching. An index in a - different column order, or a partial index that happens to serve the FK, won't be - recognized as covering it. + different column order won't be recognized as covering it. A partial index counts + only when its predicate is ` IS NOT NULL` (or an `AND` of those): the + RI lookup `WHERE $1 = fk_col` implies that predicate, so the planner can use it. + A partial index on anything else (e.g. `WHERE deleted_at IS NULL`) does not cover + the FK — the RI check must still find the rows it excludes — and other + equivalent spellings of `IS NOT NULL` are conservatively not recognized. - It doesn't measure lock waits caused by this — those only appear (in `blocking_chains`) at the moment a parent delete actually stalls behind the scan. diff --git a/internal/collect/fk_partial_index_integration_test.go b/internal/collect/fk_partial_index_integration_test.go new file mode 100644 index 0000000..0f28bb9 --- /dev/null +++ b/internal/collect/fk_partial_index_integration_test.go @@ -0,0 +1,107 @@ +package collect_test + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/pgrundev/pgbot/internal/collect" + "github.com/pgrundev/pgbot/internal/conn" + "github.com/pgrundev/pggo" +) + +// Issue #129: a partial index whose predicate is ` IS NOT NULL` covers +// the FK — the RI trigger's lookup (`WHERE $1 = fk_col`, strict operator) +// implies the predicate, so even the generic plan uses it. A partial index on +// any other predicate (e.g. soft-delete) does not: the RI check must still see +// the rows it excludes. Proves the planner fact on the server, then runs the +// real collector as the read-only role. +func TestIntegration_fkPartialIndexCoverage(t *testing.T) { + su := os.Getenv("PGBOT_TEST_SUPERUSER_DSN") + if su == "" { + t.Skip("set PGBOT_TEST_SUPERUSER_DSN (a superuser DSN) to run the FK partial-index fixture") + } + ro := dsn(t) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + admin, err := pggo.Connect(ctx, su) + if err != nil { + t.Fatalf("admin connect: %v", err) + } + t.Cleanup(func() { admin.Close() }) + + cleanup := func() { _, _ = admin.Exec(context.Background(), `DROP SCHEMA IF EXISTS pgbot_it_fk CASCADE`) } + cleanup() + t.Cleanup(cleanup) + if _, err := admin.SimpleQuery(ctx, ` + CREATE SCHEMA pgbot_it_fk; + GRANT USAGE ON SCHEMA pgbot_it_fk TO PUBLIC; + CREATE TABLE pgbot_it_fk.p (id bigint PRIMARY KEY); + CREATE TABLE pgbot_it_fk.p2 (x bigint, y bigint, PRIMARY KEY (x, y)); + INSERT INTO pgbot_it_fk.p SELECT g FROM generate_series(1, 100) g; + -- covered: predicate is exactly the FK column IS NOT NULL + CREATE TABLE pgbot_it_fk.c_notnull (id bigint PRIMARY KEY, parent_id bigint REFERENCES pgbot_it_fk.p(id)); + CREATE INDEX c_notnull_parent ON pgbot_it_fk.c_notnull (parent_id) WHERE parent_id IS NOT NULL; + -- covered: quoted FK column name, multi-column conjunction + CREATE TABLE pgbot_it_fk.c_multi (id bigint PRIMARY KEY, "Ref A" bigint, b bigint, + FOREIGN KEY ("Ref A", b) REFERENCES pgbot_it_fk.p2(x, y)); + CREATE INDEX ON pgbot_it_fk.c_multi ("Ref A", b) WHERE "Ref A" IS NOT NULL AND b IS NOT NULL; + -- NOT covered: soft-delete predicate hides rows the RI check must see + CREATE TABLE pgbot_it_fk.c_softdel (id bigint PRIMARY KEY, parent_id bigint REFERENCES pgbot_it_fk.p(id), deleted_at timestamptz); + CREATE INDEX ON pgbot_it_fk.c_softdel (parent_id) WHERE deleted_at IS NULL; + -- NOT covered: IS NOT NULL mixed with another condition + CREATE TABLE pgbot_it_fk.c_mixed (id bigint PRIMARY KEY, parent_id bigint REFERENCES pgbot_it_fk.p(id)); + CREATE INDEX ON pgbot_it_fk.c_mixed (parent_id) WHERE parent_id IS NOT NULL AND id > 10; + INSERT INTO pgbot_it_fk.c_notnull SELECT g, CASE WHEN g % 3 = 0 THEN NULL ELSE g % 100 + 1 END FROM generate_series(1, 2000) g; + ANALYZE pgbot_it_fk.c_notnull`); err != nil { + t.Fatalf("fixture: %v", err) + } + + // The premise, confirmed against the server: the RI check's query shape uses + // the partial index even as a generic (parameter-agnostic) plan. + if _, err := admin.SimpleQuery(ctx, ` + SET plan_cache_mode = force_generic_plan; + SET enable_seqscan = off; + PREPARE pgbot_it_ri(bigint) AS + SELECT 1 FROM ONLY pgbot_it_fk.c_notnull x WHERE $1 OPERATOR(pg_catalog.=) parent_id FOR KEY SHARE OF x`); err != nil { + t.Fatalf("prepare RI-shaped query: %v", err) + } + var plan string + if err := admin.QueryRow(ctx, `EXPLAIN (FORMAT JSON) EXECUTE pgbot_it_ri(5)`).Scan(&plan); err != nil { + t.Fatalf("explain: %v", err) + } + if !strings.Contains(plan, "c_notnull_parent") { + t.Fatalf("premise: the RI lookup should use the IS NOT NULL partial index, plan: %s", plan) + } + + target, err := conn.Connect(ctx, ro) + if err != nil { + t.Fatalf("connect: %v", err) + } + defer target.Close() + c, err := collect.Run(ctx, target, collect.Options{Interval: 200 * time.Millisecond, ASHHz: 0}) + if err != nil { + t.Fatalf("run: %v", err) + } + if c.Indexes == nil { + t.Fatal("indexes section missing") + } + got := map[string]bool{} + for _, fk := range c.Indexes.UnindexedFKs { + if fk.Schema == "pgbot_it_fk" { + got[fk.Table] = true + } + } + for table, wantUnindexed := range map[string]bool{ + "c_notnull": false, + "c_multi": false, + "c_softdel": true, + "c_mixed": true, + } { + if got[table] != wantUnindexed { + t.Errorf("%s: reported unindexed = %v, want %v (all: %+v)", table, got[table], wantUnindexed, c.Indexes.UnindexedFKs) + } + } +} diff --git a/internal/collect/sql/unindexed_fks.sql b/internal/collect/sql/unindexed_fks.sql index 4d00033..4ef3161 100644 --- a/internal/collect/sql/unindexed_fks.sql +++ b/internal/collect/sql/unindexed_fks.sql @@ -17,8 +17,26 @@ WHERE con.contype = 'f' AND NOT EXISTS ( SELECT 1 FROM pg_index i WHERE i.indrelid = con.conrelid - AND i.indpred IS NULL -- a partial index can't be relied on for FK checks AND (string_to_array(i.indkey::text, ' ')::int2[])[1:cardinality(con.conkey)] = con.conkey + -- A partial index only covers the FK when the RI lookup provably satisfies + -- its predicate. The RI query is `WHERE $1 = fk_col [AND ...]` with strict + -- operators, which implies `fk_col IS NOT NULL`, so the planner uses an + -- index whose predicate is (a conjunction of) ` IS NOT NULL` + -- (#129). Any other predicate (e.g. `deleted_at IS NULL`) leaves rows the + -- RI check must still scan for. Matched on pg_get_expr's deparse, which + -- renders these as `(c IS NOT NULL)` / `((a IS NOT NULL) AND (b IS NOT NULL))`; + -- anything unrecognised stays "not covering". + AND (i.indpred IS NULL OR NOT EXISTS ( + SELECT 1 + FROM regexp_split_to_table( + substr(pg_get_expr(i.indpred, i.indrelid), 2, + length(pg_get_expr(i.indpred, i.indrelid)) - 2), + '\) AND \(') AS conj(term) + WHERE btrim(conj.term, '()') NOT IN ( + SELECT quote_ident(a.attname) || ' IS NOT NULL' + FROM unnest(con.conkey) k(attnum) + JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum) + )) ) ORDER BY child_bytes DESC LIMIT 50;