Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6928 perf(issues): index scalar property contains behind a bigram prefilter (#7878)
Bohan Jiangf01eb5a06c3c
diff --git a/server/cmd/migrate/README.md b/server/cmd/migrate/README.mdindex 9a175a1d29..12ae3209a3 100644--- a/server/cmd/migrate/README.md+++ b/server/cmd/migrate/README.md@@ -37,3 +37,49 @@ has the exact migration 036 shape: a non-unique, non-partial GIN index on`LOWER(content)` using the `pg_bigm`-owned `gin_bigm_ops` operator class. Onlythen can the fallback be dropped with `DROP INDEX CONCURRENTLY` during amaintenance window.++## Build the issue properties bigram index after installing pg_bigm++Migration 446 builds `idx_issue_properties_bigm`, the index behind the prefilter+that scalar `contains` property filtering puts in front of its per-key ILIKE.+The runner only executes it where the `gin_bigm_ops` operator class is+installed; everywhere else the version is recorded with its SQL skipped, and the+filter keeps working without index acceleration.++That record is permanent, so a database that gains `pg_bigm` later never builds+the index on its own. Check first:++```sql+SELECT indexrelid::regclass AS index_name, indisvalid, indisready, indislive+FROM pg_index+WHERE indexrelid = to_regclass('idx_issue_properties_bigm');+```++If the index is missing, create it out of band. Run each statement separately+and outside a transaction so the concurrent build is valid:++```sql+CREATE EXTENSION IF NOT EXISTS pg_bigm;+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_properties_bigm;+CREATE INDEX CONCURRENTLY idx_issue_properties_bigm+ ON issue USING gin (LOWER(properties::text) gin_bigm_ops);+ANALYZE issue;+```++The `ANALYZE` is not optional and not a formality. Building an expression index+does not collect statistics for its expression, and until they exist the+planner has nothing to judge the index by: it falls back to a pattern-length+heuristic that estimates a single-character needle at 5% of the table and+leaves `contains` on a sequential scan, with the index built, valid and unused.+Migration 447 does this after 446; an out-of-band build has to do it itself.++Keep the expression exactly as written: the predicate is+`LOWER(properties::text) LIKE LOWER(...)`, and an `ILIKE`-shaped or+non-lowered index would never be used (pg_bigm 1.2 on RDS has no ILIKE index+scan — the constraint migration 036 hit).++Confirm the statistics landed:++```sql+SELECT count(*) FROM pg_statistic WHERE starelid = 'idx_issue_properties_bigm'::regclass;+```diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 00f90513fb..09f1dd4ea7 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -61,6 +61,27 @@ var commentContentBigramIndex = usableIndexRequirement{Extension: "pg_bigm",}+// extensionOperatorClass names an operator class a migration writes literally+// into a CREATE INDEX, together with the extension that must own it. A+// migration cannot both build concurrently and swallow a missing extension in a+// DO ... EXCEPTION block, so the ones that need an optional opclass are gated on+// this instead.+type extensionOperatorClass struct {+ AccessMethod string+ OperatorClass string+ Extension string+}++// issuePropertiesBigramOperatorClass gates migration 446. pg_bigm ships with+// neither core Postgres nor the pgvector image CI and self-hosted deployments+// run, so the index it builds is best-effort; the contains prefilter it+// accelerates stays correct without it.+var issuePropertiesBigramOperatorClass = extensionOperatorClass{+ AccessMethod: "gin",+ OperatorClass: "gin_bigm_ops",+ Extension: "pg_bigm",+}+// preMigrationHooks wires migration version → hook. The version key is// the file basename without the `.up.sql` suffix, matching what// `migrations.ExtractVersion` returns.@@ -276,6 +297,7 @@ var concurrentIndexCleanups = map[string]string{"440_github_pr_head_sha_index": "idx_github_pull_request_head_sha","443_issue_project_status_index": "idx_issue_project_status","445_comment_delegated_failure_unsettled_index": "idx_comment_delegated_failure_unsettled",+ "446_issue_properties_bigm_index": "idx_issue_properties_bigm",}// concurrentDownIndexCleanups covers every migration whose down direction@@ -379,6 +401,11 @@ var upMigrationConditions = map[string]migrationCondition{// fallback only after proving the preferred index has the exact usable shape;// pg_bigm-less self-hosted databases keep trgm and record 371 as a no-op."371_comment_content_search_index_strategy": whenIndexUsable(commentContentBigramIndex),+ // The properties prefilter index is an optimization, not a correctness+ // requirement: build it where pg_bigm exists and record a no-op everywhere+ // else, rather than failing the run (and with it backend startup) on every+ // database without the extension.+ "446_issue_properties_bigm_index": whenOperatorClassAvailable(issuePropertiesBigramOperatorClass),}func hooksForDirection(direction string) map[string]preMigrationHook {@@ -442,6 +469,42 @@ func whenIndexNotUsable(requirement usableIndexRequirement) migrationCondition {}}+// whenOperatorClassAvailable lets a migration's SQL run only where the operator+// class it names is installed, owned by the expected extension, and visible on+// the search_path the migration itself will resolve the unqualified name+// against — the condition runs on the same pinned connection as the SQL.+//+// Checking the extension alone would be weaker: an opclass in a schema outside+// the search_path still fails the CREATE INDEX, which would abort the run.+func whenOperatorClassAvailable(opclass extensionOperatorClass) migrationCondition {+ return func(ctx context.Context, conn *pgxpool.Conn) (bool, string, error) {+ var available bool+ if err := conn.QueryRow(ctx, `+ SELECT EXISTS (+ SELECT 1+ FROM pg_opclass opc+ JOIN pg_am am ON am.oid = opc.opcmethod+ JOIN pg_depend dep+ ON dep.classid = 'pg_opclass'::regclass+ AND dep.objid = opc.oid+ AND dep.refclassid = 'pg_extension'::regclass+ AND dep.deptype = 'e'+ JOIN pg_extension ext ON ext.oid = dep.refobjid+ WHERE opc.opcname = $1+ AND am.amname = $2+ AND ext.extname = $3+ AND pg_opclass_is_visible(opc.oid)+ )+ `, opclass.OperatorClass, opclass.AccessMethod, opclass.Extension).Scan(&available); err != nil {+ return false, "", fmt.Errorf("inspect operator class %q: %w", opclass.OperatorClass, err)+ }+ if !available {+ return false, fmt.Sprintf("operator class %s (%s) is not installed", opclass.OperatorClass, opclass.Extension), nil+ }+ return true, "", nil+ }+}+// indexIsUsable fails closed: every property needed by the search query must// match before a fallback index may be skipped or removed. In particular, the// preferred relation must be a live, ready, valid, non-partial GIN expressiondiff --git a/server/cmd/migrate/migrate_issue_properties_bigm_index_test.go b/server/cmd/migrate/migrate_issue_properties_bigm_index_test.gonew file mode 100644index 0000000000..8e897b0749--- /dev/null+++ b/server/cmd/migrate/migrate_issue_properties_bigm_index_test.go@@ -0,0 +1,344 @@+package main++import (+ "context"+ "encoding/json"+ "fmt"+ "math/rand/v2"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"+)++// issuePropertiesBigramMigrations is the pair that has to move together: 446+// builds the expression index, 447 generates the statistics the planner needs+// before it will consider it. Applying 446 alone leaves the index built, valid+// and ignored.+var issuePropertiesBigramMigrations = []string{+ "446_issue_properties_bigm_index",+ "447_issue_properties_bigm_index_statistics",+}++// TestIssuePropertiesBigramIndexBuildsOnlyWherePGBigmExists runs migrations 446+// and 447's real SQL through the runner. The gate has to hold in both+// directions: the index appears where pg_bigm is installed, and where it is+// not — core Postgres, and the pgvector image CI and self-hosted deployments+// run — the version records with its SQL skipped rather than failing the run. A+// failure there would take backend startup with it, for an index that is only+// an optimization: the contains prefilter it serves stays correct+// unaccelerated.+//+// 447 is not gated, so its statistics refresh must land in both environments.+func TestIssuePropertiesBigramIndexBuildsOnlyWherePGBigmExists(t *testing.T) {+ adminPool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()++ pgBigmUsable := installExtensionIfAvailable(t, ctx, adminPool, "pg_bigm")++ schema := createScratchSchema(t, ctx, adminPool, "migrate_issue_properties_bigm_")+ pool := openTestPoolWithSearchPath(t, schema+", public")+ seedIssuePropertiesFixture(t, ctx, pool, 500)++ // ANALYZE only records statistics for a table it has seen rows in, so the+ // post-migration assertions below are only meaningful against this+ // pre-state: nothing has analyzed the fixture yet.+ if got := statisticsRowCount(t, ctx, pool, schema, "issue"); got != 0 {+ t.Fatalf("fixture already has %d statistics rows before migrating", got)+ }++ migrationsTable := schema + ".schema_migrations"+ if err := runMigrations(ctx, pool, runOptions{+ Direction: "up",+ Files: realMigrationFiles(t, issuePropertiesBigramMigrations, "up"),+ SchemaMigrationsTable: migrationsTable,+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection("up"),+ Conditions: conditionsForDirection("up"),+ }); err != nil {+ t.Fatalf("apply properties bigram index: %v", err)+ }++ // Recorded either way: a skipped migration still advances the ledger, or+ // every later version would be blocked on a database without pg_bigm.+ for _, version := range issuePropertiesBigramMigrations {+ assertMigrationVersionRecorded(t, ctx, pool, schema, version, true)+ }+ assertIndexExists(t, pool, schema, "idx_issue_properties_bigm", pgBigmUsable)+ if pgBigmUsable {+ assertIndexValidity(t, pool, schema, "idx_issue_properties_bigm", true)+ }++ // 447 ran unconditionally, so the table's own column statistics exist in+ // every environment.+ if got := statisticsRowCount(t, ctx, pool, schema, "issue"); got == 0 {+ t.Fatal("447 did not analyze the table: no statistics rows")+ }+ // Where the index exists, the statistics that matter are the ones for its+ // expression — a separate pg_statistic entry keyed by the index relation,+ // and the only thing that lets the planner cost a contains prefilter.+ if pgBigmUsable {+ if got := statisticsRowCount(t, ctx, pool, schema, "idx_issue_properties_bigm"); got == 0 {+ t.Fatal("no statistics for the LOWER(properties::text) expression: the planner cannot cost the index")+ }+ }++ // The rollback drops unconditionally: it must be a no-op, not an error,+ // where the up direction never built anything. 447's rollback is a+ // comment-only no-op and must still execute cleanly.+ if err := runMigrations(ctx, pool, runOptions{+ Direction: "down",+ Files: realMigrationFiles(t, reversed(issuePropertiesBigramMigrations), "down"),+ SchemaMigrationsTable: migrationsTable,+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection("down"),+ }); err != nil {+ t.Fatalf("roll back properties bigram index: %v", err)+ }+ for _, version := range issuePropertiesBigramMigrations {+ assertMigrationVersionRecorded(t, ctx, pool, schema, version, false)+ }+ assertIndexExists(t, pool, schema, "idx_issue_properties_bigm", false)+}++// TestIssuePropertiesBigramIndexNeedsAnalyzeForItsExpression is the regression+// 447 exists for, and it can only be written against the real extension.+//+// Building an expression index does not collect statistics for its expression.+// Until they exist the planner falls back to a pattern-length heuristic — a+// single-character LIKE is estimated at a few percent of the table regardless+// of what the data holds — so it cannot tell a needle matching 40 rows from one+// matching 40,000. On a large table that estimate loses to a sequential scan+// and the index it just built goes unused, which is the exact query class+// MUL-6928 added it for and the shape a CJK contains filter has. The failure is+// invisible by every other signal: the index is present, valid and ready.+//+// The assertion is on the estimate rather than the chosen plan because the+// estimate is the thing 447 repairs. Which plan that estimate wins is a+// function of table size: at fixture scale a wrong estimate still picks the+// index, and it takes a production-sized table for the same error to flip to a+// sequential scan.+func TestIssuePropertiesBigramIndexNeedsAnalyzeForItsExpression(t *testing.T) {+ adminPool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)+ defer cancel()++ if !installExtensionIfAvailable(t, ctx, adminPool, "pg_bigm") {+ t.Skip("Postgres does not provide pg_bigm; the planner behaviour under test is extension-specific")+ }++ schema := createScratchSchema(t, ctx, adminPool, "migrate_issue_properties_analyze_")+ pool := openTestPoolWithSearchPath(t, schema+", public")+ seedIssuePropertiesFixture(t, ctx, pool, 40000)++ // The prefilter clause on its own: the qual whose selectivity the missing+ // statistics get wrong.+ const prefilterQuery = `SELECT i.id FROM issue i WHERE LOWER(i.properties::text) LIKE LOWER('%鬻%')`+ var actual int+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM issue i WHERE LOWER(i.properties::text) LIKE LOWER('%鬻%')`).Scan(&actual); err != nil {+ t.Fatalf("count rare needle matches: %v", err)+ }+ if actual == 0 {+ t.Fatal("fixture seeded no rows for the rare needle")+ }++ migrationsTable := schema + ".schema_migrations"+ applyMigration := func(t *testing.T, version string) {+ t.Helper()+ if err := runMigrations(ctx, pool, runOptions{+ Direction: "up",+ Files: realMigrationFiles(t, []string{version}, "up"),+ SchemaMigrationsTable: migrationsTable,+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection("up"),+ Conditions: conditionsForDirection("up"),+ }); err != nil {+ t.Fatalf("apply %s: %v", version, err)+ }+ }++ applyMigration(t, "446_issue_properties_bigm_index")+ assertIndexValidity(t, pool, schema, "idx_issue_properties_bigm", true)+ withoutStatistics := estimatedRows(t, ctx, pool, prefilterQuery)+ if withoutStatistics < actual*10 {+ t.Fatalf("expected the index build alone to leave a badly wrong estimate, got %d for %d actual rows; "++ "if Postgres now collects expression statistics at build time, 447 and this test can go",+ withoutStatistics, actual)+ }++ applyMigration(t, "447_issue_properties_bigm_index_statistics")+ if got := statisticsRowCount(t, ctx, pool, schema, "idx_issue_properties_bigm"); got == 0 {+ t.Fatal("447 generated no statistics for the LOWER(properties::text) expression")+ }+ withStatistics := estimatedRows(t, ctx, pool, prefilterQuery)+ if withStatistics*10 > withoutStatistics {+ t.Fatalf("447 did not improve the selectivity estimate: %d before, %d after, %d actual",+ withoutStatistics, withStatistics, actual)+ }+}++// seedIssuePropertiesFixture builds a scratch `issue` table shaped like the+// real one for the properties filter: a jsonb bag whose text value is drawn+// from a small shared vocabulary, plus a rare character on a few rows so a+// selective needle exists.+func seedIssuePropertiesFixture(t *testing.T, ctx context.Context, pool *pgxpool.Pool, rows int) {+ t.Helper()+ if _, err := pool.Exec(ctx, `CREATE TABLE issue (+ id BIGSERIAL PRIMARY KEY,+ properties JSONB NOT NULL DEFAULT '{}'::jsonb+ )`); err != nil {+ t.Fatalf("create issue fixture: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ INSERT INTO issue (properties)+ SELECT jsonb_build_object(+ 'text', (ARRAY['登录问题','支付延迟','看板导出','权限迁移'])[1 + (n % 4)]+ || ' ' || (ARRAY['login','payment','dashboard','export'])[1 + (n % 4)]+ || ' REF' || lpad(n::text, 7, '0')+ || CASE WHEN n % 1000 = 0 THEN ' 鬻' ELSE '' END,+ 'number', (n % 500)+ )+ FROM generate_series(1, $1) AS n+ `, rows); err != nil {+ t.Fatalf("seed issue fixture: %v", err)+ }+}++// statisticsRowCount reports how many pg_statistic rows exist for a relation.+// Expression-index statistics are keyed by the index relation, not the table,+// which is why the caller passes the relation it cares about.+func statisticsRowCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, schema, relation string) int {+ t.Helper()+ var count int+ if err := pool.QueryRow(ctx, `+ SELECT count(*)+ FROM pg_statistic s+ JOIN pg_class c ON c.oid = s.starelid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1 AND c.relname = $2+ `, schema, relation).Scan(&count); err != nil {+ t.Fatalf("read statistics for %s.%s: %v", schema, relation, err)+ }+ return count+}++// estimatedRows returns the planner's estimated row count for query — the+// top-level node's estimate, which for a bare filtering SELECT is how many rows+// it thinks the qual will keep.+func estimatedRows(t *testing.T, ctx context.Context, pool *pgxpool.Pool, query string) int {+ t.Helper()+ var raw []byte+ if err := pool.QueryRow(ctx, "EXPLAIN (FORMAT JSON) "+query).Scan(&raw); err != nil {+ t.Fatalf("explain: %v", err)+ }+ var plans []struct {+ Plan struct {+ Rows int `json:"Plan Rows"`+ } `json:"Plan"`+ }+ if err := json.Unmarshal(raw, &plans); err != nil {+ t.Fatalf("decode plan %s: %v", raw, err)+ }+ if len(plans) != 1 {+ t.Fatalf("expected one plan, got %d", len(plans))+ }+ return plans[0].Plan.Rows+}++func reversed(versions []string) []string {+ out := make([]string, len(versions))+ for i, v := range versions {+ out[len(versions)-1-i] = v+ }+ return out+}++// TestOperatorClassAvailabilityFailsClosed checks the gate itself against real+// catalog rows. Every environment has pg_trgm (migration 137), so it stands in+// for "installed"; a condition that answered false for it would silently skip+// every gated migration forever, and one that answered true for an absent+// opclass would abort the run it exists to protect.+func TestOperatorClassAvailabilityFailsClosed(t *testing.T) {+ adminPool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()++ if _, err := adminPool.Exec(ctx, "CREATE EXTENSION IF NOT EXISTS pg_trgm"); err != nil {+ t.Fatalf("install pg_trgm test dependency: %v", err)+ }+ pgBigmUsable := installExtensionIfAvailable(t, ctx, adminPool, "pg_bigm")++ conn, err := adminPool.Acquire(ctx)+ if err != nil {+ t.Fatalf("acquire connection: %v", err)+ }+ defer conn.Release()++ for _, tc := range []struct {+ name string+ opclass extensionOperatorClass+ want bool+ }{+ {"installed", extensionOperatorClass{"gin", "gin_trgm_ops", "pg_trgm"}, true},+ {"wrong owning extension", extensionOperatorClass{"gin", "gin_trgm_ops", "pg_bigm"}, false},+ {"wrong access method", extensionOperatorClass{"btree", "gin_trgm_ops", "pg_trgm"}, false},+ {"unknown opclass", extensionOperatorClass{"gin", "gin_nonexistent_ops", "pg_trgm"}, false},+ {"migration 446 gate", issuePropertiesBigramOperatorClass, pgBigmUsable},+ } {+ t.Run(tc.name, func(t *testing.T) {+ apply, reason, err := whenOperatorClassAvailable(tc.opclass)(ctx, conn)+ if err != nil {+ t.Fatalf("evaluate condition: %v", err)+ }+ if apply != tc.want {+ t.Fatalf("apply=%v (%s), want %v", apply, reason, tc.want)+ }+ if !apply && reason == "" {+ t.Fatal("a skipped migration must report why")+ }+ })+ }+}++// installExtensionIfAvailable installs name when the server ships it and+// reports whether it is usable afterwards, so a test can assert the real+// behaviour of both environments instead of skipping on one of them.+func installExtensionIfAvailable(t *testing.T, ctx context.Context, pool *pgxpool.Pool, name string) bool {+ t.Helper()+ var available bool+ if err := pool.QueryRow(ctx, `+ SELECT EXISTS (SELECT 1 FROM pg_available_extensions WHERE name = $1)+ `, name).Scan(&available); err != nil {+ t.Fatalf("inspect %s availability: %v", name, err)+ }+ if !available {+ t.Logf("%s is not provided by this Postgres; asserting the skipped path", name)+ return false+ }+ if _, err := pool.Exec(ctx, "CREATE EXTENSION IF NOT EXISTS "+pgx.Identifier{name}.Sanitize()); err != nil {+ t.Fatalf("install %s test dependency: %v", name, err)+ }+ return true+}++// createScratchSchema gives a migration test its own namespace so the real+// migrations can run against fixture tables without touching the shared+// database the rest of the suite uses.+func createScratchSchema(t *testing.T, ctx context.Context, pool *pgxpool.Pool, prefix string) string {+ t.Helper()+ schema := fmt.Sprintf("%s%d_%d", prefix, time.Now().UnixNano(), rand.Uint32())+ schemaIdent := pgx.Identifier{schema}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+schemaIdent); err != nil {+ t.Fatalf("create schema: %v", err)+ }+ t.Cleanup(func() {+ cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ if _, err := pool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {+ t.Logf("drop schema %s: %v", schema, err)+ }+ })+ return schema+}diff --git a/server/internal/handler/property.go b/server/internal/handler/property.goindex 07c5370cb4..4607213d4c 100644--- a/server/internal/handler/property.go+++ b/server/internal/handler/property.go@@ -1111,6 +1111,11 @@ type propertyOperatorPattern struct {Op string `json:"__op__"`Def string `json:"def"`Value string `json:"value"`+ // Prefilter repeats Value for the `contains` needles worth pre-screening+ // against LOWER(properties::text) (see prefilterableContainsNeedle). It is+ // absent — never empty — for the rest, so the static unroll can test for+ // the key.+ Prefilter string `json:"prefilter,omitempty"`}var propertyFilterOps = map[string]string{@@ -1130,6 +1135,29 @@ func escapeLikePattern(s string) string {return replacer.Replace(s)}+// prefilterableContainsNeedle reports whether a raw `contains` needle may be+// pre-screened against LOWER(properties::text), the expression+// idx_issue_properties_bigm indexes (migration 446). A needle that cannot falls+// back to today's per-key-only filtering: slower on a large workspace, never+// wrong.+//+// The one disqualifier is JSON escaping. Postgres writes jsonb strings through+// escape_json, which escapes `"`, `\` and every character below U+0020; a+// needle containing one of those has no literal occurrence in properties::text,+// so pre-screening on it would drop rows the per-key ILIKE does match.+//+// Everything else matches literally and is prefiltered, however short. CJK and+// other non-ASCII text is passed through by escape_json in every server+// encoding, and pg_bigm indexes 1- and 2-character keywords — the capability it+// exists for over pg_trgm, and the length at which a CJK needle is already a+// real word. Length is deliberately not a condition here: excluding short+// needles would exclude exactly the searches this index was chosen to serve.+func prefilterableContainsNeedle(needle string) bool {+ return !strings.ContainsFunc(needle, func(r rune) bool {+ return r == '"' || r == '\\' || r < 0x20+ })+}+// validatePropertyFilterOperator checks one operator member and returns the// compiled pattern. The value rules mirror the legacy string rules: non-empty,// bounded, and only comparable shapes (a float for numeric ops, a real@@ -1148,6 +1176,9 @@ func validatePropertyFilterOperator(definitionID string, op propertyFilterOperatreturn propertyOperatorPattern{}, fmt.Errorf("properties filter value must be %d characters or fewer", maxPropertyTextValueLen)}pattern.Value = escapeLikePattern(op.Value)+ if prefilterableContainsNeedle(op.Value) {+ pattern.Prefilter = pattern.Value+ }case "gt", "gte", "lt", "lte":num, err := strconv.ParseFloat(op.Value, 64)if err != nil || math.IsNaN(num) || math.IsInf(num, 0) {@@ -1322,7 +1353,7 @@ func parseOperatorPattern(alt json.RawMessage) (propertyOperatorPattern, bool) {if !hasOp || !hasDef {return propertyOperatorPattern{}, false}- return propertyOperatorPattern{Op: op, Def: def, Value: marker["value"]}, true+ return propertyOperatorPattern{Op: op, Def: def, Value: marker["value"], Prefilter: marker["prefilter"]}, true}// operatorPatternPredicate renders one operator alternative as SQL. Ops were@@ -1335,8 +1366,23 @@ func operatorPatternPredicate(pattern propertyOperatorPattern, addArg func(any)// Value is ILIKE-escaped at parse time. Restrict substring matching to// stored strings: ->> also serializes numbers, booleans, and arrays, while// the client matcher intentionally treats contains as a text/url operator.- return fmt.Sprintf("(jsonb_typeof(i.properties -> %s) = 'string' AND (i.properties ->> %s) ILIKE '%%' || %s || '%%')",+ match := fmt.Sprintf("(jsonb_typeof(i.properties -> %s) = 'string' AND (i.properties ->> %s) ILIKE '%%' || %s || '%%')",defArg, defArg, addArg(pattern.Value))+ if pattern.Prefilter == "" {+ return match+ }+ // Redundant prefilter over the whole object's text form, which+ // idx_issue_properties_bigm indexes (migration 446). The per-key check+ // above still decides the result — this one only narrows the candidate+ // set from "every issue in the workspace" to what the bigram index+ // returns, and by construction (prefilterableContainsNeedle) never+ // drops a row the per-key check would keep.+ //+ // LOWER(...) LIKE LOWER(...) rather than a second ILIKE: pg_bigm 1.2 has+ // no ILIKE index scan (migration 036), and lowering both sides in SQL is+ // exactly how ILIKE folds case, so the two cannot disagree.+ return fmt.Sprintf("(LOWER(i.properties::text) LIKE LOWER('%%' || %s || '%%') AND %s)",+ addArg(pattern.Prefilter), match)case "gt", "gte", "lt", "lte":// Bind the canonical decimal as numeric on every serving path. CASE makes// the jsonb type guard structural instead of relying on SQL qualifier@@ -1365,8 +1411,10 @@ func operatorPatternPredicate(pattern propertyOperatorPattern, addArg func(any)// A "no value" marker alternative renders as a key-absence disjunction —// `NOT (i.properties ? $m)` — which cannot use the GIN index but is exact for// the unset state (property values are never null; DELETE unsets). An operator-// alternative renders as its typed comparison (ILIKE / numeric / date string),-// also unindexed: scalar ranges fundamentally cannot use a containment index.+// alternative renders as its typed comparison (ILIKE / numeric / date string):+// scalar ranges fundamentally cannot use a containment index, and only+// `contains` gets an indexable prefilter in front of it (see+// operatorPatternPredicate).func propertiesFilterPredicate(groups [][]json.RawMessage, addArg func(any) string) string {groupSQL := make([]string, 0, len(groups))for _, alternatives := range groups {diff --git a/server/internal/handler/property_test.go b/server/internal/handler/property_test.goindex 40c151bb42..f592a5c0cd 100644--- a/server/internal/handler/property_test.go+++ b/server/internal/handler/property_test.go@@ -15,6 +15,7 @@ import ("github.com/go-chi/chi/v5""github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -1609,3 +1610,159 @@ func TestListIssuesPropertyFilterOperators(t *testing.T) {t.Fatalf("table rows operator filter wrong: total=%d rows=%d", rowsResponse.Total, len(rowsResponse.Rows))}}++// TestPropertyContainsPrefilterCompilationUnit pins which contains needles get+// the bigram prefilter that migration 446's index serves. The prefilter matches+// against the jsonb text form of the whole properties object, so a needle that+// jsonb escapes on serialization (", \, control characters) must compile+// without it — the alternative would silently drop matching rows.+func TestPropertyContainsPrefilterCompilationUnit(t *testing.T) {+ defID := uuid.NewString()+ compile := func(t *testing.T, needle string) (propertyOperatorPattern, json.RawMessage, string) {+ t.Helper()+ raw, err := json.Marshal(map[string]any{defID: []any{map[string]any{"op": "contains", "value": needle}}})+ if err != nil {+ t.Fatalf("marshal filter: %v", err)+ }+ w := httptest.NewRecorder()+ groups, ok := parsePropertiesFilterParam(w, string(raw))+ if !ok {+ t.Fatalf("parse %q: %s", needle, w.Body.String())+ }+ pattern, isOp := parseOperatorPattern(groups[0][0])+ if !isOp {+ t.Fatalf("%q did not compile to an operator pattern", needle)+ }+ var args []any+ addArg := func(v any) string {+ args = append(args, v)+ return fmt.Sprintf("$%d", len(args))+ }+ return pattern, groups[0][0], propertiesFilterPredicate(groups, addArg)+ }++ for _, tc := range []struct {+ name string+ needle string+ wantPrefilter string+ }{+ {"plain ascii", "world", "world"},+ // LIKE wildcards are escaped identically on both sides, so they stay+ // prefilterable — the escape is a backslash in the pattern, not in the+ // serialized value.+ {"like wildcards", "50% off_now", `50\% off\_now`},+ {"cjk", "中文属性", "中文属性"},+ // Short needles are prefiltered too: pg_bigm indexes 1- and+ // 2-character keywords, which is the capability it exists for over+ // pg_trgm, and one CJK character is already a word.+ {"single character", "x", "x"},+ {"single cjk character", "文", "文"},+ {"double quote", `say "hi"`, ""},+ {"backslash", `C:\logs`, ""},+ {"tab", "col\tvalue", ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ pattern, alt, sql := compile(t, tc.needle)+ if pattern.Prefilter != tc.wantPrefilter {+ t.Fatalf("prefilter for %q: got %q, want %q", tc.needle, pattern.Prefilter, tc.wantPrefilter)+ }+ // The static open_only unroll keys off the presence of the JSON+ // member, so an unsafe needle must omit it rather than carry "".+ var members map[string]json.RawMessage+ if err := json.Unmarshal(alt, &members); err != nil {+ t.Fatalf("decode alternative: %v", err)+ }+ _, hasMember := members["prefilter"]+ if hasMember != (tc.wantPrefilter != "") {+ t.Fatalf("alternative %s: prefilter member present=%v, want %v", alt, hasMember, tc.wantPrefilter != "")+ }+ hasClause := strings.Contains(sql, "LOWER(i.properties::text) LIKE LOWER(")+ if hasClause != (tc.wantPrefilter != "") {+ t.Fatalf("predicate %s: prefilter clause present=%v, want %v", sql, hasClause, tc.wantPrefilter != "")+ }+ // The per-key check is authoritative on every path, prefiltered or+ // not.+ if !strings.Contains(sql, "ILIKE") || !strings.Contains(sql, "jsonb_typeof") {+ t.Fatalf("predicate lost its per-key contains check: %s", sql)+ }+ })+ }+}++// TestPropertyContainsPrefilterKeepsResultsExact runs the needles above against+// real rows on both serving paths. The prefilter is lossy by design, so the+// property under test is that it never changes an answer: needles jsonb escapes+// must still match, and a needle that only appears elsewhere in the object —+// under another definition, or in a definition id — must still miss.+func TestPropertyContainsPrefilterKeepsResultsExact(t *testing.T) {+ text := createTestProperty(t, map[string]any{"name": "PF" + uuid.NewString()[:8], "type": "text"})+ other := createTestProperty(t, map[string]any{"name": "PO" + uuid.NewString()[:8], "type": "text"})++ listIDs := func(t *testing.T, defID, needle string, openOnly bool) map[string]bool {+ t.Helper()+ buf, err := json.Marshal(map[string]any{defID: []any{map[string]any{"op": "contains", "value": needle}}})+ if err != nil {+ t.Fatalf("marshal filter: %v", err)+ }+ query := "/api/issues?limit=50&properties=" + url.QueryEscape(string(buf))+ if openOnly {+ query += "&open_only=true"+ }+ var resp struct {+ Issues []IssueResponse `json:"issues"`+ }+ testutil.Call(t, testHandler.ListIssues, newRequest(http.MethodGet, query, nil)).+ Want(http.StatusOK).JSON(&resp)+ present := make(map[string]bool, len(resp.Issues))+ for _, issue := range resp.Issues {+ present[issue.ID] = true+ }+ return present+ }++ for _, tc := range []struct {+ name string+ value string+ needle string+ }{+ {"plain ascii", "plain value", "in val"},+ {"double quote", `he said "yes" loudly`, `"yes"`},+ // jsonb doubles the backslash, so the needle's literal form is absent+ // from properties::text — a prefiltered lookup would find nothing.+ {"backslash", `C:\bin`, `C:\bin`},+ {"tab", "column\tvalue", "\tvalue"},+ {"cjk", "中文属性值", "文属"},+ {"like wildcards", "100% done_now", "% done_"},+ {"case folded", "MiXeD Case", "mixed ca"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ hit := createPropertyTestIssue(t, "prefilter hit")+ // The decoy carries the identical string under a different+ // definition: it is in LOWER(properties::text) exactly like the+ // hit's, so only the per-key check can tell the two apart.+ decoy := createPropertyTestIssue(t, "prefilter decoy")+ if w := setIssuePropertyRaw(t, hit, text.ID, tc.value); w.Code != http.StatusOK {+ t.Fatalf("seed hit: %d %s", w.Code, w.Body.String())+ }+ if w := setIssuePropertyRaw(t, decoy, other.ID, tc.value); w.Code != http.StatusOK {+ t.Fatalf("seed decoy: %d %s", w.Code, w.Body.String())+ }++ for _, openOnly := range []bool{false, true} {+ present := listIDs(t, text.ID, tc.needle, openOnly)+ if !present[hit] {+ t.Fatalf("open_only=%v: contains %q missed the issue holding %q", openOnly, tc.needle, tc.value)+ }+ if present[decoy] {+ t.Fatalf("open_only=%v: contains %q matched another definition's value", openOnly, tc.needle)+ }+ // A definition id is part of the object's text form but never+ // part of a value, so the prefilter alone must not surface the+ // row.+ if byDefID := listIDs(t, text.ID, text.ID[:8], openOnly); byDefID[hit] {+ t.Fatalf("open_only=%v: contains matched a definition id, not a value", openOnly)+ }+ }+ })+ }+}diff --git a/server/migrations/446_issue_properties_bigm_index.down.sql b/server/migrations/446_issue_properties_bigm_index.down.sqlnew file mode 100644index 0000000000..d32b0b8a7e--- /dev/null+++ b/server/migrations/446_issue_properties_bigm_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_properties_bigm;diff --git a/server/migrations/446_issue_properties_bigm_index.up.sql b/server/migrations/446_issue_properties_bigm_index.up.sqlnew file mode 100644index 0000000000..56f242fb1a--- /dev/null+++ b/server/migrations/446_issue_properties_bigm_index.up.sql@@ -0,0 +1,20 @@+-- Bigram GIN index behind the lossy prefilter that scalar `contains` property+-- filtering puts in front of its per-key ILIKE check (MUL-6928). Without it a+-- contains filter cannot reach any index and degrades to a workspace-wide+-- sequential scan: on a 1M-issue workspace throughput drops ~8x against an+-- equality filter, which does reach idx_issue_properties_gin.+--+-- LOWER(...) LIKE, not ILIKE: pg_bigm 1.2 (RDS) has no ILIKE index scan, the+-- same constraint migration 036 hit — an ILIKE-shaped predicate would never use+-- this index. The pattern side is lowered in SQL as well so the prefilter folds+-- case exactly the way the ILIKE it guards does.+--+-- Single-statement file because a concurrent build cannot share a migration,+-- and for the same reason it cannot be wrapped in the DO ... EXCEPTION block+-- migrations 032 / 036 use to tolerate a missing pg_bigm. The runner gates this+-- version on the extension instead (issuePropertiesBigramOperatorClass in+-- cmd/migrate): environments without pg_bigm record it with the SQL skipped and+-- keep the unaccelerated — still correct — prefilter. Recovery for a database+-- that installs pg_bigm later is in cmd/migrate/README.md.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_properties_bigm+ ON issue USING gin (LOWER(properties::text) gin_bigm_ops);diff --git a/server/migrations/447_issue_properties_bigm_index_statistics.down.sql b/server/migrations/447_issue_properties_bigm_index_statistics.down.sqlnew file mode 100644index 0000000000..20580c0598--- /dev/null+++ b/server/migrations/447_issue_properties_bigm_index_statistics.down.sql@@ -0,0 +1,3 @@+-- No-op: 447 refreshes planner statistics, which are not schema. Discarding+-- them would only make the planner worse, and 446's rollback drops the+-- expression whose statistics this generated.diff --git a/server/migrations/447_issue_properties_bigm_index_statistics.up.sql b/server/migrations/447_issue_properties_bigm_index_statistics.up.sqlnew file mode 100644index 0000000000..035705a3d2--- /dev/null+++ b/server/migrations/447_issue_properties_bigm_index_statistics.up.sql@@ -0,0 +1,22 @@+-- Generate planner statistics for the LOWER(properties::text) expression that+-- migration 446 indexes. Building an expression index does not collect+-- statistics for its expression — the CREATE INDEX docs are explicit that+-- ANALYZE must run, or the autovacuum daemon must analyze the table, before the+-- planner has anything to judge the new index by.+--+-- Without it the index is built, valid, and ignored: an existing issue table+-- gets no statistics row for the expression, the planner falls back to a+-- pattern-length heuristic that estimates a single-character needle at 5% of+-- the table, and a scalar `contains` filter stays on the workspace-wide+-- sequential scan this index exists to remove — now also paying for the+-- prefilter clause on every row. A deployment with no bulk writes cannot rely+-- on autovacuum to fix that promptly: the default threshold is 10% of rows+-- changed, which a large, quiet issue table can take weeks to reach.+--+-- Deliberately not gated on pg_bigm, unlike 446: ANALYZE is valid, cheap and+-- side-effect-free everywhere, and refreshing the table's ordinary column+-- statistics is useful even where the expression index was skipped. It takes+-- ShareUpdateExclusiveLock, which does not block reads or writes.+--+-- Separate file because 446 must stay a single-statement concurrent build.+ANALYZE issue;diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 4e7743f863..241ba64109 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -1233,11 +1233,14 @@ WHERE i.workspace_id = $1-- {"__op__": "<op>", "def": "<id>", "value": "<v>"} — scalar operator-- (contains / gt / gte / lt / lte / before / after), where the contains-- value arrives already ILIKE-escaped and the op was validated in Go, so- -- the per-op branches below only ever see legal values. The correlated- -- form skips the GIN index, which is fine here: open_only is an- -- unpaginated workspace scan. The terminal-status predicate intentionally- -- remains a filter rather than a positive index narrowing so unknown legacy- -- status keys stay visible.+ -- the per-op branches below only ever see legal values. A contains pattern+ -- additionally carries "prefilter" when its needle survives jsonb text+ -- serialization intact; the clause it enables is redundant by construction+ -- (prefilterableContainsNeedle in property.go) and stays here so both renderings+ -- of the filter keep matching row for row. The correlated form skips the GIN+ -- index, which is fine here: open_only is an unpaginated workspace scan. The+ -- terminal-status predicate intentionally remains a filter rather than a+ -- positive index narrowing so unknown legacy status keys stay visible.AND ($9::jsonb IS NULLOR NOT EXISTS (@@ -1253,6 +1256,8 @@ WHERE i.workspace_id = $1AND i.properties ->> (alt.pattern ->> 'def') IS NOT NULLAND ((alt.pattern ->> '__op__' = 'contains'+ AND (NOT (alt.pattern ? 'prefilter')+ OR LOWER(i.properties::text) LIKE LOWER('%' || (alt.pattern ->> 'prefilter') || '%'))AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'AND (i.properties ->> (alt.pattern ->> 'def')) ILIKE '%' || (alt.pattern ->> 'value') || '%')OR (alt.pattern ->> '__op__' = 'gt'diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex d9f6f43821..62d0fab5a7 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -369,11 +369,14 @@ WHERE i.workspace_id = $1-- {"__op__": "<op>", "def": "<id>", "value": "<v>"} — scalar operator-- (contains / gt / gte / lt / lte / before / after), where the contains-- value arrives already ILIKE-escaped and the op was validated in Go, so- -- the per-op branches below only ever see legal values. The correlated- -- form skips the GIN index, which is fine here: open_only is an- -- unpaginated workspace scan. The terminal-status predicate intentionally- -- remains a filter rather than a positive index narrowing so unknown legacy- -- status keys stay visible.+ -- the per-op branches below only ever see legal values. A contains pattern+ -- additionally carries "prefilter" when its needle survives jsonb text+ -- serialization intact; the clause it enables is redundant by construction+ -- (prefilterableContainsNeedle in property.go) and stays here so both renderings+ -- of the filter keep matching row for row. The correlated form skips the GIN+ -- index, which is fine here: open_only is an unpaginated workspace scan. The+ -- terminal-status predicate intentionally remains a filter rather than a+ -- positive index narrowing so unknown legacy status keys stay visible.AND (sqlc.narg('properties_filter')::jsonb IS NULLOR NOT EXISTS (@@ -389,6 +392,8 @@ WHERE i.workspace_id = $1AND i.properties ->> (alt.pattern ->> 'def') IS NOT NULLAND ((alt.pattern ->> '__op__' = 'contains'+ AND (NOT (alt.pattern ? 'prefilter')+ OR LOWER(i.properties::text) LIKE LOWER('%' || (alt.pattern ->> 'prefilter') || '%'))AND jsonb_typeof(i.properties -> (alt.pattern ->> 'def')) = 'string'AND (i.properties ->> (alt.pattern ->> 'def')) ILIKE '%' || (alt.pattern ->> 'value') || '%')OR (alt.pattern ->> '__op__' = 'gt'