pond-db 0.19.6

Lossless storage and search for sessions from any AI agent client
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
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
//! `pond_sql`: read-only DataFusion SQL over the three Lance tables
//! (`sessions` / `messages` / `parts`), registered as `LanceTableProvider`s
//! (behind plan-time views that rename `id` to `message_id` / `session_id`)
//! on a fresh per-call `SessionContext`. Read-only is enforced in two layers - a
//! single-`SELECT` pre-parse and `sql_with_options` with DDL/DML/statements all
//! disabled - so no statement that mutates the corpus or touches the filesystem
//! (INSERT/UPDATE/DELETE/CREATE/DROP/COPY/CREATE EXTERNAL TABLE/SET) can run.
//! Results render inline (row-capped), as JSON rows (the HTTP `/v1/x/sql`
//! route), or export to a parquet/ndjson file the caller fetches via the
//! `pond-sql-export://` resource (`src/transport.rs`).

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::anyhow;
use arrow_json::LineDelimitedWriter;
use lance::Dataset;
use lance::datafusion::LanceTableProvider;
use lance::deps::arrow_array::builder::{
    BooleanBuilder, Float64Builder, Int64Builder, StringBuilder,
};
use lance::deps::arrow_array::cast::AsArray;
use lance::deps::arrow_array::types::{
    ArrowTimestampType, TimestampMicrosecondType, TimestampMillisecondType,
    TimestampNanosecondType, TimestampSecondType,
};
use lance::deps::arrow_array::{
    Array, ArrayRef, GenericStringArray, LargeBinaryArray, OffsetSizeTrait, RecordBatch,
    StringArray, StringViewArray,
};
use lance::deps::arrow_schema::{ArrowError, DataType, Field, Schema, SchemaRef, TimeUnit};
use lance::deps::datafusion::arrow::util::pretty::pretty_format_batches;
use lance::deps::datafusion::catalog::{Session, TableFunctionImpl, TableProvider};
use lance::deps::datafusion::common::ScalarValue;
use lance::deps::datafusion::datasource::{ViewTable, provider_as_source};
use lance::deps::datafusion::error::DataFusionError;
use lance::deps::datafusion::execution::SessionStateBuilder;
use lance::deps::datafusion::execution::runtime_env::RuntimeEnvBuilder;
use lance::deps::datafusion::logical_expr::{
    ColumnarValue, LogicalPlanBuilder, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
    TypeSignature, Volatility,
};
use lance::deps::datafusion::logical_expr::{Expr, TableType};
use lance::deps::datafusion::physical_plan::ExecutionPlan;
use lance::deps::datafusion::prelude::{SQLOptions, SessionConfig, SessionContext, col};
use lance::deps::datafusion::sql::parser::{DFParser, Statement as DfStatement};
use lance::deps::datafusion::sql::sqlparser::ast::{SetExpr, Statement as SqlStatement};
use lance_arrow::SchemaExt;
use lance_datafusion::udf::register_functions;
use lance_index::scalar::FullTextSearchQuery;
use lance_index::scalar::inverted::parser::from_json;
use parquet::arrow::ArrowWriter;

use crate::sessions::Store;
use crate::substrate::Table;

/// Per-query memory ceiling for the DataFusion runtime. Not enforced on every
/// operator (datafusion caveat), so the timeout below is the hard backstop.
const MEM_LIMIT_BYTES: usize = 512 * 1024 * 1024;
/// Wall-clock cap on `collect()`. DataFusion 53 has no built-in query timeout,
/// so this `tokio::time::timeout` is the only guard against a runaway plan.
/// Callers may raise it per query up to [`MAX_QUERY_TIMEOUT_SECS`].
pub const DEFAULT_QUERY_TIMEOUT_SECS: u64 = 30;
/// Ceiling on the caller-supplied timeout: `collect()` is cancellable only by
/// this timeout, so an absurd value must not pin the server on a runaway scan.
pub const MAX_QUERY_TIMEOUT_SECS: u64 = 600;

fn effective_timeout(timeout_secs: Option<u64>) -> Duration {
    Duration::from_secs(
        timeout_secs
            .unwrap_or(DEFAULT_QUERY_TIMEOUT_SECS)
            .clamp(1, MAX_QUERY_TIMEOUT_SECS),
    )
}
/// Byte budget for the inline (rendered table) result; rows are dropped to fit.
const INLINE_BUDGET_BYTES: usize = 80_000;
/// Byte budget for [`Mode::Json`] rows, measured as serialized JSON. Sized for
/// an HTTP client paging transcripts rather than an LLM context, so it is far
/// above the inline budget and cells are never clipped.
const JSON_BUDGET_BYTES: usize = 2 * 1024 * 1024;
/// Hard ceiling on an export artifact: base64'd over `resources/read` it costs
/// ~1.33x this in the response, so keep it well under any process envelope.
const MAX_EXPORT_BYTES: usize = 100 * 1024 * 1024;
/// Default inline row cap when the caller passes no `limit`.
pub const DEFAULT_INLINE_ROWS: usize = 100;
/// Upper bound on the caller-supplied inline `limit`.
pub const MAX_INLINE_ROWS: usize = 1_000;

/// Export serialization format. Vector columns are excluded and JSON columns
/// are decoded to text before encoding (see [`displayable`]).
#[derive(Debug, Clone, Copy)]
pub enum Format {
    Parquet,
    Ndjson,
}

impl Format {
    pub fn ext(self) -> &'static str {
        match self {
            Self::Parquet => "parquet",
            Self::Ndjson => "ndjson",
        }
    }

    pub fn mime(self) -> &'static str {
        match self {
            Self::Parquet => "application/vnd.apache.parquet",
            Self::Ndjson => "application/x-ndjson",
        }
    }
}

/// How `pond_sql` returns results.
#[derive(Debug, Clone, Copy)]
pub enum Mode {
    /// Render a row-capped table into the tool result.
    Inline,
    /// Write the full result to a file and return a `pond-sql-export://` link.
    Export(Format),
    /// Row-capped JSON objects, one per row (the HTTP `/v1/x/sql` route).
    Json,
}

/// The Lance datasets a query references, fetched fresh per call so each query
/// sees a current snapshot (the handle freshness gate runs on each
/// `Store::dataset`). A field is `None` when the query never names that table -
/// [`open_tables`] skips opening it, avoiding the slow `parts.lance` open on the
/// common messages-only query (spec.md#search). See [`mentions_table`].
pub struct Tables {
    pub sessions: Option<Arc<Dataset>>,
    pub messages: Option<Arc<Dataset>>,
    pub parts: Option<Arc<Dataset>>,
}

/// Whether `sql` references the table named `table`. A DataFusion query can
/// only reach a registered table by writing its name literally - no alias hides
/// the base name - so this lowercase word-boundary scan never yields a false
/// negative. At worst it matches the name inside a string or column literal and
/// opens a table the query won't touch: a cheap, safe false positive. Lets the
/// caller open only the datasets a query needs.
pub fn mentions_table(sql: &str, table: &str) -> bool {
    sql.to_ascii_lowercase()
        .split(|c: char| !c.is_alphanumeric() && c != '_')
        .any(|token| token == table)
}

/// Open only the datasets `sql` names (see [`mentions_table`]): the slow
/// `parts.lance` open is pure waste for the common messages-only query. The
/// ranked `fts('<table>', ...)` provider names its table literally, so the same
/// scan hands it the dataset it searches. The tables have independent
/// caches/mutexes, so their freshness/manifest fetches overlap. The table-free
/// `precheck` runs first, so a rejected query never touches storage.
pub async fn open_tables(store: &Store, sql: &str, mode: Mode) -> Result<Tables, SqlError> {
    precheck(sql, mode)?;
    let open = |table: Table| {
        let wanted = mentions_table(sql, table.as_str());
        async move {
            anyhow::Ok(match wanted {
                true => Some(store.dataset(table).await?),
                false => None,
            })
        }
    };
    let (sessions, messages, parts) = tokio::try_join!(
        open(Table::Sessions),
        open(Table::Messages),
        open(Table::Parts),
    )
    .map_err(SqlError::Storage)?;
    Ok(Tables {
        sessions,
        messages,
        parts,
    })
}

/// Result of a successful `run`.
pub enum Outcome {
    /// A rendered, row-capped table (already includes the metrics footer).
    Inline(String),
    /// Encoded export bytes plus metadata for the caller's summary/resource.
    Export {
        bytes: Vec<u8>,
        format: Format,
        rows: usize,
        columns: Vec<String>,
    },
    Json(JsonRows),
}

/// [`Mode::Json`] rows; the contract is documented on [`crate::wire::SqlResponse`].
pub struct JsonRows {
    pub columns: Vec<String>,
    pub rows: Vec<serde_json::Value>,
    pub row_count: usize,
    pub truncated: bool,
    pub elapsed_ms: u64,
}

/// Three error channels: `Query` is caller-fixable (parse/plan/exec/limits) and
/// every surface reports it as such (an MCP `isError` result the model
/// self-corrects from, an HTTP `validation_failed`); `Storage` is a transient
/// dataset-open or object-store failure worth retrying (HTTP
/// `storage_unavailable`); `Infra` is a deterministic internal failure that a
/// retry would only repeat (HTTP `internal`).
#[derive(Debug)]
pub enum SqlError {
    Query(String),
    Storage(anyhow::Error),
    Infra(anyhow::Error),
}

fn infra(error: ArrowError) -> SqlError {
    SqlError::Infra(anyhow::Error::new(error))
}

/// An execution failure is the store's, not the query's, when an object-store
/// or IO error sits anywhere in its source chain. Lance boxes an
/// `object_store::Error` as the source of its `IO` variant, which the walk
/// reaches; `lance::Error::IO` itself is lance's catch-all (resources
/// exhausted, join and decode errors), so it is deliberately not matched.
fn is_storage_failure(error: &DataFusionError) -> bool {
    let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(error);
    while let Some(current) = cause {
        if current.is::<std::io::Error>()
            || current.is::<object_store::Error>()
            || matches!(
                current.downcast_ref::<DataFusionError>(),
                Some(DataFusionError::ObjectStore(_))
            )
        {
            return true;
        }
        cause = current.source();
    }
    false
}

