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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
fn map_error(error: crate::Error) -> crate::wire::ErrorEnvelope {
error.into()
}
/// Typed identifier for the namespace a wire request targets. v1 is
/// single-namespace, so every successful resolve returns `root()`; the
/// type lets future multi-namespace routing land without churning call
/// sites (spec.md#wire-namespace-resolution).
#[derive(Debug, Clone)]
pub struct NamespaceIdent(pub Vec<String>);
impl NamespaceIdent {
pub fn root() -> Self {
Self(vec![])
}
pub fn as_table_id(&self, table_name: &str) -> Vec<String> {
let mut id = self.0.clone();
id.push(table_name.to_string());
id
}
}
/// The one and only namespace-resolution point; every wire handler funnels
/// through this. v1 accepts `None` or the default and returns the singleton
/// root namespace; everything else is a hard reject.
pub fn resolve_namespace(
namespace: Option<&str>,
) -> Result<NamespaceIdent, crate::wire::ErrorEnvelope> {
match namespace {
None | Some(crate::wire::DEFAULT_NAMESPACE) => Ok(NamespaceIdent::root()),
Some(other) => Err(map_error(crate::Error::namespace_unknown(other))),
}
}
fn map_storage(error: anyhow::Error) -> crate::wire::ErrorEnvelope {
// Classify before bucketing: an OCC commit-conflict exhaustion has its own
// wire code (spec.md#protocol). Everything else lands in `storage_unavailable`.
if let Some(conflict) = error.downcast_ref::<crate::substrate::ConflictExhausted>() {
return map_error(crate::Error::Conflict {
attempts: conflict.attempts,
});
}
map_error(crate::Error::Storage(error))
}
mod ingest_handler {
use anyhow::Result;
use tokio_stream::StreamExt;
use crate::{
adapter::{Adapter, AdapterYield, SkipOracle, SkipReason},
sessions::{IngestEvent, IngestSummary, IngestValidator, OutcomeStatus, RowOutcome, Store},
wire::{
ErrorBody, ErrorCode, IngestEnvelope, IngestRequest, IngestResponse, IngestResult,
IngestStatus, validate_protocol,
},
};
use super::{map_error, map_storage};
/// Hard cap on events per `pond_ingest` batch (spec.md#protocol).
pub const MAX_INGEST_EVENTS: usize = 1000;
/// Progress signals emitted by [`ingest_adapter`] for the CLI bar (and
/// any other observer). One [`SyncEvent::Discovered`] fires up front
/// once `adapter.discover()` returns; then one [`SyncEvent::SessionDone`]
/// fires per session as the validator commits it or the adapter skips
/// it. The adapter path never errors at the event level - every
/// per-session outcome is surfaced through this enum.
#[derive(Debug, Clone)]
pub enum SyncEvent {
/// Up-front session count from `adapter.discover()`. Emitted exactly
/// once before any `SessionDone`. When discovery fails, the field is
/// `None` and the bar runs in rolling-counter mode.
Discovered { total: Option<usize> },
/// One session finished: committed, skipped (undecodable source),
/// or rejected by the validator.
SessionDone(SessionOutcome),
}
/// What happened to one session in an adapter-driven sync.
#[derive(Debug, Clone)]
pub struct SessionOutcome {
/// Project/cwd the session ran in, when the adapter could parse it.
pub project: Option<String>,
/// Session id, when the source was decodable far enough to read one.
/// `None` means the file was unreadable before any `Session` event.
pub session_id: Option<String>,
/// Messages observed in the source stream (not the same as rows
/// written: validator-rejected sessions still report the count).
pub messages: usize,
pub status: SyncStatus,
}
/// Per-session outcome class.
///
/// - `Ok` - committed cleanly, zero drops.
/// - `Partial` - committed, but the validator dropped N events from this
/// session (per-event drop policy: bad-line skips, ordering violations,
/// duplicate ids). The non-bad events landed.
/// - `Skipped` - the adapter couldn't extract a Session header from this
/// file at all (empty `.jsonl`, header corruption). Nothing written.
/// - `Rejected` - the validator rejected the session at flush time on a
/// Session-level invariant (`source_agent` / `project` immutability).
/// The substream is dropped wholesale. This is the rare case where the
/// *whole* session is lost; for everything else use `Partial`.
#[derive(Debug, Clone)]
pub enum SyncStatus {
Ok,
Partial {
dropped_events: usize,
/// First drop's error message; subsequent drops counted, not
/// retained. Full detail at `POND_LOG=pond=debug`.
first_drop_reason: Option<String>,
},
Skipped {
reason: String,
},
Rejected {
reason: String,
},
/// Per-session staleness skip (spec.md#adapter-integrity-event-ordering): adapter short-circuited
/// the file decode because `mtime < MAX(messages.timestamp)`.
Fresh,
/// File produced no importable session (empty `.jsonl`, sidecar-only
/// rows, or an unextractable header). Benign: counted in
/// `skipped_empty`, never an error or a drop.
Empty,
}
#[derive(Debug, Default)]
struct InFlight {
project: Option<String>,
session_id: String,
messages: usize,
/// Events the adapter dropped mid-stream (skip-bad-line) that belong
/// to this in-flight session. Summed with the validator's per-event
/// drops at flush time to compute the final `SyncStatus::Partial`
/// count.
dropped_events: usize,
first_drop_reason: Option<String>,
/// The `index` value used when the Session event was pushed to the
/// validator. After batched flush, `RowOutcome.index` lets us match
/// per-session outcomes back to the originating session.
session_index: usize,
}
/// One session that has been fully observed but whose write hasn't
/// completed yet (queued in the validator's batched-flush buffer).
/// Emitted as `SyncEvent::SessionDone` after the corresponding flush
/// returns its outcomes.
#[derive(Debug)]
struct PendingDone {
project: Option<String>,
session_id: String,
messages: usize,
dropped_events: usize,
first_drop_reason: Option<String>,
session_index: usize,
}
/// Batch size used by the adapter ingest loop: flush every N completed
/// substreams to amortize per-commit cost. 100 is the value validated in
/// `benches/ingest_bench.rs` against the measured profile (substream
/// flushes were 78-88% of wall time at batch=1; ~25x fewer commits at
/// batch=100 closes most of that gap). Memory bound: ~N x (avg events
/// per session) staged in RAM, ~tens of MB at this scale.
const ADAPTER_FLUSH_BATCH: usize = 100;
/// Drain `adapter.events()` into `store`, accumulating an [`IngestSummary`]
/// and reporting progress through `on_event`. The adapter path is
/// CLI-driven (`pond sync`) and reports aggregates, not per-row results -
/// the wire-level [`pond_ingest`] handler keeps the per-row contract for
/// HTTP clients.
///
/// Undecodable session substreams are skipped, not warned: the design
/// contract (no silent drops) is met by surfacing each skip through
/// `on_event` as [`SyncStatus::Skipped`]. The tracing line stays available
/// at DEBUG for deep-debug; default verbosity is silent.
pub async fn ingest_adapter<F>(
store: &Store,
adapter: &dyn Adapter,
oracle: &dyn SkipOracle,
mut on_event: F,
) -> Result<IngestSummary>
where
F: FnMut(SyncEvent),
{
let mut summary = IngestSummary::default();
let truncations_before = crate::adapter::extract::truncated_values_count();
// Discovery is best-effort: a failure (no read perm, bad config)
// still lets the bar run as a rolling counter. We surface the count
// upfront when we can; otherwise the bar uses `set_length(0)`.
let total = adapter
.discover()
.await
.map_err(|error| tracing::debug!(%error, "adapter discover failed"))
.ok();
on_event(SyncEvent::Discovered { total });
let mut events = adapter.events_with(oracle);
let mut validator = IngestValidator::default();
// Adapter events have no stable input index (they stream from disk);
// assign a monotonic counter so RowOutcome.index stays unique even
// though the values aren't surfaced anywhere.
let mut index = 0usize;
let mut in_flight: Option<InFlight> = None;
// Sessions whose end-of-stream we've observed but whose write is
// still pending in the validator's batch buffer. Drained in FIFO
// order against `validator.flush()`'s outcome stream.
let mut pending_dones: std::collections::VecDeque<PendingDone> =
std::collections::VecDeque::new();
// Perf probe accumulators. Logged once at the end of the run under
// `POND_LOG=pond=info` so a single sync emits one tidy summary plus
// per-merge_insert lines from substrate. Visible only at INFO; never
// affects normal output.
let mut decode_total = std::time::Duration::ZERO;
let mut decode_count = 0u64;
let mut validator_total = std::time::Duration::ZERO;
let mut validator_count = 0u64;
let run_started = std::time::Instant::now();
loop {
let decode_start = std::time::Instant::now();
let next = events.next().await;
decode_total += decode_start.elapsed();
decode_count += 1;
let event = match next {
Some(event) => event,
None => break,
};
match event {
Ok(AdapterYield::Skipped {
session_id,
project,
reason,
}) => {
let status = match reason {
SkipReason::Fresh => {
summary.skipped_fresh += 1;
SyncStatus::Fresh
}
SkipReason::Empty => {
summary.skipped_empty += 1;
SyncStatus::Empty
}
};
on_event(SyncEvent::SessionDone(SessionOutcome {
project,
session_id,
messages: 0,
status,
}));
}
Ok(AdapterYield::Event(event)) => {
// A new Session means the current one is being closed
// out by the validator (moved to its `completed` buffer
// for batched flush). Stage the PendingDone so we can
// emit SessionDone with proper status after flush.
if matches!(&event, IngestEvent::Session(_))
&& let Some(prev) = in_flight.take()
{
pending_dones.push_back(PendingDone {
project: prev.project,
session_id: prev.session_id,
messages: prev.messages,
dropped_events: prev.dropped_events,
first_drop_reason: prev.first_drop_reason,
session_index: prev.session_index,
});
}
let event_index = index;
match &event {
IngestEvent::Session(session) => {
in_flight = Some(InFlight {
project: Some((*session.project).clone()),
session_id: session.id.clone(),
messages: 0,
dropped_events: 0,
first_drop_reason: None,
session_index: event_index,
});
}
IngestEvent::Message(_) => {
if let Some(slot) = in_flight.as_mut() {
slot.messages += 1;
}
}
IngestEvent::Part(_) => {}
}
let validator_start = std::time::Instant::now();
let push_outcomes = validator.push(store, index, event).await?;
validator_total += validator_start.elapsed();
validator_count += 1;
// Per-event drops returned synchronously by push (ordering
// / dup-id violations) attribute to the in-flight
// session's drop count. Session-level errors (e.g. empty
// source_agent) come back here too; we don't currently
// distinguish them - they're rare and end up in
// `summary.dropped_events`.
for outcome in &push_outcomes {
if matches!(outcome.status, OutcomeStatus::Error)
&& outcome.kind != "session"
&& let Some(slot) = in_flight.as_mut()
{
slot.dropped_events += 1;
if slot.first_drop_reason.is_none() {
slot.first_drop_reason =
outcome.error.as_ref().map(|err| err.message.clone());
}
}
}
summary.add_outcomes(&push_outcomes);
index += 1;
// Drain the batch periodically. The validator's
// `pending_substreams()` count grows by one each time we
// close a substream; once it hits the batch threshold we
// commit them in one parallel 3-table merge_insert.
if validator.pending_substreams() >= ADAPTER_FLUSH_BATCH {
let flush_start = std::time::Instant::now();
let flush_outcomes = validator.flush(store).await?;
validator_total += flush_start.elapsed();
validator_count += 1;
summary.add_outcomes(&flush_outcomes);
drain_pending_dones(&mut pending_dones, &flush_outcomes, &mut on_event);
}
}
Err(error) => {
// Per-event drop semantics: the adapter's error is either
// a pre-Session header failure (whole file unusable) or a
// mid-session bad-line skip. The validator is not reset
// on either case so subsequent good lines from the same
// file still land.
tracing::debug!(
%error,
"adapter event error (per-line drop by design)"
);
match in_flight.as_mut() {
Some(slot) => {
// Mid-session bad line. Charge one dropped event
// to this session; the bar will render the per-
// session summary at SessionDone time.
slot.dropped_events += 1;
if slot.first_drop_reason.is_none() {
slot.first_drop_reason = Some(error.to_string());
}
summary.dropped_events += 1;
}
None => {
// Pre-Session decode failure: no in-flight
// session to attribute to. This is a whole-file
// skip - surface it as a SessionDone with
// session_id=None and status=Skipped.
summary.skipped_files += 1;
on_event(SyncEvent::SessionDone(SessionOutcome {
project: None,
session_id: None,
messages: 0,
status: SyncStatus::Skipped {
reason: error.to_string(),
},
}));
}
}
}
}
}
if let Some(prev) = in_flight.take() {
pending_dones.push_back(PendingDone {
project: prev.project,
session_id: prev.session_id,
messages: prev.messages,
dropped_events: prev.dropped_events,
first_drop_reason: prev.first_drop_reason,
session_index: prev.session_index,
});
}
let validator_start = std::time::Instant::now();
let final_outcomes = validator.finish(store).await?;
validator_total += validator_start.elapsed();
validator_count += 1;
summary.add_outcomes(&final_outcomes);
drain_pending_dones(&mut pending_dones, &final_outcomes, &mut on_event);
summary.truncated_values = crate::adapter::extract::truncated_values_count()
.saturating_sub(truncations_before) as usize;
let total = run_started.elapsed();
let other = total
.saturating_sub(decode_total)
.saturating_sub(validator_total);
tracing::info!(
target: "pond::perf",
total_ms = total.as_millis() as u64,
decode_ms = decode_total.as_millis() as u64,
validator_ms = validator_total.as_millis() as u64,
other_ms = other.as_millis() as u64,
decode_calls = decode_count,
validator_calls = validator_count,
rows_inserted = summary.inserted as u64,
rows_matched = summary.matched as u64,
dropped_events = summary.dropped_events as u64,
dropped_sessions = summary.dropped_sessions as u64,
skipped_files = summary.skipped_files as u64,
skipped_fresh = summary.skipped_fresh as u64,
truncated_values = summary.truncated_values as u64,
"ingest_adapter complete"
);
Ok(summary)
}
/// Match the validator's flush outcomes back to the queued PendingDone
/// entries (FIFO; `RowOutcome.index` aligns with `PendingDone.session_index`).
/// Each matched PendingDone yields one `SyncEvent::SessionDone`. The queue
/// drains in order; if outcomes are missing for any (shouldn't happen with
/// a well-formed validator path), the SessionDone is emitted as Ok using
/// only the adapter-side drop count.
fn drain_pending_dones<F>(
queue: &mut std::collections::VecDeque<PendingDone>,
outcomes: &[RowOutcome],
on_event: &mut F,
) where
F: FnMut(SyncEvent),
{
// Index session-kind outcomes by their `index` value so we can look
// them up by `session_index` regardless of relative ordering.
let mut session_outcome_by_index: std::collections::HashMap<usize, &RowOutcome> =
std::collections::HashMap::new();
for outcome in outcomes {
if outcome.kind == "session" {
session_outcome_by_index.insert(outcome.index, outcome);
}
}
while let Some(done) = queue.pop_front() {
let session_outcome = session_outcome_by_index.get(&done.session_index).copied();
let rejection_reason = session_outcome.and_then(|outcome| {
if matches!(outcome.status, OutcomeStatus::Error) {
Some(
outcome
.error
.as_ref()
.map(|err| err.message.clone())
.unwrap_or_else(|| "session-level rejection".to_owned()),
)
} else {
None
}
});
let status = if let Some(reason) = rejection_reason {
SyncStatus::Rejected { reason }
} else if done.dropped_events > 0 {
SyncStatus::Partial {
dropped_events: done.dropped_events,
first_drop_reason: done.first_drop_reason,
}
} else {
SyncStatus::Ok
};
on_event(SyncEvent::SessionDone(SessionOutcome {
project: done.project,
session_id: Some(done.session_id),
messages: done.messages,
status,
}));
}
}
/// The `pond_ingest` wire handler (spec.md#protocol): validate the transport
/// envelope, then drive the event batch through [`ingest_events`]. Transport
/// failures (bad protocol, unknown namespace, empty or oversized batch) fail
/// the whole request via the spec.md#protocol; per-event failures land
/// in the response's `results[]` with `status: "error"`.
pub async fn pond_ingest(store: &Store, request: IngestRequest) -> IngestEnvelope {
if let Err(envelope) = validate_protocol(request.protocol_version) {
return IngestEnvelope::Error(envelope);
}
if let Err(envelope) = super::resolve_namespace(request.namespace.as_deref()) {
return IngestEnvelope::Error(envelope);
}
if request.events.is_empty() {
return IngestEnvelope::Error(map_error(crate::Error::validation_field(
"events must be a non-empty array",
"events",
Some(serde_json::json!([])),
Some("non-empty array".to_owned()),
)));
}
if request.events.len() > MAX_INGEST_EVENTS {
return IngestEnvelope::Error(map_error(crate::Error::validation_field(
format!("ingest batch exceeds the event cap: at most {MAX_INGEST_EVENTS} events"),
"events",
Some(serde_json::json!(request.events.len())),
Some(format!("at most {MAX_INGEST_EVENTS} events")),
)));
}
match ingest_events(store, request.events).await {
Ok(outcomes) => {
let mut accepted = 0;
let mut rejected = 0;
for outcome in &outcomes {
match outcome.status {
OutcomeStatus::Inserted | OutcomeStatus::Matched => accepted += 1,
OutcomeStatus::Error => rejected += 1,
}
}
let results = outcomes
.into_iter()
.map(outcome_to_result)
.collect::<Vec<_>>();
IngestEnvelope::Success(IngestResponse {
accepted,
rejected,
results,
})
}
Err(failure) => IngestEnvelope::Error(map_storage(failure)),
}
}
/// Drive a flat event batch through [`IngestValidator`], returning per-row
/// outcomes in input-array order. A substream that fails validation has
/// every one of its events tagged with [`OutcomeStatus::Error`] (the
/// offending event and any others in the same substream); ingest of later
/// sessions in the batch continues (spec.md#protocol).
pub async fn ingest_events(store: &Store, events: Vec<IngestEvent>) -> Result<Vec<RowOutcome>> {
let mut validator = IngestValidator::default();
let mut outcomes = Vec::with_capacity(events.len());
for (index, event) in events.into_iter().enumerate() {
let mut chunk = validator.push(store, index, event).await?;
outcomes.append(&mut chunk);
}
let mut tail = validator.finish(store).await?;
outcomes.append(&mut tail);
outcomes.sort_by_key(|outcome| outcome.index);
Ok(outcomes)
}
fn outcome_to_result(outcome: RowOutcome) -> IngestResult {
let (status, error) = match (outcome.status, outcome.error) {
(OutcomeStatus::Inserted, _) => (IngestStatus::Inserted, None),
(OutcomeStatus::Matched, _) => (IngestStatus::Matched, None),
(OutcomeStatus::Error, error) => {
let body = error
.map(|err| {
let mut details = serde_json::Map::new();
if let Some(field) = err.field {
details.insert("field".to_owned(), serde_json::json!(field));
}
if let Some(reason) = err.reason {
details.insert("reason".to_owned(), serde_json::json!(reason));
}
ErrorBody {
code: ErrorCode::ValidationFailed,
message: err.message,
details: serde_json::Value::Object(details),
}
})
.unwrap_or_else(|| ErrorBody {
code: ErrorCode::ValidationFailed,
message: "ingest failed".to_owned(),
details: serde_json::json!({}),
});
(IngestStatus::Error, Some(body))
}
};
IngestResult {
index: outcome.index,
kind: outcome.kind.to_owned(),
pk: outcome.pk,
status,
error,
}
}
}
pub use crate::sessions::{IngestEvent, IngestSummary, IngestValidator, search_text};
pub use ingest_handler::{
MAX_INGEST_EVENTS, SessionOutcome, SyncEvent, SyncStatus, ingest_adapter, ingest_events,
pond_ingest,
};
mod export_handler {
//! `pond_export` (spec.md#protocol): walk every session in the store and
//! emit its canonical event stream as JSONL - one `IngestEvent` per line.
//! The output is byte-identical with what `pond ingest` / `pond_ingest`
//! accepts on input, so `export | ingest` is a portable backup loop.
//! Sessions are emitted in lexicographic id order; within each session,
//! messages run in `(timestamp, message_id)` order and each message's
//! parts immediately follow in `ordinal` order. Matches the
//! spec.md#adapter-integrity-event-ordering ordering contract so the output
//! re-imports without re-ordering.
use anyhow::{Context, Result};
use tokio::io::{AsyncWrite, AsyncWriteExt};
use crate::sessions::{IngestEvent, Store};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExportSummary {
pub sessions: usize,
pub messages: usize,
pub parts: usize,
}
pub async fn pond_export<W>(
store: &Store,
session_filter: Option<&str>,
writer: &mut W,
) -> Result<ExportSummary>
where
W: AsyncWrite + Unpin,
{
let mut session_ids = match session_filter {
Some(id) => vec![id.to_owned()],
None => store.session_ids().await?,
};
session_ids.sort();
let mut summary = ExportSummary::default();
for session_id in session_ids {
let Some(stored) = store
.get_session(&session_id)
.await
.with_context(|| format!("export: failed to load session {session_id}"))?
else {
if session_filter.is_some() {
anyhow::bail!("export: session not found: {session_id}");
}
continue;
};
write_event(writer, &IngestEvent::Session(stored.session)).await?;
summary.sessions += 1;
for message_with_parts in stored.messages {
write_event(writer, &IngestEvent::Message(message_with_parts.message)).await?;
summary.messages += 1;
for part in message_with_parts.parts {
write_event(writer, &IngestEvent::Part(part)).await?;
summary.parts += 1;
}
}
}
writer.flush().await.context("export: flush failed")?;
Ok(summary)
}
async fn write_event<W>(writer: &mut W, event: &IngestEvent) -> Result<()>
where
W: AsyncWrite + Unpin,
{
let line = serde_json::to_string(event).context("export: serialize event")?;
writer
.write_all(line.as_bytes())
.await
.context("export: write event")?;
writer
.write_all(b"\n")
.await
.context("export: write newline")?;
Ok(())
}
}
pub use export_handler::{ExportSummary, pond_export};
mod restore_handler {
//! `restore_lineage` (spec.md#adapter-lineage-complete-restore): collect the named
//! session plus its direct subagent children for the `pond export session
//! --as` restore path. The spawn graph is one level deep; a collected
//! child that is itself a parent means a deeper graph, which is a typed
//! error - never a silently flattened restore.
use anyhow::{Context, Result, bail};
use crate::sessions::{SessionWithMessages, Store};
pub async fn restore_lineage(
store: &Store,
session_id: &str,
) -> Result<Vec<SessionWithMessages>> {
let Some(parent) = store.get_session(session_id).await? else {
bail!("export: session not found: {session_id}");
};
let mut sessions = vec![parent];
for child in store.child_sessions(session_id).await? {
if !store.child_sessions(&child.id).await?.is_empty() {
bail!(
"adapter-lineage-complete-restore supports one subagent level; session {} has child sessions",
child.id
);
}
let child_id = child.id;
let stored = store
.get_session(&child_id)
.await?
.with_context(|| format!("export: child session disappeared: {child_id}"))?;
sessions.push(stored);
}
Ok(sessions)
}
}
pub use restore_handler::restore_lineage;
mod get_handler {
use crate::{
sessions::{GetLookup, MessageViewParams, RetrievedMessage, SessionViewParams, Store},
wire::{
GetEnvelope, GetRequest, GetResponse, GetResult, GetSession, MessageView, PartSummary,
ResponseMode, ResponsePart, validate_protocol,
},
};
use super::{map_error, map_storage};
/// Project canonical retrieval data into the response DTO. In `verbatim` the
/// full parts ride `parts` and `text`/`content` are dropped - they would just
/// duplicate the inlined text part; otherwise the compact summary rides along
/// and full parts are elided.
fn to_message_view(message: RetrievedMessage, verbatim: bool) -> MessageView {
if verbatim {
return MessageView {
id: message.id,
role: message.role,
timestamp: message.timestamp,
text: None,
content: None,
parts_summary: Vec::new(),
parts: Some(
message
.parts
.into_iter()
.map(ResponsePart::from_part)
.collect(),
),
};
}
let parts_summary = message
.parts
.iter()
.filter_map(|part| PartSummary::for_kind(&part.kind))
.collect();
MessageView {
id: message.id,
role: message.role,
timestamp: message.timestamp,
text: message.text,
content: message.content,
parts_summary,
parts: None,
}
}
/// Server response budget, sized to the declared
/// `_meta["anthropic/maxResultSizeChars"]` cap (~200KB / ~50k tokens). The
/// server stops adding messages (or parts) when the next would exceed it;
/// `messages_remaining` / `target_parts_remaining` then signal pagination.
const BUDGET_BYTES: usize = 200_000;
pub async fn pond_get(store: &Store, request: GetRequest) -> GetEnvelope {
if let Err(error) = validate_protocol(request.protocol_version) {
return GetEnvelope::Error(error);
}
if let Err(envelope) = super::resolve_namespace(request.namespace.as_deref()) {
return GetEnvelope::Error(envelope);
}
let response = match (&request.session_id, &request.message_id) {
(Some(session_id), None) => session_result(store, session_id, &request).await,
(None, Some(message_id)) => message_result(store, message_id, &request).await,
(Some(_), Some(_)) => Err(map_error(crate::Error::validation_field(
"session_id and message_id are mutually exclusive",
"message_id",
request.message_id.clone().map(serde_json::Value::String),
Some("omit when session_id is present".to_owned()),
))),
(None, None) => Err(map_error(crate::Error::validation(
"one of session_id or message_id is required",
))),
};
match response {
Ok(response) => GetEnvelope::Success(response),
Err(error) => GetEnvelope::Error(error),
}
}
/// Map a stale/unknown `after_id` to a `validation_failed` naming the fix
/// (spec.md#protocol); `anchor_of` describes the id the client should supply.
fn unknown_after_id(request: &GetRequest, anchor_of: &str) -> crate::wire::ErrorEnvelope {
map_error(crate::Error::validation_field(
"after_id not found (stale or mistyped continuation anchor)",
"after_id",
request.after_id.clone().map(serde_json::Value::String),
Some(format!("a {anchor_of} from a prior page of this read")),
))
}
async fn session_result(
store: &Store,
session_id: &str,
request: &GetRequest,
) -> Result<GetResponse, crate::wire::ErrorEnvelope> {
let params = SessionViewParams {
mode: request.response_mode,
after_id: request.after_id.as_deref(),
limit: request.limit,
budget_bytes: BUDGET_BYTES,
};
let view = match store
.session_view(session_id, params)
.await
.map_err(map_storage)?
{
GetLookup::NotFound => {
return Err(map_error(crate::Error::not_found(
"session",
serde_json::json!(session_id),
format!("session not found: {session_id}"),
)));
}
GetLookup::UnknownAfterId => return Err(unknown_after_id(request, "message id")),
GetLookup::Found(view) => view,
};
let verbatim = matches!(request.response_mode, ResponseMode::Verbatim);
Ok(GetResponse {
session: GetSession::from_session(&view.session),
result: GetResult::Session {
messages: view
.messages
.into_iter()
.map(|message| to_message_view(message, verbatim))
.collect(),
messages_remaining: view.messages_remaining,
},
})
}
async fn message_result(
store: &Store,
message_id: &str,
request: &GetRequest,
) -> Result<GetResponse, crate::wire::ErrorEnvelope> {
let params = MessageViewParams {
context_depth: request.context_depth,
after_id: request.after_id.as_deref(),
limit: request.limit,
budget_bytes: BUDGET_BYTES,
};
let view = match store
.message_view(message_id, params)
.await
.map_err(map_storage)?
{
GetLookup::NotFound => {
return Err(map_error(crate::Error::not_found(
"message",
serde_json::json!(message_id),
format!("message not found: {message_id}"),
)));
}
GetLookup::UnknownAfterId => return Err(unknown_after_id(request, "part id")),
GetLookup::Found(view) => view,
};
// The target's body rides `target_parts` (paginated, full); carrying
// `text`/`content` on the header too would just duplicate it.
let target = MessageView {
id: view.target.id,
role: view.target.role,
timestamp: view.target.timestamp,
text: None,
content: None,
parts_summary: Vec::new(),
parts: None,
};
Ok(GetResponse {
session: GetSession::from_session(&view.session),
result: GetResult::Message {
target,
target_parts: view
.target_parts
.into_iter()
.map(ResponsePart::from_part)
.collect(),
target_parts_remaining: view.target_parts_remaining,
siblings: view
.siblings
.into_iter()
.map(|sibling| to_message_view(sibling, false))
.collect(),
},
})
}
}
pub use get_handler::pond_get;
mod search_handler {
//! The `pond_search` handler: hybrid (vector + BM25) retrieval at message
//! granularity, with filter pushdown and session-grouped responses
//! (spec.md#search).
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use crate::{
Clock, SystemClock,
embed::{Embedder, LazyEmbedder, format_query},
sessions::{MessageKey, MessageMeta, Store},
substrate::{Predicate, ScalarValue},
wire::{
ErrorEnvelope, PartSummary, ProjectFilter, Role, SearchCursor, SearchEnvelope,
SearchFilters, SearchRequest, SearchResponse, SearchResult, SearchSession,
validate_protocol,
},
};
use chrono::NaiveDate;
use std::collections::HashMap;
use super::{map_error, map_storage};
/// Internal branching enum for the retrieval mode. Production callers
/// never pick: the server decides hybrid-vs-FTS from embedder availability.
/// `Vector` exists for operator tooling - selected via `pond search --mode`
/// or the `mode_override` wire field consumed by `scripts/search-benchmarks/`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchMode {
Hybrid,
Fts,
Vector,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SearchPlan {
pub mode: SearchMode,
pub query: String,
/// When set, vector-only "find similar messages to this stored
/// message" mode: the stored vector for `similar_to` is the query;
/// `query` and FTS arm are ignored.
pub similar_to: Option<String>,
pub filter: Predicate,
pub filters: SearchFilters,
pub pool: usize,
pub vector_pool: usize,
pub limit: usize,
pub offset: usize,
pub min_score: f64,
}
const LIMIT_CAP: usize = 200;
const MAX_MATCHES_PER_SESSION: usize = 3;
const SEARCH_BUDGET_BYTES: usize = 60_000;
/// Centered query-windowed body returned on every hit (spec.md#search).
/// Calibrated for the agent-context budget: ~600 code points fits a typical
/// match site without crowding the 10k-token `pond_get` page.
const HIT_SNIPPET_CHARS: usize = 600;
const SCORE_DENOMINATOR: f64 = FTS_FUSION_WEIGHT + VECTOR_FUSION_WEIGHT;
// Score-normalized hybrid fusion weights (spec.md#search). Per-arm
// base_score is min-max normalized within the arm's pool, then the two
// arms are combined as w_fts * norm_fts + w_vec * norm_vec. The 0.135:1
// ratio was identified by `scripts/search-benchmarks/simulate_fusion.py` on the
// 111-query paraphrase set: a wide plateau at w_fts in [0.09, 0.14]
// (S@3 = 0.640-0.649), centroid 0.135. Symmetric across arms - no
// per-query routing; cross-lingual queries are an agent-layer concern
// (see the `pond_search` MCP description).
const FTS_FUSION_WEIGHT: f64 = 0.135;
const VECTOR_FUSION_WEIGHT: f64 = 1.0;
fn encode_search_cursor(cursor: &SearchCursor) -> String {
#[allow(clippy::expect_used)]
let bytes = serde_json::to_vec(cursor).expect("search cursor encodes as JSON");
URL_SAFE_NO_PAD.encode(bytes)
}
fn decode_search_cursor(raw: &str) -> Result<SearchCursor, ErrorEnvelope> {
let bytes = URL_SAFE_NO_PAD.decode(raw).map_err(|_| {
map_error(crate::Error::validation_field(
"cursor is malformed (expected opaque value from a prior response)",
"cursor",
Some(serde_json::json!(raw)),
Some("opaque base64url".to_owned()),
))
})?;
serde_json::from_slice(&bytes).map_err(|_| {
map_error(crate::Error::validation_field(
"cursor is malformed (decode failed)",
"cursor",
Some(serde_json::json!(raw)),
Some("opaque cursor from a prior response".to_owned()),
))
})
}
/// Run a hybrid or FTS-only search. The mode is server-determined - hybrid
/// when the store has any vectors, FTS-only otherwise. The embedder is
/// `LazyEmbedder`-loaded on the first hybrid/vector call, so FTS-only
/// corpora never pay the model load. The response has no top-level mode
/// field; retriever attribution stays in `explain_search_plan`.
///
/// Must run on a multi-threaded Tokio runtime: hybrid mode embeds the query via
/// `block_in_place`, which panics on a `current_thread` runtime.
pub async fn pond_search(
store: &Store,
embedder: &LazyEmbedder,
request: SearchRequest,
search: &crate::config::SearchConfig,
) -> SearchEnvelope {
match run_search(store, embedder, request, search, &SystemClock).await {
Ok(response) => SearchEnvelope::Success(response),
Err(envelope) => SearchEnvelope::Error(envelope),
}
}
pub async fn explain_search_plan(
store: &Store,
embedder: &LazyEmbedder,
request: SearchRequest,
search: &crate::config::SearchConfig,
) -> Result<String, ErrorEnvelope> {
let override_mode = request.mode_override.map(wire_mode_to_internal);
let mut plan = plan_search(request, SearchMode::Fts)?;
plan.mode = resolve_effective_mode(store, override_mode).await?;
let mut out = String::new();
if matches!(plan.mode, SearchMode::Fts | SearchMode::Hybrid) {
let fts = store
.explain_fts_plan(&plan.query, plan.pool, &plan.filter)
.await
.map_err(map_storage)?;
out.push_str("fts:\n");
out.push_str(&fts);
out.push('\n');
}
if matches!(plan.mode, SearchMode::Vector | SearchMode::Hybrid) {
let backend = load_embedder(embedder).await?;
let vector = embed_query(backend.as_ref(), &plan.query)?;
let vector_plan = store
.explain_vector_plan(&vector, plan.vector_pool, &plan.filter, Some(search))
.await
.map_err(map_storage)?;
out.push_str("vector:\n");
out.push_str(&vector_plan);
out.push('\n');
}
Ok(out)
}
async fn run_search(
store: &Store,
embedder: &LazyEmbedder,
request: SearchRequest,
search: &crate::config::SearchConfig,
_clock: &dyn Clock,
) -> Result<SearchResponse, ErrorEnvelope> {
let override_mode = request.mode_override.map(wire_mode_to_internal);
let mut plan = plan_search(request, SearchMode::Fts)?;
// `similar_to` pins mode to Vector regardless of override or store
// state: we are running kNN over a stored vector, not embedding a
// query, so there is no FTS arm and no query-side embedder load.
if plan.similar_to.is_some() {
plan.mode = SearchMode::Vector;
} else {
// Mode is server-determined unless the caller passed an explicit
// override (operator tooling). `has_embeddings()` is the only
// gate: hybrid when the store has any vectors, FTS-only when empty.
plan.mode = resolve_effective_mode(store, override_mode).await?;
}
let candidates = match plan.mode {
SearchMode::Fts => {
let hits = store
.fts_search(&plan.query, plan.pool, &plan.filter)
.await
.map_err(map_storage)?;
normalize_fts(hits)
}
SearchMode::Hybrid => {
let backend = load_embedder(embedder).await?;
let vector = embed_query(backend.as_ref(), &plan.query)?;
// The two retrievers hit disjoint datasets (and disjoint mutexes),
// so run them concurrently rather than back-to-back.
let fts_fut = async {
store
.fts_search(&plan.query, plan.pool, &plan.filter)
.await
.map_err(map_storage)
};
let vector_fut = async {
store
.vector_search(&vector, plan.vector_pool, &plan.filter, Some(search))
.await
.map_err(map_storage)
};
let (fts, vector_raw) = tokio::try_join!(fts_fut, vector_fut)?;
// Per-arm score shaping before fusion:
// - FTS: max-normalize raw BM25 (`score / max`) so the
// unbounded BM25 head doesn't dominate fusion when the
// query has one term that hits a rare phrase very hard.
// - Vector: rank-normalize the cosine-distance-ordered
// output (`1 - idx/n`); this is what the bench harness
// `simulate_fusion.py` was tuned against and what the
// vector-only path already emits as `base_score`.
// Fusion (`fuse_arms`) min-max normalizes again over the
// arm's full pool and weights the two arms by
// FTS_FUSION_WEIGHT and VECTOR_FUSION_WEIGHT.
let fts_max = fts.iter().map(|(_, s)| *s).fold(0.0_f32, f32::max);
let fts_entries: Vec<(MessageKey, f64)> = fts
.into_iter()
.map(|(key, score)| {
let normed = if fts_max > 0.0 {
f64::from(score / fts_max)
} else {
0.0
};
(key, normed)
})
.collect();
let vec_n = vector_raw.len() as f64;
let vector_entries: Vec<(MessageKey, f64)> = vector_raw
.into_iter()
.enumerate()
.map(|(idx, (key, _))| {
let normed = if vec_n > 0.0 {
1.0 - (idx as f64 / vec_n)
} else {
0.0
};
(key, normed)
})
.collect();
// FTS first: when both arms picked different messages from the
// same session_root, the fuser keeps FTS's representative
// (better for hit display since BM25 highlights the lexical
// match).
let lists = [
RankedList {
retriever: RetrieverKind::Fts,
entries: fts_entries,
weight: FTS_FUSION_WEIGHT,
},
RankedList {
retriever: RetrieverKind::Vector,
entries: vector_entries,
weight: VECTOR_FUSION_WEIGHT,
},
];
fuse_arms(&lists)
.into_iter()
.map(|hit| Candidate {
session_id: hit.key.session_id,
message_id: hit.key.message_id,
base_score: hit.score,
})
.collect()
}
// Vector-only branch. Reached two ways:
// - caller pinned `similar_to`: pond fetches the stored vector
// for that message_id and uses it directly as the query (no
// embedder load, no query-side text formatting).
// - caller set `mode_override = Vector` (operator tooling /
// benchmark harness): embed `plan.query` and run kNN.
SearchMode::Vector => {
let vector = if let Some(similar_id) = &plan.similar_to {
let stored = store
.message_vector_by_id(similar_id)
.await
.map_err(map_storage)?;
let Some(vector) = stored else {
return Err(map_error(crate::Error::not_found(
"message",
serde_json::json!(similar_id),
format!(
"no embedded message with id {similar_id} (the message may not \
exist, or it exists but is not yet embedded - run `pond embed`)"
),
)));
};
vector
} else {
let backend = load_embedder(embedder).await?;
embed_query(backend.as_ref(), &plan.query)?
};
let vector_raw = store
.vector_search(&vector, plan.vector_pool, &plan.filter, Some(search))
.await
.map_err(map_storage)?;
normalize_vector(vector_raw)
}
};
if candidates.is_empty() {
return Ok(empty_response());
}
// Hydrate hit metadata (timestamp, role, project, preview source) from
// the `messages` table - the retrievers return only message keys.
let keys = candidates
.iter()
.map(|candidate| MessageKey {
session_id: candidate.session_id.clone(),
message_id: candidate.message_id.clone(),
})
.collect::<Vec<_>>();
let metas = store
.message_metas_by_keys(&keys)
.await
.map_err(map_storage)?;
let meta_index = metas
.iter()
.map(|meta| ((meta.session_id.as_str(), meta.message_id.as_str()), meta))
.collect::<std::collections::HashMap<_, _>>();
let mut scored = Vec::with_capacity(candidates.len());
for candidate in candidates {
let Some(meta) =
meta_index.get(&(candidate.session_id.as_str(), candidate.message_id.as_str()))
else {
continue;
};
let score = candidate.base_score;
if score < plan.min_score {
continue;
}
scored.push(ScoredHit {
meta: (*meta).clone(),
score,
});
}
scored.sort_by(|left, right| {
right
.score
.partial_cmp(&left.score)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| left.meta.session_id.cmp(&right.meta.session_id))
.then_with(|| left.meta.message_id.cmp(&right.meta.message_id))
});
let matched_total = scored.len();
let sessions = build_sessions(store, &scored, &plan.query).await?;
page_sessions(sessions, matched_total, &plan)
}
/// Pick the retrieval mode. An explicit caller override (operator tooling
/// via the wire `mode_override` field / `pond search --mode`) wins; in its
/// absence the server runs hybrid when the store has any vectors and
/// FTS-only when it doesn't (`has_embeddings()` is the only gate).
async fn resolve_effective_mode(
store: &Store,
override_mode: Option<SearchMode>,
) -> Result<SearchMode, ErrorEnvelope> {
if let Some(mode) = override_mode {
return Ok(mode);
}
let has = store.has_embeddings().await.map_err(map_storage)?;
Ok(if has {
SearchMode::Hybrid
} else {
SearchMode::Fts
})
}
/// Materialize the lazy embedder on the first hybrid/vector branch that
/// needs it. Wraps the load error in an Internal envelope - candle/Metal
/// load failure is a server-side problem, not a caller error.
async fn load_embedder(
embedder: &LazyEmbedder,
) -> Result<std::sync::Arc<dyn Embedder>, ErrorEnvelope> {
embedder.get().await.map_err(|error| {
map_error(crate::Error::internal(format!(
"embedder load failed: {error}"
)))
})
}
pub fn plan_search(
request: SearchRequest,
mode: SearchMode,
) -> Result<SearchPlan, ErrorEnvelope> {
validate_protocol(request.protocol_version)?;
let _ns = super::resolve_namespace(request.namespace.as_deref())?;
let cursor = match request.cursor.as_deref() {
Some(raw) => Some(decode_search_cursor(raw)?),
None => None,
};
let (query_raw, similar_raw, filters, offset) = match cursor {
Some(cursor) => (
cursor.query,
cursor.similar_to,
cursor.filters,
cursor.offset,
),
None => (request.query, request.similar_to, request.filters, 0),
};
let query = query_raw.trim().to_owned();
let similar_to = similar_raw
.as_ref()
.map(|id| id.trim().to_owned())
.filter(|id| !id.is_empty());
if similar_to.is_none() && query.is_empty() {
return Err(map_error(crate::Error::validation_field(
"query must be non-empty after trim",
"query",
Some(serde_json::json!(query_raw)),
Some("non-empty string after trim, or pass `similar_to`".to_owned()),
)));
}
if request.limit == 0 {
return Err(map_error(crate::Error::validation_field(
"limit must be at least 1",
"limit",
Some(serde_json::json!(request.limit)),
Some("integer >= 1".to_owned()),
)));
}
let limit = request.limit.min(LIMIT_CAP);
let min_score = filters.min_score;
let filter = build_filter(&filters)?;
// Retriever candidate pool: wider than `limit` so the fuser has
// material to merge.
let pool = limit.saturating_mul(5).max(50);
Ok(SearchPlan {
mode,
query,
similar_to,
filter,
filters,
pool,
vector_pool: pool.saturating_mul(2),
limit,
offset,
min_score,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetrieverKind {
Vector,
Fts,
}
impl RetrieverKind {
fn as_wire(self) -> &'static str {
match self {
Self::Vector => "vector",
Self::Fts => "fts",
}
}
}
/// A retriever-ranked arm: scored hits best-first plus the arm's fusion
/// weight. `entries` carries each hit's raw `base_score` (BM25 for FTS,
/// cosine-similarity for the vector arm); the fuser min-max normalizes
/// those within the arm before combining across arms. `weight` is the
/// per-arm scalar that controls relative arm influence after
/// normalization.
pub struct RankedList {
pub retriever: RetrieverKind,
pub entries: Vec<(MessageKey, f64)>,
pub weight: f64,
}
/// Wire-to-internal mode mapping. Kept here so the wire type stays free of
/// handler-internal concerns and the conversion is one obvious place.
fn wire_mode_to_internal(wire: crate::wire::SearchModeWire) -> SearchMode {
match wire {
crate::wire::SearchModeWire::Fts => SearchMode::Fts,
crate::wire::SearchModeWire::Vector => SearchMode::Vector,
crate::wire::SearchModeWire::Hybrid => SearchMode::Hybrid,
}
}
/// One merged hybrid-fusion result.
#[derive(Debug, Clone, PartialEq)]
pub struct FusedHit {
pub key: MessageKey,
pub score: f64,
pub matched_via: Vec<String>,
}
/// Conversation root for grouping and per-arm dedup. The Claude Code adapter
/// stores sub-agent sessions under ids of the form `<parent-uuid>/agent-<id>`;
/// stripping at the first `/` yields the user-facing conversation root. Other
/// adapters (codex, etc.) use ids without `/` and pass through unchanged.
fn session_root(session_id: &str) -> &str {
match session_id.find('/') {
Some(idx) => &session_id[..idx],
None => session_id,
}
}
/// Score-normalized hybrid fusion keyed on the conversation root: for
/// each arm, the surviving (post intra-arm dedup-by-root) raw `base_score`
/// values are min-max normalized to [0, 1] across that arm's pool, then
/// summed across arms weighted by `RankedList.weight`. The representative
/// message_id is the first one each arm picked for the root; when both
/// arms picked different messages from the same root, the first arm in
/// the `lists` argument wins the representative (callers should list FTS
/// first when FTS-side provenance is preferred for the displayed hit).
/// Ties break on the representative key for determinism
/// (spec.md#search).
///
/// Why session-root keying instead of `(session_id, message_id)`: a long
/// session whose best FTS message and best vector message differ would
/// otherwise appear as two separate fused hits, neither getting the
/// cross-arm validation bonus. Keying on the root credits cross-arm
/// agreement at the conversation level - which is what the user sees.
///
/// Why per-arm score normalization instead of RRF: RRF discards score
/// magnitude (rank 1 contributes the same whether the vector cosine is
/// 0.85 or 0.55), and on paraphrase queries that magnitude is the load-
/// bearing signal. See `scripts/search-benchmarks/simulate_fusion.py` and
/// `docs/researches/embeddings/`.
pub fn fuse_arms(lists: &[RankedList]) -> Vec<FusedHit> {
let mut merged: std::collections::HashMap<String, (f64, Vec<String>, MessageKey)> =
std::collections::HashMap::new();
for list in lists {
if list.entries.is_empty() {
continue;
}
// Min-max normalize across the FULL arm pool BEFORE dedup. The
// benchmark simulator (scripts/search-benchmarks/simulate_fusion.py) and
// the production code MUST agree on the normalization basis;
// dedupping first would narrow [lo, hi] to only the surviving
// session-roots' scores and skew the normalized signal away
// from what the benchmark reports. A degenerate arm where every
// hit ties on raw score collapses to zero contribution; the
// other arm then decides the order.
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
for (_, raw) in &list.entries {
if *raw < lo {
lo = *raw;
}
if *raw > hi {
hi = *raw;
}
}
let range = hi - lo;
// Intra-arm dedup-by-root keeps the highest-scoring message
// each arm returned for a given conversation: without it a long
// session whose top-N hits all share a root would crowd out
// cross-arm signal from other sessions.
let mut seen_in_arm: std::collections::HashSet<String> =
std::collections::HashSet::new();
for (key, raw) in &list.entries {
let root = session_root(&key.session_id).to_owned();
if !seen_in_arm.insert(root.clone()) {
continue;
}
let norm = if range > 0.0 { (raw - lo) / range } else { 0.0 };
let contribution = list.weight * norm;
let entry = merged
.entry(root)
.or_insert_with(|| (0.0, Vec::new(), key.clone()));
entry.0 += contribution;
entry.1.push(list.retriever.as_wire().to_owned());
}
}
let mut hits = merged
.into_values()
.map(|(score, matched_via, key)| FusedHit {
key,
score,
matched_via,
})
.collect::<Vec<_>>();
hits.sort_by(|left, right| {
right
.score
.partial_cmp(&left.score)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| left.key.cmp(&right.key))
});
hits
}
/// Minimum query-term length considered "informative" for snippet
/// anchoring. Shorter terms ("how", "the", "is", "my", "at") attract the
/// `.min()` anchor to offset-near-0 because they occur very early in any
/// text, masking the real match site.
const ANCHOR_MIN_TERM_CHARS: usize = 4;
/// Build a hit's `text` payload (spec.md#search): the message body when
/// it fits within the snippet window, otherwise a query-windowed slice
/// centered on the first informative term. Bounded for the agent-context
/// budget; callers fetch the full body via `pond_get`.
pub fn hit_payload(text: &str, query: &str) -> String {
let chars_len = text.chars().count();
if chars_len <= HIT_SNIPPET_CHARS {
return text.to_owned();
}
query_snippet(text, query)
}
/// A snippet windowed around the first informative query term found in
/// `text`, capped at [`HIT_SNIPPET_CHARS`] code points. Falls back to the
/// text head when no term matches.
///
/// Terms shorter than [`ANCHOR_MIN_TERM_CHARS`] are excluded from anchor
/// selection because they pull the window to offset-0 (a snippet audit on
/// the live corpus found ~25-30% of conversational queries had their
/// anchor degraded by short stop-word-like terms like "how", "the", "my").
/// If every term is short, the filter is bypassed.
///
/// TODO(snippet-anchor): reassess for vector-only hits (e.g. similar_to,
/// paraphrase queries where no literal term matches): the fallback to
/// offset-0 is OK but not great. Possible upgrades: ngram match overlap,
/// or skip-window-around-most-distinctive-substring. See snippet audit
/// in tier-0 findings.
fn query_snippet(text: &str, query: &str) -> String {
let lower_text = text.to_lowercase();
let terms: Vec<String> = query
.split_whitespace()
.filter(|term| !term.is_empty())
.map(str::to_lowercase)
.collect();
let any_informative = terms
.iter()
.any(|term| term.chars().count() >= ANCHOR_MIN_TERM_CHARS);
let hit = terms
.iter()
.filter(|term| !any_informative || term.chars().count() >= ANCHOR_MIN_TERM_CHARS)
.filter_map(|term| lower_text.find(term.as_str()))
.min();
let chars: Vec<char> = text.chars().collect();
// `find` returned a byte offset into the lowercased copy; index that
// copy, not `text` - lowercasing can change byte length, so the offset
// is not necessarily a valid char boundary in the original.
let center = hit
.map(|byte| lower_text[..byte].chars().count())
.unwrap_or(0);
let half = HIT_SNIPPET_CHARS / 2;
let start = center.saturating_sub(half);
let end = (start + HIT_SNIPPET_CHARS).min(chars.len());
let start = end.saturating_sub(HIT_SNIPPET_CHARS);
// Truncation markers carry the omitted-char counts so the agent knows
// this is a windowed slice and roughly how much it's missing; the hit's
// `message_id` is the handle to fetch the rest via `pond_get`.
let mut snippet = String::new();
if start > 0 {
snippet.push_str(&format!("[{start} chars before] "));
}
snippet.extend(&chars[start..end]);
if end < chars.len() {
snippet.push_str(&format!(
" [+{} more chars; pond_get for full]",
chars.len() - end
));
}
snippet
}
struct Candidate {
session_id: String,
message_id: String,
base_score: f64,
}
struct ScoredHit {
meta: MessageMeta,
score: f64,
}
impl ScoredHit {
fn to_search_result(
&self,
query: &str,
summaries: &HashMap<(String, String), Vec<PartSummary>>,
) -> Result<SearchResult, ErrorEnvelope> {
let text = hit_payload(&self.meta.search_text, query);
let role = match self.meta.role.as_str() {
"system" => Role::System,
"user" => Role::User,
"assistant" => Role::Assistant,
"tool" => Role::Tool,
other => {
return Err(map_error(crate::Error::internal(format!(
"stored message has unknown role: {other}"
))));
}
};
// Only user hits earn a parts_summary (FilePart signal); see the
// rationale in spec.md#search.
let parts_summary = if matches!(role, Role::User) {
summaries
.get(&(self.meta.session_id.clone(), self.meta.message_id.clone()))
.cloned()
.unwrap_or_default()
} else {
Vec::new()
};
Ok(SearchResult {
message_id: self.meta.message_id.clone(),
role,
timestamp: self.meta.timestamp,
text,
score: normalize_score(self.score),
parts_summary,
})
}
}
fn normalize_score(score: f64) -> f64 {
(score / SCORE_DENOMINATOR).clamp(0.0, 1.0)
}
fn normalize_fts(hits: Vec<(MessageKey, f32)>) -> Vec<Candidate> {
let max = hits.iter().map(|(_, score)| *score).fold(0.0_f32, f32::max);
hits.into_iter()
.map(|(key, score)| Candidate {
session_id: key.session_id,
message_id: key.message_id,
base_score: if max > 0.0 {
f64::from(score / max)
} else {
0.0
},
})
.collect()
}
fn normalize_vector(hits: Vec<(MessageKey, f32)>) -> Vec<Candidate> {
let n = hits.len() as f64;
hits.into_iter()
.enumerate()
.map(|(idx, (key, _))| Candidate {
session_id: key.session_id,
message_id: key.message_id,
base_score: if n > 0.0 { 1.0 - (idx as f64 / n) } else { 0.0 },
})
.collect()
}
fn embed_query(embedder: &dyn Embedder, query: &str) -> Result<Vec<f32>, ErrorEnvelope> {
let prompt = format_query(query);
// Model inference is synchronous and CPU-bound; `block_in_place` keeps
// it from stalling other tasks on the async worker thread. (Requires a
// multi-threaded runtime - see `pond_search`.)
let vectors =
tokio::task::block_in_place(|| embedder.embed(&[prompt])).map_err(|error_value| {
map_error(crate::Error::internal(format!(
"failed to embed query: {error_value}"
)))
})?;
vectors.into_iter().next().ok_or_else(|| {
map_error(crate::Error::internal(
"embedder returned no vector for query",
))
})
}
async fn build_sessions(
store: &Store,
scored: &[ScoredHit],
query: &str,
) -> Result<Vec<SearchSession>, ErrorEnvelope> {
use std::collections::BTreeMap;
struct Acc {
project: String,
source_agent: String,
matched_count: usize,
matches: Vec<SearchResult>,
}
// Precompute part summaries for user-role hits, grouped by their actual
// session id (a subagent hit's parts live under `root/agent-...`, not
// the grouping root).
let mut user_ids_by_session: BTreeMap<String, Vec<String>> = BTreeMap::new();
for hit in scored {
if hit.meta.role == "user" {
user_ids_by_session
.entry(hit.meta.session_id.clone())
.or_default()
.push(hit.meta.message_id.clone());
}
}
let mut summaries: HashMap<(String, String), Vec<PartSummary>> = HashMap::new();
for (session_id, message_ids) in &user_ids_by_session {
for (key, parts) in store
.summary_parts_for_messages(session_id, message_ids)
.await
.map_err(map_storage)?
{
summaries.insert(
key,
parts
.iter()
.filter_map(|part| PartSummary::for_kind(&part.kind))
.collect(),
);
}
}
let mut groups: BTreeMap<String, Acc> = BTreeMap::new();
for hit in scored {
let root = session_root(&hit.meta.session_id).to_owned();
let entry = groups.entry(root).or_insert_with(|| Acc {
project: hit.meta.project.clone(),
source_agent: hit.meta.source_agent.clone(),
matched_count: 0,
matches: Vec::new(),
});
entry.matched_count += 1;
entry.matches.push(hit.to_search_result(query, &summaries)?);
}
let session_ids = groups.keys().cloned().collect::<Vec<_>>();
let counts = store
.session_message_counts(&session_ids)
.await
.map_err(map_storage)?;
let mut result = groups
.into_iter()
.map(|(session_id, mut acc)| {
acc.matches.sort_by(|left, right| {
right
.score
.partial_cmp(&left.score)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| left.message_id.cmp(&right.message_id))
});
acc.matches.truncate(MAX_MATCHES_PER_SESSION);
SearchSession {
session_messages_count: counts.get(&session_id).copied().unwrap_or_default(),
session_id,
project: acc.project,
source_agent: acc.source_agent,
matched_message_count: acc.matched_count,
matches: acc.matches,
}
})
.collect::<Vec<_>>();
result.sort_by(|left, right| {
let left_score = left
.matches
.first()
.map(|hit| hit.score)
.unwrap_or_default();
let right_score = right
.matches
.first()
.map(|hit| hit.score)
.unwrap_or_default();
right_score
.partial_cmp(&left_score)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| left.session_id.cmp(&right.session_id))
});
Ok(result)
}
fn page_sessions(
sessions: Vec<SearchSession>,
matched_total: usize,
plan: &SearchPlan,
) -> Result<SearchResponse, ErrorEnvelope> {
if plan.offset >= sessions.len() {
return Ok(SearchResponse {
sessions: Vec::new(),
matched_total,
has_more: false,
next_cursor: None,
});
}
let mut emitted = Vec::new();
let mut used_bytes = 0usize;
for session in sessions.iter().skip(plan.offset) {
if emitted.len() >= plan.limit {
break;
}
let bytes = serde_json::to_string(session)
.map_err(|error| {
map_error(crate::Error::internal(format!(
"failed to size search response session: {error}"
)))
})?
.len();
if !emitted.is_empty() && used_bytes.saturating_add(bytes) > SEARCH_BUDGET_BYTES {
break;
}
used_bytes = used_bytes.saturating_add(bytes);
emitted.push(session.clone());
}
let next_offset = plan.offset + emitted.len();
let has_more = next_offset < sessions.len();
let next_cursor = has_more.then(|| {
encode_search_cursor(&SearchCursor {
query: plan.query.clone(),
similar_to: plan.similar_to.clone(),
filters: plan.filters.clone(),
offset: next_offset,
})
});
Ok(SearchResponse {
sessions: emitted,
matched_total,
has_more,
next_cursor,
})
}
/// Build the shared scalar filter predicate pushed into both retrievers.
/// Both the FTS and vector retrievers scan `messages` (spec.md#datasets),
/// so one predicate serves both.
pub fn build_filter(filters: &SearchFilters) -> Result<Predicate, ErrorEnvelope> {
let mut clauses = Vec::new();
match &filters.project {
None => {}
Some(ProjectFilter::Contains(value)) => {
clauses.push(Predicate::LikeContains("project", value.clone()));
}
Some(ProjectFilter::Regex(pattern)) => {
clauses.push(Predicate::Regex("project", pattern.clone()));
}
}
if let Some(session_id) = &filters.session_id {
clauses.push(Predicate::Eq("session_id", session_id.clone().into()));
}
if let Some(source_agent) = &filters.source_agent {
clauses.push(Predicate::Eq("source_agent", source_agent.clone().into()));
}
if let Some(role) = &filters.role {
if !matches!(role.as_str(), "user" | "assistant" | "system" | "tool") {
return Err(map_error(crate::Error::validation_field(
format!(
"filters.role must be one of: user, assistant, system, tool; got {role}"
),
"filters.role",
Some(serde_json::json!(role)),
Some("one of: user, assistant, system, tool".to_owned()),
)));
}
clauses.push(Predicate::Eq("role", role.clone().into()));
}
if let Some(from_date) = &filters.from_date {
clauses.push(Predicate::Gte(
"timestamp",
ScalarValue::Raw(date_bound(from_date, "filters.from_date", false)?),
));
}
if let Some(to_date) = &filters.to_date {
clauses.push(Predicate::Lte(
"timestamp",
ScalarValue::Raw(date_bound(to_date, "filters.to_date", true)?),
));
}
Ok(Predicate::And(clauses))
}
/// Parse a `YYYY-MM-DD` filter date into a timestamp literal. `end_of_day`
/// pushes `to_date` to the inclusive end of the day.
fn date_bound(date: &str, field: &str, end_of_day: bool) -> Result<String, ErrorEnvelope> {
NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| {
map_error(crate::Error::validation_field(
format!("{field} must be in YYYY-MM-DD format; got {date}"),
field,
Some(serde_json::json!(date)),
Some("YYYY-MM-DD".to_owned()),
))
})?;
let time = if end_of_day { "23:59:59" } else { "00:00:00" };
Ok(format!("timestamp '{date} {time}'"))
}
fn empty_response() -> SearchResponse {
SearchResponse {
sessions: Vec::new(),
matched_total: 0,
has_more: false,
next_cursor: None,
}
}
#[cfg(test)]
mod fusion_helpers_tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::*;
#[test]
fn session_root_strips_agent_suffix_for_claude_code_subagents() {
assert_eq!(
session_root("94a50f23-1234-5678-9abc-def012345678"),
"94a50f23-1234-5678-9abc-def012345678",
);
assert_eq!(
session_root("94a50f23-1234-5678-9abc-def012345678/agent-abc123"),
"94a50f23-1234-5678-9abc-def012345678",
);
// Multiple slashes: still cut at the first one (defensive).
assert_eq!(session_root("root/a/b"), "root");
}
#[test]
fn fuse_arms_dedupes_intra_arm_by_session_root_and_credits_cross_arm() {
let mk = |sid: &str, mid: &str| crate::sessions::MessageKey {
session_id: sid.to_owned(),
message_id: mid.to_owned(),
};
// FTS pool (raw BM25): session-A msg-1 (10.0), session-A msg-2
// (9.0, same root, dropped by intra-arm dedup), session-B msg-3
// (6.0), session-A/agent-x msg-4 (5.0, same root as A, dropped).
// Vector pool (raw cosine): session-B msg-7 (0.9, different
// message than FTS's pick for B), session-A msg-9 (0.6).
let fts = RankedList {
retriever: RetrieverKind::Fts,
entries: vec![
(mk("session-A", "msg-1"), 10.0),
(mk("session-A", "msg-2"), 9.0),
(mk("session-B", "msg-3"), 6.0),
(mk("session-A/agent-x", "msg-4"), 5.0),
],
weight: 0.135,
};
let vec_arm = RankedList {
retriever: RetrieverKind::Vector,
entries: vec![
(mk("session-B", "msg-7"), 0.9),
(mk("session-A", "msg-9"), 0.6),
],
weight: 1.0,
};
let merged = fuse_arms(&[fts, vec_arm]);
// Output: one row per session_root after intra-arm dedup.
assert_eq!(merged.len(), 2);
// Per-arm min-max over the FULL pool BEFORE dedup:
// FTS pool [10, 9, 6, 5]: range 5. A's first hit (10) -> 1.0;
// B's first hit (6) -> 0.2.
// Vector pool [0.9, 0.6]: range 0.3. B -> 1.0; A -> 0.0.
// session-A: 0.135 * 1.0 + 1.0 * 0.0 = 0.135.
// session-B: 0.135 * 0.2 + 1.0 * 1.0 = 1.027. B wins.
assert_eq!(merged[0].key.session_id, "session-B");
// FTS was listed first, so FTS's pick (msg-3) wins the
// representative over Vector's pick (msg-7) for session-B.
assert_eq!(merged[0].key.message_id, "msg-3");
assert_eq!(merged[0].matched_via, vec!["fts", "vector"]);
assert_eq!(merged[1].key.session_id, "session-A");
assert_eq!(merged[1].key.message_id, "msg-1");
assert_eq!(merged[1].matched_via, vec!["fts", "vector"]);
}
#[test]
fn fuse_arms_collapses_degenerate_tied_arm_to_zero_contribution() {
// When every surviving hit in an arm shares the same raw score,
// min-max normalization has zero range; that arm contributes 0
// and the other arm decides the order on its own normalized
// signal. This protects fusion from "flat" arms (e.g. an FTS arm
// whose BM25 scores all tie at the same low magnitude).
let mk = |sid: &str, mid: &str| crate::sessions::MessageKey {
session_id: sid.to_owned(),
message_id: mid.to_owned(),
};
let fts = RankedList {
retriever: RetrieverKind::Fts,
entries: vec![(mk("session-A", "a"), 1.0), (mk("session-B", "b"), 1.0)],
weight: 0.135,
};
let vec_arm = RankedList {
retriever: RetrieverKind::Vector,
entries: vec![(mk("session-A", "a"), 0.9), (mk("session-B", "b"), 0.3)],
weight: 1.0,
};
let merged = fuse_arms(&[fts, vec_arm]);
// Vector arm alone decides: A's normalized 1.0 beats B's 0.0.
assert_eq!(merged[0].key.session_id, "session-A");
assert!((merged[0].score - 1.0).abs() < 1e-9);
assert!(merged[1].score.abs() < 1e-9);
}
}
}
pub use search_handler::{
FusedHit, RankedList, RetrieverKind, SearchMode, SearchPlan, build_filter, explain_search_plan,
fuse_arms, hit_payload, plan_search, pond_search,
};
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used)]
use super::*;
use crate::wire::{ProjectFilter, SearchFilters, SearchRequest};
use chrono::Utc;
fn search_request(query: &str) -> SearchRequest {
SearchRequest {
protocol_version: crate::PROTOCOL_VERSION,
namespace: Some("local".to_owned()),
query: query.to_owned(),
mode_override: None,
similar_to: None,
filters: SearchFilters::default(),
limit: 20,
cursor: None,
}
}
fn key(session: &str, id: &str) -> crate::sessions::MessageKey {
crate::sessions::MessageKey {
session_id: session.to_owned(),
message_id: id.to_owned(),
}
}
#[test]
fn fuse_arms_fuses_retrievers_and_reports_provenance() {
// Each session contributes at most one ballot per arm; cross-arm
// agreement is credited per session_root, not per message_id.
// Vector pool (raw cosine): a=0.9, b=0.7, c=0.5.
// FTS pool (raw BM25): b=10.0, a=8.0, d=4.0.
let lists = [
RankedList {
retriever: RetrieverKind::Vector,
entries: vec![
(key("session-a", "a"), 0.9),
(key("session-b", "b"), 0.7),
(key("session-c", "c"), 0.5),
],
weight: 1.0,
},
RankedList {
retriever: RetrieverKind::Fts,
entries: vec![
(key("session-b", "b"), 10.0),
(key("session-a", "a"), 8.0),
(key("session-d", "d"), 4.0),
],
weight: 0.135,
},
];
let merged = fuse_arms(&lists);
// Vector normalized: a=1.0, b=0.5, c=0.0.
// FTS normalized: b=1.0, a=2/3, d=0.0.
// session-a: 1.0 * 1.0 + 0.135 * 2/3 = 1.090
// session-b: 1.0 * 0.5 + 0.135 * 1.0 = 0.635
// session-c: 1.0 * 0.0 + 0 = 0
// session-d: 0 + 0.135 * 0.0 = 0
assert_eq!(merged[0].key.session_id, "session-a");
assert_eq!(merged[1].key.session_id, "session-b");
assert_eq!(merged[0].matched_via, vec!["vector", "fts"]);
assert!(merged[0].score > merged[1].score);
let c = merged
.iter()
.find(|hit| hit.key.session_id == "session-c")
.unwrap();
assert_eq!(c.matched_via, vec!["vector"]);
let d = merged
.iter()
.find(|hit| hit.key.session_id == "session-d")
.unwrap();
assert_eq!(d.matched_via, vec!["fts"]);
}
#[test]
fn hit_payload_returns_short_text_in_full() {
let short = "a short message body";
let text = hit_payload(short, "message");
assert_eq!(text, short, "small text is returned as-is");
}
#[test]
fn hit_payload_windows_long_text_around_the_query_term() {
// ~2400 chars: filler head, query term mid-body, filler tail.
let body = format!("{}NEEDLE{}", "a".repeat(2000), "b".repeat(394));
let text = hit_payload(&body, "needle");
assert!(
text.contains("NEEDLE"),
"text is the match-windowed snippet: {text}"
);
// The <=600-char window is wrapped with truncation markers
// ("[N chars before] " / " [+N more chars; pond_get for full]"); allow for their length.
assert!(
text.chars().count() <= 600 + 64,
"snippet window is bounded by HIT_SNIPPET_CHARS plus markers: {}",
text.chars().count()
);
}
#[test]
fn hit_payload_snippet_survives_case_folding_that_changes_byte_length() {
// `to_lowercase` of 'İ' is two code points, so the lowercased copy has
// a different byte layout than the original. A query offset taken from
// that copy must never be sliced into the original text.
let body = format!("İÉÉÉ{}", "a".repeat(2100));
let text = hit_payload(&body, "ééé");
assert!(
text.contains("ÉÉÉ"),
"snippet windows on the matched term: {text}"
);
}
#[tokio::test]
async fn restore_lineage_rejects_a_graph_nesting_deeper_than_one_level() {
use crate::adapter::Extracted;
use crate::sessions::Store;
use crate::wire::{ProviderOptions, Session};
use tempfile::TempDir;
let session = |id: &str, parent: Option<&str>| Session {
id: id.to_owned(),
parent_session_id: parent.map(str::to_owned),
parent_message_id: None,
source_agent: "claude-code".to_owned(),
created_at: Utc::now(),
project: Extracted::from_test_value("/tmp/pond".to_owned()),
options: ProviderOptions::new(),
};
let dir = TempDir::new().unwrap();
let store = Store::open_local(dir.path()).await.unwrap();
// A -> B -> C is a two-level spawn graph; spec 6.2 caps lineage at one.
store
.upsert_sessions(&[
session("a", None),
session("b", Some("a")),
session("c", Some("b")),
])
.await
.unwrap();
// Restoring A reaches child B, then finds B is itself a parent of C.
let err = restore_lineage(&store, "a").await.unwrap_err();
assert!(
err.to_string().contains("one subagent level"),
"expected the deeper-graph error, got: {err}"
);
// Restoring B is a clean one-level graph: B plus its single child C.
let lineage = restore_lineage(&store, "b").await.unwrap();
let ids: Vec<&str> = lineage.iter().map(|s| s.session.id.as_str()).collect();
assert_eq!(ids, ["b", "c"]);
}
#[test]
fn build_filter_pushes_down_each_predicate_and_handles_empty() {
let filters = SearchFilters {
project: Some(ProjectFilter::Contains("/Users/me/pond".to_owned())),
session_id: Some("01HXY".to_owned()),
source_agent: Some("claude-code".to_owned()),
role: Some("assistant".to_owned()),
from_date: Some("2026-01-01".to_owned()),
to_date: Some("2026-05-01".to_owned()),
min_score: 0.0,
};
let sql = build_filter(&filters).unwrap().to_lance();
assert!(sql.contains("project LIKE '%/Users/me/pond%'"));
assert!(sql.contains("session_id = '01HXY'"));
assert!(sql.contains("source_agent = 'claude-code'"));
assert!(sql.contains("role = 'assistant'"));
assert!(sql.contains("timestamp >="));
assert!(sql.contains("timestamp <="));
// Empty filters produce no predicate.
assert_eq!(
build_filter(&SearchFilters::default()).unwrap().to_lance(),
"",
);
}
#[test]
fn build_filter_rejects_bad_role_and_date() {
let bad_role = SearchFilters {
role: Some("wizard".to_owned()),
..SearchFilters::default()
};
assert!(build_filter(&bad_role).is_err());
let bad_date = SearchFilters {
from_date: Some("01-01-2026".to_owned()),
..SearchFilters::default()
};
assert!(build_filter(&bad_date).is_err());
}
#[test]
fn build_filter_contains_escapes_like_wildcards() {
let filters = SearchFilters {
project: Some(ProjectFilter::Contains("/Users/me/my_project".to_owned())),
..SearchFilters::default()
};
let sql = build_filter(&filters).unwrap().to_lance();
// `_` is a LIKE wildcard and is everywhere in real paths; it must be escaped
// so `my_project` matches literally, with an ESCAPE clause naming the char.
assert!(
sql.contains(r"my\_project"),
"underscore must be escaped: {sql}"
);
assert!(
sql.contains(r"ESCAPE '\'"),
"predicate must declare the escape char: {sql}"
);
}
#[test]
fn plan_search_shapes_request_for_each_planning_input() {
let mut request = search_request(" vector memory ");
request.limit = 500;
request.filters.min_score = 0.42;
let plan = plan_search(request, SearchMode::Hybrid).unwrap();
assert_eq!(plan.mode, SearchMode::Hybrid);
assert_eq!(plan.query, "vector memory");
assert_eq!(plan.limit, 200);
assert_eq!(plan.pool, 1000);
assert_eq!(plan.vector_pool, 2000);
assert_eq!(plan.min_score, 0.42);
// Case 2: a tiny limit floors the pools so retrievers don't starve.
let mut request = search_request("tiny pool");
request.limit = 1;
let plan = plan_search(request, SearchMode::Fts).unwrap();
assert_eq!(plan.mode, SearchMode::Fts);
assert_eq!(plan.limit, 1);
assert_eq!(plan.pool, 50);
assert_eq!(plan.vector_pool, 100);
// Case 3: filters get plumbed into the shared filter predicate.
let mut request = search_request("filtered");
request.filters.project = Some(ProjectFilter::Contains("/Users/me/pond".to_owned()));
request.filters.role = Some("assistant".to_owned());
let plan = plan_search(request, SearchMode::Fts).unwrap();
let sql = plan.filter.to_lance();
assert!(sql.contains("project LIKE"));
assert!(sql.contains("role = 'assistant'"));
}
#[test]
fn plan_search_rejects_invalid_composition_before_execution() {
let mut blank = search_request(" ");
let error = plan_search(blank.clone(), SearchMode::Fts)
.unwrap_err()
.error;
assert_eq!(error.code, crate::wire::ErrorCode::ValidationFailed);
assert_eq!(error.details["field"], "query");
blank.query = "valid".to_owned();
blank.limit = 0;
let error = plan_search(blank.clone(), SearchMode::Fts)
.unwrap_err()
.error;
assert_eq!(error.details["field"], "limit");
blank.limit = 1;
blank.namespace = Some("remote".to_owned());
let error = plan_search(blank, SearchMode::Fts).unwrap_err().error;
assert_eq!(error.code, crate::wire::ErrorCode::NamespaceUnknown);
assert_eq!(error.details["namespace"], "remote");
}
}