Skip to content

fix(python-sdk): unify query contracts and atomic manager operations - #31262

Merged
XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/python-sdk-quality-20261026
Oct 26, 2026
Merged

XuPeng-SH merged 15 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/python-sdk-quality-20261026

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 26, 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:

Closes #30242
Closes #31202
Closes #31203
Closes #31204
Closes #31205
Closes #31206
Closes #31207
Closes #31208
Closes #31209
Closes #31210
Closes #31211
Closes #31212
Closes #31213
Closes #31214
Closes #31215
Closes #31216
Closes #31217
Closes #31218
Closes #31219
Closes #31220
Closes #31221
Closes #31223
Closes #31224
Closes #31225
Closes #31226
Closes #31227
Closes #31228
Closes #31229
Closes #31230
Closes #31231
Closes #31233
Closes #31234
Closes #31235
Closes #31236
Closes #31238
Closes #31240
Closes #31242
Closes #31243
Closes #31244
Closes #31245
Closes #31246
Closes #31247
Closes #31248
Closes #31249
Closes #31251
Closes #31252
Closes #31253
Closes #31254
Closes #31255
Closes #31258
Closes #31259
Closes #31260
Closes #31241
Closes #31263
Closes #31266
Closes #31267
Closes #31276

Related to #30067 and #30069; this does not claim completion of their broader scope.

What this PR does / why we need it:

The Python SDK had divergent sync/async SQL construction, incomplete transaction ownership and manager APIs that could silently return incorrect data or partially apply batches. This consolidates those boundaries and adds native-result, failure, cancellation and dependency-version contracts.

  • Share typed SQLAlchemy bind compilation, boolean grouping, alias handling and snapshot validation. Preserve main's UPDATE/DELETE ORDER BY and LIMIT behavior, including LIMIT 0. Reject unsupported ambiguous forms before execution.
  • Retain direct legacy Query execution and mapped attribute/projection results. Resolve one schema/table/alias target for SELECT, UPDATE and DELETE, including async sessions; reject conflicting database targets and unsupported joined mutations before dispatch. Preserve recursive CTE intent, expose AsyncClient.export and allow safely rendered fulltext SQL to compose through exports and logical_in.
  • Preserve native Decimal binding and render Decimal literals as bounded fixed-point tokens, keeping adjacent high-precision values distinct in read/update/delete predicates; reject excessive exponent expansion before formatting.
  • Establish explicit server transactions and pool-owned physical connection initialization. Preserve cancellation and primary errors during rollback, close and scoped fulltext-setting restoration. Fix aiomysql pre-ping on SQLAlchemy 2.0.43.
  • Make Pinecone batches validate before mutation and execute atomically; require an unambiguous primary key. Correct vector metric selection, numeric values, metadata and duplicate result labels.
  • Correct snapshot/publication/Stage/PITR catalog readback, LOAD option propagation, reflected index parsing and metadata aggregation. CSV relations detect changed observed schemas; LOCAL INFILE now requires explicit opt-in.
  • Make public fulltext group() emit one required positive OR group; reject branch structures that cannot preserve membership. Check each mapped server file using bounded DATALINK reads at construction, before scanning, at true stream EOF, and before import commit.
  • Isolate capability observations per connection generation. Treat version banners as descriptive rather than assuming feature support. Remove duplicated async snapshot implementation and unsafe transaction examples.
  • Replace global dependency mocks with real dependency contracts, add a runner that rejects skipped/empty required suites and records provenance, and retain SQLAlchemy compatibility coverage; workflow configuration is delivered separately. Core installation remains independent of Arrow.

Validation

  • Offline suites rerun after the SQLite fixture correction: SQLAlchemy 1.4.54: 1958 passed, 2.0.43: 1954 passed, 2.1.6: 1962 passed, each with 95 passing subtests, zero skips. The documentation regression parses the AsyncSession examples in README.md, README_USER.md and docs/quickstart.rst, and rejects the prior same-session asyncio.gather(session.execute(...)) pattern.
  • MatrixOne 4.2.5 (git_version=1a44f3d): 70 required native contracts passed, zero skips. Source server v20261026, actual binary 305be60 built from main 83c1e23: 70 passed, zero skips. Later kernel merges were not rebuilt or claimed as tested.
  • Portable execution reports record the source/test/config fingerprints, observed server identities, exact test selections and native JUnit results for the implementation before the final documentation correction. The final change adds only three documentation examples and one offline AST test; it does not modify SDK runtime code. The complete offline matrix above was rerun again after the SQLite fixture correction described below.
  • Native assertions cover exact exported rows, recursive CTE results, legacy projection mapping, schema-qualified writes, async client/session database isolation, rejected joined writes, safe fulltext composition, mapped-file completion and EOF/precommit rollback. Pool ownership and connection reuse are checked after failures.
  • Changed Python Black checks, whole-SDK fatal flake8 and four shared-helper mypy checks passed. The changed literal helper has the same two pre-existing Optional-iterator mypy diagnostics as the clean baseline, with no introduced findings. Wheel/sdist build and twine checks passed. Earlier clean Python 3.8/3.9 core import checks without Arrow apply to the unchanged import graph.
  • Python has no Go-style race detector; no Go files change. Deterministic async cancellation, physical close-once, atomic rollback, error precedence and pool-reuse tests cover the existing lifecycle mechanisms across the three SQLAlchemy versions.
  • The 57 linked issues were audited individually against concrete regression assertions: 186 issue-to-test references across 115 distinct JUnit case IDs were checked against the three final offline reports and both native reports, with zero missing references and no failures/errors/skips for the mapped cases. Shared cases cover related issue triggers; this does not mean 57 independent test suites. [Bug]: Python SDK metadata.scan exposes MIN/MAX/SUM but wildcard scan always returns NULL #31246's initial ZoneMap behavior is covered, while its ALTER+UPDATE/CLONE statistics variants are not individually exercised. [Bug]: Python SDK selects the wrong vector index on multi-vector-column tables #31223's offline case distinguishes IVF/HNSW ownership, but native vector cases cover two IVF indexes rather than native HNSW.
  • Prior-head GitHub CI for 5fbb1bc564aefc1f9059236646fe61faef32019e completed successfully (run): all six Python SDK offline matrix jobs, CI preflight and CI Required passed. Online/native and kernel/coverage jobs were skipped by SDK-only routing; the separate Iceberg adapter tidy job passed, while Iceberg E2E Local was skipped. The retained local native JUnit reports predate the documentation and SQLite fixture corrections; neither correction changes SDK runtime or native tests. CI for the updated head is pending.

Review correction: portable schema-routing oracle

The legacy Query.first() retains LIMIT 1. Reusing that Query for an UPDATE made the schema-routing offline test depend on SQLite's optional ENABLE_UPDATE_DELETE_LIMIT extension. The mutation now uses a fresh legacy Query, preserving every schema-routing, row-value, default-table isolation and deletion assertion. MatrixOne UPDATE/DELETE LIMIT semantics remain unchanged.

  • Before correction: reproduced the sync failure on Python 3.11.14 / SQLite 3.50.4 without the extension; async control passed.
  • After correction: complete offline suites on SQLAlchemy 1.4.54 / 2.0.43 / 2.1.6 passed with 1958 / 1954 / 1962 cases, respectively, plus 95 passing subtests per suite; zero failures/errors/skips. Existing mutation LIMIT/order and lifecycle/cancellation cases remain included.
  • Incremental static checks: repository Black configuration and fatal flake8 (E9,F63,F7,F82) passed for the changed test module. No Go code changes; Go race is not applicable, and Python has no equivalent Go race detector.
  • Reused native evidence was reconciled against all 214 recorded source/test/config inputs before this correction; the only changed input afterward is this offline test. No new server qualification or throughput improvement is claimed. The repair adds one ordinary test-only Query object and no service, I/O or additional test case.

CI routing

This PR changes only clients/python/**. The SDK workflow configuration enhancement is split into supporting CI PR #31265, so the existing trusted classifier selects scope=sdk and omits kernel UT/BVT/coverage. The new AsyncSession documentation regression is under tests/offline; the existing issue contract tests remain under tests/offline/contracts and tests/online, selected by the existing trusted SDK workflow. The supporting CI change also filters the independently triggered Iceberg workflow; that filter only takes effect after it enters the trusted base.

Compatibility and cost

Decimal literal expansion is capped at 4096 characters before allocation. The native report records a 4.2.5 limitation for some 38-fractional-place literal values; no SDK workaround changes server semantics. Both native release and source targets are tested explicitly; these results do not imply support for every historical MatrixOne release. LOCAL loading now defaults off. Invalid/ambiguous IDs, metric names, duplicate vector labels, conflicting explicit database targets, joined UPDATE/DELETE and unsupported snapshot/fulltext syntax raise instead of silently producing misleading results. Stage ALTER IF EXISTS returns None when absent.

Vector metadata is refreshed with two reads per query. Explicit per-column metadata statistics require sequential scans proportional to the observed column count; wildcard metadata retains its fast path. Upsert performs whole-batch validation before its transaction. CSV inference is bounded and cannot guarantee an immutable file after validation. Submitted COMMIT outcomes are not retried or represented as guaranteed rollback. Details and reproduction commands are in clients/python/TESTING.md and the design documents.

Mapped file checks add O(number of explicit files) bounded reads per validation point and reuse the active stream/write connection. They require native DATALINK read permission and do not pin object versions. A removed-and-restored file between checks may evade detection; emitted stream batches cannot be retracted after a terminal error. Unsupported URI/glob forms raise before execution. Fulltext group() supports positive word/prefix branches; conjunction/exclusion/phrase/nested branches are explicitly rejected.

@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 26, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 46c106fa153d9fc4cc0ce0767fc1d5119e5491d7

PR head changed during fetch

This was referenced Oct 27, 2026
XuPeng-SH added a commit that referenced this pull request Oct 27, 2026
…1322)

## What type of PR is this?

- [x] API-change
- [x] BUG
- [x] Improvement
- [x] Documentation
- [ ] Feature
- [x] Test and CI
- [x] Code Refactoring

## Which issue(s) this PR fixes:

Closes #30963
Closes #31023
Closes #31312
Closes #31314
Related to #30067, #30068, #30069 and #31262.

## What this PR does / why we need it:

Unify Python SDK execution and SQL construction across MatrixOne 4.1.x
and 4.2.x. Immutable snapshot Selects remain cache-keyed through Client,
Session and export compilation, including caller caches warmed before
engine adoption. Preserve the caller's driver, dialect, pool and typed
results. Shared-engine adoption preserves supported SQLAlchemy 1.4
string execution. Compiler-owned late snapshot literals preserve
percent/placeholder-like names, avoid caller parameter collisions, and
prevent execution arguments from replacing snapshot identity. Raw/export
compilation preserves escaped parameter names and their type processors
across SQLAlchemy versions.

Explicit configuration overrides take precedence over invalid
lower-priority environment values. Buffered fetch sizes cannot rewind
cursors and retain integer-index compatibility. Administrative
managers/builders share identifier and grammar-string construction;
metadata booleans, fulltext LIMIT 0, native error sources/errno and
async user cleanup preserve their public contracts.

Clone managers verify target existence after acknowledgement on the same
executor. Safe manager `if_not_exists=True` uses a catalog observation
and plain CLONE because native CLONE IF NOT EXISTS can append duplicate
data. The catalog check now preserves exact names for
`lower_case_table_names=0` and uses binary comparisons, so an existing
`target` no longer makes an absent `Target` a successful no-op. Released
servers can still lowercase a CLONE internally in mode 0, so a
conflicting sibling may result in a native error; the SDK propagates it.
In mode 2 a successful native clone can be followed by a failed `SHOW
CREATE` verification for mixed-case names; the SDK reports this instead
of claiming success. Raw builders reject the unsafe flag. Session
retains transaction/rollback ownership; async clone phases share one
timeout. This costs two statements ordinarily, three for a missing
target with the safe flag, and one for an existing-target no-op.
Snapshot compilation adds one bounded compiler-owned literal and no
network roundtrip; no throughput improvement is claimed.

Validation of the delivered source:

- Python 3.12.12 complete offline suites: SQLAlchemy 1.4.54 / 2.0.43 /
2.1.6 passed **2195 / 2191 / 2199** tests, plus **95 subtests each**,
with zero failures/errors/skips. Includes deterministic async
cancellation and execution ownership, as well as the explicit
disposable-server opt-in guard.
- Isolated native **4.1.0 and 4.2.6**, **48 clone cases each**, zero
failures/errors/skips. These cover three naming modes, sync/async
Client/Session, database and qualified/unqualified table names,
differently cased schema and table names, existing-target no-op, native
conflict propagation, successful lowercase and mode-1 mixed-case clones,
rollback and single-connection pools. Independent native probes exercise
Unicode, escaped lookup literals and native CLONE controls.
- The earlier **782 native cases on 4.1.0–4.1.6 and 4.2.0–4.2.6**
qualified the previous source. The rebase changed no SDK or SDK-workflow
inputs; that evidence remains relevant to unchanged boundaries, while
clone behavior was revalidated as described above. [Earlier
qualification](https://gist.github.com/XuPeng-SH/0329a8729ef9194c9e325f0ddd9178bf).
- Changed-file Black, configured fatal flake8, syntax and diff checks
pass. Changed-runtime-file mypy reports **458 diagnostics versus 460 on
the merge base**, with no introduced path/message/code finding.
Wheel/sdist build and twine checks pass; all 56 shipped Python modules
match the tested source.
- `gpt-6.1-sol/xhigh` design and final overall review completed with no
unresolved material blocker. No Go code changed; Go race detection is
not applicable.

Current source hashes, dependencies, native release identities, test
results and per-case JUnit: [validation
evidence](https://gist.github.com/XuPeng-SH/b52035e12a1d99564cf757f919621757).

Hosted checks must run on the new head; previous hosted results apply
only to `36721e73cf`. Full native server contracts require
`MO_SDK_DISPOSABLE_SERVER=1` and a serial, exclusively owned disposable
server or tenant because the case-mode tests temporarily change a
tenant-global setting. Standalone qualification excludes optional
TLS/S3/HNSW, multi-CN, async Arrow and the baseline unsupported direct
`matrixone://` DBAPI entrypoint. Native Stage/fulltext limitations
remain narrow native-versus-SDK negative contracts. The separate
existing analytics suite is outside this release certification.
mergify Bot pushed a commit that referenced this pull request Oct 28, 2026
…31524)

The escaping parts of #31384 are already fixed on `main` (#31262 for `metadata_scan` and #31322 for `_build_moctl_sql`; see the issue comment). This PR fixes what is left: expected behavior #2, a non-JSON `mo_ctl` reply.

**Root cause.**
1. `_execute_moctl` (sync in `moctl.py`, async in `async_client.py`) called `json.loads(result_str)` directly. On a plain-text reply it raised `MoCtlError("Failed to parse mo_ctl result: Expecting value: line 1 column 1 (char 0)")`, and the server's actual output was lost.
2. A `MoCtlError` raised inside the `try` block (no rows, or a `returnStr` other than `OK`) was caught again by `except Exception` and re-wrapped, so the message read `mo_ctl operation failed: mo_ctl operation failed: table not found`. In the async manager the same re-wrap also hid the JSON error behind the generic prefix.

**Fix.**
- New `_decode_moctl_result()` in `moctl.py`, shared by both managers. On non-JSON it raises the manager's own `MoCtlError` class: the sync manager uses `matrixone.moctl.MoCtlError` and the async manager uses `matrixone.exceptions.MoCtlError`, as before.
- The error message includes a raw-output preview (capped at 500 chars). The full text is available as `error.raw_output`.
- `except MoCtlError: raise` lets SDK errors pass through unwrapped. Other exceptions are still wrapped as before.

**Tests** (`tests/offline/test_moctl.py`):
- `test_execute_moctl_non_json_keeps_raw_output`: a sync plain-text reply keeps the raw text in the message and in `raw_output`.
- `test_async_execute_moctl_non_json_keeps_raw_output`: the same check for the async manager.
- `test_execute_moctl_failed_return_str_is_not_double_wrapped`: the message is exactly `mo_ctl operation failed: table not found`.

**Results:**
- Before the fix, all 3 new tests fail (the actual message was `mo_ctl operation failed: mo_ctl operation failed: table not found`). After the fix, all 3 pass.
- `test_moctl.py` + `test_moctl_simple.py`: 26 passed.
- `pytest tests/offline` (Python 3.13, run locally): 2289 passed, 95 subtests passed.
- `black --check` is clean. `flake8` reports no new warnings (4 before, 4 after; all are existing unused imports in `async_client.py`).

3 files, +61/-9.

本操作由 LW 授权的 Grok Bot 智能体执行

Approved by: @XuPeng-SH
XuPeng-SH added a commit that referenced this pull request Oct 28, 2026
## What type of PR is this?

- [x] Improvement
- [x] Code Refactoring
- [x] Test and CI
- [x] Documentation

## Which issue(s) this PR fixes:

Follow-up to #29947 and the changes in #31020, #28987, #31000, #30054
and #31262.

## What this PR does / why we need it:

`cumrank` rescanned the partition prefix for every output row, while
wide constant-width `mrank` repeatedly scanned its frame. Use a
compressed frequency index that starts at the current output demand and
grows geometrically. This reduces repeated comparisons without indexing
the entire partition before the first result. Rebuilds seed the active
physical frame, preserving NULL, NaN, tie and eviction semantics.

The index is optional and accounted. Capacity rejection falls back to
scanning; if required output allocation runs out of capacity, release
the index and retry the same fixed-width append once. Cancellation and
invalid-account errors still propagate. Completed partitions, reset and
free release the index. Small/variable widths and all-NULL partitions
retain scan paths; `tmrank` retains its civil-time semantics.

Also share the SORT ROLLUP type capability between planner and executor,
consolidate Python identifier quoting while preserving API behavior, fix
test-helper cleanup on error, correct the Decimal64 DISTINCT benchmark's
group distribution and repeated-hit workload, and replace review-history
transcripts with links. Existing inexpensive small-input oracle tests
remain.

[Design and execution/memory contract at this
revision](https://github.com/matrixorigin/matrixone/blob/e4fb331b5229b52ef8613151e083c8e7dbe1966c/docs/design/20261023-local-sliding-window-ranks.md).

## Validation

- Full Window package tests and full package race run passed.
Regressions cover output-budget fallback, later-batch pressure, failed
retry, cancellation, sealed accounts, reset/reuse, short/NULL prefixes
and frame seeding across growth.
- Focused ROLLUP planner/executor, Decimal64 and nonempty colexec mock
lifecycle race checks passed; unchanged-path evidence remains
applicable.
- Incremental `go vet`, configured golangci-lint v2.14.0 and molint
passed for affected Go packages. Golangci reported no new issues; molint
emitted only pre-existing diagnostics on unchanged source.
- Python SQL parameter/identifier boundary suite: 105 passed.
- Isolated single-CN SQL smoke through the real MySQL frontend: 8,205
rows with NULLs and ties; cumulative and width-128 ranks matched an
independent row-by-row oracle across output-batch growth.
- Same-host baseline/candidate microbenchmarks used the same harness and
native build, GOMAXPROCS=2, three one-operation samples. Medians against
the merge-base implementation:

| Workload | Baseline | This PR |
| --- | ---: | ---: |
| 1M rows, mrank width 128, first output | 17.64 ms | 4.56 ms |
| 1M rows, mrank width 128, full consumption | 2,174 ms | 1,329 ms |
| 1M rows, cumrank, first output | 505.95 ms | 4.41 ms |
| 16K rows, cumrank, full consumption | 2,069.90 ms | 7.91 ms |

Width-127 scan control remained approximately 32 ms. These are
microbenchmarks, not production workload results. Geometric rebuilding
raises total allocated bytes for full 1M-row width-128 consumption from
about 41.7 MB to 91.9 MB; first-output allocation is about 8.86 MB
versus 8.65 MB. These figures are cumulative allocation, not peak
memory. Full 100K-row all-NULL cases were approximately 0.6–0.9 ms
slower.

Input remains materialized. Variable-width/time-based rank scans,
explicit-frame weighted percentile, and ROLLUP state reuse remain
separate follow-ups. Distributed BVT was not run locally; CI for the
updated head is pending.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment