Module: Parse::VectorSearch
- Defined in:
- lib/parse/vector_search.rb,
lib/parse/vector_search/hybrid.rb,
lib/parse/vector_search/index_definition.rb
Overview
Atlas Vector Search entry point. Routes through Parse::MongoDB
rather than Parse Server's REST aggregate (REST aggregate is master-
key-only and bypasses ACL/CLP — see CLAUDE.md).
v5.0 ships the low-level surface only:
Parse::VectorSearch.search( "WikiArticle", field: :embedding, query_vector: vec, k: 10, index: "WikiArticle_embedding_voyage_multimodal_3_1024_idx", session_token: token, )
The high-level Class.find_similar(text: …) wrapper and the
:vector property type land later in the v5.0 cycle. This module
is callable today against any collection that has a queryable
vectorSearch index — including the vector_prototype.Movie
fixture in scripts/vector_prototype/.
== Stage 0 invariant
Atlas refuses any pipeline whose stage 0 is not $vectorSearch,
$search, or $searchMeta. The module therefore bypasses
Parse::MongoDB.aggregate (which prepends an ACL $match at
stage 0) and reproduces the SDK-side enforcement chain inline —
ACL $match is appended AFTER $vectorSearch, mirroring
Parse::AtlasSearch.search.
== ACL / CLP enforcement
Identity is resolved through ACLScope.resolve!, so the
same kwargs accepted by mongo-direct paths are honored here:
session_token:, master: true, acl_user:, acl_role:. The
resolution drives:
- CLP
findboundary check — refuses calls the equivalent REST find would refuse. pointerFields/readUserFieldsownership$matchafter$vectorSearch, pushed into the$vectorSearch.filterprefilter when every owner pointer (_p_<field>) is declared as atype: "filter"field of the index.- Post-
$vectorSearchACL$matchinjection (Parse Server's_rpermpredicate). - Post-fetch
protectedFieldsredaction.
master: true bypasses ACL/CLP injection (matches the standard
mongo-direct semantics). The unconditional
PipelineSecurity.strip_internal_fields pass runs on
every result row regardless of mode, so _hashed_password and
friends never appear in returned documents.
Defined Under Namespace
Modules: Hybrid, IndexDefinition Classes: ConstraintNotSupported, InvalidQueryVector, NotAvailable
Constant Summary collapse
- MAX_DIMENSIONS =
Hard cap on query-vector dimensions to bound validator work and to refuse obvious garbage (the largest production-grade model today, Voyage
voyage-multimodal-3, is 1024-dim; OpenAItext-embedding-3-largeis 3072-dim). 8192- MAX_K =
Hard cap on
limit(k). Atlas itself caps$vectorSearch.limitat 10_000 but practical RAG workloads stay well below that; tighter cap here keeps a runaway caller from materializing a huge result set client-side. 1000- DEFAULT_NUM_CANDIDATES_MULTIPLIER =
Default
numCandidatesmultiplier when the caller doesn't pass one. Atlas's guidance: numCandidates ≥ 10 × limit, ≤ 10_000. 20- DEFAULT_CANDIDATE_MULTIPLIER =
How far past
kthe$vectorSearch.limitis raised when something downstream can drop rows (ACL enforcement, a caller-suppliedfilter,protectedFields, or pointer-field filtering). Atlas applieslimitBEFORE any of those run, so without overfetching a caller who can read 2 of the top 10 asks for 10 and receives 2 — even when hundreds of readable matches exist further down the ranking.This is a mitigation, not a guarantee: a sufficiently selective ACL can still exhaust any finite candidate window. Deterministic fill would require
_rpermdeclared astype: "filter"in the Atlas index (so the prefilter enforces visibility) or iterative candidate expansion. The instrumentation emitted by search exists so an underfill is observable rather than silent. 10- MAX_CANDIDATE_LIMIT =
Ceiling on the internally-raised candidate window. Atlas caps
numCandidatesat 10_000 andnumCandidatesmust be >=limit, so the candidate window cannot usefully exceed that. 10_000- AS_NOTIFICATION_NAME =
Emitted once per search. The counts are deliberately named for where they are actually measured — there is no cheap way to learn how many rows
$vectorSearchemitted before the server-side$matchstages ran, so no field claims to be that number:candidate_limit/num_candidates— the requested window.post_filter_count— rows returned by the pipeline, i.e. after the server-side ACL$match, the pointerFields$match, and any callerfilter.post_pointer_count— rows left after client-side redaction and the defense-in-depth pointer-field re-check.returned_count— rows handed back, after trimming tok.underfilled— the caller received fewer thank.
Obtaining a true pre-
$matchcount would require a$facet, at the cost of a second pass over the candidate set. "parse.vector_search.search"- INDEX_DRIFT_POLICIES =
Accepted index_drift_policy values.
%i[warn raise ignore].freeze
Class Attribute Summary collapse
-
.default_index ⇒ String?
Optional fallback for VectorSearch.search's
index:keyword.
Class Method Summary collapse
-
.index_drift_policy ⇒ Symbol
Current drift policy (default
:warn). -
.index_drift_policy=(value) ⇒ Symbol
Policy applied when first-query index verification (see Core::VectorSearchable) finds the deployed Atlas vectorSearch index disagreeing with the model declaration — wrong
numDimensions, wrongsimilarity, or a tenant-scope field missing from the index'sfilterpaths. -
.search_without_schema_snapshot ⇒ Array<Hash>
Low-level
$vectorSearchentry point. -
.validate_query_vector!(vec, dimensions: nil) ⇒ Array<Float>
Validate a query vector.
Class Attribute Details
.default_index ⇒ String?
Optional fallback for search's index: keyword.
487 488 489 |
# File 'lib/parse/vector_search.rb', line 487 def default_index @default_index end |
Class Method Details
.index_drift_policy ⇒ Symbol
Returns current drift policy (default :warn).
176 177 178 |
# File 'lib/parse/vector_search.rb', line 176 def index_drift_policy @index_drift_policy ||= :warn end |
.index_drift_policy=(value) ⇒ Symbol
Policy applied when first-query index verification (see
Core::VectorSearchable) finds the deployed Atlas
vectorSearch index disagreeing with the model declaration —
wrong numDimensions, wrong similarity, or a tenant-scope
field missing from the index's filter paths.
:warn(default) — emit a[Parse::VectorSearch:DRIFT]warning once per (class, field, index) and continue. Drift usually means the index predates a model change; queries still run but return degraded or wrongly-scoped results.:raise— fail the query with Core::VectorSearchable::IndexDriftError. Strict mode for deployments that treat drift as a release blocker.:ignore— skip verification entirely.
165 166 167 168 169 170 171 172 173 |
# File 'lib/parse/vector_search.rb', line 165 def index_drift_policy=(value) v = value.respond_to?(:to_sym) ? value.to_sym : nil unless v && INDEX_DRIFT_POLICIES.include?(v) raise ArgumentError, "Parse::VectorSearch.index_drift_policy must be one of " \ "#{INDEX_DRIFT_POLICIES.inspect} (got #{value.inspect})." end @index_drift_policy = v end |
.search_without_schema_snapshot ⇒ Array<Hash>
Low-level $vectorSearch entry point.
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 |
# File 'lib/parse/vector_search.rb', line 746 def search(collection_name, field:, query_vector:, k: 10, num_candidates: nil, candidate_limit: nil, filter: nil, vector_filter: nil, index: nil, max_time_ms: nil, **scope_opts) candidate_limit_override = candidate_limit require_available! index_name = (index || @default_index) if index_name.nil? || index_name.to_s.empty? raise ArgumentError, "Parse::VectorSearch.search requires index: (or set Parse::VectorSearch.default_index)." end # `Parse::ACLScope.resolve!` mutates the options hash by deleting # auth kwargs. Pass a fresh hash so we don't accidentally drop # caller kwargs and so `resolve!` can refuse 2-of-N combinations. resolution = Parse::ACLScope.resolve!(scope_opts, method_name: :"VectorSearch.search") path = field.to_s if path.empty? || path.start_with?("$") || path.include?(".") raise ArgumentError, "field: must be a non-empty, non-$-prefixed, non-dotted field name." end if Parse::PipelineSecurity::INTERNAL_FIELDS_DENYLIST.include?(path) || path.start_with?("_auth_data_") raise ArgumentError, "field: refuses internal/sensitive field path #{path.inspect}." end k_int = Integer(k) if k_int <= 0 || k_int > MAX_K raise ArgumentError, "k must be in 1..#{MAX_K} (got #{k_int})." end # Anything that can drop rows AFTER Atlas has already applied # `limit` forces an overfetch, otherwise the caller silently # receives fewer than `k`. Master mode with no caller filter # has no attrition, so it keeps the old one-for-one cost. attrition_possible = !resolution.master? || !(filter.nil? || filter.empty?) candidate_limit = if candidate_limit_override Integer(candidate_limit_override) elsif attrition_possible [k_int * DEFAULT_CANDIDATE_MULTIPLIER, MAX_CANDIDATE_LIMIT].min else k_int end if candidate_limit < k_int raise ArgumentError, "candidate_limit (#{candidate_limit}) must be >= k (#{k_int})." end if candidate_limit > MAX_CANDIDATE_LIMIT raise ArgumentError, "candidate_limit capped at #{MAX_CANDIDATE_LIMIT} by Atlas (got #{candidate_limit})." end # ANN width stays anchored to `k`, NOT to the raised window. # Deriving it from `candidate_limit` would multiply twice and # silently widen the HNSW search by the candidate multiplier — # a scoped k=10 would jump from 200 to 2000 candidates. The # window only needs numCandidates to be at least as large as # `limit`, so take whichever is greater. derived_num_candidates = [k_int * DEFAULT_NUM_CANDIDATES_MULTIPLIER, candidate_limit].max num_candidates_int = (num_candidates || derived_num_candidates).to_i num_candidates_int = MAX_CANDIDATE_LIMIT if num_candidates_int > MAX_CANDIDATE_LIMIT && num_candidates.nil? # A caller-supplied num_candidates that predates the candidate # window used to be valid whenever it was >= k. Clamping the # implicit window down to it keeps those calls working rather # than turning them into a new ArgumentError. An EXPLICIT # candidate_limit still conflicts loudly — that combination can # only be a mistake. if num_candidates && num_candidates_int < candidate_limit if candidate_limit_override raise ArgumentError, "num_candidates (#{num_candidates_int}) must be >= candidate_limit " \ "(#{candidate_limit})." end candidate_limit = [num_candidates_int, k_int].max end if num_candidates_int < k_int raise ArgumentError, "num_candidates (#{num_candidates_int}) must be >= k (#{k_int})." end if num_candidates_int > MAX_CANDIDATE_LIMIT raise ArgumentError, "num_candidates capped at #{MAX_CANDIDATE_LIMIT} by Atlas (got #{num_candidates_int})." end validated_vector = validate_query_vector!(query_vector) Parse::PipelineSecurity.validate_filter!(filter) if filter Parse::PipelineSecurity.validate_filter!(vector_filter) if vector_filter # CLP `find` boundary + pointerFields. Mirrors # `Parse::AtlasSearch.search` — without this, a scoped caller # could issue $vectorSearch against a collection whose CLP # would refuse them on the equivalent REST find. assert_clp_find!(collection_name, resolution) pointer_fields = resolve_pointer_fields!(collection_name, resolution) protected_fields = Parse::CLPScope.protected_fields_for( collection_name, resolution., client: Parse::MongoDB.clp_client_for(resolution), strict: true, ) assert_protected_fields_untouched!(collection_name, path, filter, vector_filter, protected_fields, resolution) vs_stage = { "index" => index_name.to_s, "path" => path, "queryVector" => validated_vector, "numCandidates" => num_candidates_int, # Deliberately the raised candidate window, not `k` — the # result set is trimmed to `k` after enforcement runs. "limit" => candidate_limit, } caller_prefilter = vector_filter if vector_filter && !vector_filter.empty? owner_prefilter = unless resolution.master? owner_vector_prefilter(collection_name, index_name, pointer_fields, resolution) end prefilter = [caller_prefilter, owner_prefilter].compact unless prefilter.empty? vs_stage["filter"] = prefilter.size == 1 ? prefilter.first : { "$and" => prefilter } end pipeline = [{ "$vectorSearch" => vs_stage }] pipeline << { "$addFields" => { "_vscore" => { "$meta" => "vectorSearchScore" } }, } # Inject ACL $match AFTER $vectorSearch + the score projection # but BEFORE the caller-supplied filter, so the user-controlled # filter cannot exfiltrate restricted documents that passed the # $vectorSearch operator. NOTE: Atlas's `$vectorSearch.filter` # (the pre-filter) cannot enforce ACL here because `_rperm` # would need to be declared as `type: "filter"` in the index # definition — out of scope at the SDK layer. The post-stage # `$match` is the enforcement boundary. unless resolution.master? acl_match = Parse::ACLScope.match_stage_for(resolution) pipeline << acl_match if acl_match # pointerFields / readUserFields ownership, server-side so it # runs on the whole candidate window before the trim to `k`. # When every owner pointer is filter-indexed it also ran as the # `$vectorSearch.filter` prefilter above; this stage then drops # nothing but still covers the array-of-pointers storage form. if pointer_fields pipeline << { "$match" => Parse::CLPScope.pointer_fields_predicate(pointer_fields, resolution.user_id), } end end pipeline << { "$match" => filter } if filter = Parse::ACLScope.client_of(resolution) raw_results = begin run_pipeline!(collection_name, pipeline, max_time_ms: max_time_ms, authorizing_client: ) rescue StandardError => e raise unless owner_prefilter && owner_prefilter_rejected?(e, owner_prefilter) # Atlas is serving an index version without the owner filter # path (a rebuild in progress, or a stale cached definition). # Stop pushing it down and rerun once without it; the # ownership `$match` after `$vectorSearch` still enforces it. owner_prefilter_unavailable!(collection_name, index_name) if caller_prefilter vs_stage["filter"] = caller_prefilter else vs_stage.delete("filter") end run_pipeline!(collection_name, pipeline, max_time_ms: max_time_ms, authorizing_client: ) end # Already past the server-side ACL `$match` and any caller # `filter` — NOT the number $vectorSearch emitted. post_filter_count = raw_results.length # Post-fetch enforcement: walk the rows the same way # Parse::MongoDB.aggregate would. Master mode skips every # redaction layer (matches the helper's behavior). unless resolution.master? Parse::ACLScope.redact_results!(raw_results, resolution) Parse::CLPScope.redact_protected_fields!(raw_results, protected_fields) if protected_fields.any? # Defense in depth: the pointerFields `$match` already ran in # the pipeline, so this should drop nothing. if pointer_fields raw_results = Parse::CLPScope.filter_by_pointer_fields( raw_results, pointer_fields, resolution.user_id, ) end end # Internal-fields denylist is the process-level floor: runs in # every mode, master included, so `_hashed_password` / # `_session_token` can never surface through this entry point. raw_results.map! { |doc| Parse::PipelineSecurity.strip_internal_fields(doc) } # Trim only AFTER every enforcement layer has run — that # ordering is the whole point of the raised candidate window. post_pointer_count = raw_results.length raw_results = raw_results.first(k_int) if post_pointer_count > k_int emit_search_stats( collection_name: collection_name, k: k_int, candidate_limit: candidate_limit, num_candidates: num_candidates_int, post_filter_count: post_filter_count, post_pointer_count: post_pointer_count, returned_count: raw_results.length, master: resolution.master?, ) raw_results end |
.validate_query_vector!(vec, dimensions: nil) ⇒ Array<Float>
Validate a query vector. Public so callers (and tests) can invoke it independently of search.
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 |
# File 'lib/parse/vector_search.rb', line 455 def validate_query_vector!(vec, dimensions: nil) unless vec.is_a?(Array) raise InvalidQueryVector, "query_vector must be an Array (got #{vec.class})." end if vec.empty? raise InvalidQueryVector, "query_vector cannot be empty." end if vec.length > MAX_DIMENSIONS raise InvalidQueryVector, "query_vector length #{vec.length} exceeds MAX_DIMENSIONS=#{MAX_DIMENSIONS}." end if dimensions && vec.length != dimensions raise InvalidQueryVector, "query_vector length #{vec.length} != declared dimensions #{dimensions}." end out = Array.new(vec.length) vec.each_with_index do |v, i| unless v.is_a?(Numeric) raise InvalidQueryVector, "query_vector[#{i}] is not numeric (#{v.class})." end f = v.to_f unless f.finite? raise InvalidQueryVector, "query_vector[#{i}] is not finite (#{v.inspect})." end out[i] = f end out.freeze end |