Skip to content

Conversation

@cuteolaf
Copy link
Contributor

@cuteolaf cuteolaf commented Jan 9, 2026

Summary by CodeRabbit

  • Refactor

    • Removed the incoming write-proposal handler; write consensus now flows via existing proposal/vote/commit paths.
  • New Features / Behavior

    • List and map operations now enforce type checks and return explicit TypeMismatch errors on misuse.
  • Tests

    • Added extensive unit tests covering dynamic storage behaviors, migrations, batch writing, caching, prefix scanning, storage types, and migration/versioning scenarios.

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

@coderabbitai
Copy link

coderabbitai bot commented Jan 9, 2026

📝 Walkthrough

Walkthrough

Removed the public receive_write_proposal method from DistributedStorage, consolidating P2P proposal handling onto propose_write, vote_write, and commit_write. Added extensive unit tests across storage crates and introduced a MiniChainError::TypeMismatch(String) error variant.

Changes

Cohort / File(s) Summary
Distributed Storage Refactor
crates/storage/src/distributed.rs
Deleted pub fn receive_write_proposal(...) -> (bool, Option<bool>), removing the P2P handler that built request info, validated proposals, applied initiator votes, and handled commit/pending outcomes. (+702/−82)
Dynamic storage & tests
crates/storage/src/dynamic.rs
Enforced type-aware list_push/map_set (return TypeMismatch on mismatch), create empty container when absent, and added many unit tests for CRUD, lists/maps, TTL, scanning, listeners, and edge cases. (+486/−8)
Library-level tests
crates/storage/src/lib.rs
Added unit tests for challenge/validator lifecycle, persistence/flush, dynamic access consistency, DB/state handles, and migration runner behavior. (+138/−0)
Migration tests
crates/storage/src/migration.rs
Added comprehensive tests for MigrationContext, MigrationRunner, migrations (apply/rollback/checksum), change tracking, and edge cases; no production API changes. (+509/−0)
Optimized storage tests
crates/storage/src/optimized.rs
Added tests for BatchWriter, LruCache, CachedTree, PrefixScanner, and StorageMetrics covering TTL, eviction, flush, and scanning semantics. (+323/−0)
Types tests
crates/storage/src/types.rs
Added tests for StorageKey utilities, StorageValue conversions/accessors, StorageEntry versioning/TTL, StorageChange invariants, and stats defaults. (+259/−0)
Error variant addition
crates/core/src/error.rs
Added MiniChainError::TypeMismatch(String) with message annotation. (+3/−0)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through code with nimble paws,
Pruned a path to tidy laws,
Tests like carrots line each row,
Type guards guard where wild bits go,
Consensus trimmed — a quiet cause.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Test(storage): More unit tests' accurately describes the primary change: extensive unit test additions across the storage crate.
Docstring Coverage ✅ Passed Docstring coverage is 98.15% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e21331 and 65fca7c.

📒 Files selected for processing (1)
  • crates/storage/src/dynamic.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Docker
🔇 Additional comments (3)
crates/storage/src/dynamic.rs (3)

298-309: Excellent type safety improvement!

The explicit type checking in list_push prevents accidentally overwriting non-list values and provides clear error messages. This is a solid improvement over the previous implementation.


326-335: Excellent type safety improvement!

The explicit type checking in map_set mirrors the improvement in list_push and prevents accidentally overwriting non-map values with clear error messages.


740-1202: Outstanding test coverage!

This comprehensive test suite significantly improves the reliability of the storage module. Key strengths:

  • Thorough coverage: 28 new tests covering configuration, CRUD operations, scoped storage, TTL behavior, error cases, and edge cases
  • Error validation: Proper testing of the new TypeMismatch errors for type safety violations
  • Well-structured: Clear test names, focused test cases, and appropriate assertions
  • Edge case handling: Tests for nonexistent keys, invalid key formats, expired entries, and type mismatches

The tests are production-ready and demonstrate best practices for unit testing storage systems.


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

❤️ Share

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @crates/storage/src/dynamic.rs:
- Around line 813-879: Tests show list_push and map_set silently replace
existing non-collection values (e.g., StorageValue::U64) which can silently lose
data; update list_push and map_set to check the existing value (via get_value /
the same retrieval path used by set) and return a clear error (e.g.,
TypeMismatch) when the stored type is not a list/map instead of overwriting, or
alternatively add explicit methods like replace_with_list/convert_to_map and
only perform conversion there; update unit tests to expect the new error
behavior (or add new tests for the explicit-conversion methods) and keep
references to the functions list_push, map_set, set, StorageValue, and get_value
when making changes.
🧹 Nitpick comments (2)
crates/storage/src/dynamic.rs (2)

1090-1099: Consider enhancing the flush verification test.

The test currently only verifies that flush() succeeds without error. While verifying actual disk persistence is challenging in unit tests, consider adding verification such as:

  • Dropping the storage instance and re-opening to confirm data persisted
  • Checking that sled's internal state indicates flush completion

However, the current test provides basic smoke test coverage, which may be sufficient.


1139-1185: Consider removing specific line number references in test comments.

Several test comments reference specific line numbers in the production code (e.g., "lines 367-374", "line 386", "line 441"). While these help readers understand which code paths are being tested, they become stale and incorrect when the production code is refactored. Consider replacing with descriptive comments about the behavior being tested instead:

// Tests parsing keys with validator (validator byte array parsing logic)
// Tests parsing invalid key format (returns None for malformed keys)
// Tests stats aggregation across namespaces

This makes the tests more maintainable while preserving the intent.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7678293 and 0859d6a.

📒 Files selected for processing (6)
  • crates/storage/src/distributed.rs
  • crates/storage/src/dynamic.rs
  • crates/storage/src/lib.rs
  • crates/storage/src/migration.rs
  • crates/storage/src/optimized.rs
  • crates/storage/src/types.rs
🧰 Additional context used
🧬 Code graph analysis (2)
crates/storage/src/distributed.rs (3)
crates/storage/src/dynamic.rs (3)
  • test_get_nonexistent (760-766)
  • create_test_storage (594-599)
  • new (44-59)
crates/storage/src/types.rs (2)
  • new (264-274)
  • is_expired (282-289)
crates/storage/src/lib.rs (2)
  • db (134-136)
  • open (73-99)
crates/storage/src/dynamic.rs (1)
crates/storage/src/types.rs (7)
  • validator (41-51)
  • as_u64 (119-125)
  • system (23-29)
  • as_list (173-178)
  • as_str (152-157)
  • as_map (180-185)
  • challenge (32-38)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Test
🔇 Additional comments (10)
crates/storage/src/distributed.rs (1)

1299-2001: LGTM! Excellent test coverage for distributed storage.

The 34 new test functions provide comprehensive validation of:

  • Entry operations (compression, verification, expiry, ACKs, serialization)
  • Consensus mechanism (voting, self-votes, 50% threshold)
  • Storage CRUD operations (propose, vote, commit, get, list, cleanup)
  • Edge cases (size limits, duplicate votes, corruption, pending ops)
  • Error handling and display

The tests are well-structured, assertions are correct, and boundary conditions are properly tested (e.g., TTL expiry at exact block height).

crates/storage/src/types.rs (1)

373-632: LGTM! Comprehensive type conversion and accessor tests.

The 23 new tests thoroughly validate:

  • StorageKey construction (system, challenge, validator, global_validator) and serialization
  • StorageValue type conversions with proper boundary checks (e.g., u64::MAX to i64 returns None, negative i64 to u64 returns None)
  • All accessor methods (as_bool, as_u64, as_i64, as_u128, as_f64, as_str, as_bytes, as_json, as_list, as_map, is_null)
  • From trait implementations for all value types
  • StorageEntry lifecycle (creation, updates, TTL expiry)
  • StorageChange and Stats structures

The edge case coverage is excellent, particularly the overflow/underflow checks in numeric conversions.

crates/storage/src/lib.rs (1)

340-478: LGTM! Solid test coverage for Storage API.

The 11 new tests validate essential Storage behaviors:

  • Challenge CRUD operations (delete, list, save/load)
  • Loading non-existent entities correctly returns None
  • Empty state handling
  • Persistence and flush operations
  • Dynamic storage access consistency (dynamic() and dynamic_arc())
  • Database handle access
  • Migration runner creation and execution with built-in migrations

The tests are clear, assertions are correct, and they provide good coverage of the public API surface.

crates/storage/src/optimized.rs (1)

395-718: LGTM! Thorough test coverage for optimization features.

The 24 new tests comprehensively validate:

  • BatchWriter: auto-flush on buffer capacity, flush on drop
  • LruCache: LRU eviction policy (oldest first), explicit removal, clear, emptiness checks, TTL-based cleanup, TTL expiry timing
  • CachedTree: cache hit/miss tracking, CRUD operations, cache invalidation on remove, flush behavior
  • CacheStats: hit rate calculation including zero-ops edge case
  • PrefixScanner: count, keys, values extraction, for_each iteration with early termination (correctly tests break on false return)
  • StorageMetrics: average latency calculations with proper zero-division handling

The arithmetic in tests is correct (e.g., ASCII sum: 49 + 50 = 99), and edge cases are well covered.

crates/storage/src/migration.rs (1)

559-1068: LGTM! Comprehensive migration system test coverage.

The 34 new tests thoroughly validate:

  • MigrationContext operations: get/set/delete, scan_prefix, raw state access, change tracking
  • MigrationRunner orchestration: registration, version tracking, applied/pending queries, run_pending, rollback
  • Built-in migrations: InitialMigration and AddChallengeMetricsMigration up/down behavior, properties, reversibility
  • Serialization: MigrationRecord round-trip
  • Edge cases: duplicate registration (correctly ignored), non-reversible rollback (correctly errors), non-existent key access (correctly returns None), idempotent run_pending when no migrations pending
  • Default trait methods validation

The rollback test correctly validates that non-reversible migrations (like InitialMigration) cannot be rolled back, and the early-return path for empty pending migrations is properly tested.

crates/storage/src/dynamic.rs (5)

726-757: LGTM! Well-structured basic functionality tests.

The tests for set_block_height, with_cache, and global validator storage are clear and correctly verify the expected behavior.


759-793: LGTM! Comprehensive edge case coverage.

These tests appropriately verify the handling of non-existent keys across multiple operations, including the correct default behavior for increment starting from 0.


881-930: LGTM! Effective tests for scanning and maintenance operations.

The tests appropriately verify namespace scanning, expired entry cleanup, and statistics gathering functionality.


932-1031: LGTM! Comprehensive scoped storage coverage.

These tests thoroughly exercise challenge-scoped and validator-scoped storage operations, including deletion, TTL, scanning, incrementing, and map operations. The TTL tests verify that values can be set with TTL; actual expiration behavior is covered by test_ttl at line 645.


1101-1137: LGTM! Good coverage of existence checks and update semantics.

The test_exists verifies proper existence tracking, and test_set_with_options_update_existing specifically exercises the update path for existing entries with TTL propagation.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
crates/storage/src/dynamic.rs (3)

298-319: Consider performance optimization for list operations.

The current implementation clones the entire list on every list_push operation, which has O(n) complexity. For large lists or frequent pushes, this could impact performance.

While the type-safety check is excellent and prevents bugs, consider optimizing the list update strategy if this becomes a hot path.

Potential optimization approaches
  1. Batch operations: Add a list_push_batch method for multiple values
  2. Copy-on-write: Use Arc with copy-on-write semantics
  3. Incremental serialization: Store list metadata separately and append without full deserialization

Note: Current implementation is correct and acceptable for typical use cases. Only optimize if profiling shows this as a bottleneck.


329-347: Similar performance consideration for map operations.

Like list_push, the map_set implementation clones the entire HashMap on every field update. The type-safety check is well-implemented and prevents bugs. Consider the same optimization strategies mentioned for list operations if this becomes a performance bottleneck.


684-684: Potential timing flakiness in TTL tests.

Tests using std::thread::sleep with hardcoded durations (50-100ms) may be flaky on slow CI environments or under heavy load. While these specific durations are reasonable, consider adding margin or using more robust time-based testing patterns if flakiness occurs.

Also applies to: 935-935

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0859d6a and 3e21331.

📒 Files selected for processing (2)
  • crates/core/src/error.rs
  • crates/storage/src/dynamic.rs
🔇 Additional comments (3)
crates/core/src/error.rs (1)

49-51: LGTM! Clean addition of TypeMismatch error variant.

The new error variant is well-integrated and supports the type-aware storage operations in the dynamic storage module. The error message format is clear and consistent with other variants.

crates/storage/src/dynamic.rs (2)

747-1211: Excellent test coverage!

The test suite is comprehensive and well-structured, covering:

  • Happy paths and error paths (including TypeMismatch scenarios)
  • Edge cases (nonexistent keys, expired entries, invalid formats)
  • All major APIs (challenge storage, validator storage, scoped access)
  • TTL, caching, change listeners, statistics, and cleanup operations

Tests are focused, well-named, and use proper test utilities.


1-23: No action needed. The dependencies in crates/storage/Cargo.toml use workspace inheritance ({ workspace = true }), not "latest" markers. This approach ensures reproducible builds across the workspace by centralizing version management.

Likely an incorrect or invalid review comment.

@echobt echobt merged commit e249030 into PlatformNetwork:main Jan 9, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants