Skip to content

feat(platform)!: derived index properties read a removed document's kept fields (PV14) - #5223

Merged
QuantumExplorer merged 1 commit into
v5.0-devfrom
claude/derived-index-kept-values
Sep 30, 2026
Merged

QuantumExplorer merged 1 commit into
v5.0-devfrom
claude/derived-index-kept-values

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

An index can hold a value of the document a reference points at, such as a reply indexed by its post's owner (postId.$ownerId, #5216). When the reference is a moderatedDocument one, the post can be removed by a moderator, and Drive then reads the value from the post's removal record instead. Until now that record kept only the owner, so the owner was the only value such an index could hold.

Since #5219 a post type can list fields its removal record keeps public (moderatorAbilities.deleteKeepsFields), such as a hashtag. This PR lets an index read those kept fields through a moderatedDocument reference too. A reply can now be indexed by the hashtag of the post it replies to, and it stays filed under that hashtag after a moderator removes the post.

Issue being fixed or feature implemented

Follow-up to #5216 (derived index properties) and #5219 (deleteKeepsFields). The moderatedDocument pair check already reads kept fields from a removal record; derived index values read only the owner.

Before, this contract was refused at registration:

"post": {
  "documentsMutable": false,
  "canBeDeleted": false,
  "moderatorAbilities": { "delete": true, "deleteKeepsFields": ["hashtag"] },
  ...
},
"reply": {
  "indices": [{ "name": "byTag", "properties": [{ "postId.hashtag": "asc" }, { "$createdAt": "asc" }] }],
  "properties": {
    "postId": { ..., "refersTo": { "type": "moderatedDocument", "documentType": "post" } }
  },
  ...
}
index "byTag" of document type "reply" reads "postId.hashtag": "postId" is a moderatedDocument reference,
whose document a moderator's removal replaces with a record keeping only its owner: through it a derived
index property reads $ownerId only

After, it registers. [["postId.hashtag", "==", "dash"]] finds the replies to posts tagged dash, before and after a moderator removes the post. An edit or deletion of a reply after the removal finds its entry under the hashtag the record kept.

What was done?

Registration (dpp). Through a moderatedDocument reference, a derived field may be:

  • $ownerId, as before;
  • a schema property the referenced type lists under deleteKeepsFields;
  • a property inside an object listed there (e.g. postId.meta.topic when meta is kept whole).

Every other #5216 rule still applies: the field must be fixed once written and indexable. The kept check needs the referenced type, so it moved from parse_derived_index_property_name to resolve_derived_index_properties (derived_index_field_error now takes the reference kind). $creatorId stays refused in the name parse, since no record keeps it. A property the record does not keep is refused with InvalidContractStructure (10231), saying to list it under deleteKeepsFields.

Shared helpers. is_kept_path and kept_value_at moved from drive-abci's reference validation (private is_kept / kept_value) to dpp::data_contract::config::moderation. The parser, Drive and the moderatedDocument pair check now share one definition of "kept" and one read of a kept value.

Drive. ReferencedValues::RemovedOwner(Identifier) became Removed(Box<ContractDocumentRemoval>). removed_document_value returns:

  • the owner for $ownerId;
  • for a kept property, the value the record keeps, as the document held it. The record's values are decoded the first time a derived property asks for one, and a path the document held nothing at reads as null, exactly as it did while the document was in state.

A field the record does not keep is CorruptedCodeExecution, never a key under a value the entry was not written under. A record whose values do not decode is CorruptedDriveState.

How Drive gets a derived value. Drive reads the removal record only when the referenced document is no longer in state, and only through a moderatedDocument reference. It always tries the document first.

flowchart TD
    A["Drive keys a reply: insert, replace, delete,<br/>moderator delete or restore, ttl expiry"] --> B{"Values already carried<br/>for this postId?"}
    B -- "yes: a create, from its reference validation,<br/>or a replace's old version, from the new one" --> K["Use the carried values<br/>nothing read"]
    B -- no --> C{"Reply holds a postId?"}
    C -- no --> N["Value: null<br/>nothing read"]
    C -- yes --> D{"Dry run?"}
    D -- yes --> E["Price the worst case: the post read,<br/>plus the removal record read for moderatedDocument<br/>Value: a placeholder of the field's type"]
    D -- no --> F["Read the post at its id (billed)"]
    F --> G{"Post in state?"}
    G -- yes --> H["Value read from the post"]
    G -- no --> I{"Reference kind?"}
    I -- permanentDocument --> X1["Error: CorruptedDriveState<br/>its documents never leave state"]
    I -- moderatedDocument --> J["Read the post's removal record (billed)"]
    J --> L{"Record there and not restored?"}
    L -- no --> X2["Error: CorruptedDriveState<br/>neither in state nor removed on the record"]
    L -- yes --> M{"Field the index reads?"}
    M -- "$ownerId" --> O["Owner kept in the record"]
    M -- "kept field, or a path<br/>inside a kept object" --> P["Kept values decoded once per reference<br/>Value as the post held it, null if it held none"]
    M -- "anything else" --> X3["Error: CorruptedCodeExecution<br/>registration refuses such a field"]
Loading

A create can not newly refer to a removed document, so only later writes of a reply (replace, delete, moderator delete or restore, expiry) ever reach the record.

Unchanged:

  • Fees and dry runs. A dry run already priced the record read with the kept fields' size.
  • Creates. A create can not newly refer to a removed document, so creates never read a record.

Docs. Book derived-index-properties.md (example, the "removed referenced document" step, the registration rule) and deletion.md (a kept value can be indexed through a reference); v14 note 65.

In-place changes to shipped generations

None shipped. Parser generation 3, create_document_types_from_document_schemas 1, Drive's derived-value reads and document reference validation 0's pair check are protocol version 14 only. PV14 is unreleased, and these are edited in place. The pair check's behaviour is unchanged: its helpers only moved crates.

How Has This Been Tested?

  • dpp:

    • should_admit_a_field_a_moderated_posts_removal_record_keeps covers a kept field (full validation and stored-contract parse) and a path inside a kept object.
    • should_refuse_a_field_a_moderated_posts_removal_record_does_not_keep covers a type keeping nothing, a type keeping another field, and $creatorId.
    • should_read_a_kept_path_or_a_path_inside_a_kept_object is a unit test for the shared helpers.
  • drive-abci e2e should_read_a_kept_field_of_a_removed_post_from_its_removal_record. It files replies under a post's kept text, removes the post, then checks:

    • the query still finds the replies;
    • an edit succeeds;
    • a delete takes out exactly one entry;
    • a proof query on committed state verifies.

    Mutation-checked: with Drive reading null instead of the kept value, the edit fails.

  • cargo clippy -p dpp -p drive -p drive-abci --all-targets -- -D warnings is clean, and cargo fmt --all -- --check passes.

  • cargo test -p dpp --lib -- derived_index document_removal moderator_abilities moderated_document validate_update: 201 passed.

  • cargo test -p drive --lib -- derived_index moderation moderated: 66 passed.

  • cargo test -p drive-abci --lib -- contract_user_moderation document_reference derived: 175 passed.

Breaking Changes

Protocol version 14 (unreleased) registers contracts it refused before: a derived index property reading a kept field through a moderatedDocument reference. A node without this change would refuse such a contract, so nodes running PV14 must upgrade together. Nothing changes for protocol versions 13 and earlier.

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

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

PR Hygiene · 0ff5cfc

  • 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.

Summary by CodeRabbit

  • New Features
    • Derived indexes can now use fields retained in a moderated document’s removal record, including nested fields within retained objects.
    • After a referenced document is removed by a moderator, indexes can continue to file and return related documents using those retained values.
    • Indexes on fields not retained in the removal record remain unavailable; creator ID is not retained.

…ept fields (PV14)

A derived index property reading through a moderatedDocument reference could
name only the referenced $ownerId, because the removal record a moderator's
deletion leaves kept nothing else. Since #5219 the record also keeps the
fields the type lists under moderatorAbilities.deleteKeepsFields, so a
derived property may now read one of those too (a kept path, or a path
inside a kept object), e.g. a reply indexed by postId.hashtag.

- dpp: the kept check moves from the name parse to
  resolve_derived_index_properties, where the referenced type is known;
  $creatorId stays refused, since no record keeps it. is_kept_path and
  kept_value_at move to config::moderation, shared by the parser, Drive and
  the moderatedDocument pair check.
- drive: once the referenced document is removed, derived values come from
  its removal record (owner, or the kept value decoded on first use); a
  field the record does not keep is an error, never a key under null.
- Book and v14 note 65 updated; dpp, helper and drive-abci e2e tests added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added this to the v4.2.0 milestone Sep 30, 2026
@github-actions

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-30T14:27:19.816Z

@coderabbitai

coderabbitai Bot commented Sep 30, 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: 56a6b778-c518-4fd9-91c5-2c67f15e4dda

📥 Commits

Reviewing files that changed from the base of the PR and between a31bce1 and 0ff5cfc.

📒 Files selected for processing (11)
  • book/src/contract-keywords/deletion.md
  • book/src/contract-keywords/derived-index-properties.md
  • packages/rs-dpp/src/data_contract/config/moderation/document_removal.rs
  • packages/rs-dpp/src/data_contract/config/moderation/mod.rs
  • packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/derived_index_property_tests.rs
  • packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/mod.rs
  • packages/rs-dpp/src/data_contract/document_type/index/derived_index_property.rs
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_reference_validation/v0/mod.rs
  • packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/derived_index_properties.rs
  • packages/rs-drive/src/drive/document/derived_index_values.rs
  • 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

Derived indexes through moderated-document references can now use fields retained in removal records, in addition to the owner. Registration validates retained paths, and Drive reads retained values when it materializes derived indexes.

Changes

Moderated-reference derived indexes

Layer / File(s) Summary
Retained-path lookup and reuse
packages/rs-dpp/src/data_contract/config/moderation/*, packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_reference_validation/v0/mod.rs
Shared helpers match exact or nested kept paths and retrieve kept values. Document-reference validation uses these helpers instead of local implementations.
Derived-field registration validation
packages/rs-dpp/src/data_contract/document_type/index/derived_index_property.rs, packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/*, packages/rs-platform-version/src/version/v14.rs, book/src/contract-keywords/derived-index-properties.md
Registration permits owner fields and schema fields retained directly or through a retained object. Validation tests cover accepted retained fields and rejected unretained fields and creator ID.
Materializing indexes from removal records
packages/rs-drive/src/drive/document/derived_index_values.rs, packages/rs-platform-version/src/version/v14.rs, packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/contract_user_moderation/tests/derived_index_properties.rs, book/src/contract-keywords/*
Drive reads owner and retained values from removal records to materialize derived indexes. Tests cover index behavior after removal, edits, deletion, and committed-state queries.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Moderator
  participant ContractDocumentRemoval
  participant derived_index_values
  participant CommittedStateProofQuery
  Moderator->>ContractDocumentRemoval: retain configured fields on removal
  derived_index_values->>ContractDocumentRemoval: read owner and retained values
  derived_index_values->>CommittedStateProofQuery: provide materialized index values
  CommittedStateProofQuery-->>derived_index_values: query matching indexed replies
Loading

Merge Risk: ⚪ Minimal · up to 0ff5c

No actionable merge-blocking issue is established. Retained-field indexes appear consistent across registration and removal-record reads; merge after normal checks and the planned coordinated PV14 upgrade.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 0ff5c

The new index access remains restricted to same-contract references and explicitly retained, fixed fields. No newly introduced authorization bypass was demonstrated. Recovery across interrupted moderation, retention-policy changes, and version rollback is only partially established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The newly admitted lookup is bounded to referenced documents within the declaring contract and to fixed fields explicitly retained by the referenced type. Its demonstrated exposure is retained data used as queryable index keys, not cross-contract access or additional moderator authority.

Trust Boundaries and Controls

  • observed — Contract-authored index paths pass through schema and fixed-field validation before admission, then retention is checked again at the removal-record sink. Nested-path authority requires an exact retained path or a dot-delimited descendant of a retained object; prefix-sharing names and unretained siblings are not authorized.

Resilience and Maintainability Implications

  • observed — Derived values are computed before callers assemble document/index operations, containing lookup failures at the materialization boundary. The removal writer returns keyed batch operations, and state validation guards repeat deletion and restoration. The inspected evidence does not establish atomic application of the complete moderation transition or its interruption and concurrency recovery.

Hardening Proposals

  • proposed — Establish an explicit lifecycle compatibility guarantee covering atomic removal-record/document updates, restoration and repeat deletion, interrupted or concurrent referring-document writes, retention-policy updates, and downgrade behavior after newly admitted contracts exist.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 95.65% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 9 files. (2 skipped: 2 …
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: derived index properties can read fields retained from a removed document in PV14.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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 the waiting-bots Waiting for the review bots to report on this head label Sep 30, 2026
@thepastaclaw

thepastaclaw commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

🕓 Queued for automated review — 1st in line, estimated start in ~35 min (commit 0ff5cfc)
Estimated review time once started: ~1.2 h (two-phase automated review; median of recent runs).

  • Request priority review — click to move this review to the front of the queue.

@QuantumExplorer

Copy link
Copy Markdown
Member Author

Reviewed

@QuantumExplorer
QuantumExplorer merged commit 70b226d into v5.0-dev Sep 30, 2026
46 of 47 checks passed
@QuantumExplorer
QuantumExplorer deleted the claude/derived-index-kept-values branch September 30, 2026 15:28
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