Skip to content

Fix compilation errors in holographic_transport.rs#737

Open
iberi22 wants to merge 1 commit intomainfrom
fix/holographic-transport-compilation-1952248865540049900
Open

Fix compilation errors in holographic_transport.rs#737
iberi22 wants to merge 1 commit intomainfrom
fix/holographic-transport-compilation-1952248865540049900

Conversation

@iberi22
Copy link
Owner

@iberi22 iberi22 commented Mar 12, 2026

I have fixed the compilation errors in crates/synapse-infra/src/adapters/holographic_transport.rs.

The primary issue was an attempt to call .write().await on a CrystallineLedger instance directly, rather than on an RwLock wrapping it. I updated the create_projection method to accept a reference to an RwLock<CrystallineLedger>, marked the method as async, and updated its internal logic to acquire a read lock before cloning the ledger for speculative validation.

I also updated the encode_state method to properly await the now-async create_projection calls. Additionally, I resolved several other compilation issues discovered during verification, including missing Default implementations and integer type mismatches in the interpolation logic.

While some unrelated compilation errors persist in the synapse-infra crate (specifically in surrealdb_adapter.rs and tokenomics_adapter.rs due to trait bound issues), the holographic_transport.rs file now passes semantic checks.

Fixes #736


PR created automatically by Jules for task 1952248865540049900 started by @iberi22

Summary by CodeRabbit

  • New Features
    • Introduced a holographic transport module enabling efficient data encoding and decoding with built-in validation.
    • Provides configurable reconstruction capabilities with multiple interpolation options.
    • Includes comprehensive error handling for data integrity and validation checks.

- Recovered holographic_transport.rs from git history as it was missing from the working directory.
- Registered holographic_transport module in adapters/mod.rs.
- Fixed E0599 by updating create_projection to accept &RwLock<CrystallineLedger> and making it async.
- Updated encode_state to correctly await the async create_projection call.
- Resolved type mismatches in nearest-neighbor and linear interpolation logic.
- Implemented Default for ReconstructionParams to fix missing method error.
- Verified fixes with cargo check (remaining errors in synapse-infra are unrelated to these changes).

Co-authored-by: iberi22 <10615454+iberi22@users.noreply.github.com>
@google-labs-jules
Copy link
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces the foundational holographic_transport module, enabling the system to encode and decode application states into holographic projections. This new service leverages the Crystalline Ledger for state reconstruction and validation, providing a robust mechanism for data transmission. The changes primarily focus on establishing this new functionality and resolving initial compilation issues to ensure its operational integrity.

Highlights

  • New Holographic Transport Module: Introduced a new module, holographic_transport.rs, which implements a service for encoding and decoding state into holographic projections using a Crystalline Ledger.
  • Compilation Error Resolution: Addressed several compilation errors within the new holographic_transport.rs file, primarily related to incorrect RwLock usage for CrystallineLedger and ensuring async methods were properly awaited.
  • Data Structure and Trait Implementations: Defined core data structures like HolographicState, HolographicProjection, and HologramTransportPacket, along with HolographicEncode and HolographicDecode traits for various data types.
  • Interpolation and Checksum Logic: Implemented logic for angular transformation, checksum calculation, and data interpolation during state reconstruction, including fixes for integer type mismatches.
Changelog
  • crates/synapse-infra/src/adapters/holographic_transport.rs
    • Added the HolographicTransport service, including its core logic for state encoding and decoding.
    • Defined HolographicState, HolographicProjection, HologramTransportPacket, and related data structures.
    • Implemented HolographicEncode and HolographicDecode traits for Vec<u8>, String, and HoloPacket.
    • Corrected the usage of RwLock for CrystallineLedger within the create_projection method.
    • Updated create_projection to be an async function and ensured it is awaited in encode_state.
    • Resolved integer type mismatches in the interpolate_data function.
    • Added Default implementations for ReconstructionParams and ProjectionHints.
    • Included comprehensive unit tests for the holographic transport functionality.
  • crates/synapse-infra/src/adapters/mod.rs
    • Declared the new holographic_transport module to integrate it into the synapse-infra crate.
Activity
  • The pull request was automatically created by Jules for task 1952248865540049900.
  • The author, @iberi22, addressed compilation errors to ensure the new holographic transport module functions correctly.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Mar 12, 2026

📝 Walkthrough

Walkthrough

Introduces a new holographic transport module implementing state transport over voxel projections. Includes data structures for holographic states and projections, encoding/decoding logic, error handling, and integration with CrystallineLedger for voxel resonance validation with comprehensive test coverage.

Changes

Cohort / File(s) Summary
Holographic Transport Core
crates/synapse-infra/src/adapters/holographic_transport.rs
Introduces comprehensive holographic transport system with HolographicState, HolographicProjection, HologramTransportPacket structures; HolographicTransport service providing encode/decode operations; HolographicEncode/Decode traits for Vec, String, and HoloPacket; error handling via HolographicTransportError; voxel projection generation with checksum validation; interpolation methods (Linear, Cubic, Nearest); CrystallineLedger integration for resonance checks. ⚠️ Note: Linked issue #736 indicates compilation errors—verify crystal: &RwLock<CrystallineLedger> is correctly applied to methods using .write().await.
Module Export
crates/synapse-infra/src/adapters/mod.rs
Adds public module declaration for holographic_transport.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HolographicTransport
    participant CrystallineLedger
    participant Output as Encoded Packet

    Client->>HolographicTransport: encode_state(state)
    HolographicTransport->>HolographicTransport: create_projection(angles)
    HolographicTransport->>HolographicTransport: state_to_voxels(angle)
    HolographicTransport->>HolographicTransport: calculate_checksum(voxels)
    HolographicTransport->>CrystallineLedger: check_voxel_resonance()
    CrystallineLedger-->>HolographicTransport: resonance_valid
    HolographicTransport->>CrystallineLedger: add_voxel()
    CrystallineLedger-->>HolographicTransport: ack
    HolographicTransport->>Output: HologramTransportPacket
Loading
sequenceDiagram
    participant Client
    participant HolographicTransport
    participant Interpolator as Interpolation Engine
    participant Output as Recovered State

    Client->>HolographicTransport: decode_state(packet)
    HolographicTransport->>HolographicTransport: validate_checksum(projections)
    alt Checksum Valid
        HolographicTransport->>HolographicTransport: collect_voxel_chunks()
        HolographicTransport->>Interpolator: interpolate_data(chunks, method)
        Interpolator-->>HolographicTransport: reconstructed_data
        HolographicTransport->>Output: HolographicState
    else Checksum Mismatch
        HolographicTransport->>Output: ChecksumMismatch Error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🔮 A crystal lattice holds the light,
Voxels dance in holographic flight,
States encoded, projections bloom,
Through resonant pathways, data finds room! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing compilation errors in holographic_transport.rs, which aligns with the PR's primary objective.
Linked Issues check ✅ Passed The PR fully addresses issue #736's requirements: correcting RwLock usage by making create_projection async and accepting &RwLock, fixing type mismatches, and implementing Default for ReconstructionParams.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing compilation errors in holographic_transport.rs; module registration in mod.rs and helper implementations are necessary supporting changes.
Docstring Coverage ✅ Passed Docstring coverage is 84.00% 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 (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/holographic-transport-compilation-1952248865540049900

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

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new holographic transport mechanism and fixes several compilation errors. The new file is well-structured with clear separation of concerns for encoding, decoding, and data structures. However, I've found several issues, including a critical bug in the reconstruction logic where an angular transformation is not being reversed, potential panics due to unchecked byte slice operations, and ignored error results that could lead to incorrect behavior. I've also identified opportunities for performance improvement and increased robustness.

Comment on lines +448 to +466
fn derotate_voxel(&self, voxel: &Voxel, angle: usize, _tolerance: f32) -> Vec<u8> {
// Reverse the angular transformation
let rotation_offset = angle as f32 * std::f32::consts::TAU / self.max_projections as f32;

// Apply noise tolerance by rounding to nearest value
let mut corrected = Vec::with_capacity(voxel.payload.len());
let baseline = (voxel.neutral_axis * 255.0).round() as i16;

for &byte in &voxel.payload {
let delta = byte as i16 - baseline;
if delta.abs() <= (_tolerance * 50.0) as i16 {
corrected.push(baseline as u8);
} else {
corrected.push(byte);
}
}

corrected
}

Choose a reason for hiding this comment

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

critical

The rotation_offset variable is calculated but never used within the function. The function's comment states it should "Reverse the angular transformation", but the implementation only seems to apply noise correction. This appears to be a critical bug as the reconstruction logic is incomplete and will likely lead to incorrect data being reconstructed.


// Try to add voxels to crystal and check resonance
for voxel in &voxels {
let _ = crystal_clone.add_voxel(voxel.clone());

Choose a reason for hiding this comment

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

high

The result of crystal_clone.add_voxel(voxel.clone()) is ignored. The add_voxel method returns a Result which indicates success or failure of adding the voxel to the ledger, which includes a resonance check. By ignoring the result, you are missing potential errors that should be handled. If the resonance check fails, this function should probably return an error.

Suggested change
let _ = crystal_clone.add_voxel(voxel.clone());
crystal_clone.add_voxel(voxel.clone())?;

Comment on lines +628 to +665
fn from_holographic_state(state: &HolographicState) -> Result<Self> {
let mut offset = 0;
let data = &state.data;

// Read refraction_index
let bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
let refraction_index = f32::from_le_bytes(bytes);
offset += 4;

// Read polarization_signature
let sig_len_bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
let sig_len = u32::from_le_bytes(sig_len_bytes) as usize;
offset += 4;

let mut polarization_signature = Vec::with_capacity(sig_len);
for _ in 0..sig_len {
let sig_bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
polarization_signature.push(f32::from_le_bytes(sig_bytes));
offset += 4;
}

// Read temporal_phase
let phase_bytes: [u8; 8] = data[offset..offset + 8].try_into()?;
let temporal_phase = u64::from_le_bytes(phase_bytes);
offset += 8;

// Read variance
let variance = if offset < data.len() && data[offset] == 1 {
offset += 1;
let var_bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
Some(f32::from_le_bytes(var_bytes))
} else {
None
};

Ok(HoloPacket::new(refraction_index, polarization_signature, temporal_phase)
.with_variance(variance.unwrap_or(0.0)))
}

Choose a reason for hiding this comment

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

high

The from_holographic_state implementation performs manual deserialization by slicing the data buffer. These slicing operations (e.g., data[offset..offset + 4] on line 633) are not preceded by bounds checks. If the input data is shorter than expected, this will cause a panic. To make this function safe against malformed input, you should check if data has enough bytes before each slicing operation and return an error if it doesn't. This applies to all reads from the data buffer in this function (lines 633, 638, 644, 650, and 657).

Comment on lines +72 to +75
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),

Choose a reason for hiding this comment

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

medium

The call to .unwrap() on duration_since(std::time::UNIX_EPOCH) can panic if the system clock is set to a time before the UNIX epoch. While this is unlikely on most systems, for robust code it's better to handle this possibility. Since this function doesn't return a Result, you could handle the error case by, for example, using 0 as a timestamp.

Suggested change
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0),

Comment on lines +217 to +220
for angle in 0..self.max_projections {
let projection = self.create_projection(&state, angle, &self.crystal).await?;
projections.push(projection);
}

Choose a reason for hiding this comment

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

medium

The loop to create projections is sequential. Since each projection creation is an independent async operation, this is a good candidate for parallelization using futures::future::try_join_all. This could significantly improve performance, especially when max_projections is large. This would require careful lifetime management as create_projection takes references.

let mut found_any = false;

