Skip to content

feat: add C02 bounded encoding codec foundation - #29750

Merged
mergify[bot] merged 13 commits into
matrixorigin:mainfrom
ck89119:issue-29481-encoding-main
Oct 10, 2026
Merged

mergify[bot] merged 13 commits into
matrixorigin:mainfrom
ck89119:issue-29481-encoding-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 8, 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 #29481. Foundation batch only; this PR does not close the issue.

What this PR does / why we need it:

Implements the independently deliverable codec foundation from the merged C02 design (#29651, f6c86c9c0452db27af1b0c9aceff1aa5b96aabad, sections 3.1 and 5).

  • Add pkg/common/collation/encoding using the existing charset enum. Keep repertoire validation separate from byte-preserving identity, connection/result replacement, and target-specific binary-source CONVERT behavior (invalid UTF-8 → NULL; ASCII high-bit bytes → ?).
  • Compute exact output size before an accounted MPool.Alloc; bound output by the caller limit and allocator maximum, check cancellation at bounded scan/allocation/publication boundaries, and release every untransferred allocation on failure.
  • Reuse the codec in the existing CONVERT evaluator without opening new SQL charset admission. Preserve binary bytes, NULL/empty distinctions, constant arguments, selection lists, and utf8/utf8mb3 → utf8mb4 compatibility. Inline vector values do not consume external-area budget.
  • Add 203 actual MySQL Community 8.4.11 wire observations, an exclusive-output recapture probe, and offline request/row-packet pairing checks. Cover malformed continuation bytes versus incomplete source sequences, not just generic invalid UTF-8.

Scope deliberately not activated

No default, persisted collation identity, key format, session migration, handshake, prepared binding, or result protocol changes. ASCII conversions are internal helpers only: ASCII session/SQL admission remains unchanged. Strict utf8mb3 is validation-only; GBK and new comparison domains remain disabled.

Follow-up C02 batches still need atomic session tuples and statement staging, literal/prepared source-domain propagation and candidate binding publication, all result/metadata consumers, and the applicable ASCII client/results upgrade/release gates. This foundation is not full issue acceptance.

Validation

Current implementation revision: 90b5bf4a2d6e305e11b9220fc034a95c8b84fb39, merged with mo/main at 0ccc989731f9c2b40d31554a44ca505c656c0e62.

Latest CI correction (90b5bf4a2d): run 37956564665 passed shared build, SCA, native checks, and Proxy/Pessimistic BVT, but failed two independent UTs. The cgroup watcher now joins an already-started cancellation File.Close before its task drains; a second Close alone cannot prove the first close completed. TestExporter now awaits collector completion of both asynchronous raw-histogram batches before gathering/restoring global configuration. It retains all original 4-send/14-sample/clock/buffer-capacity assertions; production histogram dispatch remains asynchronous.

  • Go 1.27.1 / real Linux arm64 / CGO: the unchanged cgroup baseline reproduced the exact FD 0→1 failure under race ×1000. Fixed cgroup watcher tests under race ×1000, full owning system race/vet, and short/matrixone_test coverage-set mode pass. Linux pinned v2.14.0 incremental lint: 0 issues.
  • Go 1.27.1 / darwin arm64 / repository CGo wrapper: exporter race ×1000, full owning mometric race/vet and short/matrixone_test coverage-set mode pass. The exporter CI failure was not reproduced by the old Mac stress; its asynchronous ordering assumption is removed with a completion barrier, not sleeps/retries or weaker assertions.
  • After the latest main merge, codec/evaluator owning tests with -count=1 -vet=all pass again. Host pinned lint over the complete changed Go package closure reports 0 issues. Linux tests used a test-owned auto-removed container; existing services were untouched.
  • New-head CI is pending. Prior-head BVT/native/SCA success and historical performance evidence below are revision-qualified, not a claim that new-head CI has passed.

Review performance correction (d950b1d344): a shared, stack-local borrowed CONVERT scope consolidates small-value cancellation checks across a single evaluator batch. It checks before the first actual value, within 4096 cumulative input bytes (empty values count as one), during large UTF8 scans, and before result publication. Per-value caller/allocator limits remain enforced. Single-value Convert reuses the owner and immediately finishes; ASCII replacement/allocation ownership and public charset admission are unchanged. The evaluator does not implement independent charset semantics.

  • At the performance-correction revision, codec/evaluator owning UT with -count=1 -vet=all, codec owning race, allocation-cleanup/publication race ×100, and pinned v2.14.0 incremental lint passed. All 203 offline MySQL observations and existing NULL/const/selection/compatibility oracles remain green. A public RunFunctionDirectly control proves cancelled publication returns no vector and frees its staged result back to the MPool baseline.
  • Controlled 128×8-byte evaluator benchmark, Go 1.27.1 / darwin arm64 / Apple M1 Pro, five 500ms samples: pre-fix medians binary 7628 and UTF8MB4 14050 ns/batch; fixed medians 3720 and 4621 (about 51%/67% lower), with 0 B/op and 0 allocs/op.
  • Exact d2a0055ebe base evaluator versus fixed evaluator in one binary, identical prebuilt inputs/constant target/reset: medians base 3227/4084 versus fixed 3618/4662 ns/batch. Approximately 12%/14% residual local CPU overhead remains for bounded cancellation/output-budget guards; this is not a zero-overhead or end-to-end throughput claim. The actual evaluator benchmark is committed; the temporary old evaluator copy is not.
  • New-head CI is pending; the preceding head's successful CI is not claimed as validation of this change. No new service/BVT run is claimed.

CI correction (4b63d5890e): run 37892718308 failed before BVT/coverage execution: published Go 1.27.0 images inherited GOTOOLCHAIN=local despite go.mod requiring 1.27.1, and native dependency downloads exhausted retries on HTTP 504. CPU source-build stages now explicitly allow go.mod-directed toolchain selection. The existing immutable, SHA256-verified HTTPS ONNX media fallback also handles curl HTTP failures (22), not only timeouts (28). No Go minimum, image tag, SQL expectations, workflow permissions, or coverage gate is weakened.

  • New regression controls fail against the pre-fix recipes/downloader and pass after the correction. Full downloader tests cover native/legacy retries, HTTP fallback success, absent/exhausted fallback, corrupt/oversized payload rejection, cleanup and unchanged destinations. All four Docker/cache seed contract tests and the native build contract suite pass.
  • Actual primary and media endpoint downloads independently match the pinned Linux x64 ONNX checksum. A test-owned cached Linux/arm64 Go 1.26.4 image automatically selected and ran Go 1.27.1 with the current module; this is a stale-toolchain control, not a full CI-image or Docker build claim.
  • At the CI-correction revision, codec/evaluator owning tests with -count=1 -vet=all passed using Go 1.27.1 / darwin arm64 and the repository CGo wrapper. The later performance correction is independently validated above; do not substitute the old revision's evidence for new-head CI.

Historical P2 correction and revision-qualified foundation evidence (dc4bfb36ef): binary→ASCII CONVERT replaces each high-bit source byte rather than returning NULL. The new wire direction reproduces the previous failure; 29 binary→ASCII observations and empty/7f controls bring the fixture to 203 cases. All previous 162 records remain byte-for-byte unchanged. Target UTF8MB4 still returns NULL for invalid binary input. Ownership, byte-unit replacement, budget and cancellation controls were added.

  • Go 1.27.1 / darwin arm64, repository CGo wrapper and verified worktree native build.
  • Normal owning-package tests with -count=1 -vet=all: ./pkg/common/collation/... and ./pkg/sql/plan/function passed. Codec statement coverage is approximately 99%; CONVERT helper coverage is approximately 91%.
  • Focused allocation/cancellation/ownership race tests, 100 repetitions of the failure-cleanup test, and the codec owning package under -race passed. Their relevant code/dependencies are unchanged by the main merge.
  • Repository-pinned golangci-lint v2.14.0 incremental checks: 0 issues; gofmt and diff checks passed.
  • The initial foundation at fedbf870c987d6c624e5d8a2a7db11e525d6da96 passed make -j8 build. Subsequent corrections have linked owning-package validation as documented above; a new service build is not claimed.
  • At that initial foundation revision, existing public-path BVT in normal comparison mode: function/func_cast.test (252/252), charset_collation/charset_collation_basic.sql (297/297), and charset_collation/charset_collation_errors.sql (207/207), each twice on the same clean test-owned standalone instance after SQL and ISCP readiness. Teardown postconditions were checked. Those foundation runs used isolated ports rather than interfering with an existing service on port 6001. The P2 correction has no new BVT: ASCII SQL admission remains disabled and the evaluator still uses only binary/UTF8MB4 targets, whose owning tests passed after the fix and main merge.
  • Two independent final oracle captures matched exactly. Ordinary codec UT is offline and does not require MySQL.
  • Codec benchmarks include borrow, validation, and ASCII replacement paths; no end-to-end performance improvement is claimed. Native mpool allocation is not reported as Go heap bytes by benchmem.

No BVT expected result, workflow, generated production file, or dependency was modified. CI is not yet verified.

@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 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep review of 90b5bf4 against declared base/merge-base 0ccc989: APPROVE. Reviewed all 15 changed files and the prior review thread. No remaining blocking finding; the previous P2 CONVERT performance finding is substantively addressed.

Design and ownership: the approved C02 design in #29651 explicitly permits a codec foundation before session/prepared/result-protocol activation. This change keeps SQL charset admission in its existing resolver and conversion semantics in the codec. BorrowedConvertUsing is a stack-local sequential-batch owner shared by the evaluator and single-value Convert, not a persistent state machine or a second semantic implementation. The added state pays for amortized cancellation checks without giving up the output limit or publication check. Strict MB3 validation and internal ASCII conversion remain within the approved foundation; this does not close all of #29481.

Prior comment closure and performance: independently compared the unchanged base evaluator body with the current evaluator in one binary, using the same prebuilt vectors, constant charset, reused result buffer, 128 rows of 8 bytes, and five 500ms samples on Go1.27.1/Darwin arm64/Apple M4. Medians: binary 2804 -> 3084 ns/batch (+10.0%); UTF8MB4 2982 -> 3231 ns/batch (+8.4%). Both arms remain 0 B/op and 0 allocs/op. The previous 2.09x/3.29x regression is gone. The remaining approximately 2 ns/row buys explicit output bounds and bounded cancellation and is proportionate here. This is an evaluator microbenchmark, not a measured TP/prepared-statement throughput result; prepared executions containing CONVERT still use this evaluator. No new connection or prepared-protocol codec activation occurs.

Correctness and adversarial closure: traced SQL resolution -> evaluator -> codec -> vector append -> public result/error cleanup. Checked cumulative 4096-byte cancellation boundaries, empty values, invalid UTF8 becoming NULL versus cancellation remaining an error, large UTF8 chunks, partial masks/NULLs, constant and per-row targets, inline/external varlena limits, and final publication. The single-value API uses the same borrowed owner. Allocation failures and cancellation after allocation release untransferred output; RunFunctionDirectly discards staged vectors and restores pool usage on error. The unchanged 203 MySQL wire cases and capture helper retain the independently verified provenance from the previous review; no live recapture was needed or performed.

Additional CI-fix closures: the cgroup watcher now makes task completion wait for the actual AfterFunc close when its callback has started. Traced Stopper cancellation/task draining and Go's pollable-file Close/Read reference release: Close wakes the read, the read releases its reference before the task defer waits, and the callback closes closeDone independently. Setup failures and rejected tasks still close their FD; normal-return and cancellation paths have one effective close owner. One channel per watcher adds no growing state or TP hot-path cost. The histogram test waits for both asynchronous batches to pass the collector before restoring global configuration; no later producer operation reads that configuration. Four sends, fourteen samples, clock and capacity assertions remain intact.

Validation: repository-provenance native build completed; exact-head codec owning tests and all selected CONVERT evaluator/return-domain tests passed with count=1 and vet=all. TestExporter passed under race, count=100. Docker seed contract: all 4 tests passed. Full downloader suite passed, including both retry engines, HTTP fallback, corrupt/oversized response rejection, unchanged destinations and cleanup. HTTPS, immutable checksums, byte/time/retry bounds and atomic publication remain owned by the existing downloader. Exact-head ALL CI run 38022106429 is completed/success, including Linux UT/coverage and enabled proxy/compose BVT; Linux watcher execution evidence is reused from CI and the revision-qualified author validation, not claimed as a local Darwin execution. Skipped jobs are not counted as evidence.

Incremental quality: implementation +343/-18 across 8 files; tests/oracle/probe +957/-7 across 7 files; documentation delta 0. Reviewed these separately. Shared fixtures and the existing wire probe avoid duplicate setup; new cases prove limits, cleanup, semantic boundaries and real public-result publication rather than only helper internals. The unrelated CI repairs are small, separately committed and have concrete failure owners. No obsolete per-row generic conversion path or duplicated charset admission remains in the changed consumer. The sole prior inline review finding is resolved; no additional substantive comment remains open. Reviewer-only benchmark source/logs are retained locally, its temporary source was removed, and no production edits or subagents were used.

@mergify mergify Bot added the queued label Oct 10, 2026
@mergify

mergify Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-10 05:23 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-10 06:38 UTC · at 888e1ea4469b6c2bf7a23c31f3376654cb8a30cc · squash

This pull request spent 1 hour 15 minutes 55 seconds in the queue, including 1 hour 15 minutes 38 seconds running CI.

Required conditions to merge

This branch was previously deployed

1 inactive deployment
ci — ad76be30 Deployed Oct 10, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature kind/refactor Code refactor kind/test-ci size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants