Skip to content

SOLR-18199: Delete-by-query deletes nested descendants - #5391

Open
dsmiley wants to merge 11 commits into
apache:mainfrom
dsmiley:SOLR-18199-dbq-nested
Open

dsmiley wants to merge 11 commits into
apache:mainfrom
dsmiley:SOLR-18199-dbq-nested

Conversation

@dsmiley

@dsmiley dsmiley commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

https://issues.apache.org/jira/browse/SOLR-18199

Description

Delete-by-query (DBQ) with nested documents could easily leave orphaned child documents: unless the query also matched every descendant of what it deleted, nested-doc integrity was violated.

Solution

When the schema has _nest_path_, DirectUpdateHandler2.getQuery() wraps the DBQ in a new WithDescendantsQuery, which also matches all nested descendants of the matched docs, at any depth. Because only the query string is logged and forwarded, expanding it there applies consistently on every replica, to reordered DBQs, and on tlog replay. *:* is left alone. Opt out with the withDescendants=false local param, e.g. {!lucene withDescendants=false}....

WithDescendantsQuery relies on descendants being indexed immediately before their ancestor. When all matches in a segment are roots (the common case), it uses the cached roots filter shared with {!parent which=/}. Otherwise it works level by level from the _nest_path_ terms. See its javadocs for details. A small FixedBitSetIntersectionIterator utility was added for that.

Notes:

  • Docs without a nest path (anonymous children, or docs indexed before _nest_path_ was added) aren't found as descendants; documented.
  • The roots filter is obtained without the request's searcher, since some UpdateLog requests are never closed (a pre-existing leak risk for any DBQ parser that calls req.getSearcher()).
  • Fixed SolrTestCaseJ4.json(), which wrote child docs in a list twice.

Tests

  • WithDescendantsQueryTest: randomized multi-level trees across segments vs. a reference model, plus Lucene's QueryUtils.check
  • DeleteByQueryNestedDocsTest: randomized DBQ shapes vs. a model, opt-out, and a _root_-only schema
  • TestRecovery: reordered DBQs with tlog replay
  • DeleteByQueryNestedDocsCloudTest: replicas stay consistent
  • FixedBitSetIntersectionIteratorTest

Checklist

  • I have reviewed the guidelines for How to Contribute and my code conforms to the standards described there to the best of my ability.
  • I have created a Jira issue and added the issue ID to my pull request title.
  • I have given Solr maintainers access to contribute to my PR branch. (optional but recommended, not available for branches on forks living under an organisation)
  • I have developed this patch against the main branch.
  • I have run ./gradlew check.
  • I have added tests for my changes.
  • I have added documentation for the Reference Guide
  • I have added a changelog entry for my change

🤖 Generated with Claude Code

When the schema has _nest_path_, a delete-by-query now also deletes all
nested descendants of the documents it matches, preventing orphaned child
documents. Opt out with the withDescendants=false local param.

* New WithDescendantsQuery, optimized for the common case of matching only root docs
* Expansion happens in DirectUpdateHandler2, so it applies on every replica and on tlog replay
* Fixed SolrTestCaseJ4.json() writing child docs in a list twice
* Docs: nested documents page and Solr 10 upgrade notes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Automated PR readiness judgements (LLM-generated; may be wrong; not updated on later pushes).

  • ✅ Jira issue in title: already present
  • ⚠️ Changelog — differs from the entry (suggest type: fixed; PR has type: changed): The change fixes a bug where delete-by-query could leave orphaned child documents in nested document schemas, which is a user-visible data integrity issue.​ The changelog entry title explicitly describes this as preventing orphaned child documents.​
  • ✅ Reference Guide update: included
  • ✅ Upgrade notes: included
  • ✅ Tests: included

@dsmiley
dsmiley requested a review from mkhludnev November 26, 2026 06:52
@dsmiley

dsmiley commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

I haven't looked through the tests closely yet but I have everything else.

Claude initially suggested a match doc iteration over DocValues. I suggested this instead, iterating the paths. Which way is faster depends on how many matching docs there are and maybe depth of nesting and also the overall ratio of nested docs to root docs. Note that nest path's terms index != it's DocValues -- the latter has more info embedded in it.


When the schema has the `\_nest_path_` field, a delete-by-query now also deletes all nested descendants of the documents it matches, at any depth.
Previously, a query matching a parent but not all of its descendants left orphaned child documents behind, violating Solr's integrity assumptions for nested documents.
To opt out, add the `withDescendants=false` local param to the query, e.g., `{!lucene withDescendants=false}category:obsolete`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why this parameter belongs to query, but not to handler request parameters? Can such query be a clause of enclosing query? I don't think so.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Quoting the 2nd sentence of the solution:

Because only the query string is logged and forwarded, expanding it there applies consistently on every replica, to reordered DBQs, and on tlog replay.

Putting request parameters on a /update is really problematic as it's not captured in the update log and thus wouldn't be replayed.

dsmiley and others added 4 commits November 26, 2026 21:01
… roots

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… for all paths

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ts filter for roots

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

Copy link
Copy Markdown

Versioned DBQ replay deletes a newer child

On 4889ce8059d4e4ba413c61b71ff529196d6c09f5, I added this test to TestRecovery. It uses the existing replay helper:

@Test
public void testReplayOlderDbqAgainstNewerInPlaceChild() throws Exception {
  testLogReplayWithReorderedDBQWrapper(
      () -> {
        updateJ(
            jsonAdd(sdoc("id", "RDBQ8", "_version_", 1L, "kids",
                sdocs(sdoc("id", "RDBQ8.0", "val_i_dvo", 1)))),
            params(DISTRIB_UPDATE_PARAM, FROM_LEADER));
        long childVersion =
            addAndGetVersion(
                sdoc("id", "RDBQ8.0", "_root_", "RDBQ8", "val_i_dvo", map("set", 7)),
                null);
        assertTrue(childVersion > 2);
        updateJ(
            jsonDelQ("id:RDBQ8"),
            params(DISTRIB_UPDATE_PARAM, FROM_LEADER, "_version_", "-2"));
      },
      () -> {
        assertJQ(req("q", "id:RDBQ8.0"), "/response/numFound==1");
        assertJQ(req("q", "id:RDBQ8"), "/response/numFound==1");
      });
}

Run with ./gradlew :solr:core:test --tests org.apache.solr.search.TestRecovery.testReplayOlderDbqAgainstNewerInPlaceChild.

The child assertion fails: the query returns 0 documents instead of 1, although replay reports errors=0. In DirectUpdateHandler2.getQuery(), the version filter applies before WithDescendantsQuery adds the child, so the child's newer version does not protect it.

Could the version check also cover descendants, while retaining any ancestors needed by a protected child?

AI assistance: AI helped review the code, design and run the reproduction, and draft this comment.

dsmiley and others added 4 commits November 27, 2026 10:25
…nd last match

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

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

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

dsmiley commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

@shihchengwei-lab re: versioned DBQ replay

Thanks for the careful repro. The replay result is real: a newer child under an older DBQ-matched root gets deleted. But I don't think a real update stream can produce that sequence.

A DBQ only runs with an older _version_ on the non-leader path, meaning a replica handling a FROM_LEADER update or a tlog replay/peer sync. On a leader, or in standalone mode, the DBQ always gets a fresh version, and a client-supplied _version_ is ignored. So the version order is the leader's order. In your repro the DBQ has version 2 and the child update a much higher version, which means the leader applied the DBQ first. With this PR, that DBQ already deleted the child as a descendant of the matched root. The in-place update that follows can't find its doc and falls back to an atomic update, which then fails ("Document not found for update. id=R"). The leader therefore never accepts that update, and no replica or tlog can contain it. If the leader had applied the in-place update first, the child's version would be older than the DBQ's, and deleting it would be correct.

This small test demonstrates both points on a single node: the in-place update is rejected after the DBQ, and a client _version_ on a DBQ is ignored: https://gist.github.com/dsmiley/d89c4215e0d87a133fd97684873ffefb

The sequence only arises from hand-built FROM_LEADER input, or in theory from a leader running pre-PR code during a rolling upgrade. I don't think the upgrade case justifies extra complexity here. An in-place update to a child does leave the block with mixed versions, which is a quirk worth knowing about, but this PR doesn't depend on block versions being uniform.

🤖 This response was AI-generated with Claude Code.

@dsmiley

dsmiley commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

I substantially improved WithDescendantsQuery:

  • It doesn't need the "result" FixedBitSet anymore
  • the nest path terms processing and bitset processing now mostly scopes to the range of docs of the underlying query, thus skipping leading irrelevant docs and trailing likewise. So a query matching a tight cluster (perhaps 1 doc) will benefit a lot.
  • the bottom/maximum depth needn't collect descendants.
    • This thus showed we could short circuit the more expensive logic with a single-depth hierarchy (i.e. 1 depth below root)

I moved the intersecting/conjunction DISI to an inner class as we're not using this anywhere else (yet). It could be moved or donated to Lucene if it proves useful. I also stopped computing the cost() as we don't need it.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants