Skip to content

DocumentDB sync sha=afa22a5efe - #541

Merged
guanzhousongmicrosoft merged 24 commits into
documentdb:mainfrom
guanzhousongmicrosoft:documentdbpush_03_24_15_51
Mar 26, 2026
Merged

guanzhousongmicrosoft merged 24 commits into
documentdb:mainfrom
guanzhousongmicrosoft:documentdbpush_03_24_15_51

Conversation

@guanzhousongmicrosoft

Copy link
Copy Markdown
Member

No description provided.

Deepak Pemmaraju and others added 23 commits March 24, 2026 15:51
…, drop, currentOp, killOp, renameCollection inside transactions resulting in error 263 to mimic what the C# gateway does

### Does this PR have any customer impact?

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)

### Are you introducing any new config? If yes, do you have tests with and without them being set?

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description

blocking commands in transactions

----
#### AI description  (iteration 1)
#### PR Classification
This PR implements an API change to block unsupported commands from executing within multi-document transactions.

#### PR Summary
The changes enforce that specific commands run inside a transaction return error code 263 (OperationNotSupportedInTransaction) rather than executing normally.
- In `documentdb_tests/src/commands/transaction.rs`, a helper function and multiple validation functions are added to assert that commands like listCollections, drop, currentOp, killOp, and renameCollection are properly blocked in transactions.
- In `documentdb_gateway_core/src/processor/transaction.rs`, logic is introduced to return explicit error messages for these blocked commands when encountered in a transaction.
- Test files in `/gateway/native/tests/transaction_tests.rs` and `/oss/pg_documentdb_gw/documentdb_tests/tests/transaction_tests.rs` are updated with new tests to verify the rejection behavior.
<!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->

Signed-off-by: Guanzhou Song <[email protected]>
…ndexes

### Does this PR have any customer impact?
Yes

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Feature

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No
### Are you introducing any new config? If yes, do you have tests with and without them being set?
Yes
### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description

Add support for fillfactor in extended rum indexes to honor fillfactor as an option.
When set to >50 this means that inserts into tail pages will extend the index and fill the left page with that percentage rather than split 50/50.

Support this for both non-parallel build and reindex type scenarios for PG > 15

Signed-off-by: Guanzhou Song <[email protected]>
### Does this PR have any customer impact?

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)

### Are you introducing any new config? If yes, do you have tests with and without them being set?

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description
The new WithExpr accumulators support collation in their comparisons, but the `$group` stage itself does not yet support collation for grouping keys.
Initially, enabling `EnableCollation` + `CanUseWithExprAggregates()` was enough to let collation pass through HandleGroup, but this inadvertently allowed collation into the full $group stage — including the grouping key path, which doesn't respect it.

This PR adds a dedicated GUC `EnableCollationForNewGroupAccumulators` to explicitly gate collation in $group so it only flows through **only** to the accumulators.

Extra Change:
Rename `bson_dollar_ops_collation_tests_runtime` to `bson_collation_runtime_tests`

----
#### AI description  (iteration 1)
#### PR Classification
New feature: Introduce a GUC to control collation support for new group accumulators.

#### PR Summary
This pull request implements a new configuration flag (`enableCollationForNewGroupAccumulators`) that governs whether collation is allowed in new group accumulator stages. It updates the aggregation pipeline logic, modifies test cases and SQL regression files to use and validate the new setting, and revises documentation accordingly.
- **`src/configs/feature_flag_configs.c` & `include/aggregation/bson_aggregation_pipeline.h`**: Define and expose the new GUC.
- **`src/aggregation/bson_aggregation_pipeline.c`**: Update collation handling in the group accumulator logic to respect the new flag.
- **Test and SQL regression files**: Incorporate SET commands for the new flag and adjust expected outputs.
- **Documentation**: Update feature flag status to include `enableCollationForNewGroupAccumulators`.
<!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->

Signed-off-by: Guanzhou Song <[email protected]>
### Does this PR have any customer impact?
Yes
### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Feature
### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No
### Are you introducing any new config? If yes, do you have tests with and without them being set?
No
### ChangeLog (Refer [Template](../oss/CHANGELOG.md))
1.111
### Description
Previously, we mapped the valid but unsupported commands incorrectly to CommandNotFound.
In order to support this, we have to complete the whole list of the commands including the valid but unsupported commands.
We moved all of the supported and unsupported commands to a new enum

Related work items: #5058431

Signed-off-by: Guanzhou Song <[email protected]>
…fetime used in npgsql

### Does this PR have any customer impact?
Minimal, it only affects how long idle connections are allowed to stay alive.

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Refactoring

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No

### Are you introducing any new config? If yes, do you have tests with and without them being set?
No new configs

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))
Change the max connection age to match connection lifetime used in npgsql *[Refactoring]*

### Description
Change the max connection age to match connection lifetime used in npgsql

Signed-off-by: Guanzhou Song <[email protected]>
   No. This is a code-quality improvement only -- all changes are lint annotations, idiomatic Rust refactors, and Cargo metadata additions. No behavioral or API changes.

   ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)

   Refactoring

   ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)

   No

   ### Are you introducing any new config? If yes, do you have tests with and without them being set?

   No new config. Workspace-level Clippy lint configuration was expanded in `pg_documentdb_gw/Cargo.toml` (pedantic, nursery, cargo, and restriction lint groups) and `clippy.toml`
  (`allow-expect-in-tests`, `allow-unwrap-in-tests`).

   ### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

   N/A -- no user-facing changes.

   ### Description

   Bring the gateway Rust codebase (`pg_documentdb_gw/`) to a fully clippy-clean state under strict linting (`-D warnings`) with pedantic, nursery, cargo, and targeted restriction lints enabled.

   - **Lint configuration** -- Enabled `clippy::pedantic`, `clippy::nursery`, `clippy::cargo`, and 30+ restriction lints (e.g. `unwrap_used`, `expect_used`, `str_to_string`, `clone_on_ref_ptr`, `map_err_ignore`) in the workspace `Cargo.toml`. Added `clippy.toml` settings to allow `unwrap`/`expect` in test code.
   - **Cargo metadata** -- Added `repository`, `readme`, `keywords`, `categories`, and `description` fields to all four crate manifests (`documentdb_gateway`, `documentdb_gateway_core`, `documentdb_macros`, `documentdb_tests`).

   **Validation:** All three workspaces pass `cargo clippy --all-targets --all-features -- -D warnings`:
   - `pg_documentdb_gw/Cargo.toml`
   - `pg_documentdb_gw_host/Cargo.toml` (with `--features pg16`)

Related work items: #4689753

Signed-off-by: Guanzhou Song <[email protected]>
### Does this PR have any customer impact?
Yes

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
FEature/Bugfix
### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No
### Are you introducing any new config? If yes, do you have tests with and without them being set?

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description

The parallel build for extended_rum was loading the wrong background worker - fix that
Enable parallel build by default using the postgres default computation for parallel builds

----
#### AI description  (iteration 1)
#### PR Classification
This pull request introduces a new feature that enables parallel index build support for OSS Extended RUM.

#### PR Summary
The changes enable parallel index builds on supported PostgreSQL versions by adding conditional logic and a new GUC variable.
- **`pg_documentdb_extended_rum/core/src/ruminsert.c` and `pgmongo_rum/src/ruminsert.c`**: Added conditional code to assign parallel workers using `plan_create_index_workers` when `RumEnableParallelIndexBuild` is enabled, adjusting worker assignment checks.
- **`pg_documentdb_extended_rum/core/src/rumconfigs.c` and `pg_documentdb_extended_rum/core/include/pg_documentdb_rum.h`**: Introduced the Boolean GUC `RumEnableParallelIndexBuild` (default true) to control parallel build functionality.
- **Test files**: Moved related tests from `/pgmongo` directories to `/oss/pg_documentdb` test directories and updated test schedules to include the new parallel build tests.
<!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->

Signed-off-by: Guanzhou Song <[email protected]>
… command definition)

schema/command definition

----
This pull request implements a new feature by introducing the bulkWrite command for 8.0.

