Skip to content

Conversation

@lklimek
Copy link
Contributor

@lklimek lklimek commented Jan 15, 2026

Issue being fixed or feature implemented

What was done?

How Has This Been Tested?

Breaking Changes

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

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • New Features
    • Add document property references to declare identity/contract links with a mustExist flag (default: true); supports nested and multiple references and is immutable after contract creation.
  • Validation
    • Enforce existence checks for referenced identities during document create/replace operations; only changed fields may be revalidated when applicable.
  • Error Handling
    • New explicit error when a referenced entity is not found.
  • Tests & Docs
    • New documentation, test fixtures, and comprehensive tests covering parsing, state validation, and negative cases.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 15, 2026

📝 Walkthrough

Walkthrough

Adds an optional refersTo keyword for document properties, with parsing, schema updates, versioned runtime reference validation (identity existence checks), new consensus error type for missing referenced entities, WASM bindings, tests, and platform/version bumps to enable the feature.

Changes

Cohort / File(s) Summary
Specification & Schema
docs/specs/reference-validation.md, packages/rs-dpp/schema/meta_schemas/document/v0/document-meta.json
Introduces refersTo keyword (type: identity
Property Reference Types & Data Model
packages/rs-dpp/src/data_contract/document_type/property/mod.rs, packages/rs-dpp/src/data_contract/document_type/mod.rs
Adds DocumentPropertyReference, DocumentPropertyReferenceTarget, optional reference field on DocumentProperty, and REFERS_TO constant.
Property Parsing & Schema Processing
packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs, packages/rs-dpp/src/data_contract/document_type/v0/random_document_type.rs
Parses refersTo on identifier properties, rejects on non-identifiers, initializes new reference field in test generators.
Schema Compatibility & Validation Rules
packages/rs-dpp/src/data_contract/document_type/methods/validate_update/v0/mod.rs, packages/rs-json-schema-compatibility-validator/src/rules/rule_set.rs, packages/rs-json-schema-compatibility-validator/tests/rules.rs
Prevents adding/modifying refersTo after contract creation; adds compatibility rule and tests to detect incompatible changes.
DPP Meta Validators
packages/rs-dpp/src/validation/meta_validators/mod.rs
Adds tests validating refersTo presence/valid types against document meta schema.
Consensus Error Types
packages/rs-dpp/src/errors/consensus/state/document/referenced_entity_not_found_error.rs, packages/rs-dpp/src/errors/consensus/state/state_error.rs, packages/rs-dpp/src/errors/consensus/basic/basic_error.rs, packages/rs-dpp/src/errors/consensus/codes.rs, packages/rs-dpp/src/errors/consensus/state/document/mod.rs
Introduces ReferencedEntityNotFoundError with entity_id, entity_type, path; integrates into error enums and code mappings.
Document Reference Validation Module
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/document_reference_validation/*
Adds DocumentReferenceValidation trait and v0 implementation that iterates document properties, validates identity references (respecting mustExist), supports nested fields and changed-fields optimization.
Document Create/Replace State Validation (V1/V2)
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/action_validation/document/*
Adds v2 for create and v1/v2 for replace transitions; v2 delegates to v1 then runs reference validation.
Advanced Structure & Callsite Adjustments
packages/rs-drive-abci/src/execution/validation/state_transition/processor/traits/advanced_structure_with_state.rs, packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v0/mod.rs, packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/mod.rs
Reorders parameters for advanced-structure validations, adds clippy allowance for many args, updates callsites to match.
Tests & Fixtures
packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/*, packages/rs-drive-abci/tests/supporting_files/contract/reference-validation/*
Adds extensive creation/replace tests covering missing/existing references, mustExist=false, nested/multiple refs; adds three contract fixtures.
Platform Versioning
packages/rs-platform-version/src/version/*
Introduces v8 validation version and Platform v12, adds document_reference_validation flags across drive_abci versions, updates latest protocol/platform references.
WASM Bindings
packages/wasm-dpp/src/errors/consensus/state/document/referenced_entity_not_found_error.rs, packages/wasm-dpp/src/errors/consensus/state/document/mod.rs, packages/wasm-dpp/src/errors/consensus/consensus_error.rs
Adds ReferencedEntityNotFoundErrorWasm with JS accessors and integrates mapping in error conversion.
Misc / Minor
packages/dapi-grpc/Cargo.toml, scripts/configure_test_suite_network.sh, small import/test adjustments
Minor formatting, YAML path quoting, HTTPS URL update, import path tweaks, stack_size attributes, and vec!→slice test callsite updates.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ABCI as State Transition ABCI
    participant DocValidator as Document Validator (V2)
    participant RefValidator as Reference Validator (V0)
    participant Platform as Platform State
    participant Identity as Identity Store

    Client->>ABCI: Submit Document Create/Replace
    ABCI->>DocValidator: validate_state_v2(...)
    DocValidator->>DocValidator: validate_state_v1(...)
    alt v1 fails
        DocValidator-->>ABCI: return v1 error
    else v1 passes
        DocValidator->>RefValidator: validate_document_references(document_data, changed_fields, ...)
        RefValidator->>RefValidator: collect properties with refersTo
        loop each referenced property
            alt refersTo.type == "identity" && mustExist == true
                RefValidator->>Platform: fetch_identity_revision(identity_id)
                Platform->>Identity: query by id
                alt identity found
                    Identity-->>Platform: identity
                    Platform-->>RefValidator: success
                else identity missing
                    Identity-->>Platform: not found
                    Platform-->>RefValidator: error -> ReferencedEntityNotFoundError
                    RefValidator-->>ABCI: return error
                end
            else mustExist == false
                RefValidator-->>RefValidator: skip existence check
            end
        end
        RefValidator-->>DocValidator: success
        DocValidator-->>ABCI: success
    end
Loading
sequenceDiagram
    participant Contract as Contract Definition
    participant Parser as Property Parser
    participant SchemaCompat as Compatibility Validator

    Contract->>Parser: parse document schema
    Parser->>Parser: for each property
    alt property is identifier
        Parser->>Parser: parse refersTo if present -> DocumentPropertyReference
        Parser-->>Contract: property with reference attached
    else non-identifier + refersTo present
        Parser-->>Contract: emit parse error
    end
    Contract->>SchemaCompat: schema update comparison
    alt refersTo added/modified post-creation
        SchemaCompat-->>Contract: IncompatibleDocumentTypeSchemaError
    else unchanged
        SchemaCompat-->>Contract: compatible
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • pauldelucia

Poem

🐰 With twitching nose I hop and write,
I stitched refersTo through day and night.
I check each id, both near and nested,
If missing, an error's kindly requested.
Platform twelve now hops along, delight! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 69.66% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: identity reference validation' accurately captures the main feature: adding validation for identity references in documents. It is concise, clear, and directly reflects the primary changes across the codebase.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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 and usage tips.

@github-actions github-actions bot added this to the v3.0.0 milestone Jan 15, 2026
@lklimek lklimek force-pushed the feat/reference-validation branch from 72fede5 to 2eab1ca Compare January 20, 2026 12:56
@lklimek lklimek modified the milestones: v3.0.0, v3.1.0 Jan 22, 2026
@lklimek lklimek marked this pull request as ready for review January 22, 2026 13:02
@lklimek
Copy link
Contributor Author

lklimek commented Jan 22, 2026

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 22, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions github-actions bot modified the milestones: v3.1.0, v3.0.0 Jan 22, 2026
@lklimek lklimek modified the milestones: v3.0.0, v3.1.0 Jan 22, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🤖 Fix all issues with AI agents
In `@docs/specs/reference-validation.md`:
- Around line 31-33: The spec currently names the error
ReferencedIdentityNotFoundError but the implementation defines
ReferencedEntityNotFoundError; update the spec text to use
ReferencedEntityNotFoundError everywhere (including any examples/fields like {
path, identityId } -> keep fields consistent with the implementation) so the
documented error name and payload match the actual error type used by the code
(ReferencedEntityNotFoundError).

In `@packages/rs-dpp/schema/meta_schemas/document/v0/document-meta.json`:
- Around line 126-144: The schema currently allows "refersTo" on any property,
which can let non-identifier fields pass validation; update the JSON Schema so
that whenever a property contains "refersTo" it is constrained to the identifier
media type and appropriate base type: add an if/then (or dependencies) clause
that checks for the presence of "refersTo" and then enforces "type": "string"
(or the correct identifier base type) and "mediaType":
"application/vnd.dash.identifier" (or the canonical identifier media type used
in the repo), and apply this guard to both occurrences of the "refersTo" block
(the one with properties including "type" and "mustExist" and the second similar
block later in the file) so reference validation no longer accepts
non-identifier fields.

In
`@packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/replacement.rs`:
- Around line 2251-2317: The test functions in this file use imperative names
instead of the required "should ..." convention; rename the four test functions
test_document_replace_fails_when_referenced_identity_missing,
test_document_replace_succeeds_when_must_exist_false,
test_document_replace_validates_only_changed_fields, and
test_document_replace_fails_when_reference_field_changed_to_missing_identity to
start with "should" (e.g.,
should_document_replace_fail_when_referenced_identity_missing,
should_document_replace_succeed_when_must_exist_false,
should_document_replace_validate_only_changed_fields,
should_document_replace_fail_when_reference_field_changed_to_missing_identity)
so they conform to the tests/** naming guideline and update any references to
these symbols accordingly (keep function bodies and assertions unchanged).

In `@packages/rs-json-schema-compatibility-validator/tests/rules.rs`:
- Around line 54-97: Rename the test function to follow the "should …" naming
convention: change the function named test_refers_to_addition_is_incompatible to
a "should" form (for example should_refers_to_addition_be_incompatible or
should_detect_incompatible_refers_to_addition) so the test name reflects the
guideline; update the function declaration (fn
test_refers_to_addition_is_incompatible) to the new name and leave the body,
assertions (result.is_compatible, result.incompatible_changes() check) and
referenced symbols (/properties/toUserId/refersTo,
validate_schemas_compatibility, Options) unchanged.

In `@packages/rs-platform-version/src/version/v12.rs`:
- Around line 33-34: Fix the typo in the module-level documentation comment in
v12.rs: change "Intruduced" to "Introduced" in the doc comment that begins "This
version introduces document reference validation..." so the sentence reads
"Introduced in Platform release 3.1.0." This is the doc comment near the top of
the v12.rs file that documents the version change.
🧹 Nitpick comments (2)
packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs (1)

117-154: Align refersTo validation across object/non-object paths.

insert_values only calls parse_property_reference on non-object properties, so a refersTo placed on an object property could be silently ignored, while insert_values_nested rejects it. Consider validating refersTo before the match to keep behavior consistent.

♻️ Suggested adjustment
-        let property_type =
-            DocumentPropertyType::try_from_value_map(&inner_properties, &config.into())?;
+        let property_type =
+            DocumentPropertyType::try_from_value_map(&inner_properties, &config.into())?;
+        let reference = parse_property_reference(&inner_properties, &property_type)?;
 
         match property_type {
             DocumentPropertyType::Object(_) => {
                 if let Some(properties_as_value) = inner_properties.get(property_names::PROPERTIES)
                 {
                     ...
                 }
             }
             property_type => {
-                let reference = parse_property_reference(&inner_properties, &property_type)?;
                 document_properties.insert(
                     prefixed_property_key,
                     DocumentProperty {
                         property_type,
                         required: is_required,
                         transient: is_transient,
                         reference,
                     },
                 );
             }
         };
packages/rs-dpp/src/data_contract/document_type/property/mod.rs (1)

35-40: Consider omitting reference: null from serialized output.

If DocumentProperty is serialized anywhere, the new field will emit reference: null for properties without references. If you want to preserve the previous JSON shape, skip serialization when it’s None.

♻️ Suggested adjustment
 pub struct DocumentProperty {
     pub property_type: DocumentPropertyType,
     pub required: bool,
     pub transient: bool,
+    #[serde(skip_serializing_if = "Option::is_none")]
     pub reference: Option<DocumentPropertyReference>,
 }

lklimek and others added 4 commits January 22, 2026 14:23
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@github-actions github-actions bot modified the milestones: v3.1.0, v3.0.0 Jan 22, 2026
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.

2 participants