for projection in &packet.projections {
if projection.angle_index >= projection.voxels.len() {

Choose a reason for hiding this comment

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

medium

The condition if projection.angle_index >= projection.voxels.len() seems incorrect. angle_index is the index of the projection (0-8), while projection.voxels.len() is the number of voxels in that projection. There's no logical reason to compare them, and it's unlikely for this condition to be true. This is likely a bug or dead code and should be reviewed or removed.

let val_count = meta_voxel.payload.len() / 4;
let mut vals = Vec::with_capacity(val_count);
for i in 0..val_count {
let bytes: [u8; 4] = meta_voxel.payload[i * 4..(i + 1) * 4].try_into().unwrap_or([0, 0, 0, 0]);

Choose a reason for hiding this comment

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

medium

Using unwrap_or here can hide issues with malformed data. If try_into() fails, it means the payload length is not a multiple of 4, which indicates data corruption. Instead of silently using a zero-filled array, it would be better to propagate an error to signal that the packet is invalid.

Suggested change
let bytes: [u8; 4] = meta_voxel.payload[i * 4..(i + 1) * 4].try_into().unwrap_or([0, 0, 0, 0]);
let bytes: [u8; 4] = meta_voxel.payload[i * 4..(i + 1) * 4].try_into()?;

return Vec::new();
}

let len = chunks[0].len();

Choose a reason for hiding this comment

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

medium

The linear interpolation logic assumes that all Vec<u8> in chunks have the same length as the first one. If they don't, data will be silently truncated or ignored due to .take(len) on line 489. It would be safer to add a check to ensure all chunks have the same length and return an error if they don't.

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: 3

🧹 Nitpick comments (2)
crates/synapse-infra/src/adapters/holographic_transport.rs (2)

448-466: Unused rotation_offset and misleading underscore prefix on _tolerance.

  1. rotation_offset is calculated (line 450) but never used in the de-rotation logic
  2. _tolerance has underscore prefix suggesting it's unused, but it's actually used on line 458
♻️ Suggested cleanup
-    fn derotate_voxel(&self, voxel: &Voxel, angle: usize, _tolerance: f32) -> Vec<u8> {
+    fn derotate_voxel(&self, voxel: &Voxel, angle: usize, tolerance: f32) -> Vec<u8> {
         // Reverse the angular transformation
-        let rotation_offset = angle as f32 * std::f32::consts::TAU / self.max_projections as f32;
+        let _rotation_offset = angle as f32 * std::f32::consts::TAU / self.max_projections as f32;
+        // TODO: Apply rotation_offset for proper angular de-transformation

         // Apply noise tolerance by rounding to nearest value
         let mut corrected = Vec::with_capacity(voxel.payload.len());
         let baseline = (voxel.neutral_axis * 255.0).round() as i16;

         for &byte in &voxel.payload {
             let delta = byte as i16 - baseline;
-            if delta.abs() <= (_tolerance * 50.0) as i16 {
+            if delta.abs() <= (tolerance * 50.0) as i16 {
                 corrected.push(baseline as u8);
             } else {
                 corrected.push(byte);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/synapse-infra/src/adapters/holographic_transport.rs` around lines 448
- 466, In derotate_voxel, remove the unused local rotation_offset (or integrate
it into the de-rotation math if you intended to adjust values by angle) and
rename the parameter from _tolerance to tolerance so it no longer signals
"unused"; update all references (the delta comparison uses the tolerance value)
to use the new name and ensure any intended use of rotation_offset is
implemented (e.g., apply rotation_offset to adjust baseline or delta) or simply
delete the rotation_offset calculation if not needed.

259-264: Consider logging voxel resonance validation failures.

The add_voxel errors are silently discarded with let _ =. According to the context snippets, add_voxel can return GenesisError::ZeroVector or GenesisError::MoralPanic when validation fails. While this speculative validation pattern (cloning then modifying) is sound, logging failures would aid debugging:

♻️ Suggested improvement
         // Try to add voxels to crystal and check resonance
         for voxel in &voxels {
-            let _ = crystal_clone.add_voxel(voxel.clone());
+            if let Err(e) = crystal_clone.add_voxel(voxel.clone()) {
+                // Resonance validation failure is expected for some voxels
+                tracing::trace!("Voxel resonance check failed (expected): {:?}", e);
+            }
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/synapse-infra/src/adapters/holographic_transport.rs` around lines 259
- 264, The loop currently discards add_voxel results (let _ =
crystal_clone.add_voxel(...)); change it to match the Result and log validation
failures (e.g., Err(GenesisError::ZeroVector) or Err(GenesisError::MoralPanic))
including the voxel (Debug/ID) and error variant; keep successful adds
unchanged. Update the code around crystal.read().await.clone() and the for voxel
in &voxels loop to do: if let Err(e) = crystal_clone.add_voxel(voxel.clone()) {
/* log e and voxel via existing logger or tracing::warn/error */ } so failures
are recorded but the loop continues.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/synapse-infra/src/adapters/holographic_transport.rs`:
- Around line 628-661: The from_holographic_state deserializer (function
from_holographic_state) reads multiple slices from state.data using
data[offset..offset+N] without bounds checks; add explicit checks before each
read (e.g., ensure offset + 4 <= data.len() before reading a 4-byte field,
offset + 8 <= data.len() for 8-byte fields and offset + sig_len*4 <= data.len()
before the polarization_signature loop) and return a proper Err (use anyhow! or
the crate's error helper) with a clear message on unexpected end-of-data; update
the variance branch to check there is at least one byte for the presence flag
and then 4 more bytes for the f32 if present, and use these checks consistently
for refraction_index, sig_len, signature elements, temporal_phase, and variance
to prevent panics.
- Around line 72-75: The current timestamp construction in
holographic_transport.rs uses
SystemTime::now().duration_since(UNIX_EPOCH).unwrap(), which can panic if the
system clock is before 1970; change this to handle the Result safely (e.g.,
match or .unwrap_or_else) so the code never panics: call
SystemTime::now().duration_since(UNIX_EPOCH) and on Err convert to a safe
fallback (zero or log and use 0) and on Ok use as_secs(), then assign that value
to the timestamp field; reference the timestamp field initialization and the
SystemTime::now()/duration_since(UNIX_EPOCH) call to locate the change.
- Around line 373-376: The bounds check "if projection.angle_index >=
projection.voxels.len()" is ineffective because angle_index is 0..8 while
voxels.len() is much larger; remove this check or replace it with the meaningful
check used for voxel access: ensure that chunk_idx (the index actually used to
access projection.voxels) is within bounds (e.g., verify chunk_idx <
projection.voxels.len()) before indexing, or if you intended to validate
angle_index instead, replace the condition with an explicit range check for
angle_index (e.g., angle_index < 9) and document which invariant is required;
update the loop over packet.projections accordingly (references:
projection.angle_index, projection.voxels, chunk_idx, packet.projections).

---

Nitpick comments:
In `@crates/synapse-infra/src/adapters/holographic_transport.rs`:
- Around line 448-466: In derotate_voxel, remove the unused local
rotation_offset (or integrate it into the de-rotation math if you intended to
adjust values by angle) and rename the parameter from _tolerance to tolerance so
it no longer signals "unused"; update all references (the delta comparison uses
the tolerance value) to use the new name and ensure any intended use of
rotation_offset is implemented (e.g., apply rotation_offset to adjust baseline
or delta) or simply delete the rotation_offset calculation if not needed.
- Around line 259-264: The loop currently discards add_voxel results (let _ =
crystal_clone.add_voxel(...)); change it to match the Result and log validation
failures (e.g., Err(GenesisError::ZeroVector) or Err(GenesisError::MoralPanic))
including the voxel (Debug/ID) and error variant; keep successful adds
unchanged. Update the code around crystal.read().await.clone() and the for voxel
in &voxels loop to do: if let Err(e) = crystal_clone.add_voxel(voxel.clone()) {
/* log e and voxel via existing logger or tracing::warn/error */ } so failures
are recorded but the loop continues.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3e2892b1-b23e-4b2b-89e5-d7362bc8809d

📥 Commits

Reviewing files that changed from the base of the PR and between d60204b and 0b87e33.

📒 Files selected for processing (2)
  • crates/synapse-infra/src/adapters/holographic_transport.rs
  • crates/synapse-infra/src/adapters/mod.rs

Comment on lines +72 to +75
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Consider defensive handling for system time edge case.

Using .unwrap() on duration_since(UNIX_EPOCH) could panic if the system clock is set before 1970 (rare but possible on misconfigured systems).

🛡️ Proposed defensive fix
         Self {
             state_id,
             data,
             validation_vector,
             timestamp: std::time::SystemTime::now()
                 .duration_since(std::time::UNIX_EPOCH)
-                .unwrap()
+                .unwrap_or_default()
                 .as_secs(),
             version: 1,
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/synapse-infra/src/adapters/holographic_transport.rs` around lines 72 -
75, The current timestamp construction in holographic_transport.rs uses
SystemTime::now().duration_since(UNIX_EPOCH).unwrap(), which can panic if the
system clock is before 1970; change this to handle the Result safely (e.g.,
match or .unwrap_or_else) so the code never panics: call
SystemTime::now().duration_since(UNIX_EPOCH) and on Err convert to a safe
fallback (zero or log and use 0) and on Ok use as_secs(), then assign that value
to the timestamp field; reference the timestamp field initialization and the
SystemTime::now()/duration_since(UNIX_EPOCH) call to locate the change.

Comment on lines +373 to +376
for projection in &packet.projections {
if projection.angle_index >= projection.voxels.len() {
continue;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for similar patterns or tests that exercise this code path
rg -n "angle_index" crates/synapse-infra/src/adapters/holographic_transport.rs -A 2 -B 2

Repository: iberi22/synapse-protocol

Length of output: 1074


🏁 Script executed:

#!/bin/bash
# Get the full context of the decode_state method around lines 373-400
sed -n '373,400p' crates/synapse-infra/src/adapters/holographic_transport.rs | cat -n

Repository: iberi22/synapse-protocol

Length of output: 1815


🏁 Script executed:

#!/bin/bash
# Search for how voxels are accessed in the surrounding code
rg -n "voxels\[" crates/synapse-infra/src/adapters/holographic_transport.rs -B 2 -A 2

Repository: iberi22/synapse-protocol

Length of output: 727


🏁 Script executed:

#!/bin/bash
# Look for the derotate_voxel function signature to understand what it expects
rg -n "fn derotate_voxel" crates/synapse-infra/src/adapters/holographic_transport.rs -A 5

Repository: iberi22/synapse-protocol

Length of output: 455


Remove or fix the ineffective bounds check at line 374.

Line 374 checks if projection.angle_index >= projection.voxels.len(), but this condition is invalid. The angle_index field is constrained to 0-8 (for 9-dimensional projection space), while voxels.len() is typically much larger. Since the actual voxel access at line 381 uses chunk_idx (not angle_index) with proper bounds checking at line 380, the check at line 374 provides no protection and will almost never be true.

Either remove this check or replace it with a meaningful bounds check if one is needed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/synapse-infra/src/adapters/holographic_transport.rs` around lines 373
- 376, The bounds check "if projection.angle_index >= projection.voxels.len()"
is ineffective because angle_index is 0..8 while voxels.len() is much larger;
remove this check or replace it with the meaningful check used for voxel access:
ensure that chunk_idx (the index actually used to access projection.voxels) is
within bounds (e.g., verify chunk_idx < projection.voxels.len()) before
indexing, or if you intended to validate angle_index instead, replace the
condition with an explicit range check for angle_index (e.g., angle_index < 9)
and document which invariant is required; update the loop over
packet.projections accordingly (references: projection.angle_index,
projection.voxels, chunk_idx, packet.projections).

Comment on lines +628 to +661
fn from_holographic_state(state: &HolographicState) -> Result<Self> {
let mut offset = 0;
let data = &state.data;

// Read refraction_index
let bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
let refraction_index = f32::from_le_bytes(bytes);
offset += 4;

// Read polarization_signature
let sig_len_bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
let sig_len = u32::from_le_bytes(sig_len_bytes) as usize;
offset += 4;

let mut polarization_signature = Vec::with_capacity(sig_len);
for _ in 0..sig_len {
let sig_bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
polarization_signature.push(f32::from_le_bytes(sig_bytes));
offset += 4;
}

// Read temporal_phase
let phase_bytes: [u8; 8] = data[offset..offset + 8].try_into()?;
let temporal_phase = u64::from_le_bytes(phase_bytes);
offset += 8;

// Read variance
let variance = if offset < data.len() && data[offset] == 1 {
offset += 1;
let var_bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
Some(f32::from_le_bytes(var_bytes))
} else {
None
};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Missing bounds validation in HoloPacket deserialization.

The deserialization logic performs multiple slice operations (data[offset..offset + N]) without verifying data.len() is sufficient. Malformed or truncated data will cause a panic:

let bytes: [u8; 4] = data[offset..offset + 4].try_into()?;  // panics if data too short
🛡️ Proposed bounds-checking fix
 impl HolographicDecode for HoloPacket {
     fn from_holographic_state(state: &HolographicState) -> Result<Self> {
         let mut offset = 0;
         let data = &state.data;

+        // Minimum size: 4 (refraction_index) + 4 (sig_len) + 8 (temporal_phase) = 16 bytes
+        if data.len() < 16 {
+            return Err(anyhow!("HoloPacket data too short: {} bytes", data.len()));
+        }
+
         // Read refraction_index
         let bytes: [u8; 4] = data[offset..offset + 4].try_into()?;

Additionally, validate before each read:

+        if offset + 4 > data.len() {
+            return Err(anyhow!("Unexpected end of data at offset {}", offset));
+        }
         let sig_bytes: [u8; 4] = data[offset..offset + 4].try_into()?;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/synapse-infra/src/adapters/holographic_transport.rs` around lines 628
- 661, The from_holographic_state deserializer (function from_holographic_state)
reads multiple slices from state.data using data[offset..offset+N] without
bounds checks; add explicit checks before each read (e.g., ensure offset + 4 <=
data.len() before reading a 4-byte field, offset + 8 <= data.len() for 8-byte
fields and offset + sig_len*4 <= data.len() before the polarization_signature
loop) and return a proper Err (use anyhow! or the crate's error helper) with a
clear message on unexpected end-of-data; update the variance branch to check
there is at least one byte for the presence flag and then 4 more bytes for the
f32 if present, and use these checks consistently for refraction_index, sig_len,
signature elements, temporal_phase, and variance to prevent panics.

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.

FIX: Compilation errors in holographic_transport.rs

1 participant