Skip to content

perf(mongodb): use idx_search_date_end for end-bounded date filters and unfiltered -date sort - #2679

Open
eterceros wants to merge 29 commits into
mainfrom
feat/2601-mongodb-use-idx-search
Open

eterceros wants to merge 29 commits into
mainfrom
feat/2601-mongodb-use-idx-search

Conversation

@eterceros

@eterceros eterceros commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

At a glance: main vs this branch

main branch
Unfiltered _sort=-date walk ~689k keys, ~1 s 200-400 keys, 3-10 ms
51 benchmark cases (15% rule) 48 better / 3 same / 0 worse
Deep offsets sort_desc_off290000 3,424 ms; sort_code_off30000 1,498 ms 1,130 ms (3x); 149 ms (10x)
Observation?subject=<id> 41 commands, 8,627 ms 4 commands, 8 ms

What changed

  • Date filters: gt hints idx_search_date_end; ge/ne run unhinted; an unfiltered _sort=-date walks that index and stops after offset + _count + 1 live ids; a rejected hint reruns unhinted.
  • Bare-id references: root $or; :below as a range plus the original regex.
  • Identity hint and limit on Q138 page bodies; Q186/Q187 hinted; Q143 skips an empty read.
  • Liveness reads return the whole $in in one reply.
  • Q173 later counts stop one row past the smallest count (keys -51%).
  • date=ap unhinted once idx_search_date_end is ready (270 -> 168 ms).
  • New index idx_resources_live_id, hinted at six liveness sites: documents fetched drop to 0.
  • A 65,536-row driver batch was tried, was slower (6-43%), and is reverted.

Evidence and limits

Same session, back to back, A-B and B-A passes. Strict 5% rule: 45 / 5 / 1. The one worse case is sort_obs_status_off20000 (+9%, one pass, a shape not touched here). Results are identical to the earlier head on 2,768 requests. The same binary run twice moved 84 of 237 cases by over 5%, so only two-pass verdicts count. Unit tests 818 passed (2 flaky profiler tests fail in parallel, pass alone). Integration: 876 passed, 1 failed (covered_membership tenant-skew, passes alone). Full numbers: issue #2180.

Write cost of the new index

91 MB for 2.27 M resources (identity index 196 MB). Inserts +3% (noise).

Upgrade note

The first boot of an existing store builds idx_resources_live_id (4.8 s on the test copy). No schema bump; not created with Elasticsearch search.

Open

Groups (c)-(e) (driver cap, :not arm, _has drain, token sort, chunked read-by-id, folded strings) need approval. Row 9 offset 20000 and Condition clinical-status offset 20000 remain.

Closes #2601

🤖 Generated with Claude Code

eterceros and others added 8 commits November 20, 2026 17:38
…nd unfiltered -date sort

gt date filters now hint idx_search_date_end when it is ready; a root $or
(ge, ne, comma lists) runs unhinted so MongoDB plans each arm, with the
cursor boundary distributed into each arm. date_hint_rejected accepts both
date indexes so a missing index falls back to an unhinted query. An
unfiltered _sort=-date page walks idx_search_date_end in end order instead
of grouping the whole parameter. Without the index every plan is unchanged.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…nt the new date hints

Document the idx_search_date_end hint for gt, the unhinted root $or for
ge/ne and the unfiltered descending date walk in search-indexes.md.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
gt (and the end-bounded arm of ge/ne) now wins on idx_search_date_end, so the
covered-scan assertion takes a set of acceptable indexes per search.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Bound a resource-lookup index filter with the predicate's own
bounded_filter, so an unhinted date root $or keeps the cursor boundary in
each arm instead of being wrapped in a root $and; rework the unit test to
pin exactly that and the hinted/wrapped cases.

Restore ge coverage in the date tests that were switched to eq: each now
runs eq, ge with idx_search_date_end ready (unhinted) and ge with it
missing (v3 hint). The covered-date-scan test requires idx_search_date_v3
for le again. New container tests cover gt/ge/ne and unfiltered -date
without the end index (v3 hint, grouped aggregate, positive control for
the $group.key0 check), ge/gt cursor paging to exhaustion, -date parity at
the keyed/keyless and live-count boundaries with and without a total, and
page-2 ids after a hot index drop.

Correct the docs and comments that said only the descending sort uses the
generation 7 index, that a comma list is always unhinted and that the
cursor boundary is repeated in every arm of any paged search.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…-idx-search

# Conflicts:
#	crates/persistence/src/backends/mongodb/search_impl/search_plan/legacy_candidates_tests.rs
…lters wrapped in $and

The `_id` batch page path wraps the date filter in
`{$and: [filter, {resource_id boundary}]}` before PredicateAccess is
computed, and the wrapped shape kept the idx_search_date_v3 hint. On 1M
rows with second-resolution dates that hint reads ~997k keys for a
selective gt/ge, while the planner (unhinted, or gt on
idx_search_date_end) reads ~59k with docsExamined 0.

With idx_search_date_end ready, a wrapped gt now keeps the end hint (the
resource_id bound does not change its value_date_end range), and a
wrapped $or (ge, ne, comma lists) goes unhinted so MongoDB plans each
arm. The pipeline_parts and seed paths already use bounded_filter and
were not affected. Without the end index, and for eq/lt/le/sa/eb/ap,
the v3 hint is unchanged; the rejected-hint retry still applies.

Tests: hint choice for wrapped gt/ge/ne ready vs not ready (unit and
container), and explain with executionStats on 5,000 distinct-second
rows showing keys bounded by the matches.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…rdered index walk

An unfiltered `_sort` by one typed search parameter (ascending or
descending date, string, token, number, quantity, reference, uri) now
walks the parameter's value index and stops after offset + count + 1
live ids, instead of grouping every row of the parameter with
$min/$max and sorting the result. The first row of a resource in key
order holds its $min/$max, so ids, tie order, missing-value placement,
has_next and totals match the grouped path. Untyped sorts, composite
and special parameters and multi-key sorts keep the grouped path, as
does any query whose index is missing, building or dropped hot.

The walk gives the sort back to the grouped aggregate when it meets an
equal-key group of more than UNFILTERED_WALK_TIE_ROWS (8,192) rows, as
a parameter with few distinct values has, so a low-cardinality sort
costs at most 0.2-0.7 s over the aggregate.

Measured on 1,000,000 rows (mongo:9.0.8, second-resolution dates),
walk vs grouped: `_sort=date` page 1 10 ms vs 2.6 s; offset 100,000
2.2 s vs 10.4 s; offset 290,000 8.1 s vs 19.2 s. No offset guard is
needed: the walk makes more round trips (1,712 vs 182 at 290,000) but
wins at every offset up to the cap. Same shape for -date and a string
sort.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
eterceros and others added 3 commits November 21, 2026 15:50
The ordered walk that serves unfiltered single-key sorts pages 101
documents at a time, so its cost grows with the offset, while the grouped
top_param_sorted_ids path is flat. Real-data measurement (689,080
Observations, _sort=-date, mongo:9.0.8, 10 VUs): offset 0 1.8 s -> 9 ms,
offset 10,000 2.05 s -> 149 ms, but offset 100,000 3.5 s -> 4.4 s (+24%)
and offset 290,000 6.6 s -> 13.8 s (~2.1x). The crossover lies between
50,000 and 100,000.

The walk now applies only when offset + _count + 1 <= 50,000
(UNFILTERED_WALK_MAX_WINDOW); above it the grouped aggregate answers as
before. The id-cap check (TooManyResults) is unchanged and independent,
and the filtered over-cap walk (#2588) is not gated.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Root cause: open_sort_row_streams selected the sort rows with
`<value_field>: {$exists: true, $ne: null}`. An index key cannot answer
$exists: true, so every row the walk passed was a FETCH of its
search_index document. On 689,080 real Observations (mongo:9.0.8,
3.5 GB cache) 100,021 rows of -date took 4.5-9 s fetched against
45-55 ms covered, and one walk at offset 100,000 read 8.6 GB of pages
through the cache. `{$ne: null}` alone selects the same rows in the same
order, proves the partial index's $exists and plans as
PROJECTION_COVERED with no document examined. The filtered over-cap
walk (#2588) opens the same cursors and is covered too. The null-end
stream of a descending date (rows written before #1391) still fetches;
it is empty once the date rows are reindexed.

Measured (single-request server+driver time, 689k real rows, replay of
both paths): offset 100,000 651 ms covered walk against 1,854 ms
grouped; offset 290,000 1,944 against 3,619. The walk is now cheaper
than the grouped aggregate at every offset up to the id cap.

Unfiltered walk only (the filtered walk keeps its 512-id batches):
- batches sized to the window (unfiltered_walk_batch: need + need/16 + 1,
  32..10,000 ids; cursor batch 128..2,048 rows): page 1 checks 32 ids,
  not 512; batches double while a full window waits for its tie or a
  batch yields under half its ids; once the batch covers the window the
  walk stops at the first new key and never enters the next group.
- counting tie guard: when an equal-key group reaches 512 rows it is
  counted once (sort_key_rows_exceed, covered, bounded); the walk gives
  up only if more rows remain than the window lacks plus
  max(8,192, offset + _count + 1). This fixes the abandoned long ties
  the window needed (_sort=code&_offset=30000, _sort=subject&_offset=10000).

Removed: UNFILTERED_WALK_MAX_WINDOW, unfiltered_walk_max_window,
with_unfiltered_walk_max_window, unfiltered_walk_applies and their tests,
and the in-loop "tie_rows > UNFILTERED_WALK_TIE_ROWS -> None" guard.
Readiness gates, hot-drop fallback and the id cap are unchanged.

Tests: covered sort-key cursors (docsExamined == 0, unfiltered both
directions of every type and filtered over-cap), a long tie the window
needs is walked with the grouped answer, a tie past the allowance falls
back after one count, batch sizing and allowance unit tests.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@eterceros
eterceros marked this pull request as ready for review November 23, 2026 14:34
@eterceros
eterceros requested review from smunini and removed request for smunini November 23, 2026 14:34
@eterceros
eterceros marked this pull request as draft November 23, 2026 14:35
eterceros and others added 2 commits November 23, 2026 14:36
…-idx-search

# Conflicts:
#	crates/persistence/mongodb/search-indexes.md
…nd follow its index in the walk tests

After merging #2602, a descending quantity sort reads idx_search_quantity_high.
The equal-key guard still counted value_quantity_value, and three walk tests
still expected the value index. Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@eterceros
eterceros marked this pull request as ready for review November 23, 2026 16:42
@eterceros
eterceros requested a review from smunini November 23, 2026 16:42
@eterceros
eterceros marked this pull request as draft November 23, 2026 16:43
@eterceros
eterceros removed the request for review from smunini November 23, 2026 16:43
@eterceros
eterceros marked this pull request as ready for review November 23, 2026 16:43
@eterceros
eterceros requested a review from smunini November 23, 2026 16:44
@eterceros
eterceros marked this pull request as draft November 23, 2026 16:46
@eterceros
eterceros removed the request for review from smunini November 23, 2026 16:46
An unfiltered single-key `_sort` walk read a long first equal-key group whole
to order it by id, or gave it to the grouped aggregate: `CarePlan?_sort=-date`
(1,653 of 3,580 rows share the open end 9999-12-31) checked 1,655 ids in seven
batches, and `Immunization?_sort=status` (one status, 14,927 rows) gave up
after four batches and grouped.

Before the walk starts, `unfiltered_first_group_window` looks at the first
sort-key cursor batch (kept buffered for the walk). When it opens with at
least 128 rows of one key K, does not show the group ending before the
window, a descending date or quantity has no row without an end, and the
window is at most 10,000 ids, it reads the rows of K from the walk's own
index ordered by resource_id in the id direction (covered, limited to the
window plus a sixteenth), deduplicates adjacent ids and checks liveness once.
K is the first key, so its group is exactly the resources with a row of K,
ordered by id as the grouped path does. A short group, stale rows that leave
fewer live ids, or a dropped index fall back to the unchanged walk.

The filter and index of an equal-key group move to `sort_key_group_filter`,
shared with `sort_key_rows_exceed`. Tests cover parity with the grouped
oracle for the seven types in both directions and both id directions, a
resource with two head rows, deletions among the lowest ids, an endless row
that switches the read off, and the profiler shape (one hinted covered find,
one liveness check, no $group); the head tie tests now expect no grouping.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@eterceros
eterceros marked this pull request as ready for review November 23, 2026 19:29
@eterceros
eterceros requested a review from smunini November 23, 2026 19:30
@eterceros
eterceros marked this pull request as draft November 23, 2026 19:30
@eterceros
eterceros marked this pull request as ready for review November 24, 2026 01:06
@eterceros
eterceros marked this pull request as draft November 24, 2026 01:06
eterceros and others added 13 commits November 24, 2026 08:49
An unfiltered `_sort` whose window crossed the end of the first equal-key
group into a long second group was slower than the grouped plan of main
(CarePlan `_sort=status` offset 1700, Condition `_sort=clinical-status`
offset 8600): the first-group read by id was attempted and discarded, the
walk read the group again row by row, and on entering the long second
group it gave the whole parameter to the grouped aggregate.

- unfiltered_first_group_window declines a group that runs past the first
  cursor batch with one bounded count when it has fewer rows than the
  window, declines a group ending in the batch with fewer distinct
  resources than the window, skips the liveness check when the read holds
  fewer distinct ids than the window, and sizes its read with
  unfiltered_group_read_limit (not cut at SORT_ID_CHUNK).
- When the walk counts the group its window ends in (after 512 rows, or
  128 when the window only waits for its open tie) and the group is much
  longer than the window still needs, it reads that group by id on the
  walk's index (unfiltered_group_closed_by_id): the ids before the group,
  then its first live members in the id direction, doubling the limit up
  to SORT_ID_CHUNK when stale rows cut the read. Otherwise the walk goes
  on unchanged. Only a single-stream walk reads by id: a descending date
  or quantity with a row without an end keeps the previous behaviour.
- ParamSortWindow::may_keep skips the check of rows the window drops
  whatever their check says; a batch with none left sends no command.
- compare_sort_keys orders -0.0 equal to 0.0, as MongoDB does; the walk
  split a group of zeros and lost its id order (test confirms it).

sort_key_rows_exceed becomes sort_key_rows_upto and returns the bounded
count. Tests compare pages, has_next and totals with the grouped oracle
around the ends of the first three groups in all four key/id direction
combinations, with deleted low ids, repeated rows and resources keyed in
two groups, a dead group head (limit doubling) and a dead group, and pin
one read by id and no $group for the closed case.

Closes #2601

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Review of af8a02e: the read by id that closes the group a window ends
in doubled its limit up to SORT_ID_CHUNK, so a group of stale or
already-keyed rows could cost many reads and liveness checks.

- unfiltered_group_closed_by_id reads at most twice: the first read is
  sized by the members the walk met per row of the group
  (lacking * tie_rows / fresh, through unfiltered_group_read_limit, at
  most SORT_ID_CHUNK); a cut read is followed by one read of
  SORT_ID_CHUNK rows. No read when the walk met no member of the group.
  It checks liveness only of the unknown members before the lacking-th
  member already known live, returns the members instead of a cloned
  window, and a rejected hint hands the sort to the grouped plan.
- The walk tries the close only when unfiltered_group_read_limit of what
  the window lacks fits in SORT_ID_CHUNK, so a group past its allowance
  that cannot be closed is grouped before the batch is checked.
- unfiltered_first_group_window passes a first group it declined for
  holding fewer members than the window, with its size known, to the
  walk as already counted: no second count, batches not cut at the probe.
- ParamSortWindow::may_keep: with the tie full, a row of another key is
  not checked (its push completes the window whatever the check says).
- The 128-row probe of a full window applies only to a single-stream
  walk, the only one that can read a group by id.
- keyed maps each resource to the ordinal of its first group instead of
  keeping a per-tie set of fresh ids.

Tests: parity with the grouped plan for a token code under two systems
and a date start with different ends (four directions); last pages whose
group lacks members (at most two reads, none when no member was met); a
dead group past its allowance grouped after two reads; read-limit
boundaries (-method offset 9,500 reads 10,000 rows, 9,501 none; first
group window 10,000 reads 10,626 rows, 10,001 none); a first group
counted at exactly the window (one count, one read of 6,387). The dead
head test now pins two reads, the second of SORT_ID_CHUNK rows. Docs in
search-indexes.md follow.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The unfiltered walk issued 6-13 commands where the grouped plan issues 3-5
on a window that crosses from a first group into a long second one: it
fetched another cursor batch just to reach the 128-row probe, counted the
group, then read it by id; and a window lacking more than SORT_ID_CHUNK
members (Condition clinical-status offset 20000) was walked and counted
twice, then grouped.

- Before a row that costs a round trip: with the batch covering what the
  window lacks, check the batch first; with the window full and an open,
  uncounted tie on one stream, read that group by id; with the group after
  a long one (>= 128 rows) and the window lacking more, count it first.
- The 128-row probe applies as soon as the batch covers the window; a
  covered single-stream group is read by id before it is counted, and
  counted only if the read leaves it open (unfiltered_tie_count).
- The reads by id are no longer bounded by SORT_ID_CHUNK: the first-group
  read takes any window, and the group close reads up to
  unfiltered_group_read_ceiling (twice the read limit, at least 10,000),
  with allowDiskUse on both finds.

The count is only a cost guard: the read by id gives the same members
whatever it says, and give-up/walk-on outcomes are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Reduces 5b191b8 to its two dry-stream rules. Before a row that would
cost a round trip on the sort-key cursor, with the batch holding what the
window lacks:

- in the walk's first batch, check the rows in hand first instead of
  fetching another cursor batch;
- with the window full and an open, uncounted tie on one stream, read
  that group by id at once, and count it only if the read leaves it
  open (unfiltered_tie_count).

Removed against 5b191b8: the 128-row probe switch inside a batch, the
read-before-count at the probe, the count of a group after a long one,
and the reads by id past SORT_ID_CHUNK (unfiltered_group_read_ceiling,
allowDiskUse on the reads); those bounds are da526e6's again.

A window just past the first group that the first batch covers
(CarePlan status offset 1700, Patient gender offset 520, Observation code
offset 150) now costs the sort find, the batch's liveness check, one read
by id and the page: no count and no getMore on the sort cursor. Other
shapes issue the same commands as da526e6. Under these rules the
give-up and walk-on outcomes are those of da526e6: a group read by id
before it was counted is counted after an open read and handled as the
probe's count would have handled it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ODB_QUERY_TAGS=1

With HFS_MONGODB_QUERY_TAGS=1 every search command sent through the
search deadline decorator (and the two hint-fallback helpers) carries the
source line that issued it as its comment, `hfs:<file>:<line>`, so the
MongoDB slow-query log, the profiler and currentOp name the code that sent
it. The decorators and helpers are #[track_caller]; the helpers stop being
async fns so the caller's location is captured. Off by default: unset, the
code path is the old one plus one cached environment lookup. A comment is
not part of the query shape or the plan cache key, so plans do not change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A bare id on normalized rows tests `value_reference` and
`value_reference_target`. Nested under the shared tenant, type and
parameter conjuncts, that `$or` implied neither partial value index, so
the planner read every row of the parameter through
`idx_search_composite` and fetched each one: `subject=<id>` examined
2.8 M keys and documents for 20 entries. The filter now puts each arm
at the top with the scope repeated, as date alternatives already do,
so each arm seeks its own index (explain on the qmon copy: 2,713,356
keys + 914,648 docs -> 396 keys, 0 docs, same 394 rows).

`:below` was one regex `^base(/|$)`. Its alternation keeps MongoDB from
deriving bounds from the literal prefix, so it read the whole parameter
(914,649 keys for 394 rows). The filter adds the range [base, base0),
which holds every string the regex matches, and keeps the regex as the
exact test on the keys walked (394 keys).

Results are unchanged: the root `$or` is the same disjunction
distributed over the scope, and the range only narrows the keys read.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Three reads already hold the ids they want and left the index to the
planner, which often walked `idx_resources_type_scan` instead:

- the page bodies of a resource-order page (`resource_order_page`):
  33,070 to 327,966 keys where the identity index reads 1,999. They are
  now hinted to `idx_resources_identity` and limited to the id count.
- the live count and the count-and-page facet of a candidate batch
  (`BatchedIndexPlan::match_batch`): the planner chose the type scan in
  329 of 467 such commands, up to 10,489 keys for one row. They now take
  the identity hint the batch's live-id find already used.

The page bodies of a parameter sort skip their find when the page is
empty (27 empty `$in` reads in the matrix capture).

Results are unchanged: a hint and a limit equal to the number of ids
choose how the same documents are read.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The driver cursor of `matching_resource_ids` used the server's batching:
101 rows, then 16 MB getMores of about 250k projected rows. A driver
that crosses the 300k id cap is thrown away after 300k rows, yet the
second getMore had already read 504k keys (`status=final&_sort=-date`).
The cursor now asks for 65,536 rows per reply, which bounds that
overshoot to one batch and answers any driver up to that size in the
first reply, with no getMore.

The liveness reads by id (`resource_level_ids`, `live_ids_among` and the
live-id find of a candidate batch) returned 101 rows and needed one
getMore for the rest of their `$in`: 11 of the 51 commands of
`_sort=code&_offset=30000`. They now ask for one more row than the
`$in` holds, so one reply returns every match and closes the cursor.

Results are unchanged: batch sizes only change how replies are cut.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
When every predicate's probe reaches the 10,000-row cap, the planner
counts each one in full and drives from the smallest. A predicate
counted after the smallest so far now stops one row past it: reaching
that limit proves it is not smaller, and the first still wins a tie, so
the driver is the one full counts choose. `date=ge2025&date=lt2026`
read 689,080 keys to pick a driver of 17,065 rows; it now reads about
twice the smallest count.

A count stopped at its limit is a lower bound: it is cached as
`AtLeast`, never as a full count, and a cached lower bound above the
smallest count settles that predicate without counting it again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
`ap` bounds the start of the stored range from above and its end from
below. The `idx_search_date_v3` hint seeks the start only, so it read
every row that starts before the window's end: 27,973 keys where
`idx_search_date_end` read 2 (78,416 against 33,542 in the gap cases).
Which side is narrower depends on the value, so once the end index is
ready an `ap`-only parameter is left unhinted and MongoDB plans it;
before that it keeps the v3 hint.

Results are unchanged: only the index choice differs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Every read that asks which candidate ids are live filters on
`is_deleted: false` and projects `id`. `idx_resources_identity` has no
`is_deleted`, so each one fetched the whole document for that boolean:
up to 290,046 documents for `/Observation?_sort=-date&_offset=290000`,
and the unkeyed walk of a parameter sort fetched every resource it
passed.

A new `resources` index `idx_resources_live_id` on
`(tenant_id, resource_type, is_deleted, id)` makes those reads covered
scans. It is hinted at the six liveness reads (`resource_level_ids`
when it has ids, `live_ids_among`, the unkeyed walk of
`param_sorted_filtered_window_over`, and the count, count-and-page and
find of `BatchedIndexPlan::match_batch`). Boot creates it with the other
`resources` indexes, except when search is offloaded to Elasticsearch,
where nothing reads it. There is no schema version or search-index
generation change, because an older build neither reads nor drops it. A rejected
hint (the index dropped by hand) runs the read again on the identity
index, which answers the same ids with a fetch.

The index adds one B-tree entry per resource insert and per deletion
flip; updates that keep `is_deleted` do not touch it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
421ee3d asked the `matching_resource_ids` driver cursor for 65,536
rows per reply. Measured on the qmon copy (two passes per side), that
bounded the over-cap read of `status=final&_sort=-date` (506,871 ->
330,323 examined, 316 -> 273 ms), but every driver that scans a long
regex range and answers in one reply got slower: `subject:contains`
386 -> 551 ms, `encounter:contains` 1,759 -> 2,436 ms, `code:text`
420 -> 530 ms, with the same keys and commands, in 11 such cases. The
net is a loss, so the cursor goes back to the server's batching. The
liveness reads keep their one-reply batch size.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
`search-indexes.md` gains a section on the `resources` liveness index:
which reads hint it, why the identity index fetched, its build at boot
(4.8 s and 91 MB for 2.27 M resources on the benchmark copy), its
write cost (inserts +3% on average, inside the noise, in an A-B-B-A
copy of 100,000 resources), the identity fallback and how to drop it.
The mongodb-elasticsearch list notes that boot does not create it there.

The README's MongoDB table gains `HFS_MONGODB_QUERY_TAGS`.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@eterceros
eterceros marked this pull request as ready for review November 25, 2026 19:20
smunini and others added 2 commits November 25, 2026 16:55
…and ids

resource_level_ids forced idx_resources_live_id whenever it had ids to
check. With another resource-level predicate (_lastUpdated, _id, a stored
version, missing_params) the hinted read fetched every candidate document
to test it, where the planner answers from another index:
Observation?code=X&_lastUpdated=gt...&_sort=-date went from 0 to 119,746
documents fetched and 150 to 400 ms on 1.2M Observations. Leave those
filters unhinted, as before #2601; with the change the query is back to
155 ms and results are unchanged.
Move the condition of resource_level_ids into resource_level_ids_hint and
test it on the filters build_resource_filter builds: another
resource-level predicate (_lastUpdated, _id, a stored version,
:missing=true) leaves the index to MongoDB (#2601).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MongoDB: use idx_search_date_end for date filters and descending date sorts

2 participants