Skip to content

[Tech Request]: Intelligent Query Execution Scheduling #25451

Description

@fengttt

Is there an existing issue for the same tech request?

  • I have checked the existing issues.

Does this tech request not affect user experience?

  • This tech request doesn't affect user experience.

What would you like to be added ?

At this moment, MO will parse a query and based on some logic to determine if the query is a AP query or TP query.   TP query is executed on the current CN (handling connection), and AP will be executed on ALL available CN (and with all threads on each CN).

This is unreasonably restrictive.  In theory, a query can be executed on ANY or ANY subset of CNs, and especially, the subset of CNs does not need to include current CN (client is connected)

Why is this needed ?

To utilize hardware info much more efficiently.

Additional information

There is a routing decision that should be made after query parsing. It could be automatic, intelligent, for example, look at ALL CNs, pick up CNs with load less than 50%. Use this subset of CN.

Or a more manual style. For example, we can give each CN a tag, so a cluster may have say, a few TP CNs, a few ETL CNs, and some AP CNs. Let's assume clients are all connected to TP CNs. After parsing, we can execute all TP queries in current CN. For LOAD, etc, run the work on the ETL CNs, and for large AP queries, send to those AP CNs. These different CNs (TP, LOAD, AP) does not need to have same hardware resource.
We can optimize allocation, for example, more memory for TP CNs and less memory, but more disk bandwidth for ETL CNs, etc.

One interesting case, is that we can have many customers, each have its own TP CN, let's assume each customer has just one TP CN. A shared pool of AP CNs for all customers to run AP queries. Note that this case the AP query is executed on a subset of CNs that does not include current CN.

Also on TPC-C like workload, we can have a bunch of CNs, based on the warehouse id after query parsing, we either execute the query on current CN, or, route the the CN that "owns" the partition. If we do this, TPC-C does not have any distributed transactions. This is actually quite common because some experienced DBA will shard data exactly to avoid transactions across shards.

Finally, I do not know if our AP queries runs correctly on several CNs if each of them are configured with different number of CPUs. And I don't think we can run a query only use a subset of the CPUs on a CN -- that is, if we can run a pipeline with parallelism 4 even if the machine has 8 cores. But these may not as important if we fully embraces K8S -- we can always partition a bigger machine to a standard "unit" size.
But worth find out where we fail right now and understand the problems at least.

Activity

  1. added
    kind/tech-request
    on Jul 4, 2026
  2. XuPeng-SH commented on Aug 12, 2026

    @XuPeng-SH
    Contributor

    Product-first reset for #25451 — 2026-08-13

    This revision supersedes the implementation-led “Phase 9–14” roadmap previously posted in this comment. The existing PRs are implementation history and evidence; they do not define the product.

    1. What product are we actually building?

    The customer-facing promise should be:

    Run each statement on an authorized compute group with predictable isolation and overload behavior, while MatrixOne chooses the concrete CN topology internally without breaking session, transaction, or data-locality semantics.

    A customer should be able to answer, before running a workload:

    • Which named compute group may run it?
    • Who is allowed to use that group?
    • If the group is unavailable or full, will the statement wait, fail, or use an explicitly authorized alternative?
    • What concurrency/resource boundary is promised?
    • Which decision was made for this statement, and why?
    • What changes when configuration or cluster membership changes?

    “Pick CNs below 50% CPU”, “TP versus AP”, “use CN-3”, and “match these raw labels” are not product contracts. They are heuristics, current implementation details, or examples from the original request.

    2. Industry calibration

    Mature systems expose a stable compute or admission boundary and keep machine selection internal:

    • Snowflake attaches a session to a warehouse; insufficient capacity queues work, and multi-cluster warehouses address concurrency within that boundary.
    • BigQuery assigns workloads to reservations and allocates slots fairly inside a reservation; users do not assign individual workers.
    • Databricks SQL submits work to a SQL warehouse, which owns admission, queueing, and scaling behavior.
    • Trino resolves selectors to resource groups, then applies explicit concurrency, bounded queueing, and fairness.
    • The Kubernetes scheduling framework also separates filter, score, reserve/permit, and bind. Selecting a node is not the same as owning capacity on it.

    MatrixOne should follow these responsibility boundaries, not copy any one product's syntax.

    3. MatrixOne's minimal stable model

    MatrixOne already has an operational concept of named cnGroups / CN resource groups, created by the Operator and selected by Proxy for a connection (current MatrixOne documentation). Query scheduling must build on that one compute identity rather than introduce a second unrelated “pool”.

    Use three concepts, introduced only when their behavior exists:

    1. Compute group (existing CN group; final public name to be decided once)

      • Operator/control-plane owned.
      • Stable name/identity, CN membership, lifecycle, capabilities, and account ACL.
      • CN labels may implement membership, but labels and CN IDs are infrastructure attributes, not the customer API.
      • It says where work may run. It does not yet promise CPU/memory fairness.
    2. Binding / assignment

      • Maps trusted request identity to an authorized compute group.
      • MVP precedence should be: authorized statement override → authorized session/connection selection → administrator default binding → legacy behavior when the feature is disabled.
      • Role, source/application, and explicit workload tag may be added only after concrete use cases establish their precedence.
      • An optimizer decision such as TP/AP is not a stable binding key.
    3. Admission policy (later)

      • Owns concurrency, queue limits, timeouts, cancellation, reservation/release, and fairness.
      • Until this exists, max_workers is only a topology/DOP hint and must not be presented as resource governance.

    The internal flow is:

    authenticated request + explicit selection
                     |
                     v
          resolve authorized compute group
                     |
                     v
     apply hard execution constraints and worker eligibility
                     |
                     v
          admission / capacity reservation
                     |
                     v
     deterministic placement inside the admitted group
                     |
                     v
     execution -> release -> bounded observability
    

    Authorization and hard execution constraints always win; load information may rank an eligible set but may never widen it.

    4. Required product behavior

    Default and compatibility

    • With this feature disabled, preserve current main behavior exactly.
    • Roll out per account/compute group; no global behavior change after upgrade.
    • An explicit target must be authorized. Missing, unknown, or unauthorized groups fail before execution.
    • No silent fallback to ingress, an unlabeled CN, or another account's group. A transitional fallback, if needed for upgrade compatibility, must be opt-in, bounded in lifetime, and observable.

    Unavailable versus overloaded

    These are different states:

    • Group absent, unauthorized, incompatible, or with no routable healthy CN: fail immediately with a configuration/availability error.
    • Group healthy but at capacity: enter a bounded, cancellable queue or return a defined retryable overload error.
    • Queue full or deadline expired: reject clearly; never create an unbounded waiter.
    • Draining removes a CN from new placement. Running work follows an explicit drain deadline/cancel policy; it is not silently migrated.

    Configuration changes

    • Each execution pins one immutable group/binding generation.
    • Changes affect new admissions, not already running statements.
    • PREPARE does not own capacity. EXECUTE resolves the effective group and admission at execution time; the resulting attempt then remains immutable.
    • A retry must remain authorized, re-acquire capacity, and must not expand into a different group merely because a worker failed.
    • Rename/delete/membership changes require explicit semantics; a stale group reference cannot resolve by matching unrelated labels.

    Session and transaction ownership

    The scheduler cannot override correctness:

    • Client connection, result writer, session state, temporary/local objects, and LOAD DATA LOCAL input belong to the ingress CN.
    • RemoteRun transports a transaction snapshot, not the ingress CN's uncommitted workspace.
    • A statement needing local input, read-your-writes, local locks, or transaction/session-owned state must retain ingress participation or fail before side effects.
    • The execution group for an active transaction must be pinned at a defined boundary; changing the session group during a transaction must either be rejected or apply only to the next transaction.
    • DDL/maintenance stays outside general query routing until lock owner, commit owner, failure recovery, and retry semantics are explicitly designed.
    • Warehouse/partition-owner TP routing is a separate transaction-affinity problem. The owner must be selected before transaction-local state exists; a query scheduler must not migrate an active transaction.

    Classification

    Separate business intent from execution capability:

    • Stable workload identity comes from an explicit workload tag/source or an administrator binding, with permissions and documented precedence.
    • TP/AP_ONECN/AP_MULTICN remains an internal planner/execution result. It can constrain topology but is not a durable customer workload class: statistics, indexes, prepared parameters, cost thresholds, and releases can change it for the same SQL.
    • A future automatic classifier may recommend or select a group only as an opt-in policy with a recorded reason and confidence/fallback. It must never be the only way to obtain predictable placement.

    Observability

    For every scheduled attempt, operators need bounded-cardinality visibility of:

    • requested and resolved compute group;
    • binding source and generation;
    • hard constraint/admission/placement outcome;
    • queue wait and rejection reason;
    • selected worker count/topology and DOP;
    • retry attempt, worker drain/failure, and whether any explicitly configured fallback occurred.

    EXPLAIN/preview must not mutate state or claim admission that has not happened.

    5. What current code has established

    Current main (6a29b7d at this review) has useful internal foundations from #25461, #25492, #25496, #25517, #25537, #25564, #25581, and #25990:

    • candidate discovery is separated from pool resolution and placement;
    • current-CN constraints and runtime worker eligibility are explicit;
    • AP multi-CN can select a deterministic HRW worker subset from a label-resolved set;
    • query/scan/stage/RemoteRun topology, prepared/retry propagation, bounded trace, and EXPLAIN preview exist.

    This is infrastructure, not the completed product. TP and AP-one-CN still remain on ingress; advertised CPUTotal is static DOP input, not live free capacity; there is no admission, reservation, bounded shared-pool fairness, or transaction-owner routing.

    6. Product review of #26109

    #26109 contains valuable internal work that should be preserved or extracted:

    • immutable snapshots and monotonic revisions;
    • candidate/placement generation fencing;
    • prepared/retry topology validation;
    • strict tenant identity injection;
    • RemoteRun topology materialization and failure-path tests;
    • trace/metrics and several correctness closures (LOAD DATA LOCAL, dirty workspace, rolling upgrade).

    However, its public product surface should not merge as-is:

    1. pool is not a resource object. The policy stores both a display pool and independently effective labels; labels perform the actual selection. They can drift, and neither field owns membership, ACL, capacity, rename/delete, or lifecycle.
    2. tp/ap/load/internal/unclassified mixes business workload, SQL syntax, and planner execution type. In particular, TP/AP is derived from cost/statistics and can change for the same SQL.
    3. ALTER ACCOUNT CONFIG ... query_workload_policy = JSON exposes CN labels plus current_cn, empty_worker, fallback, and worker topology in one document. It makes infrastructure safety constraints customer configuration and freezes an internal representation as an account API.
    4. max_workers limits CN fan-out; without admission it is not a CPU, memory, or concurrency budget.
    5. The PR adds a catalog table, cache lifecycle, publication RPC, upgrade gate, parser surface, and 75-file integration before the resource identity and user behavior are settled. Repeated correctness fixes improve implementation quality but do not repair that product boundary.

    The correct action is to re-scope #26109, not continue patching the JSON model:

    • keep/extract independently useful scheduling and topology mechanisms;
    • pause the public DDL/catalog/RPC contract;
    • first define how the existing named CN group becomes the single canonical compute-group identity visible to SQL;
    • enforce transaction/local-input constraints internally, not as user-selectable current_cn;
    • start with explicit authorized binding, then add stable workload assignments after their precedence is proven.

    7. Outcome-gated roadmap

    This replaces numbered implementation phases.

    Milestone A — product contract and canonical compute identity

    Deliver an RFC and executable acceptance matrix before more public API code:

    • one canonical identity bridging Operator cnGroups, Proxy connection routing, CN metadata, and SQL scheduling;
    • ownership and ACL for group creation/use/alter/drop;
    • membership, rename/delete, drain, rolling-upgrade, and stale-generation behavior;
    • session/statement selection and transaction pinning semantics;
    • clear unavailable/overloaded/cancel/timeout errors;
    • the smallest SQL/API examples, with no raw CN labels.

    Exit gate: product, control-plane, Proxy, transaction, and SQL owners agree on the contract; two real deployments are expressible without contradictory names or fallbacks.

    Milestone B — static compute-group execution MVP

    Implement only:

    • account default binding plus an authorized explicit session/statement selection;
    • immutable group snapshot;
    • deterministic worker subset and DOP within the group;
    • hard ingress/transaction/local-input constraints;
    • strict failure outside the group;
    • bounded trace/EXPLAIN;
    • compatibility-off default.

    Do not add live CPU scoring, generic selector DSL, shared-pool fairness, or autoscaling.

    Exit gate: real multi-CN E2E covers autocommit/read-only analytics, supported LOAD, ingress-only input, first DML, explicit transaction read-your-writes, prepared execution, retry, cancellation, draining, address/membership change, mixed version, and cross-account denial. The disabled path has no catalog/RPC and no material allocation/latency regression.

    Milestone C — stable workload assignment

    After explicit group selection works, add only selectors justified by real customers: for example authenticated account/role, client source or explicit workload tag, and statement kind. Define deterministic precedence and a mandatory default. Keep optimizer TP/AP classification internal.

    Automatic plan-based assignment is a separate opt-in experiment and ships only if it is predictable enough to beat explicit/static assignment in the acceptance workloads.

    Exit gate: the same request resolves identically across CNs and retries for a fixed policy generation; every decision is explainable; no selector can widen ACLs.

    Milestone D — admission and shared-group safety

    When contention measurements show the need, start with the smallest explainable mechanism: group-level concurrent-query permits plus a bounded cancellable queue. Define a single owner and idempotent release across success, error, timeout, cancellation, retry, CN loss, and restart.

    Cross-account shared groups are enabled only here, after per-account limits/fairness and audit exist.

    Exit gate: overload tests prove bounded memory/waiters, no permit leak/double release, defined queue fairness, preserved TP tail latency, and useful queue/reject metrics.

    Milestone E — heterogeneous capacity and dynamic placement

    Only after admission owns capacity:

    • add calibrated capability/capacity units and memory/IO constraints where measurements justify them;
    • use reserved capacity and a TTL/generation resource snapshot for placement;
    • define stale/unknown behavior, deterministic tie-breaking, and hysteresis;
    • keep static deterministic placement as the safe fallback;
    • consider autoscaling only from sustained queue/capacity signals.

    A single instantaneous CPU threshold and per-query cluster polling are explicitly rejected.

    Exit gate: controlled mixed-workload tests show a material repeatable gain in throughput or P95/P99 queue/query latency without correctness, isolation, stampede, oscillation, or steady fast-path regression. Otherwise retain the simpler static policy.

    Independent track — transaction/data-locality routing

    TPCC warehouse/partition affinity requires partition ownership, routing-key availability (including prepared parameters), transaction-begin pinning, owner generation, cross-owner transaction behavior, and failover. It should consume the compute-group eligibility contract but must not be hidden inside query worker placement.

    Immediate decision

  3. 12 remaining items

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

Metadata

Metadata

Assignees

Labels

kind/tech-request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions