Skip to content

Mongo queries (wire protocol + dialect) - #68493

Open
scanhex12 wants to merge 291 commits into
ClickHouse:masterfrom
scanhex12:mongo_db_parser
Open

scanhex12 wants to merge 291 commits into
ClickHouse:masterfrom
scanhex12:mongo_db_parser

Conversation

@scanhex12

@scanhex12 scanhex12 commented Aug 17, 2024 •

Copy link
Copy Markdown
Member

Adds two ways to run MongoDB queries against ClickHouse:

  • a wire protocol endpoint (mongo_port), so MongoDB drivers and tools such as pymongo and mongosh can connect to ClickHouse as if it were a MongoDB server;
  • a query dialect (SET dialect = 'mongo'), so MongoDB shell syntax can be sent over the usual ClickHouse interfaces.

A Mongo database maps onto a ClickHouse database, a collection onto a table, a document onto a row, and a nested field onto an a.b column. A collection created by the first insert gets one column per field of the first inserted document. The supported commands are insert, find, count, update, delete, create, drop, createIndexes, listDatabases, listCollections, isMaster and saslStart; only the PLAIN authentication mechanism is supported, because it is the only one that provides the cleartext password ClickHouse needs.

Both are experimental and cover a subset of MongoDB. They are meant for pointing an existing MongoDB application at ClickHouse without rewriting its queries, not as a MongoDB replacement. The limitations are listed in docs/en/interfaces/mongo.md.

Task: #58394

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added a MongoDB-compatible wire protocol endpoint (the mongo_port server setting) and a MongoDB query dialect (SET dialect = 'mongo') for basic collection operations.


Workflow [PR]
Sync PR [sync-upstream/pr/68493]

@scanhex12 scanhex12 changed the title MongoDB Queries in CH MongoDB Queries in CH part 1 Aug 17, 2024
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 18, 2024
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-feature Pull request with new product feature label Aug 19, 2024
@scanhex12 scanhex12 changed the title MongoDB Queries in CH part 1 [WIP] Mongo client (wire protocol + dialect) Feb 13, 2025
@scanhex12
scanhex12 marked this pull request as draft February 13, 2025 06:31
@scanhex12 scanhex12 changed the title [WIP] Mongo client (wire protocol + dialect) Mongo client (wire protocol + dialect) Feb 23, 2025
@scanhex12
scanhex12 marked this pull request as ready for review February 23, 2025 11:22
@scanhex12 scanhex12 changed the title Mongo client (wire protocol + dialect) Mongo queries (wire protocol + dialect) Feb 23, 2025
@clickhouse-gh

clickhouse-gh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [beaf54a]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
04813_mongo_dialect_limit_zero FAIL cidb
04813_mongo_dialect_limit_zero FAIL cidb
04813_mongo_dialect_limit_zero FAIL cidb
04813_mongo_dialect_limit_zero FAIL cidb
04813_mongo_dialect_limit_zero FAIL cidb
Too many test failures FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds an experimental MongoDB endpoint and query dialect. Reviewed head beaf54a04dd3b5ed9e1d08c8fcffb716f2456a4c, the current code, and all prior discussion. Five actionable correctness problems remain: composite insert validation, composite union types, map unwinding, negative slicing, and null regex results. Posted two new findings in one review and replied to/reopened three bot-authored threads whose claimed fixes are incomplete. The two deliberately deferred issues remain below without further thread comments.

The new scalar $unwind output was followed through $match, $project/$set, repeated $unwind, sorting/grouping, $unionWith, and BSON encoding. The expression stages consume the substituted field; union type checks and encoding expose the compound-value gaps below.

Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this review job, and local test execution is prohibited. Findings are established by concrete source traces; focused regressions should confirm them. The head's Fast test, Style check, and four arm_tidy shards passed, but the full suite is gated by unresolved review threads. CI report.
Findings

❌ Blockers

  • src/Core/Mongo/Handlers/Insert.cpp:753: Numeric validation stops at Tuple and other composite destinations. A wire insert of {"x":[2147483648]} into x Tuple(Int32) bypasses the range check and reaches the unchecked integer reader, storing -2147483648 while acknowledging success. Decimal tuple members also bypass scale checks. Recursively validate corresponding values and destination types, or reject unsupported composite writes. Replied to and reopened the existing thread.

  • src/Parsers/Mongo/ParserMongoAggregateQuery.cpp:1100: $unionWith classifies composite types as “other” and accepts incompatible nested BSON categories. Tuple(flag Bool) united with Tuple(flag Int32) becomes Tuple(flag Int32), changing true into numeric 1 in the returned document. Map values and arrays of composites share the gap. Compare nested schemas or reject incompatible composite unions. Replied to and reopened the existing thread.

  • src/Parsers/Mongo/ParserMongoAggregateQuery.cpp:853: The non-array $unwind fix explicitly routes Map through ARRAY JOIN. A map {'a':1,'b':2}, returned as a BSON document before this stage, becomes two key/value tuple rows; an empty map drops the row. Treat maps as single document values and preserve a null index. Replied to and reopened the existing thread.

  • src/Parsers/Mongo/ParserMongoAggregateExpression.cpp:1875: Three-argument $slice passes oversized negative positions directly to arraySlice. $slice: [[1,2,3],-15,2] consequently returns []; MongoDB clamps the position to the beginning and returns [1,2]. Clamp before applying the count while keeping AST construction bounded. MongoDB contract.

  • src/Parsers/Mongo/ParserMongoAggregateExpression.cpp:2444: An unsuccessful $regexFind produces three null leaf columns, which appendFieldTree wraps into {"r":{"match":null,"idx":null,"captures":null}}. The required result is {"r":null}. Preserve parent nullness through the result representation and BSON encoder. This is separate from nonparticipating capture groups in a successful match. MongoDB contract.

  • src/Parsers/Mongo/ParserMongoUpdateQuery.cpp:250 [dismissed by author -- https://github.com/Mongo queries (wire protocol + dialect) #68493#discussion_r4304923235]: $inc/$mul validate constants but leave the computed result unchecked. Incrementing 2147483647 in Int32 stores -2147483648. The concern about failed asynchronous mutations blocking later work is valid, but silent persisted overflow remains a correctness violation. Reject unsafe operations or provide an execution strategy that checks results safely; the documented limitation does not prevent data corruption. No additional thread comment posted.

⚠️ Majors

  • src/Parsers/Mongo/ParserMongoAggregateExpression.cpp:2465 [dismissed by author -- https://github.com/Mongo queries (wire protocol + dialect) #68493#discussion_r4362358046]: A capture group that does not participate in a successful $regexFind returns an empty string instead of null. This changes client null checks and subsequent expressions. The documented limitation explains the missing function support but preserves the semantic difference. A participation-preserving capture function would close it. No additional thread comment posted.
Tests
  • ⚠️ Add rejected wire inserts into composite integer/decimal destinations, asserting no stored rows; cover object-shaped composite values as well as tuples represented by arrays.
  • ⚠️ Add a union of nested boolean/numeric fields, checking preserved BSON categories or explicit rejection.
  • ⚠️ Add populated and empty maps to $unwind, including includeArrayIndex; current scalar coverage misses this representation.
  • ⚠️ Add ordinary and oversized negative $slice positions, including a column operand.
  • ⚠️ Add a wire $regexFind assertion for a completely unsuccessful match. Stateless checks of three null leaf columns cannot verify the parent BSON type.
Final Verdict

Status: ❌ Block

Fix the five active correctness findings and add the focused regressions. Resolve the deferred mutation-overflow behavior safely before approval; the capture-group limitation remains a separate documented concern.

Comment thread src/Core/Mongo/Wire/OpMessage.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Insert.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Insert.cpp Resolved
Comment thread src/Core/Mongo/Document.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Insert.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Auth.cpp Resolved
Comment thread src/Core/Mongo/Document.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Create.cpp Resolved
Comment thread src/Parsers/Mongo/Utils.h Resolved
Comment thread src/Core/Mongo/Handlers/Insert.cpp Resolved
@alexey-milovidov alexey-milovidov self-assigned this Jul 27, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

All the findings of the AI review are addressed. Where a finding is fixed, the fix is listed with the test that covers it.

Blockers

Finding Fix Test
OpMessage.cpp:74 reads until the socket buffer is empty instead of consuming message_length MongoHandler validates message_length, reads exactly the rest of the message and parses it from a bounded buffer; sections are read until that buffer is exhausted, and a document sequence section is bounded by its own size test_two_frames_in_one_packet, test_frame_split_across_packets
Document.cpp:62 trusts the unauthenticated doc_size checked against the BSON minimum of 5 and against the bytes left in the frame before the resize; a document libbson refuses to parse is rejected test_invalid_bson_length
Insert.cpp:106 embeds values into INSERT text rows are passed as JSONEachRow data, so no value reaches the query text test_insert_special_values
Auth.cpp:72 authenticates as $db the PLAIN payload is split on its NUL separators and authcid is used; a mechanism other than PLAIN is rejected test_authentication_user_differs_from_database
Insert.cpp:157 drops the $db namespace all handlers resolve the target through getCollectionRef, which takes the database from $db and quotes both names; the dialect now accepts an explicit database as the first name test_same_collection_in_two_databases, 04628_mongo_dialect_qualified_collection
Insert.cpp:187 sizes ordered_values from the current document the schema and every row are derived from the same flattened form of the document; a missing field gets its column default and an unknown field is rejected with input_format_skip_unknown_fields = 0 test_insert_heterogeneous_documents
Document.cpp:100 never calls bson_destroy the destructor destroys it; temporary child documents are destroyed after libbson copies them, and the ones passed to bson_append_array_begin are no longer heap-allocated —
Utils.h:51 uses a process-global rapidjson allocator the allocator belongs to the QueryMetadata of the query being parsed —

Majors

Finding Fix Test
Create.cpp:16 reads json["drop"] reads the create field test_create_collection
ParserMongoFunction.cpp:223 reads both the name and the value of $inc with GetObject the column comes from the member name and the amount from the member value test_increment_update
Insert.cpp:127 serializes arrays as ] arrays are written by rapidjson as part of the JSONEachRow row test_insert_arrays

CI

  • Style check/cpp: the quoted includes are converted to <>, and std::format is replaced with fmt::format.
  • Fast test: the build failed on 'rapidjson/document.h' file not found because it configures with -DENABLE_LIBRARIES=0. src/Parsers/Mongo is now built only when rapidjson is available and the dialect dispatch sites are guarded; setting dialect = 'mongo' in a build without rapidjson fails with SUPPORT_IS_DISABLED rather than silently parsing the query as ClickHouse SQL. rapidjson is header-only, so it is also enabled in the Fast test build, which lets the stateless dialect tests run there.
  • Build (arm_tidy): the leftover full_inp debug variable is removed, together with the header include cycles, the uninitialized members and the other reported violations. OpReply, which was never instantiated and whose serialize did not write the documents, is deleted.

Documentation: added docs/en/interfaces/mongo.md, which describes both the endpoint and the dialect, the mapping of Mongo concepts onto ClickHouse, how a collection schema is inferred, the supported commands and operators, and the limitations.

Changelog: the category is now Experimental Feature and the entry mentions both the wire protocol and the dialect.

Two notes on behaviour that the findings did not cover but the requested tests made visible: drop on a collection that does not exist and listCollections on a database that does not exist now answer as a Mongo server does — ns not found with code 26, and an empty cursor — instead of failing with UNKNOWN_TABLE or UNKNOWN_DATABASE; and a collection created explicitly with createCollection has no document to infer a schema from, so it gets a single JSON column, which is documented as a limitation.

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature and removed pr-feature Pull request with new product feature labels Jul 27, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Running the new wire protocol tests against a server found one more real bug, now fixed in 1252a74: the handlers put the database into the text of the query they build for the Mongo dialect, where the literal db means the current database — and a Mongo database may itself be named db, which is the name most pymongo and mongosh examples use. In that case the database was dropped and every command hit the current database of the session, so insert, find, count, createIndexes and update on client["db"] failed with UNKNOWN_TABLE. parseMongoQuery now takes the database as an argument and the handlers pass the $db value, so the text no longer carries it.

All 14 tests of test_mongo_protocol pass against a locally built server, and 03214_mongo_queries and the new 04628_mongo_dialect_qualified_collection pass too.

alexey-milovidov added a commit to scanhex12/ClickHouse that referenced this pull request Jul 28, 2026
…ly built

`Fast test` configures with `-DENABLE_RAPIDJSON=1`, but it also initializes only the
submodules listed in `ci/jobs/fast_test.py`, and `contrib/rapidjson` was not one of
them. `add_contrib` returns early for an empty submodule directory, so
`ch_contrib::rapidjson` never existed, `USE_RAPIDJSON` stayed `0`, and
`src/Parsers/Mongo` was dropped from the build. `03214_mongo_queries` and
`04628_mongo_dialect_qualified_collection` then failed with
`SYNTAX_ERROR: failed at position 1 (db)`, because the client fell back to the
ClickHouse parser instead of the Mongo one.

Add the submodule, and make that fallback impossible to hit silently: `ClientBase` and
`LocalConnection` now throw `SUPPORT_IS_DISABLED` for `dialect = 'mongo'` in a build
without rapidjson, the same as `executeQuery` already did. Parsing a Mongo query as
ClickHouse SQL only produced a confusing syntax error that pointed at the query rather
than at the build.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=1252a7414ba8acf66e47253ee3f1193660169d98&name_0=PR&name_1=Fast%20test
ClickHouse#68493

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov added a commit to scanhex12/ClickHouse that referenced this pull request Jul 28, 2026
`cpp`:
- `getRapidJsonRepresentation` and `getJson` are renamed to
  `getRapidJSONRepresentation` and `getJSON`, since an abbreviation has to be in all
  caps.
- `splitByNewline` used `std::stringstream`; it reads through `ReadBufferFromString`
  now. The result is the same for every input, including an empty string, a missing
  trailing newline and an empty line in the middle.
- Remove the extra empty lines in `ParserMongoOrderBy.cpp`.

`catch_all`: the two `catch (...)` blocks of `handle` turned any failure of a Mongo
command into the `{"errmsg": ..., "ok": 0}` reply and left no trace on the server, so
the reason a command failed was only visible to the client. They call
`tryLogCurrentException` now.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68493&sha=1252a7414ba8acf66e47253ee3f1193660169d98&name_0=PR&name_1=Style%20check
ClickHouse#68493

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits November 10, 2026 08:31
… operand, fold a `Dynamic` sum in order, promote `$multiply` like Mongo

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…reter does, a temporary table included

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed c0b57832f72b. This addresses the seven clickhouse-gh threads from 2026-11-09. Each has a reply and is resolved:

  • The wire insert now checks values against the range of Int128, UInt128, Int256 and UInt256 columns, including inside arrays.
  • OP_MSG sections are accepted in any order.
  • The argument of .sort(...) ends at the matching parenthesis outside string literals, so a field named x)y works through both the dialect and the wire find.
  • $divide and $log return null for a null operand before checking the domain of the other operand.
  • A Dynamic sum is folded in operand order per row, and $multiply promotes its product the way Mongo does.
  • A dialect $rename on a session temporary table is checked against that table's columns.
  • The pipeline that $unionWith copies into its type probe is limited in size, so nested unions cannot grow exponentially.

New tests: 05617_mongo_dialect_sort_parenthesis_null_domains_dynamic_fold_temporary_rename_nested_unions and three integration tests. All 119 tests in test_mongo_protocol pass locally, and so do the Mongo dialect stateless tests.

Two threads are still open and need a human decision, as explained in them:

  • non-participating capture groups of $regexFind (this needs a new function);
  • the overflow of an arithmetic result in $inc and $mul at the column boundary.

alexey-milovidov and others added 2 commits November 11, 2026 09:38
… output

The `$rename` case filtered the client output with `^[0-9].*` to keep the
selected row, which also kept the frames of the stack trace that the Fast test
prints with the error, so the test failed with "having exception in stdout".
Keep only the name of the error and a row of two numbers.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=68493&sha=c0b57832f72b6b4930dba3c65d28eca588470ed3&name_0=PR&name_1=Fast%20test
ClickHouse#68493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Core/Mongo/MongoProtocol.cpp Resolved
Comment thread src/Interpreters/MongoUpdateAccess.cpp Resolved
alexey-milovidov and others added 3 commits November 12, 2026 18:26
With parallel replicas, a read of a temporary table logs a warning that the other
replicas do not have it, and the test failed on the output in stderr. Only errors are
sent to the client by the queries on the temporary table now.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=68493&sha=9463c56fac224155de640b881e16130d63a60d51&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
ClickHouse#68493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mporary table updates

- `$add` and `$subtract` reject a date held by a `Dynamic` operand in each row, as they
  reject a date operand.
- `$divide` rejects a decimal held by a `Dynamic` operand, whose quotient would keep the
  scale of the dividend.
- `$pow` rejects a decimal held by a `Dynamic` operand, and a power of integers held by
  it that a `Float64` may not hold exactly; zero raised to a negative exponent is an
  error, as in Mongo, instead of an infinity.
- `makeIsDecimal` accepts `LowCardinality`, as `makeIsAccumulatedNumber` does.
- `$not` rejects a constant, also one written in Extended JSON, and an empty document,
  instead of taking it as a negated equality.
- The statements of the wire protocol run with every `*_overflow_mode` set to `throw`,
  so a limit of the profile fails the command instead of returning a cut result with
  an exhausted cursor.
- The access check of a Mongo update resolves the table as the reading of its columns
  does, so an update of a temporary table is checked against it, not against a
  namesake in the current database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed fdd983e4f6e8 and 14cdc63206ff:

  • The CI failure of 05617_mongo_dialect_..._nested_unions in the ParallelReplicas job is fixed. With parallel replicas, reading the temporary table logged a warning that the other replicas do not have it, and that warning ended up in stderr. The temporary-table queries now send only errors to the client.
  • The nine clickhouse-gh threads from 2026-11-11 each have a reply and are resolved:
    • Dynamic operands in $add, $subtract, $divide and $pow
    • LowCardinality decimals, which ClickHouse cannot actually create
    • scalar $not
    • the profile's *_overflow_mode on the wire
    • access to temporary tables in updates
    • $pow of zero to a negative exponent
  • New tests: 05627_mongo_dialect_dynamic_operands_scalar_not_temporary_update, and test_profile_limits_fail_instead_of_cutting_the_result in test_mongo_protocol. All 63 Mongo dialect stateless tests pass locally on the merged build.

