Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🐘 test: refresh FerretDB harness, registry-derived models, bulkWrite coverage (#14679)
Danny Avilac57051776828
diff --git a/packages/data-schemas/misc/ferretdb/bson-inventory.txt b/packages/data-schemas/misc/ferretdb/bson-inventory.txtnew file mode 100644index 0000000000..88c5371589--- /dev/null+++ b/packages/data-schemas/misc/ferretdb/bson-inventory.txt@@ -0,0 +1,467 @@+ nspname | proname | args | result | vol+-------------------------+----------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------+-----+ documentdb_api | binary_extended_version | | text | i+ documentdb_api | binary_version | | text | i+ documentdb_api | list_databases | p_list_databases_spec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_aggregation_count | databasename text, countspec documentdb_core.bson, OUT document documentdb_core.bson | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_aggregation_distinct | databasename text, distinctspec documentdb_core.bson, OUT document documentdb_core.bson | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_aggregation_find | databasename text, findspec documentdb_core.bson, OUT document documentdb_core.bson | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_aggregation_pipeline | databasename text, aggregationpipeline documentdb_core.bson, OUT document documentdb_core.bson | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_array_agg | documentdb_core.bson, text | documentdb_core.bson | i+ documentdb_api_catalog | bson_array_agg | documentdb_core.bson, text, boolean | documentdb_core.bson | i+ documentdb_api_catalog | bson_build_distinct_response | documentdb_core.bson[] | documentdb_core.bson | i+ documentdb_api_catalog | bson_distinct_agg | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_distinct_unwind | documentdb_core.bson, text | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_add_fields | document documentdb_core.bson, pathspec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_all | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_bits_all_clear | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_bits_all_set | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_bits_any_clear | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_bits_any_set | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_elemmatch | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_eq | documentdb_core.bson, documentdb_core.bsonquery | boolean | i+ documentdb_api_catalog | bson_dollar_eq | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_exists | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_expr | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_facet_project | documentdb_core.bson, boolean | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_geointersects | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_geowithin | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_gt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_gt | documentdb_core.bson, documentdb_core.bsonquery | boolean | i+ documentdb_api_catalog | bson_dollar_gte | documentdb_core.bson, documentdb_core.bsonquery | boolean | i+ documentdb_api_catalog | bson_dollar_gte | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_in | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_json_schema | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_lt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_lt | documentdb_core.bson, documentdb_core.bsonquery | boolean | i+ documentdb_api_catalog | bson_dollar_lte | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_lte | documentdb_core.bson, documentdb_core.bsonquery | boolean | i+ documentdb_api_catalog | bson_dollar_mod | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_ne | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_nin | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_project | document documentdb_core.bson, pathspec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_project_find | document documentdb_core.bson, pathspec documentdb_core.bson, queryspec documentdb_core.bson DEFAULT NULL::documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_project_geonear | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_regex | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_replace_root | document documentdb_core.bson, pathspec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_set | document documentdb_core.bson, pathspec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_size | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_type | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_dollar_unset | document documentdb_core.bson, pathspec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_unwind | documentdb_core.bson, text | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_dollar_unwind | documentdb_core.bson, documentdb_core.bson | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_expression_get | document documentdb_core.bson, expressionspec documentdb_core.bson, isnullonempty boolean DEFAULT false | documentdb_core.bson | i+ documentdb_api_catalog | bson_expression_map | document documentdb_core.bson, sourcearrayname text, expressionspec documentdb_core.bson, isnullonempty boolean DEFAULT false | documentdb_core.bson | i+ documentdb_api_catalog | bson_geonear_distance | documentdb_core.bson, documentdb_core.bson | double precision | i+ documentdb_api_catalog | bson_gist_geography_options | internal | void | i+ documentdb_api_catalog | bson_gist_geometry_2d_options | internal | void | i+ documentdb_api_catalog | bson_lookup_unwind | documentdb_core.bson, text | SETOF documentdb_core.bson | i+ documentdb_api_catalog | bson_object_agg | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_orderby | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bson_query_match | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_true_match | documentdb_core.bson | boolean | i+ documentdb_api_catalog | bson_validate_geography | p_document documentdb_core.bson, p_keypath text | documentdb_core.bson | i+ documentdb_api_catalog | bson_validate_geometry | p_document documentdb_core.bson, p_keypath text | documentdb_core.bson | i+ documentdb_api_catalog | bsonaverage | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bsonfirst | documentdb_core.bson, documentdb_core.bson[] | documentdb_core.bson | i+ documentdb_api_catalog | bsonfirstn | documentdb_core.bson, bigint, documentdb_core.bson[] | documentdb_core.bson | i+ documentdb_api_catalog | bsonfirstnonsorted | documentdb_core.bson, bigint | documentdb_core.bson | i+ documentdb_api_catalog | bsonfirstonsorted | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bsonlast | documentdb_core.bson, documentdb_core.bson[] | documentdb_core.bson | i+ documentdb_api_catalog | bsonlastn | documentdb_core.bson, bigint, documentdb_core.bson[] | documentdb_core.bson | i+ documentdb_api_catalog | bsonlastnonsorted | documentdb_core.bson, bigint | documentdb_core.bson | i+ documentdb_api_catalog | bsonlastonsorted | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bsonmax | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bsonmin | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | bsonsum | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_catalog | dollar_support | internal | internal | i+ documentdb_api_catalog | gin_bson_can_pre_consistent | smallint, documentdb_core.bson, integer, internal, internal, internal | boolean | i+ documentdb_api_catalog | gin_bson_compare | bytea, bytea | boolean | i+ documentdb_api_catalog | gin_bson_compare_partial | bytea, bytea, smallint, internal | integer | i+ documentdb_api_catalog | gin_bson_consistent | internal, smallint, anyelement, integer, internal, internal | boolean | i+ documentdb_api_catalog | gin_bson_exclusion_pre_consistent | internal, smallint, documentdb_api_catalog.shard_key_and_document, integer, internal, internal, internal, internal | void | i+ documentdb_api_catalog | gin_bson_pre_consistent | internal, smallint, documentdb_core.bson, integer, internal, internal, internal, internal | void | i+ documentdb_api_catalog | gin_bson_single_path_extract_value | documentdb_core.bson, internal | internal | i+ documentdb_api_catalog | gin_bson_single_path_options | internal | void | i+ documentdb_api_catalog | gin_bson_wildcard_project_extract_value | documentdb_core.bson, internal | internal | i+ documentdb_api_catalog | gin_bson_wildcard_project_options | internal | void | i+ documentdb_api_catalog | query_match_support | internal | internal | i+ documentdb_api_internal | aggregation_support | internal | internal | i+ documentdb_api_internal | bson_add_to_set | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_document_add_score_field | documentdb_core.bson, double precision | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_add_fields | document documentdb_core.bson, pathspec documentdb_core.bson, letvariablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_add_fields | document documentdb_core.bson, pathspec documentdb_core.bson, letvariablespec documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_eq | documentdb_core.bson, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bson_dollar_expr | documentdb_core.bson, documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_extract_merge_filter | documentdb_core.bson, text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_fullscan | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_gt | documentdb_core.bson, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bson_dollar_gte | documentdb_core.bson, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bson_dollar_index_hint | document documentdb_core.bson, index_name text, key_document documentdb_core.bson, is_sparse boolean | boolean | i+ documentdb_api_internal | bson_dollar_inverse_match | document documentdb_core.bson, spec documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_lookup_expression_eval_merge | document documentdb_core.bson, pathspec documentdb_core.bson, variablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_lookup_extract_filter_array | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson[] | i+ documentdb_api_internal | bson_dollar_lookup_extract_filter_expression | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_lookup_filter_support | internal | internal | i+ documentdb_api_internal | bson_dollar_lookup_join_filter | documentdb_core.bson, documentdb_core.bson, text | boolean | i+ documentdb_api_internal | bson_dollar_lookup_project | documentdb_core.bson, documentdb_core.bson[], text | SETOF documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_lt | documentdb_core.bson, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bson_dollar_lte | documentdb_core.bson, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bson_dollar_merge_add_object_id | documentdb_core.bson, documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_add_object_id | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_documents | document documentdb_core.bson, pathspec documentdb_core.bson, overridearray boolean | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_documents_at_path | leftdocument documentdb_core.bson, rightdocument documentdb_core.bson, fieldpath text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_fail_when_not_matched | documentdb_core.bson, text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_filter_support | internal | internal | i+ documentdb_api_internal | bson_dollar_merge_generate_object_id | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_handle_when_matched | documentdb_core.bson, documentdb_core.bson, integer | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_handle_when_matched | documentdb_core.bson, documentdb_core.bson, integer, documentdb_core.bson, integer | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_merge_join | documentdb_core.bson, documentdb_core.bson, text | boolean | i+ documentdb_api_internal | bson_dollar_not_gt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_not_gte | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_not_lt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_not_lte | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_project | document documentdb_core.bson, pathspec documentdb_core.bson, variablespec documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_project | document documentdb_core.bson, pathspec documentdb_core.bson, variablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_project_find | document documentdb_core.bson, pathspec documentdb_core.bson, queryspec documentdb_core.bson, letvariablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_project_find | document documentdb_core.bson, pathspec documentdb_core.bson, queryspec documentdb_core.bson, letvariablespec documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_range | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_dollar_redact | documentdb_core.bson, documentdb_core.bson, text, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_redact | document documentdb_core.bson, redactspec documentdb_core.bson, redactspectext text, variablespec documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_replace_root | document documentdb_core.bson, pathspec documentdb_core.bson, variablespec documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_replace_root | document documentdb_core.bson, pathspec documentdb_core.bson, variablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_dollar_text | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_expression_get | document documentdb_core.bson, expressionspec documentdb_core.bson, isnullonempty boolean, variablespec documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_expression_get | document documentdb_core.bson, expressionspec documentdb_core.bson, isnullonempty boolean, variablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_expression_map | document documentdb_core.bson, sourcearrayname text, expressionspec documentdb_core.bson, isnullonempty boolean, variablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_expression_partition_by_fields_get | document documentdb_core.bson, expressionspec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_expression_partition_get | document documentdb_core.bson, expressionspec documentdb_core.bson, isnullonempty boolean, variablespec documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_expression_partition_get | document documentdb_core.bson, expressionspec documentdb_core.bson, isnullonempty boolean DEFAULT false | documentdb_core.bson | i+ documentdb_api_internal | bson_expression_partition_get | document documentdb_core.bson, expressionspec documentdb_core.bson, isnullonempty boolean, variablespec documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_extract_vector | document documentdb_core.bson, path text | vector | i+ documentdb_api_internal | bson_geonear_within_range | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_index_transform | bytea, bytea, smallint, internal | bytea | i+ documentdb_api_internal | bson_merge_objects | documentdb_core.bson, bigint, documentdb_core.bson[], documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_merge_objects_on_sorted | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_orderby | document documentdb_core.bson, filter documentdb_core.bson, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_orderby_compare | documentdb_core.bson, documentdb_core.bson | integer | i+ documentdb_api_internal | bson_orderby_compare_sort_support | internal | void | i+ documentdb_api_internal | bson_orderby_eq | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_orderby_gt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_orderby_lt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_orderby_partition | documentdb_core.bson, documentdb_core.bson, boolean | documentdb_core.bson | i+ documentdb_api_internal | bson_orderby_partition | document documentdb_core.bson, filter documentdb_core.bson, istimerangewindow boolean, collationstring text | documentdb_core.bson | i+ documentdb_api_internal | bson_orderby_reverse | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bson_query_match | document documentdb_core.bson, query documentdb_core.bson, variablespec documentdb_core.bson, collationstring text | boolean | i+ documentdb_api_internal | bson_query_to_tsquery | query documentdb_core.bson, textsearch text DEFAULT NULL::text | tsquery | i+ documentdb_api_internal | bson_rum_composite_ordering | bytea, documentdb_core.bson, smallint, internal | documentdb_core.bson | i+ documentdb_api_internal | bson_search_param | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_text_meta_qual | documentdb_core.bson, tsquery, bytea, boolean | boolean | i+ documentdb_api_internal | bson_text_tsquery | documentdb_core.bson, tsquery | boolean | i+ documentdb_api_internal | bson_unique_exclusion_index_equal | documentdb_api_catalog.shard_key_and_document, documentdb_api_catalog.shard_key_and_document | boolean | i+ documentdb_api_internal | bson_unique_index_equal | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_unique_shard_path_equal | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | bson_update_document | document documentdb_core.bson, updatespec documentdb_core.bson, queryspec documentdb_core.bson, arrayfilters documentdb_core.bson DEFAULT NULL::documentdb_core.bson, buildupdatedesc boolean DEFAULT false, variablespec documentdb_core.bson DEFAULT NULL::documentdb_core.bson, OUT newdocument documentdb_core.bson, OUT updatedesc documentdb_core.bson | record | i+ documentdb_api_internal | bson_update_returned_value | shard_key_id bigint | integer | i+ documentdb_api_internal | bson_value_dollar_all | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_bits_all_clear | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_bits_all_set | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_bits_any_clear | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_bits_any_set | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_elemmatch | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_eq | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_exists | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_gt | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_gte | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_in | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_lt | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_lte | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_mod | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_ne | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_nin | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_regex | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_size | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bson_value_dollar_type | internal, documentdb_core.bson | internal | i+ documentdb_api_internal | bsoncovariancepop | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsoncovariancesamp | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonderivative | documentdb_core.bson, documentdb_core.bson, bigint | documentdb_core.bson | i+ documentdb_api_internal | bsonfirst | documentdb_core.bson, documentdb_core.bson[], documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonfirstn | documentdb_core.bson, bigint, documentdb_core.bson[], documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonfirstnonsorted | documentdb_core.bson, bigint, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonfirstonsorted | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonindexbounds_in | cstring | documentdb_api_internal.bsonindexbounds | i+ documentdb_api_internal | bsonindexbounds_out | documentdb_api_internal.bsonindexbounds | cstring | i+ documentdb_api_internal | bsonindexbounds_recv | internal | documentdb_api_internal.bsonindexbounds | i+ documentdb_api_internal | bsonindexbounds_send | documentdb_api_internal.bsonindexbounds | bytea | i+ documentdb_api_internal | bsonintegral | documentdb_core.bson, documentdb_core.bson, bigint | documentdb_core.bson | i+ documentdb_api_internal | bsonlast | documentdb_core.bson, documentdb_core.bson[], documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonlastn | documentdb_core.bson, bigint, documentdb_core.bson[], documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonlastnonsorted | documentdb_core.bson, bigint, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonlastonsorted | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonmaxn | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonmedian | documentdb_core.bson, integer, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonminn | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonpercentile | documentdb_core.bson, integer, documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonquery_eq | documentdb_core.bsonquery, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bsonquery_gt | documentdb_core.bsonquery, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bsonquery_gte | documentdb_core.bsonquery, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bsonquery_lt | documentdb_core.bsonquery, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bsonquery_lte | documentdb_core.bsonquery, documentdb_api_internal.bsonindexbounds | boolean | i+ documentdb_api_internal | bsonstddevpop | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | bsonstddevsamp | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | cursor_state | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_api_internal | documentdb_core_bson_to_bson | documentdb_core.bson | documentdb_core.bson | i+ documentdb_api_internal | generate_unique_shard_document | p_document documentdb_core.bson, p_shard_key_value bigint, p_unique_spec documentdb_core.bson, p_sparse boolean | documentdb_core.bson | i+ documentdb_api_internal | get_shard_key_value | p_shard_key documentdb_core.bson, p_collection_id bigint, p_document documentdb_core.bson | bigint | i+ documentdb_api_internal | gin_bson_composite_path_compare_partial | bytea, bytea, smallint, internal | integer | i+ documentdb_api_internal | gin_bson_composite_path_consistent | internal, smallint, anyelement, integer, internal, internal | boolean | i+ documentdb_api_internal | gin_bson_composite_path_extract_value | documentdb_core.bson, internal | internal | i+ documentdb_api_internal | gin_bson_composite_path_options | internal | void | i+ documentdb_api_internal | gin_bson_exclusion_consistent | internal, smallint, anyelement, integer, internal, internal | boolean | i+ documentdb_api_internal | gin_bson_exclusion_extract_query | documentdb_api_catalog.shard_key_and_document, internal, smallint, internal, internal, internal, internal | void | i+ documentdb_api_internal | gin_bson_exclusion_extract_value | documentdb_api_catalog.shard_key_and_document, internal | internal | i+ documentdb_api_internal | gin_bson_exclusion_options | internal | void | i+ documentdb_api_internal | gin_bson_hashed_consistent | internal, smallint, anyelement, integer, internal, internal | boolean | i+ documentdb_api_internal | gin_bson_hashed_extract_query | documentdb_core.bson, internal, smallint, internal, internal, internal, internal | void | i+ documentdb_api_internal | gin_bson_hashed_extract_value | documentdb_core.bson, internal | internal | i+ documentdb_api_internal | gin_bson_hashed_options | internal | void | i+ documentdb_api_internal | gin_bson_unique_shard_consistent | internal, smallint, anyelement, integer, internal, internal | boolean | i+ documentdb_api_internal | gin_bson_unique_shard_extract_query | documentdb_core.bson, internal, smallint, internal, internal, internal, internal | void | i+ documentdb_api_internal | gin_bson_unique_shard_extract_value | documentdb_core.bson, internal | internal | i+ documentdb_api_internal | gin_bson_unique_shard_pre_consistent | internal, smallint, documentdb_core.bson, integer, internal, internal, internal, internal | void | i+ documentdb_api_internal | index_spec_as_bson | index_spec documentdb_api_catalog.index_spec_type, for_get_indexes boolean DEFAULT false, namespacename text DEFAULT NULL::text | documentdb_core.bson | i+ documentdb_api_internal | index_spec_options_are_equivalent | left_index_spec documentdb_api_catalog.index_spec_type, right_index_spec documentdb_api_catalog.index_spec_type | boolean | i+ documentdb_api_internal | rum_bson_single_path_extract_tsvector | documentdb_core.bson, internal, internal, internal, internal | internal | i+ documentdb_api_internal | rum_bson_text_path_options | internal | void | i+ documentdb_api_internal | tdigest_add_double | internal, documentdb_core.bson, integer, documentdb_core.bson | internal | i+ documentdb_api_internal | tdigest_add_double_array | internal, documentdb_core.bson, integer, documentdb_core.bson | internal | i+ documentdb_api_internal | tdigest_array_percentiles | internal | documentdb_core.bson | i+ documentdb_api_internal | tdigest_combine | internal, internal | internal | i+ documentdb_api_internal | tdigest_deserial | bytea, internal | internal | i+ documentdb_api_internal | tdigest_percentile | internal | documentdb_core.bson | i+ documentdb_api_internal | tdigest_serial | internal | bytea | i+ documentdb_api_internal | update_bson_document | document documentdb_core.bson, updatespec documentdb_core.bson, queryspec documentdb_core.bson, arrayfilters documentdb_core.bson DEFAULT NULL::documentdb_core.bson, variablespec documentdb_core.bson DEFAULT NULL::documentdb_core.bson, OUT newdocument documentdb_core.bson | documentdb_core.bson | i+ documentdb_core | bson_compare | documentdb_core.bson, documentdb_core.bson | integer | i+ documentdb_core | bson_equal | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_core | bson_from_bytea | bytea | documentdb_core.bson | i+ documentdb_core | bson_get_value | documentdb_core.bson, text | documentdb_core.bson | i+ documentdb_core | bson_get_value_text | documentdb_core.bson, text | text | i+ documentdb_core | bson_gt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_core | bson_gte | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_core | bson_hash_int4 | documentdb_core.bson | integer | i+ documentdb_core | bson_hash_int8 | documentdb_core.bson, bigint | bigint | i+ documentdb_core | bson_hex_to_bson | cstring | documentdb_core.bson | i+ documentdb_core | bson_in | cstring | documentdb_core.bson | i+ documentdb_core | bson_in_range_interval | documentdb_core.bson, documentdb_core.bson, interval, boolean, boolean | boolean | i+ documentdb_core | bson_in_range_numeric | documentdb_core.bson, documentdb_core.bson, documentdb_core.bson, boolean, boolean | boolean | i+ documentdb_core | bson_json_to_bson | text | documentdb_core.bson | i+ documentdb_core | bson_lt | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_core | bson_lte | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_core | bson_not_equal | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_core | bson_object_keys | documentdb_core.bson | SETOF text | i+ documentdb_core | bson_out | documentdb_core.bson | cstring | i+ documentdb_core | bson_recv | internal | documentdb_core.bson | i+ documentdb_core | bson_repath_and_build | VARIADIC "any" | documentdb_core.bson | i+ documentdb_core | bson_send | documentdb_core.bson | bytea | i+ documentdb_core | bson_to_bson_hex | documentdb_core.bson | cstring | i+ documentdb_core | bson_to_bsonsequence | documentdb_core.bson | documentdb_core.bsonsequence | i+ documentdb_core | bson_to_bytea | documentdb_core.bson | bytea | i+ documentdb_core | bson_to_json_string | documentdb_core.bson | cstring | i+ documentdb_core | bson_unique_index_equal | documentdb_core.bson, documentdb_core.bson | boolean | i+ documentdb_core | bsonquery_compare | documentdb_core.bsonquery, documentdb_core.bsonquery | integer | i+ documentdb_core | bsonquery_compare | documentdb_core.bson, documentdb_core.bsonquery | integer | i+ documentdb_core | bsonquery_equal | documentdb_core.bsonquery, documentdb_core.bsonquery | boolean | i+ documentdb_core | bsonquery_gt | documentdb_core.bsonquery, documentdb_core.bsonquery | boolean | i+ documentdb_core | bsonquery_gte | documentdb_core.bsonquery, documentdb_core.bsonquery | boolean | i+ documentdb_core | bsonquery_in | cstring | documentdb_core.bsonquery | i+ documentdb_core | bsonquery_lt | documentdb_core.bsonquery, documentdb_core.bsonquery | boolean | i+ documentdb_core | bsonquery_lte | documentdb_core.bsonquery, documentdb_core.bsonquery | boolean | i+ documentdb_core | bsonquery_not_equal | documentdb_core.bsonquery, documentdb_core.bsonquery | boolean | i+ documentdb_core | bsonquery_out | documentdb_core.bsonquery | cstring | i+ documentdb_core | bsonquery_recv | internal | documentdb_core.bsonquery | i+ documentdb_core | bsonquery_send | documentdb_core.bsonquery | bytea | i+ documentdb_core | bsonsequence_from_bytea | bytea | documentdb_core.bsonsequence | i+ documentdb_core | bsonsequence_get_bson | documentdb_core.bsonsequence | SETOF documentdb_core.bson | i+ documentdb_core | bsonsequence_in | cstring | documentdb_core.bsonsequence | i+ documentdb_core | bsonsequence_out | documentdb_core.bsonsequence | cstring | i+ documentdb_core | bsonsequence_recv | internal | documentdb_core.bsonsequence | i+ documentdb_core | bsonsequence_send | documentdb_core.bsonsequence | bytea | i+ documentdb_core | bsonsequence_to_bytea | documentdb_core.bsonsequence | bytea | i+ documentdb_core | row_get_bson | record | documentdb_core.bson | i+ documentdb_api_catalog | bson_array_agg_final | bytea | documentdb_core.bson | s+ documentdb_api_catalog | bson_array_agg_transition | bytea, documentdb_core.bson, text | bytea | s+ documentdb_api_catalog | bson_array_agg_transition | bytea, documentdb_core.bson, text, boolean | bytea | s+ documentdb_api_catalog | bson_avg_final | bytea | documentdb_core.bson | s+ documentdb_api_catalog | bson_first_combine | bytea, bytea | bytea | s+ documentdb_api_catalog | bson_first_last_final | bytea | documentdb_core.bson | s+ documentdb_api_catalog | bson_first_last_final_on_sorted | bytea | documentdb_core.bson | s+ documentdb_api_catalog | bson_first_transition | bytea, documentdb_core.bson, documentdb_core.bson[] | bytea | s+ documentdb_api_catalog | bson_first_transition_on_sorted | bytea, documentdb_core.bson | bytea | s+ documentdb_api_catalog | bson_firstn_combine | bytea, bytea | bytea | s+ documentdb_api_catalog | bson_firstn_lastn_final | bytea | documentdb_core.bson | s+ documentdb_api_catalog | bson_firstn_lastn_final_on_sorted | bytea | documentdb_core.bson | s+ documentdb_api_catalog | bson_firstn_transition | bytea, documentdb_core.bson, bigint, documentdb_core.bson[] | bytea | s+ documentdb_api_catalog | bson_firstn_transition_on_sorted | bytea, documentdb_core.bson, bigint | bytea | s+ documentdb_api_catalog | bson_last_combine | bytea, bytea | bytea | s+ documentdb_api_catalog | bson_last_transition | bytea, documentdb_core.bson, documentdb_core.bson[] | bytea | s+ documentdb_api_catalog | bson_last_transition_on_sorted | bytea, documentdb_core.bson | bytea | s+ documentdb_api_catalog | bson_lastn_combine | bytea, bytea | bytea | s+ documentdb_api_catalog | bson_lastn_transition | bytea, documentdb_core.bson, bigint, documentdb_core.bson[] | bytea | s+ documentdb_api_catalog | bson_lastn_transition_on_sorted | bytea, documentdb_core.bson, bigint | bytea | s+ documentdb_api_catalog | bson_max_combine | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_catalog | bson_max_transition | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_catalog | bson_min_combine | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_catalog | bson_min_max_final | documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_catalog | bson_min_transition | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_catalog | bson_object_agg_final | bytea | documentdb_core.bson | s+ documentdb_api_catalog | bson_object_agg_transition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_catalog | bson_sum_avg_combine | bytea, bytea | bytea | s+ documentdb_api_catalog | bson_sum_avg_transition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_catalog | bson_sum_final | bytea | documentdb_core.bson | s+ documentdb_api_catalog | gin_bson_extract_query | documentdb_core.bson, internal, smallint, internal, internal, internal, internal | internal | s+ documentdb_api_internal | authenticate_with_scram_sha256 | p_user_name text, p_auth_msg text, p_client_proof text | documentdb_core.bson | s+ documentdb_api_internal | bson_add_to_set_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_add_to_set_transition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_array_agg_minvtransition | bytea, documentdb_core.bson, text, boolean | bytea | s+ documentdb_api_internal | bson_const_fill | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_covariance_pop_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_covariance_pop_samp_combine | bytea, bytea | bytea | s+ documentdb_api_internal | bson_covariance_pop_samp_invtransition | bytea, documentdb_core.bson, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_covariance_pop_samp_transition | bytea, documentdb_core.bson, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_covariance_samp_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_dense_rank | | documentdb_core.bson | s+ documentdb_api_internal | bson_densify_full | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_densify_partition | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_densify_range | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_derivative_transition | bytea, documentdb_core.bson, documentdb_core.bson, bigint | bytea | s+ documentdb_api_internal | bson_distinct_array_agg_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_distinct_array_agg_transition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_document_number | | documentdb_core.bson | s+ documentdb_api_internal | bson_dollar_bucket_auto | document documentdb_core.bson, spec documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_dollar_selectivity | internal, oid, internal, integer | double precision | s+ documentdb_api_internal | bson_exp_moving_avg | documentdb_core.bson, documentdb_core.bson, boolean | documentdb_core.bson | s+ documentdb_api_internal | bson_first_transition | bytea, documentdb_core.bson, documentdb_core.bson[], documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_first_transition_on_sorted | bytea, documentdb_core.bson, documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_firstn_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_firstn_transition | bytea, documentdb_core.bson, bigint, documentdb_core.bson[], documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_firstn_transition_on_sorted | bytea, documentdb_core.bson, bigint, documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_integral_derivative_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_integral_transition | bytea, documentdb_core.bson, documentdb_core.bson, bigint | bytea | s+ documentdb_api_internal | bson_last_transition | bytea, documentdb_core.bson, documentdb_core.bson[], documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_last_transition_on_sorted | bytea, documentdb_core.bson, documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_lastn_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_lastn_transition | bytea, documentdb_core.bson, bigint, documentdb_core.bson[], documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_lastn_transition_on_sorted | bytea, documentdb_core.bson, bigint, documentdb_core.bson DEFAULT NULL::documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_linear_fill | documentdb_core.bson, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_locf_fill | documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_maxminn_combine | bytea, bytea | bytea | s+ documentdb_api_internal | bson_maxminn_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_maxn_transition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_merge_objects_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_merge_objects_transition | bytea, documentdb_core.bson, bigint, documentdb_core.bson[], documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_merge_objects_transition_on_sorted | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_minn_transition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_rank | | documentdb_core.bson | s+ documentdb_api_internal | bson_shift | documentdb_core.bson, integer, documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | bson_std_dev_pop_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_std_dev_pop_samp_combine | bytea, bytea | bytea | s+ documentdb_api_internal | bson_std_dev_pop_samp_transition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_std_dev_pop_samp_winfunc_invtransition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | bson_std_dev_pop_winfunc_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_std_dev_samp_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_std_dev_samp_winfunc_final | bytea | documentdb_core.bson | s+ documentdb_api_internal | bson_sum_avg_minvtransition | bytea, documentdb_core.bson | bytea | s+ documentdb_api_internal | coll_stats_aggregation | p_database_name text, p_collection_name text, p_collstatsspec documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | current_cursor_state | documentdb_core.bson | documentdb_core.bson | s+ documentdb_api_internal | gin_bson_composite_path_extract_query | documentdb_core.bson, internal, smallint, internal, internal, internal, internal | internal | s+ documentdb_api_internal | index_stats_aggregation | p_database_name text, p_collection_name text | SETOF documentdb_core.bson | s+ documentdb_api_internal | index_stats_worker | p_database_name text, p_collection_name text | documentdb_core.bson | s+ documentdb_api_internal | scram_sha256_get_salt_and_iterations | p_user_name text | documentdb_core.bson | s+ documentdb_core | bson_operator_selectivity | internal, oid, internal, integer | double precision | s+ documentdb_core | bson_typanalyze | internal | boolean | s+ documentdb_api | aggregate_cursor_first_page | database text, commandspec documentdb_core.bson, cursorid bigint DEFAULT 0, OUT cursorpage documentdb_core.bson, OUT continuation documentdb_core.bson, OUT persistconnection boolean, OUT cursorid bigint | record | v+ documentdb_api | coll_mod | p_database_name text, p_collection_name text, p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | coll_stats | p_database_name text, p_collection_name text, p_scale double precision DEFAULT 1 | documentdb_core.bson | v+ documentdb_api | collection | p_database_name text, p_collection_name text, OUT shard_key_value bigint, OUT object_id documentdb_core.bson, OUT document documentdb_core.bson | SETOF record | v+ documentdb_api | compact | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | connection_status | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | count_query | database text, countspec documentdb_core.bson, OUT document documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | create_collection | p_database_name text, p_collection_name text | boolean | v+ documentdb_api | create_collection_view | dbname text, createspec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | create_indexes_background | p_database_name text, p_index_spec documentdb_core.bson, OUT retval documentdb_core.bson, OUT ok boolean, OUT requests documentdb_core.bson | record | v+ documentdb_api | create_role | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | create_user | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | current_op_command | p_spec documentdb_core.bson, OUT document documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | cursor_get_more | database text, getmorespec documentdb_core.bson, continuationspec documentdb_core.bson, OUT cursorpage documentdb_core.bson, OUT continuation documentdb_core.bson | record | v+ documentdb_api | db_stats | p_database_name text, p_scale double precision DEFAULT 1, p_freestorage boolean DEFAULT false | documentdb_core.bson | v+ documentdb_api | delete | p_database_name text, p_delete documentdb_core.bson, p_insert_documents documentdb_core.bsonsequence DEFAULT NULL::documentdb_core.bsonsequence, p_transaction_id text DEFAULT NULL::text, OUT p_result documentdb_core.bson, OUT p_success boolean | record | v+ documentdb_api | distinct_query | database text, distinctspec documentdb_core.bson, OUT document documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | drop_collection | p_database_name text, p_collection_name text, p_write_concern documentdb_core.bson DEFAULT NULL::documentdb_core.bson, p_collection_uuid uuid DEFAULT NULL::uuid, p_track_changes boolean DEFAULT true | boolean | v+ documentdb_api | drop_database | p_database_name text, p_write_concern documentdb_core.bson DEFAULT NULL::documentdb_core.bson | void | v+ documentdb_api | drop_indexes | IN p_database_name text, IN p_arg documentdb_core.bson, INOUT retval documentdb_core.bson DEFAULT NULL::documentdb_core.bson | | v+ documentdb_api | drop_role | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | drop_user | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | find_and_modify | p_database_name text, p_message documentdb_core.bson, p_transaction_id text DEFAULT NULL::text, OUT p_result documentdb_core.bson, OUT p_success boolean | record | v+ documentdb_api | find_cursor_first_page | database text, commandspec documentdb_core.bson, cursorid bigint DEFAULT 0, OUT cursorpage documentdb_core.bson, OUT continuation documentdb_core.bson, OUT persistconnection boolean, OUT cursorid bigint | record | v+ documentdb_api | insert | p_database_name text, p_insert documentdb_core.bson, p_insert_documents documentdb_core.bsonsequence DEFAULT NULL::documentdb_core.bsonsequence, p_transaction_id text DEFAULT NULL::text, OUT p_result documentdb_core.bson, OUT p_success boolean | record | v+ documentdb_api | insert_bulk | IN p_database_name text, IN p_insert documentdb_core.bson, IN p_insert_documents documentdb_core.bsonsequence DEFAULT NULL::documentdb_core.bsonsequence, IN p_transaction_id text DEFAULT NULL::text, INOUT p_result documentdb_core.bson DEFAULT NULL::documentdb_core.bson, INOUT p_success boolean DEFAULT NULL::boolean | | v+ documentdb_api | insert_one | p_database_name text, p_collection_name text, p_document documentdb_core.bson, p_transaction_id text DEFAULT NULL::text | documentdb_core.bson | v+ documentdb_api | list_collections_cursor_first_page | database text, commandspec documentdb_core.bson, cursorid bigint DEFAULT 0, OUT cursorpage documentdb_core.bson, OUT continuation documentdb_core.bson, OUT persistconnection boolean, OUT cursorid bigint | record | v+ documentdb_api | list_indexes_cursor_first_page | database text, commandspec documentdb_core.bson, cursorid bigint DEFAULT 0, OUT cursorpage documentdb_core.bson, OUT continuation documentdb_core.bson, OUT persistconnection boolean, OUT cursorid bigint | record | v+ documentdb_api | rename_collection | p_database_name text, p_collection_name text, p_target_name text, p_drop_target boolean DEFAULT false | void | v+ documentdb_api | reshard_collection | p_shard_key_spec documentdb_core.bson | void | v+ documentdb_api | roles_info | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | shard_collection | p_shard_key_spec documentdb_core.bson | void | v+ documentdb_api | shard_collection | p_database_name text, p_collection_name text, p_shard_key documentdb_core.bson, p_is_reshard boolean DEFAULT true | void | v+ documentdb_api | unshard_collection | p_shard_key_spec documentdb_core.bson | void | v+ documentdb_api | update | p_database_name text, p_update documentdb_core.bson, p_insert_documents documentdb_core.bsonsequence DEFAULT NULL::documentdb_core.bsonsequence, p_transaction_id text DEFAULT NULL::text, OUT p_result documentdb_core.bson, OUT p_success boolean | record | v+ documentdb_api | update_bulk | IN p_database_name text, IN p_update documentdb_core.bson, IN p_insert_documents documentdb_core.bsonsequence DEFAULT NULL::documentdb_core.bsonsequence, IN p_transaction_id text DEFAULT NULL::text, INOUT p_result documentdb_core.bson DEFAULT NULL::documentdb_core.bson, INOUT p_success boolean DEFAULT NULL::boolean | | v+ documentdb_api | update_role | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | update_user | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | users_info | p_spec documentdb_core.bson | documentdb_core.bson | v+ documentdb_api | validate | database text, validatespec documentdb_core.bson, OUT document documentdb_core.bson | documentdb_core.bson | v+ documentdb_api_catalog | bson_gist_geography_compress | internal | internal | v+ documentdb_api_catalog | bson_gist_geography_consistent | internal, documentdb_core.bson, integer | boolean | v+ documentdb_api_catalog | bson_gist_geography_distance | internal, documentdb_core.bson, integer | double precision | v+ documentdb_api_catalog | bson_gist_geometry_2d_compress | internal | internal | v+ documentdb_api_catalog | bson_gist_geometry_consistent_2d | internal, documentdb_core.bson, integer | boolean | v+ documentdb_api_catalog | bson_gist_geometry_distance_2d | internal, documentdb_core.bson, integer | double precision | v+ documentdb_api_catalog | documentdbrumhandler | internal | index_am_handler | v+ documentdb_api_internal | apply_extension_data_table_upgrade | integer, integer, integer | void | v+ documentdb_api_internal | build_index_background | IN p_job_index integer | | v+ documentdb_api_internal | build_index_concurrently | IN p_job_index integer | | v+ documentdb_api_internal | check_build_index_status | p_arg documentdb_core.bson, OUT retval documentdb_core.bson, OUT ok boolean, OUT complete boolean | record | v+ documentdb_api_internal | check_build_index_status_internal | p_arg documentdb_core.bson | documentdb_core.bson | v+ documentdb_api_internal | coll_stats_worker | p_database_name text, p_collection_name text, p_scale double precision DEFAULT 1 | documentdb_core.bson | v+ documentdb_api_internal | collection_update_trigger | | trigger | v+ documentdb_api_internal | command_feature_counter_stats | reset_stats_after_read boolean, OUT feature_name text, OUT usage_count integer | SETOF record | v+ documentdb_api_internal | create_builtin_id_index | collection_id bigint, register_id_index boolean DEFAULT true | void | v+ documentdb_api_internal | create_indexes_background_internal | p_database_name text, p_arg documentdb_core.bson | documentdb_core.bson | v+ documentdb_api_internal | create_indexes_non_concurrently | p_database_name text, p_arg documentdb_core.bson, p_skip_check_collection_create boolean DEFAULT false | documentdb_core.bson | v+ documentdb_api_internal | current_op_aggregation | p_spec documentdb_core.bson, OUT document documentdb_core.bson | SETOF documentdb_core.bson | v+ documentdb_api_internal | current_op_worker | p_spec documentdb_core.bson, OUT document documentdb_core.bson | documentdb_core.bson | v+ documentdb_api_internal | cursor_directory_cleanup | expiry_time_seconds bigint DEFAULT NULL::bigint | void | v+ documentdb_api_internal | db_stats_worker | p_collection_ids bigint[] | documentdb_core.bson | v+ documentdb_api_internal | delete_cursors | cursorids bigint[] | documentdb_core.bson | v+ documentdb_api_internal | delete_expired_rows | IN p_batch_size integer DEFAULT '-1'::integer | | v+ documentdb_api_internal | delete_expired_rows_background | IN p_batch_size integer DEFAULT '-1'::integer | | v+ documentdb_api_internal | delete_one | p_collection_id bigint, p_shard_key_value bigint, p_query documentdb_core.bson, p_sort documentdb_core.bson, p_return_document boolean, p_return_fields documentdb_core.bson, p_transaction_id text, OUT o_is_row_deleted boolean, OUT o_result_deleted_document documentdb_core.bson | record | v+ documentdb_api_internal | delete_worker | p_collection_id bigint, p_shard_key_value bigint, p_shard_oid regclass, p_update_internal_spec documentdb_core.bson, p_update_internal_docs documentdb_core.bsonsequence, p_transaction_id text | documentdb_core.bson | v+ documentdb_api_internal | documentdb_get_next_collection_id | | bigint | v+ documentdb_api_internal | documentdb_get_next_collection_index_id | | integer | v+ documentdb_api_internal | empty_data_table | OUT shard_key_value bigint, OUT object_id documentdb_core.bson, OUT document documentdb_core.bson | SETOF record | v+ documentdb_api_internal | ensure_valid_db_coll | text, text | boolean | v+ documentdb_api_internal | get_bloat_stats_worker | p_collection_id bigint | documentdb_core.bson | v+ documentdb_api_internal | index_build_is_in_progress | p_index_id integer | boolean | v+ documentdb_api_internal | insert_one | p_collection_id bigint, p_shard_key_value bigint, p_document documentdb_core.bson, p_transaction_id text | boolean | v+ documentdb_api_internal | insert_worker | p_collection_id bigint, p_shard_key_value bigint, p_shard_oid regclass, p_insert_internal_spec documentdb_core.bson, p_insert_internal_docs documentdb_core.bsonsequence, p_transaction_id text | documentdb_core.bson | v+ documentdb_api_internal | invalidate_collection_cache | | void | v+ documentdb_api_internal | record_id_index | p_collection_id bigint | void | v+ documentdb_api_internal | schedule_background_index_build_jobs | p_force_override boolean DEFAULT false | void | v+ documentdb_api_internal | schema_validation_against_update | p_eval_state bytea, p_target_document documentdb_core.bson, p_source_document documentdb_core.bson, p_is_moderate boolean | boolean | v+ documentdb_api_internal | trigger_validate_dbname | | trigger | v+ documentdb_api_internal | update_one | p_collection_id bigint, p_shard_key_value bigint, p_query documentdb_core.bson, p_update documentdb_core.bson, p_shard_key documentdb_core.bson, p_is_upsert boolean, p_sort documentdb_core.bson, p_return_old_or_new boolean, p_return_fields documentdb_core.bson, p_array_filters documentdb_core.bson, p_transaction_id text, OUT o_is_row_updated boolean, OUT o_update_skipped boolean, OUT o_is_retry boolean, OUT o_reinsert_document documentdb_core.bson, OUT o_upserted_object_id bytea, OUT o_result_document documentdb_core.bson | record | v+ documentdb_api_internal | update_worker | p_collection_id bigint, p_shard_key_value bigint, p_shard_oid regclass, p_update_internal_spec documentdb_core.bson, p_update_internal_docs documentdb_core.bsonsequence, p_transaction_id text | documentdb_core.bson | v+ documentdb_api_internal | validate_dbname | dbname text | void | v+(463 rows)+diff --git a/packages/data-schemas/misc/ferretdb/bson-legibility.md b/packages/data-schemas/misc/ferretdb/bson-legibility.mdnew file mode 100644index 0000000000..dbf18780d5--- /dev/null+++ b/packages/data-schemas/misc/ferretdb/bson-legibility.md@@ -0,0 +1,160 @@+# Projecting FerretDB/DocumentDB BSON into readable PostgreSQL columns++Can the `documentdb_core.bson` blob that FerretDB writes be exposed as typed,+queryable PostgreSQL columns — and can those columns be replicated downstream by+change-data-capture? Part one is answered here and passes; part two needs managed+infrastructure and remains open.++Three mechanisms are compared throughout:++| Mechanism | What it is |+|---|---|+| **A. Generated columns + `publish_generated_columns`** | `GENERATED ALWAYS AS ... STORED` columns replicated directly. Needs PostgreSQL 18. |+| **B. Trigger-maintained plain columns** | Ordinary columns filled by a `BEFORE INSERT OR UPDATE` row trigger. Works on PostgreSQL 17. |+| **C. Separate projection tables** | Typed rows written alongside the collection tables, leaving DocumentDB's own tables untouched. |+++Executed 2026-08-02 against `ghcr.io/ferretdb/postgres-documentdb:17-0.107.0-ferretdb-2.7.0`+(PostgreSQL 17.6, `documentdb` / `documentdb_core` 0.107-0) + `ghcr.io/ferretdb/ferretdb:2.7.0`,+driven through the real `mongodb` Node driver. Full accessor inventory (exit criterion 1) is in+[bson-inventory.txt](./bson-inventory.txt) — 467 lines, pasted verbatim from `pg_proc`.++## Verdict++**The local half passes on every gate.** Typed generated columns and a+whole-document `jsonb` projection both work, and DocumentDB/FerretDB is completely indifferent+to the extra columns.++**The replication half remains open** (it needs a managed PostgreSQL 18 instance and a+ClickPipes pipe, neither provisionable locally), but two local findings reframe it:++1. **No PG18 build of the DocumentDB extension exists.** ghcr tags for+ `ferretdb/postgres-documentdb` cover PG 15/16/17 only (checked live 2026-08-02; upstream+ `microsoft/documentdb` unverified — GitHub API rate-limited). `publish_generated_columns`+ is PG18-only, so **mechanism A cannot be deployed on a DocumentDB PostgreSQL today even if+ ClickPipes supports the parameter.** The probe is still worth running to know whether A+ becomes available once a PG18 extension build lands, but it no longer gates the choice.+2. **STORED generated-column values are already materialized in WAL tuples on PG17** —+ `test_decoding` prints them. The pre-18 limitation lives purely in the `pgoutput`+ publication layer that ClickPipes/PeerDB consumes. The data is there; the protocol drops it.++**Conclusion: mechanism B — trigger-maintained plain columns.** Proven end-to-end locally:+a plain column maintained by a `BEFORE INSERT OR UPDATE` row trigger fires correctly on+FerretDB's write path and its values flow through logical decoding on stock PG17. Mechanism A+becomes an upgrade path if DocumentDB ships a PG18 build *and* the replication probe passes.++## A1 — accessor surface (pass)++Immutable paths out of `documentdb_core.bson` exist for every target we need:++| Function | Signature | Volatility | Notes |+|---|---|---|---|+| `documentdb_core.bson_get_value_text` | `(bson, text) → text` | **IMMUTABLE** | The `->>` operator. Dotted paths work (`'meta.model'`). |+| `documentdb_core.bson_get_value` | `(bson, text) → bson` | **IMMUTABLE** | The `->` operator. |+| `documentdb_core.bson_to_json_string` | `(bson) → cstring` | **IMMUTABLE** | Whole document as canonical Extended JSON; `::text::jsonb` composes and stays immutable-safe. |+| `documentdb_core.bson_json_to_bson` | `(text) → bson` | IMMUTABLE | Reverse direction, useful for tests. |++Casts registered on the type: only `bytea ↔ bson` (+ `bson → bsonsequence`) — no SQL-type+casts, so the functions above are the whole story. All 72 operators on the type are+IMMUTABLE; the only non-immutable bson functions in the extension are aggregate transition+helpers (STABLE) and two GiST distance functions (VOLATILE), none of which matter here.+Note the operators live in `documentdb_core`/`documentdb_api_catalog`, not on the default+`search_path` — use schema-qualified function calls in DDL.++### Accessor semantics — the quirks that decide the recipes++- `bson_get_value_text` returns **JSON-flavored text, not raw values**: strings arrive+ wrapped in quotes and inner quotes are *not* escaped (`"Ünïcödé & "quotes" test"`), so its+ string output is neither the raw string nor valid JSON. Numbers arrive clean (`12`).+ Dates/ObjectIds arrive as EJSON fragments (`{ "$date" : "2026-08-01T10:00:00Z" }`).+- `bson_to_json_string` escapes correctly (the same title round-trips through `::jsonb`+ perfectly), and emits **canonical** EJSON: `{"$numberInt": "12"}`,+ `{"$date": {"$numberLong": "1785578400000"}}`, `{"$oid": "..."}`.+- Missing field → SQL `NULL`; BSON `null` → the string `null`. Distinguishable, but remember it.+- `text::timestamptz` is STABLE (GUC-dependent), so a direct `timestamptz` generated column+ is rejected by Postgres — the trap worth knowing about, since it fails loudly here but+ would silently corrupt a hand-rolled equivalent. Project+ epoch millis as `bigint` (canonical `$date.$numberLong` via jsonb path ops, all immutable)+ and type it on the ClickHouse side.++**Recipes:** numbers → `bson_get_value_text(document, 'field')::bigint`. Strings and+everything else → project `doc_json jsonb` once via `bson_to_json_string(document)::text::jsonb`+and extract with plain jsonb operators (in Postgres or in ClickHouse).++## A2/A3/A5 — projection (pass)++Backing tables are `documentdb_data.documents_<collection_id>`+(`shard_key_value bigint, object_id bson, document bson`, PK on the pair; ids mapped in+`documentdb_api_catalog.collections`; id 1 is a `system.dbSentinel` with a+`disallow_writes_check`). All three column shapes added and backfilled existing rows without error:++```sql+ALTER TABLE documentdb_data.documents_2+ ADD COLUMN conversation_id text GENERATED ALWAYS AS (documentdb_core.bson_get_value_text(document, 'conversationId')) STORED,+ ADD COLUMN message_count bigint GENERATED ALWAYS AS ((documentdb_core.bson_get_value_text(document, 'messageCount'))::bigint) STORED,+ ADD COLUMN doc_json jsonb GENERATED ALWAYS AS (documentdb_core.bson_to_json_string(document)::text::jsonb) STORED;+```++## A4 — DocumentDB still works (pass, 14/14)++Through FerretDB against the modified table: `insertOne`, `insertMany`, `updateOne $set`,+`updateOne $inc`, `replaceOne`, filtered `find`, `$group` aggregate, `createIndex`,+indexed `findOne`, `dropIndex`, **unique** `createIndex`, unique-violation rejection+(proper `E11000`, code 11000), `deleteOne`, collection `drop` (table removed cleanly,+projections and all). Generated columns recomputed correctly after every write shape+($inc 12→17, $set →99, replace →7). No errors, no warnings in server logs.++## New collections — event trigger works (exit criterion 4)++A `ddl_command_end` event trigger filtering `CREATE TABLE` on+`documentdb_data.documents_%` successfully `ALTER TABLE`-ed a projection onto a collection+created *implicitly by a FerretDB insert*, inside DocumentDB's own create path, and the+insert succeeded. **Event trigger suffices; no `pg_cron` sweep needed** (a periodic+reconciliation sweep is still cheap insurance). Caveat for managed Postgres: creating event+triggers needs superuser-ish privilege — verify on any managed instance before relying on it.++## Write amplification (exit criterion 4)++Interleaved `insertMany` rounds of 1000 × ~1KB docs, 5 rounds each, medians:++| Configuration | ms / 1000 docs | Overhead |+|---|---|---|+| No projections | 18 | — |+| 3 scalar generated columns | 18 | **unmeasurable** |+| + whole-doc `jsonb` projection | 48 | ~2.8× batch path (~30µs/doc) |++Storage at 6000 docs: 9.9MB → 12MB with the jsonb projection (+21%; TOAST compresses the+EJSON well). Scalar projections are free; the jsonb copy costs real but modest write CPU+and ~a fifth more disk. Per-request in production, ~30µs/doc is noise next to network RTT.++## CDC evidence gathered locally++- `test_decoding` on PG17: the plain trigger-maintained column carries its value on both+ INSERT and UPDATE from FerretDB; the generated `jsonb` column's value is present in the+ WAL tuple; the raw `document` column decodes as `BSONHEX<hex>` — confirming the premise+ that the blob is opaque to any downstream consumer.+- `CREATE PUBLICATION` works on collection tables, both `FOR TABLE` and+ `FOR TABLES IN SCHEMA documentdb_data`.+- The PK includes `object_id documentdb_core.bson` — a custom-type key column. Whether+ ClickPipes handles custom types (as their text representation or at all) is a real+ question for the replication probe; mechanism C's projection tables sidestep it entirely+ with a clean typed PK.++## What remains for the replication probe++The probe stands as originally scoped (managed PG18, `cdc_gencol_probe`,+`publish_generated_columns = stored`, direct connection not PgBouncer, watch for+ClickPipes building its own publication). Add one check: point a pipe at a table with a+`documentdb_core.bson`-typed column — or any custom type — and observe how ClickPipes maps+it, since that decides whether mechanism B can replicate the raw tables directly or whether+mechanism C's projection tables are required.++## Recommendation++Proceed on **mechanism B**: plain columns plus `BEFORE INSERT OR UPDATE` row triggers (the+trigger body is three lines; scalar maintenance cost is unmeasurable). Choose between B and+C once the ClickPipes custom-type question is answered — if ClickPipes chokes on+`bson`-typed columns, projection tables (C) become the replication surface and DocumentDB's+tables stay untouched, which is the more robust design regardless. Any upstream request to+the DocumentDB extension can now carry a concrete finding: the mechanism is proven, PG17 is+sufficient, and no PG18 feature is required.diff --git a/packages/data-schemas/misc/ferretdb/bulkWrite.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/bulkWrite.ferretdb.spec.tsnew file mode 100644index 0000000000..afe61f598f--- /dev/null+++ b/packages/data-schemas/misc/ferretdb/bulkWrite.ferretdb.spec.ts@@ -0,0 +1,592 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { PrincipalType, PrincipalModel, ResourceType } from 'librechat-data-provider';+import type { AnyBulkWriteOperation, Model } from 'mongoose';+import type { IConversationTag } from '~/schema/conversationTag';+import type { ITransaction } from '~/schema/transaction';+import type * as t from '~/types';+import { createConversationTagMethods } from '~/methods/conversationTag';+import { createTransactionMethods } from '~/methods/transaction';+import { createConversationMethods } from '~/methods/conversation';+import { createAclEntryMethods } from '~/methods/aclEntry';+import { createMessageMethods } from '~/methods/message';+import { runAsSystem } from '~/config/tenantContext';+import { createFileMethods } from '~/methods/file';+import { createModels } from '~/models';++/**+ * Differential bulkWrite specs. FerretDB's compatibility documentation lists+ * `bulkWrite` as unsupported, so these measure what actually happens across+ * the five bulkWrite call paths in this repo:+ *+ * 1. import — `bulkSaveConvos` + `bulkSaveMessages` (both hard-code/accept+ * `timestamps:false`, matching `importBatchBuilder.saveBatch()`)+ * 2. `bulkWriteAclEntries` — ACL sharing grants+ * 3. `bulkIncrementTagCounts` — tag count bookkeeping+ * 4. `Transaction.insertMany` via `bulkInsertTransactions`+ * 5. the file-TTL bulkWrite — `extendFilesTTL`+ *+ * Multi-document transactions already degrade gracefully through the+ * `supportsTransactions` probe in `~/utils/transactions` (exercised in+ * `misc/documentdb/compat.documentdb.spec.ts`) — not re-tested here.+ *+ * Every flow runs the identical operation sequence first against a real+ * mongodb-memory-server (always, ungated — this is the correctness+ * baseline) and then, only when FERRETDB_URI is set, against FerretDB,+ * asserting the two runs produce equal normalized results (bulk-op counts+ * plus the resulting documents' business fields — no raw driver result+ * objects or wall-clock-sensitive timestamps are compared directly).+ *+ * Run against FerretDB (2.x requires auth):+ * FERRETDB_URI="mongodb://ferretdb:[email protected]:27020/bulkwrite_test" \+ * npx jest --config misc/ferretdb/jest.ferretdb.config.mjs bulkWrite.ferretdb --testTimeout=120000+ *+ * Without FERRETDB_URI set, only the mongodb-memory-server baseline runs.+ */++const FERRETDB_URI = process.env.FERRETDB_URI;+const itIfFerretDB = FERRETDB_URI ? it : it.skip;++const HOUR = 3_600_000;++let mongoServer: MongoMemoryServer;++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ if (mongoose.modelNames().length === 0) {+ createModels(mongoose);+ }+});++afterAll(async () => {+ await mongoServer.stop();+});++/**+ * Connects the shared mongoose singleton to `uri`, drops any leftover+ * database, runs `work`, then disconnects. Models are registered once at+ * module scope (`createModels`) and stay bound to `mongoose.connection`+ * across reconnects, so the same method objects transparently redirect+ * between the memory-server and FerretDB runs. `autoIndex: false` skips+ * building indexes for all ~37 models on every reconnect — these flows+ * only assert on data, and index builds racing the next flow's disconnect+ * otherwise log noisy (harmless) "Operation interrupted" errors.+ *+ * `work` runs inside `runAsSystem()` because these flows call production+ * methods unscoped, exactly as a cross-tenant maintenance job would; without+ * it the tenant-isolation middleware throws under `TENANT_ISOLATION_STRICT`.+ */+async function withStore<T>(uri: string, work: () => Promise<T>): Promise<T> {+ await mongoose.connect(uri, { autoIndex: false });+ await mongoose.connection.dropDatabase().catch(() => undefined);+ try {+ return await runAsSystem(work);+ } finally {+ await mongoose.connection.dropDatabase().catch(() => undefined);+ await mongoose.disconnect();+ }+}++interface BulkCounts {+ matchedCount: number;+ modifiedCount: number;+ upsertedCount: number;+}++/** Normalizes a bulkWrite result to just the counts flows in this file assert on. */+function pickCounts(result: unknown): BulkCounts {+ const r = result as Partial<BulkCounts> | null | undefined;+ return {+ matchedCount: r?.matchedCount ?? 0,+ modifiedCount: r?.modifiedCount ?? 0,+ upsertedCount: r?.upsertedCount ?? 0,+ };+}++// ─── FLOW 1: import — bulkSaveConvos + bulkSaveMessages ───────────────────++interface ImportFlowResult {+ convoBulk: BulkCounts;+ messageBulk: BulkCounts;+ convos: Array<{+ conversationId: string;+ user: string;+ title: string;+ endpoint: string;+ model: string;+ }>;+ messages: Array<{+ messageId: string;+ conversationId: string;+ user: string;+ sender: string;+ text: string;+ isCreatedByUser: boolean;+ }>;+}++async function runImportFlow(): Promise<ImportFlowResult> {+ const conversationMethods = createConversationMethods(mongoose);+ const messageMethods = createMessageMethods(mongoose);+ const Conversation = mongoose.models.Conversation as Model<t.IConversation>;+ const Message = mongoose.models.Message as Model<t.IMessage>;+ const user = 'import-flow-user';++ // First import batch: three brand-new conversations (upsert-only path).+ await conversationMethods.bulkSaveConvos([+ { conversationId: 'import-convo-1', user, title: 'First', endpoint: 'openAI', model: 'gpt-4' },+ { conversationId: 'import-convo-2', user, title: 'Second', endpoint: 'openAI', model: 'gpt-4' },+ { conversationId: 'import-convo-3', user, title: 'Third', endpoint: 'openAI', model: 'gpt-4' },+ ]);++ // Second import batch: re-imports two existing conversations — a full+ // document REPLACE, since bulkSaveConvos' update has no `$set` — plus one+ // brand-new conversation, exercising matched+modified and upserted in the+ // same bulkWrite call.+ const convoBulk = pickCounts(+ await conversationMethods.bulkSaveConvos([+ {+ conversationId: 'import-convo-1',+ user,+ title: 'First (re-imported)',+ endpoint: 'openAI',+ model: 'gpt-4',+ },+ {+ conversationId: 'import-convo-2',+ user,+ title: 'Second (re-imported)',+ endpoint: 'openAI',+ model: 'gpt-4',+ },+ {+ conversationId: 'import-convo-4',+ user,+ title: 'Fourth',+ endpoint: 'openAI',+ model: 'gpt-4',+ },+ ]),+ );++ const messageBulk = pickCounts(+ await messageMethods.bulkSaveMessages(+ [+ {+ messageId: 'import-msg-1',+ conversationId: 'import-convo-1',+ user,+ sender: 'user',+ text: 'Hi',+ isCreatedByUser: true,+ },+ {+ messageId: 'import-msg-2',+ conversationId: 'import-convo-1',+ user,+ sender: 'GPT-4',+ text: 'Hello',+ isCreatedByUser: false,+ },+ {+ messageId: 'import-msg-3',+ conversationId: 'import-convo-2',+ user,+ sender: 'user',+ text: 'Hey',+ isCreatedByUser: true,+ },+ {+ messageId: 'import-msg-4',+ conversationId: 'import-convo-4',+ user,+ sender: 'user',+ text: 'New',+ isCreatedByUser: true,+ },+ ],+ true, // overrideTimestamp, matching importBatchBuilder.saveBatch()+ ),+ );++ const convos = await Conversation.find({ user })+ .sort({ conversationId: 1 })+ .select({ conversationId: 1, user: 1, title: 1, endpoint: 1, model: 1, _id: 0 })+ .lean<ImportFlowResult['convos']>();++ const messages = await Message.find({ user })+ .sort({ messageId: 1 })+ .select({+ messageId: 1,+ conversationId: 1,+ user: 1,+ sender: 1,+ text: 1,+ isCreatedByUser: 1,+ _id: 0,+ })+ .lean<ImportFlowResult['messages']>();++ return { convoBulk, messageBulk, convos, messages };+}++describe('import path: bulkSaveConvos + bulkSaveMessages (timestamps:false)', () => {+ let baseline: ImportFlowResult;++ it('produces the expected upsert/update counts on mongodb-memory-server', async () => {+ baseline = await withStore(mongoServer.getUri(), runImportFlow);+ expect(baseline.convoBulk).toEqual({ matchedCount: 2, modifiedCount: 2, upsertedCount: 1 });+ expect(baseline.messageBulk).toEqual({ matchedCount: 0, modifiedCount: 0, upsertedCount: 4 });+ expect(baseline.convos.map((c) => c.conversationId)).toEqual([+ 'import-convo-1',+ 'import-convo-2',+ 'import-convo-3',+ 'import-convo-4',+ ]);+ expect(baseline.convos.find((c) => c.conversationId === 'import-convo-1')?.title).toBe(+ 'First (re-imported)',+ );+ expect(baseline.messages).toHaveLength(4);+ });++ itIfFerretDB('matches mongodb-memory-server on FerretDB', async () => {+ const ferret = await withStore(FERRETDB_URI as string, runImportFlow);+ expect(ferret).toEqual(baseline);+ });+});++// ─── FLOW 2: bulkWriteAclEntries ───────────────────────────────────────────++const ACL_RESOURCE_ID = new mongoose.Types.ObjectId('507f1f77bcf86cd799439011');+const ACL_USER_1 = new mongoose.Types.ObjectId('507f1f77bcf86cd799439012');+const ACL_USER_2 = new mongoose.Types.ObjectId('507f1f77bcf86cd799439013');+const ACL_USER_3 = new mongoose.Types.ObjectId('507f1f77bcf86cd799439014');+const ACL_GROUP_1 = new mongoose.Types.ObjectId('507f1f77bcf86cd799439015');+const ACL_GRANTED_BY = new mongoose.Types.ObjectId('507f1f77bcf86cd799439016');++/** Mirrors the `updateOne` + `$set`/`$setOnInsert` + `upsert:true` shape PermissionService.js builds for sharing grants. */+function grantOp(+ principalType: PrincipalType,+ principalId: mongoose.Types.ObjectId,+ principalModel: PrincipalModel,+ permBits: number,+): AnyBulkWriteOperation<t.AclEntry> {+ return {+ updateOne: {+ filter: {+ principalType,+ principalId,+ resourceType: ResourceType.AGENT,+ resourceId: ACL_RESOURCE_ID,+ },+ update: {+ $set: { permBits, grantedBy: ACL_GRANTED_BY },+ $setOnInsert: {+ principalType,+ resourceType: ResourceType.AGENT,+ resourceId: ACL_RESOURCE_ID,+ principalId,+ principalModel,+ },+ },+ upsert: true,+ },+ };+}++interface AclFlowResult {+ firstBulk: BulkCounts;+ secondBulk: BulkCounts;+ entries: Array<{+ principalType: string;+ principalId: string;+ resourceType: string;+ resourceId: string;+ permBits: number;+ }>;+}++async function runAclFlow(): Promise<AclFlowResult> {+ const aclMethods = createAclEntryMethods(mongoose);+ const AclEntry = mongoose.models.AclEntry as Model<t.IAclEntry>;++ const firstBulk = pickCounts(+ await aclMethods.bulkWriteAclEntries([+ grantOp(PrincipalType.USER, ACL_USER_1, PrincipalModel.USER, 1),+ grantOp(PrincipalType.USER, ACL_USER_2, PrincipalModel.USER, 1),+ grantOp(PrincipalType.GROUP, ACL_GROUP_1, PrincipalModel.GROUP, 3),+ ]),+ );++ // A second share round: widens two existing grants and adds a new+ // principal — matched+modified and upserted in the same bulkWrite call.+ const secondBulk = pickCounts(+ await aclMethods.bulkWriteAclEntries([+ grantOp(PrincipalType.USER, ACL_USER_1, PrincipalModel.USER, 7),+ grantOp(PrincipalType.USER, ACL_USER_2, PrincipalModel.USER, 2),+ grantOp(PrincipalType.USER, ACL_USER_3, PrincipalModel.USER, 1),+ ]),+ );++ const entries = await AclEntry.find({ resourceId: ACL_RESOURCE_ID })+ .sort({ principalType: 1, permBits: 1 })+ .lean<t.IAclEntry[]>();++ return {+ firstBulk,+ secondBulk,+ entries: entries.map((entry) => ({+ principalType: entry.principalType,+ principalId: String(entry.principalId),+ resourceType: entry.resourceType,+ resourceId: String(entry.resourceId),+ permBits: entry.permBits,+ })),+ };+}++describe('bulkWriteAclEntries (ACL sharing grants)', () => {+ let baseline: AclFlowResult;++ it('produces the expected upsert/update counts on mongodb-memory-server', async () => {+ baseline = await withStore(mongoServer.getUri(), runAclFlow);+ expect(baseline.firstBulk).toEqual({ matchedCount: 0, modifiedCount: 0, upsertedCount: 3 });+ expect(baseline.secondBulk).toEqual({ matchedCount: 2, modifiedCount: 2, upsertedCount: 1 });+ expect(baseline.entries).toHaveLength(4);+ expect(baseline.entries.map((e) => e.permBits).sort((a, b) => a - b)).toEqual([1, 2, 3, 7]);+ });++ itIfFerretDB('matches mongodb-memory-server on FerretDB', async () => {+ const ferret = await withStore(FERRETDB_URI as string, runAclFlow);+ expect(ferret).toEqual(baseline);+ });+});++// ─── FLOW 3: bulkIncrementTagCounts ────────────────────────────────────────++interface TagFlowResult {+ tags: Array<{ tag: string; count: number }>;+}++async function runTagFlow(): Promise<TagFlowResult> {+ const tagMethods = createConversationTagMethods(mongoose);+ const ConversationTag = mongoose.models.ConversationTag as Model<IConversationTag>;+ const user = 'tag-flow-user';++ await ConversationTag.create([+ { user, tag: 'existing-a', count: 2, position: 0 },+ { user, tag: 'existing-b', count: 0, position: 1 },+ ]);++ // Duplicates in the input dedupe to a single increment (Set-based); 'missing'+ // has no pre-existing row and bulkIncrementTagCounts does not upsert, so it+ // is silently skipped ("increments existing tags only").+ await tagMethods.bulkIncrementTagCounts(user, [+ 'existing-a',+ 'existing-a',+ 'existing-b',+ 'missing',+ ]);++ const tags = await ConversationTag.find({ user })+ .sort({ tag: 1 })+ .select({ tag: 1, count: 1, _id: 0 })+ .lean<TagFlowResult['tags']>();++ return { tags };+}++describe('bulkIncrementTagCounts (existing-only, deduped)', () => {+ let baseline: TagFlowResult;++ it('increments existing tags once each and skips missing tags on mongodb-memory-server', async () => {+ baseline = await withStore(mongoServer.getUri(), runTagFlow);+ expect(baseline.tags).toEqual([+ { tag: 'existing-a', count: 3 },+ { tag: 'existing-b', count: 1 },+ ]);+ });++ itIfFerretDB('matches mongodb-memory-server on FerretDB', async () => {+ const ferret = await withStore(FERRETDB_URI as string, runTagFlow);+ expect(ferret).toEqual(baseline);+ });+});++// ─── FLOW 4: Transaction.insertMany (bulkInsertTransactions) ──────────────++const TX_USER = '507f1f77bcf86cd799439020';++interface TransactionFlowResult {+ transactions: Array<{+ user: string;+ conversationId?: string;+ tokenType: string;+ model?: string;+ rawAmount?: number;+ tokenValue?: number;+ }>;+}++async function runTransactionFlow(): Promise<TransactionFlowResult> {+ const transactionMethods = createTransactionMethods(mongoose, {+ getMultiplier: () => 1,+ getCacheMultiplier: () => null,+ });+ const Transaction = mongoose.models.Transaction as Model<ITransaction>;++ await transactionMethods.bulkInsertTransactions([+ {+ user: TX_USER,+ conversationId: 'tx-convo-1',+ tokenType: 'prompt',+ model: 'gpt-4',+ rawAmount: -100,+ tokenValue: -100,+ },+ {+ user: TX_USER,+ conversationId: 'tx-convo-1',+ tokenType: 'completion',+ model: 'gpt-4',+ rawAmount: -50,+ tokenValue: -50,+ },+ {+ user: TX_USER,+ conversationId: 'tx-convo-2',+ tokenType: 'credits',+ rawAmount: 500,+ tokenValue: 500,+ },+ ]);++ const transactions = await Transaction.find({ user: TX_USER })+ .sort({ conversationId: 1, tokenType: 1 })+ .select({+ user: 1,+ conversationId: 1,+ tokenType: 1,+ model: 1,+ rawAmount: 1,+ tokenValue: 1,+ _id: 0,+ })+ .lean<TransactionFlowResult['transactions']>();++ return {+ transactions: transactions.map((tx) => ({ ...tx, user: String(tx.user) })),+ };+}++describe('Transaction.insertMany (bulkInsertTransactions)', () => {+ let baseline: TransactionFlowResult;++ it('inserts every transaction doc on mongodb-memory-server', async () => {+ baseline = await withStore(mongoServer.getUri(), runTransactionFlow);+ expect(baseline.transactions).toHaveLength(3);+ expect(baseline.transactions.map((tx) => tx.tokenType)).toEqual([+ 'completion',+ 'prompt',+ 'credits',+ ]);+ });++ itIfFerretDB('matches mongodb-memory-server on FerretDB', async () => {+ const ferret = await withStore(FERRETDB_URI as string, runTransactionFlow);+ expect(ferret).toEqual(baseline);+ });+});++// ─── FLOW 5: file-TTL bulkWrite (extendFilesTTL) ───────────────────────────++const FILE_TTL_USER = '507f1f77bcf86cd799439030';+/** `createFile`'s `Partial<IMongoFile>` requires a real ObjectId; `extendFilesTTL`'s owner scope takes a string (Mongoose casts filters automatically). */+const FILE_TTL_USER_OID = new mongoose.Types.ObjectId(FILE_TTL_USER);++interface FileTtlFlowResult {+ widenedCount: number;+ verdicts: Record<string, 'widened' | 'unchanged'>;+}++async function runFileTtlFlow(): Promise<FileTtlFlowResult> {+ const fileMethods = createFileMethods(mongoose);+ const File = mongoose.models.File as Model<t.IMongoFile>;++ const nearExpiryId = 'file-ttl-near-expiry';+ const farExpiryId = 'file-ttl-far-expiry';++ await fileMethods.createFile({+ file_id: nearExpiryId,+ user: FILE_TTL_USER_OID,+ filename: 'near.txt',+ filepath: '/uploads/near.txt',+ type: 'text/plain',+ bytes: 1,+ });+ await fileMethods.createFile({+ file_id: farExpiryId,+ user: FILE_TTL_USER_OID,+ filename: 'far.txt',+ filepath: '/uploads/far.txt',+ type: 'text/plain',+ bytes: 1,+ });++ // nearExpiry: about to lapse (1 minute out) — the hold should widen it.+ // farExpiry: already beyond the 24h renewal target (30 hours out) — the+ // `expiresAt >= next` write guard should leave it alone.+ await File.updateOne(+ { file_id: nearExpiryId },+ { $set: { expiresAt: new Date(Date.now() + 60_000) } },+ { timestamps: false },+ );+ await File.updateOne(+ { file_id: farExpiryId },+ { $set: { expiresAt: new Date(Date.now() + 30 * HOUR) } },+ { timestamps: false },+ );++ const before = await File.find({ user: FILE_TTL_USER })+ .select({ file_id: 1, expiresAt: 1, _id: 0 })+ .lean<Array<{ file_id: string; expiresAt?: Date }>>();+ const beforeByFile = new Map(before.map((f) => [f.file_id, f.expiresAt?.getTime()]));++ const widenedCount = await fileMethods.extendFilesTTL(+ [nearExpiryId, farExpiryId],+ { renewMs: 24 * HOUR, maxLifetimeMs: 48 * HOUR },+ { user: FILE_TTL_USER },+ );++ const after = await File.find({ user: FILE_TTL_USER })+ .select({ file_id: 1, expiresAt: 1, _id: 0 })+ .sort({ file_id: 1 })+ .lean<Array<{ file_id: string; expiresAt?: Date }>>();++ const verdicts: Record<string, 'widened' | 'unchanged'> = {};+ for (const file of after) {+ const beforeMs = beforeByFile.get(file.file_id);+ const afterMs = file.expiresAt?.getTime();+ verdicts[file.file_id] = beforeMs !== afterMs ? 'widened' : 'unchanged';+ }++ return { widenedCount, verdicts };+}++describe('file-TTL bulkWrite (extendFilesTTL)', () => {+ let baseline: FileTtlFlowResult;++ it('widens only the near-expiry file on mongodb-memory-server', async () => {+ baseline = await withStore(mongoServer.getUri(), runFileTtlFlow);+ expect(baseline.widenedCount).toBe(1);+ expect(baseline.verdicts).toEqual({+ 'file-ttl-near-expiry': 'widened',+ 'file-ttl-far-expiry': 'unchanged',+ });+ });++ itIfFerretDB('matches mongodb-memory-server on FerretDB', async () => {+ const ferret = await withStore(FERRETDB_URI as string, runFileTtlFlow);+ expect(ferret).toEqual(baseline);+ });+});diff --git a/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.tsindex a4d895f37a..1ff69a6f08 100644--- a/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.ts+++ b/packages/data-schemas/misc/ferretdb/multiTenancy.ferretdb.spec.ts@@ -1,36 +1,6 @@import mongoose from 'mongoose';import { execSync } from 'child_process';-import {- actionSchema,- agentSchema,- agentApiKeySchema,- agentCategorySchema,- assistantSchema,- balanceSchema,- bannerSchema,- conversationTagSchema,- convoSchema,- fileSchema,- keySchema,- messageSchema,- pluginAuthSchema,- presetSchema,- projectSchema,- promptSchema,- promptGroupSchema,- roleSchema,- sessionSchema,- shareSchema,- tokenSchema,- toolCallSchema,- transactionSchema,- userSchema,- memorySchema,- groupSchema,-} from '~/schema';-import accessRoleSchema from '~/schema/accessRole';-import aclEntrySchema from '~/schema/aclEntry';-import mcpServerSchema from '~/schema/mcpServer';+import { getModelSchemas } from './schemas';/*** FerretDB Multi-Tenancy Benchmark@@ -40,7 +10,8 @@ import mcpServerSchema from '~/schema/mcpServer';** Phases:* 1. useDb schema mapping — verifies per-org PostgreSQL schema creation and data isolation- * 2. Index initialization — validates all 29 collections + 97 indexes, tests for deadlocks+ * 2. Index initialization — validates every current org-local collection + its+ * indexes, tests for deadlocks* 3. Scaling curve — measures catalog growth, init time, and query latency at 10/50/100 orgs* 4. Write amplification — compares update cost on high-index vs zero-index collections* 5. Shared-collection alternative — benchmarks orgId-discriminated shared collections@@ -70,42 +41,12 @@ const SCALE_TIERS: number[] = process.env.SCALE_TIERSconst WRITE_AMP_DOCS = parseInt(process.env.WRITE_AMP_DOCS || '200', 10);-/** All 29 LibreChat schemas by Mongoose model name */-const MODEL_SCHEMAS: Record<string, mongoose.Schema> = {- User: userSchema,- Token: tokenSchema,- Session: sessionSchema,- Balance: balanceSchema,- Conversation: convoSchema,- Message: messageSchema,- Agent: agentSchema,- AgentApiKey: agentApiKeySchema,- AgentCategory: agentCategorySchema,- MCPServer: mcpServerSchema,- Role: roleSchema,- Action: actionSchema,- Assistant: assistantSchema,- File: fileSchema,- Banner: bannerSchema,- Project: projectSchema,- Key: keySchema,- PluginAuth: pluginAuthSchema,- Transaction: transactionSchema,- Preset: presetSchema,- Prompt: promptSchema,- PromptGroup: promptGroupSchema,- ConversationTag: conversationTagSchema,- SharedLink: shareSchema,- ToolCall: toolCallSchema,- MemoryEntry: memorySchema,- AccessRole: accessRoleSchema,- AclEntry: aclEntrySchema,- Group: groupSchema,-};+/** Org-local schema map derived from the live `createModels` registry (see ./schemas) */+const MODEL_SCHEMAS: Record<string, mongoose.Schema> = getModelSchemas(mongoose);const MODEL_COUNT = Object.keys(MODEL_SCHEMAS).length;-/** Register all 29 models on a given Mongoose Connection */+/** Register every model in MODEL_SCHEMAS on a given Mongoose Connection */function registerModels(conn: mongoose.Connection): Record<string, mongoose.Model<unknown>> {const models: Record<string, mongoose.Model<unknown>> = {};for (const [name, schema] of Object.entries(MODEL_SCHEMAS)) {@@ -234,7 +175,7 @@ describeIfFerretDB('FerretDB Multi-Tenancy Benchmark', () => {createdDbs.push(org1Db, org2Db);});- it('creates separate databases with all 29 collections via useDb()', async () => {+ it('creates separate databases with all collections via useDb()', async () => {const c1 = mongoose.connection.useDb(org1Db, { useCache: true });const c2 = mongoose.connection.useDb(org2Db, { useCache: true });@@ -353,7 +294,13 @@ describeIfFerretDB('FerretDB Multi-Tenancy Benchmark', () => {console.log(`[Phase 2] User: ${userIdxs.length} total, ${sparseCount} sparse, ${ttlCount} TTL`,);- expect(sparseCount).toBeGreaterThanOrEqual(8);+ /**+ * Counts are deliberately not pinned — the point is that FerretDB reports+ * each index *type* back, and the User schema's sparse/TTL declarations+ * change independently of this harness.+ */+ expect(sparseCount).toBeGreaterThanOrEqual(1);+ expect(ttlCount).toBeGreaterThanOrEqual(1);const fileIdxs = await conn.model('File').collection.indexes();const partialFile = fileIdxs.find(@@ -513,7 +460,7 @@ describeIfFerretDB('FerretDB Multi-Tenancy Benchmark', () => {createdDbs.push(db);const conn = mongoose.connection.useDb(db, { useCache: false });- const HighIdx = conn.model('User', userSchema);+ const HighIdx = conn.model('User', MODEL_SCHEMAS['User']);await HighIdx.createCollection();await HighIdx.createIndexes();diff --git a/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.tsindex fdea2eb8fc..2db44d62bf 100644--- a/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.ts+++ b/packages/data-schemas/misc/ferretdb/orgOperations.ferretdb.spec.ts@@ -1,36 +1,6 @@import mongoose, { Schema, type Connection, type Model } from 'mongoose';-import {- actionSchema,- agentSchema,- agentApiKeySchema,- agentCategorySchema,- assistantSchema,- balanceSchema,- bannerSchema,- conversationTagSchema,- convoSchema,- fileSchema,- keySchema,- messageSchema,- pluginAuthSchema,- presetSchema,- projectSchema,- promptSchema,- promptGroupSchema,- roleSchema,- sessionSchema,- shareSchema,- tokenSchema,- toolCallSchema,- transactionSchema,- userSchema,- memorySchema,- groupSchema,-} from '~/schema';-import accessRoleSchema from '~/schema/accessRole';-import mcpServerSchema from '~/schema/mcpServer';-import aclEntrySchema from '~/schema/aclEntry';import { initializeOrgCollections, createIndexesWithRetry, retryWithBackoff } from '~/utils/retry';+import { getModelSchemas } from './schemas';/*** Production operations tests for FerretDB multi-tenancy:@@ -48,40 +18,18 @@ const describeIfFerretDB = FERRETDB_URI ? describe : describe.skip;const DB_PREFIX = 'ops_test_';-const MODEL_SCHEMAS: Record<string, Schema> = {- User: userSchema,- Token: tokenSchema,- Session: sessionSchema,- Balance: balanceSchema,- Conversation: convoSchema,- Message: messageSchema,- Agent: agentSchema,- AgentApiKey: agentApiKeySchema,- AgentCategory: agentCategorySchema,- MCPServer: mcpServerSchema,- Role: roleSchema,- Action: actionSchema,- Assistant: assistantSchema,- File: fileSchema,- Banner: bannerSchema,- Project: projectSchema,- Key: keySchema,- PluginAuth: pluginAuthSchema,- Transaction: transactionSchema,- Preset: presetSchema,- Prompt: promptSchema,- PromptGroup: promptGroupSchema,- ConversationTag: conversationTagSchema,- SharedLink: shareSchema,- ToolCall: toolCallSchema,- MemoryEntry: memorySchema,- AccessRole: accessRoleSchema,- AclEntry: aclEntrySchema,- Group: groupSchema,-};+const MODEL_SCHEMAS: Record<string, Schema> = getModelSchemas(mongoose);const MODEL_COUNT = Object.keys(MODEL_SCHEMAS).length;+/**+ * Stand-in for a model added after the orgs were provisioned. It must stay+ * absent from the registry map above, otherwise `registerModels()` creates its+ * collection during setup and the migration test stops exercising anything.+ */+const NEW_MODEL = 'OrgEvent';+const NEW_COLLECTION = 'orgevents';+function registerModels(conn: Connection): Record<string, Model<unknown>> {const models: Record<string, Model<unknown>> = {};for (const [name, schema] of Object.entries(MODEL_SCHEMAS)) {@@ -575,6 +523,8 @@ describeIfFerretDB('Org Operations (Production)', () => {}, 60_000);it('adds a new collection to all existing orgs', async () => {+ expect(MODEL_SCHEMAS[NEW_MODEL]).toBeUndefined();+const newSchema = new Schema({orgId: { type: String, index: true },@@ -588,22 +538,30 @@ describeIfFerretDB('Org Operations (Production)', () => {for (const orgId of migrationOrgs) {const conn = baseConn.useDb(`${DB_PREFIX}org_${orgId}`, { useCache: true });- const AuditLog = conn.models['AuditLog'] || conn.model('AuditLog', newSchema);- await AuditLog.createCollection();- await createIndexesWithRetry(AuditLog);+ const collections = (await conn.db!.listCollections().toArray()).map((c) => c.name);+ expect(collections).not.toContain(NEW_COLLECTION);++ const OrgEvent = conn.models[NEW_MODEL] || conn.model(NEW_MODEL, newSchema);+ await OrgEvent.createCollection();+ await createIndexesWithRetry(OrgEvent);}for (const orgId of migrationOrgs) {const conn = baseConn.useDb(`${DB_PREFIX}org_${orgId}`, { useCache: true });const collections = (await conn.db!.listCollections().toArray()).map((c) => c.name);- expect(collections).toContain('auditlogs');+ expect(collections).toContain(NEW_COLLECTION);- const indexes = await conn.db!.collection('auditlogs').indexes();- expect(indexes.length).toBeGreaterThanOrEqual(4);+ const indexes = await conn.db!.collection(NEW_COLLECTION).indexes();+ expect(indexes.length).toBeGreaterThanOrEqual(5);+ const compound = indexes.some(+ (idx: Record<string, unknown>) =>+ JSON.stringify(idx.key) === JSON.stringify({ orgId: 1, eventType: 1, createdAt: -1 }),+ );+ expect(compound).toBe(true);}console.log(- `[Migration] New collection 'auditlogs' added to ${migrationOrgs.length} orgs with 4+ indexes`,+ `[Migration] New collection '${NEW_COLLECTION}' added to ${migrationOrgs.length} orgs with its 4 declared indexes`,);}, 60_000);diff --git a/packages/data-schemas/misc/ferretdb/schemas.ts b/packages/data-schemas/misc/ferretdb/schemas.tsnew file mode 100644index 0000000000..9c29ee15a1--- /dev/null+++ b/packages/data-schemas/misc/ferretdb/schemas.ts@@ -0,0 +1,84 @@+import type { Schema } from 'mongoose';+import { createModels } from '~/models';++/**+ * Registry entries that production keeps app-wide instead of provisioning into+ * every org database, per the rationale in each factory under `src/models`:+ * `SystemGrant` (cross-tenant control plane), `AuditLog` (append-only chain+ * serialized per `chainKey`), `SkillSyncCredential` and `SkillSyncStatus`+ * (app-wide GitHub skill sync). They are exactly the registry entries that opt+ * out of the tenant-isolation plugin, so provisioning them per org would+ * duplicate credentials and control-plane state into every tenant.+ */+export const APP_WIDE_MODELS: ReadonlySet<string> = new Set([+ 'AuditLog',+ 'SkillSyncCredential',+ 'SkillSyncStatus',+ 'SystemGrant',+]);++let cachedSchemas: Record<string, Schema> | undefined;++/**+ * Rebuilds a schema from its own definition, options, and declared indexes.+ *+ * The registry schemas are module-level singletons that `createModels` mutates+ * with application middleware (tenant isolation, audit chaining). This harness+ * benchmarks raw per-database storage behavior and reads/writes without any+ * tenant context, so it must not inherit that middleware — under+ * `TENANT_ISOLATION_STRICT=true` those hooks throw before a single FerretDB+ * assertion runs. The copy keeps every path, index, and option the collection+ * layout depends on while carrying none of the hooks.+ */+function detachSchema(mongoose: typeof import('mongoose'), source: Schema): Schema {+ const detached = new mongoose.Schema(source.obj, source.options);+ const declared = new Set(detached.indexes().map(([fields]) => JSON.stringify(fields)));++ for (const [fields, options] of source.indexes()) {+ const key = JSON.stringify(fields);+ if (declared.has(key)) {+ continue;+ }+ detached.index(fields, options);+ declared.add(key);+ }++ return detached;+}++/**+ * Derives a `{ modelName: Schema }` map of every org-local LibreChat model from+ * the live `createModels` registry instead of a hand-maintained list, so each+ * FerretDB harness spec that provisions "one of every org collection" tracks+ * the current model set automatically as models are added or removed.+ *+ * The registry is built on a throwaway Mongoose instance so nothing is+ * registered on the default connection — the benchmark opens that connection+ * itself, and default models would otherwise auto-create their collections in+ * the URI's base database and skew catalog metrics and timings.+ */+export function getModelSchemas(mongoose: typeof import('mongoose')): Record<string, Schema> {+ if (cachedSchemas) {+ return cachedSchemas;+ }++ const registry = createModels(new mongoose.Mongoose());++ const unknownAppWide = [...APP_WIDE_MODELS].filter((name) => !(name in registry));+ if (unknownAppWide.length > 0) {+ throw new Error(+ `APP_WIDE_MODELS lists models missing from the registry: ${unknownAppWide.join(', ')}`,+ );+ }++ const schemas: Record<string, Schema> = {};+ for (const [name, model] of Object.entries(registry)) {+ if (APP_WIDE_MODELS.has(name)) {+ continue;+ }+ schemas[name] = detachSchema(mongoose, model.schema);+ }++ cachedSchemas = schemas;+ return schemas;+}diff --git a/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.tsindex e27e0bbe09..42c4d12285 100644--- a/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.ts+++ b/packages/data-schemas/misc/ferretdb/sharding.ferretdb.spec.ts@@ -1,41 +1,11 @@import mongoose, { Schema, type Connection, type Model } from 'mongoose';-import {- actionSchema,- agentSchema,- agentApiKeySchema,- agentCategorySchema,- assistantSchema,- balanceSchema,- bannerSchema,- conversationTagSchema,- convoSchema,- fileSchema,- keySchema,- messageSchema,- pluginAuthSchema,- presetSchema,- projectSchema,- promptSchema,- promptGroupSchema,- roleSchema,- sessionSchema,- shareSchema,- tokenSchema,- toolCallSchema,- transactionSchema,- userSchema,- memorySchema,- groupSchema,-} from '~/schema';-import accessRoleSchema from '~/schema/accessRole';-import aclEntrySchema from '~/schema/aclEntry';-import mcpServerSchema from '~/schema/mcpServer';+import { getModelSchemas } from './schemas';/*** Sharding PoC — self-contained proof-of-concept that exercises:* 1. Multi-pool connection management via mongoose.createConnection()* 2. Persistent org→pool assignment table with capacity limits- * 3. Lazy per-org model registration using all 29 LibreChat schemas+ * 3. Lazy per-org model registration using every current org-local LibreChat schema* 4. Cross-pool data isolation* 5. Routing overhead measurement* 6. Capacity overflow handling@@ -67,39 +37,9 @@ interface PoolStats {available: number;}-// ─── ALL 29 LIBRECHAT SCHEMAS ───────────────────────────────────────────────--const MODEL_SCHEMAS: Record<string, Schema> = {- User: userSchema,- Token: tokenSchema,- Session: sessionSchema,- Balance: balanceSchema,- Conversation: convoSchema,- Message: messageSchema,- Agent: agentSchema,- AgentApiKey: agentApiKeySchema,- AgentCategory: agentCategorySchema,- MCPServer: mcpServerSchema,- Role: roleSchema,- Action: actionSchema,- Assistant: assistantSchema,- File: fileSchema,- Banner: bannerSchema,- Project: projectSchema,- Key: keySchema,- PluginAuth: pluginAuthSchema,- Transaction: transactionSchema,- Preset: presetSchema,- Prompt: promptSchema,- PromptGroup: promptGroupSchema,- ConversationTag: conversationTagSchema,- SharedLink: shareSchema,- ToolCall: toolCallSchema,- MemoryEntry: memorySchema,- AccessRole: accessRoleSchema,- AclEntry: aclEntrySchema,- Group: groupSchema,-};+// ─── LIBRECHAT ORG-LOCAL SCHEMAS (derived from the live model registry) ────++const MODEL_SCHEMAS: Record<string, Schema> = getModelSchemas(mongoose);const MODEL_COUNT = Object.keys(MODEL_SCHEMAS).length;@@ -154,7 +94,7 @@ class TenantRouter {return orgConn;}- /** Get all 29 models registered on an org's connection (lazy) */+ /** Get every model registered on an org's connection (lazy) */async getOrgModels(orgId: string): Promise<Record<string, Model<unknown>>> {const cached = this.orgModels.get(orgId);if (cached) {@@ -366,13 +306,13 @@ describeIfFerretDB('Sharding PoC', () => {});describe('org initialization and model registration', () => {- it('initializes an org with all 29 collections and indexes', async () => {+ it('initializes an org with all collections and indexes', async () => {const ms = await router.initializeOrg('org_1');- console.log(`[Sharding] org_1 init: ${ms}ms (29 collections + 98 indexes)`);+ console.log(`[Sharding] org_1 init: ${ms}ms (${MODEL_COUNT} collections)`);expect(ms).toBeGreaterThan(0);}, 60_000);- it('registers all 29 models lazily on the org connection', async () => {+ it('registers every model lazily on the org connection', async () => {const models = await router.getOrgModels('org_1');expect(Object.keys(models)).toHaveLength(MODEL_COUNT);