The changes add the command schema, initial stub implementation, and corresponding documentation for the bulkWrite command, laying the groundwork for multi-collection batch write support.
- Added new documentation in ``/docs/pgmongo/design_docs/data_plane/commands/bulkWrite.md`` detailing the syntax, behavior, design, and test plan.
- Introduced a new C command implementation in ``/oss/pg_documentdb/src/commands/bulk_write.c`` that defines the bulkWrite command (Phase 1 stub).
- Extended the OID cache by adding ``BulkWriteCommandOid`` in ``/pgmongo/src/metadata/oid_cache.c`` and its header file, along with updates to the feature counter.
- Updated ``/pgmongo/src/infrastructure/command_funcs.c`` to dispatch the new ``MongoFunction_BulkWrite``.
- Added new SQL UDF procedure scripts in ``/oss/pg_documentdb/sql/udfs/commands_crud/bulkWrite--*.sql`` to expose the command via the API schema.
<!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->

Signed-off-by: Guanzhou Song <[email protected]>
 ### Does this PR have any customer impact?

   No. This is an internal refactoring of how the Rust gateway executes PostgreSQL queries. All existing retry behavior is preserved — the same error codes produce the same retry decisions. No external API changes.

   ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
   Refactoring

   ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
   No.

   ### Are you introducing any new config? If yes, do you have tests with and without them being set?
   No new configuration. Existing retry-related configuration (`short_retry_*`, `long_retry_*`, `command_timeout`, `is_replica_cluster`) is consumed from the same sources as before.

   ### ChangeLog (Refer [Template](../oss/CHANGELOG.md))
   N/A — internal gateway refactoring, no user-visible behavior change.

   ### Description
Introduce centralized query execution functions and migrating all data client methods to use them.

   **Problem:** The retry loop in `process.rs` wrapped 36+ request dispatches in a monolithic block. Retry logic was coupled to the request processor, impossible to reuse for individual queries, and the retry entry point in `connection.rs` was not present

   **Solution:** New query execution function in `query_dispatch.rs`:

   - **`query_with_retry`** — Acquires a connection from the pool, executes a query closure, classifies errors via `retry_policy()`, applies jittered backoff (short/long), re-acquires fresh connections on retry, and respects command timeout budgets.

   All ~47 `execute_*` methods in `DocumentDBDataClient` now route through retry functions. The retry loop in `process.rs` has been removed — it is now a pure request dispatcher.

   **Key design decisions:**
   - Transaction-aware: methods with active transactions use `pull_connection` directly (can't retry mid-transaction)
   - Cursor-returning queries use generic `T` return to pass back `(Vec<Row>, Arc<Connection>)`
   - Read-only delete/drop paths split into `_when_readonly` variants that wrap in transactions internally
   - `QueryContext` carries per-query retry flags; helper constructors on data clients populate from `DynamicConfiguration`

Related work items: #4317407, #5059170, #5059175

Signed-off-by: Guanzhou Song <[email protected]>
… setup postgres script

### Does this PR have any customer impact?
No

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Infrastructure

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No

### Are you introducing any new config? If yes, do you have tests with and without them being set?
No
### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description

This enables to compile and install a local PG build

Signed-off-by: Guanzhou Song <[email protected]>
…o driver

### Does this PR have any customer impact?
No

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Bugfix for code_name error field

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No

### Are you introducing any new config? If yes, do you have tests with and without them being set?
No

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))
N/A

### Description

Driver sdk expects code_name property on error which exposed to users.
In native product, on running a few manual tests, the code_name seems to matching with the corresponding mongo error int based on native error docs.

In this pr, remove inconsistencies in how error code name assigned and compute it from ErrorCode enum directly.

Signed-off-by: Guanzhou Song <[email protected]>
We relied on the request to get the authorization mechanism, in some cases, the request omits this "mechanism" field and since we were not tracking it from the time we authenticated, we just lost it. With this change, we store the authentication mechanism when we either do sasl start or continue and default it to Unknown for operations like isMaster, hello, where it is expected that mechanism is missing.

Before:

![image (2).png](https://msdata.visualstudio.com/ba574a88-a171-48e0-8fcb-5fef6d23739c/_apis/git/repositories/501a5e7e-ffdc-4d1e-a5e6-910f73c6eb9a/pullRequests/2005476/attachments/image%20%282%29.png)

After:

![image.png](https://msdata.visualstudio.com/ba574a88-a171-48e0-8fcb-5fef6d23739c/_apis/git/repositories/501a5e7e-ffdc-4d1e-a5e6-910f73c6eb9a/pullRequests/2005476/attachments/image.png)

Related work items: #5098190

Signed-off-by: Guanzhou Song <[email protected]>
…s for environments without IPv6

### Does this PR have any customer impact?
Yes, unblock customers to run gateway on environment where with no ipv6 support like AKS Edge.

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Bugfix.

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No

### Are you introducing any new config? If yes, do you have tests with and without them being set?
No

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

## Summary
Implements dual IPv4/IPv6 TCP listener support for the OSS Rust gateway, enabling operation in environments where IPv6 is unavailable (e.g., AKS Edge).

## Changes
- Added `create_tcp_listeners()` function that binds to both IPv4 (`0.0.0.0`) and IPv6 (`[::]`) addresses
- Uses `IPV6_V6ONLY` socket option via `socket2` crate for consistent cross-platform behavior
  - Linux defaults to dual-stack (IPv6 socket accepts IPv4), Windows/macOS default to IPv6-only
  - Explicitly setting `IPV6_V6ONLY=true` ensures we need both listeners on all platforms
- If one address family fails to bind, logs a warning and continues with the other
- Returns an error only if both bindings fail
- Refactored connection accept loop with `spawn_tcp_handler`/`spawn_unix_handler` helpers

## Behavior
| Scenario | Result |
|----------|--------|
| Both IPv4 and IPv6 available | Both listeners active |
| Only IPv4 available (no IPv6) | IPv4 listener active, warning logged |
| Only IPv6 available | IPv6 listener active, warning logged |
| Neither available | Error returned |

## Testing
- Added 7 unit tests covering localhost, non-localhost, port assignment, partial failure, and total failure scenarios
- All 19 existing tests pass

## Related
- Follows pattern from documentdb#485
- Matches C# gateway dual-listener approach (`IPAddress.Any` + `IPAddress.IPv6Any`)

Signed-off-by: Guanzhou Song <[email protected]>
…h supplemental filters

### Does this PR have any customer impact?
Yes

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Bugfix

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No
### Are you introducing any new config? If yes, do you have tests with and without them being set?

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description

With backwards walk, sort and filter on supplemental path, ensure that the ordering works as expected.

Signed-off-by: Guanzhou Song <[email protected]>
## Description
Performance optimization for `$first` and `$last` accumulator operators in the `$group` aggregation pipeline stage when no preceding `$sort` stage is present (referred to as "OnSorted" path in code). Gated behind the `enableNewFirstLastAccumulators` feature flag (default: off).

### The new aggregates :
```
   BSONFIRSTWITHEXPR(document, expressionSpec, variableSpec, collationString)
   BSONLASTWITHEXPR(document, expressionSpec, variableSpec, collationString)
```

1. Eliminate redundant allocation and unnecessary BSON materialization by removing calls to separate 'bson_expression_get' function. This is done by embedding expression evaluation directly in the transition function, reducing per-row evaluation overhead.
2. Defining a 'Combine' function which allows pushing the group to individual workers and pulling all data in coordinator (missing before).
2. In case of $first, do not evaluate any expression after accumulating a result.

### Why is the preceding `$sort` path for `$first` / `$last` and `$firstN` / `$lastN` not optimized ?
For these scenarios, the transition function takes in full document with optional sort spec (not to be confused with expression spec for $first[N] / $last[N] property). It then maintains sorted N documents and only applying the expression get/map on final result. The optimization opportunity described above thus doesn't exist here.

### Callouts
`bson_aggregate_group_firstlast_explain_sharded` is only run on pg17 and pg18+citus14 as EXPLAIN is broken on prior versions (known citus bug handling the cstring version)

## Does this PR have any customer impact?
Performance improvement

## Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Run aggregates on 20million row table with a warm up stage and then calculate average of 3 runs using \timing.

![image.png](https://msdata.visualstudio.com/ba574a88-a171-48e0-8fcb-5fef6d23739c/_apis/git/repositories/501a5e7e-ffdc-4d1e-a5e6-910f73c6eb9a/pullRequests/1991292/attachments/image.png)  schema level changes? (Table, Column, Index, UDF, etc level changes)
Yes

## Are you introducing any new config? If yes, do you have tests with and without them being set?
New GUC documentdb.enableNewFirstLastAccumulators (default: false).
Version-gated to require cluster version ≥ 0.111-0 via CanUseWithExprFirstLastAggregates() check.

## ChangeLog (Refer Template)
Updated

Signed-off-by: Guanzhou Song <[email protected]>
…r queries for streaming cursor

### Does this PR have any customer impact?
Yes

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Bugfix

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No

### Are you introducing any new config? If yes, do you have tests with and without them being set?
Yes, Yes

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description
UpdatePathsWithExtensionStreamingCursorPlans scans rel->baserestrictinfo looking for extension FuncExprs like `bson_dollar_in(document, '{"_id": {"$in": [...]}}'::bson)`. When it finds one, it can extract the `$in` values and construct a new btree primary key IndexPath with `object_id = ANY(...)` pushed into the index clauses.

In the late flow (flag off), ReplaceExtensionFunctionOperatorsInRestrictionPaths runs first and transforms that bson_dollar_in FuncExpr into a different form (an OpExpr). By the time UpdatePathsWithExtensionStreamingCursorPlans runs, the original FuncExpr is gone — it can no longer recognize/extract the $in values, so the btree IndexPath only gets shard_key_value = X as an index clause. The $in filter ends up as a runtime filter instead.

In the early flow (flag on), UpdatePathsWithExtensionStreamingCursorPlans runs first against the untransformed baserestrictinfo, finds the original bson_dollar_in FuncExpr, extracts the values, and builds the IndexPath with object_id = ANY(...) in Index Cond. Then ReplaceExtensionFunctionOperatorsInRestrictionPaths processes the remaining quals — but the pushdown has already happened.

For 1M docs, and with 8000 $in, 1000 batchsize we roughly see a ~5x improvement (520ms vs 100ms)

Signed-off-by: Guanzhou Song <[email protected]>
…s for $min/$max

## Problem
`$group` pipelines using `$min` / `$max` with collation return incorrect results on **sharded collections** for remote executions.

When aggregation executes on worker nodes, collation is silently ignored, defaulting to binary comparison.

## Root Cause

Currently, collation applicability during execution depends on session-level GUCs that are **not propagated to worker nodes**.

Specifically:

*   Multiple code paths use `IsCollationApplicable()`, which gates collation on:
    *   `EnableCollation` GUC
    *   collation string validity
*   Worker nodes default `EnableCollation = OFF`
*   As a result, workers treat collation as not applicable even though it was validated at planning time

Affected paths:

*   `CompareStrings()` falls back to binary `memcmp`
*   `BsonMinMaxWithExprTransitionCore()` does not serialize collation
*   `BsonMinMaxWithExprCombineCore()` merges partial results with NULL collation

## Fix
Replace **`IsCollationApplicable()`** with **`IsCollationValid()`** in all execution-time paths.

### Rationale
*   Collation is validated and authorized **at query planning time** on the coordinator
*   Worker nodes should trust the provided collation parameter
*   Execution-time checks must only validate string correctness, not session GUC state

### Changes
*   Replace `IsCollationApplicable()` → `IsCollationValid()` in:
    *   String comparison path
    *   `$min` / `$max` transition function
    *   Partial aggregate combine path
*   Ensure collation is preserved during aggregate state serialization/deserialization
*   Worker-side comparisons now correctly use ICU collation when provided

## Testing

Added **Test 17** to BSON aggregation pipeline tests.

Test coverage:
*   `$group` with `$min` / `$max`
*   Multiple documents per group
*   Ensures worker-side transition path is exercised

## Result
*   Correct ordering for `$min` / `$max` on sharded collections
*   Consistent collation behavior between coordinator and worker nodes
*   Eliminates silent correctness bug in distributed aggregation

### Why recv/in (PgbsonToSinglePgbsonElementWithCollation) functions don't need changes (for now)
`bsonaggvalue_recv` and `bsonaggvalue_in` both call `PgbsonToSinglePgbsonElementWithCollation` which also gates on EnableCollation.
However, these deserialization functions run on the  coordinator (which receives partial aggregate results from workers), where the GUC is ON.

Signed-off-by: Guanzhou Song <[email protected]>
…om setup configuration json file

### Does this PR have any customer impact?

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)

### Are you introducing any new config? If yes, do you have tests with and without them being set?

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description

Add instance kind to hello response and read it from setup configuration json on the gw

This will add a field to the topology document send back in the hello response like:

```json
internal { versions: [....], kind: '' }
```

Signed-off-by: Guanzhou Song <[email protected]>
…ubTransactionCount

### Does this PR have any customer impact?

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)

### Are you introducing any new config? If yes, do you have tests with and without them being set?

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description
Relaxing setting on a GUC for BatchWriteSubTransactionCount

----
#### AI description  (iteration 1)
#### PR Classification
This pull request implements a configuration change that relaxes restrictions on a GUC setting.

#### PR Summary
The update modifies the definition of BatchWriteSubTransactionCount by removing restrictive flags, allowing the setting to be modified more freely.
- In `oss/pg_documentdb/src/configs/system_configs.c`, the flags `GUC_NO_SHOW_ALL` and `GUC_NOT_IN_SAMPLE` are removed and replaced with a zero value, thereby relaxing the parameter’s constraints.
<!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->

Signed-off-by: Guanzhou Song <[email protected]>
…e event for changestream

### Does this PR have any customer impact?
No

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Feature

### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No

### Are you introducing any new config? If yes, do you have tests with and without them being set?
No

### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description

This is a minimal change to consider updates performed through aggregation pipeline as `replace` events instead of `update` and if update description changes is too verbose converting it too `replace`.
For optimal diff algorithms we need sorted field iterators which is anyway an open item so we can revisit this after.

----
#### AI description  (iteration 1)
#### PR Classification
This PR fixes the behavior of changestream update events by treating updates performed via pipeline stages as replacement events.

#### PR Summary
The changes ensure that update operations using pipelines (e.g., with stages like $set, $addFields, etc.) are reported as replace events both in the changestream and in the underlying metadata. This improves the correctness of change event reporting and updates test expectations accordingly.
- `pgmongo/src/test/regress/expected/pgmongo_change_stream_update_description.out` and `pgmongo/src/test/regress/sql/pgmongo_change_stream_update_description.sql`: Updated tests to verify that pipeline update operations now yield replace events.
- `oss/pg_documentdb/src/update/bson_update.c`: Modified logic to classify pipeline updates as replacement events.
- `pgmongo/src/change_stream/change_stream_xlog_utils.c`: Adjusted update description deserialization to conditionally process the document only for traditional updates.
- `pgmongo/src/change_stream/change_stream_wal_utils.c`: Added null checks and improved copying of update descriptions to handle events consistently.
<!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->

Signed-off-by: Guanzhou Song <[email protected]>
…y (size=0)

### Does this PR have any customer impact?
Yes

### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Bugfix
### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes)
No
### Are you introducing any new config? If yes, do you have tests with and without them being set?
No
### ChangeLog (Refer [Template](../oss/CHANGELOG.md))

### Description
QT2QTN is called on an empty TSQuery (size=0) when websearch_to_tsquery produces no valid tokens (e.g., empty string or only stop words)
-The empty TSQuery is 8 bytes (header only, size=0)
-GETQUERY(query) returns pointer at offset 8 → past the object
-QT2QTN reads in->type (1 byte) from that invalid location

ASAN is unable to detect this issue because reading one byte beyond an 8-byte palloc'd TSQuery still falls within the valid 16KB malloc block.
Valgrind tracks memory at the byte level and can identify this problem.
```
==00:00:00:49.090 80606== VALGRINDERROR-BEGIN
==00:00:00:49.090 80606== Invalid read of size 1
==00:00:00:49.090 80606==    at 0x661ABD: QT2QTN (tsquery_util.c:34)
==00:00:00:49.090 80606==    by 0x8672506: BsonTextGenerateTSQueryCore (bson_text_gin.c:565)
==00:00:00:49.090 80606==    by 0x8671ACC: BsonTextGenerateTSQuery (bson_text_gin.c:318)
==00:00:00:49.090 80606==    by 0x8682DBF: GetOpExprClauseFromIndexOperator (index_support.c:3989)
==00:00:00:49.090 80606==    by 0x8680C0B: HandleSupportRequestCondition (index_support.c:3214)
==00:00:00:49.090 80606==    by 0x867AAA6: dollar_support (index_support.c:396)
==00:00:00:49.090 80606==    by 0x6A47B3: FunctionCall1Coll (fmgr.c:1110)
==00:00:00:49.090 80606==    by 0x6A503A: OidFunctionCall1Coll (fmgr.c:1388)
==00:00:00:49.090 80606==    by 0x476207: get_index_clause_from_support (indxpath.c:2632)
==00:00:00:49.090 80606==    by 0x47796C: match_funcclause_to_indexcol (indxpath.c:2585)
==00:00:00:49.090 80606==    by 0x478437: match_clause_to_indexcol (indxpath.c:2289)
==00:00:00:49.090 80606==    by 0x47854B: match_clause_to_index (indxpath.c:2171)
==00:00:00:49.090 80606==  Address 0x12b42460 is 1,824 bytes inside a block of size 16,384 alloc'd
==00:00:00:49.090 80606==    at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==00:00:00:49.091 80606==    by 0x6C1298: AllocSetAlloc (aset.c:924)
==00:00:00:49.091 80606==    by 0x6CA40E: palloc (mcxt.c:1240)
==00:00:00:49.091 80606==    by 0x41E52A: new_list (list.c:136)
==00:00:00:49.091 80606==    by 0x41E8D1: lappend (list.c:343)
==00:00:00:49.091 80606==    by 0x64ECFC: get_quals_from_indexclauses (selfuncs.c:6421)
==00:00:00:49.091 80606==    by 0x64EF62: genericcostestimate (selfuncs.c:6497)
==00:00:00:49.091 80606==    by 0x64F689: btcostestimate (selfuncs.c:6893)
==00:00:00:49.091 80606==    by 0x867E034: documentdb_btcostestimate (index_support.c:2061)
==00:00:00:49.091 80606==    by 0x46F72A: cost_index (costsize.c:590)
==00:00:00:49.091 80606==    by 0x4AF5EC: create_index_path (pathnode.c:1031)
==00:00:00:...

Signed-off-by: Guanzhou Song <[email protected]>
Co-authored-by: Copilot <[email protected]>
Signed-off-by: Guanzhou Song <[email protected]>
@guanzhousongmicrosoft
guanzhousongmicrosoft requested a review from a team as a code owner March 24, 2026 20:07
@guanzhousongmicrosoft
guanzhousongmicrosoft force-pushed the documentdbpush_03_24_15_51 branch 2 times, most recently from 66f2859 to 9ad99e5 Compare March 25, 2026 15:36
- Add clippy #[expect] attributes to rename_collection.rs test file
- Add trailing newline to public_api_schema.out expected output
- Increase background index build timeout from 10s to 60s in
  distributed test helpers (max_attempts=600) and update both
  expected output files (single-node and multinode) including
  shifted psql NOTICE line references

Co-authored-by: Copilot <[email protected]>
@guanzhousongmicrosoft
guanzhousongmicrosoft force-pushed the documentdbpush_03_24_15_51 branch from 9ad99e5 to 51e0d7b Compare March 25, 2026 15:55
@guanzhousongmicrosoft
guanzhousongmicrosoft enabled auto-merge (rebase) March 26, 2026 16:18
@guanzhousongmicrosoft
guanzhousongmicrosoft merged commit 16afd9e into documentdb:main Mar 26, 2026
13 checks passed
@guanzhousongmicrosoft
guanzhousongmicrosoft deleted the documentdbpush_03_24_15_51 branch March 26, 2026 16:22
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.