Skip to content

Sadalmia/backport pg16#8534

Open
SarthakDalmia1 wants to merge 8 commits intocitusdata:mainfrom
SarthakDalmia1:sadalmia/backport_pg16
Open

Sadalmia/backport pg16#8534
SarthakDalmia1 wants to merge 8 commits intocitusdata:mainfrom
SarthakDalmia1:sadalmia/backport_pg16

Conversation

@SarthakDalmia1
Copy link
Copy Markdown

DESCRIPTION: PR description that will go into the change log, up to 78 characters

colm-mchugh and others added 8 commits March 27, 2026 11:47
…ection integration

Add per-connection prepared statement cache infrastructure:

- New GUC citus.enable_prepared_statement_caching (default off, PGC_USERSET)
- PreparedStatementCacheEntry/Key types with HTAB-based cache keyed by
  (planId, shardId), with MAX_CACHED_STMTS_PER_CONNECTION=1000 hard limit
- Create/Lookup/Insert/Destroy cache lifecycle functions in
  prepared_statement_cache.c (TopMemoryContext for connection-scoped lifetime)
- HTAB *preparedStatementCache field added to MultiConnection struct
- Cache cleanup integrated into ShutdownConnection() and CitusPQFinish()
  to ensure no leaks on connection close
Core integration (prepared statement caching in executor):

1. Query template preservation (citus_clauses.c/h):
   - Add EVALUATE_FUNCTIONS mode to CoordinatorEvaluationMode enum
   - New ExecuteCoordinatorEvaluableFunctions() evaluates functions
     while preserving Param nodes for parameterized queries

2. Task metadata (multi_physical_planner.h, citus_custom_scan.c):
   - Add preparedStatementPlanId and jobQueryForPrepare fields to Task
   - CitusBeginReadOnlyScan and CitusBeginModifyScan save pre-evaluation
     job query and annotate tasks with plan ID for cache lookup
   - INSERT commands excluded (query trees have special RTEs that
     pg_get_query_def cannot deparse)

3. SendNextQuery prepared statement path (adaptive_executor.c):
   - New if-block at top of SendNextQuery() checks
     EnablePreparedStatementCaching && task->jobQueryForPrepare
   - Cache miss: UpdateRelationToShardNames + pg_get_query_def to
     construct parameterized shard query, PQprepare via SendRemotePrepare,
     cache the entry, then PQsendQueryPrepared via SendRemotePreparedQuery
   - Cache hit: reuse cached statement name with PQsendQueryPrepared
   - Fallback: goto plain_sql when cache is full
   - Skip MarkUnreferencedExternParams when caching enabled to preserve
     original parameter types

4. libpq wrappers (remote_commands.c/h):
   - SendRemotePrepare: synchronous PQprepare wrapper
   - SendRemotePreparedQuery: async PQsendQueryPrepared wrapper

5. Cache key fix (prepared_statement_cache.c/h):
   - Changed planId from uint32 to uint64 to match DistributedPlan.planId

Tests:

- Regression test suite for prepared statement caching (GUC toggle,
  single-shard SELECT, multi-shard routing, INSERT/UPDATE/DELETE,
  function evaluation, concurrent statements, connection loss re-prepare)
On cache hits (2nd+ execution with caching enabled), skip the expensive
CopyDistributedPlanWithoutCache, ExecuteCoordinatorEvaluableExpressions,
and RegenerateTaskForFasthPathQuery. Instead:

1. Preserve distribution key param index at plan time so the executor
   can extract the value directly from ParamListInfo.

2. In CitusBeginReadOnlyScan, when caching is enabled and the plan has
   been executed before, extract the distribution key from params, look
   up the shard interval via FindShardInterval (two hash lookups), and
   build a minimal Task - no deep copy, no tree walks, no deparse.

3. In SendNextQuery, defer TaskQueryStringAtIndex until the plain_sql
   label (cache hits never need it). Handle cache-full fallback by
   constructing the query string inline from the saved job query.

Safety: always reset workerJob->taskList = NIL at the top of
CitusBeginReadOnlyScan to prevent dangling pointers if the GUC is
toggled between executions.
…ogging

Add DML cache-hit fast path in CitusBeginModifyScan() for UPDATE/DELETE
queries with deferred pruning and no coordinator-evaluable functions.
Mirrors the existing SELECT fast path in CitusBeginReadOnlyScan(),
skipping CopyDistributedPlanWithoutCache, expression evaluation, and
RegenerateTaskForFasthPathQuery by extracting the distribution key
directly from ParamListInfo and building a minimal MODIFY_TASK.

Bug fixes:
- Add missing COPY_SCALAR_FIELD(distributionKeyParamId) in copyJobInfo()
  and COPY_SCALAR_FIELD(preparedStatementPlanId) in CopyNodeTask() so
  these fields survive copyObject() in the PG plan cache.
- Add missing WRITE_INT_FIELD(distributionKeyParamId) in OutJobFields()
  and WRITE_UINT64_FIELD(preparedStatementPlanId) in OutTask().
- Fix shardIntervalListList nesting: use list_make1(list_make1(...))
  instead of flat list in the SELECT cache-hit fast path.
- Fix use-after-free: move stale taskList/parametersInJobQueryResolved
  cleanup from AdaptiveExecutorCreateScan to CitusEndScan, gated on
  deferredPruning, so the plan is always clean for the next execution.
- Fix DML returning 0 rows: gate stale-state cleanup on deferredPruning
  to avoid clearing real taskList on non-deferred plans (INSERTs, etc.).
- Fix DML savedJobQueryForCaching: save template from original plan's
  jobQuery (pre-copy, pre-eval) since PartiallyEvaluateExpression with
  EVALUATE_FUNCTIONS silently switches to EVALUATE_FUNCTIONS_PARAMS for
  non-SELECT queries, resolving Params prematurely.
- Skip expensive two-phase evaluation path for INSERT statements since
  they are excluded from worker-side prepared statement caching.

Add DEBUG2 logging on four code paths: SELECT cache-hit fast path,
DML cache-hit fast path, DML two-phase evaluation, and SendNextQuery
cache hit/miss in adaptive_executor.c.
Single-row INSERT with a parameterized distribution key and no
coordinator evaluation now uses the same cache-hit fast path as
SELECT/UPDATE/DELETE.

Changes:
- RouterInsertJob: capture Param index for distribution key column
  so the executor can extract the value from ParamListInfo
- CitusBeginModifyScan: remove CMD_INSERT exclusion from three guards
  (fast path entry, saved query template, metadata attachment),
  set anchorDistributedTableId on fast-path tasks for INSERT
- SendNextQuery: branch on CMD_INSERT to use deparse_shard_query()
  instead of UpdateRelationToShardNames + pg_get_query_def for both
  cache-miss and cache-full fallback paths
- Update test comments to reflect INSERT is now cached

Also fixes INSERT ON CONFLICT deparse with shard name in rtable_names

When deparse_shard_query deparses an INSERT for a specific shard,
qualified column references in ON CONFLICT DO UPDATE (e.g.
'tablename.col') used the original base table name instead of the
shard name. This caused 'missing FROM-clause entry' errors on
workers and connection hangs.

The fix: in get_query_def_extended, after set_deparse_for_query
builds the rtable_names list, replace the INSERT target relation's
name with the shard name when (a) a valid distrelid/shardid is set,
(b) the RTE matches the distributed relation, and (c) the RTE has
no user-defined alias (preserving the citus_table_alias used by
INSERT...SELECT).
The fast-path optimisation (Phase 4+) creates tasks with TASK_QUERY_NULL
type to skip expensive deparsing. Multiple code paths call
TaskQueryString(task) which crashes on TASK_QUERY_NULL tasks:

1. Local executor — ParseQueryString(TaskQueryString(task), ...) when a
   fast-path task routes to local execution (shards on coordinator).
2. Adaptive executor plain_sql fallback — TaskQueryStringAtIndex() when
   the prepared statement cache is full.
3. CheckNodeCopyAndSerialization (cassert only) — serialises stale task
   pointers from a previous execution's freed memory.

Fixes:
- TaskQueryString(): handle TASK_QUERY_NULL by deparsing from
  jobQueryForPrepare template instead of crashing. Caches the result
  so subsequent calls don't re-deparse.
- Local executor: add TASK_QUERY_NULL handler that deparses from the
  template and plans locally.
- SELECT fast path: add CacheLocalPlanForShardQuery so local executor
  can use cached plan (DML fast path already had this).
- SELECT fast path: set anchorDistributedTableId (needed for INSERT
  deparsing via deparse_shard_query).
- GetDistributedPlan: clear stale taskList before
  CheckNodeCopyAndSerialization to prevent use-after-free in cassert.
- CopyNodeTask: add missing fields (jobQueryForPrepare,
  partitionKeyValue, colocationId).
- copyJobInfo: add missing fields (colocationId,
  savedJobQueryForCaching).
- OutTask/OutJobFields: add colocationId for serialisation.
@microsoft-github-policy-service
Copy link
Copy Markdown

@SarthakDalmia1 please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@akalend
Copy link
Copy Markdown

akalend commented Apr 5, 2026

@microsoft-github-policy-service agree

Copy link
Copy Markdown
Contributor

@colm-mchugh colm-mchugh left a comment

Choose a reason for hiding this comment

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

@SarthakDalmia1 PG16 support is now in the dev branch.
The feature is not yet in main, so this PR is not needed.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants