Skip to content

fix(python): unify SDK execution contracts across 4.1.x and 4.2.x - #31322

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/python-sdk-release-quality-20261026
Oct 27, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/python-sdk-release-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 #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.
  • 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.

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.

@XuPeng-SH
XuPeng-SH requested a review from aptend as a code owner October 26, 2026 18:40
@XuPeng-SH XuPeng-SH self-assigned this Oct 26, 2026
@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 →

@mergify mergify Bot added kind/bug Something isn't working kind/enhancement kind/documentation Improvements or additions to documentation kind/test-ci kind/refactor Code refactor kind/api-change labels Oct 26, 2026
@XuPeng-SH

XuPeng-SH commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 51ba12003555bd59f6daa1b540dd191cde861620

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: 51ba12003555bd59f6daa1b540dd191cde861620

Assessment: request_changes

Reviewed the complete 40-file delta. Centralized compiler/cache handling and same-executor clone phases have sound responsibility ownership, but two reproducible compatibility defects remain. Required native release evidence also cannot be reconciled to this candidate. Both frozen discussion items are informational; there are no substantive prior findings or rebuttals.

Model: gpt-6-astra / xhigh

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

  • P2 clients/python/matrixone/sqlalchemy_ext/dialect.py:267: Adopt a shared MySQL engine with Client.from_engine under supported SQLAlchemy 1.4, then call connection.execute('SELECT 1').
    Impact: The new before_execute listener receives a supported legacy string and raises AttributeError when reading statement._annotations. Existing caller SQL stops working after SDK adoption. Pass non-ClauseElement inputs through unchanged and add a regression test.
    Evidence: legacy-adoption-contract.py reproduces success before public Client.from_engine and AttributeError("'str' object has no attribute '_annotations'") afterward; TextClause and exec_driver_sql controls pass. Uses real SQLAlchemy 1.4.54 with a deterministic DBAPI transport fixture. Log: legacy-adoption-contract.log; receipt: checks/1793041709572372548-3.json.

  • P2 clients/python/matrixone/sqlalchemy_ext/dialect.py:212: Execute a typed Select.with_snapshot('snapshot%name') or Select.with_snapshot('snapshot%%name') through the PyMySQL-backed Client/Session path.
    Impact: Snapshot text is inserted after MySQL compilation without dialect-specific percent escaping. PyMySQL raises ValueError for the first name and silently changes the second to 'snapshot%name', potentially addressing a different historical snapshot. Escape the inserted token for the active DBAPI while preserving raw/export SQL semantics.
    Evidence: snapshot-entrypoint-contract.py confirms both behaviors through Client.execute and Session using real SQLAlchemy/PyMySQL formatting with a transport fixture. driver-percent-contract.py covers bound/unbound statements and passing raw/export controls. Logs: snapshot-entrypoint-contract.log and driver-percent-contract-final.log; receipts: checks/1793041764952381596-3.json and checks/1793041639298354794-2.json.

  • P2 clients/python/docs/design/release-quality.md:97: Qualify the changed snapshot, administrative SQL and multi-statement clone contracts across the documented 4.1.x/4.2.x release matrix.
    Impact: Validation requirement: provide traceable current-input native results before approval. The author reports 785 native cases, but corresponding artifacts are absent from the frozen evidence. Attach existing commands, manifests, terminal results and server identities for the four full-suite corners and ten core-suite intermediates; execute only missing coverage.
    Evidence: evidence.json.local_validation is empty and frozen online CI is skipped. The retained sdk-quality-results.json covers older 70-case runs on 4.2.5/current-source: 37 input hashes differ, and test_sdk_release_contracts.py is absent. validation-reconciliation.json verifies these mismatches and the older JUnit hashes. Those executions do not establish current release-specific grammar, clone transaction/no-op behavior or snapshot/export correctness.

Validation:

  • Artifacts are retained under /home/xupeng/.local/state/mo-bot/jobs/bb5145fcc58e5b11488017b5/attempt-1. validation-reconciliation.json maps commands, receipts, source hashes and logs. The source remains clean at the assessed head.

  • Full offline suites passed: SQLAlchemy 2.0.43—2,086 tests; SQLAlchemy 1.4.54—2,090 tests. Each also passed 95 subtests, with zero skips/errors/failures. Receipts: checks/1793041194991283264-2.json and checks/1793041655632459226-2.json. Provenance, JUnit and logs are retained under offline-sa20 and offline-sa14.

  • Three diagnostic checks confirmed the two defects with passing controls. They exercise actual compilation, event dispatch and driver formatting; no native server execution is claimed.

  • Saved discussion-assessment.json covering every nonempty raw discussion item and discussion_index entry. Complete design, caller, test-quality and performance analysis is retained in review-map.json.

Limitations:

  • Native release qualification and independent SQLAlchemy 2.1 execution remain unverified here. Linked issue bodies were absent from the frozen bundle; review used the PR's stated contracts and current design/tests.

  • Clone adds the documented two statements ordinarily, three for a missing target with if_not_exists, and one for an existing-target no-op. Compiler preparation adds bounded per-statement state and a callback to typed SELECT/DML/DDL. The author's 6.8-to-7.0 microsecond cache-lookup measurement lacks a retained artifact here; throughput and concurrency costs were not independently measured.

  • Optional TLS/S3/HNSW, multi-CN, async Arrow and the baseline unsupported direct matrixone:// DBAPI entrypoint remain outside the accepted scope. Pending/skipped CI and diagnostic setup errors are not treated as product failures.

@XuPeng-SH

XuPeng-SH commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 36721e73cf0d9644521d25424fea7eebac005643

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: 36721e73cf0d9644521d25424fea7eebac005643

Assessment: request_changes

Reviewed the complete 40-file delta. Shared compiler, literal and execution ownership is reasonable, and current code plus reconciled author evidence resolves all three prior findings. One new correctness defect remains: clone preflight conflates distinct case-sensitive targets.

Model: gpt-6-astra / xhigh

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

  • P2 clients/python/matrixone/clone.py:89: With lower_case_table_names=0, create tables source and target while Target is absent, then call clone_table('Target', 'source', if_not_exists=True).
    Impact: The unconditional LOWER('Target') lookup matches target. Both managers return success without issuing CLONE or verifying Target, leaving the requested table absent. Respect the execution owner's native naming mode and add case-sensitive existing/missing-target regression coverage.
    Evidence: clone-case-contract-final.log and checks/1793067067948473210-10.json confirm the wrong no-op through actual SDK managers with a SQLite catalog oracle. Native case-sensitive semantics are established independently by pkg/sql/parsers/dialect/mysql/mysql_lexer.go:611 and test/distributed/cases/system_variable/lower_case_table_names.result:74. Current native clone tests exercise default normalization, not mode 0.

Validation:

  • Reconciled 219 current source/test/config hashes and 17 author command/exit/JUnit records: SQLAlchemy 1.4/2.0/2.1 offline suites passed 2194/2190/2198 cases plus 95 subtests each; fourteen native release runs passed 782 cases, with zero failures/errors/skips.

  • Local checks confirmed the clone defect, passed an additional warmed-cache lambda-statement control, checked changed Python syntax, and verified clean source/diff. Receipts and logs are mapped in validation-reconciliation.json.

  • Saved discussion-assessment.json accounting for all four discussion entries and review-map.json covering design, callers, lifecycle, performance and test quality. Artifacts are under /home/xupeng/.local/state/mo-bot/jobs/86c583089ce58bb6ccdf3d58/attempt-1.

Limitations:

  • Native release results were reused from qualified author evidence; the new mode-0 reproduction is a host probe supported by frozen server source and regression expectations, not a new native execution.

  • Clone adds the documented one/two/three-query costs; comparative throughput and allocation measurements are unavailable. Mypy retains reported baseline diagnostics.

  • Linked issue bodies were absent. Optional TLS/S3/HNSW, multi-CN, async Arrow and the baseline unsupported matrixone:// DBAPI entrypoint remain outside qualification.

XuPeng-SH added a commit that referenced this pull request Oct 27, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Refs #29249

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

Remove unused helpers, duplicate bookkeeping and transient state whose
consumers have already been retired. This consolidates the 19 closed
cleanup PRs into one reviewable change on current main; each affected
file matches its original published PR, with no additional cleanup.

The cleanup covers TAE task/logstore/merge/RPC helpers, HAKeeper replica
views, obsolete ETL writer and path state, batch/vector constructors,
RPC client bookkeeping, metrics/CDC/fulltext state, MongoScan, message
receivers, fixture helpers and interactive viewport state. Retained
execution, ownership, cancellation, parser/error, replay, plugin
registration and MySQL driver registration paths remain intact.

Supersedes #31325, #31327, #31329, #31331, #31332, #31333, #31334,
#31335, #31336, #31337, #31339, #31340, #31341, #31342, #31343, #31344,
#31345, #31346 and #31347. Already merged #31323/#31324 and Python SDK
#31322 are excluded.

Validation on the combined change: all 30 changed owning packages built;
28 ran tests, with 2,066 top-level / 4,580 named cases passing and two
existing external-data ETL tests skipped. The two support packages have
no tests. Existing component-level race, before/after probes and
consumer checks were reviewed for reuse. Formatting, go vet and
incremental golangci-lint passed; forced all-four-analyzer molint
reported six findings already reproduced at the baseline, with no new
findings. These are local focused checks, not a full CI or GPU run.
@XuPeng-SH
XuPeng-SH force-pushed the codex/python-sdk-release-quality-20261026 branch from 36721e7 to 79ad086 Compare October 27, 2026 02:48
@XuPeng-SH
XuPeng-SH requested a review from fengttt as a code owner October 27, 2026 02:48
@XuPeng-SH

XuPeng-SH commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 79ad086b2f30025e45054ed5393a48e275ce6fee

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: 79ad086b2f30025e45054ed5393a48e275ce6fee

Assessment: approve

Reviewed the complete 41-file delta and all six discussion items. Shared compiler, literal and clone ownership is coherent, with explicit cleanup and transaction contracts. Current code and reconciled evidence resolve all four prior findings: legacy string execution, snapshot escaping, release qualification and case-sensitive clone lookup. Native mixed-case failures now propagate rather than producing false success. No actionable unresolved findings remain.

Model: gpt-6-astra / xhigh

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

Validation:

  • Verified all 219 current manifest hashes against the clean checkout. Reconciled earlier evidence against its recorded revision and identified the four changed inputs.

  • Current author JUnit reports show 2,195/2,191/2,199 offline tests passing under SQLAlchemy 1.4/2.0/2.1, plus 95 subtests each, with no failures, errors or skips.

  • Current native reports contain 48 passing clone cases each on identified 4.1.0 and 4.2.6 servers, including naming modes, Client/Session ownership, rollback and single-connection pools. Earlier fourteen-release records containing 782 cases were reconciled and reused only for unchanged boundaries.

  • Frozen candidate CI records seven successful offline jobs and two successful core-import jobs. Skipped online CI was not counted as native validation.

  • Local source, syntax, evidence and discussion audits passed. Receipts: checks/1793070015653167980-4.json and checks/1793070613446060299-5.json; logs: reconcile-evidence.log and final-audit.log.

  • Saved discussion-assessment.json, review-map.json, validation-reconciliation.json and final-evidence-audit.json under /home/xupeng/.local/state/mo-bot/jobs/2f7cecb2b25daadb022d06ee/attempt-1.

Limitations:

  • Product execution evidence was reused; no local pytest or native-server run was performed. Current focused native reports supply source-bound terminal JUnit and server identities but omit shell command/exit receipts and raw console logs. They do not establish a fresh complete fourteen-release run.

  • No comparative performance benchmark was qualified. Typed execution adds bounded statement preparation; clone uses one, two or three statements, and catalog lookup costs can grow with catalog size. No throughput improvement is claimed.

  • Linked issue bodies were absent from the frozen bundle. Review used the stated PR contracts and maintained design. Optional TLS/S3/HNSW, multi-CN, async Arrow and the baseline unsupported direct matrixone:// entrypoint remain outside qualification.

@XuPeng-SH
XuPeng-SH merged commit baa83f4 into matrixorigin:main Oct 27, 2026
27 of 28 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/python-sdk-release-quality-20261026 branch October 27, 2026 07:25
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/api-change kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/enhancement kind/refactor Code refactor kind/test-ci

Projects

None yet

1 participant