Skip to content

feat: protect embedded Sirius TAE admission - #29211

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
aunjgr:feature/28966-protected-tae-admission
Sep 22, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
aunjgr:feature/28966-protected-tae-admission

Conversation

@aunjgr

@aunjgr aunjgr commented Sep 21, 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:

Refs #28966. This protection/harness PR does not close the migration issue.

What this PR does / why we need it:

Adds the storage-agnostic protection contract and evidence harness needed by embedded direct-TAE execution, without yet enabling that execution mode in CN configuration.

Protected read ownership

  • Adds typed Flight and embedded-TAE consumers.
  • Preserves the durable journal JSON schema: a real nonzero 32-byte SPKI identifies Flight, while the reserved all-zero marker identifies embedded TAE.
  • Rejects embedded capabilities in the Flight resolver before certificate/audit handling; unknown references keep the existing authentication boundary.
  • Replays consumer identity from existing records, releases stale in-process embedded leases after restart, preserves Flight reconciliation, and blocks embedded startup semantics when Flight work remains.
  • Applies the new 64 MiB aggregate manifest/descriptor budget only to embedded TAE. Flight keeps its existing per-read behavior.
  • Requires a bounded snapshot provider before embedded manifest construction, passes decreasing remaining capacity, and defensively rechecks returned metadata. The disttae provider rejects during construction rather than materializing a second over-limit manifest.
  • Returns borrowed protected manifest/schema views for synchronous native preparation, avoiding another manifest-sized copy.

Deterministic parity campaign

Adds a command-injected, serial five-route campaign for MO native, Flight+TAE, Flight+MO, embedded+TAE, and embedded+MO:

  • all Q1-Q22 at SF1 and SF10;
  • streams 1, 2, and 4;
  • one excluded warm-up plus five measured suites at streams=2;
  • Q9 repeated ten times;
  • typed exact results except explicit per-query float tolerances;
  • fallback disabled, GPU/source/terminal/capacity evidence required;
  • per-scale timing tables and approved relative gates;
  • strict revision/query/dataset/config/hardware provenance;
  • sanitized campaign.json, runs.jsonl, summary.csv, and summary.md artifacts with no row contents, unknown runner fields, credentials, or object paths.

The harness defines and validates evidence; this PR does not run or claim TPC-H results.

Approved design alignment

Exact reviewed design revision: Embedded Sirius migration design v2 at 24161f69ba1bfefbd159d120cecc1758d00f98ed. The document records approval of the ten-PR delivery plan and requires every implementation PR to identify and map itself to that revision. This PR is the protected direct-TAE admission and evidence-harness portion of delivery-map PR 8; it does not enable embedded execution or alter the rollout selector.

Contract mapping:

  • Ownership and consumer identity (sections 3, 4, and 6): Flight and embedded TAE use disjoint typed consumers while preserving the durable journal schema. Query-local read references remain owned by one lease manager; synchronous native preparation may borrow immutable manifest/schema views only until the read reference is released.
  • Restart and reconciliation (section 6): stale in-process embedded leases are released on restart, Flight reconciliation remains pending for its external owner, failed unregister remains retryable, and mixed unresolved Flight work prevents embedded startup semantics rather than silently transferring ownership.
  • Capacity and bounded construction (section 5, including bounded native execution details): the 64 MiB aggregate embedded metadata budget covers manifest and descriptor expansion before construction; the bounded provider receives decreasing remaining capacity and the admission boundary rechecks returned usage. Flight retains its existing per-read contract.
  • Flight isolation and coexistence (sections 3, 6, and 7): the reserved embedded marker cannot enter Flight authentication/audit resolution, the existing Flight journal wire/JSON schema remains compatible, and this PR does not change backend selection or enable the embedded route.
  • Verification and cutover evidence (sections 9 and 10): the serial five-route harness encodes the approved streams, all-22, correctness, telemetry, provenance, and timing gates. It validates evidence shape only; actual SF1/SF10 results remain a later acceptance gate and are not claimed here.
  • Rollout boundary (sections 7 and 11): this PR supplies reusable protection and evidence contracts only. CN launcher wiring, native execution ownership, opt-in enablement, default cutover, and Flight retirement remain deferred to later [Feature Request]: Embed Sirius in MatrixOne through CGo and retire Flight offload #28966 PRs.

Validation on the exact branch:

  • Full pkg/sql/plan/substrait and pkg/vm/engine/disttae/sidecar packages passed through the repository CGo-aware wrapper.
  • Full race and repeated restart/construction boundary tests passed during implementation review.
  • All twelve deterministic Python campaign tests passed; the schedule contains 1,860 serial runs.
  • go vet, Python compile/tab checks, gofmt, and diff checks passed.
  • Independent lifecycle review found and closed Flight-regression, pre-materialization bound, false-positive telemetry, identity, and redaction issues.
  • No containers and no mo-pr-guard run.

@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 (exact head e523f21).\n\nREQUEST_CHANGES.\n\nP1 — The feature/design gate is not closed. This PR adds a substantial embedded Sirius TAE admission contract, durable lease-consumer semantics, restart/reconciliation behavior, aggregate metadata budgeting, a bounded provider interface, and a deterministic parity campaign. The linked issue's approved implementation plan explicitly requires the versioned design artifact docs/design/sirius-embedded.md covering API, ownership, capacity, lifecycle, validation, and rollout contracts, and identifies the protection/harness stage as dependent on that approved contract. This PR body provides no approved design revision or alignment link; the linked issue still lists the MO contract/design stage as incomplete.\n\nPlease add and obtain approval for the exact design revision, then tie this implementation to it (or explicitly narrow this PR to an already-approved contract). Current CI and the added unit/Python tests do not close the missing design/rollout proof; no further implementation polishing is requested until that gate is closed.

@gouhongshen gouhongshen 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.

Codex automated review

Reviewed git diff origin/main...HEAD (3 commits, 9 files) from first principles. The PR has no existing reviews, no inline review comments, and one issue comment (a paused-Qodo bot notice), so nothing was withdrawn as disproven and no finding duplicates another reviewer.

Live Flight path — no regression proved

  • manifestBuilder.add projection changed from emptySize - len("[]") + … to emptySize + …. The old form under-projected by exactly 2 bytes (the [] brackets remain when objects are appended), and finish() was always the authoritative check, so the exact projection only moves the reject point 2 bytes earlier with the same NotEligible(EligibilitySnapshot) outcome. finish() is unchanged for Flight because objectDescriptorBytes stays 0; TestSnapshotProviderStopsObjectVisitationAtManifestBound still holds (I re-derived both new boundary tests by hand against add/finish).
  • PendingExecutions() now filters on Consumer == ReadConsumerFlight. The only production admission caller (pkg/sql/compile/sirius_read.go:99) leaves Consumer at its zero value, and loadCertificateSPKIHash (pkg/cnservice/sirius_runtime.go:191) returns sha256(RawSubjectPublicKeyInfo) of a parsed PEM certificate, which cannot collide with the reserved all-zero marker. So no durable lease can be reclassified as embedded and silently dropped from ReconcileReplay.
  • Consumer inference in journal.load and validateLease derives from the same 32-byte hash, so it is self-consistent; journalRecord keeps its exact JSON field set and authority digest, asserted by TestFlightJournalSchemaAndAuthorityRemainConsumerNeutral.
  • Embedded budget accounting is internally consistent: the provider enforces manifest + Σ(16+len(name)) ≤ remaining, and chargeReturnedTAEMetadata charges exactly that quantity against the same remaining budget. prechargeQueryTAEMetadata's columns > remaining/128 guard prevents 128*columns overflow, and the metadataBytes == metadataLimit check keeps the provider's maximum ≥ 1. chargeTAEMetadata cannot underflow (charged ≤ remaining is invariant).
  • ReconcileRestart holds mutation for the whole sweep, releaseLease does not re-acquire it (no deadlock), and a failed Unregister leaves the lease in releaseMarked so a retry resumes — covered by TestRestartReconciliationRetainsFailedEmbeddedCleanup.
  • AdmittedTAERead aliases the published lease clone. Publication transfers a private clone via cloneLease and no lifecycle path mutates it, so the borrow is memory-safe; the "finish native preparation before releasing ReadRef" pin contract is documented. ResolveHandler is the only surface that serves lease.Manifest, and it now rejects embedded leases, so no second read path bypasses the consumer check.
  • The all-zero-SPKI rejection for Flight cannot fire in production for the reason above; the test runtimes that still use make([]byte, 32) (pkg/sql/compile/sirius_runtime_test.go:70, :86) only reach Validate(), never AdmitReads.

gofmt -l is clean for all touched Go packages, and no helper in the new test file collides with existing package symbols. I could not execute the Go tests locally: this worktree has no thirdparties/install and no lib/libmo, so go vet/go test fail in the CGo layer (xxhash.h, roaring.h, usearch.h, jemalloc.h) and CGO_ENABLED=0 excludes required packages. The Go conclusions above are static proofs, not test runs. The 7 Python harness tests do pass locally.

No blocking defect found. Remaining items are non-blocking: the resolver's fail-closed certificate gate moved behind body read and durable journal I/O (unreachable in production but unnecessary), the new optools parity harness is unreachable from any Makefile target or workflow, and that harness retains every typed result set for the whole campaign.

P1 - New parity harness and its unittest are unreachable from CI and outside the PR's stated scope (optools/sirius_parity.py:734)

The PR adds 756 lines of harness plus 311 lines of unittest, but nothing in the repository invokes either. Searching for sirius_parity outside these two files returns no hits: there is no Makefile target, no .github/workflows step or path filter, and optools/run_ut.sh runs only the Go UT schedule (it invokes other optools/*.py helpers by explicit name — summarize_ut_slow_cases.py, active_ut_incremental.py, summarize_ut_setup.py — never this one). Compare the existing precedent optools/iceberg_external_runner.py, which is called from optools/iceberg_ci.bash and listed as a trigger path in .github/workflows/iceberg-connector.yml:11.

Consequence: the "seven deterministic Python campaign tests" cited in the PR description give no ongoing protection. The module hardcodes a contract for a runtime that does not live in this repository (REQUIRED_EXECUTION_STATS, tae_work_limit == max(2, 2 * streams) at optools/sirius_parity.py:441, maximum_slice = (64 << 20) // expected_limit), so it will drift silently and the only check that would catch the drift never runs. It also widens the PR considerably beyond its stated scope of embedded TAE admission protection.

Non-blocking because it changes no production behavior. Suggested fix: add a Makefile target plus a workflow path filter so cd optools && python3 -m unittest sirius_parity_test runs on changes to these two files, or split the harness into its own PR.

P2 - ResolveHandler now performs budget, body-read and durable journal I/O before verifying the client certificate (pkg/sql/plan/substrait/admission.go:1244)

Before this PR the verified-client-certificate check was the first gate after the Content-Type check, so an unauthenticated request never touched resolver state. It now sits at pkg/sql/plan/substrait/admission.go:1244, after leases.resolveBytes.acquire (pkg/sql/plan/substrait/admission.go:1211), readResolveRequestBody (pkg/sql/plan/substrait/admission.go:1218), UnmarshalResolveRequest, UnmarshalTaeRead, and leases.resolve (pkg/sql/plan/substrait/admission.go:1233) — and for a journaled manager resolve performs a durable journal.Active() round-trip under a 5s timeout (pkg/sql/plan/substrait/admission.go:442). The new consumer check at pkg/sql/plan/substrait/admission.go:1238 also runs before the certificate check, which creates a response-code distinction: a certificate-less caller gets 404 for a readRef that maps to an embedded lease but 401 for any other readRef. TestResolverRejectsEmbeddedConsumerBeforeCertificateHandling asserts both halves, so the ordering is now locked in by test.

This is not reachable in production today — NewResolverServer rejects any TLS config whose ClientAuth != tls.RequireAndVerifyClientCert or whose ClientCAs is nil (pkg/sql/plan/substrait/server.go:46) and serves via tls.NewListener, so the handshake fails before the handler runs. That is why this is not a blocker.

But ResolveHandler is exported, and the reorder was not needed to reach the stated goal. The audit record is only constructed at pkg/sql/plan/substrait/admission.go:1262-1276, and an embedded lease's all-zero AuthorizedClientSPKIHash can never equal a real principalHash, so the existing comparison already returns 404 without auditing. Moving if ok && lease.Consumer != ReadConsumerFlight { 404 } to immediately after leases.resolve while leaving the certificate check in its original position achieves "an embedded marker can never enter Flight's authentication/audit path" without weakening the fail-closed ordering or introducing the 404/401 distinction. Suggest restoring the original gate order and adjusting the test to assert 401-first.

P2 - Parity campaign retains every typed result set for all 1,860 runs instead of validating per contiguous cell group (optools/sirius_parity.py:295)

execute_campaign (optools/sirius_parity.py:295-302) accumulates one record per schedule entry, each holding the runner's full output including result.rows. validate_runs then pins every output a second time in by_cell (optools/sirius_parity.py:500-516) and reads them only for the native-oracle comparison (optools/sirius_parity.py:530-535). Nothing is released until the process exits; write_artifacts drops rows only while serializing (optools/sirius_parity.py:697). Peak RSS therefore scales with the total answer-set volume of the entire campaign rather than with one cell, which for the SF10 leg of a 1,860-run serial schedule is the harness's dominant memory cost — in a tool that is deliberately serial everywhere else.

The schedule already makes this avoidable. build_schedule emits all five routes for a fixed (scale_factor, phase, streams, suite, repetition, query) contiguously in every phase (optools/sirius_parity.py:164-167, optools/sirius_parity.py:170-179, optools/sirius_parity.py:181-186), and the mo-native oracle for a cell is always inside that same group, while summarize needs only wall_seconds per run (optools/sirius_parity.py:552). Validating each 5-run group as it completes — compare against the group's native output, keep the timings, drop the rows — would bound retention to one group without changing any evidence semantics or artifact bytes.

Non-blocking: it is a resource-scaling property of an unwired tool, not a correctness defect, and TPC-H answer sets are small enough that a single SF1 leg may still fit.

@aptend aptend 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.

P1 — The mandatory design-first gate is still open at exact head e523f21. This PR changes cross-owner storage admission and durable/restart contracts (pkg/sql/plan/substrait/admission.go, consumer.go, journal.go, and the disttae provider) and adds the parity/cutover evidence contract, so the feature-design gate applies independently of CI. The base document docs/design/sirius-embedded.md explicitly requires every implementation PR to link the reviewed revision, but this PR body only references #28966 and does not identify which exact design revision/approval governs these semantics or map this split protection/harness stage to that revision. This is material because the repository base contains design v1 while a later v2 revision is being cited by adjacent Sirius PRs; without a pinned revision, reviewers cannot determine which restart ownership, aggregate metadata budget, direct-TAE protection, and validation/cutover rules are authoritative or whether this delivery split is an approved deviation. Please link the exact approved design commit and record the section-by-section alignment (or update/review the design first). I reviewed the full review/comment history and confirmed there are no inline threads or an author response closing this gate; implementation approval remains blocked until the traceable design revision is present.

@aunjgr
aunjgr requested a review from XuPeng-SH September 22, 2026 08:36
@matrix-meow matrix-meow added the size/XXL Denotes a PR that changes 2000+ lines label Sep 22, 2026
@aunjgr

aunjgr commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH @aptend Resolved the four new harness blockers at head ff759466d4:

  • Float tolerance is now schema-directed and applies only to explicit floating SQL types. Decimal cells require exact string encoding; decimal/integer comparisons remain exact, with negative regressions for both.
  • Capacity evidence now enforces the reviewed design-v2 limits with over-limit tests: 8 MiB per TAE staging slice, 32 MiB cached TAE metadata, 64 MiB aggregate TAE host window, and 64 MiB result window. The review text called 8 MiB a result-window boundary; design v2 section 5 defines it as the per-unit TAE staging entitlement and defines the result window as 64 MiB, so the code follows the approved values.
  • Runner processes now start in a dedicated POSIX session; timeout, cancellation, and completed-parent paths kill the complete process group and reap the direct runner. Tests cover a real surviving descendant on timeout plus injected cancellation cleanup.
  • Result schema and typed cells now use exact allowlisted fields. Nested/unknown schema fields fail closed, and artifact serialization reconstructs only name/type, with a nested object_path regression.

After merging current main, Python compile/tab checks, all nine campaign tests, and five repeated real descendant-cleanup runs pass. Re-review is requested only from reviewers with outstanding CHANGES_REQUESTED reviews.

@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.

GPT-6 high force review at exact head ff75946 (base 27ffab6): REQUEST_CHANGES.

[P2] Integer results still allow lossy float encoding in the parity validator. In optools/sirius_parity.py:409-435, decimal/floating checks were tightened but integer schema values still accept float. BIGINT values 9007199254740992 and 9007199254740993 both become 9007199254740992.0, yet the current validator accepts them; the full 1,860-record campaign can pass. Require lossless integer encoding, reject float/boolean representations for integer types, and add a 2^53 boundary negative test.

[P2] Descendants created in a new session can escape timeout cleanup and make timeout handling unbounded. optools/sirius_parity.py:338-346 kills only the runner process group and then calls communicate() without a timeout; killpg cannot reach a child that started a new session. This was reproduced both with a detached child surviving and with inherited pipes causing communicate() to wait until the child was killed. Define ownership/termination for all descendants and make cleanup waiting bounded.

The prior decimal-tolerance, 64/32/8 MiB capacity, and nested-schema allowlist findings are fixed. The Go ownership/Flight/reconciliation review found no new confirmed defect. Current shared-build CI is successful, but UT/SCA/BVT are still running and real GPU/TPC-H cutover was not claimed.

@aptend aptend 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 re-review at exact head ff759466d495dcde6535cf417b9337e5945d9189 (merge-base/base 27ffab65a0f1c98752bb2fa5e852810cc6e12900): APPROVE.

I re-read the complete review/comment/thread history, checked the incremental fix from e523f2189903d7b4471b78be04800ce1d0c6aa13, and re-audited the full diff against the pinned v2 design (24161f69ba1bfefbd159d120cecc1758d00f98ed). All four prior blockers are closed:

  • tolerance is now schema-directed and applies only to explicit floating SQL types; decimal/integer cells remain exact and decimal encodings are checked;
  • the evidence validator enforces the 8 MiB TAE slice, 32 MiB cached metadata, 64 MiB aggregate TAE staging, and 64 MiB result-window limits, including one-over-bound tests;
  • each runner starts in a POSIX session/process group and timeout/cancellation/completed-parent paths kill and reap the group; the committed descendant timeout test and an additional real successful-parent descendant counterexample both passed;
  • schema/cell shapes are exact allowlists and persisted artifacts are reconstructed, so nested runner-controlled fields and row contents are not emitted.

Lifecycle audit: process creation has one reap path on success, timeout, and cancellation (Q1); communicate is bounded by the configured timeout and group kill releases inherited pipes for the owned process group (Q2); the newly asserted TAE/result accumulations have explicit hard limits (Q3). Flight/embedded lease ownership, retryable restart reconciliation, resolver isolation, and bounded manifest construction remain coherent in the unchanged Go delta.

Local exact-head evidence: 9/9 Python campaign tests passed; both touched Go packages passed; focused lifecycle/admission/provider tests passed under -race -count=3; the changed compile recovery test passed; git diff --check passed. Exact-head shared build, coverage, and SCA checks are green; remaining broad UT/BVT jobs were still running at submission time.

@aunjgr

aunjgr commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH @aptend Resolved the two latest blockers at head bcb178e252:

  • Integer-typed cells now require a real Python/JSON integer (not float, bool, or string) and must fit the declared signed/unsigned SQL width. Regressions cover exact 2^53+1, its lossy float representation, boolean encoding, and BIGINT overflow.
  • Runner lifecycle now uses exclusive Linux subreaper ownership. A campaign call rejects pre-existing children, enables PR_SET_CHILD_SUBREAPER, starts the runner in a new session, bounds every direct wait and pidfd poll by one five-second cleanup deadline, repeatedly SIGKILLs/reaps adopted descendants until the owned child set is empty, restores prior subreaper state only after cleanup, and poisons future admission after cleanup failure. This covers children that call setsid() and either retain or close inherited pipes.

After merging current main, Python compile/tab checks and all twelve campaign tests pass. The real timeout and successful-parent detached-child cases also passed five repeated paired runs. No GPU/TPC-H result is claimed by this PR.

@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.

GPT-6 high force review at exact head bcb178e (base 1634996): APPROVE.

The prior two blockers are closed: integer schema values now require lossless integer encoding with signed/unsigned range checks, rejecting float/bool/string representations including 2^53 boundary cases; descendant cleanup now uses subreaper/pidfd handling with bounded termination, reaping, and executor quarantine on persistent failure.

The full review found the design/rollout boundary, Flight/embedded isolation, journal compatibility, restart/reconciliation, capacity accounting, borrowed-view lifetime, parity schedule, schema-directed tolerances, and artifact checks sound. Current-head CI passed, and the local Python suite plus boundary checks passed. Linux/GPU/TPC-H/cutover deployment acceptance remains a later gate and is not claimed to close #28966.

This branch was previously deployed

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants