Skip to main content

qualia_core_db/domains/geospatial/
spatial_sync.rs

1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4/// A planted asset representation for the spatial sync protocol.
5/// Defines "who-planted-what-where" across a shared world, keyed by spatial index.
6#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
7pub struct PlantedAsset {
8    /// A unique identifier for this placement (UUID or similar).
9    pub asset_id: String,
10    /// The H3 cell (or quadtree node) index this asset was planted in.
11    pub cell_id: u64,
12    /// The exact world-space position.
13    pub position: [f64; 3],
14    /// Orientation/rotation (quaternion or euler angles), stubbed as [f64; 4] for quaternion.
15    pub rotation: [f64; 4],
16    /// DID of the participant who planted this.
17    pub creator_did: String,
18    /// Lamport clock tracking the latest update/deletion state.
19    pub lamport: u64,
20    /// True if the asset was deleted/uprooted by the creator.
21    pub deleted: bool,
22}
23
24/// A spatial sync cell keyed by H3/quadtree cell id, holding the merged planted assets.
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct SpatialSyncCell {
27    pub cell_id: u64,
28    pub planted_assets: Vec<PlantedAsset>,
29}
30
31impl SpatialSyncCell {
32    /// Creates a default `SpatialSyncCell`.
33    pub fn new(cell_id: u64, planted_assets: Vec<PlantedAsset>) -> Self {
34        Self {
35            cell_id,
36            planted_assets,
37        }
38    }
39
40    /// Build a cell view from merged assets, filtering to the target cell and dropping tombstones.
41    pub fn from_assets(cell_id: u64, assets: &[PlantedAsset]) -> Self {
42        let mut planted_assets: Vec<PlantedAsset> = assets
43            .iter()
44            .filter(|a| a.cell_id == cell_id && !a.deleted)
45            .cloned()
46            .collect();
47        planted_assets.sort_by(|a, b| a.asset_id.cmp(&b.asset_id));
48        Self {
49            cell_id,
50            planted_assets,
51        }
52    }
53
54    /// Merge incoming remote/local assets into this cell using LWW resolution.
55    pub fn merge(&mut self, incoming: &[PlantedAsset]) {
56        let merged = merge_planted_assets(&self.planted_assets, incoming);
57        self.planted_assets = merged
58            .into_iter()
59            .filter(|a| a.cell_id == self.cell_id && !a.deleted)
60            .collect();
61    }
62}
63
64/// Last-Write-Wins (LWW) conflict resolution for overlapping asset placements.
65/// Merges two sets of `PlantedAsset`s, resolving conflicts by `asset_id` using the Lamport clock.
66/// Higher Lamport wins. Deterministic tie-breaking on `asset_id` string if clocks match.
67pub fn merge_planted_assets(local: &[PlantedAsset], remote: &[PlantedAsset]) -> Vec<PlantedAsset> {
68    let mut state: HashMap<String, PlantedAsset> = HashMap::new();
69
70    for asset in local.iter().chain(remote.iter()) {
71        if let Some(existing) = state.get(&asset.asset_id) {
72            if asset.lamport > existing.lamport {
73                state.insert(asset.asset_id.clone(), asset.clone());
74            } else if asset.lamport == existing.lamport {
75                // Deterministic tie breaker using position string just in case
76                // but really should not happen for the exact same asset_id unless they are identical
77                // We'll prefer the one that is somehow "larger" in creator_did as a stable tie-break,
78                // or just leave it. If identical, leaving `existing` is fine.
79                if asset.creator_did > existing.creator_did {
80                    state.insert(asset.asset_id.clone(), asset.clone());
81                }
82            }
83        } else {
84            state.insert(asset.asset_id.clone(), asset.clone());
85        }
86    }
87
88    // Convert to sorted vec to ensure deterministic output
89    let mut merged: Vec<PlantedAsset> = state.into_values().collect();
90    merged.sort_by(|a, b| a.asset_id.cmp(&b.asset_id));
91    merged
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn test_merge_planted_assets() {
100        let asset1_v1 = PlantedAsset {
101            asset_id: "obj-1".into(),
102            cell_id: 1234,
103            position: [1.0, 2.0, 3.0],
104            rotation: [0.0, 0.0, 0.0, 1.0],
105            creator_did: "did:q42:alice".into(),
106            lamport: 1,
107            deleted: false,
108        };
109
110        let asset1_v2 = PlantedAsset {
111            asset_id: "obj-1".into(),
112            cell_id: 1234,
113            position: [1.0, 5.0, 3.0], // moved
114            rotation: [0.0, 0.0, 0.0, 1.0],
115            creator_did: "did:q42:alice".into(),
116            lamport: 2,
117            deleted: false,
118        };
119
120        let asset2 = PlantedAsset {
121            asset_id: "obj-2".into(),
122            cell_id: 1234,
123            position: [5.0, 5.0, 5.0],
124            rotation: [0.0, 0.0, 0.0, 1.0],
125            creator_did: "did:q42:bob".into(),
126            lamport: 1,
127            deleted: false,
128        };
129
130        let local = vec![asset1_v1.clone()];
131        let remote = vec![asset1_v2.clone(), asset2.clone()];
132
133        let merged = merge_planted_assets(&local, &remote);
134        assert_eq!(merged.len(), 2);
135
136        // V2 should overwrite V1 for obj-1
137        assert_eq!(merged[0].asset_id, "obj-1");
138        assert_eq!(merged[0].position[1], 5.0);
139
140        assert_eq!(merged[1].asset_id, "obj-2");
141    }
142
143    #[test]
144    fn spatial_sync_cell_filters_by_cell_and_tombstones() {
145        let active = PlantedAsset {
146            asset_id: "obj-a".into(),
147            cell_id: 42,
148            position: [0.0, 0.0, 0.0],
149            rotation: [0.0, 0.0, 0.0, 1.0],
150            creator_did: "did:q42:alice".into(),
151            lamport: 1,
152            deleted: false,
153        };
154        let tombstone = PlantedAsset {
155            asset_id: "obj-b".into(),
156            cell_id: 42,
157            position: [1.0, 0.0, 0.0],
158            rotation: [0.0, 0.0, 0.0, 1.0],
159            creator_did: "did:q42:bob".into(),
160            lamport: 2,
161            deleted: true,
162        };
163        let other_cell = PlantedAsset {
164            asset_id: "obj-c".into(),
165            cell_id: 99,
166            position: [2.0, 0.0, 0.0],
167            rotation: [0.0, 0.0, 0.0, 1.0],
168            creator_did: "did:q42:carol".into(),
169            lamport: 1,
170            deleted: false,
171        };
172
173        let cell = SpatialSyncCell::from_assets(42, &[active.clone(), tombstone, other_cell]);
174        assert_eq!(cell.cell_id, 42);
175        assert_eq!(cell.planted_assets.len(), 1);
176        assert_eq!(cell.planted_assets[0].asset_id, "obj-a");
177    }
178
179    #[test]
180    fn spatial_sync_cell_merge_applies_lww() {
181        let local = PlantedAsset {
182            asset_id: "obj-1".into(),
183            cell_id: 7,
184            position: [0.0, 0.0, 0.0],
185            rotation: [0.0, 0.0, 0.0, 1.0],
186            creator_did: "did:q42:alice".into(),
187            lamport: 1,
188            deleted: false,
189        };
190        let remote = PlantedAsset {
191            asset_id: "obj-1".into(),
192            cell_id: 7,
193            position: [5.0, 0.0, 0.0],
194            rotation: [0.0, 0.0, 0.0, 1.0],
195            creator_did: "did:q42:bob".into(),
196            lamport: 3,
197            deleted: false,
198        };
199
200        let mut cell = SpatialSyncCell::from_assets(7, &[local]);
201        cell.merge(&[remote]);
202        assert_eq!(cell.planted_assets.len(), 1);
203        assert_eq!(cell.planted_assets[0].position[0], 5.0);
204    }
205}