Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ separately by `model.SchemaVersion` (currently 1.6.0).
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).
- `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 `<fk column> 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).
- `pgbot sql explain` no longer treats a `$1` inside a dollar-quoted literal
(`$$ … $$`, `$tag$ … $tag$`) as a parameter placeholder, so the generic-plan
"parameter values unknown" caveat is no longer shown for such queries (#141).
Expand Down
4 changes: 4 additions & 0 deletions cmd/pgbot/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions cmd/pgbot/mcp_tools_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
8 changes: 6 additions & 2 deletions docs/findings/fk_unindexed.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<fk column> 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.

Expand Down
107 changes: 107 additions & 0 deletions internal/collect/fk_partial_index_integration_test.go
Original file line number Diff line number Diff line change
@@ -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 `<fk col> 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)
}
}
}
20 changes: 19 additions & 1 deletion internal/collect/sql/unindexed_fks.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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) `<fk column> 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;
82 changes: 79 additions & 3 deletions internal/why/analyze.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package why

import (
"fmt"
"regexp"
"sort"
"strings"
"time"
"unicode"
"unicode/utf8"

"github.com/pgrundev/pgbot/internal/model"
)
Expand Down Expand Up @@ -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<QuoteMeta(table)>\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.
Expand Down
Loading
Loading