Two threads stay open for a human decision, as explained there:

  • null captures in $regexFind, which needs a new function
  • a checked conversion of an arithmetic result such as $inc at the type boundary

Comment thread src/Core/Mongo/Handlers/Insert.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Update.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Delete.cpp Resolved
}

/// Mongo drops a document whose array is empty or missing, which is what an inner `ARRAY JOIN` does.
chain.array_join = makeArrayJoin(std::move(expressions));

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.

❌ Blocker: MongoDB allows $unwind on a non-array value too: when the field is present, non-null, and not an empty array, the stage must emit that document once with the value unchanged (and includeArrayIndex is null for the non-array case). Here both branches still route the path through ARRAY JOIN, so a valid pipeline such as [{"$unwind":"$name"}] on name String reaches ARRAY JOIN of not array nor map instead.

The preserving branch has the same static-array assumption in translateUnwindPreservingEmpty, so this is not limited to the non-preserving form. Please special-case non-array inputs instead of lowering every path through ARRAY JOIN.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Not fixed: this needs a human decision. The translation does not know the column type, and SQL cannot pick a for an array column and [a] for any other column. if/multiIf need a common supertype of Array(T) and T, even with a constant condition. arrayFlatten([a]) wraps a scalar correctly but flattens an array of arrays through every level, which would unwind [[1, 2], [3]] into 1, 2, 3 instead of [1, 2], [3]. A faithful fix needs either the schema at translation time (the wire handler could read system.columns before translating) or a new function such as arrayWrapIfNotArray. Either is a separate design change. [{"$unwind": "$name"}] on a String column is still rejected (ARRAY JOIN of not array nor map), not answered wrongly. In 35e6be994e7e, docs/concepts/features/interfaces/mongo.mdx documents that $unwind requires a field of an array type. I am leaving this thread open for a decision on which approach to take.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in beaf54a04dd3, without a new function and without reading the schema at translation time. A field that is not an array is now unwound into itself: the document is kept once with the field and its type unchanged and a null includeArrayIndex, and it is dropped when the field is null unless preserveNullAndEmptyArrays is set.

The array to join is chosen by a constant condition on toTypeName of the field. A plain if needs a common type of Array(T) and T, so the choice is written as nested if functions whose unselected branches name a column that does not exist (the __mongo_ prefix is reserved). The analyzer replaces an if of a constant condition with the selected branch when the other branch cannot be analyzed, the same way if(hasColumnInTable(...), column, default) works, so only the selected branch decides the type. Both forms of $unwind share one translation now, so the preserving one is covered too.

A Dynamic or a Variant column can hold an array in one row and another value in the next, so the type cannot decide it; such a column is still rejected rather than kept in one piece. The docs say so.

Tests: the new 05872_mongo_dialect_unwind_of_a_field_that_is_not_an_array (string, number, LowCardinality, Nullable, index, preserving form, array of arrays, Dynamic), and test_aggregate in test_mongo_protocol now checks the wire result instead of an error.

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.

[Blocker] The non-array fix still sends Map values through the array path at src/Parsers/Mongo/ParserMongoAggregateQuery.cpp:852-853. For an existing t(m Map(String, Int32)) containing map('a', 1, 'b', 2), db.t.aggregate([{"$unwind":"$m"}]) produces two rows of key/value tuples instead of keeping the original document once. An empty map drops the row entirely. appendTypedValue encodes a Map as a BSON document (src/Core/Mongo/Handler.cpp:559-570), but getArrayJoinDataType converts it into Array(Tuple(...)) (src/Interpreters/ArrayJoinAction.cpp:35-39), so this is still a non-array value being unwound. Route Map through the single-value branch and cover a populated and an empty map, including includeArrayIndex.

alexey-milovidov and others added 2 commits November 14, 2026 09:16
The condition of `$expr` in a `find` is evaluated for every row of a block
read, not only for the rows the condition on `id` selects. So the query that
expected `{"id":2}` also evaluated `$divide` on the date and the decimal rows
of the same table and failed with `ILLEGAL_TYPE_OF_ARGUMENT` or the decimal
`throwIf`, which ended up in stderr. The queries with `$expr` now read tables
that hold a single kind of value.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=68493&sha=14cdc63206ffd0984e65d1d9f2cf88cf88899247&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20targeted%29
ClickHouse#68493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The wire `update` and `delete` reject a per-spec `hint`, as they reject
  `collation`, instead of running without it.
- A field name of a document inserted over the wire protocol must not be empty,
  start with `$` or contain a dot, as in the dialect insert. The dialect insert
  rejects a dot too: `{"a.b": 1}` and `{"a": {"b": 1}}` would both map onto the
  column `a.b`.
- `$size`, in a filter and in an aggregation expression, takes the type of the
  value in each row for a `Dynamic` field (`makeIsRuntimeArray`), and its size
  from the JSON text of the value (`makeRuntimeArraySize`), which never throws,
  also with `short_circuit_function_evaluation = 'disable'`.
- The documentation states that `$unwind` requires a field of an array type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed d5cb6b647032 and 35e6be994e7e:

  • Fixed the CI failure of 05627_mongo_dialect_dynamic_operands_scalar_not_temporary_update, which failed in every stateless job. The condition of $expr is evaluated for every row of a block, not only for the rows that the condition on id selects. So the find that expected {"id":2} also ran $divide on the date and decimal rows, and the errors went to stderr. The queries with $expr now read tables that hold one kind of value.
  • Addressed four of the five clickhouse-gh threads from 2026-11-12, each with a reply and resolved:
    • The wire update and delete reject a per-spec hint.
    • Wire inserts reject empty, $-prefixed and dotted field names. Dialect inserts now reject dotted names too.
    • $size of a Dynamic field checks the type of the value in each row, in filters and in aggregation.
  • Left open: the $unwind-on-a-non-array thread. Doing what MongoDB does needs the column type at translation time or a new function, which is a design decision. The docs now state the limitation. The two older open threads (overflow of an $inc result, and null for $regexFind capture groups that did not participate) still wait on the human decisions described there.

Tested locally: all Mongo stateless tests, the new 05628, and test_mongo_protocol::test_unsupported_command_options_are_rejected.

Comment thread src/Parsers/Mongo/ParserMongoFilter.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Insert.cpp Resolved
alexey-milovidov and others added 2 commits November 18, 2026 09:56
…, `BFloat16`, `$toLong` of null

- The column check of a `$unionWith` of two collections reads the columns of an
  unqualified collection from the temporary table of the session when there is
  one of that name, as the query itself does: `system.columns` lists temporary
  tables under the empty database, so the check compared two empty lists and
  let a union of `a(x, y)` and `b(y, x)` relabel the fields.
- `parseData` rejects a field name that contains a zero byte. The translation
  passes names on as C strings, so `{"x\u0000ignored": 1}` filtered, sorted,
  updated or deleted by `x`.
- A wire insert of an integer into a `BFloat16` column, or an element of an
  `Array(BFloat16)`, that the type does not hold exactly is rejected, as it is
  for `Float32` and `Float64`, instead of being stored as a neighbouring value.
- `$toLong` of a `null` literal is `null`, and its range check skips a `NULL`
  value, so it does not throw with short-circuit evaluation disabled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/Mongo/MongoConstants.cpp Resolved
Comment thread src/Core/Mongo/Handlers/Drop.cpp Resolved
alexey-milovidov and others added 3 commits November 21, 2026 09:53
Conflicts:
- `src/Interpreters/DDLTask.cpp`: took the restructured code of `DDLLogEntry::setSettingsIfRequired` from master and kept `dialect` in the list of initiator-only settings.
- `docs/concepts/navigation.json`, `docs/concepts/features/interfaces/mongo.mdx`: the `interfaces` directory was reorganized into `connect-to-clickhouse`; moved the page to `protocols/compatibility/mongo.mdx` next to the MySQL and PostgreSQL pages.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…` of a BSON regex, `maxTimeMS` of DDL

- The identifiers the translation generates (`__mongo_variable_x` for `$$x`,
  `__mongo_value_1`, `__mongo_element` and so on) could still be captured by a
  document field of the same name. The prefix `__mongo_` is reserved now: a
  query that names such a field, and an insert of a document that has one, is
  rejected, so the generated names are disjoint from every field a query
  refers to.
- `$size` takes only a number or the Extended JSON wrapper of one. A boolean
  or a string operand was compared with the length, so
  `deleteMany({"a": {"$size": true}})` deleted the arrays of one element.
- The `$options` next to a `$regex` that holds a BSON regular expression were
  dropped, so a negated case-insensitive match deleted the documents it should
  have kept. They are applied now, for both Extended JSON forms of the regular
  expression; options in both places are an error, as in MongoDB.
- `drop`, `dropDatabase` and `createIndexes` reject a non-zero `maxTimeMS`,
  as `create` does, because their DDL is not bounded by `max_execution_time`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed e141dd9e639e, 1bc64d2bf56b and 96e40f631b9c:

  • Conflicts with master are resolved. The interfaces docs directory was reorganized into connect-to-clickhouse, so the page is now docs/concepts/features/connect-to-clickhouse/protocols/compatibility/mongo.mdx, next to the MySQL and PostgreSQL pages. In DDLTask.cpp, dialect stays in the list of initiator-only settings.
  • The arm_tidy builds failed with modernize-use-nodiscard, which is enabled on master now. The getters under src/Core/Mongo and src/Parsers/Mongo are marked [[nodiscard]]; a local clang-tidy run of that check over all 38 Mongo sources is clean.
  • The four clickhouse-gh threads from 2026-11-18 each have a reply and are resolved:
    • the prefix __mongo_ is reserved for generated identifiers, so a document field can no longer be captured by a lambda parameter;
    • $size takes only a number;
    • the $options next to a $regex that holds a BSON regular expression are applied;
    • drop, dropDatabase and createIndexes reject a non-zero maxTimeMS.

Three older threads stay open because they need a human decision, as explained in each: the overflow of an arithmetic result in $inc, null for a capture group that did not participate in $regexFind, and $unwind of a non-array field.

alexey-milovidov and others added 3 commits November 24, 2026 09:30
The `settings_changes_history` style check requires a new setting to be recorded under the current version.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
MongoDB unwinds a field that is not an array into itself: the document is kept once with the field unchanged and a null `includeArrayIndex`, and it is dropped when the field is null unless `preserveNullAndEmptyArrays` is set. The Mongo dialect lowered every path through `ARRAY JOIN`, so `[{"$unwind": "$name"}]` on a `String` column failed with `ARRAY JOIN of not array nor map`.

The translation does not know the type of the column, so the array to join is chosen by a constant condition on `toTypeName` of the field. A plain `if` would need a common type of an array and its element, so the choice is written as nested `if` functions whose unselected branches name a column that does not exist: the analyzer replaces an `if` of a constant condition with the selected branch when the other one cannot be analyzed, so the type of the field is kept as it is.

Both forms of `$unwind` now compute the array and its indexes below the `ARRAY JOIN` under names of their own. A `Dynamic` or a `Variant` column, which can hold an array in one row and another value in the next, is still rejected.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed f5071ef665a2 and beaf54a04dd3:

  • settings_changes_history in the Style check is fixed: enable_mongo_dialect is recorded under version 26.12, the current one, instead of 26.11.
  • The $unwind thread is fixed and resolved. A field that is not an array is unwound into itself, as in MongoDB, with a null index. The reply in the thread explains how the translation does this without knowing the column type. A Dynamic or a Variant column is still rejected.
  • Tested locally on the merged build: all 67 Mongo dialect stateless tests, including the new 05872_mongo_dialect_unwind_of_a_field_that_is_not_an_array, and test_aggregate and test_unwind_and_the_other_stages of test_mongo_protocol.

Two threads stay open because they need a human decision, as explained in each:

  • the overflow of an arithmetic result such as $inc at the type boundary: a check can only fail while the mutation runs, and a failed mutation blocks the table;
  • null for a capture group that did not participate in $regexFind: ClickHouse's regular expression functions return an empty string for it, so this needs a new function.

While these two threads are unresolved, the review-threads gate in Finish Workflow stays red and the full CI suite is skipped, so the builds and tests of this PR do not run. Someone has to decide on the two threads, or resolve them as documented limitations, before the CI can say anything about this branch.

Comment on lines +1873 to +1875
auto offset = makeASTFunction(
"if", positive, makeASTFunction("plus", position->clone(), makeLiteral(Field(UInt64(1)))), position->clone());
return makeASTFunction("arraySlice", arguments[0], offset, arguments[2]);

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.

[Blocker] Clamp an oversized negative $slice position before applying the count. On a nonempty collection, db.t.aggregate([{"$project":{"s":{"$slice":[[1,2,3],-15,2]}}}]) becomes arraySlice([1,2,3], -15, 2) and returns []. MongoDB requires [1,2] for this exact input: a negative position beyond the array starts at its beginning. ClickHouse instead subtracts the out-of-range distance from the requested length (src/Functions/GatherUtils/Sources.h:134-139). Clamp against the array length, binding the input once to keep AST growth bounded, and add oversized and ordinary negative-position regressions for the shared dialect/wire lowering.

auto matched = makeASTFunction("match", input, pattern);
auto whole_match = makeASTFunction("regexpExtract", input, pattern, makeLiteral(Field(UInt64(0))));

result.push_back({name + ".match", makeASTFunction("if", matched, whole_match, makeNull())});

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.

[Blocker] Preserve the nullness of the whole $regexFind result. On a nonempty collection, projecting {"r":{"$regexFind":{"input":"b","regex":"a"}}} emits three null leaf columns here. The wire encoder's appendFieldTree unconditionally wraps those leaves into {"r":{"match":null,"idx":null,"captures":null}} (src/Core/Mongo/Handler.cpp:648-652), whereas MongoDB requires {"r":null} when no match exists. Clients therefore receive a non-null object for an unsuccessful search. Carry parent nullness through the result representation and add a wire regression for a missing match. This concerns an unsuccessful match, separately from the existing thread about capture groups within a successful match.

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants