Repository navigation
feat(plan): widen functional index expression eligibility and diagnostics - #32510
Conversation
…tics Resolve the three components split from matrixorigin#31448 into matrixorigin#32437 under the approved eligibility-widening design (docs/design/20261110-functional-index-eligibility-widening.md): - Admission: functionalScalarFunctionEligible admits substring/substr/mid, left, reverse, md5, crc32, hex, length and concat by resolved registry identity, arity and argument/result predicates - never by SQL spelling - through the shared verifyFunctionalIndexOverload re-derivation; md5 over a CHAR subject binds through the single implicit CHAR-widening adapter with stored md5 values identical to the VARCHAR subject, and the physical hidden-key equality is added only for byte-stable keys (no CHAR reference reachable), so force/ignore index-vs-scan agreement holds under every sql_mode including PAD_CHAR_TO_FULL_LENGTH. - Distinct numeric JSON case: functionalJSONNumericCastEligible admits cast(json_extract(<JSON column>, <constant single-location path>) as <integer target>) across the CAST grammar's integer spellings in both bound forms, with the hidden key bound to the cast target; persisted spellings canonicalize the LONGLONG family (as signed integer -> as signed, as unsigned integer -> as unsigned) and every replay (SHOW CREATE, LIKE, COPY, RENAME COLUMN) is fail-closed lossless in key type, width and value domain. - Diagnostics: replace the one catch-all session-independence message with a three-way model - the generated-column nondeterminism message now fires before eligibility, the session-independence message is reserved for conversions that demonstrably read session state (TIMESTAMP-involving casts, string-to-float32/64, string-to-DATE/DATETIME/TIME parses), and every other rejection reports the new NotSupported message naming the exact authored expression text, including bind-stage resolution failures (wrong arity, unknown functions) mapped from ErrInvalidArg, with compact authored argument lists; the retained MEDIUMINT/INT3 not-yet-implemented family stays distinct, and rejected DDL changes no metadata. - Persistence: renderFunctionalIndexOriginString is the single width-preserving rendering entry for every persisted functional-expression SQL producer (lowering and identifier rewrite), with fail-closed origin and rewrite round-trip guards so lossless replay is asserted at DDL and at RENAME/ CHANGE COLUMN; a backslash-containing literal persists as the hex-introducer spelling _utf8mb4 X'<hex>' through authoring and renames. Tests: new pkg/sql/plan/functional_index_eligibility_test.go (admission matrices, identity-cast controls, persisted-spelling canonicalization, plan-shape match proofs, byte-stability rules, identifier-rewrite persistence through the real rewrite functions, fail-closed rewrite guard, the 14-row predicated diagnostics and the volatile-before-eligibility assertions), updated functional_index_test.go and sqlintegration lifecycle pins for the lossless literal spelling, and extended functional_index / functional_json_key BVT cases with index-vs-scan agreement after insert/update/rollback, LIKE and COPY replays, rename-then-replay controls, rejection families and border values - regenerated via mo-tester and double-run green (two consecutive comparison runs at 100%, error.txt empty); the new type switch carries the repository's reasoned typeswitch:partial annotation and pkg/container/types TestTypeSwitchFamilies passes. Related to matrixorigin#32437.
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
Unrelated CI failure on this PR's latest run (tracked)
|
|
mo-bot review · Commit: Review discussion changed before publication; a fresh contextual review is queued. |
iamlinjunhong
left a comment
There was a problem hiding this comment.
Reviewed exact head 71f09a1fc7788b2f33cd51e99ad0c12c2062ac12 against main base 45917e803f2915f6f0838b2b2fe9f591fc5b6018, within issue #32437 and the existing scope record. No confirmed P0/P1 findings. APPROVE: the remaining nonblocking limitation below has an explicit author response after the previous review.
-
[P2] Negative-count LEFT indexes still miss their own equality lookup —
pkg/sql/plan/functional_index.go:847–849; regression expectation atpkg/sql/plan/functional_index_eligibility_test.go:477.With
name VARCHAR(40),CREATE INDEX ix ON t ((LEFT(name,-1)))now succeeds, butWHERE LEFT(name,-1)=''still receives no hidden-column equality. The persisted binder retainsunary_minus(1)and derives width 40; query binding folds the count and derives width 0.foldFunctionalIndexSignedConstantnormalizes the literal without reconciling the enclosing function's width, so the exact typed comparison rejects the match. The new test explicitly expects no hidden equality for this expression. The index incurs storage and maintenance costs without serving this ordinary equality lookup; this establishes a missing rewrite, not incorrect rows or a measured throughput regression. The author's post-review response explicitly acknowledges the source-envelope width and residual-only behavior. This limitation remains nonblocking.
The previous review's signed-literal admission failures are fixed, including the negative-position SUBSTRING lookup. The positive-count SUBSTRING/LEFT provenance mismatch and the UINT64-to-DECIMAL comparison-wrapper mismatch are also addressed by the current code and focused planner assertions. The author supplied a separate response to the designated review; replies were checked against the actual changes rather than treated as proof of resolution.
CI is not entirely success: the supplied exact-head snapshot contains 29 checks: 13 success, 14 skipped and 2 neutral, with no failed or pending checks. CI Required and the recorded Ubuntu/x86 UT check succeeded. The earlier failure mentioned in the conversation is not the current check state.
Validation: inspected all 12 changed paths, the previous-head repair diff, and the relevant binder, generated-column, matching and DDL replay consumers. The read-only PR artifact check passed. No local Go tests, SQL service or BVT runs were executed; supplied CI and author runtime reports are distinguished from local evidence. Local runtime testing was skipped because the retained finding is established by the binding/type-refinement path and its explicit planner-test expectation. Deep concurrency/race and index-plugin checks were skipped because this change introduces no asynchronous ownership or plugin-dispatch contract. Source remained unchanged, and no GitHub writes were performed.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 71f09a1fc7788b2f33cd51e99ad0c12c2062ac12
Assessment: approve
Reviewed all 12 changed paths and affected owners. The three prior concerns are resolved. The design coherently extends existing generated-column, index and persistence capabilities; negative-count LEFT remains an accepted residual-only case.
Model: gpt-6.1-sol / max
Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0
Validation:
-
Frozen-head CI: 13 successful, 14 skipped, 2 neutral; UT, SCA, shared build, active BVT jobs and CI Required succeeded.
-
Reused author-reported focused/full planner and tree tests, three integration roots, and two 271/271 BVT comparison runs.
-
Local static audit passed: frozen range, seven Go files formatted, 271 SQL/result statement echoes, 13 discussion keys covered, source unchanged. Receipt: checks/1794393455126268000-4.json; reconciliation: validation-audit.json.
Limitations:
-
No fresh local Go/service/BVT execution; raw author and CI logs were not supplied.
-
CHAR-dependent keys and negative-count LEFT retain residual-only matching.
🚫 Left the queue · pull request dequeued18 min in the queue, with no time running CI. So far
Reason Pull request #32510 has been dequeued Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.
To get back in the queue
Tick the box to put this pull request back in the merge queue (same as
Times in UTC · dashboard · how the merge queue works |
What type of PR is this?
Which issue(s) this PR fixes:
Related to #32437
What this PR does / why we need it:
Completes the three unresolved components split from #31448 into #32437, under the independently reviewed eligibility-widening design delivered at
docs/design/20261110-functional-index-eligibility-widening.md.Root causes
functionalExpressionEligible(pkg/sql/plan/functional_index.go) implemented only the initial increment's allowlist (lower/upper, text-cast JSON chain, integer arithmetic) and failed closed for the requested scalar functions, and the JSON gate admitted only the bounded text chain.SUBSTRING,LEFT,MD5,CRC32,HEX,REVERSE,LENGTHandCONCATwere rejected on base (b743219dd2), as was the consolidatedCAST(JSON_EXTRACT(j, constant_path) AS <integer>).lowerFunctionalIndexraisedfunctional index expression must have session-independent semanticsfor every inadmissible expression and ran the volatile-function check only after eligibility, so unsupported coverage was reported as session dependence (and genuinely nondeterministic functions never got the generated-column message); wrong-arity/unknown-function DDL leaked the raw registry error (invalid argument function ..., client code 20203) from the bind seam.,instead of the authoredCONCAT(v,1)spelling.What changed
functionalScalarFunctionEligibleadmits substring/substr/mid, left, reverse, md5, crc32, hex, length and concat by resolved registry identity, arity, argument-domain and result predicates — never by SQL spelling — and each candidate is re-verified through the sharedverifyFunctionalIndexOverloadregistry re-derivation; md5 over a CHAR subject binds through the single implicit CHAR-widening adapter (values identical to the VARCHAR subject); the physical hidden-key equality is added only for byte-stable keys (integer or VARCHAR hidden key and no CHAR reference reachable), so force/ignore result agreement holds under every sql_mode includingPAD_CHAR_TO_FULL_LENGTH.functionalJSONNumericCastEligibleadmitscast(json_extract(<JSON column>, <constant single-location path>) as <integer target>)across the CAST grammar's integer spellings in both bound forms the binder produces, with the hidden key bound to the cast target; the equality-match seam unwraps the binder's flag-clear widening wrapper so the plainas intspelling physically matches its INT32 key;as signed integer/as unsigned integerpersist under the canonical bare spellings (as signed/as unsigned) and every replay (SHOW CREATE, LIKE, COPY, RENAME COLUMN) keeps the identical key type, width and value domain, with identical out-of-range errors (2147483648 on int32 keys and their replays, matching int64/uint64 keys).functional index expression is not supported: <exact authored text>— including bind-stage resolution failures (wrong arity, unknown functions) mapped fromErrInvalidArg— with compact authored argument lists (CONCAT(v,1), notCONCAT(v, 1), via the new default-offtree.WithCompactArgListsformatting option applied only at the two diagnostic producers); the retained MEDIUMINT/INT3 not-yet-implemented family (client 20102) stays distinct from this family (20105), and every rejected DDL changes no metadata.renderFunctionalIndexOriginStringis the single width-preserving rendering entry for every persisted functional-expression SQL producer, plusverifyFunctionalIndexOriginRoundTrip/verifyFunctionalIndexRewriteRoundTripfail-closed guards: authored persistence text must re-parse, re-bind and re-admit with the authored hidden-key type before the DDL is accepted, and an ALTER's rewritten text must re-bind identically or the ALTER fails closed and changes no metadata; a backslash literal persists as_utf8mb4 X'<hex>'at authoring and through renames.Issue-to-test proof
b743219dd2)probe-base-run.log: all eight scalars rejected with the catch-all message;lower(name)/id+1admitTestFunctionalIndexScalarAdmission/...NegativeControls/...CharSubjectBindings; BVT admitted DDL + hidden-column counts + force/ignore agreement after insert/update/rollback (mo-tester double run 100%)TestFunctionalIndexNumericJSONAdmission/...PersistedSpellingCanonicalization/...NumericJSONMatchPlan/...ByteStabilityMatchRules; functional_json_key BVT boundary matrix (2147483648 / 4294967296, NULL sets, LIKE/COPY/rename replays)arity-red-ut.log/probe-arity-red.log/base-arity-probe.log: wrong-arity DDL leakedinvalid argument function substring, bad value [VARCHAR](20203) on base and pre-repair trees; multi-argument rejections renderedCONCAT(v, 1)TestFunctionalIndexPredicatedDiagnostics(14 rows: three families, exact authored tokens incl.CONCAT(v,1), MEDIUMINT/INT3 NYI-distinctness),TestFunctionalIndexVolatileDiagnosticsBeforeEligibility; live service probe PASS; rejection BVT blocks with unchanged hidden-column countsprobe-literal-replay-run.log/probe-rename-replay-run.log: X-form literal reverted to a widthless cast at the first renameTestFunctionalIndexIdentifierRewritePersistence/...RewriteRoundTripGuard, updatedTestFunctionalIndexOriginStringQuotesLiterals, sqlintegration lifecycle SHOW CREATE pins (lower(_utf8mb4 X'615c62')), rename-then-replay BVT controlsTestTypeSwitchFamiliesfailed on the pre-annotation tree:float switch misses T_bf16, T_float16, T_float8, T_float4typeswitch:partialannotation on the audited float32/64 diagnostic subset;TestTypeSwitchFamiliespassesThe full ladder was green on the delivered tree: focused and full
./pkg/sql/planowning-package runs (ok 155.793s), focused sqlintegration (ok 12.963s), statics (gofmt / go list / go vet / golangci-lint over the changed closure, all exit 0,0 issues.), a live one-node service rejection probe (PASS, exact authored tokens, unchanged SHOW CREATE across rejections, post-error recovery), and two consecutive mo-tester comparison runs of the extended BVT case files at 100% (TOTAL :250, SUCCESS :250, FAILED :0, error.txt empty; functional_index 157/157, functional_json_key 93/93), with both.resultfiles regenerated bygenrs, hand-reviewed row by row and delivered in the repository plain format.Test commands
Review-repair round (mo-bot request_changes, 2026-11-11)
All three planner findings from the review reproduced at the previous head with probe receipts (
probe-32510-review-red.log,probe-32510-review-red2.log) and are fixed. Design erratum item 6 indocs/design/20261110-functional-index-eligibility-widening.md(sha2566bcfc6d03a6114928f0171658ebb53e5be4dd25d69d149f2269116dedac7c8a7) records the three repairs under the same independently approved design.pkg/sql/plan/functional_index.go):functionalExpressionEligibleadmits the persisted bind'sunary_minusspelling of an authored signed-integer constant — exactly one non-null signed-integer literal argument under the identical signed-integer result type. Negated columns (signed or unsigned, with or without their widening/signedness adapters), non-integer negations and every other unary-minus form keep failing closed. The match-time comparison copies fold that same persisted spelling into the query-side folded literal, so asubstring(name,-2,2)key serves its own literal lookups; theleft(name,-1)count spelling keeps the source-envelope persisted width and stays residual-only (documented asymmetry, pinned by its own UT row).pkg/sql/plan/functional_index.go):normalizeFunctionalExpressionclears the query-onlyPreparedNumeric.StringDomainSourcepointer on the comparison copies exactly as it already zeroed AuxId/Ndv/Selectivity; value-bearing shape, type metadata and the base-row residual are untouched, restoring ordinary literal-equality lookups onsubstring(name,1,8)/left(name,4)keys. Folded negated integer literals also carried a query-sidestring_sourceprovenance asymmetry; integer-literal comparison copies zero it (the pinned integer is the entire value, and executed plans are never the normalized copies).pkg/sql/plan/functional_json_index.go): the comparison-operand unwrap additionally strips the binder's flag-clear overload-0 integer-to-DECIMAL promotion when value-exact — the decimal's integer-digit capacity (width minus scale) covers the source type's widest value (uint64 20, int64 19, int32 10, int8 4 digits). Insufficient adapters stay unstripped, user-explicit casts keep their syntax flag and never match, and the re-bound hidden equality rides the same promotion so the base-row residual keeps owning correctness.Tests added this round — UT:
TestFunctionalIndexOrdinaryLookupRewrites(hidden-key equality plus base-row residual forsubstring(name,1,8),left(name,4),substring(name,-2,2),crc32(name)=123,cast(json_extract(doc,'$.a') as unsigned)=4294967296and... as int)=1.5; residual-only pins forleft(name,-1)and the explicitcast(crc32(name) as decimal(38,0))=123control), signed-literal admission rows plus negated-column/unsigned/fractional negative controls, andTestFunctionalIndexDecimalPromotionCapacity(uint64 covered by DECIMAL128(38,0)/(20,0) and not by (19,0)/decimal64; int32 by (11,1) not (10,1); int8 by (4,0) not (2,0); int64 by (19,0) not (18,0)). BVT:is_sneg/is_lnegDDL withbad_neg_col/bad_neg_upos/bad_neg_realrejection controls, signed-literal position lookups ('ef'/'fg'/IS NULL/left(name,-1)=''),crc32(name)=<literal>numeric-literal lookups and decimal-literal JSON-key lookups (=42.0/=123.0/=42.5, force/ignore agreement).Validation this round — focused 20-root plan batch green (postfix-focused-run3.log); full
./pkg/sql/plan+./pkg/sql/parsers/treegreen on the final tree (postfix-plan-tree-run2.log:ok 193.786s/ok 1.313s); the three sqlintegration lifecycle roots green post-format (postfix-sqlintegration-3roots-run2.log:ok 13.289s); gofmt on the changed closure clean;go vet -mod=readonlygreen over the changed closure; golangci-lint green over the changed closure (0 issues.); BVT regenerated viagenrs, converted to the repository plain format, hand-reviewed row by row and proven through two consecutive 100% mo-tester comparison runs on the rebuilt service (271/271 each, error.txt empty; functional_index 172/172, functional_json_key 99/99). Evidence logs under this issue's artifact directory.Residual risks
functionalScalarFunctionEligibleadmits a delimited set: functions outside it (sha1, locate, replace, instr, temporal functions, unlisted builtins) stay rejected as coverage; widening further needs the same per-function safety accounting as the design requires.tree.WithCompactArgListsoption; a future change ofExprs.Formatdefaults or of the helper options must regenerate the pinned.resultrows.ErrInvalidArgfrom the authored-expression bind only); a future planner refactor changing that error code must revisit the seam — pinned by the wrong-arity UT rows and the MEDIUMINT NYI-distinctness assertion.pkg/container/types's type-family guard now passes; the taggedtypeswitch:partialswitch documents that low-precision float cast targets (bf16/float16/float8/float4) intentionally stay rejection-by-coverage — extending the audit to them would be a design-level category change.