/// The table-free checks: the read-only gate plus the misuse rejections that
/// need only the SQL text. Microseconds, so [`run`] repeats it for callers that
/// bypass [`open_tables`].
fn precheck(sql: &str, mode: Mode) -> Result<StatementKind, SqlError> {
    let parsed = parse_and_gate(sql)?;
    if matches!(parsed.kind, StatementKind::Explain) && matches!(mode, Mode::Export(_)) {
        return Err(SqlError::Query(
            "EXPLAIN returns a plan, not a result set; read it with format=text instead".to_owned(),
        ));
    }
    if projection_mentions_vector(parsed.projection_query()) {
        return Err(SqlError::Query(
            "the `vector` column is not selectable from pond_sql (it is a \
             FixedSizeList<f32> embedding, ~600 bytes per row and not useful in a result). \
             For semantic search use pond_search. Filtering on it is allowed in WHERE \
             (e.g. `vector IS NOT NULL`)."
                .to_owned(),
        ));
    }
    if jsonb_cast_misuse(sql) {
        return Err(SqlError::Query(
            "CAST / `::` does not work on the binary JSONB columns (variant_data, options) - \
             when the bytes happen to be valid text it can even silently return garbage. \
             Stringify the whole value with json_extract(col, '$') or read one field with \
             json_extract(col, '$.field')."
                .to_owned(),
        ));
    }
    if jsonb_fulldoc_like_scan(sql) {
        return Err(SqlError::Query(
            "a leading-wildcard LIKE over the whole JSONB document - \
             json_extract(variant_data, '$') LIKE '%...%' - stringifies and scans every row, \
             so over parts it will not finish within the time limit. There is no substring \
             index on tool bodies yet (TODO #47: lance FM-Index). Instead match a single \
             field with json_extract(variant_data, '$.field') LIKE '...', scope to one session \
             with session_id = '<id>' and read it with pond_get_session, or search \
             conversational text with contains_tokens(search_text, '...')."
                .to_owned(),
        ));
    }
    Ok(parsed.kind)
}

/// Execute one read-only SQL query and return either a rendered table, JSON
/// rows, or encoded export bytes.
pub async fn run(
    tables: &Tables,
    sql: &str,
    mode: Mode,
    max_rows: usize,
    timeout_secs: Option<u64>,
) -> Result<Outcome, SqlError> {
    let kind = precheck(sql, mode)?;
    let ctx = build_context()?;
    register(&ctx, tables)?;

    // Defense in depth on top of the pre-parse gate: SQLOptions blocks DDL/DML
    // at planning time. `allow_statements` stays false for a plain SELECT (the
    // parse-time gate already rejects SET/SHOW etc.) but must be true for
    // EXPLAIN, which DataFusion classifies as a Statement node. The inner
    // query of an EXPLAIN was vetted by the gate above.
    let options = SQLOptions::new()
        .with_allow_ddl(false)
        .with_allow_dml(false)
        .with_allow_statements(matches!(kind, StatementKind::Explain));
    let mut df = ctx
        .sql_with_options(sql, options)
        .await
        .map_err(|error| SqlError::Query(enrich(&format!("SQL error: {error}"))))?;
    // One row past the cap keeps `truncated` exact while the cap pushes into the scan.
    if matches!(mode, Mode::Json) && matches!(kind, StatementKind::Query) {
        df = df
            .limit(0, Some(max_rows.saturating_add(1)))
            .map_err(|error| SqlError::Query(enrich(&format!("SQL error: {error}"))))?;
    }

    // Captured before `collect()` consumes `df`, so an empty result still
    // renders its column headers.
    let result_schema = Arc::new(df.schema().as_arrow().clone());
    let started = Instant::now();
    // TODO(#47): substring hunts inside parts.variant_data (json_extract +
    // LIKE full scans) are the dominant real-world cause of this timeout. The
    // planned fix is lance's FM-Index on variant_data (raw-byte substring
    // search via `contains(variant_data, 'needle')`); until it lands, the
    // message steers agents to predicates the current indexes can serve.
    let timeout = effective_timeout(timeout_secs);
    let collected = tokio::time::timeout(timeout, df.collect())
        .await
        .map_err(|_| {
            SqlError::Query(format!(
                "query exceeded the {}s limit; add a narrower WHERE or a LIMIT, or raise \
                 the per-query timeout (`timeout_seconds` on pond_sql and POST /v1/x/sql, \
                 `--timeout` on pond sql; max {MAX_QUERY_TIMEOUT_SECS}s) if it legitimately needs \
                 longer. On a remote object store, queries over parts cost seconds per \
                 round-trip - scope by session_id / tool_name, and to reconstruct one \
                 session use pond_get_session, not SQL. For tool analytics use the \
                 narrow native columns (tool_name, \
                 call_id, is_failure) instead of json_get_* over variant_data. If you were \
                 substring-scanning variant_data (json_extract + LIKE), there is no \
                 substring index on tool bodies yet: scope-then-scan - first collect \
                 candidate session_ids from the indexed conversational text (WITH hits AS \
                 (SELECT DISTINCT session_id FROM messages WHERE \
                 contains_tokens(search_text, '...')), then run the field LIKE only \
                 against parts JOINed to those session_ids; unscoped body scans time out.",
                timeout.as_secs()
            ))
        })?
        .map_err(|error| match is_storage_failure(&error) {
            true => SqlError::Storage(anyhow!("sql execution failed: {error}")),
            false => SqlError::Query(enrich(&format!("SQL error: {error}"))),
        })?;
    let elapsed = started.elapsed();

    let display: Vec<RecordBatch> = if collected.is_empty() {
        vec![displayable(&RecordBatch::new_empty(result_schema)).map_err(infra)?]
    } else {
        collected
            .into_iter()
            .map(|batch| displayable(&batch))
            .collect::<Result<_, _>>()
            .map_err(infra)?
    };

    match mode {
        Mode::Inline => Ok(Outcome::Inline(
            render_inline(&display, max_rows, elapsed).map_err(infra)?,
        )),
        Mode::Json => Ok(Outcome::Json(json_rows(&display, max_rows, elapsed)?)),
        Mode::Export(format) => {
            let rows = display.iter().map(RecordBatch::num_rows).sum();
            let columns = column_names(&display);
            let bytes = match format {
                Format::Parquet => encode_parquet(&display)?,
                Format::Ndjson => encode_ndjson(&display)?,
            };
            if bytes.len() > MAX_EXPORT_BYTES {
                return Err(SqlError::Query(format!(
                    "export is {} bytes, over the {MAX_EXPORT_BYTES} byte limit; \
                     narrow the query or aggregate",
                    bytes.len()
                )));
            }
            Ok(Outcome::Export {
                bytes,
                format,
                rows,
                columns,
            })
        }
    }
}

/// Top-level statement shape allowed past the read-only gate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StatementKind {
    /// A plain `Query` (SELECT/WITH/VALUES/UNION).
    Query,
    /// `EXPLAIN [ANALYZE] <query>` - planning info only, no mutation.
    Explain,
}

/// Parsed top-level statement, normalized so downstream checks always see a
/// projection-bearing `Query` regardless of whether the user wrote `SELECT`
/// or `EXPLAIN SELECT`. DataFusion's parser wraps EXPLAIN in its own
/// `DfStatement::Explain` variant (separate from sqlparser's
/// `SqlStatement::Explain`), so the gate has to peel both layers.
struct ParsedStatement {
    kind: StatementKind,
    query: lance::deps::datafusion::sql::sqlparser::ast::Query,
}

impl ParsedStatement {
    fn projection_query(&self) -> &lance::deps::datafusion::sql::sqlparser::ast::Query {
        &self.query
    }
}

/// Read-only gate: parse the SQL and require exactly one top-level `Query` or
/// `EXPLAIN <Query>`. Rejects DDL/DML/COPY/SET/SHOW and multi-statement input,
/// which `SQLOptions` alone does not catch at planning time. EXPLAIN of a
/// non-Query (e.g. `EXPLAIN INSERT ...`) is also rejected: EXPLAIN itself is
/// read-only, but letting the inner shape be DDL/DML widens the surface area
/// the gate has to reason about for no real agent gain.
fn parse_and_gate(sql: &str) -> Result<ParsedStatement, SqlError> {
    let statements = DFParser::parse_sql(sql)
        .map_err(|error| SqlError::Query(format!("SQL parse error: {error}")))?;
    if statements.len() != 1 {
        return Err(SqlError::Query(
            "pond_sql runs exactly one statement; submit a single SELECT".to_owned(),
        ));
    }
    let Some(front) = statements.front() else {
        return Err(read_only_rejection());
    };
    match front {
        DfStatement::Statement(boxed) => match boxed.as_ref() {
            SqlStatement::Query(query) => Ok(ParsedStatement {
                kind: StatementKind::Query,
                query: query.as_ref().clone(),
            }),
            _ => Err(read_only_rejection()),
        },
        DfStatement::Explain(explain) => match explain.statement.as_ref() {
            DfStatement::Statement(inner) => match inner.as_ref() {
                SqlStatement::Query(query) => Ok(ParsedStatement {
                    kind: StatementKind::Explain,
                    query: query.as_ref().clone(),
                }),
                _ => Err(read_only_rejection()),
            },
            _ => Err(read_only_rejection()),
        },
        _ => Err(read_only_rejection()),
    }
}

fn read_only_rejection() -> SqlError {
    // Surface-neutral wording: this message reaches both the pond_sql
    // MCP tool and the `pond sql` CLI, so it names neither.
    SqlError::Query(
        "pond's SQL surface is read-only: only a single SELECT/WITH (or EXPLAIN of one) is \
         allowed (no INSERT/UPDATE/DELETE/CREATE/DROP/COPY/SET)"
            .to_owned(),
    )
}

/// Reject any top-level projection that explicitly references the embedding
/// `vector` column. Today such queries silently return an empty column (the
/// FixedSizeList<f32> is stripped by `displayable`), which wastes agent tokens
/// diagnosing. WHERE/HAVING references stay legal - the doc lets agents filter
/// on it (e.g. `WHERE vector IS NOT NULL`); only projecting the column out is
/// blocked. Heuristic: tokenize each top-level SELECT item and look for a bare
/// `vector` identifier. Covers `SELECT vector`, `SELECT id, vector`,
/// `SELECT m.vector`, and `SELECT array_length(vector)`. Wildcards (`*` /
/// `messages.*`) keep the existing silent-strip behavior since they don't name
/// the column explicitly.
fn projection_mentions_vector(query: &lance::deps::datafusion::sql::sqlparser::ast::Query) -> bool {
    walk_set_expr_for_vector(query.body.as_ref())
}

fn walk_set_expr_for_vector(expr: &SetExpr) -> bool {
    match expr {
        SetExpr::Select(select) => select
            .projection
            .iter()
            .any(|item| mentions_vector_token(&item.to_string())),
        SetExpr::Query(inner) => walk_set_expr_for_vector(inner.body.as_ref()),
        SetExpr::SetOperation { left, right, .. } => {
            walk_set_expr_for_vector(left) || walk_set_expr_for_vector(right)
        }
        _ => false,
    }
}

fn mentions_vector_token(text: &str) -> bool {
    text.split(|c: char| !c.is_alphanumeric() && c != '_')
        .any(|token| token == "vector")
}

/// Plan-time gate for CAST / `::` on the binary JSONB columns. The runtime
/// failure is data-dependent (CAST only errors when a non-UTF8 byte is hit;
/// JSONB header bytes are often valid ASCII, so it can silently "succeed" and
/// return binary garbage), so reject before scanning. Token-scan heuristic in
/// the spirit of `projection_mentions_vector`; an aliased column that slips
/// through still hits the `enrich` runtime hint.
fn jsonb_cast_misuse(sql: &str) -> bool {
    const JSONB_COLUMNS: [&str; 2] = ["variant_data", "options"];
    let lowered = sql.to_ascii_lowercase();
    let bytes = lowered.as_bytes();
    let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';

    // `<col> :: <type>`
    for column in JSONB_COLUMNS {
        let mut start = 0;
        while let Some(pos) = lowered[start..].find(column) {
            let begin = start + pos;
            let end = begin + column.len();
            start = end;
            let bounded = (begin == 0 || !is_ident(bytes[begin - 1]))
                && (end == bytes.len() || !is_ident(bytes[end]));
            if bounded && lowered[end..].trim_start().starts_with("::") {
                return true;
            }
        }
    }

    // `CAST(<qualifier.>col AS <type>`
    let mut start = 0;
    while let Some(pos) = lowered[start..].find("cast") {
        let begin = start + pos;
        start = begin + 4;
        if begin > 0 && is_ident(bytes[begin - 1]) {
            continue;
        }
        let Some(open) = lowered[begin + 4..].trim_start().strip_prefix('(') else {
            continue;
        };
        let mut operand = open.trim_start();
        if let Some(dot) = operand.find('.')
            && dot > 0
            && operand.as_bytes()[..dot].iter().all(|b| is_ident(*b))
        {
            operand = &operand[dot + 1..];
        }
        for column in JSONB_COLUMNS {
            if let Some(after) = operand.strip_prefix(column)
                && !after.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_')
                && after
                    .trim_start()
                    .strip_prefix("as")
                    .is_some_and(|rest| rest.starts_with(char::is_whitespace))
            {
                return true;
            }
        }
    }
    false
}

/// Plan-time gate for the one substring shape that reliably exhausts the
/// wall-clock cap: a leading-wildcard LIKE/ILIKE over the *whole-document*
/// stringify of a binary JSONB column - `json_extract(variant_data|options,
/// '$') LIKE '%...%'`. That materializes every row's entire JSONB blob just to
/// substring-scan it, and the leading `%` defeats every index; over parts
/// (>1M rows) it does not finish, even scoped to a day. A single-field extract
/// (`'$.name'`) or any non-leading pattern is left to run - only the
/// whole-document murder shape is rejected, so the agent gets the indexed path
/// in milliseconds instead of a timeout. Token-scan heuristic in the spirit of
/// `jsonb_cast_misuse`; the timeout message remains the backstop for anything
/// that slips through.
/// TODO(#47): lance's FM-Index gives raw-byte substring search
/// (`contains(variant_data, 'needle')`); retire this gate once it lands.
fn jsonb_fulldoc_like_scan(sql: &str) -> bool {
    const JSONB_COLUMNS: [&str; 2] = ["variant_data", "options"];
    const NEEDLE: &str = "json_extract";
    let lowered = sql.to_ascii_lowercase();
    let bytes = lowered.as_bytes();
    let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_';

    let mut start = 0;
    while let Some(pos) = lowered[start..].find(NEEDLE) {
        let begin = start + pos;
        start = begin + NEEDLE.len();
        if begin > 0 && is_ident(bytes[begin - 1]) {
            continue;
        }
        let Some(rest) = lowered[start..].trim_start().strip_prefix('(') else {
            continue;
        };
        let mut operand = rest.trim_start();
        // optional `qualifier.`
        if let Some(dot) = operand.find('.')
            && dot > 0
            && operand.as_bytes()[..dot].iter().all(|b| is_ident(*b))
        {
            operand = &operand[dot + 1..];
        }
        let Some(col) = JSONB_COLUMNS.into_iter().find(|c| operand.starts_with(c)) else {
            continue;
        };
        // Require the whole-document path `, '$' )` exactly - a single-field
        // extract (`'$.name'`) is fine and must keep running.
        let tail = operand[col.len()..].trim_start();
        let Some(tail) = tail
            .strip_prefix(',')
            .map(str::trim_start)
            .and_then(|t| t.strip_prefix("'$'"))
            .map(str::trim_start)
            .and_then(|t| t.strip_prefix(')'))
        else {
            continue;
        };
        // Step past any wrapper close-parens (`lower(...)`/`upper(...)`).
        let mut tail = tail.trim_start();
        while let Some(next) = tail.strip_prefix(')') {
            tail = next.trim_start();
        }
        if let Some(next) = tail.strip_prefix("not")
            && next.starts_with(char::is_whitespace)
        {
            tail = next.trim_start();
        }
        for op in ["like", "ilike"] {
            if let Some(next) = tail.strip_prefix(op)
                && next.starts_with(char::is_whitespace)
                && next.trim_start().starts_with("'%")
            {
                return true;
            }
        }
    }
    false
}

fn build_context() -> Result<SessionContext, SqlError> {
    let runtime = RuntimeEnvBuilder::new()
        .with_memory_limit(MEM_LIMIT_BYTES, 1.0)
        .build_arc()
        .map_err(|error| SqlError::Infra(anyhow!("datafusion runtime init failed: {error}")))?;
    // information_schema is the standard self-discovery path (SELECT ... FROM
    // information_schema.columns); agents reach for it before any doc.
    let state = SessionStateBuilder::new()
        .with_config(SessionConfig::new().with_information_schema(true))
        .with_runtime_env(runtime)
        .with_default_features()
        .build();
    Ok(SessionContext::new_with_state(state))
}

/// Plan-time key renames: each table's storage `id` is exposed under a
/// self-describing name so the same value never changes name between tables -
/// agents copy column names across queries. One source drives both the
/// registered views and fts() output so they cannot diverge.
fn renamed_key(table: &str) -> Option<&'static str> {
    match table {
        "messages" => Some("message_id"),
        "sessions" => Some("session_id"),
        _ => None,
    }
}

fn register(ctx: &SessionContext, tables: &Tables) -> Result<(), SqlError> {
    for (name, dataset) in [
        ("sessions", &tables.sessions),
        ("messages", &tables.messages),
    ] {
        let Some(dataset) = dataset else { continue };
        // LanceTableProvider (not the bare Dataset impl) so WHERE/projection/
        // limit push into Lance's indexed scan; (false, false) hides _rowid /
        // _rowaddr from the SQL schema. The view applies `renamed_key`
        // plan-time only; storage keeps `id`.
        let provider = LanceTableProvider::new(dataset.clone(), false, false);
        let key = renamed_key(name).unwrap_or("id");
        let view = renamed_view(name, Arc::new(provider), "id", key)
            .map_err(|error| SqlError::Infra(anyhow!("build {name} view: {error}")))?;
        ctx.register_table(name, Arc::new(view))
            .map_err(|error| SqlError::Infra(anyhow!("register table {name}: {error}")))?;
    }
    // `parts` hides the `data` blob column behind a projecting view: blob
    // columns scan as `{position, size}` descriptor structs, so any SQL touch
    // dies in the planner with an opaque CAST error. The view inlines at plan
    // time - filters still push into the Lance scan underneath.
    if let Some(parts) = &tables.parts {
        let provider = LanceTableProvider::new(parts.clone(), false, false);
        let keep: Vec<_> = parts
            .schema()
            .fields
            .iter()
            .filter(|field| field.name != "data")
            .map(|field| col(field.name.as_str()))
            .collect();
        let plan = LogicalPlanBuilder::scan("parts", provider_as_source(Arc::new(provider)), None)
            .and_then(|builder| builder.project(keep))
            .and_then(LogicalPlanBuilder::build)
            .map_err(|error| SqlError::Infra(anyhow!("build parts view: {error}")))?;
        ctx.register_table("parts", Arc::new(ViewTable::new(plan, None)))
            .map_err(|error| SqlError::Infra(anyhow!("register table parts: {error}")))?;
    }
    // `fts('messages', '{...}')` BM25 search-in-SQL (vendored provider with a
    // declared `_score` column - see `ScoredFtsUdtf`), and lance's JSON /
    // contains_tokens UDFs for filtering inside the JSON columns. Only the
    // referenced tables are present, matching the registered views above.
    let datasets = [
        ("sessions", &tables.sessions),
        ("messages", &tables.messages),
        ("parts", &tables.parts),
    ]
    .into_iter()
    .filter_map(|(name, dataset)| dataset.clone().map(|d| (name.to_owned(), d)))
    .collect();
    let fts = ScoredFtsUdtf { datasets };
    ctx.register_udtf("fts", Arc::new(fts));
    register_functions(ctx);
    // Shadow lance's strict json_get_* by name: the strict versions abort the
    // whole scan when any row's field is non-scalar (e.g. tool_result `result`
    // arrays), turning one polymorphic value into a dead query.
    for udf in lenient_json_udfs() {
        ctx.register_udf(udf);
    }
    // `any_value` (Postgres 16 / DuckDB / BigQuery - agents reach for it)
    // doesn't exist in DataFusion 53; alias first_value, which satisfies the
    // same contract (any_value promises no ordering, so first-encountered is
    // a valid answer). register_udaf indexes aliases.
    if let Some(first_value) = ctx.state().aggregate_functions().get("first_value") {
        ctx.register_udaf(first_value.as_ref().clone().with_aliases(["any_value"]));
    }
    // `fts` as a *scalar* exists only to fail at plan time with the correction:
    // agents pattern-match FTS into WHERE (MySQL MATCH / Postgres @@ priors)
    // and DataFusion's stock error is "Did you mean 'cos'?". Scalar and
    // table-function registries are separate namespaces, so the real fts()
    // UDTF in FROM position is unaffected.
    ctx.register_udf(ScalarUDF::new_from_impl(FtsMisuse::new()));
    Ok(())
}

/// Wrap `provider` in a view projecting every column, with `from` renamed to
/// `to`. The view inlines at plan time, so filters and projections still push
/// into the underlying Lance scan.
fn renamed_view(
    scan_name: &str,
    provider: Arc<dyn TableProvider>,
    from: &str,
    to: &str,
) -> Result<ViewTable, DataFusionError> {
    let projection: Vec<_> = provider
        .schema()
        .fields()
        .iter()
        .map(|field| {
            let column = col(field.name().as_str());
            if field.name() == from {
                column.alias(to)
            } else {
                column
            }
        })
        .collect();
    let plan = LogicalPlanBuilder::scan(scan_name, provider_as_source(provider), None)?
        .project(projection)?
        .build()?;
    Ok(ViewTable::new(plan, None))
}

const FTS_MISUSE: &str = "fts is a table function and goes in FROM, not in WHERE or the \
    projection. For filtering use WHERE contains_tokens(search_text, 'word1 word2') (all \
    words must match; index-accelerated). For ranked results: SELECT m.message_id, f._score \
    FROM fts('messages', '{\"match\":{\"column\":\"search_text\",\"terms\":\"...\"}}') f \
    JOIN messages m ON m.message_id = f.message_id ORDER BY f._score DESC.";

/// See the registration comment: a plan-time teaching error for `WHERE fts(...)`.
#[derive(Debug, PartialEq, Eq, Hash)]
struct FtsMisuse {
    signature: Signature,
}

impl FtsMisuse {
    fn new() -> Self {
        Self {
            signature: Signature::variadic_any(Volatility::Immutable),
        }
    }
}

impl ScalarUDFImpl for FtsMisuse {
    fn name(&self) -> &str {
        "fts"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType, DataFusionError> {
        Err(DataFusionError::Plan(FTS_MISUSE.to_owned()))
    }

    fn invoke_with_args(
        &self,
        _args: ScalarFunctionArgs,
    ) -> Result<ColumnarValue, DataFusionError> {
        Err(DataFusionError::Plan(FTS_MISUSE.to_owned()))
    }
}

/// Vendored replacement for lance's `FtsQueryUDTF` (src/dataset/udtf.rs,
/// still unfixed at lance-12.0.0). The upstream provider omits `_score` from its
/// declared schema while leaving the scanner's scoring autoprojection on, so
/// `_score` is physically appended but logically unknown: naming it in SQL
/// fails ("No field named _score") and any aggregate over fts() dies on
/// DataFusion's physical-vs-logical schema check (COUNT plans 0 columns,
/// receives 1). This provider declares `_score` as a regular nullable Float32
/// column, projects it explicitly, and disables the autoprojection - which is
/// also lance's documented intended end state for score columns
/// (scanner.rs "_score/_distance should become regular output columns").
/// Delete once fixed upstream.
#[derive(Debug)]
struct ScoredFtsUdtf {
    datasets: HashMap<String, Arc<Dataset>>,
}

impl TableFunctionImpl for ScoredFtsUdtf {
    fn call(
        &self,
        expr: &[Expr],
    ) -> Result<Arc<dyn TableProvider>, lance::deps::datafusion::error::DataFusionError> {
        let [table_expr, query_expr] = expr else {
            return Err(DataFusionError::Execution(
                "fts() takes (table_name, fts_query_json)".to_owned(),
            ));
        };
        let Expr::Literal(ScalarValue::Utf8(Some(table_name)), _) = table_expr else {
            return Err(DataFusionError::Execution(
                "fts() first argument must be a table name string".to_owned(),
            ));
        };
        let Expr::Literal(ScalarValue::Utf8(Some(fts_query)), _) = query_expr else {
            return Err(DataFusionError::Execution(
                "fts() second argument must be the fts query as a JSON string".to_owned(),
            ));
        };
        let dataset = self.datasets.get(table_name).ok_or_else(|| {
            DataFusionError::Execution(format!("fts(): table {table_name} not found"))
        })?;
        let mut full_schema = Schema::from(dataset.schema());
        full_schema = full_schema
            .try_with_column(Field::new(SCORE_COLUMN, DataType::Float32, true))
            .map_err(|error| DataFusionError::ArrowError(Box::new(error), None))?;
        let provider: Arc<dyn TableProvider> = Arc::new(ScoredFtsProvider {
            dataset: dataset.clone(),
            fts_query: FullTextSearchQuery::new_query(from_json(fts_query)?),
            full_schema: Arc::new(full_schema),
        });
        // Same `renamed_key` as the registered views, so fts() output joins
        // without a name switch.
        match renamed_key(table_name) {
            Some(key) => Ok(Arc::new(renamed_view("fts", provider, "id", key)?)),
            None => Ok(provider),
        }
    }
}

const SCORE_COLUMN: &str = "_score";

#[derive(Debug)]
struct ScoredFtsProvider {
    dataset: Arc<Dataset>,
    fts_query: FullTextSearchQuery,
    full_schema: SchemaRef,
}

#[async_trait::async_trait]
impl TableProvider for ScoredFtsProvider {
    fn schema(&self) -> SchemaRef {
        self.full_schema.clone()
    }

    fn table_type(&self) -> TableType {
        TableType::Temporary
    }

    async fn scan(
        &self,
        _state: &dyn Session,
        projection: Option<&Vec<usize>>,
        filters: &[Expr],
        limit: Option<usize>,
    ) -> Result<Arc<dyn ExecutionPlan>, lance::deps::datafusion::error::DataFusionError> {
        let mut scan = self.dataset.scan();
        scan.full_text_search(self.fts_query.clone())?;
        // `_score` is a declared column projected explicitly below; with the
        // autoprojection off, the physical batch always matches the logical
        // plan (the mismatch is what breaks aggregates upstream).
        scan.disable_scoring_autoprojection();
        match projection {
            Some(projection) if projection.is_empty() => {
                scan.empty_project()?;
            }
            Some(projection) => {
                let columns: Vec<&str> = projection
                    .iter()
                    .map(|idx| self.full_schema.field(*idx).name().as_str())
                    .collect();
                scan.project(&columns)?;
            }
            None => {
                let columns: Vec<&str> = self
                    .full_schema
                    .fields()
                    .iter()
                    .map(|field| field.name().as_str())
                    .collect();
                scan.project(&columns)?;
            }
        }
        if let Some(combined) = filters
            .iter()
            .cloned()
            .reduce(|left, right| left.and(right))
        {
            scan.filter_expr(combined);
        }
        scan.limit(limit.map(|l| l as i64), None)?;
        scan.create_plan().await.map_err(DataFusionError::from)
    }
}

/// The four scalar shapes the lenient JSON getters produce.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum JsonGet {
    Text,
    Int,
    Float,
    Bool,
}

/// Deepest key path the lenient getters accept; deeper nesting is what
/// json_extract's JSONPath is for.
const MAX_JSON_KEYS: usize = 6;

/// Lenient replacements for lance's `json_get_string` / `_int` / `_float` /
/// `_bool`. The strict originals call jsonb's exact converters and turn one
/// non-scalar field value into a query-wide abort ("Failed to convert to
/// string: InvalidCast"). Lenient semantics: a string getter serializes
/// objects/arrays to JSON text; the typed getters return NULL on a
/// non-coercible value. Unlike lance's one-key originals they take a variadic
/// key path - `json_get_string(col, 'a', 'b')` - the datafusion-functions-json
/// convention agents reach for first. Registered after `register_functions`
/// so they shadow by name.
fn lenient_json_udfs() -> [ScalarUDF; 4] {
    let make = |name: &'static str, kind: JsonGet, return_type: DataType| {
        ScalarUDF::new_from_impl(LenientJsonGet {
            name,
            kind,
            return_type,
            signature: json_key_path_signature(),
        })
    };
    [
        make("json_get_string", JsonGet::Text, DataType::Utf8),
        make("json_get_int", JsonGet::Int, DataType::Int64),
        make("json_get_float", JsonGet::Float, DataType::Float64),
        make("json_get_bool", JsonGet::Bool, DataType::Boolean),
    ]
}

/// `(LargeBinary, Utf8)` through `(LargeBinary, Utf8 x MAX_JSON_KEYS)`.
fn json_key_path_signature() -> Signature {
    let arities = (1..=MAX_JSON_KEYS)
        .map(|keys| {
            let mut types = vec![DataType::LargeBinary];
            types.extend(std::iter::repeat_n(DataType::Utf8, keys));
            TypeSignature::Exact(types)
        })
        .collect();
    Signature::one_of(arities, Volatility::Immutable)
}

/// See [`lenient_json_udfs`].
#[derive(Debug, PartialEq, Eq, Hash)]
struct LenientJsonGet {
    name: &'static str,
    kind: JsonGet,
    return_type: DataType,
    signature: Signature,
}

impl ScalarUDFImpl for LenientJsonGet {
    fn name(&self) -> &str {
        self.name
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType, DataFusionError> {
        Ok(self.return_type.clone())
    }

    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue, DataFusionError> {
        json_get_lenient(&args.args, &self.kind)
    }
}

/// One step of the key walk: object member by name, array element by index.
fn json_step(raw: jsonb::RawJsonb<'_>, key: &str) -> Option<jsonb::OwnedJsonb> {
    let value = if raw.is_object().unwrap_or(false) {
        raw.get_by_name(key, false).ok().flatten()
    } else if raw.is_array().unwrap_or(false) {
        key.parse::<usize>()
            .ok()
            .and_then(|index| raw.get_by_index(index).ok().flatten())
    } else {
        None
    };
    value.filter(|value| !value.as_raw().is_null().unwrap_or(false))
}

fn json_get_lenient(
    args: &[ColumnarValue],
    kind: &JsonGet,
) -> Result<ColumnarValue, DataFusionError> {
    let arrays = ColumnarValue::values_to_arrays(args)?;
    let Some((jsonb_arg, key_args)) = arrays.split_first().filter(|(_, keys)| !keys.is_empty())
    else {
        return Err(DataFusionError::Execution(
            "json_get_* takes (json_column, 'key', ...) - at least one key".to_owned(),
        ));
    };
    let jsonb_array = jsonb_arg
        .as_any()
        .downcast_ref::<LargeBinaryArray>()
        .ok_or_else(|| {
            DataFusionError::Execution(
                "json_get_* argument 1 must be a JSON column (variant_data, options)".to_owned(),
            )
        })?;
    let key_arrays: Vec<&StringArray> = key_args
        .iter()
        .map(|key_arg| {
            key_arg
                .as_any()
                .downcast_ref::<StringArray>()
                .ok_or_else(|| {
                    DataFusionError::Execution("json_get_* keys must be string literals".to_owned())
                })
        })
        .collect::<Result<_, _>>()?;

    let field = |row: usize| -> Option<jsonb::OwnedJsonb> {
        if jsonb_array.is_null(row) {
            return None;
        }
        let mut keys = key_arrays.iter();
        let first = keys.next()?;
        if first.is_null(row) {
            return None;
        }
        let mut current = json_step(
            jsonb::RawJsonb::new(jsonb_array.value(row)),
            first.value(row),
        )?;
        for key_array in keys {
            if key_array.is_null(row) {
                return None;
            }
            current = json_step(current.as_raw(), key_array.value(row))?;
        }
        Some(current)
    };

    let rows = jsonb_array.len();
    let array: Arc<dyn Array> = match kind {
        JsonGet::Text => {
            let mut builder = StringBuilder::with_capacity(rows, 1024);
            for row in 0..rows {
                match field(row) {
                    // Scalar strings come back unquoted; objects/arrays/
                    // numbers serialize to JSON text instead of erroring.
                    Some(value) => match value.as_raw().to_str() {
                        Ok(text) => builder.append_value(text),
                        Err(_) => builder.append_value(value.to_string()),
                    },
                    None => builder.append_null(),
                }
            }
            Arc::new(builder.finish())
        }
        JsonGet::Int => {
            let mut builder = Int64Builder::with_capacity(rows);
            for row in 0..rows {
                builder.append_option(field(row).and_then(|value| value.as_raw().to_i64().ok()));
            }
            Arc::new(builder.finish())
        }
        JsonGet::Float => {
            let mut builder = Float64Builder::with_capacity(rows);
            for row in 0..rows {
                builder.append_option(field(row).and_then(|value| value.as_raw().to_f64().ok()));
            }
            Arc::new(builder.finish())
        }
        JsonGet::Bool => {
            let mut builder = BooleanBuilder::with_capacity(rows);
            for row in 0..rows {
                builder.append_option(field(row).and_then(|value| value.as_raw().to_bool().ok()));
            }
            Arc::new(builder.finish())
        }
    };
    Ok(ColumnarValue::Array(array))
}

/// Failures name the fix: append a recovery hint to the DataFusion error
/// classes agents actually hit, so a failed call teaches the correct next
/// query instead of starting a guessing loop. First match wins.
fn enrich(message: &str) -> String {
    const HINTS: &[(&str, &str)] = &[
        (
            "No field named",
            "columns are messages(session_id, message_id, timestamp, role, source_agent, \
             project, content [system-role only], search_text [the conversational text], \
             embedding_model, options) | sessions(session_id, parent_session_id, \
             parent_message_id, source_agent, created_at, project, options) | \
             parts(session_id, message_id, id, ordinal, type, provenance, tool_name, \
             call_id, is_failure, variant_data, options). Part bodies live in \
             parts.variant_data (JSONB) and nest by part type: tool_call is {call_id, \
             name, params} - a Bash command is json_extract(variant_data, \
             '$.params.command') - tool_result is {call_id, name, is_failure, result}, \
             text/reasoning carry {text}. For text search use \
             contains_tokens(search_text, '...') in WHERE, or the fts('messages', ...) \
             table function in FROM for ranked results; to read a transcript use \
             pond_get_session. Full doc: resource schema://pond-sql.",
        ),
        (
            "Encountered non UTF-8 data",
            "JSON columns (variant_data, options) are binary JSONB - CAST / ::text does not \
             work on them. Stringify the whole value with json_extract(col, '$'), or fetch \
             one field with json_extract(col, '$.field').",
        ),
        (
            "Resources exhausted",
            "the query ran out of memory - usually from carrying whole JSON columns \
             (variant_data, options) through a join or sort. Project narrow fields with \
             json_extract(col, '$.field') instead of whole columns, filter before joining, \
             or export the full set with format=parquet.",
        ),
        (
            "LIKE prefix queries are not supported for bitmap indexes",
            "prefix LIKE ('x%') and starts_with() fail on bitmap-indexed columns \
             (messages.source_agent). Use equality, \
             split_part(source_agent, '/', 1) = '...', or an infix pattern (LIKE '%x%').",
        ),
        (
            "call to 'json_",
            "JSON function signatures: json_get_string|json_get_int|json_get_float|\
             json_get_bool(col, 'key', ...) walk a key path (array steps by numeric \
             index); json_get(col, 'key') returns JSONB for chaining; json_extract(col, \
             '$.a.b') takes a JSONPath and returns JSON text of any value (the right tool \
             for deeply nested or mixed-type fields).",
        ),
        (
            "Invalid function 'json",
            "available JSON functions: json_get_string, json_get_int, json_get_float, \
             json_get_bool (col, 'key', ...); json_get(col, 'key') -> JSONB for chaining; \
             json_extract(col, '$.a.b') -> JSON text; json_array_contains; \
             json_array_length. See resource schema://pond-sql.",
        ),
        (
            // Defensive: lance's fts `boolean` query can plan a CollectLeft
            // HashJoin over multi-partition match arms, which the optimizer
            // does not always repair (works through pond's vendored fts()
            // provider; kept for any path that still trips it).
            "does not satisfy distribution requirements",
            "this fts query shape planned an unexecutable join. For AND semantics use a \
             single match query with operator And: fts('messages', \
             '{\"match\":{\"column\":\"search_text\",\"terms\":\"a b\",\"operator\":\"And\"}}'), \
             optionally with LIKE post-filters in WHERE.",
        ),
        (
            "position is not found but required for phrase queries",
            "the full-text index is built without positions, so \"phrase\" queries are \
             unavailable. Use a match query with operator And plus LIKE post-filters for \
             exact-substring matching.",
        ),
    ];
    for (pattern, hint) in HINTS {
        if message.contains(pattern) {
            return format!("{message}\nhint: {hint}");
        }
    }
    message.to_owned()
}

/// Decode lance JSONB columns to JSON text, then drop columns that don't render
/// readably (the embedding `vector` FixedSizeList and any leftover binary).
fn displayable(batch: &RecordBatch) -> Result<RecordBatch, ArrowError> {
    let decoded = lance_arrow::json::convert_lance_json_to_arrow(batch)?;
    let keep: Vec<usize> = decoded
        .schema()
        .fields()
        .iter()
        .enumerate()
        .filter(|(_, field)| is_displayable(field.data_type()))
        .map(|(index, _)| index)
        .collect();
    decoded.project(&keep)
}

fn is_displayable(data_type: &DataType) -> bool {
    !matches!(
        data_type,
        DataType::FixedSizeList(_, _)
            | DataType::Binary
            | DataType::LargeBinary
            | DataType::BinaryView
            | DataType::FixedSizeBinary(_)
    )
}

/// Per-cell character cap for the inline rendered table. Without it a single
/// fat cell (tool bodies reach 56KB) defeats the row-halving byte budget in
/// [`render_inline`] - which cannot drop below one row - and the table
/// renderer amplifies it ~5x by padding every row to the widest cell.
/// Measured: one 42KB cell rendered a 214KB response. Export modes
/// (parquet/ndjson) are never clipped.
const CELL_CLIP_CHARS: usize = 1_000;

/// Bound each cell for the inline table: clip long values to
/// [`CELL_CLIP_CHARS`] with a marker naming the unclipped path, and collapse
/// embedded newlines (markdown, multi-line commands) that otherwise explode a
/// row across many table lines that hard-wrap unreadably in narrow clients.
/// The literal two-char `\n` matches the JSON escaping agents already read,
/// and keeps row boundaries unambiguous. Inline table mode only - json and
/// export modes keep raw data.
fn bound_cells(batches: &[RecordBatch]) -> Result<Vec<RecordBatch>, ArrowError> {
    fn escape<O: OffsetSizeTrait>(array: &GenericStringArray<O>) -> ArrayRef {
        let escaped: GenericStringArray<O> =
            array.iter().map(|value| value.map(escape_cell)).collect();
        Arc::new(escaped)
    }
    fn escape_cell(text: &str) -> std::borrow::Cow<'_, str> {
        let clipped = match text.char_indices().nth(CELL_CLIP_CHARS) {
            Some((cut, _)) => {
                let omitted = text[cut..].chars().count();
                std::borrow::Cow::Owned(format!(
                    "{} [+{omitted} chars - pond_get_message (CLI: pond get-message) on \
                     this row's message_id renders the full part; or format=ndjson, or a \
                     narrower json_extract path]",
                    &text[..cut]
                ))
            }
            None => std::borrow::Cow::Borrowed(text),
        };
        if clipped.contains(['\n', '\r']) {
            std::borrow::Cow::Owned(clipped.replace("\r\n", "\\n").replace(['\n', '\r'], "\\n"))
        } else {
            clipped
        }
    }
    batches
        .iter()
        .map(|batch| {
            let columns: Vec<ArrayRef> = batch
                .columns()
                .iter()
                .map(|array| match array.data_type() {
                    DataType::Utf8 => array
                        .as_any()
                        .downcast_ref::<StringArray>()
                        .map_or_else(|| array.clone(), escape),
                    DataType::LargeUtf8 => array
                        .as_any()
                        .downcast_ref::<GenericStringArray<i64>>()
                        .map_or_else(|| array.clone(), escape),
                    DataType::Utf8View => array
                        .as_any()
                        .downcast_ref::<StringViewArray>()
                        .map_or_else(
                            || array.clone(),
                            |view| {
                                let escaped: StringViewArray =
                                    view.iter().map(|value| value.map(escape_cell)).collect();
                                Arc::new(escaped)
                            },
                        ),
                    _ => array.clone(),
                })
                .collect();
            RecordBatch::try_new(batch.schema(), columns)
        })
        .collect()
}

fn render_inline(
    display: &[RecordBatch],
    max_rows: usize,
    elapsed: Duration,
) -> Result<String, ArrowError> {
    let total: usize = display.iter().map(RecordBatch::num_rows).sum();
    let elapsed_ms = elapsed.as_millis();
    if total == 0 {
        // Still render the header so the caller sees the result columns.
        return Ok(format!(
            "0 rows ({elapsed_ms} ms).\n{}",
            pretty_format_batches(display)?
        ));
    }
    let render = |shown: usize| -> Result<String, ArrowError> {
        let limited = bound_cells(&limit_batches(display, shown))?;
        Ok(pretty_format_batches(&limited)?.to_string())
    };
    let mut shown = total.min(max_rows);
    let mut table = render(shown)?;
    while table.len() > INLINE_BUDGET_BYTES && shown > 1 {
        shown = (shown / 2).max(1);
        table = render(shown)?;
    }
    let mut out = format!("{total} row(s) in {elapsed_ms} ms; showing {shown}.\n{table}");
    if shown < total {
        out.push_str(&format!(
            "\n... {} row(s) omitted. To page: ORDER BY <indexed col> DESC, message_id DESC \
             (e.g. timestamp), then in the next call add `WHERE (col < <last_col> OR \
             (col = <last_col> AND message_id < '<last_message_id>'))` - keyset \
             pagination, see schema://pond-sql. For the full set: format=parquet or \
             format=ndjson.",
            total - shown
        ));
    }
    Ok(out)
}

fn column_names(display: &[RecordBatch]) -> Vec<String> {
    display
        .first()
        .map(|batch| {
            batch
                .schema()
                .fields()
                .iter()
                .map(|field| field.name().clone())
                .collect()
        })
        .unwrap_or_default()
}

/// [`Mode::Json`]: cap at `max_rows`, then drop rows from the end until the
/// serialized rows fit [`JSON_BUDGET_BYTES`] - but always keep the first row,
/// so a pager is never stalled by one oversized message.
fn json_rows(
    display: &[RecordBatch],
    max_rows: usize,
    elapsed: Duration,
) -> Result<JsonRows, SqlError> {
    let total: usize = display.iter().map(RecordBatch::num_rows).sum();
    let limited = limit_batches(display, max_rows)
        .iter()
        .map(timestamps_as_rfc3339)
        .collect::<Result<Vec<_>, _>>()
        .map_err(infra)?;
    let encoded = encode_ndjson(&limited)?;
    let mut rows = Vec::new();
    let mut used = 0;
    for line in encoded.split(|byte| *byte == b'\n') {
        if line.is_empty() {
            continue;
        }
        if !rows.is_empty() && used + line.len() > JSON_BUDGET_BYTES {
            break;
        }
        used += line.len();
        rows.push(
            serde_json::from_slice(line)
                .map_err(|error| SqlError::Infra(anyhow!("json row decode failed: {error}")))?,
        );
    }
    Ok(JsonRows {
        columns: column_names(display),
        row_count: rows.len(),
        truncated: rows.len() < total,
        rows,
        elapsed_ms: u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX),
    })
}

/// Render timestamp columns as RFC3339 UTC with exactly six fractional digits.
/// arrow-json trims fractions (`.384Z`), and JSON clients use these values as
/// keyset cursors, so the microsecond value must round-trip losslessly.
fn timestamps_as_rfc3339(batch: &RecordBatch) -> Result<RecordBatch, ArrowError> {
    fn render<T: ArrowTimestampType>(array: &ArrayRef, to_micros: fn(i64) -> i64) -> ArrayRef {
        let text: StringArray = array
            .as_primitive::<T>()
            .iter()
            .map(|value| {
                value
                    .and_then(|raw| chrono::DateTime::from_timestamp_micros(to_micros(raw)))
                    .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Micros, true))
            })
            .collect();
        Arc::new(text)
    }
    let schema = batch.schema();
    if !schema
        .fields()
        .iter()
        .any(|field| matches!(field.data_type(), DataType::Timestamp(_, _)))
    {
        return Ok(batch.clone());
    }
    let (fields, columns): (Vec<Field>, Vec<ArrayRef>) = schema
        .fields()
        .iter()
        .zip(batch.columns())
        .map(|(field, array)| {
            let rendered = match field.data_type() {
                DataType::Timestamp(TimeUnit::Second, _) => {
                    render::<TimestampSecondType>(array, |s| s.saturating_mul(1_000_000))
                }
                DataType::Timestamp(TimeUnit::Millisecond, _) => {
                    render::<TimestampMillisecondType>(array, |ms| ms.saturating_mul(1_000))
                }
                DataType::Timestamp(TimeUnit::Microsecond, _) => {
                    render::<TimestampMicrosecondType>(array, |us| us)
                }
                DataType::Timestamp(TimeUnit::Nanosecond, _) => {
                    render::<TimestampNanosecondType>(array, |ns| ns.div_euclid(1_000))
                }
                _ => return (field.as_ref().clone(), array.clone()),
            };
            (
                Field::new(field.name(), DataType::Utf8, field.is_nullable()),
                rendered,
            )
        })
        .unzip();
    RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)
}

fn limit_batches(batches: &[RecordBatch], max_rows: usize) -> Vec<RecordBatch> {
    let mut out = Vec::new();
    let mut remaining = max_rows;
    for batch in batches {
        if remaining == 0 {
            break;
        }
        if batch.num_rows() <= remaining {
            remaining -= batch.num_rows();
            out.push(batch.clone());
        } else {
            out.push(batch.slice(0, remaining));
            remaining = 0;
        }
    }
    out
}

fn encode_parquet(batches: &[RecordBatch]) -> Result<Vec<u8>, SqlError> {
    let schema = batches
        .first()
        .map(RecordBatch::schema)
        .ok_or_else(|| SqlError::Query("query returned no columns to export".to_owned()))?;
    let mut buffer = Vec::new();
    let mut writer = ArrowWriter::try_new(&mut buffer, schema, None)
        .map_err(|error| SqlError::Infra(anyhow!("parquet init failed: {error}")))?;
    for batch in batches {
        writer
            .write(batch)
            .map_err(|error| SqlError::Infra(anyhow!("parquet write failed: {error}")))?;
    }
    writer
        .close()
        .map_err(|error| SqlError::Infra(anyhow!("parquet close failed: {error}")))?;
    Ok(buffer)
}

fn encode_ndjson(batches: &[RecordBatch]) -> Result<Vec<u8>, SqlError> {
    let mut buffer = Vec::new();
    {
        let mut writer = LineDelimitedWriter::new(&mut buffer);
        let refs: Vec<&RecordBatch> = batches.iter().collect();
        writer
            .write_batches(&refs)
            .map_err(|error| SqlError::Infra(anyhow!("ndjson write failed: {error}")))?;
        writer
            .finish()
            .map_err(|error| SqlError::Infra(anyhow!("ndjson finish failed: {error}")))?;
    }
    Ok(buffer)
}

#[cfg(test)]
mod tests {
    #![expect(clippy::expect_used, reason = "tests fail by panicking")]

    use super::*;

    fn rejected(sql: &str) -> bool {
        matches!(parse_and_gate(sql), Err(SqlError::Query(_)))
    }

    fn parses_as(sql: &str, expected: StatementKind) -> bool {
        match parse_and_gate(sql) {
            Ok(parsed) => matches!(
                (&parsed.kind, &expected),
                (StatementKind::Query, StatementKind::Query)
                    | (StatementKind::Explain, StatementKind::Explain)
            ),
            Err(_) => false,
        }
    }

    #[test]
    fn mentions_table_is_sound_for_open_pruning() {
        // Referenced => must be detected (no false negative, else a valid query
        // breaks). Case-insensitive: DataFusion lowercases identifiers.
        assert!(mentions_table("SELECT * FROM messages", "messages"));
        assert!(mentions_table("select * from MESSAGES", "messages"));
        assert!(mentions_table(
            "SELECT s.id FROM sessions s JOIN parts p ON s.id = p.session_id",
            "parts",
        ));
        assert!(mentions_table(
            "SELECT * FROM fts('messages', '{\"match\":{}}')",
            "messages",
        ));
        assert!(mentions_table(
            "WITH x AS (SELECT * FROM sessions) SELECT * FROM x",
            "sessions",
        ));
        // Not referenced => skip the open. Word boundary: a longer identifier
        // that merely contains the name is not a reference.
        assert!(!mentions_table("SELECT * FROM messages", "parts"));
        assert!(!mentions_table("SELECT * FROM messages", "sessions"));
        assert!(!mentions_table(
            "SELECT counterparts FROM messages",
            "parts"
        ));
    }

    #[test]
    fn allows_single_select_and_cte() {
        assert!(parses_as("SELECT 1", StatementKind::Query));
        assert!(parses_as(
            "SELECT role, count(*) FROM messages GROUP BY role",
            StatementKind::Query
        ));
        assert!(parses_as(
            "WITH t AS (SELECT 1 AS a) SELECT a FROM t",
            StatementKind::Query
        ));
    }

    #[test]
    fn allows_explain_of_select() {
        assert!(parses_as("EXPLAIN SELECT 1", StatementKind::Explain));
        assert!(parses_as(
            "EXPLAIN ANALYZE SELECT role FROM messages",
            StatementKind::Explain
        ));
    }

    #[test]
    fn rejects_explain_of_non_query() {
        // EXPLAIN of a side-effecting statement: the inner statement is what
        // would matter; reject to keep the surface tight.
        assert!(rejected("EXPLAIN INSERT INTO messages VALUES ('x')"));
        // ANALYZE executes the inner statement, so it is gated on the same shape.
        assert!(rejected(
            "EXPLAIN ANALYZE INSERT INTO messages VALUES ('x')"
        ));
        assert!(rejected("EXPLAIN ANALYZE DELETE FROM messages"));
    }

    #[test]
    fn rejects_writes_and_side_effects() {
        assert!(rejected("INSERT INTO messages VALUES ('x')"));
        assert!(rejected("UPDATE messages SET role = 'x'"));
        assert!(rejected("DELETE FROM messages"));
        assert!(rejected("CREATE TABLE t (x INT)"));
        assert!(rejected("CREATE VIEW v AS SELECT 1"));
        assert!(rejected("DROP TABLE messages"));
        assert!(rejected(
            "CREATE EXTERNAL TABLE t STORED AS PARQUET LOCATION '/etc'"
        ));
        assert!(rejected("COPY (SELECT 1) TO '/tmp/x.parquet'"));
        assert!(rejected("SET a = 1"));
    }

    #[test]
    fn rejects_multiple_statements() {
        assert!(rejected("SELECT 1; SELECT 2"));
        assert!(rejected("SELECT 1; DROP TABLE messages"));
    }

    #[test]
    fn rejects_unparseable() {
        assert!(rejected("NOT SQL AT ALL ;;"));
    }

    fn mentions_vector(sql: &str) -> bool {
        match parse_and_gate(sql) {
            Ok(parsed) => projection_mentions_vector(parsed.projection_query()),
            Err(_) => false,
        }
    }

    #[test]
    fn explicit_vector_projection_is_rejected() {
        assert!(mentions_vector("SELECT vector FROM messages"));
        assert!(mentions_vector("SELECT id, vector FROM messages"));
        assert!(mentions_vector("SELECT m.vector FROM messages m"));
        assert!(mentions_vector("SELECT array_length(vector) FROM messages"));
        assert!(mentions_vector("EXPLAIN SELECT vector FROM messages"));
    }

    #[test]
    fn enrich_appends_recovery_hints() {
        // One literal error string per class, captured from real failed calls.
        let cases = [
            (
                "SQL error: Schema error: No field named created_at.",
                "schema://pond-sql",
            ),
            (
                "SQL error: External error: Arrow error: Invalid argument error: \
                 Encountered non UTF-8 data",
                "json_extract",
            ),
            (
                "SQL error: External error: Not supported: LIKE prefix queries are not \
                 supported for bitmap indexes",
                "split_part",
            ),
            (
                "SQL error: Error during planning: Failed to coerce arguments to satisfy \
                 a call to 'json_get_string' function",
                "JSONPath",
            ),
            (
                "SQL error: Error during planning: Invalid function 'json_get_json'.",
                "json_extract",
            ),
            (
                "SQL error: Resources exhausted: Additional allocation failed for \
                 HashJoinInput[0] with top memory consumers",
                "json_extract",
            ),
        ];
        for (raw, marker) in cases {
            let enriched = enrich(raw);
            assert!(enriched.starts_with(raw), "original kept: {enriched}");
            assert!(enriched.contains("hint:"), "hint appended: {enriched}");
            assert!(enriched.contains(marker), "hint names the fix: {enriched}");
        }
        // Unrecognized errors pass through untouched.
        assert_eq!(
            enrich("SQL error: division by zero"),
            "SQL error: division by zero"
        );
    }

    #[test]
    fn select_star_and_where_vector_are_allowed() {
        // `SELECT *` falls through to the existing silent-strip in displayable.
        assert!(!mentions_vector("SELECT * FROM messages"));
        // Filtering on `vector` is documented as legal (`vector IS NOT NULL`).
        assert!(!mentions_vector(
            "SELECT message_id FROM messages WHERE vector IS NOT NULL"
        ));
    }

    #[test]
    fn jsonb_cast_misuse_detects_cast_and_coloncolon() {
        for sql in [
            "SELECT CAST(variant_data AS VARCHAR) FROM parts",
            "SELECT cast(p.variant_data as text) FROM parts p",
            "SELECT variant_data::text FROM parts",
            "SELECT p.variant_data :: varchar FROM parts p",
            "SELECT options::text FROM messages",
            "SELECT lower(CAST(variant_data AS VARCHAR)) FROM parts",
        ] {
            assert!(jsonb_cast_misuse(sql), "should reject: {sql}");
        }
    }

    #[test]
    fn jsonb_cast_misuse_allows_legitimate_use() {
        for sql in [
            "SELECT json_extract(variant_data, '$') FROM parts",
            "SELECT json_get_string(variant_data, 'name') FROM parts",
            "SELECT CAST(ordinal AS BIGINT) FROM parts",
            "SELECT timestamp::date FROM messages",
            // `options` as part of a longer identifier is not the column.
            "SELECT my_options::text FROM t",
            "SELECT CAST(json_extract(variant_data, '$.x') AS BIGINT) FROM parts",
        ] {
            assert!(!jsonb_cast_misuse(sql), "should allow: {sql}");
        }
    }

    #[test]
    fn jsonb_fulldoc_like_scan_detects_whole_document_substring() {
        for sql in [
            "SELECT * FROM parts WHERE json_extract(variant_data, '$') LIKE '%needle%'",
            "SELECT * FROM parts p WHERE lower(json_extract(p.variant_data, '$')) LIKE '%x%'",
            "SELECT * FROM messages WHERE json_extract(options, '$') ILIKE '%y%'",
            "SELECT * FROM parts WHERE json_extract(variant_data,'$') NOT LIKE '%z%'",
            // The real timeout shape: day-scoped join still scans every part.
            "SELECT p.message_id FROM parts p JOIN messages m ON p.message_id = m.message_id \
             WHERE m.timestamp >= '2026-06-11' AND lower(json_extract(p.variant_data, '$')) \
             LIKE '%weekly limit%'",
        ] {
            assert!(jsonb_fulldoc_like_scan(sql), "should reject: {sql}");
        }
    }

    #[test]
    fn jsonb_fulldoc_like_scan_allows_targeted_and_nonleading() {
        for sql in [
            // single-field extract, not the whole document
            "SELECT * FROM parts WHERE json_extract(variant_data, '$.name') LIKE '%x%'",
            // non-leading (prefix) pattern can be served without a full stringify
            "SELECT * FROM parts WHERE json_extract(variant_data, '$') LIKE 'pre%'",
            // plain text LIKE has no whole-document stringify
            "SELECT * FROM messages WHERE search_text LIKE '%x%'",
            // indexed predicate, the path agents should take
            "SELECT * FROM messages WHERE contains_tokens(search_text, 'x')",
            // projecting the stringified value is fine; no LIKE scan
            "SELECT json_extract(variant_data, '$') FROM parts LIMIT 1",
        ] {
            assert!(!jsonb_fulldoc_like_scan(sql), "should allow: {sql}");
        }
    }

    #[test]
    fn render_inline_clips_fat_cells() {
        let schema = Arc::new(Schema::new(vec![Field::new("t", DataType::Utf8, true)]));
        let fat = "x".repeat(42_000);
        let batch = RecordBatch::try_new(
            schema,
            vec![Arc::new(StringArray::from(vec![Some(fat.as_str())]))],
        )
        .expect("single-column batch");
        let out = render_inline(&[batch], 10, Duration::from_millis(1)).expect("render succeeds");
        assert!(
            out.len() < INLINE_BUDGET_BYTES,
            "one fat cell stays within the inline budget: {} bytes",
            out.len()
        );
        assert!(
            out.contains(
                "[+41000 chars - pond_get_message (CLI: pond get-message) on this row's message_id"
            ),
            "clip marker names the omitted count and the full path: {out}"
        );
    }

    #[test]
    fn cell_clip_respects_multibyte_boundaries_and_collapses_newlines() {
        let schema = Arc::new(Schema::new(vec![Field::new("t", DataType::Utf8, true)]));
        // Multibyte chars around the cut plus embedded newlines in the kept
        // prefix: the clip must cut on a char boundary and still collapse.
        let fat = format!("é\ný{}", "λ".repeat(2_000));
        let batch = RecordBatch::try_new(
            schema,
            vec![Arc::new(StringArray::from(vec![Some(fat.as_str())]))],
        )
        .expect("single-column batch");
        let out = render_inline(&[batch], 10, Duration::from_millis(1)).expect("render succeeds");
        assert!(
            out.contains("é\\ný") && out.contains("[+1003 chars"),
            "char-boundary clip with newline collapse: {out}"
        );
        // Short cells are untouched.
        let exactly_cap = "a".repeat(CELL_CLIP_CHARS);
        let schema = Arc::new(Schema::new(vec![Field::new("t", DataType::Utf8, true)]));
        let batch = RecordBatch::try_new(
            schema,
            vec![Arc::new(StringArray::from(vec![Some(
                exactly_cap.as_str(),
            )]))],
        )
        .expect("single-column batch");
        let out = render_inline(&[batch], 10, Duration::from_millis(1)).expect("render succeeds");
        assert!(!out.contains("chars -"), "cap-sized cell not clipped");
    }

    #[test]
    fn render_inline_collapses_newlines_in_cells() {
        let schema = Arc::new(Schema::new(vec![Field::new("t", DataType::Utf8, true)]));
        let batch = RecordBatch::try_new(
            schema,
            vec![Arc::new(StringArray::from(vec![Some(
                "line one\nline two\r\nline three",
            )]))],
        )
        .expect("single-column batch");
        let out = render_inline(&[batch], 10, Duration::from_millis(1)).expect("render succeeds");
        assert!(
            out.contains("line one\\nline two\\nline three"),
            "newlines collapse to literal \\n: {out}"
        );
        // The data row renders as one physical line: header rule, header,
        // rule, row, rule - the row itself never wraps.
        let row_lines: Vec<&str> = out
            .lines()
            .filter(|line| line.contains("line one"))
            .collect();
        assert_eq!(row_lines.len(), 1, "one physical line per row: {out}");
    }

    fn no_tables() -> Tables {
        Tables {
            sessions: None,
            messages: None,
            parts: None,
        }
    }

    async fn run_json(sql: &str, limit: usize) -> Result<JsonRows, SqlError> {
        match run(&no_tables(), sql, Mode::Json, limit, None).await? {
            Outcome::Json(rows) => Ok(rows),
            Outcome::Inline(_) | Outcome::Export { .. } => panic!("Mode::Json yields Json"),
        }
    }

    #[tokio::test]
    async fn json_rows_are_objects_with_typed_values_and_omitted_nulls() {
        let result = run_json(
            "SELECT 'abc' AS session_id, \
                    TIMESTAMP '2026-09-25T04:00:02.384123Z' AS last_ts, \
                    TIMESTAMP '2026-09-25T04:00:02.384Z' AS whole_ms, \
                    3 AS n, true AS ok, CAST(NULL AS VARCHAR) AS gone",
            DEFAULT_INLINE_ROWS,
        )
        .await
        .expect("query runs");
        assert_eq!(
            result.columns,
            ["session_id", "last_ts", "whole_ms", "n", "ok", "gone"],
            "columns list every result column, the all-NULL one included"
        );
        assert_eq!(result.row_count, 1);
        assert!(!result.truncated);
        // Exactly six fractional digits: the microsecond cursor round-trips,
        // and a whole-millisecond value is not trimmed to `.384Z`.
        assert_eq!(
            result.rows,
            [serde_json::json!({
                "session_id": "abc",
                "last_ts": "2026-09-25T04:00:02.384123Z",
                "whole_ms": "2026-09-25T04:00:02.384000Z",
                "n": 3,
                "ok": true,
            })]
        );
    }

    #[tokio::test]
    async fn json_empty_result_still_names_its_columns() {
        let result = run_json("SELECT 1 AS n, 'x' AS s WHERE false", DEFAULT_INLINE_ROWS)
            .await
            .expect("query runs");
        assert_eq!(result.columns, ["n", "s"]);
        assert!(result.rows.is_empty());
        assert_eq!(result.row_count, 0);
        assert!(!result.truncated);
    }

    #[tokio::test]
    async fn json_row_cap_truncates_and_reports_it() {
        let sql = "SELECT value FROM generate_series(1, 150) ORDER BY value";
        let capped = run_json(sql, DEFAULT_INLINE_ROWS)
            .await
            .expect("query runs");
        assert_eq!(capped.row_count, DEFAULT_INLINE_ROWS);
        assert_eq!(capped.rows.len(), DEFAULT_INLINE_ROWS);
        assert!(capped.truncated, "the row cap cut the result");
        assert_eq!(capped.rows[0], serde_json::json!({"value": 1}));

        let whole = run_json(sql, 150).await.expect("query runs");
        assert_eq!(whole.row_count, 150);
        assert!(!whole.truncated, "a cap that fits cuts nothing");

        // No ORDER BY: the cap is pushed into the scan as a LIMIT, and one row
        // past it still reports the cut.
        let unordered = run_json("SELECT value FROM generate_series(1, 1000000)", 5)
            .await
            .expect("query runs");
        assert_eq!(unordered.row_count, 5);
        assert!(unordered.truncated);
    }

    #[test]
    fn storage_failures_are_told_apart_from_query_errors() {
        let io = || std::io::Error::other("connection reset");
        assert!(is_storage_failure(&DataFusionError::IoError(io())));
        let timed_out = object_store::Error::Generic {
            store: "S3",
            source: "request timed out".into(),
        };
        assert!(is_storage_failure(&DataFusionError::External(Box::new(
            lance::Error::from(timed_out)
        ))));
        assert!(!is_storage_failure(&DataFusionError::External(Box::new(
            lance::Error::io("resources exhausted")
        ))));
        assert!(is_storage_failure(&DataFusionError::Context(
            "scan".to_owned(),
            Box::new(DataFusionError::External(Box::new(io())))
        )));
        assert!(!is_storage_failure(&DataFusionError::Plan(
            "no such column".to_owned()
        )));
        assert!(!is_storage_failure(&DataFusionError::Execution(
            "division by zero".to_owned()
        )));
    }

    #[tokio::test]
    async fn json_mode_drops_binary_columns_like_export() {
        let result = run_json("SELECT X'00ff' AS raw, 1 AS n", DEFAULT_INLINE_ROWS)
            .await
            .expect("query runs");
        assert_eq!(result.columns, ["n"]);
        assert_eq!(result.rows, [serde_json::json!({"n": 1})]);
    }

    #[tokio::test]
    async fn json_mode_returns_explain_plan_rows_as_data() {
        let result = run_json("EXPLAIN SELECT 1", DEFAULT_INLINE_ROWS)
            .await
            .expect("EXPLAIN of a SELECT is allowed");
        assert_eq!(result.columns, ["plan_type", "plan"]);
        assert!(result.row_count > 0);
        assert!(
            run_json("DELETE FROM messages", DEFAULT_INLINE_ROWS)
                .await
                .is_err(),
            "the read-only gate holds in JSON mode"
        );
    }

    #[test]
    fn json_mode_renders_jsonb_as_text_and_drops_vectors() {
        let options =
            lance_arrow::json::JsonArray::try_from_iter([Some(r#"{"pond":{"host":"desk"}}"#)])
                .expect("valid json")
                .into_inner();
        let vector = lance::deps::arrow_array::FixedSizeListArray::from_iter_primitive::<
            lance::deps::arrow_array::types::Float32Type,
            _,
            _,
        >([Some([Some(0.5_f32), Some(0.25)])], 2);
        let schema = Arc::new(Schema::new(vec![
            lance_arrow::json::json_field("options", true),
            Field::new("vector", vector.data_type().clone(), true),
        ]));
        let batch =
            RecordBatch::try_new(schema, vec![Arc::new(options), Arc::new(vector)]).expect("batch");
        let display = displayable(&batch).expect("displayable");
        let result = json_rows(&[display], DEFAULT_INLINE_ROWS, Duration::ZERO).expect("json rows");
        assert_eq!(result.columns, ["options"], "the vector column is dropped");
        let text = result.rows[0]["options"]
            .as_str()
            .expect("JSONB arrives as JSON text, not a nested object");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(text).expect("valid JSON text"),
            serde_json::json!({"pond": {"host": "desk"}})
        );
    }

    fn text_rows(cells: &[&str]) -> RecordBatch {
        let schema = Arc::new(Schema::new(vec![Field::new("t", DataType::Utf8, true)]));
        RecordBatch::try_new(
            schema,
            vec![Arc::new(StringArray::from(
                cells.iter().map(|cell| Some(*cell)).collect::<Vec<_>>(),
            ))],
        )
        .expect("single-column batch")
    }

    #[test]
    fn json_budget_drops_rows_from_the_end_without_clipping_cells() {
        let fat = "x".repeat(JSON_BUDGET_BYTES * 2 / 5);
        let batch = text_rows(&[&fat, &fat, &fat]);
        let result = json_rows(&[batch], DEFAULT_INLINE_ROWS, Duration::ZERO).expect("json rows");
        assert_eq!(result.row_count, 2, "a third row overflows the budget");
        assert!(result.truncated, "the byte budget cut the result");
        assert_eq!(
            result.rows[1]["t"].as_str().map(str::len),
            Some(fat.len()),
            "cells are never clipped in JSON mode"
        );
    }

    #[test]
    fn json_budget_always_returns_the_first_row() {
        let huge = "y".repeat(JSON_BUDGET_BYTES + 1);
        let batch = text_rows(&[&huge, "small"]);
        let result = json_rows(&[batch], DEFAULT_INLINE_ROWS, Duration::ZERO).expect("json rows");
        assert_eq!(result.row_count, 1, "one oversized row still pages");
        assert!(result.truncated);
        assert_eq!(result.rows[0]["t"].as_str().map(str::len), Some(huge.len()));
    }

    #[test]
    fn effective_timeout_defaults_and_clamps() {
        assert_eq!(
            effective_timeout(None),
            Duration::from_secs(DEFAULT_QUERY_TIMEOUT_SECS)
        );
        assert_eq!(effective_timeout(Some(60)), Duration::from_secs(60));
        assert_eq!(effective_timeout(Some(0)), Duration::from_secs(1));
        assert_eq!(
            effective_timeout(Some(u64::MAX)),
            Duration::from_secs(MAX_QUERY_TIMEOUT_SECS)
        );
    }
}