Registry Mirror
Skip to content

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Basic explanation

What this does: From protocol version 15 a document type can keep its sums in 128 bits, so a sum can be larger than a 64-bit integer holds. This pull request carries such a sum whole from the proof to the screen: the Rust proof verifiers, the Rust SDK, the iOS FFI, the Swift SDK and the SwiftExampleApp Sum / Average Documents view. The average is now computed exactly in Rust; the app shows it and no longer divides.

Value: Before, asking for a sum past 64 bits gave an error ("the proved sum does not fit the 64 bits a sum result carries"). Now it gives the number, and its exact average.

Risks: Low. No consensus code changes: the proof verifiers run on clients, and the node's unproven query path still answers in 64 bits as before. The FFI result shape changes (sums become decimal strings), which callers of dash_sdk_document_sum / dash_sdk_document_average must follow; both in-repo callers (Swift, Kotlin) are covered below.

Issue being fixed or feature implemented

#5987 keeps document sums in 128-bit trees from protocol version 15 when the summed property is not declared within ±2^27, and left "a sum past 64 bits cannot be returned" as out of scope. A search of open pull requests and issues found no other work on returning wide sums.

Before (unchanged base, drive test should_refuse_a_proved_sum_past_64_bits_as_too_wide, passing on the base commit): Drive's verifier refused a proved sum past 64 bits with ProofError::SumPastResultWidth, drive-proof-verifier turned it into Error::UnusableVerifiedResult, and dash_sdk_document_sum returned that error to the app. Not a wrong number, but no number.

Two listings at the largest i64 price, summed and averaged in the app:

Before:  Sum      error: the proved sum does not fit the 64 bits a sum result carries
         Average  error: the proved sum does not fit the 64 bits a sum result carries
After:   Sum      18446744073709551614
         Average  9223372036854775807.0000

What was done?

Drive (client-side verify only)

  • The sum and average proof verifiers (DriveDocumentSumQuery::verify_*_sum_proof, verify_*_count_and_sum_proof, primary-key and carrier forms) return the proved sum as i128, read with Element::big_sum_value_or_default / count_big_sum_value_or_default, and no longer refuse a sum past 64 bits.
  • SumEntry::sum and AverageEntry::sum are Option<i128>.
  • The unproven (no-proof) path is unchanged in behaviour: it still reads sums at 64 bits (sum_width::element_sum) and the drive-abci handler writes them into the 64-bit sint64 wire field (new wire_sum, which refuses rather than truncates a value that would not fit; none reaches it).
  • counter_sum_as_document_count takes the counter sum at either width (impl Into<i128>); same count for the same value.
  • sum_width::proved_element_sum / proved_element_count_and_sum are removed; proved_sum_in_64_bits stays for the ranked and HAVING verifiers, whose entries still carry 64 bits.

drive-proof-verifier, dash-platform-queries, rs-sdk

  • DocumentSum(i128), DocumentAverage { count: u64, sum: i128 }, SplitSumEntry::sum / SplitAverageEntry::sum: Option<i128>; folds use i128::checked_add.
  • New average_to_decimal_string(count, sum, fraction_digits): integer long division, rounded half away from zero, exact for every i128 sum. Also DocumentAverage::to_decimal_string and SplitAverageEntry::to_decimal_string.
  • The sum and average verifier wrappers map Drive errors with map_drive_error; MapProvedSumError stays for ranked and HAVING.
  • rs-sdk mock encodings use i128.

rs-sdk-ffi

  • dash_sdk_document_sum: each sum is a base-10 string.
  • dash_sdk_document_average: sum is a base-10 string and each entry carries average, computed in Rust to 4 places (what both example apps showed), null when count is 0.

Swift SDK and SwiftExampleApp

  • DocumentSumResult.sums: [String: Int128], DocumentAverageEntry { count: UInt64, sum: Int128, average: String? }. Parsing moved into init(json:); a value that is not a decimal string throws SDKError.serializationError instead of being dropped or narrowed.
  • SumAverageDocumentsView shows the Int128 sum and the Rust average string; the Double division is gone.
  • TEST_PLAN: DOC-13 and DOC-14 describe the new result shapes; new row DOC-18 (sum and average past 64 bits, protocol version 15, not yet driven on a device).

Kotlin (not changed)

The JNI passes the FFI JSON through. KotlinExampleApp reads sums as string content, so wide sums display whole. Its average parser reads sum with toLongOrNull() and divides in Double: a normal-sized sum (now a string) still parses, but an average entry with a sum past 64 bits is dropped (an ungrouped wide average shows no result section). It ignores the new average field. Worth a follow-up to display the Rust average there too.

Public interface changes

rs-sdk-ffi JSON (wire format of two C functions, signatures unchanged):

dash_sdk_document_sum
  before: {"sums":{"":42,"61":-5}}
  after:  {"sums":{"":"42","61":"-5"}}                 wide: {"sums":{"":"27670116110564327421"}}

dash_sdk_document_average
  before: {"averages":{"61":{"count":3,"sum":30}}}
  after:  {"averages":{"61":{"count":3,"sum":"30","average":"10.0000"}}}
  absent: {"averages":{"":{"count":0,"sum":"0","average":null}}}

Callers must read sums values and sum as decimal strings into a 128-bit integer (or display them as text), and should display average rather than divide. count stays a JSON number.

SwiftDashSDK:

// before
public struct DocumentSumResult { public let sums: [String: Int64]; public var total: Int64? }
public struct DocumentAverageEntry {
    public let count: UInt64; public let sum: Int64
    public init(count: UInt64, sum: Int64)
    public var average: Double?          // computed sum / count
}
// after
public struct DocumentSumResult { public let sums: [String: Int128]; public var total: Int128? }
public struct DocumentAverageEntry {
    public let count: UInt64; public let sum: Int128
    public let average: String?          // computed in Rust, 4 places
    public init(count: UInt64, sum: Int128, average: String?)
}

Callers using Int64 sums or the Double average no longer compile; use Int128 and the average string. A malformed payload now throws instead of being skipped.

drive-proof-verifier:

// before                                        // after
pub struct DocumentSum(pub i64);                 pub struct DocumentSum(pub i128);
pub struct DocumentAverage { count: u64, sum: i64 }   { count: u64, sum: i128 }
SplitSumEntry::sum: Option<i64>                  Option<i128>
SplitAverageEntry::sum: Option<i64>              Option<i128>
DocumentSplitSums::try_into_flat_map() -> BTreeMap<Vec<u8>, i64>        -> BTreeMap<Vec<u8>, i128>
DocumentSplitAverages::try_into_flat_map() -> BTreeMap<Vec<u8>, (u64, i64)> -> (u64, i128)
verify_aggregate_sum_proof / verify_primary_key_sum_tree_proof -> Result<i64, _>   -> Result<i128, _>
verify_aggregate_count_and_sum_proof / verify_primary_key_count_sum_tree_proof
    -> Result<(u64, i64), _>                     -> Result<(u64, i128), _>
// new
pub fn average_to_decimal_string(count: u64, sum: i128, fraction_digits: u32) -> Option<String>;
DocumentAverage::to_decimal_string(&self, fraction_digits: u32) -> Option<String>;
SplitAverageEntry::to_decimal_string(&self, fraction_digits: u32) -> Option<String>;

Rust callers storing these sums in i64 must widen to i128 (or i64::try_from). A sum that used to be refused as too wide is now returned.

drive: SumEntry::sum and AverageEntry::sum are Option<i128>; the DriveDocumentSumQuery sum and average verifiers return i128 sums ((RootHash, i128), (RootHash, u64, i128), Vec<(Vec<u8>, i128)>, Vec<(Vec<u8>, u64, i128)>); counter_sum_as_document_count(sum: impl Into<i128>).

wasm-sdk: sum and average maps are still JS bigint; a value past 64 bits now arrives instead of an error.

Unchanged: the gRPC getDocuments messages (sint64 sums), the no-proof server answers, stored bytes, root hashes, proofs and version tables.

In-place changes to shipped generations

All are client-side proof verifiers in packages/rs-drive/src/verify/document_sum/; no block execution or validation path calls them.

Generation Selected by Why consensus cannot change
verify_aggregate_sum_proof, verify_aggregate_count_and_sum_proof, verify_carrier_aggregate_sum_proof, verify_carrier_aggregate_count_and_sum_proof: v0 and v1 v0 through DRIVE_VERIFY_METHOD_VERSIONS_V1/V2, v1 from V3 on (shipped protocol versions included) Client-side proof verification; no block execution or validation path calls them. Each returned the sum as i64 and refused one past 64 bits; it now returns i128. A 64-bit tree's sum is the same number widened, and a 128-bit tree exists only from protocol version 15, so every result returned before is returned unchanged.
verify_distinct_sum_proof, verify_distinct_count_and_sum_proof, verify_point_lookup_sum_proof, verify_point_lookup_count_and_sum_proof, verify_primary_key_sum_tree_proof, verify_primary_key_count_sum_tree_proof: v0 every protocol version with document sums as above

A comment at each edited line says the same.

counter_sum_as_document_count (unversioned, reachable from count reads) only widens its parameter: the count is u64::try_from of the same value, so it is identical for every input it received before. The drive and drive-abci no-proof executors and handlers only widen and narrow back values they read at 64 bits, so their answers are unchanged.

How Has This Been Tested?

