Skip to content

fix(drive)!: index null flags follow each index's own path (PV14) - #5173

Merged
QuantumExplorer merged 3 commits into
v4.2-devfrom
claude/sibling-null-flags-per-index
Sep 29, 2026
Merged

QuantumExplorer merged 3 commits into
v4.2-devfrom
claude/sibling-null-flags-per-index

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

What this does: Drive stores a unique index's entry in one of two shapes: a single reference when all of the index's values are present, or a small tree of references when one of them is missing (a missing value cannot be held to uniqueness). Drive picks the shape with flags it updates while walking the document type's merged index tree. When two indexes share their first property, the flags were carried from one index's branch into the next, so the shape of one index's entry could depend on another index's values. Now every index is judged by its own values only.

Value: What Drive writes now matches what the replace path, the SDK document cost (documentCreateCost) and documentTypeLayout already assume for every index.

Risks: Low to medium, contained to protocol version 14, which is not live on mainnet.

  • Consensus: the v2 index walkers change in place; they only run at protocol version 14. Devnets running 4.2 betas must upgrade all nodes together, as with any PV14 rule change.
  • Existing entries: entries written by earlier versions are still found. Where an earlier writer could disagree with this rule, the delete and the replace read how the entry is stored and remove or refresh it there.

Issue being fixed or feature implemented

Under a shared first property, the index-level walkers kept any_fields_null / all_fields_null in the function's own variables and updated them for each sibling sub-level in turn. A missing value in one branch therefore also marked every branch visited after it. The replace walker (update v1), the SDK cost model and the layout compute the flags per index, so they could disagree with what an insert wrote.

walk(level, any_fields_null):                      the sub-levels, in name order:
    for sub_level in level.sub_levels():               category  ──►  slug
        any_fields_null |= value.is_empty()   ◄── before: one variable for all siblings
        walk(sub_level, any_fields_null)

    for sub_level in level.sub_levels():
        let own = any_fields_null || value.is_empty()   ◄── after: each sibling from its parent
        walk(sub_level, own)

What was done?

Before and after

"listing": {
  "indices": [
    { "name": "byOwnerCategory", "properties": [{ "$ownerId": "asc" }, { "category": "asc" }] },
    { "name": "byOwnerSlug", "properties": [{ "$ownerId": "asc" }, { "slug": "asc" }], "unique": true }
  ],
  "properties": {
    "category": { "type": "string", "maxLength": 32, "position": 0 },
    "slug": { "type": "string", "minLength": 1, "maxLength": 32, "position": 1 }
  },
  "required": ["slug"]
}

A listing { "slug": "my-bike" } without a category. Under the owner's value tree the walker visits category before slug:

                                      before (carried)          after (per path)
listing/$ownerId/<owner>/             any_fields_null: false    any_fields_null: false
├── category/""   (missing)           true                      true
│   └── [0]: tree ── <id>: ref        byOwnerCategory (not unique): the same either way
└── slug/"my-bike"                    true  ◄── from category   false
    └── [0]:                          tree ── <id>: ref         ref
                                      (missing-value shape,     (unique shape)
                                       both values present)

The same carrying applied to all_fields_null, which decides whether a nullSearchable: false index writes an entry. A profile { "name": "ada" } with no city and no zip, beside byCityName [city, name] and byCityZip [city, zip] (nullSearchable: false):

                                      before (carried)          after (per path)
profile/city/""   (missing)           all_fields_null: true     all_fields_null: true
├── name/"ada"                        false                     false
│   └── [0]: tree ── <id>: ref        byCityName: the same either way
└── zip/""        (missing)           false ◄── from name       true
    └── [0]:                          tree ── <id>: ref         no entry
                                      (written although every   (nullSearchable: false
                                       value of it is missing)   skips it)

State trees

What Drive stores for the examples, dumped from a test run of each protocol version ([0] at the document type is primary storage; <id> is the document, <owner> its owner; "" is the null key a missing value takes).

A listing { "slug": "my-bike" } without a category:

inserted at protocol version 13                 inserted at protocol version 14

