helios-persistence 0.1.43

Polyglot persistence layer for Helios FHIR Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Result merging strategies for composite storage.
//!
//! This module provides strategies for merging search results from multiple backends.
//!
//! # Merge Strategies
//!
//! | Strategy | Description | Use Case |
//! |----------|-------------|----------|
//! | Intersection | Results must appear in all sources | Precise filtering |
//! | Union | Results from any source | Broad search |
//! | PrimaryEnriched | Primary results, enriched by secondaries | Metadata augmentation |
//! | SecondaryFiltered | Filter secondary results through primary | Candidate validation |
//!
//! # Example
//!
//! ```ignore
//! use helios_persistence::composite::merger::{ResultMerger, MergeOptions, MergeStrategy};
//!
//! let merger = ResultMerger::new();
//!
//! let merged = merger.merge(
//!     primary_result,
//!     vec![("es".to_string(), es_result)],
//!     MergeOptions {
//!         strategy: MergeStrategy::Intersection,
//!         preserve_primary_order: true,
//!         deduplicate: true,
//!     },
//! )?;
//! ```

use std::collections::{HashMap, HashSet};

use crate::core::SearchResult;
use crate::error::StorageResult;
use crate::types::{Page, PageInfo, StoredResource};

use super::router::MergeStrategy;

/// Options for merging results.
#[derive(Debug, Clone)]
pub struct MergeOptions {
    /// The merge strategy to use.
    pub strategy: MergeStrategy,

    /// Whether to preserve the ordering from the primary result.
    pub preserve_primary_order: bool,

    /// Whether to deduplicate results.
    pub deduplicate: bool,
}

impl Default for MergeOptions {
    fn default() -> Self {
        Self {
            strategy: MergeStrategy::Intersection,
            preserve_primary_order: true,
            deduplicate: true,
        }
    }
}

/// Result merger for combining results from multiple backends.
pub struct ResultMerger {
    /// Maximum results to return.
    max_results: usize,
}

impl ResultMerger {
    /// Creates a new result merger.
    pub fn new() -> Self {
        Self { max_results: 1000 }
    }

    /// Creates a merger with a custom max results limit.
    pub fn with_max_results(mut self, max: usize) -> Self {
        self.max_results = max;
        self
    }

    /// Merges results from primary and auxiliary backends.
    pub fn merge(
        &self,
        primary: SearchResult,
        auxiliary: Vec<(String, SearchResult)>,
        options: MergeOptions,
    ) -> StorageResult<SearchResult> {
        match options.strategy {
            MergeStrategy::Intersection => self.merge_intersection(primary, auxiliary, &options),
            MergeStrategy::Union => self.merge_union(primary, auxiliary, &options),
            MergeStrategy::PrimaryEnriched => {
                self.merge_primary_enriched(primary, auxiliary, &options)
            }
            MergeStrategy::SecondaryFiltered => {
                self.merge_secondary_filtered(primary, auxiliary, &options)
            }
        }
    }

    /// Intersection merge: results must appear in all sources.
    fn merge_intersection(
        &self,
        primary: SearchResult,
        auxiliary: Vec<(String, SearchResult)>,
        options: &MergeOptions,
    ) -> StorageResult<SearchResult> {
        if auxiliary.is_empty() {
            return Ok(primary);
        }

        // Build set of IDs from each auxiliary source
        let aux_id_sets: Vec<HashSet<String>> = auxiliary
            .iter()
            .map(|(_, result)| result.resources.items.iter().map(resource_key).collect())
            .collect();

        // Filter primary to only include resources that appear in ALL auxiliary sets
        let mut filtered_items = Vec::new();
        for resource in primary.resources.items {
            let key = resource_key(&resource);
            if aux_id_sets.iter().all(|set| set.contains(&key)) {
                filtered_items.push(resource);
            }
        }

        // Limit results
        if filtered_items.len() > self.max_results {
            filtered_items.truncate(self.max_results);
        }

        // Combine included resources
        let mut all_included = primary.included;
        for (_, aux_result) in auxiliary {
            all_included.extend(aux_result.included);
        }

        if options.deduplicate {
            all_included = deduplicate_resources(all_included);
        }

        Ok(SearchResult {
            resources: Page::new(filtered_items, primary.resources.page_info),
            included: all_included,
            total: None, // Total is now uncertain due to filtering
        })
    }

    /// Union merge: results from any source (OR).
    fn merge_union(
        &self,
        primary: SearchResult,
        auxiliary: Vec<(String, SearchResult)>,
        options: &MergeOptions,
    ) -> StorageResult<SearchResult> {
        let mut all_resources = primary.resources.items;
        let mut seen_keys: HashSet<String> = all_resources.iter().map(resource_key).collect();

        // Add resources from auxiliary sources
        for (_, aux_result) in auxiliary {
            for resource in aux_result.resources.items {
                let key = resource_key(&resource);
                if !seen_keys.contains(&key) {
                    seen_keys.insert(key);
                    all_resources.push(resource);
                }
            }
        }

        // Sort if not preserving primary order
        if !options.preserve_primary_order {
            // Sort by last updated, descending
            all_resources.sort_by_key(|r| std::cmp::Reverse(r.last_modified()));
        }

        // Limit results
        if all_resources.len() > self.max_results {
            all_resources.truncate(self.max_results);
        }

        Ok(SearchResult {
            resources: Page::new(all_resources, primary.resources.page_info),
            included: primary.included,
            total: None,
        })
    }

    /// Primary enriched: primary results with metadata from secondaries.
    fn merge_primary_enriched(
        &self,
        primary: SearchResult,
        _auxiliary: Vec<(String, SearchResult)>,
        _options: &MergeOptions,
    ) -> StorageResult<SearchResult> {
        // For FHIR resources, we generally don't want to modify the content
        // This strategy is more about adding metadata that doesn't change resources
        // For now, just return primary results unchanged
        Ok(primary)
    }

    /// Secondary filtered: filter secondary results through primary.
    fn merge_secondary_filtered(
        &self,
        primary: SearchResult,
        auxiliary: Vec<(String, SearchResult)>,
        _options: &MergeOptions,
    ) -> StorageResult<SearchResult> {
        if auxiliary.is_empty() {
            return Ok(primary);
        }

        // Get IDs from all auxiliary sources (union of auxiliary IDs)
        let mut aux_ids: HashSet<String> = HashSet::new();
        for (_, aux_result) in &auxiliary {
            for resource in &aux_result.resources.items {
                aux_ids.insert(resource_key(resource));
            }
        }

        // Filter primary to only include resources that appear in auxiliary results
        let filtered_items: Vec<_> = primary
            .resources
            .items
            .into_iter()
            .filter(|r| aux_ids.contains(&resource_key(r)))
            .take(self.max_results)
            .collect();

        Ok(SearchResult {
            resources: Page::new(filtered_items, primary.resources.page_info),
            included: primary.included,
            total: None,
        })
    }

    /// Merges ID sets from multiple sources.
    pub fn merge_ids(&self, sources: Vec<Vec<String>>, strategy: MergeStrategy) -> Vec<String> {
        match strategy {
            MergeStrategy::Intersection => self.intersect_ids(sources),
            MergeStrategy::Union => self.union_ids(sources),
            _ => self.intersect_ids(sources),
        }
    }

    /// Computes intersection of ID sets.
    fn intersect_ids(&self, sources: Vec<Vec<String>>) -> Vec<String> {
        if sources.is_empty() {
            return Vec::new();
        }

        if sources.len() == 1 {
            return sources.into_iter().next().unwrap();
        }

        let mut sets: Vec<HashSet<String>> = sources
            .into_iter()
            .map(|v| v.into_iter().collect())
            .collect();

        // Sort by size (smallest first for efficiency)
        sets.sort_by_key(|s| s.len());

        let mut result: HashSet<String> = sets.remove(0);
        for set in sets {
            result = result.intersection(&set).cloned().collect();
        }

        result.into_iter().collect()
    }

    /// Computes union of ID sets.
    fn union_ids(&self, sources: Vec<Vec<String>>) -> Vec<String> {
        let mut result: HashSet<String> = HashSet::new();
        for source in sources {
            result.extend(source);
        }
        result.into_iter().collect()
    }
}

impl Default for ResultMerger {
    fn default() -> Self {
        Self::new()
    }
}

/// Creates a unique key for a resource.
fn resource_key(resource: &StoredResource) -> String {
    format!("{}/{}", resource.resource_type(), resource.id())
}

/// Deduplicates resources by their key.
fn deduplicate_resources(resources: Vec<StoredResource>) -> Vec<StoredResource> {
    let mut seen = HashSet::new();
    resources
        .into_iter()
        .filter(|r| seen.insert(resource_key(r)))
        .collect()
}

/// Weighted result for relevance-based merging.
#[derive(Debug, Clone)]
pub struct WeightedResult {
    /// The resource.
    pub resource: StoredResource,

    /// Relevance score (higher is better).
    pub score: f64,

    /// Source backend ID.
    pub source: String,
}

/// Relevance-based merger for search results.
pub struct RelevanceMerger {
    /// Backend weights for scoring.
    weights: HashMap<String, f64>,
}

impl RelevanceMerger {
    /// Creates a new relevance merger.
    pub fn new() -> Self {
        Self {
            weights: HashMap::new(),
        }
    }

    /// Sets weight for a backend.
    pub fn with_weight(mut self, backend_id: impl Into<String>, weight: f64) -> Self {
        self.weights.insert(backend_id.into(), weight);
        self
    }

    /// Merges results with relevance scoring.
    pub fn merge_with_relevance(
        &self,
        results: Vec<(String, SearchResult)>,
        max_results: usize,
    ) -> SearchResult {
        let mut weighted: Vec<WeightedResult> = Vec::new();

        for (source, result) in results {
            let base_weight = self.weights.get(&source).copied().unwrap_or(1.0);

            for (idx, resource) in result.resources.items.into_iter().enumerate() {
                // Score based on position and source weight
                // Earlier positions get higher scores
                let position_score = 1.0 / (idx as f64 + 1.0);
                let score = position_score * base_weight;

                weighted.push(WeightedResult {
                    resource,
                    score,
                    source: source.clone(),
                });
            }
        }

        // Sort by score descending
        weighted.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Deduplicate, keeping highest scored
        let mut seen = HashSet::new();
        let final_results: Vec<StoredResource> = weighted
            .into_iter()
            .filter(|w| seen.insert(resource_key(&w.resource)))
            .take(max_results)
            .map(|w| w.resource)
            .collect();

        SearchResult {
            resources: Page::new(final_results, PageInfo::end()),
            included: Vec::new(),
            total: None,
        }
    }
}

impl Default for RelevanceMerger {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tenant::TenantId;
    use helios_fhir::FhirVersion;

    fn make_resource(resource_type: &str, id: &str) -> StoredResource {
        StoredResource::new(
            resource_type,
            id,
            TenantId::new("test"),
            serde_json::json!({"resourceType": resource_type, "id": id}),
            FhirVersion::default(),
        )
    }

    fn make_result(resources: Vec<StoredResource>) -> SearchResult {
        SearchResult {
            resources: Page::new(resources, PageInfo::end()),
            included: Vec::new(),
            total: None,
        }
    }

    #[test]
    fn test_intersection_merge() {
        let merger = ResultMerger::new();

        let primary = make_result(vec![
            make_resource("Patient", "1"),
            make_resource("Patient", "2"),
            make_resource("Patient", "3"),
        ]);

        let aux = vec![(
            "es".to_string(),
            make_result(vec![
                make_resource("Patient", "2"),
                make_resource("Patient", "3"),
                make_resource("Patient", "4"),
            ]),
        )];

        let merged = merger.merge(primary, aux, MergeOptions::default()).unwrap();

        // Only 2 and 3 should remain (intersection)
        assert_eq!(merged.resources.len(), 2);
        let ids: Vec<_> = merged.resources.items.iter().map(|r| r.id()).collect();
        assert!(ids.contains(&"2"));
        assert!(ids.contains(&"3"));
    }

    #[test]
    fn test_union_merge() {
        let merger = ResultMerger::new();

        let primary = make_result(vec![
            make_resource("Patient", "1"),
            make_resource("Patient", "2"),
        ]);

        let aux = vec![(
            "es".to_string(),
            make_result(vec![
                make_resource("Patient", "2"),
                make_resource("Patient", "3"),
            ]),
        )];

        let merged = merger
            .merge(
                primary,
                aux,
                MergeOptions {
                    strategy: MergeStrategy::Union,
                    ..Default::default()
                },
            )
            .unwrap();

        // All unique resources (1, 2, 3)
        assert_eq!(merged.resources.len(), 3);
    }

    #[test]
    fn test_secondary_filtered_merge() {
        let merger = ResultMerger::new();

        let primary = make_result(vec![
            make_resource("Patient", "1"),
            make_resource("Patient", "2"),
            make_resource("Patient", "3"),
        ]);

        let aux = vec![(
            "graph".to_string(),
            make_result(vec![make_resource("Patient", "2")]),
        )];

        let merged = merger
            .merge(
                primary,
                aux,
                MergeOptions {
                    strategy: MergeStrategy::SecondaryFiltered,
                    ..Default::default()
                },
            )
            .unwrap();

        // Only 2 should remain (filtered by secondary)
        assert_eq!(merged.resources.len(), 1);
        assert_eq!(merged.resources.items[0].id(), "2");
    }

    #[test]
    fn test_id_intersection() {
        let merger = ResultMerger::new();

        let sources = vec![
            vec!["1".to_string(), "2".to_string(), "3".to_string()],
            vec!["2".to_string(), "3".to_string(), "4".to_string()],
            vec!["3".to_string(), "4".to_string(), "5".to_string()],
        ];

        let result = merger.merge_ids(sources, MergeStrategy::Intersection);
        assert_eq!(result.len(), 1);
        assert!(result.contains(&"3".to_string()));
    }

    #[test]
    fn test_id_union() {
        let merger = ResultMerger::new();

        let sources = vec![
            vec!["1".to_string(), "2".to_string()],
            vec!["3".to_string(), "4".to_string()],
        ];

        let result = merger.merge_ids(sources, MergeStrategy::Union);
        assert_eq!(result.len(), 4);
    }

    #[test]
    fn test_relevance_merge() {
        let merger = RelevanceMerger::new()
            .with_weight("primary", 2.0)
            .with_weight("search", 1.0);

        let results = vec![
            (
                "primary".to_string(),
                make_result(vec![
                    make_resource("Patient", "1"),
                    make_resource("Patient", "2"),
                ]),
            ),
            (
                "search".to_string(),
                make_result(vec![
                    make_resource("Patient", "3"),
                    make_resource("Patient", "1"), // duplicate
                ]),
            ),
        ];

        let merged = merger.merge_with_relevance(results, 10);

        // Patient 1 should be first (highest weight from primary)
        assert_eq!(merged.resources.items[0].id(), "1");
        // Should have 3 unique resources
        assert_eq!(merged.resources.len(), 3);
    }
}