Targeted runs only:

  • cargo test -p drive --lib -- query:: verify:: add_history_operations summable_off_count preallocated_index array_index typed_array_counter document::update: 1193 passed. New: should_prove_and_verify_a_sum_past_64_bits (range sum and count-and-sum over the document history contract's priceUpdate.price, three listings at i64::MAX) and should_prove_and_verify_a_primary_tree_total_past_64_bits (purchase primary tree). They replace should_refuse_a_proved_sum_past_64_bits_as_too_wide, which passed on the base commit and shows the old refusal. PV14 twins are unchanged.
  • cargo test -p drive-proof-verifier: 448 passed plus the doctest; new average_to_decimal_string tests (rounding, sign, zero count, 128-bit extremes, a wide sum averaged exactly) and split-view folds past 64 bits.
  • cargo test -p dash-platform-queries --lib: 107 passed (folds past 64 bits, i128 overflow guards).
  • cargo test -p dash-sdk --lib: 945 passed.
  • RUST_MIN_STACK=16777216 cargo test -p drive-abci --lib -- query::document_query: 161 passed.
  • cargo test -p rs-sdk-ffi --lib -- document::queries: 34 passed (wide sum, wide average "9223372036854775807.0000", negative sum, null average).
  • cargo check -p rs-unified-sdk-jni, cargo check -p drive --no-default-features --features verify, cargo check -p wasm-drive-verify --target wasm32-unknown-unknown, cargo check -p wasm-sdk (host target; the wasm32 build needs a C toolchain for rs-x11-hash not set up locally).
  • cargo clippy -p drive -p drive-proof-verifier -p dash-platform-queries -p dash-sdk -p drive-abci -p rs-sdk-ffi --all-targets --all-features --locked -- --no-deps -D warnings: clean. cargo fmt --all.
  • Swift: new DocumentAggregateResultParsingTests (6 passed: wide sums, signed grouped sums, wide averages, null average, malformed payloads). SwiftDashSDK and SwiftExampleApp compiled against a borrowed xcframework (no C signature changes here); its static library predates feat(swift-example-app): update a data contract from its detail screen, with a Rust preview of the changes #6053, so linking needed -Xlinker -U for two feat(swift-example-app): update a data contract from its detail screen, with a Rust preview of the changes #6053 symbols unrelated to this change. Not driven on a simulator or a live protocol version 15 network (DOC-18 is 🧪).

Breaking Changes

No consensus change. Client interface changes are listed under "Public interface changes".

Checklist:

  • I have performed a self-review of my own code
  • My Rust, FFI, WASM, Swift or Kotlin changes follow the coding conventions
  • 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
  • If I added or changed a system contract's document schemas, I checked the contract 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 · a33a7cf

  • Bots — thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed
  • Reviewer requests paused — your 5 review slots are occupied; this PR is excluded from reviewers' queues. Required approvals still count without a slot.
  • Build running
  • Approvals
    • github (.github/workflows/release-swift-sdk.yml) — ktechmidas or shumkov
    • files with no dedicated owner — you own it
    • kotlin-sdk (packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md, packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/CountDocumentsScreen.kt, packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/SumAverageDocumentsScreen.kt and 1 more) — HashEngineering
    • rs-drive-abci — you own it
    • rs-drive — you own it
    • rust-sdk-ffi (packages/rs-sdk-ffi/src/document/queries/average.rs, packages/rs-sdk-ffi/src/document/queries/sum.rs) — lklimek or shumkov
    • rust-sdk (packages/rs-sdk/src/mock/requests.rs) — lklimek or shumkov
    • swift-sdk (packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift, packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SumAverageDocumentsView.swift, packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md and 1 more) — llbartekll or romchornyi
    • js-wasm-sdk (packages/wasm-sdk/src/queries/document.rs) — shumkov

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

From protocol version 15 a document type can keep its sums in 128-bit
trees. A proved sum past 64 bits was refused as too wide by Drive's sum
and average proof verifiers, so the SDK, the FFI and the iOS Sum /
Average view showed an error for it.

- drive: the sum and average proof verifiers return the proved sum at
  128 bits; `SumEntry::sum` and `AverageEntry::sum` are `i128`. The
  unproven path still answers in the 64 bits its response carries.
- drive-proof-verifier: `DocumentSum`, `DocumentAverage` and the split
  views carry `i128`; new `average_to_decimal_string` computes an exact
  average on integers.
- dash-platform-queries, rs-sdk mocks: fold and encode at 128 bits.
- rs-sdk-ffi: sums are decimal strings, and each average entry carries
  the Rust-computed average.
- SwiftDashSDK and SwiftExampleApp: `Int128` sums, the Rust average
  shown as is; TEST_PLAN DOC-13/14 updated, DOC-18 added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added this to the v5.1.0 milestone Nov 22, 2026
@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 5d14854 and a33a7cf.

Files selected for processing: 70

  • .github/workflows/release-swift-sdk.yml
  • book/src/drive/document-sum-trees.md
  • book/src/sdk/protocol-version-15-upgrade.md
  • packages/dash-platform-queries/src/documents/average_proof_helpers.rs
  • packages/dash-platform-queries/src/documents/document_average.rs
  • packages/dash-platform-queries/src/documents/document_sum.rs
  • packages/dash-platform-queries/src/documents/sum_proof_helpers.rs
  • packages/kotlin-sdk/KotlinExampleApp/TEST_PLAN.md
  • packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/CountDocumentsScreen.kt
  • packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/SumAverageDocumentsScreen.kt
  • packages/kotlin-sdk/KotlinExampleApp/app/src/test/java/org/dashfoundation/example/ui/contracts/AverageResultParsingTest.kt
  • packages/rs-drive-abci/src/query/document_query/v1/dispatch/average.rs
  • packages/rs-drive-abci/src/query/document_query/v1/dispatch/sum.rs
  • packages/rs-drive-abci/tests/document_sum_signed_wide.rs
  • packages/rs-drive-proof-verifier/src/lib.rs
  • packages/rs-drive-proof-verifier/src/proof/document_average.rs
  • packages/rs-drive-proof-verifier/src/proof/document_split_average.rs
  • packages/rs-drive-proof-verifier/src/proof/document_split_sum.rs
  • packages/rs-drive-proof-verifier/src/proof/document_sum.rs
  • packages/rs-drive-proof-verifier/src/verify.rs
  • packages/rs-drive/benches/document_sum_worst_case.rs
  • packages/rs-drive/src/drive/contract/insert/insert_contract/v0/tests/preallocated_index_e2e_tests.rs
  • packages/rs-drive/src/drive/contract/insert/insert_contract/v0/tests/summable_off_count_index_e2e_tests.rs
  • packages/rs-drive/src/drive/contract/insert/insert_contract/v0/tests/typed_array_counter_index_e2e_tests.rs
  • packages/rs-drive/src/drive/document/insert/add_document_for_contract/array_index_e2e_tests.rs
  • packages/rs-drive/src/drive/document/insert/add_history_operations/mod.rs
  • packages/rs-drive/src/drive/document/update/mod.rs
  • packages/rs-drive/src/query/drive_document_average_query/drive_dispatcher.rs
  • packages/rs-drive/src/query/drive_document_average_query/mod.rs
  • packages/rs-drive/src/query/drive_document_count_and_sum_query/drive_dispatcher.rs
  • packages/rs-drive/src/query/drive_document_count_and_sum_query/executors/per_in_value.rs
  • packages/rs-drive/src/query/drive_document_count_and_sum_query/executors/range_no_proof.rs
  • packages/rs-drive/src/query/drive_document_count_query/mod.rs
  • packages/rs-drive/src/query/drive_document_sum_query/drive_dispatcher.rs
  • packages/rs-drive/src/query/drive_document_sum_query/execute_point_lookup.rs
  • packages/rs-drive/src/query/drive_document_sum_query/execute_range_sum.rs
  • packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs
  • packages/rs-drive/src/query/drive_document_sum_query/executors/total.rs
  • packages/rs-drive/src/query/drive_document_sum_query/mod.rs
  • packages/rs-drive/src/query/sum_width.rs
  • packages/rs-drive/src/verify/document_sum/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_aggregate_count_and_sum_proof/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_aggregate_count_and_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_aggregate_count_and_sum_proof/v1/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_aggregate_sum_proof/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_aggregate_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_aggregate_sum_proof/v1/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_carrier_aggregate_count_and_sum_proof/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_carrier_aggregate_count_and_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_carrier_aggregate_count_and_sum_proof/v1/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_carrier_aggregate_sum_proof/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_carrier_aggregate_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_carrier_aggregate_sum_proof/v1/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_distinct_count_and_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_distinct_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_point_lookup_count_and_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_point_lookup_sum_proof/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_point_lookup_sum_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_primary_key_count_sum_tree_proof/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_primary_key_count_sum_tree_proof/v0/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_primary_key_sum_tree_proof/mod.rs
  • packages/rs-drive/src/verify/document_sum/verify_primary_key_sum_tree_proof/v0/mod.rs
  • packages/rs-sdk-ffi/src/document/queries/average.rs
  • packages/rs-sdk-ffi/src/document/queries/sum.rs
  • packages/rs-sdk/src/mock/requests.rs
  • packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift
  • packages/swift-sdk/SwiftExampleApp/SwiftExampleApp/Views/SumAverageDocumentsView.swift
  • packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md
  • packages/swift-sdk/SwiftTests/SwiftDashSDKTests/DocumentAggregateResultParsingTests.swift
  • packages/wasm-sdk/src/queries/document.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

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

thepastaclaw commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

🔍 Review in progress (commit a33a7cf) · live progress

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

Changes requested: 2 blockers

  • Android silently drops verified averages whose sums exceed 64 bits — packages/rs-sdk-ffi/src/document/queries/average.rs:64-68 (new)
    Impact: On a protocol 15 network, an Android example-app user running Average on a supported summable index sees no result for a wide total or an incomplete list for a grouped query, without an error.
  • Updating the native framework alone makes released decoders drop ordinary sums and averages — packages/rs-sdk-ffi/src/document/queries/sum.rs:103-104 (new)
    Impact: Apps that update the separately distributed DashSDKFFI binary while retaining a released numeric decoder can receive empty aggregate results even on protocol 14.

This PR preserves signed 128-bit document sums from proof verification through the SDK, formats averages in Rust, and displays the exact decimal result in Swift without changing consensus or the unproven gRPC response. Rust workspace, wasm32, and Kotlin checks passed; the Swift build failed with the same type-check timeout at SendTransactionView.swift:80 as the base-side build, so it did not validate the Swift changes. PR Hygiene is pending; this was a static review.

🔴 2 blocking | 🟡 4 suggestion(s) | 💬 1 nitpick(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

💬 Nitpick: The per-In-value executor documents the old map and entry types
Impact: Maintainers reading the executor's documentation see i64 storage where the code now uses i128, obscuring the distinction between storage width and the no-proof result limit.
packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25

The comment no longer describes the executor's types. The merged map is BTreeMap<Vec<u8>, i128> and SumEntry::sum is Option<i128>, even though the underlying no-proof reads still enforce a 64-bit range. Document both facts.

    /// Cartesian-forks the single `In` clause into one Equal-per-value
    /// sub-query against a `summable: "<sum_property>"` index; collects
    /// the per-branch sums in a `BTreeMap<serialized_value, i128>`
    /// (deduplicated by key bytes) and emits per-In-value `SumEntry` values
    /// with `in_key: None`, `key: serialized_value`, and `sum: Some(i128)`.
    /// The underlying no-proof reads still enforce the signed 64-bit range.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality)

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: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); reviewer 9: gpt-6.2-sol (agent: phase2-reviewer, role: general); reviewer 10: gpt-6.2-sol (agent: phase2-reviewer, role: architecture-layering); reviewer 11: gpt-6.2-sol (agent: phase2-reviewer, role: ffi-engineer); reviewer 12: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 13: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 14: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The change spans Drive proof verification, SDKs, and mobile bindings, but it widens client-side aggregate results without changing consensus rules, cryptography, or the unproven query wire format.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-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; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-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-sdk-ffi/src/document/queries/average.rs`:
- [BLOCKING] packages/rs-sdk-ffi/src/document/queries/average.rs:64-68: Android silently drops verified averages whose sums exceed 64 bits
  Impact: On a protocol 15 network, an Android example-app user running Average on a supported summable index sees no result for a wide total or an incomplete list for a grouped query, without an error.
  A successful query can now look empty or complete with rows missing. The merge-base verifier surfaced a width error through JNI; this serializer now returns the full sum and the Rust-computed average, and JNI forwards both unchanged. The Kotlin screen still calls `sum.toLongOrNull()` and uses `mapNotNull` over the entries, so a verified sum of `18446744073709551614` is dropped even though the response includes `9223372036854775807.0000` as its average. Migrate the Android decoder and renderer with the payload: keep the sum as decimal text, display Rust's nullable average instead of dividing in `Double`, and report invalid rows rather than omitting them. Test an ungrouped wide total and a grouped response with one narrow and one wide row.
- [SUGGESTION] packages/rs-sdk-ffi/src/document/queries/average.rs:327-336: The wide-result tests miss the handoff from a signed document response to the native APIs
  Impact: A width or routing regression in the SDK fetch or FFI grouped-result path could reach mobile callers while the new tests still pass.
  The new tests can pass even if a wide group never reaches the native caller. Drive's new tests generate real scalar range and primary-tree proofs but call Drive's verifiers directly; the existing signed SDK cases use narrow values. The new FFI tests start with hand-built result maps, and the Swift tests start with literal JSON, so neither exercises the SDK fetch, grouped flattening, or key mapping. Add a protocol 15 case to the existing signed `GetDocuments` harness that checks the full SUM and AVG values at the SDK entry point. Reuse that proof or an offline fixture at the native boundary to check the exported calls with a wide group, including its key, exact sum, count, and formatted average.

In `packages/rs-sdk-ffi/src/document/queries/sum.rs`:
- [BLOCKING] packages/rs-sdk-ffi/src/document/queries/sum.rs:103-104: Updating the native framework alone makes released decoders drop ordinary sums and averages
  Impact: Apps that update the separately distributed DashSDKFFI binary while retaining a released numeric decoder can receive empty aggregate results even on protocol 14.
  An app can turn a valid total of 42 into an empty result after updating the native binary. The XCFramework is published as a standalone binary target, and the existing `dash_sdk_document_sum` and `dash_sdk_document_average` symbols still link, but both now emit quoted sums for every value, not just wide ones. The v5.0.2 Swift decoders accept only `NSNumber` and silently skip those entries; the new Swift decoders reject the old average shape and numeric sums. Keep the existing entry points on their numeric schema with checked width errors, and give bindings an explicit opt-in or new symbols for the decimal schema. This is a native API compatibility decision, not a PlatformVersion gate.
- [SUGGESTION] packages/rs-sdk-ffi/src/document/queries/sum.rs:109-114: The native guide still shows numeric sums, and the 5.1 upgrade guide omits the aggregate API changes
  Impact: Native clients following the book can configure a decoder that rejects even small sums, and Rust and Swift clients that upgrade before activation have no published migration guidance for the changed result types.
  Callers following the book can build against the wrong result shape. The native example at `book/src/drive/document-sum-trees.md:423–438` shows numeric `i64` values and an outdated distinct-range argument where the function now takes `group_by_json`. The 5.1 upgrade guide tells apps to upgrade before protocol 15 activates but does not explain that Rust sums widen to `i128` and Swift widens to `Int128` and replaces its numeric average with a nullable string. Update the examples to match the final native API, including the nullable average and the distinction from the unchanged `sint64` no-proof response. Document any remaining source changes and required wrapper/binary pairing in the upgrade guide.

In `packages/rs-drive-proof-verifier/src/proof/document_average.rs`:
- [SUGGESTION] packages/rs-drive-proof-verifier/src/proof/document_average.rs:158-170: Oversized precision can panic or exhaust memory in the public average formatter
  Impact: Rust callers that pass an oversized precision can hit a capacity-overflow panic on wasm32 or require gigabytes of memory and billions of division steps on 64-bit targets.
  The formatter can fail the process instead of rejecting an unsupported precision. With a nonzero count, the public function uses the full `u32` directly as a `Vec<u8>` capacity and performs one long-division step per digit before building a second buffer. On wasm32, a capacity above `isize::MAX` panics before formatting begins. The mobile FFI always passes four, so no current product path supplies an oversized value. Use a bounded precision type or validate a documented limit before allocating; keep an invalid precision distinct from `None`, which means there is no average.

In `packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md`:
- [SUGGESTION] packages/swift-sdk/SwiftExampleApp/TEST_PLAN.md:240: The wide-sum device test can return zero after two successful listings
  Impact: A tester using a sellable document type without pricing history can complete both price updates without exercising a wide sum.
  DOC-18 can produce zero matching history rows even when both listings succeed. Drive's price-update action writes a `priceUpdate` event only when the source type enables `keepsPricingHistory`, which defaults to false. The query also reads the whole history for that contract after timestamp zero, so earlier listings can change the expected result. Specify a fresh seller-priced source contract with `keepsPricingHistory: true` so the two listings are the only matching records.

In `packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs`:
- [NITPICK] packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25: The per-In-value executor documents the old map and entry types
  Impact: Maintainers reading the executor's documentation see `i64` storage where the code now uses `i128`, obscuring the distinction between storage width and the no-proof result limit.
  The comment no longer describes the executor's types. The merged map is `BTreeMap<Vec<u8>, i128>` and `SumEntry::sum` is `Option<i128>`, even though the underlying no-proof reads still enforce a 64-bit range. Document both facts.
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.

  • Swift CI times out while type-checking the send screen — The PR job and the base-side #6051 comparison job both report that the compiler is unable to type-check the expression at SendTransactionView.swift:80 in reasonable time. This PR does not touch that screen, and the failure prevents the Swift job from validating the aggregate changes.
    • Follow-up: Fix the send-screen type-check timeout in a separate PR and rerun Swift CI.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 22, 2026
… signed wide sums

- KotlinExampleApp: keep the sum as the FFI's decimal string, show the
  average Rust computed, and report an entry it cannot read instead of
  dropping it; unit-tested with an ungrouped wide total and a grouped
  narrow and wide response.
- drive-proof-verifier: the average formatter takes its precision as a
  u8, so its work and output are bounded.
- drive-abci test: a quorum-signed protocol 15 getDocuments answer
  verifies through the SDK's FromProof impls with the whole SUM and AVG,
  ungrouped and grouped by contract; protocol 14 still verifies.
- Book: the native sum/average example shows the decimal schema and the
  5.1 upgrade guide lists the widened sum and average types.
- TEST_PLAN DOC-18 uses a fresh contract with keepsPricingHistory, and
  the Swift release summary says to pair the xcframework with the Swift
  sources of the same tag.

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

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 22, 2026
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

📖 Book Preview built successfully.

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

Updated at 2026-11-23T01:22:56.038Z

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

Changes requested: 1 blocker

  • A wide average grouped by source contract appears as one total on Android — packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/SumAverageDocumentsScreen.kt:304-315 (new)
    Impact: On protocol 15, a user comparing listing prices by source contract can get one combined average and no per-contract rows when one contract's sum exceeds 64 bits.

New on this head: This revision makes Android display Rust-formatted averages without narrowing wide sums, bounds formatter precision, adds signed proof tests for protocol 15 with a protocol 14 control, and updates the migration and device-test guides. The Rust workspace and wasm32 checks, JS build, and book preview passed; Swift, Kotlin, and two platform test-suite jobs were pending when checked. The Dashmate local-network test timed out waiting for Core nodes to reach the same block height, before exercising any aggregate query.

🔴 1 blocking | 🟡 3 suggestion(s) | 💬 1 nitpick(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

💬 Nitpick: The per-In-value executor documents the old map and entry types
Impact: Maintainers reading the executor's documentation see i64 where both the accumulator and returned entry carry i128.
packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25

The comment still names i64 for the intermediate map and emitted sum. The map at line 64 is BTreeMap<Vec<u8>, i128>, and SumEntry::sum is Option<i128>. Document those Rust types without implying that the no-proof read or its gRPC result widened.

    /// Cartesian-forks the single `In` clause into one Equal-per-value
    /// sub-query against a `summable: "<sum_property>"` index; deduplicates
    /// the per-branch sums by serialized value in a `BTreeMap<Vec<u8>, i128>`.
    /// Emits one `SumEntry` per distinct value with `in_key: None` and
    /// `key: serialized_value`. Each no-proof sum is read at 64 bits and
    /// carried as `Some(i128)`.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-sol (phase2-reviewer: general, architecture-layering, platform-versioning)

Still open from earlier rounds (2)

  • 🟡 Suggestion: Updating the native framework alone makes released decoders drop ordinary sums and averages — packages/rs-sdk-ffi/src/document/queries/sum.rs:101-104 (thread)
  • 🟡 Suggestion: The wide-result tests miss the handoff from a signed document response to the native APIs — packages/rs-sdk-ffi/src/document/queries/average.rs:327-336 (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: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The diff is cross-cutting, but it widens authenticated query results and changes how clients render them without changing cryptographic verification, consensus rules, or the unproven wire format.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • New since the last final review (5649c852): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-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/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/SumAverageDocumentsScreen.kt`:
- [BLOCKING] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/SumAverageDocumentsScreen.kt:304-315: A wide average grouped by source contract appears as one total on Android
  Impact: On protocol 15, a user comparing listing prices by source contract can get one combined average and no per-contract rows when one contract's sum exceeds 64 bits.
  The screen shows a successful total instead of the requested breakdown. In Sum / Average Documents, select Average on the document-history contract's `priceUpdate` type and `price` property, use `in` on `dataContractId` to select two contracts that record listing history, add a `$createdAt` range, and group by `dataContractId`. When one contract's listings add up past `i64::MAX`, the signed fixture at `document_sum_signed_wide.rs:306–336` shows what verification returns: two entries with distinct contract IDs in `in_key` and empty `key` values. The grouped native AVG branch calls `try_into_flat_map()`, which folds by `entry.key` alone, combines both counts and sums, and hex-encodes the shared empty key as `""`. JNI returns that JSON unchanged. The decoder added in this revision accepts the wide sum that the preceding Android decoder dropped, then renders it as Total with no group rows. Native SUM uses the same projection. Use the Rust query/result layer's carrier plan to preserve the verified `in_key` as the output group key when the request groups by the `in` field, while retaining the intentional merge for grouping by the range field alone.

  _Confirmed by an independent pass: On a protocol 15 network, an Android user can request Average on the document-history contract’s `priceUpdate.price`, filter two source contracts with `dataContractId in [...]` and a `$createdAt` range, and group by `dataContractId`. If both contracts have matching price updates and one contract’s recorded asking prices sum past `i64::MAX`, the screen silently displays one combined average as Total instead of the two requested contract averages._
- [SUGGESTION] packages/kotlin-sdk/KotlinExampleApp/app/src/main/java/org/dashfoundation/example/ui/contracts/SumAverageDocumentsScreen.kt:326-331: Android displays a missing average field as if no documents matched
  Impact: If a native response omits `average` from an otherwise readable row, Android shows a dash even for a positive count instead of reporting the malformed response.
  The new parser accepts a missing field as a legitimate absent average. Rust always emits `average` and uses explicit JSON `null` when the count is zero; Swift rejects an omitted field. Kotlin's `null, JsonNull` branch accepts both, so the malformed row reaches `displayAverage()` instead of the screen's error handler. Reject a missing field and add that case to `AverageResultParsingTest` alongside the valid explicit-null case.

In `packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs`:
- [NITPICK] packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25: The per-In-value executor documents the old map and entry types
  Impact: Maintainers reading the executor's documentation see `i64` where both the accumulator and returned entry carry `i128`.
  The comment still names `i64` for the intermediate map and emitted sum. The map at line 64 is `BTreeMap<Vec<u8>, i128>`, and `SumEntry::sum` is `Option<i128>`. Document those Rust types without implying that the no-proof read or its gRPC result widened.

In `packages/rs-sdk-ffi/src/document/queries/sum.rs`:
- [SUGGESTION] packages/rs-sdk-ffi/src/document/queries/sum.rs:101-104: Updating the native framework alone makes released decoders drop ordinary sums and averages
  (carried; thread: https://github.com/dashpay/platform/pull/6095#discussion_r4660204306)

In `packages/rs-sdk-ffi/src/document/queries/average.rs`:
- [SUGGESTION] packages/rs-sdk-ffi/src/document/queries/average.rs:327-336: The wide-result tests miss the handoff from a signed document response to the native APIs
  (carried; thread: https://github.com/dashpay/platform/pull/6095#discussion_r4660204311)

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 22, 2026
A sum or average grouped by its `in` field, with a range on another
field, verifies to one carrier total per `In` value: the value is in
`in_key` and the terminator `key` is empty. `try_into_flat_map` keyed
entries by `key` alone, so the native FFI and wasm-sdk merged every
group under the empty key and showed one combined total. Such entries
are now keyed by their `in_key`, the key a point lookup grouped by the
`In` field gives too.

- Tests: flat maps of carrier totals in drive-proof-verifier, the
  signed protocol 15 answers in drive-abci, and new offline tests that
  call `dash_sdk_document_sum` / `dash_sdk_document_average` on a mock
  SDK, ungrouped and grouped, with a sum past 64 bits.
- KotlinExampleApp refuses an average entry without `average`; Rust
  always writes it, as null when nothing matched.

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

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 22, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

Changes requested: 1 blocker

  • Grouped sums and averages can merge documents with a missing range value into a named group — packages/rs-drive-proof-verifier/src/proof/document_split_sum.rs:43-47 (new)
    Impact: Native and JavaScript callers grouping by an optional range field across multiple In values can receive a successful result with the wrong sum and count for a named group.
    Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: This revision preserves one SUM or AVG row per In value for carrier queries, adds offline tests through both native exports, and makes Android reject an omitted average field. Rust workspace, wasm32, Kotlin, and Evo SDK checks passed; one browser test shard was still pending at the time of review. The Swift SDK job failed on a type-check timeout in the unchanged SendTransactionView.swift, and Dashmate local-network E2E hit the same Core block-sync timeout as the previous head; neither log points to the aggregate changes.

🔴 1 blocking | 💬 1 nitpick(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

💬 Nitpick: The per-In-value executor documents the old map and entry types
Impact: Maintainers tracing the no-proof path can mistake its internal result width for the unchanged 64-bit gRPC response width.
packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25

The comment still describes an i64 map and Some(i64) entries, but the accumulator is BTreeMap<Vec<u8>, i128> and SumEntry::sum is Option<i128>. Update the internal type references; the no-proof gRPC response still uses sint64.

    /// Cartesian-forks the single `In` clause into one Equal-per-value
    /// sub-query against a `summable: "<sum_property>"` index; aggregates
    /// the per-branch sums into a `BTreeMap<Vec<u8>, i128>`
    /// (deduplicated by serialized key) and emits per-In-value `SumEntry`
    /// where `in_key: None`, `key: serialized_value`, `sum: Some(i128)`.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-sol (phase2-reviewer: general, ffi-engineer)

Disputed — left to maintainers (1)

  • 🔴 Blocking: Updating the native framework alone makes released decoders drop ordinary sums and averages — packages/rs-sdk-ffi/src/document/queries/sum.rs:103-104 (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: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The change is cross-cutting, but it widens authenticated aggregate results and updates query and SDK output without changing cryptographic verification, consensus rules, or stored state.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • New since the last final review (e480311b): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-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-drive-proof-verifier/src/proof/document_split_sum.rs`:
- [BLOCKING] packages/rs-drive-proof-verifier/src/proof/document_split_sum.rs:43-47: Grouped sums and averages can merge documents with a missing range value into a named group
  Impact: Native and JavaScript callers grouping by an optional range field across multiple `In` values can receive a successful result with the wrong sum and count for a named group.
  A valid proof can yield one group with sum 40 and count 2 instead of two groups with sums 10 and 30. For example, call `getDocumentsSum` or `getDocumentsAverage` on a range-averageable `[brand, color]` index that retains missing colors, with `brand in ["a", "b"]`, `color < "z"`, and `groupBy: ["color"]`. A brand `a` document with no color and amount 10 is indexed under the empty color key, which the upper-only range includes; a brand `b` document with color `a` and amount 30 is indexed under the serialized color `a`. The `RangeDistinct` verifiers keep the actual color key and the outer brand `in_key` separately. The new `flat_group_key` mistakes the first row's real empty color key for a carrier placeholder and replaces it with the brand `a` key, which collides with the second row's color key. Both native exports and WASM use this fold, so AVG also combines the two counts and reports 20 for color `a` instead of 30. Carry the resolved carrier-versus-distinct proof shape into the shared Rust projection so only carrier totals use `in_key`, and add a signed regression covering a real empty range key.

  _Confirmed by an independent pass: On a stored document type with a range-averageable [brand, color] index that retains missing colors, insert a brand "a" document with no color and amount 10, and a brand "b" document with color "a" and amount 30. Calling getDocumentsSum or getDocumentsAverage with brand in ["a", "b"], color < "z", and groupBy: ["color"] returns only the color "a" group with sum 40 and, for AVG, count 2, instead of separate missing-color and color "a" groups with sums 10 and 30._

In `packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs`:
- [NITPICK] packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25: The per-In-value executor documents the old map and entry types
  Impact: Maintainers tracing the no-proof path can mistake its internal result width for the unchanged 64-bit gRPC response width.
  The comment still describes an `i64` map and `Some(i64)` entries, but the accumulator is `BTreeMap<Vec<u8>, i128>` and `SumEntry::sum` is `Option<i128>`. Update the internal type references; the no-proof gRPC response still uses `sint64`.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 23, 2026
The previous commit grouped a flat map entry with an empty terminator
key by its `in_key`, taking the empty key for a carrier placeholder. An
empty key can be real: a document missing an optional range property is
indexed under it, so a range-distinct result grouped by that field
across two `In` values could fold a missing-value group into a named
one.

The group is now fixed where the proof shape is known: the carrier
verifiers return each total keyed by its `In` value (`in_key: None`,
`key: <In value>`), the shape a node's unproven answer and a point
lookup grouped by the `In` field give. `try_into_flat_map` merges by
the terminator key again, with no special case, and keeps an empty
range key as its own group.

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

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 23, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

Changes requested: 1 blocker

  • Mobile shows the missing-value group as the overall total — packages/rs-drive-proof-verifier/src/proof/document_split_sum.rs:57-60 (new)
    Impact: On iOS and Android, a grouped sum or average over an optional range field can show the missing-value subtotal as the overall result and omit that group from the breakdown.
    Not counted: 1 disputed blocking finding(s) left to maintainers.

New on this head: This revision keys proved SUM and AVG branch totals by their In value and removes the flat-map heuristic, so an empty range key stays separate from named groups. Rust workspace, wasm32, Swift schema, and package functional checks passed; Kotlin and the platform test suites were pending when checked. The Swift SDK build failed on the same SendTransactionView.swift type-check timeout reproduced on PR #6093, in a view this PR does not change.

🔴 1 blocking | 🟡 1 suggestion(s) | 💬 1 nitpick(s)

1 finding(s) not shown inline (the lines are not part of this PR's diff)

💬 Nitpick: The per-In-value executor documents the old map and entry types
Impact: Drive maintainers reading the no-proof executor's rustdoc see i64 where both the internal map and emitted entries now carry i128.
packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25

The comment describes a BTreeMap<serialized_value, i64> and sum: Some(i64), but the map at lines 64–65 holds i128 and the executor copies those values into SumEntry::sum. Update the internal types without implying that the no-proof gRPC response widened; it still carries sint64.

    /// Cartesian-forks the single `In` clause into one Equal-per-value
    /// sub-query against a `summable: "<sum_property>"` index. It collects
    /// the widened sums in a `BTreeMap<Vec<u8>, i128>` keyed by serialized
    /// value and emits one `SumEntry` per distinct key, with `in_key: None`
    /// and `sum: Some(sum)`. The no-proof gRPC response still uses `sint64`.

source: muse-spark-1.3-contributor (phase1-reviewer: general, rust-quality); gpt-6.2-sol (phase2-reviewer: general, rust-quality, security-auditor)

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: ffi-engineer); reviewer 6: gpt-6.2-sol (agent: phase2-reviewer, role: platform-versioning); reviewer 7: gpt-6.2-sol (agent: phase2-reviewer, role: rust-quality); reviewer 8: gpt-6.2-sol (agent: phase2-reviewer, role: security-auditor); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: normal by gpt-6.2-sol (effort low) — The change is cross-cutting, but it widens and formats authenticated query results without changing proof authentication, consensus rules, or the node’s unproven wire format.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort xhigh); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort xhigh); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity quota lookup failed), glm-5.3-flash (not used above high effort; tier asks max)
  • New since the last final review (90847066): 1 new blocker(s) went to an independent confirmation pass (the final verifier's model in a fresh session, without its reasoning): 1 confirmed
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — architecture-layering (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — ffi-engineer (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — platform-versioning (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — rust-quality (completed, effort high); agent phase2-reviewer, gpt-6.2-sol — security-auditor (completed, effort high); agent phase2-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-drive-proof-verifier/src/proof/document_split_sum.rs`:
- [BLOCKING] packages/rs-drive-proof-verifier/src/proof/document_split_sum.rs:57-60: Mobile shows the missing-value group as the overall total
  Impact: On iOS and Android, a grouped sum or average over an optional range field can show the missing-value subtotal as the overall result and omit that group from the breakdown.
  Both Sum / Average Documents screens can report a sum of 10 or an average of 10.0000 as Total when the overall sum and average are 40 and 20.0000. With a stored type using a range-averageable `[brand, color]` index that retains missing colors, a brand `a` document without color and amount 10 is indexed under the empty color key, while a brand `b` document with color `a` and amount 30 is indexed under `a`. Run SUM or AVG with `brand in ["a", "b"]`, `color < "z"`, and `group_by: ["color"]`. The upper-only range includes both keys, and the distinct proof preserves them. By removing `flat_group_key`, this commit correctly passes the empty key through both Rust folds instead of substituting the outer brand key. The grouped native serializers then hex-encode it as `""`, which is also their ungrouped-total key. Swift's `total` accessors and Kotlin's parsers read that entry as the total, and both screens exclude it from the breakdown. Carry the grouped-versus-aggregate distinction already known to Rust across the native boundary, keep the verified keys as-is, and render the empty grouped key as a missing-value row. Test the grouped payload with both keys as well as the ungrouped total.

  _Confirmed by an independent pass: On either mobile Sum / Average Documents screen, run SUM or AVG of `amount` with `brand in ["a", "b"]`, `color < "z"`, and `group_by: ["color"]` against a protocol-15 stored type whose range-averageable `[brand, color]` index retains missing colors. If one brand `a` document has no color and amount 10, and two brand `b` documents have color `a` and amount `i64::MAX` each, both groups now verify successfully. The screen labels the missing-color group's 10 or 10.0000 as Total and omits that group from the breakdown, even though the grouped query returned no overall total._

In `packages/rs-drive-proof-verifier/src/proof/document_sum.rs`:
- [SUGGESTION] packages/rs-drive-proof-verifier/src/proof/document_sum.rs:207-210: Rust grouped SUM and AVG callers get different keys than the docs describe
  Impact: Rust callers that identify proved `In` groups by `in_key` can treat every returned group as absent after upgrading to SDK 5.1, and the verifier docs also imply that an unproven range request returns the same per-group layout.
  An SDK caller following the v5.0.2 verifier's advice to compare requested `In` values against returned `in_key`s will find none for a proof-backed `In`-plus-range query grouped only by the `In` field. This commit changes both carrier wrappers from `(Some(value), [])` to `(None, value)`, and both SDK split types forward those fields unchanged, including on protocol 14. The public split entry docs do not explain that distinction. The new wrapper docs also claim parity with the node's unproven answer, but for the same range request the no-proof SUM walk folds the branches into one empty-key entry (`execute_range_sum.rs:195–199`), and AVG wraps its combined pair the same way (`drive_document_count_and_sum_query/drive_dispatcher.rs:269–277`). Keep the comparison to point lookups grouped by `In`, document the carrier-versus-range-distinct layouts on both split entry types and in the 5.1 upgrade guide, and mark the PR title with `!` to flag the SDK break.

In `packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs`:
- [NITPICK] packages/rs-drive/src/query/drive_document_sum_query/executors/per_in_value.rs:21-25: The per-In-value executor documents the old map and entry types
  Impact: Drive maintainers reading the no-proof executor's rustdoc see `i64` where both the internal map and emitted entries now carry `i128`.
  The comment describes a `BTreeMap<serialized_value, i64>` and `sum: Some(i64)`, but the map at lines 64–65 holds `i128` and the executor copies those values into `SumEntry::sum`. Update the internal types without implying that the no-proof gRPC response widened; it still carries `sint64`.
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.

  • The Swift build times out type-checking the send screen — The exact-head Swift job reports a compiler timeout at SendTransactionView.swift:80:16. The same diagnostic occurs on PR #6093, and PR #6095 does not change that file.
    • Follow-up: Rerun the Swift job once the base includes the merged fix in #6101.

@github-actions

Copy link
Copy Markdown
Contributor

Your move: thepastaclaw requested changes on this head; dismiss the review or push a fix; thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Nov 23, 2026
…p key is never the total

In a grouped sum or average, documents missing an optional range value
form a group under the empty key. The FFI wrote it as "", which the
ungrouped total also uses, so the iOS and Android screens showed that
group as the total and left it out of the breakdown.

- rs-sdk-ffi: both results carry "grouped", from the group_by the call
  already routes on; keys are unchanged.
- SwiftDashSDK: `isGrouped` and `total` read the flag; the public inits
  take `isGrouped`. A missing or non-boolean flag throws.
- SwiftExampleApp and KotlinExampleApp: a grouped result shows its
  groups, the empty key as "(no value)" (`groupRow.empty`), and no
  total. Kotlin unwraps the result envelope by name.
- drive-proof-verifier docs: the split entry layouts per grouping, and
  the carrier comparison limited to point lookups grouped by the In
  field. The 5.1 upgrade guide notes the carrier key change and the flag.
- SumAverageDocumentsView passes Int128 values to Text as strings,
  avoiding a deprecation warning the CI build treats as an error.

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

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Nov 23, 2026
@QuantumExplorer
QuantumExplorer merged commit bac2975 into v5.1-dev Nov 23, 2026
22 of 24 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/swift-example-wide-document-sums branch November 23, 2026 01:31
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