Merged PR 1672946: [Update] Make update parsing cheaper

### Does this PR have any customer impact?
Yes
### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc)
Perf
### 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

Currently for Update/Delete, we currently parse the update spec, query spec, etc into pgbsons on startup. Then reuse it per commands.

This has a few issues - for large document requests, this causes us to duplicate memory and persist it for the duration of the update and also transcode all up front - this is worse for multi-node when all we need to do is build yet another update spec and push it to the worker.

Instead, we now only cache pointers to the spec document; then when we need it we convert to pgbson only if necessary.

A consequence of this is that on a single node update, if we're doing a simple updateOne on _id then we would never serialize the updateSpec at all (for instance).

We also more eagerly free memory on the intermediate update specs.

----
#### AI description  (iteration 1)
#### PR Classification
Performance optimization for update parsing by refactoring BSON value handling.

#### PR Summary
This PR streamlines update parsing by replacing heavy BSON initialization routines with lightweight wrappers and converting update-related types from `pgbson*` to `bson_value_t*`, which reduces overhead and improves coordinator/worker compatibility.
- `src/commands/update.c`: Replaced multiple `PgbsonInitFromDocumentBsonValue` and similar calls with efficient wrappers like `CreateBsonValueFrom` and updated serialization (including back-compatible array filter and update document formats).
- `include/commands/update.h`: Updated update structure fields to use `bson_value_t*` instead of `pgbson*`, aligning interfaces with the new parsing approach.
- `src/update/bson_update.c` and `bson_update_operators_workflow.c`: Refactored update type determination and replace document logic to use new BSON value iterators and helper functions.
- Other modules (e.g. `commands/find_and_modify.c`, `commands/delete.c`, query operators, sharding) were updated to leverage the lighter-weight BSON representation and its associated helper routines.
<!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->
This commit is contained in:
Vinod Sridharan authored and Shuai Tian committed 2025-05-29 12:12:31 +08:00
1 parent f63bc316ac
commit 8261e772f4
25 files changed
+343 -235

No files matched your search

+45 -42
View File
@@ -78,17 +78,21 @@ typedef struct
/* Forward declaration */
/* --------------------------------------------------------- */
static void BuildBsonUpdateMetadata(BsonUpdateMetadata *metadata, pgbson *updateSpec,
pgbson *querySpec, pgbson *arrayFilters,
static void BuildBsonUpdateMetadata(BsonUpdateMetadata *metadata,
const bson_value_t *updateSpec,
const bson_value_t *querySpec, const
bson_value_t *arrayFilters,
bool buildSourceDocOnUpsert);
static pgbson * BsonUpdateDocumentCore(pgbson *sourceDocument, pgbson *updateSpec,
static pgbson * BsonUpdateDocumentCore(pgbson *sourceDocument, const
bson_value_t *updateSpec,
BsonUpdateMetadata *metadata);
static pgbson * ProcessReplaceDocument(pgbson *sourceDoc, pgbson *updateSpec,
static pgbson * ProcessReplaceDocument(pgbson *sourceDoc, const bson_value_t *updateSpec,
bool isUpsert);
static pgbson * BuildBsonDocumentFromQuery(pgbson *sourceDoc, pgbson *querySpec,
static pgbson * BuildBsonDocumentFromQuery(pgbson *sourceDoc, const
bson_value_t *querySpec,
UpdateType updateType);
static void ProcessQueryProjectionValue(void *context, const char *path, const
@@ -171,10 +175,21 @@ bson_update_document(PG_FUNCTION_ARGS)
}
pgbson *sourceDocument = PG_GETARG_PGBSON(0);
pgbson *updateSpec = PG_GETARG_PGBSON(1);
pgbson *querySpec = PG_GETARG_PGBSON(2);
pgbson *arrayFilters = PG_GETARG_MAYBE_NULL_PGBSON(3);
pgbson *updateSpecDoc = PG_GETARG_PGBSON(1);
pgbson *querySpecDoc = PG_GETARG_PGBSON(2);
pgbson *arrayFiltersDoc = PG_GETARG_MAYBE_NULL_PGBSON(3);
pgbsonelement updateSpecElement;
PgbsonToSinglePgbsonElement(updateSpecDoc, &updateSpecElement);
bson_value_t querySpec = ConvertPgbsonToBsonValue(querySpecDoc);
pgbsonelement arrayFiltersBase = { 0 };
bson_value_t *arrayFilters = NULL;
if (arrayFiltersDoc != NULL)
{
PgbsonToSinglePgbsonElement(arrayFiltersDoc, &arrayFiltersBase);
arrayFilters = &arrayFiltersBase.bsonValue;
}
/* an empty document is treated as an upsert. */
bool buildSourceDocOnUpsert = IsPgbsonEmptyDocument(sourceDocument);
@@ -189,7 +204,7 @@ bson_update_document(PG_FUNCTION_ARGS)
&stateArgPositions[0],
3,
BuildBsonUpdateMetadata,
updateSpec, querySpec, arrayFilters,
&updateSpecElement.bsonValue, &querySpec, arrayFilters,
buildSourceDocOnUpsert);
if (metadata == NULL)
@@ -215,7 +230,8 @@ bson_update_document(PG_FUNCTION_ARGS)
elog(ERROR, "incorrect number of output arguments");
}
pgbson *document = BsonUpdateDocumentCore(sourceDocument, updateSpec, metadata);
pgbson *document = BsonUpdateDocumentCore(sourceDocument,
&updateSpecElement.bsonValue, metadata);
if (document != NULL)
{
@@ -255,7 +271,8 @@ bson_update_returned_value(PG_FUNCTION_ARGS)
* can be used to validate given update document.
*/
void
ValidateUpdateDocument(pgbson *updateSpec, pgbson *querySpec, pgbson *arrayFilters)
ValidateUpdateDocument(const bson_value_t *updateSpec, const bson_value_t *querySpec,
const bson_value_t *arrayFilters)
{
BsonUpdateMetadata metadata = { 0 };
bool buildSourceDocOnUpsert = false;
@@ -269,8 +286,8 @@ ValidateUpdateDocument(pgbson *updateSpec, pgbson *querySpec, pgbson *arrayFilte
* returns NULL if no update is needed.
*/
pgbson *
BsonUpdateDocument(pgbson *sourceDocument, pgbson *updateSpec,
pgbson *querySpec, pgbson *arrayFilters)
BsonUpdateDocument(pgbson *sourceDocument, const bson_value_t *updateSpec,
const bson_value_t *querySpec, const bson_value_t *arrayFilters)
{
BsonUpdateMetadata metadata = { 0 };
@@ -294,7 +311,7 @@ BsonUpdateDocument(pgbson *sourceDocument, pgbson *updateSpec,
* Returns NULL if update was a no-op.
*/
pgbson *
BsonUpdateDocumentCore(pgbson *sourceDocument, pgbson *updateSpec,
BsonUpdateDocumentCore(pgbson *sourceDocument, const bson_value_t *updateSpec,
BsonUpdateMetadata *updateMetadata)
{
bson_iter_t sourceDocumentIterator;
@@ -396,8 +413,8 @@ BsonUpdateDocumentCore(pgbson *sourceDocument, pgbson *updateSpec,
* into the metadata value provided.
*/
static void
BuildBsonUpdateMetadata(BsonUpdateMetadata *metadata, pgbson *updateSpec,
pgbson *querySpec, pgbson *arrayFilters,
BuildBsonUpdateMetadata(BsonUpdateMetadata *metadata, const bson_value_t *updateSpec,
const bson_value_t *querySpec, const bson_value_t *arrayFilters,
bool buildSourceDocOnUpsert)
{
metadata->updateType = DetermineUpdateType(updateSpec);
@@ -417,9 +434,7 @@ BuildBsonUpdateMetadata(BsonUpdateMetadata *metadata, pgbson *updateSpec,
{
if (arrayFilters != NULL)
{
pgbsonelement arrayFiltersElement = { 0 };
PgbsonToSinglePgbsonElement(arrayFilters, &arrayFiltersElement);
if (!IsBsonValueEmptyArray(&arrayFiltersElement.bsonValue))
if (!IsBsonValueEmptyArray(arrayFilters))
{
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE),
errmsg(
@@ -442,9 +457,7 @@ BuildBsonUpdateMetadata(BsonUpdateMetadata *metadata, pgbson *updateSpec,
case UpdateType_ReplaceDocument:
{
/* Simply validate the replace doc */
bson_iter_t updateIterator;
PgbsonInitIteratorAtPath(updateSpec, "", &updateIterator);
if (!BSON_ITER_HOLDS_DOCUMENT(&updateIterator))
if (updateSpec->value_type != BSON_TYPE_DOCUMENT)
{
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg(
"Replace should be a document")));
@@ -468,25 +481,18 @@ BuildBsonUpdateMetadata(BsonUpdateMetadata *metadata, pgbson *updateSpec,
* Otherwise it's a replace.
*/
UpdateType
DetermineUpdateType(pgbson *updateSpec)
DetermineUpdateType(const bson_value_t *updateSpec)
{
bson_iter_t updateIterator;
bson_iter_t updateDocumentIterator;
bool isUpdateTypeReplacement = false;
if (!PgbsonInitIteratorAtPath(updateSpec, "", &updateIterator))
{
ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg(
"Update should be specified")));
}
if (BSON_ITER_HOLDS_ARRAY(&updateIterator))
if (updateSpec->value_type == BSON_TYPE_ARRAY)
{
return UpdateType_AggregationPipeline;
}
else if (BSON_ITER_HOLDS_DOCUMENT(&updateIterator) &&
bson_iter_recurse(&updateIterator, &updateDocumentIterator))
else if (updateSpec->value_type == BSON_TYPE_DOCUMENT)
{
BsonValueInitIterator(updateSpec, &updateDocumentIterator);
while (bson_iter_next(&updateDocumentIterator))
{
const char *path = bson_iter_key(&updateDocumentIterator);
@@ -532,23 +538,20 @@ DetermineUpdateType(pgbson *updateSpec)
* from the filters into the target document.
*/
static pgbson *
ProcessReplaceDocument(pgbson *sourceDoc, pgbson *updateSpec,
ProcessReplaceDocument(pgbson *sourceDoc, const bson_value_t *updateSpec,
bool isUpsert)
{
bson_iter_t sourceDocIterator;
bson_iter_t updateIterator;
bson_iter_t replaceDocumentIterator;
pgbson_writer writer;
PgbsonInitIteratorAtPath(updateSpec, "", &updateIterator);
if (!BSON_ITER_HOLDS_DOCUMENT(&updateIterator))
if (updateSpec->value_type != BSON_TYPE_DOCUMENT)
{
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg(
"Replace should be a document")));
}
uint32_t documentLength;
const uint8_t *documentBytes;
bson_iter_document(&updateIterator, &documentLength, &documentBytes);
uint32_t documentLength = updateSpec->value.v_doc.data_len;
const uint8_t *documentBytes = updateSpec->value.v_doc.data;
/* validate the replace document. */
ValidateInputBsonBytes(documentBytes,
@@ -652,13 +655,13 @@ ProcessReplaceDocument(pgbson *sourceDoc, pgbson *updateSpec,
* will be used in the upsert case as the initial document.
*/
static pgbson *
BuildBsonDocumentFromQuery(pgbson *sourceDoc, pgbson *querySpec,
BuildBsonDocumentFromQuery(pgbson *sourceDoc, const bson_value_t *querySpec,
UpdateType updateType)
{
BsonIntermediatePathNode *root = MakeRootNode();
bson_iter_t queryDocIterator;
PgbsonInitIterator(querySpec, &queryDocIterator);
BsonValueInitIterator(querySpec, &queryDocIterator);
QueryProjectionContext context = { .root = root, .updateType = updateType };
bool isUpsert = true;
@@ -163,17 +163,16 @@ static MongoUpdateAggregationOperator AggregationOperators[] =
* the pipeline against documents to produce modified documents.
*/
struct AggregationPipelineUpdateState *
GetAggregationPipelineUpdateState(pgbson *updateSpec)
GetAggregationPipelineUpdateState(const bson_value_t *updateSpec)
{
bson_iter_t updateIterator;
PgbsonInitIteratorAtPath(updateSpec, "", &updateIterator);
if (!BSON_ITER_HOLDS_ARRAY(&updateIterator) ||
!bson_iter_recurse(&updateIterator, &updateIterator))
if (updateSpec->value_type != BSON_TYPE_ARRAY)
{
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg(
"aggregation pipeline should be an array")));
}
bson_iter_t updateIterator;
BsonValueInitIterator(updateSpec, &updateIterator);
List *aggregationStages = NIL;
while (bson_iter_next(&updateIterator))
{
@@ -305,8 +305,9 @@ static void HandleSetOnInsertUpdateTree(BsonIntermediatePathNode *tree,
static uint32_t ArrayFiltersKeyHash(const void *key, Size keysize);
static int ArrayFiltersKeyCompare(const void *obj1, const void *obj2, Size objsize);
static void WriteCurrentArrayFilterValue(pgbson_writer *writer, bson_value_t *entryValue);
static HTAB * BuildExpressionForArrayFilters(pgbson *arrayFilters);
static void PostValidateArrayFilters(HTAB *arrayFiltersHash, pgbson *updateSpec);
static HTAB * BuildExpressionForArrayFilters(const bson_value_t *arrayFilters);
static void PostValidateArrayFilters(HTAB *arrayFiltersHash, const
bson_value_t *updateSpec);
/* Value writer functions */
static bool HandleUpdateDocumentId(pgbson_writer *writer,
@@ -615,18 +616,17 @@ RegisterUpdateOperatorExtension(const MongoUpdateOperatorSpec *extensibleDefinit
* and can be reused in processing document updates.
*/
const BsonIntermediatePathNode *
GetOperatorUpdateState(pgbson *updateSpec, pgbson *querySpec,
pgbson *arrayFilters, bool isUpsert)
GetOperatorUpdateState(const bson_value_t *updateSpec, const bson_value_t *querySpec,
const bson_value_t *arrayFilters, bool isUpsert)
{
bson_iter_t updateIterator;
PgbsonInitIteratorAtPath(updateSpec, "", &updateIterator);
if (!BSON_ITER_HOLDS_DOCUMENT(&updateIterator) ||
!bson_iter_recurse(&updateIterator, &updateIterator))
if (updateSpec->value_type != BSON_TYPE_DOCUMENT)
{
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_BADVALUE), errmsg(
"Update should be a document")));
}
bson_iter_t updateIterator;
BsonValueInitIterator(updateSpec, &updateIterator);
HTAB *arrayFilterHash = BuildExpressionForArrayFilters(arrayFilters);
PositionalUpdateSpec positionalSpec =
{
@@ -2318,7 +2318,7 @@ ArrayFiltersKeyCompare(const void *obj1, const void *obj2, Size objsize)
* a QueryFilterPathAndValue.
*/
static HTAB *
BuildExpressionForArrayFilters(pgbson *arrayFilters)
BuildExpressionForArrayFilters(const bson_value_t *arrayFilters)
{
if (arrayFilters == NULL)
{
@@ -2334,11 +2334,8 @@ BuildExpressionForArrayFilters(pgbson *arrayFilters)
hash_create("Bson array filter hash table", 32, &hashBuilderInfo,
DefaultExtensionHashFlags);
pgbsonelement arrayFiltersElement;
bson_iter_t arrayIterator;
PgbsonToSinglePgbsonElement(arrayFilters, &arrayFiltersElement);
BsonValueInitIterator(&arrayFiltersElement.bsonValue, &arrayIterator);
BsonValueInitIterator(arrayFilters, &arrayIterator);
while (bson_iter_next(&arrayIterator))
{
@@ -2502,7 +2499,7 @@ WriteCurrentArrayFilterValue(pgbson_writer *writer, bson_value_t *entryValue)
* by at least 1 update entry.
*/
static void
PostValidateArrayFilters(HTAB *arrayFiltersHash, pgbson *updateSpec)
PostValidateArrayFilters(HTAB *arrayFiltersHash, const bson_value_t *updateSpec)
{
if (arrayFiltersHash == NULL)
{
@@ -2517,10 +2514,7 @@ PostValidateArrayFilters(HTAB *arrayFiltersHash, pgbson *updateSpec)
{
if (!entry->filterUsed)
{
bson_iter_t updateSpecIter;
PgbsonInitIteratorAtPath(updateSpec, "", &updateSpecIter);
const bson_value_t *bsonValue = bson_iter_value(&updateSpecIter);
const char *updateSpecStr = FormatBsonValueForShellLogging(bsonValue);
const char *updateSpecStr = FormatBsonValueForShellLogging(updateSpec);
ereport(ERROR, (errcode(ERRCODE_DOCUMENTDB_FAILEDTOPARSE),
errmsg(
"The array filter for identifier \'%.*s\' was not used in the update %s",