jammi-db 0.28.0

Vector database, SQL federation, mutable companion tables, and trigger broker for Jammi AI
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
//! Catalog repository for evidence channels and their declared columns.

use std::sync::Arc;

use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use serde::{Deserialize, Serialize};

use crate::error::{JammiError, Result};
use crate::evidence_channel::ChannelId;

use super::backend::{BackendError, Row, SqlValue, TxOptions};
use super::Catalog;

/// The closed set of Arrow types a channel column may declare.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum ChannelColumnType {
    Float32,
    Float64,
    Int32,
    Int64,
    Utf8,
    Boolean,
}

impl ChannelColumnType {
    pub fn to_arrow(self) -> DataType {
        match self {
            Self::Float32 => DataType::Float32,
            Self::Float64 => DataType::Float64,
            Self::Int32 => DataType::Int32,
            Self::Int64 => DataType::Int64,
            Self::Utf8 => DataType::Utf8,
            Self::Boolean => DataType::Boolean,
        }
    }

    pub fn from_arrow(dt: &DataType) -> Result<Self> {
        match dt {
            DataType::Float32 => Ok(Self::Float32),
            DataType::Float64 => Ok(Self::Float64),
            DataType::Int32 => Ok(Self::Int32),
            DataType::Int64 => Ok(Self::Int64),
            DataType::Utf8 => Ok(Self::Utf8),
            DataType::Boolean => Ok(Self::Boolean),
            other => Err(JammiError::EvidenceChannel(format!(
                "unsupported channel column type: {other:?}"
            ))),
        }
    }

    /// The canonical PascalCase variant name (`"Float32"`, `"Utf8"`, …). This is
    /// the string form shared with the catalog's stored representation, with
    /// [`Self::from_sql_str`], and with public-API callers (the Python binding's
    /// `register_channel` / `list_channels`, which round-trips this exact token).
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Float32 => "Float32",
            Self::Float64 => "Float64",
            Self::Int32 => "Int32",
            Self::Int64 => "Int64",
            Self::Utf8 => "Utf8",
            Self::Boolean => "Boolean",
        }
    }

    /// Parse a PascalCase variant name (`"Float32"`, `"Utf8"`, …) into a
    /// `ChannelColumnType`. The canonical string form is shared with the
    /// catalog's stored representation and with public-API callers (e.g.
    /// the Python binding's `register_channel(columns=[(name, dtype_str)])`).
    pub fn from_sql_str(s: &str) -> Result<Self> {
        match s {
            "Float32" => Ok(Self::Float32),
            "Float64" => Ok(Self::Float64),
            "Int32" => Ok(Self::Int32),
            "Int64" => Ok(Self::Int64),
            "Utf8" => Ok(Self::Utf8),
            "Boolean" => Ok(Self::Boolean),
            other => Err(JammiError::EvidenceChannel(format!(
                "unknown channel column type stored in catalog: '{other}'"
            ))),
        }
    }
}

/// One declared column on a channel.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChannelColumn {
    pub name: String,
    pub data_type: ChannelColumnType,
}

/// The full declaration for one channel: identifier, priority, ordered columns.
#[derive(Debug, Clone)]
pub struct ChannelSpec {
    pub id: ChannelId,
    pub priority: i32,
    pub columns: Vec<ChannelColumn>,
}

/// Repository over `evidence_channels` and `evidence_channel_columns`.
///
/// Constructed via [`Catalog::channels`].
pub struct ChannelRepo<'a> {
    catalog: &'a Catalog,
}

fn map_constraint(e: BackendError, channel: &str) -> JammiError {
    match e {
        BackendError::Constraint { .. } => {
            JammiError::EvidenceChannel(format!("channel '{channel}': already exists"))
        }
        other => JammiError::BackendDriver(other),
    }
}

fn read_column_row(row: &Row<'_>) -> std::result::Result<(String, String), BackendError> {
    Ok((row.get("column_name")?, row.get("column_type")?))
}

/// Does a parent `evidence_channels` row exist for `(tenant, channel)`?
///
/// Branches on the tenant to honour the `None -> IS NULL` semantics: SQL
/// `tenant_id = NULL` never matches, so a global lookup must use `IS NULL`
/// rather than binding `NULL` as a parameter (mirrors `mutable_repo`).
async fn channel_exists(
    tx: &mut super::backend::Transaction<'_>,
    tenant: Option<&str>,
    channel: &str,
) -> std::result::Result<bool, BackendError> {
    let found = if let Some(t) = tenant {
        tx.query_opt(
            "SELECT 1 AS one FROM evidence_channels \
             WHERE tenant_id = $1 AND channel_name = $2",
            &[
                SqlValue::TextOwned(t.to_string()),
                SqlValue::TextOwned(channel.to_string()),
            ],
            |row| row.get::<i32>("one"),
        )
        .await?
    } else {
        tx.query_opt(
            "SELECT 1 AS one FROM evidence_channels \
             WHERE tenant_id IS NULL AND channel_name = $1",
            &[SqlValue::TextOwned(channel.to_string())],
            |row| row.get::<i32>("one"),
        )
        .await?
    };
    Ok(found.is_some())
}

/// Highest declared ordinal on `(tenant, channel)`, or `None` if no columns.
async fn max_ordinal(
    tx: &mut super::backend::Transaction<'_>,
    tenant: Option<&str>,
    channel: &str,
) -> std::result::Result<Option<i32>, BackendError> {
    let found = if let Some(t) = tenant {
        tx.query_opt(
            "SELECT MAX(ordinal) AS m FROM evidence_channel_columns \
             WHERE tenant_id = $1 AND channel_name = $2",
            &[
                SqlValue::TextOwned(t.to_string()),
                SqlValue::TextOwned(channel.to_string()),
            ],
            |row| row.try_get::<i32>("m"),
        )
        .await?
    } else {
        tx.query_opt(
            "SELECT MAX(ordinal) AS m FROM evidence_channel_columns \
             WHERE tenant_id IS NULL AND channel_name = $1",
            &[SqlValue::TextOwned(channel.to_string())],
            |row| row.try_get::<i32>("m"),
        )
        .await?
    };
    Ok(found.flatten())
}

/// The stored `column_type` for `(tenant, channel, column)`, or `None`.
async fn column_type(
    tx: &mut super::backend::Transaction<'_>,
    tenant: Option<&str>,
    channel: &str,
    column: &str,
) -> std::result::Result<Option<String>, BackendError> {
    if let Some(t) = tenant {
        tx.query_opt(
            "SELECT column_type FROM evidence_channel_columns \
             WHERE tenant_id = $1 AND channel_name = $2 AND column_name = $3",
            &[
                SqlValue::TextOwned(t.to_string()),
                SqlValue::TextOwned(channel.to_string()),
                SqlValue::TextOwned(column.to_string()),
            ],
            |row| row.get::<String>("column_type"),
        )
        .await
    } else {
        tx.query_opt(
            "SELECT column_type FROM evidence_channel_columns \
             WHERE tenant_id IS NULL AND channel_name = $1 AND column_name = $2",
            &[
                SqlValue::TextOwned(channel.to_string()),
                SqlValue::TextOwned(column.to_string()),
            ],
            |row| row.get::<String>("column_type"),
        )
        .await
    }
}

/// `(channel_name, priority, columns)` row as returned by `list()`'s catalog
/// query. Aliased to keep the inner closure's local type readable.
type ChannelListing = (String, i32, Vec<(String, String)>);

impl<'a> ChannelRepo<'a> {
    pub(super) fn new(catalog: &'a Catalog) -> Self {
        Self { catalog }
    }

    /// Register a new channel and its columns atomically, scoped to the
    /// catalog's currently-bound tenant.
    ///
    /// The channel name is unique *per tenant*: tenant B may register a channel
    /// whose name already exists under tenant A without collision, but a
    /// re-registration within the same tenant is rejected. The explicit
    /// tenant-scoped existence check below yields the friendly "already exists"
    /// error; the database enforces the same uniqueness authoritatively via two
    /// constraints — the `UNIQUE (tenant_id, channel_name)` constraint for the
    /// non-NULL (tenant-scoped) case, and the partial unique index on
    /// `channel_name WHERE tenant_id IS NULL` for the global (`tenant = None`)
    /// case (both backends treat NULLs as distinct in a UNIQUE constraint, so
    /// the composite constraint alone would not catch a duplicate global
    /// channel). Either backstop surfaces through the same
    /// `BackendError::Constraint` → "already exists" path as the explicit check.
    pub async fn register(&self, spec: &ChannelSpec) -> Result<()> {
        let tenant = self.catalog.current_tenant().map(|t| t.to_string());
        let channel = spec.id.as_str().to_string();
        let channel_for_err = channel.clone();
        let priority = spec.priority as i64;
        let columns: Vec<(String, &'static str, i64)> = spec
            .columns
            .iter()
            .enumerate()
            .map(|(i, c)| (c.name.clone(), c.data_type.as_str(), i as i64))
            .collect();

        let res = self
            .catalog
            .backend()
            .transaction(TxOptions::default(), |tx| {
                let tenant = tenant.clone();
                Box::pin(async move {
                    // Explicit per-tenant existence check for a friendly error.
                    // The DB constraints (composite UNIQUE for tenant-scoped,
                    // partial unique index for global) are the authoritative
                    // backstop; this surfaces the same "already exists" message.
                    let exists = channel_exists(tx, tenant.as_deref(), &channel).await?;
                    if exists {
                        return Err(BackendError::Constraint {
                            table: "evidence_channels".to_string(),
                            detail: "channel_name already registered for tenant".to_string(),
                        });
                    }

                    tx.execute(
                        "INSERT INTO evidence_channels (tenant_id, channel_name, priority) \
                         VALUES ($1, $2, $3)",
                        &[
                            SqlValue::from(tenant.clone()),
                            SqlValue::TextOwned(channel.clone()),
                            SqlValue::Int(priority),
                        ],
                    )
                    .await?;

                    for (name, ty, ord) in columns {
                        tx.execute(
                            "INSERT INTO evidence_channel_columns \
                             (tenant_id, channel_name, column_name, column_type, ordinal) \
                             VALUES ($1, $2, $3, $4, $5)",
                            &[
                                SqlValue::from(tenant.clone()),
                                SqlValue::TextOwned(channel.clone()),
                                SqlValue::TextOwned(name),
                                SqlValue::Text(ty),
                                SqlValue::Int(ord),
                            ],
                        )
                        .await?;
                    }
                    Ok(())
                })
            })
            .await;

        res.map_err(|e| map_constraint(e, &channel_for_err))?;
        Ok(())
    }

    /// Append new columns to an already-registered channel. Append-only.
    /// Scoped to the catalog's currently-bound tenant: a channel is resolved,
    /// and its columns appended, only within the bound tenant's namespace.
    pub async fn add_columns(
        &self,
        channel: &ChannelId,
        new_columns: &[ChannelColumn],
    ) -> Result<()> {
        let tenant = self.catalog.current_tenant().map(|t| t.to_string());
        let channel_name = channel.as_str().to_string();
        let channel_for_err = channel_name.clone();
        let cols: Vec<(String, ChannelColumnType)> = new_columns
            .iter()
            .map(|c| (c.name.clone(), c.data_type))
            .collect();

        self.catalog
            .backend()
            .transaction(TxOptions::default(), |tx| {
                let tenant = tenant.clone();
                Box::pin(async move {
                    let tref = tenant.as_deref();
                    // Existence check on the parent row, tenant-scoped.
                    if !channel_exists(tx, tref, &channel_name).await? {
                        return Err(BackendError::Execution(format!(
                            "channel '{channel_for_err}': not registered"
                        )));
                    }

                    let max_ord = max_ordinal(tx, tref, &channel_name).await?;
                    let mut next = max_ord.unwrap_or(-1) + 1;

                    for (name, ty) in cols {
                        let existing = column_type(tx, tref, &channel_name, &name).await?;
                        if let Some(existing_type) = existing {
                            let existing = ChannelColumnType::from_sql_str(&existing_type)
                                .map_err(|e| BackendError::Execution(e.to_string()))?;
                            if existing == ty {
                                return Err(BackendError::Execution(format!(
                                    "channel '{channel_for_err}': column '{name}' already declared"
                                )));
                            } else {
                                return Err(BackendError::Execution(format!(
                                    "channel '{channel_for_err}': column '{name}' was declared {}, \
                                     cannot redeclare as {}",
                                    existing.as_str(),
                                    ty.as_str(),
                                )));
                            }
                        }

                        tx.execute(
                            "INSERT INTO evidence_channel_columns \
                             (tenant_id, channel_name, column_name, column_type, ordinal) \
                             VALUES ($1, $2, $3, $4, $5)",
                            &[
                                SqlValue::from(tenant.clone()),
                                SqlValue::TextOwned(channel_name.clone()),
                                SqlValue::TextOwned(name),
                                SqlValue::Text(ty.as_str()),
                                SqlValue::Int(next as i64),
                            ],
                        )
                        .await?;
                        next += 1;
                    }
                    Ok(())
                })
            })
            .await
            .map_err(|e| match e {
                BackendError::Execution(m) => JammiError::EvidenceChannel(m),
                other => JammiError::BackendDriver(other),
            })?;
        Ok(())
    }

    /// Look up one channel's full spec, resolved in the catalog's currently-bound
    /// tenant namespace.
    ///
    /// A tenant resolves its OWN channel if it has registered one of that name,
    /// otherwise it falls back to the GLOBAL (`tenant_id IS NULL`) channel — the
    /// same own-shadows-global precedence the model catalog uses (#140). This is
    /// what lets every tenant resolve the global seed channels (`vector`,
    /// `inference`, `bm25`) while still owning a private channel of the same
    /// name. A `tenant = None` lookup resolves only global rows. Crucially, a
    /// tenant NEVER resolves another tenant's row. Once the owning `tenant_id` is
    /// resolved, the columns are read under that SAME `tenant_id`, so a tenant's
    /// channel and a global channel of the same name never blend their columns.
    pub async fn get(&self, channel: &ChannelId) -> Result<Option<ChannelSpec>> {
        let tenant = self.catalog.current_tenant().map(|t| t.to_string());
        let channel_name = channel.as_str().to_string();
        let id = channel.clone();
        let found = self
            .catalog
            .backend()
            .transaction(
                TxOptions {
                    read_only: true,
                    ..Default::default()
                },
                |tx| {
                    let channel_name = channel_name.clone();
                    let tenant = tenant.clone();
                    Box::pin(async move {
                        let tref = tenant.as_deref();
                        // Resolve the owning row: own-tenant shadows global.
                        let resolved = if let Some(t) = tref {
                            tx.query_opt(
                                "SELECT tenant_id, priority FROM evidence_channels \
                                 WHERE (tenant_id = $1 OR tenant_id IS NULL) AND channel_name = $2 \
                                 ORDER BY (tenant_id IS NOT NULL) DESC LIMIT 1",
                                &[
                                    SqlValue::TextOwned(t.to_string()),
                                    SqlValue::TextOwned(channel_name.clone()),
                                ],
                                |row| {
                                    Ok((
                                        row.try_get::<String>("tenant_id")?,
                                        row.get::<i32>("priority")?,
                                    ))
                                },
                            )
                            .await?
                        } else {
                            tx.query_opt(
                                "SELECT tenant_id, priority FROM evidence_channels \
                                 WHERE tenant_id IS NULL AND channel_name = $1",
                                &[SqlValue::TextOwned(channel_name.clone())],
                                |row| {
                                    Ok((
                                        row.try_get::<String>("tenant_id")?,
                                        row.get::<i32>("priority")?,
                                    ))
                                },
                            )
                            .await?
                        };
                        let Some((row_tenant, priority)) = resolved else {
                            return Ok(None);
                        };
                        // Read columns under the SAME resolved tenant_id.
                        let cols = if let Some(rt) = row_tenant {
                            tx.query(
                                "SELECT column_name, column_type FROM evidence_channel_columns \
                                 WHERE tenant_id = $1 AND channel_name = $2 ORDER BY ordinal",
                                &[SqlValue::TextOwned(rt), SqlValue::TextOwned(channel_name)],
                                read_column_row,
                            )
                            .await?
                        } else {
                            tx.query(
                                "SELECT column_name, column_type FROM evidence_channel_columns \
                                 WHERE tenant_id IS NULL AND channel_name = $1 ORDER BY ordinal",
                                &[SqlValue::TextOwned(channel_name)],
                                read_column_row,
                            )
                            .await?
                        };
                        Ok(Some((priority, cols)))
                    })
                },
            )
            .await?;

        let Some((priority, raw_cols)) = found else {
            return Ok(None);
        };
        let columns: Result<Vec<ChannelColumn>> = raw_cols
            .into_iter()
            .map(|(name, ty)| {
                Ok(ChannelColumn {
                    name,
                    data_type: ChannelColumnType::from_sql_str(&ty)?,
                })
            })
            .collect();
        Ok(Some(ChannelSpec {
            id,
            priority,
            columns: columns?,
        }))
    }

    /// List every registered channel resolved in the catalog's currently-bound
    /// tenant namespace, ordered by `(priority, channel_name)`.
    ///
    /// A tenant sees its OWN channels plus the GLOBAL (`tenant_id IS NULL`)
    /// channels it has not shadowed — its own channel of a given name takes
    /// precedence over a global one of the same name (the #140 own-shadows-global
    /// rule). It NEVER sees another tenant's channels. A `tenant = None` listing
    /// returns only global rows.
    pub async fn list(&self) -> Result<Vec<ChannelSpec>> {
        let tenant = self.catalog.current_tenant().map(|t| t.to_string());
        let entries = self
            .catalog
            .backend()
            .transaction(
                TxOptions {
                    read_only: true,
                    ..Default::default()
                },
                |tx| {
                    let tenant = tenant.clone();
                    Box::pin(async move {
                        let tref = tenant.as_deref();
                        // Candidate parents: own (if any) and global. Own rows
                        // sort first so the dedup-by-name keeps the tenant's row
                        // ahead of a global row of the same name.
                        let candidates: Vec<(Option<String>, String, i32)> = if let Some(t) = tref {
                            tx.query(
                                "SELECT tenant_id, channel_name, priority FROM evidence_channels \
                                 WHERE tenant_id = $1 OR tenant_id IS NULL \
                                 ORDER BY (tenant_id IS NOT NULL) DESC, priority, channel_name",
                                &[SqlValue::TextOwned(t.to_string())],
                                |row| {
                                    Ok((
                                        row.try_get::<String>("tenant_id")?,
                                        row.get::<String>("channel_name")?,
                                        row.get::<i32>("priority")?,
                                    ))
                                },
                            )
                            .await?
                        } else {
                            tx.query(
                                "SELECT tenant_id, channel_name, priority FROM evidence_channels \
                                 WHERE tenant_id IS NULL ORDER BY priority, channel_name",
                                &[],
                                |row| {
                                    Ok((
                                        row.try_get::<String>("tenant_id")?,
                                        row.get::<String>("channel_name")?,
                                        row.get::<i32>("priority")?,
                                    ))
                                },
                            )
                            .await?
                        };

                        // Dedup by channel_name, keeping the first occurrence
                        // (own shadows global because own rows are ordered first).
                        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
                        let mut resolved: Vec<(Option<String>, String, i32)> =
                            Vec::with_capacity(candidates.len());
                        for (row_tenant, name, priority) in candidates {
                            if seen.insert(name.clone()) {
                                resolved.push((row_tenant, name, priority));
                            }
                        }

                        let mut out: Vec<ChannelListing> = Vec::with_capacity(resolved.len());
                        for (row_tenant, name, priority) in resolved {
                            let cols = if let Some(rt) = row_tenant {
                                tx.query(
                                    "SELECT column_name, column_type \
                                     FROM evidence_channel_columns \
                                     WHERE tenant_id = $1 AND channel_name = $2 ORDER BY ordinal",
                                    &[
                                        SqlValue::TextOwned(rt),
                                        SqlValue::TextOwned(name.clone()),
                                    ],
                                    read_column_row,
                                )
                                .await?
                            } else {
                                tx.query(
                                    "SELECT column_name, column_type \
                                     FROM evidence_channel_columns \
                                     WHERE tenant_id IS NULL AND channel_name = $1 ORDER BY ordinal",
                                    &[SqlValue::TextOwned(name.clone())],
                                    read_column_row,
                                )
                                .await?
                            };
                            out.push((name, priority, cols));
                        }
                        // Re-establish the documented (priority, channel_name)
                        // order after the own-first dedup pass.
                        out.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
                        Ok(out)
                    })
                },
            )
            .await?;

        let mut specs = Vec::with_capacity(entries.len());
        for (name, priority, raw_cols) in entries {
            let id = ChannelId::new(name)?;
            let columns: Result<Vec<ChannelColumn>> = raw_cols
                .into_iter()
                .map(|(cname, ctype)| {
                    Ok(ChannelColumn {
                        name: cname,
                        data_type: ChannelColumnType::from_sql_str(&ctype)?,
                    })
                })
                .collect();
            specs.push(ChannelSpec {
                id,
                priority,
                columns: columns?,
            });
        }
        Ok(specs)
    }

    /// Build the Arrow schema produced by merging the given channels'
    /// declared columns in `(priority, ordinal)` order.
    pub async fn merged_schema(&self, participating: &[ChannelId]) -> Result<SchemaRef> {
        let mut specs: Vec<ChannelSpec> = Vec::with_capacity(participating.len());
        for id in participating {
            let spec = self.get(id).await?.ok_or_else(|| {
                JammiError::EvidenceChannel(format!("channel '{id}': not registered"))
            })?;
            specs.push(spec);
        }
        specs.sort_by_key(|s| s.priority);

        let mut fields: Vec<Field> = Vec::new();
        for spec in specs {
            for col in spec.columns {
                fields.push(Field::new(&col.name, col.data_type.to_arrow(), true));
            }
        }
        Ok(Arc::new(Schema::new(fields)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    async fn open_catalog() -> (tempfile::TempDir, Catalog) {
        let dir = tempdir().unwrap();
        let catalog = Catalog::open(dir.path()).await.unwrap();
        (dir, catalog)
    }

    #[test]
    fn type_to_and_from_arrow_round_trip() {
        for t in [
            ChannelColumnType::Float32,
            ChannelColumnType::Float64,
            ChannelColumnType::Int32,
            ChannelColumnType::Int64,
            ChannelColumnType::Utf8,
            ChannelColumnType::Boolean,
        ] {
            let arrow = t.to_arrow();
            assert_eq!(ChannelColumnType::from_arrow(&arrow).unwrap(), t);
        }
    }

    #[test]
    fn from_arrow_rejects_unsupported_type() {
        let err = ChannelColumnType::from_arrow(&DataType::UInt16).unwrap_err();
        assert!(matches!(err, JammiError::EvidenceChannel(_)));
    }

    #[test]
    fn from_sql_str_rejects_unknown_token() {
        assert!(ChannelColumnType::from_sql_str("Decimal").is_err());
    }

    #[test]
    fn serde_uses_pascal_case() {
        let json = serde_json::to_string(&ChannelColumnType::Float32).unwrap();
        assert_eq!(json, "\"Float32\"");
        let parsed: ChannelColumnType = serde_json::from_str("\"Utf8\"").unwrap();
        assert_eq!(parsed, ChannelColumnType::Utf8);
    }

    #[test]
    fn serde_rejects_unknown_variant_loudly() {
        let r: std::result::Result<ChannelColumnType, _> = serde_json::from_str("\"Decimal\"");
        assert!(r.is_err());
    }

    #[tokio::test]
    async fn seed_channels_visible_via_list() {
        let (_dir, catalog) = open_catalog().await;
        let channels = catalog.channels().list().await.unwrap();
        let names: Vec<&str> = channels.iter().map(|c| c.id.as_str()).collect();
        assert!(names.contains(&"vector"));
        assert!(names.contains(&"inference"));
    }

    #[tokio::test]
    async fn vector_channel_has_similarity_column() {
        let (_dir, catalog) = open_catalog().await;
        let vector = catalog
            .channels()
            .get(&ChannelId::new("vector").unwrap())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(vector.columns.len(), 1);
        assert_eq!(vector.columns[0].name, "similarity");
        assert_eq!(vector.columns[0].data_type, ChannelColumnType::Float32);
    }

    #[tokio::test]
    async fn inference_channel_columns_ordered_by_ordinal() {
        let (_dir, catalog) = open_catalog().await;
        let inference = catalog
            .channels()
            .get(&ChannelId::new("inference").unwrap())
            .await
            .unwrap()
            .unwrap();
        let names: Vec<&str> = inference.columns.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["inference_model", "inference_task", "inference_confidence"]
        );
    }

    #[tokio::test]
    async fn register_then_get_round_trip() {
        let (_dir, catalog) = open_catalog().await;
        let id = ChannelId::new("scored_by").unwrap();
        let spec = ChannelSpec {
            id: id.clone(),
            priority: 3,
            columns: vec![
                ChannelColumn {
                    name: "ranker".into(),
                    data_type: ChannelColumnType::Utf8,
                },
                ChannelColumn {
                    name: "rank_score".into(),
                    data_type: ChannelColumnType::Float32,
                },
            ],
        };
        catalog.channels().register(&spec).await.unwrap();

        let got = catalog.channels().get(&id).await.unwrap().unwrap();
        assert_eq!(got.priority, 3);
        assert_eq!(got.columns.len(), 2);
        assert_eq!(got.columns[0].name, "ranker");
        assert_eq!(got.columns[1].name, "rank_score");
    }

    #[tokio::test]
    async fn register_rejects_duplicate_channel() {
        let (_dir, catalog) = open_catalog().await;
        let id = ChannelId::new("scored_by").unwrap();
        let spec = ChannelSpec {
            id: id.clone(),
            priority: 3,
            columns: vec![ChannelColumn {
                name: "ranker".into(),
                data_type: ChannelColumnType::Utf8,
            }],
        };
        catalog.channels().register(&spec).await.unwrap();
        let err = catalog.channels().register(&spec).await.unwrap_err();
        match err {
            JammiError::EvidenceChannel(m) => assert!(m.contains("already exists")),
            other => panic!("expected EvidenceChannel(already exists), got {other:?}"),
        }
    }

    /// A duplicate GLOBAL (unbound, `tenant = None`) registration is rejected the
    /// second time with the SAME "already exists" semantics as a tenant-scoped
    /// duplicate. `open_catalog` binds no tenant, so both `register` calls write
    /// `tenant_id IS NULL`; the partial unique index added in migration 020 is the
    /// DB-level backstop for this case (the composite `UNIQUE (tenant_id,
    /// channel_name)` treats NULLs as distinct and cannot catch it). Serial is
    /// sufficient to pin the constraint + error path — the concurrent Postgres
    /// race is closed by that same DB index, not by this test.
    #[tokio::test]
    async fn register_rejects_duplicate_global_channel() {
        let (_dir, catalog) = open_catalog().await;
        let spec = ChannelSpec {
            id: ChannelId::new("global_chan").unwrap(),
            priority: 5,
            columns: vec![ChannelColumn {
                name: "marker".into(),
                data_type: ChannelColumnType::Utf8,
            }],
        };
        catalog.channels().register(&spec).await.unwrap();
        let err = catalog.channels().register(&spec).await.unwrap_err();
        match err {
            JammiError::EvidenceChannel(m) => assert!(
                m.contains("already exists"),
                "global duplicate must reject with the same 'already exists' semantics, got: {m}"
            ),
            other => panic!("expected EvidenceChannel(already exists), got {other:?}"),
        }
    }

    #[tokio::test]
    async fn add_columns_appends_with_continuous_ordinal() {
        let (_dir, catalog) = open_catalog().await;
        let id = ChannelId::new("scored_by").unwrap();
        let spec = ChannelSpec {
            id: id.clone(),
            priority: 3,
            columns: vec![ChannelColumn {
                name: "ranker".into(),
                data_type: ChannelColumnType::Utf8,
            }],
        };
        catalog.channels().register(&spec).await.unwrap();

        catalog
            .channels()
            .add_columns(
                &id,
                &[ChannelColumn {
                    name: "rank_score".into(),
                    data_type: ChannelColumnType::Float32,
                }],
            )
            .await
            .unwrap();

        let got = catalog.channels().get(&id).await.unwrap().unwrap();
        assert_eq!(got.columns.len(), 2);
        assert_eq!(got.columns[0].name, "ranker");
        assert_eq!(got.columns[1].name, "rank_score");
    }

    #[tokio::test]
    async fn add_columns_rejects_redeclaration_with_same_type() {
        let (_dir, catalog) = open_catalog().await;
        let id = ChannelId::new("scored_by").unwrap();
        catalog
            .channels()
            .register(&ChannelSpec {
                id: id.clone(),
                priority: 3,
                columns: vec![ChannelColumn {
                    name: "ranker".into(),
                    data_type: ChannelColumnType::Utf8,
                }],
            })
            .await
            .unwrap();

        let err = catalog
            .channels()
            .add_columns(
                &id,
                &[ChannelColumn {
                    name: "ranker".into(),
                    data_type: ChannelColumnType::Utf8,
                }],
            )
            .await
            .unwrap_err();
        match err {
            JammiError::EvidenceChannel(m) => assert!(m.contains("already declared")),
            other => panic!("expected EvidenceChannel(already declared), got {other:?}"),
        }
    }

    #[tokio::test]
    async fn add_columns_rejects_redeclaration_with_different_type() {
        let (_dir, catalog) = open_catalog().await;
        let id = ChannelId::new("scored_by").unwrap();
        catalog
            .channels()
            .register(&ChannelSpec {
                id: id.clone(),
                priority: 3,
                columns: vec![ChannelColumn {
                    name: "ranker".into(),
                    data_type: ChannelColumnType::Utf8,
                }],
            })
            .await
            .unwrap();

        let err = catalog
            .channels()
            .add_columns(
                &id,
                &[ChannelColumn {
                    name: "ranker".into(),
                    data_type: ChannelColumnType::Int32,
                }],
            )
            .await
            .unwrap_err();
        match err {
            JammiError::EvidenceChannel(m) => {
                assert!(m.contains("cannot redeclare"));
                assert!(m.contains("Utf8"));
                assert!(m.contains("Int32"));
            }
            other => panic!("expected EvidenceChannel(cannot redeclare), got {other:?}"),
        }
    }

    #[tokio::test]
    async fn merged_schema_orders_by_priority_then_ordinal() {
        let (_dir, catalog) = open_catalog().await;
        let vector = ChannelId::new("vector").unwrap();
        let inference = ChannelId::new("inference").unwrap();
        let schema = catalog
            .channels()
            .merged_schema(&[inference.clone(), vector.clone()])
            .await
            .unwrap();
        let names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect();
        assert_eq!(
            names,
            vec![
                "similarity",
                "inference_model",
                "inference_task",
                "inference_confidence",
            ]
        );
    }

    #[tokio::test]
    async fn merged_schema_errors_on_unregistered_channel() {
        let (_dir, catalog) = open_catalog().await;
        let err = catalog
            .channels()
            .merged_schema(&[ChannelId::new("nonexistent").unwrap()])
            .await
            .unwrap_err();
        match err {
            JammiError::EvidenceChannel(m) => assert!(m.contains("not registered")),
            other => panic!("expected EvidenceChannel(not registered), got {other:?}"),
        }
    }
}