listing/                                        listing/
├── [0]                                         ├── [0]
│   └── <id>: document                          │   └── <id>: document
└── $ownerId                                    └── $ownerId
    └── <owner>                                     └── <owner>
        ├── category                                    ├── category
        │   └── "" (null)                               │   └── "" (null)
        │       └── [0]                                 │       └── [0]
        │           └── <id>: reference                 │           └── <id>: reference
        └── slug                                        └── slug
            └── "my-bike"                                   └── "my-bike"
                └── [0]              ◄── a tree                 └── [0]: reference  ◄── unique shape
                    └── <id>: reference

A profile { "name": "ada" } with no city and no zip (byCityZip is nullSearchable: false):

inserted at protocol version 13                 inserted at protocol version 14

profile/                                        profile/
├── [0]                                         ├── [0]
│   └── <id>: document                          │   └── <id>: document
└── city                                        └── city
    └── "" (null)                                   └── "" (null)
        ├── name                                        ├── name
        │   └── "ada"                                   │   └── "ada"
        │       └── [0]                                 │       └── [0]
        │           └── <id>: reference                 │           └── <id>: reference
        └── zip                                         └── zip
            └── "" (null)                                   └── "" (null)   ◄── no entry
                └── [0]      ◄── an entry
                    └── <id>: reference

The same profile when byCityZip keeps the default nullSearchable: true:

inserted at protocol version 13                 inserted at protocol version 14

profile/                                        profile/
├── [0]                                         ├── [0]
│   └── <id>: document                          │   └── <id>: document
└── city                                        └── city
    └── "" (null)                                   └── "" (null)
        ├── name                                        ├── name
        │   └── "ada"                                   │   └── "ada"
        │       └── [0]                                 │       └── [0]
        │           └── <id>: reference                 │           └── <id>: reference
        └── zip                                         └── zip
            └── "" (null)                                   └── "" (null)
                └── [0]                                         └── [0]
                    └── <id>: reference                             └── <id>: reference

Both versions store the same tree. With nullSearchable: true a document missing every value of the index still gets an entry, so the all-null flag decides nothing here, and the index is not unique, so the any-null flag never changes its shape: the carried flags only mattered for unique and nullSearchable: false indexes.

The other earlier writer, the replace walker of protocol version 13 and before: a badge (byOwnerCodeVariant [$ownerId, code, variant], unique, variant optional) created with { "code": "a", "variant": "x" } and replaced with { "code": "a" }:

replaced at protocol version 13                 the same badge inserted at protocol version 14

badge/                                          badge/
├── [0]                                         ├── [0]
│   └── <id>: document                          │   └── <id>: document
└── $ownerId                                    └── $ownerId
    └── <owner>                                     └── <owner>
        └── code                                        └── code
            └── "a"                                         └── "a"
                └── variant                                     └── variant
                    └── "" (null)                                   └── "" (null)
                        └── [0]: reference  ◄── bare                    └── [0]      ◄── a tree
                                                                            └── <id>: reference

In each pair, a delete or a replace at protocol version 14 of the document on the left reads the element at the marked place and removes or refreshes the entry in the shape it finds there.

Walkers (Drive)

  • Insert (add_indices_for_index_level_for_contract_operations v2): each sub-level's flags are its parent's flags combined with its own value.
  • Delete (remove_indices_for_index_level_for_contract_operations v2): the same, plus the flag as the earlier rule carried it.
  • Entries earlier versions laid out otherwise (drive::document::stored_index_entry): two earlier writers disagree with the rule. The walkers carried the flags across siblings, and the replace walker of earlier versions (update 0) laid out a unique index with some values missing as the bare reference and never skipped a nullSearchable: false entry. So:
    • for a unique index where either could disagree (a value missing on its path, or on an earlier sibling's), the delete walker and update 1 (removing the old entry, or refreshing it) read what is stored at [0] and act on that shape;
    • for a nullSearchable: false index the rule skips, they check whether an entry is there anyway and remove it.
  • These reads are unbilled bookkeeping, like the time-range walkers' removability reads, so a dry run and the applied operation bill the same. A type with a ttl (only from protocol version 14) skips them.

Which earlier writer can leave which shape, and what finds it now:

Written before version 14 by Can leave Found at 14 by
the insert walkers (carried flags) a unique entry as a [0] tree although all its values are present the delete and the replace reading [0]
the insert walkers (carried flags) a nullSearchable: false entry although all its values are missing the delete and the replace checking for an entry
the replace walker (update 0) a unique entry as a bare reference although a value is missing the delete and the replace reading [0]
the replace walker (update 0) a nullSearchable: false entry although all its values are missing the delete and the replace checking for an entry

How the delete, and the replace for the old entry, pick the shape at each index's terminal:

flowchart TD
    A["Delete, or replace (old entry),<br/>at an index's terminal"] --> B{"Fee dry run, indexOnly index,<br/>or a type with a ttl?"}
    B -- yes --> R["The rule's shape, no read"]
    B -- no --> C{"nullSearchable: false and<br/>every value missing?"}
    C -- yes --> D{"An entry for the document<br/>in the [0] tree?"}
    D -- yes --> E["Remove it"]
    D -- no --> F["Nothing to remove"]
    C -- no --> G{"Unique, and a value missing on<br/>its path or on an earlier sibling's?"}
    G -- no --> R
    G -- yes --> H{"Read [0]"}
    H -- tree --> I["Remove or refresh the<br/>reference inside the tree"]
    H -- reference --> J["Remove or refresh the<br/>reference at [0]"]
    H -- nothing --> R
Loading

Docs

  • Book, drive indexes chapter: Null Handling and the insert flow summary describe the per-path flags and how the delete and the replace find earlier entries.
  • PV14 changelog item 62.

In-place changes to shipped generations

  • add_indices_for_index_level_for_contract_operations v2, remove_indices_for_index_level_for_contract_operations v2 and update_document_for_contract_operations v1: selected only at protocol version 14 (DRIVE_DOCUMENT_METHOD_VERSIONS_V4), which is unreleased. The walkers of earlier versions are unchanged, so every historical block replays as before.
  • Every entry written before version 14 is either in the shape the rule gives, or found by the delete's and the replace's read.

How Has This Been Tested?

  • New e2e suite (sibling_null_flags_e2e_tests, fixture sibling-nulls-contract.json):
    • a listing without its category gets a bare unique reference, while its category index keeps the null tree;
    • an item beside an index on an $updatedAt it does not require gets a bare unique reference;
    • a listing without its category replaces to a fresh insert's tree and deletes back to the prior tree;
    • a profile missing both values of a nullSearchable: false index gets no entry there;
    • entries written under protocol version 13 and handled at 14:
      • a listing, an item and an offer (whose carried flag crosses a level) delete: the operations remove the reference inside the [0] tree and the prior tree is restored;
      • a listing replaced to another slug removes its old reference inside the tree and leaves a fresh insert's tree; one replaced with the same slug keeps its reference inside the tree;
      • a profile entry the nullSearchable: false rule skips is removed and its branch pruned;
      • a badge that a replace under 13 left in the bare layout (a value missing) deletes, and replaces to a fresh insert's tree.
  • Before the fix the first four failed, and so did the SDK cost test should_price_what_drive_charges on the new fixture (Drive charged more bytes than the model).
  • Mutation checks: disabling any one of the reads (the delete's unique read, its nullSearchable check, update 1's old-entry read or its refresh read) fails at least one of the version 13 tests. Without the delete's read, it removes [0] as a lone element, leaving the reference inside it in storage where no walk of the tree can see it; the tests check the operations for that.
  • The fixture is in the shared contract list, and should_lay_out_what_drive_writes and should_price_what_drive_charges now leave out the optional indexed values on two seeds (all of them, or every other one), so a carried flag fails the cost test.
  • Suites (after merging v4.2-dev): drive lib and integration (4,203, including the deterministic root hash tests), drive-abci lib (3,727), clippy (drive, drive-abci, all targets) and rustfmt pass; the verify-only drive build compiles.

Breaking Changes

Consensus: PV14 storage rules change in place (see above). No released protocol version is affected.

Notes for reviewers

  • A uniqueness check still reads a unique index's [0] as the rule lays it out, so a replace that keeps the values of an entry written the earlier way stops there, as it did before; such a document can be deleted, or replaced with other values. A later protocol version rewrites those entries to the rule's shape and drops the reads: Rewrite index entries earlier versions laid out otherwise, then drop the stored-layout reads (PV15+) #5196.
  • Noticed while testing, not changed here: the value trees above a skipped nullSearchable: false entry are written on insert and, with no entry below them, not pruned on delete (the layout's notNullSearchable note describes the first half).

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed
  • If I added or changed GroveDB structure, I described it in the area's structure.rs, regenerated grovedb-structure.json, and checked the structure viewer link posted on this pull request (no structure change: no new node kinds)

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 4294b12

  • Bots — coderabbitai ✓ · thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed once the bots are done
  • Within your 5 open PRs
  • Build green
  • Approvals — you own every area touched; none needed

When every box is checked the PR Hygiene check passes and this can merge.

The v2 index-level insert and delete walkers kept any_fields_null /
all_fields_null in the function's variables and updated them for each
sibling sub-level in turn, so a missing value in one branch of the merged
index tree also marked every branch visited after it: a unique index could
store its entry in the `[0]` tree meant for a missing value, and a
`nullSearchable: false` index an entry for a document missing all of its
values, because of another index's values. Update 1, the SDK document cost
and the layout already judge each index alone.

Each sub-level now gets its parent's flags combined with its own value.
The delete also tracks the flag as the earlier rule carried it; where the
two disagree on a unique index it reads the stored `[0]` and removes the
entry in the shape it has, so an entry written before still deletes. Only
PV14 (unreleased) selects these walkers; v0/v1 are unchanged.

Tests: sibling-nulls fixture (added to the shared contract list, so the
layout and SDK cost tests cover it) and an e2e suite, including a listing
inserted under protocol version 13 deleted at 14. Book Null Handling and
PV14 changelog item 59.

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

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: dashpay/platform/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: a2a624a4-b6d9-4334-8098-d562f258d3c6

📥 Commits

Reviewing files that changed from the base of the PR and between ab737de and 4294b12.

📒 Files selected for processing (15)
  • book/src/drive/indexes.md
  • packages/rs-drive/src/drive/contract/insert/insert_contract/v0/tests/mod.rs
  • packages/rs-drive/src/drive/contract/insert/insert_contract/v0/tests/sibling_null_flags_e2e_tests.rs
  • packages/rs-drive/src/drive/contract/insert/insert_contract/v0/tests/skip_if_absent_e2e_tests.rs
  • packages/rs-drive/src/drive/document/cost/tests.rs
  • packages/rs-drive/src/drive/document/delete/remove_indices_for_index_level_for_contract_operations/mod.rs
  • packages/rs-drive/src/drive/document/delete/remove_indices_for_index_level_for_contract_operations/v2/mod.rs
  • packages/rs-drive/src/drive/document/fixture_contracts.rs
  • packages/rs-drive/src/drive/document/insert/add_indices_for_index_level_for_contract_operations/v2/mod.rs
  • packages/rs-drive/src/drive/document/layout.rs
  • packages/rs-drive/src/drive/document/mod.rs
  • packages/rs-drive/src/drive/document/stored_index_entry.rs
  • packages/rs-drive/src/drive/document/update/internal/update_document_for_contract_operations/v1/mod.rs
  • packages/rs-drive/tests/supporting_files/contract/sibling-nulls/sibling-nulls-contract.json
  • packages/rs-platform-version/src/version/v14.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Version 14 index insertion now derives null flags independently for each index path. Delete and update walkers inspect stored entries in selected legacy-layout cases and use the detected layout. Fixtures and end-to-end tests cover sibling nulls and entries written under protocol version 13.

Changes

Index null handling

Layer / File(s) Summary
Per-path insert null flags
packages/rs-drive/src/drive/document/insert/add_indices_for_index_level_for_contract_operations/v2/mod.rs, book/src/drive/indexes.md
The v2 insert walker derives null flags for each sub-level from the parent flags and that sub-level’s value. The documentation describes the per-path behavior.
Stored-layout checks during deletion
packages/rs-drive/src/drive/document/stored_index_entry.rs, packages/rs-drive/src/drive/document/delete/..., packages/rs-drive/src/drive/document/mod.rs, packages/rs-platform-version/src/version/v14.rs, book/src/drive/indexes.md
The delete walker checks stored entries in selected cases and uses the detected layout when removing references. Shared reads identify tree entries and document references within them.
Stored-layout checks during updates
packages/rs-drive/src/drive/document/update/internal/update_document_for_contract_operations/v1/mod.rs
The update walker detects selected legacy layouts when deleting old entries or refreshing unchanged entries. The reads apply to eligible indexes on document types without TTL.
Sibling-null fixtures and end-to-end coverage
packages/rs-drive/tests/supporting_files/contract/sibling-nulls/*, packages/rs-drive/src/drive/document/fixture_contracts.rs, packages/rs-drive/src/drive/contract/insert/insert_contract/v0/tests/*, packages/rs-drive/src/drive/document/{cost/tests.rs,layout.rs}
Fixtures and tests cover missing sibling values and version 13 and 14 index layouts. Cost and layout tests generate documents with omitted optional indexed values.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 4294b

No actionable issue was established that would prevent merging after normal checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 4294b

The change corrects how indexes are stored, but compatibility with older stored entries matters when documents are later replaced or deleted. Version gating limits the rollout, while some recovery cases remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Documents and indexed field values supplied through Drive operations can determine their own persistent index representation. The corrected walker prevents a missing value on one sibling path from determining another index's representation; effective exposure is confined to calls using the changed versioned walkers.

Trust Boundaries and Controls

  • observed — For eligible unique-index deletes, reconciliation checks whether the stored element is a tree but does not use the target-document membership check used for a separate all-null case. The outcome for a mismatched or absent entry is not established by the available evidence.

Resilience and Maintainability Implications

  • observed — Focused legacy-entry cases check cleanup and database consistency for valid tree and direct layouts. They do not establish retry, interruption, conflicting-entry, or concurrent-update behavior for the read-then-remove transition.

Hardening Proposals

  • proposed — Establish the intended error or no-op behavior for absent and conflicting stored entries, and verify target identity and transactional probe/removal behavior before relying on legacy-layout reconciliation during retries or concurrent changes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 69.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 13 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: PV14 index null flags now follow each index's own path.
Full details: Docstring Coverage

Explanation

Docstring coverage is 69.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 49 functions across 13 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added this to the v4.2.0 milestone Sep 29, 2026
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

📖 Book Preview built successfully.

Download the preview from the workflow artifacts.
To view locally: download the artifact, unzip, and open index.html.

Updated at 2026-09-29T06:59:03.247Z

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Sep 29, 2026
@thepastaclaw

thepastaclaw commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

🔍 Review in progress — actively reviewing now (commit 4294b12) · triage: critical

@github-actions github-actions Bot added the bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. label Sep 29, 2026
QuantumExplorer and others added 2 commits September 29, 2026 13:54
…view)

Where an earlier writer could disagree with the per-path rule, the v2
delete walker and update 1 (old-entry removal and refresh) now read how
the entry is stored, through `drive::document::stored_index_entry`:
- a unique entry in the `[0]` tree although none of its own values is
  missing (an insert carried a sibling's null flag), or as the bare
  reference although one is (update 0 chose the layout from the all-null
  flag);
- a `nullSearchable: false` entry the rule skips (the carried all-null
  flag, or update 0, which never skipped).
The reads are unbilled bookkeeping, like the time-range walkers', so a
dry run and the applied operation bill the same; the dead estimation
arm and its comment are gone; a type with a `ttl` (PV14-only) skips them.

Tests: legacy e2e cases for item, offer (flag crossing a level), profile
(nullSearchable), badge (update 0 bare layout, delete and replace) and
listing (replace moving and refreshing a legacy entry), each pinned by a
mutation check; the shared layout and cost tests leave out optional
indexed values on two seeds, so they catch a carried flag; helpers
shared with the skip e2e suite; docs (insert v2, CONTRACTS, book,
changelog item 59).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict: v14.rs changelog. #5161 took item 58 (so skipIfAbsent is now
59) and #5170 / #5041 took 60 and 61; the null-flags item becomes 62.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot removed the bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. label Sep 29, 2026

@QuantumExplorer QuantumExplorer left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Approved

@QuantumExplorer
QuantumExplorer merged commit 1141aa7 into v4.2-dev Sep 29, 2026
58 of 59 checks passed
@QuantumExplorer
QuantumExplorer deleted the claude/sibling-null-flags-per-index branch September 29, 2026 12:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-bots Waiting for the review bots to report on this head

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants