Repository navigation
feat(dpp): typed definition of a document type, read from and written to its schema - #6422
Conversation
… to its schema A document type is declared as a document schema, a JSON object. DocumentTypeDefinition holds the same declaration with one typed field per keyword: properties, indexes, references, the rule language and the type-level keywords, and nothing a node derives from them. - try_from_schema reads a document schema into it and to_schema writes the schema back, keyword for keyword. Reading holds a schema to the shape of the grammar only; it does not decide whether a network admits the type. - Its bytes write each group of keywords as the keywords present behind a mask, refuse a name written twice, and bound nesting when decoding. - SchemaDefinitions is the same form for a contract's $defs. No protocol version selects a definition: document types are still registered from their schemas. The contract corpus test reads every document type registered on mainnet and testnet as a definition, checks that it writes back the schema it was read from, that the written schema parses to the same compiled document type, and that its bytes read back. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
|
📖 Book Preview built successfully. Download the preview from the workflow artifacts. Updated at 2026-12-01T17:07:12.787Z |
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
|
✅ Final review complete — no blockers (commit a51c957) |
thepastaclaw
left a comment
There was a problem hiding this comment.
Final validation — Phase 1 + Phase 2
Changes requested: 2 blockers
- A valid
containssubschema withadditionalProperties: truecannot be translated —packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs:36-37(new)
Impact: A contract author converting an existing typed-array schema with this declaration gets a shape error and cannot produce a typed definition without editing the schema. - Schema translation silently drops explicit
nulland rewrites arrays as objects —packages/rs-dpp/src/data_contract/document_type/definition/v0/keywords.rs:35-47(new)
Impact: An author who clears an optional setting tonullin a schema editor or supplies an array where a keyword needs an object gets a successful conversion that changes the declaration instead of reporting a shape error.
This PR adds a typed DPP representation for document schemas and $defs, with schema conversion and a compact binary codec; no registration path or protocol version selects it yet. Rust workspace and wasm32 tests, the JS build and tests, Kotlin and Swift checks, and the book preview passed; PR Hygiene and the automated review were pending. One additional verified suggestion was omitted to meet the 10-comment limit.
🔴 2 blocking | 🟡 8 suggestion(s)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: grok-4.7 (standing in for gpt-6.2-sol) (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 9: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 10: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The schema conversion and binary encoding are extensive, but the diff does not change active consensus rules, peer-facing deserialization, or persisted state. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
grok-4.7(standing in forgpt-6.2-sol) — general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs`:
- [BLOCKING] packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs:36-37: A valid `contains` subschema with `additionalProperties: true` cannot be translated
Impact: A contract author converting an existing typed-array schema with this declaration gets a shape error and cannot produce a typed definition without editing the schema.
The new translator cannot import a declaration that registration and document validation already support. The native registration checker sends `contains` to `compiled_patterns`, not the ordinary property check that requires `additionalProperties: false`. The validation-schema builder then reads `additionalProperties` as a boolean inside that subschema. V0 instead reuses `Property` for `contains`, and `Property` uses `Never`, which rejects `true`. Let the nested declaration retain either boolean, while leaving registration's false-only rule in place where it applies.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs:164-177: Non-finite floats are exported as JSON `null` without an error
Impact: A caller exporting a constructed or decoded definition with infinity in `const` receives a real `null` constraint instead of a conversion error.
Export can change the meaning of a declaration and still report success. `Literal::Float` and `Number::Float` hold raw `f64` values, so Rust construction and bincode decoding admit NaN and infinity even though schema input rejects them. `to_schema` uses `serde_json::to_value`, which maps non-finite floats to `null`; for `const`, that is an actual literal, not a missing value. Use a shared checked finite-float type, or enforce finiteness explicitly during binary decode and schema export.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs:18-19: Nested member positions above `u32::MAX` cannot be translated
Impact: An author importing a registered schema with a nested member at position `4294967296` gets a conversion error even though registration can accept that position.
V0 cannot preserve the full range of positions supported by the existing schema parser. The top-level property check reads a `u32` and requires positions starting at zero, but `schema/member_position_order.rs` reads nested positions as `u64` and checks consecutiveness only after the first member. The shared `Property` type narrows both to `u32`. Store the declared position as `u64` and leave the top-level continuity rule to registration.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/keywords.rs`:
- [BLOCKING] packages/rs-dpp/src/data_contract/document_type/definition/v0/keywords.rs:35-47: Schema translation silently drops explicit `null` and rewrites arrays as objects
Impact: An author who clears an optional setting to `null` in a schema editor or supplies an array where a keyword needs an object gets a successful conversion that changes the declaration instead of reporting a shape error.
A caller using `try_from_schema` to check and translate a draft cannot tell that it accepted a malformed declaration. Serde reads an explicit `maxLength: null` as `None`, and serialization then omits it. Separately, the derived struct visitor accepts positional sequences from `serde_json::Value`, so `private: [128]` comes back as `private: {"entrySize": 128}` despite `deny_unknown_fields`. Make keyword-group deserialization map-only and use the existing `present` helper for supplied optional fields, keeping `default` for omitted fields. This still preserves `const: null` as a literal.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/mod.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/mod.rs:56-57: The field docs give the public creation mode as the owner-only setting
Impact: An author who follows the new docs and sets `creationRestrictionMode: 0` leaves document creation open to non-owners.
A contract author can publish a type with weaker creation restrictions than intended. The field passes the number through unchanged, but its comment reverses `0` and `1`: `CreationRestrictionMode::try_from` maps `0` to `NoRestrictions` and `1` to `OwnerOnly`, and creation validation checks the contract owner only for the latter. Correct the comment and link it to the enum that defines the mapping.
In `packages/rs-dpp/src/data_contract/document_type/definition/mod.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/mod.rs:76-85: Binary `$defs` decoding silently discards earlier declarations of a repeated name
Impact: A caller decoding `$defs` with a repeated name receives only the last declaration, even through the exact untrusted decoder.
The public decoder accepts input that violates the format's duplicate-name rule and loses a declaration. `SchemaDefinitions::V0` derives its codec over a bare `BTreeMap`; both untrusted map decoders in the locked `grovedb-bincode` 2.1.0 insert each pair without checking whether it replaced an earlier entry. Exact decoding only checks that all bytes were consumed. Use a definition-owned checked decoder that verifies names before inserting them. Requiring strictly increasing names would also match the existing sorted encoding without changing the bytes for valid maps.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/mod.rs:96-123: Schema translation can exhaust the stack before checking input depth
Impact: A client that passes a deeply nested `Value` directly to either schema translator can lose the process instead of receiving a conversion error.
The borrowed `Value` APIs do not require the input to have passed a bounded decoder. Both translators call a new recursive duplicate-key walk before JSON conversion, and neither path checks depth first. Use `Value::first_depth_exceeding` before recursive conversion and reuse the iterative `Value::first_repeated_text_key` for the new translator. Leave registration's existing error order and billed read count unchanged; its walker reports a path and accounts for reads, and the iterative helper does not have the same visitation order.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/nested.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/nested.rs:16-29: Deeply nested literals can serialize successfully into bytes the decoder refuses
Impact: A caller converting a schema with a deeply nested example can write the typed definition to bytes and then get a nesting error reading those same bytes.
Successful encoding does not guarantee that the definition can be read back. `Nested` applies the 128-level limit only in its binary decoders; neither schema translation nor encoding enforces it. An example containing a chain of 129 nested lists fits within native registration's 256-container schema limit, but V0 counts a `Nested` edge for every list element on that chain, including the leaf. Make the binary limit stack-safe and sufficient for the supported schema depth, then enforce the same `Nested` budget when accepting or encoding definitions.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs:19: Rust callers can build ordered maps that lose entries on export or fail to decode
Impact: A Rust caller who collects repeated property names into an `OrderedMap` can write it successfully, then get a duplicate-name error on binary readback or lose the earlier declaration on schema export.
A map built through the public API does not necessarily round-trip. `FromIterator` collects into the unchecked backing vector, and the public field also allows duplicate names through construction or mutation. Binary encoding writes both entries, but binary decoding refuses them; schema export goes through `serde_json::Value`, which retains only the last entry. Make the vector private and provide checked construction or insertion that preserves order and rejects repeated names.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/index.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/index.rs:58-68: Typed index properties accept descending order that registration rejects
Impact: An author can translate an index property ordered by `"desc"` into V0 even though no registration grammar admits that order for an index property.
The definition gives an index property a dedicated wire variant for an order it cannot use. The native index checker and all four document meta-schemas allow only `"asc"` at this position. The grammar permits `"desc"` in `chooseFirst` ordering, which the definition models separately. Remove `Desc` from the index-property enum before a protocol version selects V0.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
… says A definition read from a schema could drop or rewrite what the schema said, and its bytes could hold what a schema never writes: - a keyword group is read from an object alone, and a keyword written as null is refused where its value takes none; before, the null was read as the keyword left out and a list was read by position - a property keeps the additionalProperties its schema declares, which a contains may write as true; only a document type itself must be closed - a member's position is 64-bit, as registration reads it - an index property is ascending only, as every registration grammar says - an ordered map is built, read and decoded only from names written once, and a contract's definitions decode only from names in order - an integer below zero is the only one written signed, and a number with a fraction is finite, so each value has one form as bytes - the nesting bound holds when a schema is read, written, encoded and decoded, and a schema nested past what registration admits is refused before anything recurses into it - a group with no optional keyword writes no mask Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Your move: thepastaclaw left review threads unresolved; resolve them. |
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Changes requested: 2 blockers
- String-only schema keywords accept objects and silently export them as strings —
packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs:127-140(new)
Impact: A contract author checking a draft with"format": {"email": null}gets a successful conversion and an exported"format": "email"instead of a shape error. - Valid document rules fail translation when an integer operand is written as
3.0—packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs:314-324(new)
Impact: An author translating an otherwise valid rule such as{"lessThan": ["price", 3.0]}must edit the schema before the new API can represent it.
New on this head: This head tightens the new DPP document-definition translator and codec without changing registration, storage, or any protocol version table. The Rust workspace and wasm32 tests and the JavaScript build passed; the book preview passed on rerun after the initial mdBook download failed to unpack. Review and PR Hygiene remain pending.
🔴 2 blocking | 🟡 5 suggestion(s)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: grok-4.7 (standing in for gpt-6.2-sol) (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 9: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 10: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — This is a large and intricate but currently unused DPP data-model and serialization change, without the diff itself altering consensus rules, peer-facing protocol handling, cryptography, funds, or storage migrations. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
grok-4.7(standing in forgpt-6.2-sol) — general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs`:
- [BLOCKING] packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs:127-140: String-only schema keywords accept objects and silently export them as strings
Impact: A contract author checking a draft with `"format": {"email": null}` gets a successful conversion and an exported `"format": "email"` instead of a shape error.
A successful `try_from_schema` no longer tells the caller that these values had the required shape. The keyword visitor requires the enclosing value to be an object, but it delegates the `format` value to `Format`'s derived enum reader. The locked `serde_json::Value` deserializer accepts a one-key object as an externally tagged enum and reads the `null` payload as a unit variant. The same problem applies to index order and generated function names, and Serde's untagged buffer also accepts the object form for a property type such as `{"string": null}`. Use string-only Serde readers, as `ObjectType` does, while keeping the bincode tags unchanged.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/property.rs:164-183: Direct Serde reads traverse nested literals before checking their depth
Impact: A Rust caller reading a deeply nested in-memory JSON value through the public Serde implementation can exhaust the stack instead of getting a depth error.
The iterative preflight in `try_from_schema` does not protect a direct `serde_json::from_value` call on `Literal`, `Property`, or `DocumentTypeDefinitionV0`. The untagged reader recursively buffers the entire literal with Serde's `ContentVisitor` before it reaches a `Nested<Literal>` guard. Even when the input is within the bound, `ContentRefDeserializer` clones the remaining subtree again at each nested literal, making a chain quadratic in traversal and copying. Replace recursive untagged reads with shape-dispatching visitors that check depth as they visit children, or expose only bounded readers. Apply the same check to recursive untagged expressions and requirement terms.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs`:
- [BLOCKING] packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs:314-324: Valid document rules fail translation when an integer operand is written as `3.0`
Impact: An author translating an otherwise valid rule such as `{"lessThan": ["price", 3.0]}` must edit the schema before the new API can represent it.
The translator rejects an operand that the existing rule grammar accepts. The native constraint checker accepts a numeric operand with no fractional part, and `parse_expression` uses `whole_integer` to interpret it exactly. The parser tests also cover `3.0` in an `in` list and at a `byteAt` index. V0's `Integer` alternatives use `u64` and `Negative(i64)`, and `ByteAt` reads its index directly as `u64`; Serde rejects the floating-point representation in both paths. Preserve the declared numeric form for rule operands that already accept whole-valued floats, and use DPP's existing exact conversion rule for their interpretation. Leave strict integer fields such as `position` alone.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs:282-304: Definitions containing `-0.0` and `0.0` compare equal but serialize differently
Impact: A caller using definition equality to build a delta can miss a change in the sign of a zero-valued literal or numeric bound even though its encoded bytes change.
The typed comparison and the encoder disagree on whether the declaration changed. `Finite::new` preserves both signs, derived `PartialEq` uses `f64` equality, and bincode writes the sign bit. This affects both `Literal::Float` and `Number::Float` and is independent of overlong varints: the official encoder emits both spellings. If the definition preserves the authored sign, compare `Finite` values by their bits. If the sign is immaterial, normalize it on construction and schema import and reject the alternate form during binary decoding.
In `packages/rs-dpp/src/data_contract/document_type/definition/mod.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/mod.rs:54-69: Exact decoding accepts different byte encodings of the same definition
Impact: A caller using exact decoding to check canonical bytes can accept input that changes when reserialized.
Both definition enums accept byte forms their encoders never emit. The locked `grovedb-bincode` 2.1.0 decoder accepts a small integer in a wider varint form, including the V0 generation tag, collection lengths, and keyword masks. The mask check sees only the decoded integer, and `deserialize_from_bytes_untrusted_exact` checks only that all input was consumed. Before adopting these bytes as a contract format, check canonicality at the new format boundary or select an opt-in strict varint mode in `dashpay/grovedb`'s `grovedb-bincode`. Leave shipped decoders unchanged and distinguish canonical output from exact decoding in the documentation.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/nested.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/nested.rs:21-28: The definition and schema depth limits disagree in both directions
Impact: An author can be unable to import a registered schema with deeply nested `contains` clauses, and a Rust caller can export a nested object definition that the same API cannot read back.
The two limits count different things. A top-level property followed by 127 `properties` member edges stays inside V0's 128 `Nested` levels, so export succeeds, but the exported schema has 257 containers and the current importer rejects it at 256. In the other direction, each `contains` edge adds just one container and one `Nested` level. Native registration's `compiled_patterns` and the validation-schema builder follow those objects, so 129 `contains` edges can fit under the registration cap while failing V0 import. Define a stack-safe schema round-trip boundary for both conversion directions, and account for registered shapes outside it before migration. Do not tighten historical registration to fit V0.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/tests.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/tests.rs:610-619: A near-limit definition round trip can exhaust a default debug thread stack
Impact: A developer processing an otherwise supported deep schema on a default-stack worker in an unoptimized build can lose the process before the round trip completes.
The depth guard still admits inputs whose recursive round trip needs more stack than a default debug worker provides. The boundary test explicitly moves the supported-schema case to a 64 MiB thread, and its comment reports that the unoptimized round trip exceeds the usual test-thread stack and fits within 4 MiB. That evidence applies to the round trip as a whole, not specifically to binary decoding alone. Make the supported-depth traversal fit default worker stacks or document and enforce a smaller safe bound for those callers; lowering the bound alone would further narrow schema compatibility.
|
Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them. |
… is written in The derived readers took more than the grammar writes, and less: - a name (a format, a type, a function, an index order) was also read from an object of one key, and written back as the string. Each is now read from a string alone - a value of several shapes was held in memory whole before any of it was read. Each is now read as it is visited, by the shape written, so a nested value counts against the nesting bound before it is entered - an integer of the rule language and of a `where` written with a fraction of zero (`3.0`), which registration reads as the integer, was refused. It is kept as written - a schema is read only as a definition that writes it back: the reading ends by writing the definition and comparing - `to_schema` takes the protocol version and refuses a schema nested deeper than registration admits, so nothing is written that does not read back - decoding takes the bytes a definition is written as and no others: a small integer in a longer form is refused - two numbers are equal when they are written the same, so `0.0` and `-0.0` differ, as their bytes do The nesting bound stays at 128. A `contains` inside a `contains`, and a list inside a list of literals, nest one value a level and so can be registered deeper than a definition holds them; no registered document type does. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
GitHub still shows changes requested by this bot (review of
95856112). Nothing on this head blocks, and the bot could not dismiss that earlier review itself: a maintainer can dismiss it.
Nothing blocks: no blocking finding stands on this head.
New on this head: This head adds the typed document-definition readers, writers, bounded representations, and canonical standalone decoding checks, while keeping the format outside contract registration and consensus paths. The book preview and CodeRabbit checks passed; the remaining CI checks were still pending or in progress at the captured head.
🟡 7 suggestion(s)
Still open from earlier rounds (1)
- 🟡 Suggestion: A near-limit definition round trip can exhaust a default debug thread stack —
packages/rs-dpp/src/data_contract/document_type/definition/v0/tests.rs:618-625(thread)
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 8: grok-4.7 (standing in for gpt-6.2-sol) (agent: phase2-reviewer, role: architecture-layering); reviewer 9: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 10: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — This is a large and intricate new Rust data-model and schema translation implementation with custom binary encoding and extensive tests, but the diff does not itself alter consensus dispatch, peer-facing protocol handling, cryptography, funds movement, or storage migrations. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Second Phase-2 pass: on this first full review every Phase-2 reviewer also ran a second, independent time, and the verifier weighed both sets
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,grok-4.7(standing in forgpt-6.2-sol) — architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-dpp/src/data_contract/document_type/definition/mod.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/mod.rs:151-167: A byte-backed literal at the schema depth limit can import successfully but fail to export
Impact: A caller importing a near-limit schema containing a byte-backed literal can receive a definition that `to_schema` rejects at the same protocol version.
The import preflight checks depth on the original `Value`, where `Value::Bytes` is scalar, and only then converts it to JSON, where the same value becomes an array and adds a container level. Thus a schema can pass `try_from_schema`, including its `written_back` comparison, while `definition_schema` rejects the resulting typed definition because the exported `Value::Array` exceeds `max_depth`. Apply the depth check to the normalized JSON representation as well as the raw input for both document schemas and `$defs`, while retaining the current iterative raw preflight before recursive conversion.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/mod.rs:64-78: An embedded definition can bypass the canonical-byte check
Impact: A future contract or transition format that embeds either definition enum through a derived bincode decoder can accept bytes that change when re-encoded, despite the standalone decoder rejecting them.
The custom `PlatformDeserializableUntrusted` implementations call `decode_in_one_form`, but the enums still derive `DecodeUntrusted` and `BorrowDecodeUntrusted`. A containing derived decoder invokes those raw field traits directly, so an overlong generation or length varint bypasses the canonical re-encoding check. No current production format embeds these types, but the module documentation describes canonical standalone decoding without explaining this composability boundary. Document the distinction and require the first enclosing wire format to enforce canonicality at its own untrusted boundary.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/mod.rs:294-300: Schema import materializes and discards a full JSON copy before converting again
Impact: Clients translating large schemas or batches of contract definitions perform an additional full recursive conversion and allocation even when no shorthand expansion changes the input.
The first `definition_json` call is needed to preflight duplicate keys and depth before shorthand expansion, but its converted JSON result is discarded. The second call repeats the same checks and conversion for the unchanged `schema` when `expanded` is `None`; `$defs` follows the same pattern. Separate the preflight from materialization, or retain and reuse the first normalized JSON when expansion did not occur, while keeping the pre-expansion safety checks.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/support.rs:355-361: Integral floating-point rule operands outside i128 are accepted by the definition but rejected by the parser
Impact: A caller translating a rule containing an integral float such as `1e300` receives a successful definition even though the existing rule parser rejects that operand outside its signed-128-bit range.
The new `Whole::new` accepts every finite `f64` with zero fractional part, including values far outside the range that the rule engine can interpret as an `i128`. The existing `whole_integer` helper accepts whole floats only when they satisfy the signed-128-bit bounds, so the typed representation can successfully preserve a rule that the parser it mirrors cannot consume. Apply the same bounds when constructing `Whole`.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/abilities.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/abilities.rs:116-124: Token-cost comments misdescribe sponsorship and optional-payment rejection
Impact: A contract author following these comments can supply token payment information expecting an automatic credit fallback, or mistake the contract's sponsorship offer for the transition's effective payer, and receive a rejection instead.
The `optional` flag permits the signer to omit token payment information and pay gas in credits; it does not make an already supplied token payment optional when that payment cannot be covered. Likewise, `gasFeesPaidBy` is the contract owner's offer, which is combined with the transition request by `GasFeesPaidBy::resolve`; it is not independently the effective payer. Describe both fields in terms of those semantics.
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/abilities.rs:27-34: `deleteWithin` is documented as starting at creation, but updates restart the window
Impact: A contract author relying on the typed API documentation can give moderators a longer deletion window than intended for documents that are updated.
The field comment says the duration is measured from document creation, but the moderation implementation uses `$updatedAt` when present and falls back to `$createdAt` only when the document has never been updated. This makes the new public documentation inaccurate for mutable documents. Describe the window as measured from the last modification, or from creation when no update timestamp exists.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/tests.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/tests.rs:618-625: A near-limit definition round trip can exhaust a default debug thread stack
(carried; thread: https://github.com/dashpay/platform/pull/6422#discussion_r4750264685)
|
Bots are done — your move: post |
… written at - a value holds bytes as one value where JSON writes a list of them, one level deeper, so a schema at the depth limit could read as a definition that did not write. The JSON a definition is read from is now held to the depth a schema is held to when written - a whole number a rule writes as a float is within the range of a 128-bit signed integer, the range the rule language reads an integer in - a schema is checked once before it is converted, and converted once - the comments of `deleteWithin`, `gasFeesPaidBy` and `optional` say what the code does, and the module says which decoders hold bytes to one form Co-Authored-By: Claude Fable 5.2 <[email protected]>
…position The pinned order listed a variant of `Rule`, `Operation`, `Literal` and the other derived enums by name alone, so one holding another type left the list unchanged. The test now writes those variants out with the types they hold: their names are checked against the enum's, in its order, and a variant is taken as the function of its values it is, so a type listed that it does not hold does not compile. The module documentation says what the test does not do: it compares the declarations with the list of the same revision, so the list is to be marked `@append_only` once the grammar no longer changes in place. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
… documentation The CI check takes any line holding the marker for the start of a marked structure, a comment included, so the mention would have marked the imports that follow it. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
thepastaclaw
left a comment
There was a problem hiding this comment.
Re-review — Final validation — Phase 2 only (queue backlog)
New on this head: The final-round change expands the layout snapshot so derived enum variants are pinned together with their payload types, and clarifies the snapshot's pre-shipping limitations. Rust workspace and Kotlin checks are failing on an unrelated base-branch wallet compile error; JavaScript and wasm32 checks remain in progress.
🟡 1 suggestion(s)
Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.
Still open from earlier rounds (1)
- 🟡 Suggestion: Derived variants can change payload bytes without changing the pinned layout —
packages/rs-dpp/src/data_contract/document_type/definition/v0/layout.rs:307-314(thread)
Review provenance
Source: reviewer 1: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: tenderdash-consensus-security); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalby fallback after triage failure (exit 1 timed_out=False: API Error: Connection dropped (ECONNRESET)) - Phase 1 reviewers: not run (skipped for throughput: 11 PRs queued, above the 10 limit)
- Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— security-auditor (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— tenderdash-consensus-security (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/layout.rs`:
- [SUGGESTION] packages/rs-dpp/src/data_contract/document_type/definition/v0/layout.rs:307-314: Derived variants can change payload bytes without changing the pinned layout
(carried; thread: https://github.com/dashpay/platform/pull/6422#discussion_r4757332760)
Out-of-scope follow-up suggestions (1)
These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.
- Workspace CI fails on an unrelated base-branch wallet error match — The Rust workspace and Kotlin SDK checks fail because exhaustive matches in
rs-platform-walletdo not handlePlatformWalletError::MasternodeVotingKeyNotInWallet. The failing wallet code is already on the base branch and is outside this PR'srs-dpplayout-only changes.- Follow-up: Merge or track the platform-wallet fix in #6431, then rerun the workspace and Kotlin checks.
|
Bots are done — your move: post |
… not its alias `CountOf::Filtered` and `SumOf::Filtered` were listed as holding `AggregateFilter`, a name for `OrderedMap<AggregateBinding>`: a change to what the name stands for would have left the list unchanged. The list names the type, and a test refuses a line that names an alias the grammar declares. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post |
There was a problem hiding this comment.
Re-review — Final validation — Phase 1 + Phase 2
Updated after discussion: 1 finding(s) of this review were settled in the inline threads.
- ⏭️ Deferred (maintainer decision): 🟡 Private and restricted aliases can hide wire type changes from the layout guard (tracked in #6427)
New on this head: This revision pins the concrete payload type for both aggregate-filter variants and adds an alias check to the V0 layout test. The codec and contract registration paths are unchanged. Rust workspace and wasm32 tests, the Kotlin emulator build and tests, and the book preview passed; the Swift build and tests, several JavaScript test jobs, and PR Hygiene were still pending, with no failed checks reported.
🟡 1 0 suggestion(s)
Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.
Review provenance
Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 3: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 4: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 5: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)
- Triage:
normalbygpt-6.2-sol(effort low) — The typed grammar and binary codec are intricate, but the diff does not hook them into consensus, peer-facing decoding, or storage migrations. - Phase 1 reviewers:
muse-spark-1.3-contributor— general (completed, effort xhigh); agentphase1-reviewer,muse-spark-1.3-contributor— rust-quality (completed, effort xhigh); agentphase1-reviewer - Phase 1 model:
muse-spark-1.3-contributor— not quota-gated; passed overgemini-3.8-flash-high(antigravity quota lookup failed),glm-5.3-flash(not used above high effort; tier asks max) - Fresh verifier:
gpt-6.2-sol— final-verifier; agentsol-verifier - Phase 2 reviewers:
gpt-6.2-sol— general (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— architecture-layering (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— platform-versioning (completed, effort high); agentphase2-reviewer,gpt-6.2-sol— rust-quality (completed, effort high); agentphase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.
In `packages/rs-dpp/src/data_contract/document_type/definition/v0/layout.rs`:
- [SUGGESTION → DEFERRED by a maintainer; not blocking, do not fix in this PR] packages/rs-dpp/src/data_contract/document_type/definition/v0/layout.rs:454-461: Private and restricted aliases can hide wire type changes from the layout guard
Impact: After V0 ships, a maintainer changing the underlying type of a keyword pinned through a private or restricted alias could change which bytes it accepts or emits without the layout check flagging the change.
The new guard would let a keyword's wire type change while its pinned line stays the same. For example, `pub(crate) type Phase = u64;` in `index.rs` would not match the scanner's `pub type ` prefix. If `TimeRange::phase` were declared and pinned as `Phase`, `keywords!` would record that spelling with `stringify!`, so changing the alias to `u32` would leave both the generated layout and `PINNED` unchanged, even with the planned base-branch check. Recognize private and restricted module-level aliases as well as public ones. The existing aggregate variants already pin their concrete types, so this gap does not affect current V0 bytes.
|
Bots are done — your move: post |
Basic explanation
What this does: Today a document type exists in the protocol only as a JSON schema: a loose tree of text keys and values that a node has to parse before it knows anything about the type. This adds a typed form of the same declaration,
DocumentTypeDefinition, with one field per keyword (properties, indexes, references, rules and the type-level settings), a function that reads it from a schema, a function that writes the schema back, and a compact binary encoding. Nothing uses it yet: document types are still registered from their schemas.Value: It is the first step towards taking JSON schema out of the protocol in 5.2. Authors keep writing JSON schema and a client translates it; what a transition will carry, and what a delta contract update (#4730) needs for its new and changed document types, is this typed form. It is closed (a keyword the grammar does not have cannot be expressed), it compares exactly (no integer written as 32 or 64 bits depending on how the JSON was built), and it is smaller: the 1,503 document types registered on mainnet and testnet take 716,867 bytes as definitions against 1,578,463 bytes as schemas, 45%.
Risks: Low. No consensus code calls the new module and no version table selects it, so no block is validated differently. The risk is in the shape itself, which becomes a wire format once a protocol version carries it: a keyword left out or typed too narrowly would have to be fixed before then. The tests below hold it to every document type on both networks, and it was checked once against every schema the parser's own tests register.
Issue being fixed or feature implemented
5.1 made document validation and registration checks native and stores contracts compiled, but a contract create or update transition still carries its document types as JSON schemas, and a stored contract still keeps them. Removing JSON schema from the protocol needs a typed form to carry in their place. #4730 is parked on the same thing: its delta would otherwise fix a JSON-based wire format into consensus.
This PR adds that form and its translation to and from a schema. It adds no rule: deciding whether a definition describes a document type a network admits, and building the document type from it, come in later PRs, as do the contract format a transition carries and the migration of stored contracts.
What was done?
DocumentTypeDefinition(packages/rs-dpp/src/data_contract/document_type/definition/), which holds a document type as its author declares it and nothing a node derives:v0/mod.rsv0/property.rscontains: 37 keywordsv0/index.rsv0/reference.rsrefersTo,ownerRefersTo,creatorRefersTowith lookups,where, requirements and conditionsv0/rule.rspropertyConstraints,deleteConstraints,retractedWhenandimmutablev0/abilities.rsmoderatorAbilities,actionFees,tokenCost,immutable,private,canBeDeletedHow the grammar grows. A keyword added later is appended, not added in a new generation of the definition. It is an optional keyword at the end of its group, where it takes the next bit of the group's mask (every group writes a mask, a zero byte for one with no optional keyword, so each can take one later), and a name, a code or a variant goes at the end of its type, so bytes written before it existed decode as they did. A generation for each keyword would copy every type between the keyword and the document type (the grammar is 92 declarations that hold one another) and give the rules that will check a definition a second set of types. Three things follow, stated in the module documentation and the book:
definition/v0/layout.rspins all 408 positions, each with the types of what it holds, and fails when a declaration of the grammar is pinned by nothing. The test compares the declarations with the list of the same revision: a keyword that moves shows as changed or renumbered lines where an appended one is one added line, and the test alone does not stop a pull request that edits both. The list is not marked@append_onlyfor CI yet: the check has no override and would refuse the changes Typed document type definition: follow-ups from the review of #6422 #6427 still plans to make in place before protocol version 16 ships, so the marker is added as the last of them (noted on Typed document type definition: follow-ups from the review of #6422 #6427).V0variant stays for what appending can not do: a keyword whose value changes shape, a group past the 64 optional keywords its mask has bits for (the document type has 40, a property 37), another layout of the bytes.This departs from the book's rule for versioned types, an enum over per-version structs, and the coding conventions now say so.
Translation.
try_from_schemareads a document schema as a contract holds it (without$schemaand$defs). It holds the schema to the shape of the grammar only: every keyword it knows, each with a value of the kind the keyword takes.to_schemawrites the schema back, keyword for keyword. A schema is read only as a definition that writes it back: the reading ends by writing the definition and comparing, and refuses a difference with the path it sits at.No value is read by a derived reader that takes more than the grammar writes. Four macros declare the grammar, each giving a type its JSON form and its bytes from one declaration:
keywords!for an object of keywords (read from an object alone, anullrefused where the value takes none),names!andcodes!for a value that is one of a few names or integer codes (read from a string or an integer alone) andshapes!for a value that is one of several shapes (the shape written picks the variant, and a value is read as it is visited, never held whole first). The definition keeps the order of every map of names, a property'spositionand each keyword as given, defaults not filled in. The property type shorthands ("type": "identifier","type": "bytes"with asize) are the one thing rewritten: they are written out as the byte arrays they stand for.SchemaDefinitionsis the same form for a contract's$defs.A schema and what its definition holds:
{ "type": "object", "properties": { "label": { "type": "string", "minLength": 3, "maxLength": 63, "position": 0 } }, "indices": [{ "name": "byLabel", "properties": [{ "label": "asc" }], "unique": true }], "additionalProperties": false }What it reads, against what registration admits. The definition reads every document schema registration admits at the protocol version it is given, and writes it back, with these exceptions, each a schema registration admits and a definition does not hold:
$defsno property refers to, a keyword beside a$ref: the schema check takes a value of the right kind there ("format": "uuid","maxLength": 5.0), no document type compiles it, and the definition holds it to the grammar like the rest. Compiling to the same document type does not make a schema one registration admits: thepositionof an object's member is compiled by none and read by registration's check of member order, and the definition reads every position that check admits.contains, and the schema of a system property such as$createdAt.containsinside acontains, or a list inside a list among the literals of anenum,constorexamples, more than 128 levels deep.A protocol version before 15 also admitted what the document meta-schemas admitted and registration no longer does (a
containsoftrue); such a schema is read by the parser of its version, not as a definition.For the migration: a contract registered today can hold any of these. No document type registered on mainnet or testnet does, but the PR that migrates stored contracts to definitions has to choose what such a contract becomes, and must not make it an error while a block executes. #6426 tracks the depth part.
In the other direction the definition reads schemas registration refuses. It holds a keyword to the type of its value, a name or a code being one of those the keyword has (
transferable,actionFees.pricing, a contest'sresolutionand the rest, each a type of its values) and an id 32 bytes; how many, which together and what a name refers to are registration's rules. It refuses, where the schema parser may not: a key named twice in one object, a keyword the grammar does not have, anullwhere a value takes none, a list where a keyword takes an object, and a name written as an object of one key. A value that does not read is refused with the keywords that lead to it, asat `properties.label.maxLength`: invalid type: string "63", expected u64.It keeps as written what the parser reads two ways: an integer of the rule language or of a
wherewritten with a fraction of zero ({"lessThan": ["price", 3.0]}), which the rule language reads as the integer.Bytes. One macro,
keywords!, declares each group of keywords once and gives it both forms, so they cannot drift apart: as JSON, the object a schema writes, refusing a keyword the group does not have; as bytes, the keywords always present, then a mask saying which optional ones follow, then those. A keyword left out takes one bit, and a mask naming a keyword the group does not have is refused. A definition has one form as bytes: a map never names an entry twice, a contract's definitions are in the order of their names, an integer below zero is the only one written signed, and a number with a fraction is finite. Each is held to that wherever it is built, read or decoded. Decoding takes the bytes a definition encodes to and no others: the platform bincode configuration also reads a small integer from a longer form, which the definition's decoder (PlatformDeserializableUntrusted) refuses by encoding what it decoded and comparing. A format that holds a definition inside its own bytes decodes it through the plainbincodedecoders, and holds its own bytes to one form at its own boundary. Two numbers are equal when they are written the same, so0.0and-0.0differ to equality as they do in bytes. Everything that nests (properties, rules, expressions, references, conditions, literals) counts against one bound of 128 levels, which holds when a schema is read, written, encoded and decoded, so nothing encodes that does not decode, and reading and writing a schema hold it to the same depth, measured on its JSON (where bytes are a list, one level deeper than the value that holds them), so nothing is written that does not read back and nothing is read that does not write. The depth limits of a definition and of a schema still count different things; #6426 tracks defining one boundary for both before the migration. The deepest objects registration admits are 126 levels, and read, encode, decode and write within 1 MiB of stack in a release build and 4 MiB in a debug build; a node's workers have 8 MiB, which is the stack the depth tests run on.Book.
book/src/data-model/data-contracts.mdgains a section on the typed definition.Not included
The suggestions of the last review round, tracked in Typed document type definition: follow-ups from the review of #6422 #6427 for the pull requests that build on this one: three places where a definition reads a value registration refuses for a rule about values that go together, a size budget for a definition decoded on its own, and a cheaper decode of
$defs.A decision on what a stored contract outside the contract above becomes: see "For the migration".
The rules that decide whether a definition describes an admissible document type, and the build of a
DocumentTypefrom one. Until they exist a definition is only a translation of a schema.A contract format that carries definitions, a version table slot, and the migration of stored contracts.
Public interface changes
All additions, in
dpp::data_contract::document_type::definition:DocumentTypeDefinition(V0(DocumentTypeDefinitionV0)) andSchemaDefinitions(V0(SortedMap<Property>)), both withPlatformSerializableandPlatformDeserializableUntrusted.With the
json-conversionfeature:The grammar types under
definition::v0, with public fields. The types that hold a value to one form are built through a checked constructor:OrderedMap::try_from_entries,SortedMap::from(BTreeMap),Negative::new,Finite::new,Whole::new.Nothing existing changes: no signature, no stored or carried bytes, no version table.
How Has This Been Tested?
Targeted runs, not full suites:
cargo test -p dpp --lib definition::: 47 passed, new. Three of them pin the grammar's encoding order (v0/layout.rs): every keyword, name, code and variant at its position with the types it holds, every declaration of the grammar's files pinned, and no type pinned by an alias. A type listed for a derived variant that the variant does not hold does not compile (ByteAt(RulePath, u64):error[E0308]). With a keyword put in the middle ofTimeRange, the first fails withthe grammar declares the first where line 178 of PINNED has the second,TimeRange bit 0 "probe": boolagainstTimeRange bit 0 "phase": u64. Each keyword read into its typed field (anullamongenumvalues and aconstofnullkept as values); the schema written back equal to the one read, and a definition that does not write its schema back refused with the path of the difference; the order of every map of names kept; the byte round trip, under half the size of the schema; bytes left over, bytes cut short and bytes in a longer form than a definition is written in refused; unknown keywords, values of the wrong kind, a key named twice, a malformed rule, a fractional integer, anullkeyword, a list in place of an object, a name written as an object and a descending index property refused; acontainswithadditionalProperties: true, a member position past 32 bits and a whole number a rule writes as a float kept; the shorthands written out; a contract's$defs, refused when decoded out of order; the three macros, each with what its derived counterpart would have taken; one form for maps, integers and numbers, and zeros of either sign told apart; the nesting bound in all four directions, the deepest objects registration admits, a literal and acontainsnested past it, a schema too deep to read back refused when written, and a schema at the limit as a value and past it as JSON refused when read. The depth tests run on 8 MiB, a node's worker stack.cargo test -p dpp --test contract_corpus: 10 passed, 1 new. For each of the 1,503 document types of the 749 corpus contracts (55 mainnet, 694 testnet), and each contract's$defs: it reads as a definition; the schema written back equals the one read; a contract rebuilt from the written schemas parses to the same compiled document types as the original (DocumentTypeInSerializationFormat, which holds the properties in order, the indexes and the validation schema); the bytes read back as the definition; and the definitions together take under half the bytes of their schemas.cargo test -p dpp --lib native_schema::tests: 25 passed, 4 new, beside registration's own checks, where its generators are. A schema counts as registered when its document type parses and the contract's check of member order admits it.should_take_for_each_closed_keyword_the_values_the_schema_check_takestries each of 25 keywords that take one of a few names or codes with every name and code any of them takes: the definition takes the ones registration's schema check takes there and no other (with a third code given totransferable, it fails with/transferable: the definition takes 2, the check refuses it).should_read_as_a_typed_definition_every_change_registration_readssets each of about forty loosely read entries on every object of nine document types that use every keyword and of their$defs, writes every integer with a fraction of zero and replaces every value bynull: of the 1,093 changes registration admits, the definition reads and writes back every one registration read, and the rest are changes after which the document type compiles to what it did before.should_read_as_a_typed_definition_every_document_type_registration_admitsholds 5,715 generated changes to those types and to the corpus to the same.should_refuse_as_a_typed_definition_a_key_registration_passes_overpins the second exception. Mutation checks: with the reader refusing a whole float in a rule, the first fails and namespropertyConstraints.cheap.lessThanOrEqual.1.uniquewas stated backwards).written back is another document type).data_contractunit tests register under full validation at protocol version 15 and later (3,498 tests). 7,240 schemas read and wrote back equal with equal bytes; 11 did not read, all in the refused groups above (2 with a repeatedpropertieskey, 7 with a fractional integer in a structural keyword, 2 with a non-textdescriptionin a system property's schema).cargo clippy -p dpp --all-features --all-targets --locked -- --no-deps -D warnings,cargo check -p dpp --libwith default features and with none, andcargo fmt --all: clean.Not run: the full
dppsuite and the other crates, which the change does not touch.Breaking Changes
None. The module is new and nothing calls it.
Checklist:
structure.rs, regeneratedgrovedb-structure.json, and checked the structure viewer link posted on this pull requestFor repository code-owners and collaborators only
🤖 Generated with Claude Code
PR Hygiene ·
a51c957/self-reviewedWhen every merge requirement is met, the
PR Hygienecheck passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.Summary by CodeRabbit