Skip to content

perf(regexp): skip terminal any-rune loops at EOF - #31079

Merged
XuPeng-SH merged 7 commits into
mainfrom
codex/regexp-terminal-repeat-20261025
Oct 25, 2026
Merged

XuPeng-SH merged 7 commits into
mainfrom
codex/regexp-terminal-repeat-20261025

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Related to #27665; partial ClickBench Q29 improvement.

What this PR does / why we need it:

Classify eligible greedy terminal-any-rune loops during regexp compilation and let the bounded bitstate matcher reach EOF directly. Preserve capture/alternative priority, immutable programs, NFA/reader behavior and linear failed-LF scanning. Perform required-prefix admission before resetting VM state to avoid slowing prefix rejection.

Recorded Linux acceptance: on the same locally generated 10M-row ClickBench projection, Q29 median improved from 5.505865s to 4.541981s (-17.51%). Baseline overlays the two production files from main 83fa4d7d; four-worker limits, two warmups and five measured runs per phase, baseline/candidate/candidate/baseline. Q5/Q6/Q21 controls showed no sustained regression. Results matched source-built DuckDB, using a deterministic Q21 tie control; representative profiles reported no spill. These are shared-host measurements, not a universal performance guarantee.

Validation recorded before this cleanup: private regexp full normal/race; both reuse/admission stress tests repeated 100 times under race; SQL regexp consumer normal/race selection; incremental formatting/vet/lint (0 new issues). This update changes review guidance, documentation and benchmark output destinations; production Go code and Go tests are unchanged.

Keep maintained reproduction scripts and configuration, with explicit output directories outside the checkout. Remove raw evidence, per-run manifests and review attestations from the delivered tree. Review guidance now requires justified complexity, separate scrutiny of implementation/tests/docs, and compact PR descriptions. GitHub CI results remain separate from the recorded local validation.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · superseded

Commit: 2ed4bb00d508749a7678b842e0fae30396347868

"interrupted"

@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: a238e0e70e7836880be3bc5bf0bf5edd510550b7

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: a238e0e70e7836880be3bc5bf0bf5edd510550b7

Assessment: request_changes

Reviewed the complete five-file delta and callers. Compile-time classification and the linear-scan invariant are sound; correctness and race checks passed. A reproducible rejection-path slowdown violates the stated performance criterion, and required public-query evidence remains unauditable.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

  • P2 pkg/sql/plan/function/internal/regexp/backtrack.go:106: Repeated searches whose required literal prefix is absent, including ineligible patterns such as a.*b against 300 consecutive b characters.
    Impact: Every bitstate search initializes the new optimization state before prefix rejection. Interleaved measurements reproduce a shared rejection-path penalty, contrary to the design's explicit no-repeatable-generic-regression criterion. Address this penalty and rerun rejection and eligible-tail controls.
    Evidence: Eight interleaved phases measured prefix rejection at 24.285→25.510 ns (+5.04%), with non-overlapping sample ranges. A separate production-vector ABBA comparison measured ineligible a.*b REGEXP_INSTR at 24710.5→25300.5 ns per 256 rows (+2.39%); both candidate phase medians exceeded both baseline medians. See attempt-1/control-bench.log and vector-bench.log, with successful receipts 1792910579543490501-4.json and 1792910874175549904-252.json. Baseline overlays use verified merge-base matcher files.

  • P2 docs/design/20261025-regexp-terminal-repeat.md:95: Accepting the declared 10M-row, non-spill Q29 performance and result-parity gate.
    Impact: Validation requirement: the supplied aggregates cannot establish this required public-query result independently. Provide retained source/binary fingerprints, commands, terminal results, parity logs and no-spill plans for the reported comparison; reuse existing artifacts before rerunning it.
    Evidence: evidence.json.local_validation is empty. The frozen PR body reports aggregate Q29/DuckDB results without auditable artifacts. Recovered receipts cover private matcher tests and microbenchmarks; fresh checks cover vector function entry points, not public Q29 execution. The design explicitly states that microbenchmarks alone are insufficient.

Validation:

  • Evidence retained under /home/xupeng/.local/state/mo-bot/jobs/dfc7800a204ee0e5f21c521c/attempt-1; final-audit.json correlates commands, source fingerprints, exit receipts and log hashes.

  • Reused completed private-regexp normal/race tests after proving package and module inputs identical to the earlier tested revision. No earlier review verdict was reused.

  • Preflight passed. Repository native-provenance verification passed with all 192 native inputs matching. SQL checks passed: 65 normal tests, 20 supplemental normal tests and 112 race tests, without skips or failures.

  • Diagnostic vector probes passed for eligible tails, captures, LF failure/recovery, NULLs, binary invalid UTF-8, offsets and reuse.

  • gofmt, go vet, pinned molint, golangci-lint 2.14.0 and diff checks passed. Recovered benchmarks show approximately 96% eligible-tail improvement and linear failed-start scaling.

Limitations:

  • Vector measurements are function-entrypoint benchmarks, not end-to-end SQL query latency.

  • Public Q29/DuckDB measurements remain author-reported; raw artifacts were requested but unavailable.

  • Frozen CI build, UT, SCA and coverage checks were pending. Source remained unchanged.

@mergify mergify Bot added kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/test-ci labels Oct 25, 2026
@matrix-meow matrix-meow added size/XXL Denotes a PR that changes 2000+ lines and removed size/M Denotes a PR that changes [100,499] lines labels Oct 25, 2026
@XuPeng-SH

XuPeng-SH commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: 28cbea62ed7099a2dd44e56a62e08d5d9227f40d

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: 28cbea62ed7099a2dd44e56a62e08d5d9227f40d

Assessment: approve

Reviewed the complete 16-file delta and affected callers. Compile-time classification appropriately owns eligibility, while per-search LF tracking preserves linear work, capture priority and pooled-state isolation without duplicating the matcher. Both earlier review concerns are resolved; no actionable findings remain.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Private matcher normal and race suites passed: 102 tests/subtests each. Focused admission/reuse race tests passed 100 repetitions.

  • SQL-consumer normal and race selections passed: 335 tests/subtests each, with no failures or skips.

  • Isolation preflight, native provenance verification, all 192 native-input comparisons, gofmt, owner/consumer go vet and diff checks passed.

  • Independently reconciled retained source hashes, benchmark commands/results, SQL parity and all 16 MatrixOne plans plus four DuckDB profiles. Recorded Q29 improved 17.51%; ineligible prefix rejection improved 20.44%, and vector rejection improved 5.93% with unchanged allocations.

  • Commands, source fingerprints, terminal receipts and log hashes are correlated in /home/xupeng/.local/state/mo-bot/jobs/798687b67eb457ba4f998014/attempt-1/final-audit.json. Source remained unchanged.

Limitations:

  • Public performance uses audited retained evidence, not a fresh 10M-row rerun. Measurements used a shared host; profiling executions were separate from timing samples.

  • External author test logs were unavailable; fresh tests replaced those summary-only claims. Third-party lint was not rerun locally.

  • Frozen CI remained pending. This is a partial Q29 improvement, not closure of the broader #27665 issue.

@XuPeng-SH
XuPeng-SH merged commit 3e38fc7 into main Oct 25, 2026
9 of 10 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/regexp-terminal-repeat-20261025 branch October 25, 2026 12:21
mergify Bot pushed a commit that referenced this pull request Oct 25, 2026
…ode (#31125)

### Root cause

MySQL 8.0 multiline (`m`) mode treats LF, CR, CRLF, NEL (U+0085), LINE SEPARATOR (U+2028) and PARAGRAPH SEPARATOR (U+2029) as line terminators, so `^b` matches after any of them. MatrixOne's `REGEXP_LIKE` / `REGEXP_INSTR` / `REGEXP_SUBSTR` / `REGEXP_REPLACE` recognized only LF and CRLF: `SELECT REGEXP_LIKE(CONCAT('a', CONVERT(0x0D USING utf8mb4), 'b'), '^b', 'm')` returned `0` where MySQL returns `1` (same mismatch for `INSTR`/`SUBSTR`/`REPLACE`, in both directions of position and replacement-byte semantics). The Unix-only `u` flag was and must remain LF-only.

### Exact changes

1. **Vendored backtracking engine** `pkg/sql/plan/function/internal/regexp2`: byte-pinned fork `github.com/XuPeng-SH/regexp2@718f43e031fe` (= dlclark/regexp2 v1.10.0 + fastclock patch, MIT; attribution and pre-rename SHA-256 inventory in `LICENSE`/`ATTRIB`/`PROVENANCE`). MatrixOne-owned additions: `linemode.go`/`linemode_test.go` (wide line-terminator classification, CRLF kept atomic, `\n` boundaries preserved for `mu`) and `errors.go`/`syntax/errors.go` (`errString`, required by the repository err-check gate). Upstream files carry line-policy fields so `^`/`$` assertion candidates honor the wide terminator set only when the MatrixOne multiline bit is set.
2. **Engine classifier** `pkg/sql/plan/function/internal/regexpclass`: routes each pattern to the pinned Go RE2 copy (`internal/regexp`) or to regexp2, with native line-policy fields; RE2-eligible patterns keep their existing engine and gain the wide terminator set through `internal/regexp/lines.go`. Anchored-prefix fast paths are preserved.
3. **Entry points** `pkg/sql/plan/function/func_builtin_regexp.go` + `regexp_icu.go`: the four SQL functions extend `m` to the full MySQL terminator set with original character positions and replacement bytes preserved; `mu` stays Unix-only. The engine timeout message stays byte-identical (`match timeout after %v on input %v`, detected by `regexp_icu.go`).
4. **Policy conformance**: vendored sources satisfy the repository's configured staticcheck/gofmt/ineffassign/unused policy, the err-check gate, and `gofmt -s`; `.licenserc.yml` exempts exactly the 23 upstream files individually (MIT retained, no Apache text stamped onto upstream sources).
5. **Design document**: `docs/design/20261024-30210-regexp-multiline-line-terminators.md` (Rev 11, SHA-256 `88b073910fb37bbc7cb7c5f931239e255116b348bb930a980a6d0d366763ec2d`). Design-first review was distinct and complete before implementation review: Rev 1-9 received design-stage REQUEST_CHANGES from the independent local reviewer (each finding verified against primary sources and live ICU 77.1 measurement, addressed per revision in the document change log), and Rev 10 (SHA-256 `5dcab7b28d863dbec65e003b5db3503fdbc3ee1c1374d4622e9ae737bf3315b4`) received the design-stage **PASS** on 2026-10-25 with no remaining blocking finding. Rev 11 is a status-record-only revision (design content identical to Rev 10 outside the Status paragraph, the new "Design review record" section and the Rev 11 change-log entry) that publishes the approval chain inside the document. Implementation-stage local reviews re-verified the invariant map against the code each round, retained the design PASS, and ended in approval; its two non-blocking P3 findings are addressed at this head (vendored-copy sync procedure + maintained-change inventory in `internal/regexp2/README.md`/`PROVENANCE`, unseen-spelling cache-bound assertions in `internal/regexpclass/review_fixes_round9_test.go`).
6. **Tests**: UT harness for the classifier/linemode mapping (28 tests), round 2-9 review regression suites, `regexp_multiline_test.go`, `regexp_wide_linesplit_review_test.go`, conformance suites against Go `regexp/syntax`; BVT rows added to `test/distributed/cases/operator/regexp_operator.test[.result]` and `test/distributed/cases/function/func_regular_like.test[.result]` covering all six separators x `m`/`mu` x all four entry points.

### Proof (issue -> test)

- Baseline red / fixed green: the 28-test harness fails on merge-base `6fb6531432aa` and passes on this tree (same tests, same commands).
- Live SQL behavior: 178/178 recorded checks on a running instance over all six separators (CR, LF, CRLF, NEL, LS, PS) x {`m`, `mu`} x {LIKE, INSTR, SUBSTR, REPLACE}, verifying exact positions and replacement bytes (`m`=1 for CR/NEL/LS/PS, `mu`=0 for them, LF/CRLF behavior unchanged).
- Independent oracle: 169 ICU 77.1 reference checks replayed by the local reviewer without disagreement.
- BVT (mo-tester against the patch build): all 66 failing cases in the broader run match the normalized baseline exactly; the new regexp cases pass.
- Regression/consistency: full `pkg/sql/plan/function` suite, regexpclass/regexp/regexp2 suites, and race-detector runs are green; scaling benchmarks on >1 MiB inputs and anchored-prefix patterns show no regression vs `main`.
- Delivery gates: configured `golangci-lint run -c .golangci.yml` on the affected closure reports 0 issues; `make err-check` passes; repo-wide `license-eye -c .licenserc.yml header check` reports 0 invalid files.

### Test commands

- `go test ./pkg/sql/plan/function -count=1` (cgo env) — full function suite incl. the issue harness.
- `go test ./pkg/sql/plan/function/internal/regexp/... ./pkg/sql/plan/function/internal/regexp2/... ./pkg/sql/plan/function/internal/regexpclass/... -count=1`.
- `go test -race` on the same closure (race belt) and package-level race runs for regexpclass.
- `golangci-lint run -v -c .golangci.yml <4 packages>` with the repository `CGO_CFLAGS` (golangci-lint 2.14.0, go1.27.1): 0 issues.
- `make err-check`: passes ("Does not find 'fmt.Errorf()', 'errors.New()','context.WithTimeout' and 'context.WithDeadline'").
- `license-eye -c .licenserc.yml header check`: 6877 files, 0 invalid.
- mo-tester BVT: `regexp_operator` and `func_regular_like` cases green; whole-run failures byte-identical to baseline after path normalization.

### Residual risks / notes

- The vendored engine is a maintained fork-in-tree: `PROVENANCE` pins pristine upstream hashes and enumerates every local change class; `README.md` documents the synchronization procedure so a re-vendor cannot silently drop the line-policy fields, assertion changes, or policy corrections.
- Behaviors outside the tested 6-separator x 2-mode x 4-entry-point matrix (exotic flag combinations, unusual encodings already routed to ICU) keep their existing semantics; the ICU oracle found no disagreement on the sampled space.
- Two `molint` informational observations remain (upstream Debug-only `fmt.Printf` in `runner.go`); the tool exits 0 and the Makefile line is non-gating. Kept deliberately to minimize upstream divergence.
- Open PR #30646 upstream supplies only a partial fix (regexp2-only paths); this PR covers all four entry points and the RE2 path as well.

### Rebase notes (2026-10-25)

`main` merged #31079 (`perf(regexp): skip terminal any-rune loops at EOF`), which restructured the unanchored loop in `internal/regexp/backtrack.go` (required-prefix admission before `bitState.reset`, prefix re-scan at the loop bottom, `markEndTextRepeats` EOF classification) and conflicted with this PR's CRLF-interior start suppression. The conflict was resolved semantically: upstream's loop structure is kept, and this PR's guard (`lineMask && crlfBetween(i.context(pos))`) now wraps the candidate match attempt inside the restructured loop — the same form as the NFA-path guard in `exec.go`. The upstream optimization is orthogonal: it classifies only `InstRuneAny`/`InstRuneAnyNotNL` loops that accept at `EmptyEndText`, and the wide line modes change line assertions only, never consuming instructions, so both changes compose without interaction.

Post-rebase validation on the delivered head `379e87f1e0` (base `9dcd26be43`, includes #31079): `go build ./pkg/sql/plan/function/...` exit 0; `go test -count=1` green for `internal/regexp` (7.962s, incl. upstream #31079 `backtrack_test.go` and this PR's `lines_test.go`), `internal/regexpclass` (4.709s) and `internal/regexp2` (2.995s); `go test -count=1 -run 'Regexp|REGEXP' ./pkg/sql/plan/function/` green (15.940s, incl. upstream `regexp_regular_engine_test.go` and this PR's multiline/line-split/review-round suites).

Approved by: @XuPeng-SH

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/enhancement kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants