tango-core 0.3.0

The tango schema, entities, migrations, and search contract
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
//! What was said, and where: the transcript search RPCs.
//!
//! `search_transcripts`, `count_transcripts` and `search_video_transcript` are
//! the public functions `docs/rpc.md` documents; this module is the one place
//! in the workspace they are called from. The binding list is why. The page
//! call takes ten arguments and the count six of the same filters in a
//! different order, so a second copy of the call is how a page size ends up
//! bound to `p_require_all` - the mistake the API's own comment describes, and
//! one no test would have to fail for it to reach production.
//!
//! Every argument is passed by name (`p_query => $1`), which is what `rpc.md`
//! tells outside callers to do. Both consumers then exercise the convention
//! the contract documents rather than a positional call only this code knows
//! is correct.

use sea_orm::{ConnectionTrait, DatabaseConnection, DbBackend, QueryResult, Statement};
use serde::{Deserialize, Serialize};

/// What `rpc.md` documents as the default page size, and what the CLI uses.
pub const DEFAULT_PAGE_SIZE: u32 = 24;

/// What a transcript search is ordered by.
///
/// A closed enum, because `search_transcripts` resolves the key through guarded
/// CASE arms: it takes a value, never SQL, and raises on anything this does not
/// name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TranscriptSort {
    /// Best first: `matched_terms`, then `context_matches`, then `rank`, then
    /// playback order. The only sort that means anything on its own, and the
    /// order `docs/rpc.md` calls the relevance order.
    #[default]
    Rank,
    PublishedAt,
    ViewCount,
    /// Earliest first: where a topic first comes up, rather than where it is
    /// discussed most densely.
    StartMs,
}

impl TranscriptSort {
    /// The key as `search_transcripts` expects it.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Rank => "rank",
            Self::PublishedAt => "published_at",
            Self::ViewCount => "view_count",
            Self::StartMs => "start_ms",
        }
    }

    /// Parses a sort key, with the list in the message so a mistyped key is
    /// answerable without the source. A plain message rather than an error
    /// enum, because the CLI and the API want different things from a refusal:
    /// one prints it, the other turns it into a 400.
    pub fn parse(raw: &str) -> anyhow::Result<Self> {
        match raw {
            "rank" => Ok(Self::Rank),
            "published_at" => Ok(Self::PublishedAt),
            "view_count" => Ok(Self::ViewCount),
            "start_ms" => Ok(Self::StartMs),
            other => anyhow::bail!(
                "unknown transcript sort key {other:?}. Expected one of: rank, published_at, \
                 view_count, start_ms"
            ),
        }
    }
}

impl std::str::FromStr for TranscriptSort {
    type Err = anyhow::Error;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        Self::parse(raw)
    }
}

/// Which caption pool a track came from.
///
/// `manual` is authored, `auto` is speech recognition, and the two differ in
/// quality by more than any other attribute of a track.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TranscriptSource {
    Manual,
    Auto,
}

impl TranscriptSource {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Manual => "manual",
            Self::Auto => "auto",
        }
    }

    pub fn parse(raw: &str) -> anyhow::Result<Self> {
        match raw {
            "manual" => Ok(Self::Manual),
            "auto" => Ok(Self::Auto),
            other => anyhow::bail!("unknown transcript source {other:?}. Expected: manual, auto"),
        }
    }
}

impl std::str::FromStr for TranscriptSource {
    type Err = anyhow::Error;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        Self::parse(raw)
    }
}

/// One transcript search: the filters the page and the count share, plus the
/// page and the sort.
///
/// `page` is one-based and `page_size` in rows, like
/// [`crate::search::SearchQuery`]. The functions take `p_limit`/`p_offset`,
/// zero-based; the conversion happens here, beside the saturation rule, so the
/// two front ends cannot round it differently.
#[derive(Debug, Clone)]
pub struct TranscriptQuery {
    pub text: String,
    pub page: u32,
    pub page_size: u32,
    /// Every term must appear in the video's deduplicated transcript, not in
    /// the returned utterance: no sixteen-word cue holds a phrase like `dark
    /// root basin` even when the video discusses it for ten minutes. See
    /// `rpc.md` for why there is no fallback to any-term.
    pub require_all: bool,
    pub video_id: Option<String>,
    /// BCP-47, e.g. `en`.
    pub lang: Option<String>,
    pub source: Option<TranscriptSource>,
    pub sort_by: TranscriptSort,
    /// Descending. Meaningful for every key here, the default sort included.
    pub desc: bool,
    /// Literal and adjacent, over the `simple` configuration, so `racing` is
    /// not satisfied by `race`.
    pub exact: bool,
}

/// A row of `search_transcripts`: one matching utterance, and where it is.
#[derive(Debug, Clone)]
pub struct TranscriptCueRow {
    pub video_id: String,
    pub video_title: String,
    pub lang: String,
    /// `manual` or `auto`.
    pub source: String,
    pub cue_index: i32,
    pub start_ms: i32,
    pub end_ms: i32,
    pub content: String,
    /// The matched part, with `»` and `«` around the hit.
    pub snippet: String,
    /// Cover density over the utterance, `ts_rank_cd`. The lowest of the three
    /// relevance signals; see the traps section of `rpc.md` before sorting or
    /// comparing on it.
    pub rank: f32,
    /// How many distinct query terms this utterance carries.
    pub matched_terms: i64,
    /// Matching utterances within +-300 s, in the same video and track.
    pub context_matches: i64,
    pub published_at: Option<chrono::DateTime<chrono::Utc>>,
    pub view_count: Option<i64>,
}

impl TranscriptCueRow {
    fn from_row(row: &QueryResult) -> anyhow::Result<Self> {
        Ok(Self {
            video_id: row.try_get("", "video_id")?,
            video_title: row.try_get("", "video_title")?,
            lang: row.try_get("", "lang")?,
            source: row.try_get("", "source")?,
            cue_index: row.try_get("", "cue_index")?,
            start_ms: row.try_get("", "start_ms")?,
            end_ms: row.try_get("", "end_ms")?,
            content: row.try_get("", "content")?,
            snippet: row.try_get("", "snippet")?,
            rank: row.try_get("", "rank")?,
            matched_terms: row.try_get("", "matched_terms")?,
            context_matches: row.try_get("", "context_matches")?,
            published_at: row.try_get("", "published_at")?,
            view_count: row.try_get("", "view_count")?,
        })
    }
}

/// A row of `search_video_transcript`: one matching cue in one video, with the
/// `moment` number the function assigns - cues more than ten seconds apart
/// begin a new moment, so the rolling repeats around one mention group.
#[derive(Debug, Clone)]
pub struct TranscriptMomentRow {
    pub cue_index: i32,
    pub start_ms: i32,
    pub end_ms: i32,
    pub content: String,
    pub snippet: String,
    pub matched_terms: i64,
    pub moment: i32,
    /// Comes back from the function already carrying `&t=`.
    pub url: String,
}

impl TranscriptMomentRow {
    fn from_row(row: &QueryResult) -> anyhow::Result<Self> {
        Ok(Self {
            cue_index: row.try_get("", "cue_index")?,
            start_ms: row.try_get("", "start_ms")?,
            end_ms: row.try_get("", "end_ms")?,
            content: row.try_get("", "content")?,
            snippet: row.try_get("", "snippet")?,
            matched_terms: row.try_get("", "matched_terms")?,
            moment: row.try_get("", "moment")?,
            url: row.try_get("", "url")?,
        })
    }
}

/// Every argument of the page call, by name.
const SEARCH: &str = "SELECT * FROM public.search_transcripts(\
     p_query => $1, p_limit => $2, p_offset => $3, p_require_all => $4, \
     p_video_id => $5, p_lang => $6, p_source => $7, \
     p_sort_by => $8, p_sort_desc => $9, p_exact => $10)";

/// The same filters the count takes, by name. Fewer arguments, and not the
/// same first six: `search_transcripts` is `(p_query, p_limit, p_offset,
/// p_require_all, ...)` and this is `(p_query, p_require_all, ...)`.
const COUNT: &str = "SELECT public.count_transcripts(\
     p_query => $1, p_require_all => $2, p_video_id => $3, p_lang => $4, \
     p_source => $5, p_exact => $6) AS count";

const MOMENTS: &str = "SELECT * FROM public.search_video_transcript(\
     p_video_id => $1, p_query => $2, p_lang => $3, p_source => $4)";

/// One page of matching utterances, ordered by `q`.
pub async fn search(
    db: &DatabaseConnection,
    q: &TranscriptQuery,
) -> anyhow::Result<Vec<TranscriptCueRow>> {
    let statement = Statement::from_sql_and_values(DbBackend::Postgres, SEARCH, page_values(q));

    let rows = db
        .query_all_raw(statement)
        .await
        .map_err(|e| anyhow::anyhow!("transcript search failed: {e}"))?;

    rows.iter().map(TranscriptCueRow::from_row).collect()
}

/// How many utterances the same query matches in total.
///
/// Counts the same scan the page comes from, so a total and a page cannot
/// describe different searches. A caller that wants a pager needs this, and
/// the page it just fetched cannot stand in for it: the page may be empty
/// while the total is not.
pub async fn count(db: &DatabaseConnection, q: &TranscriptQuery) -> anyhow::Result<u64> {
    let statement = Statement::from_sql_and_values(DbBackend::Postgres, COUNT, count_values(q));

    let row = db
        .query_one_raw(statement)
        .await
        .map_err(|e| anyhow::anyhow!("transcript count failed: {e}"))?;

    // `count_transcripts` returns bigint, and sqlx-postgres has no u64 codec -
    // reading it as one fails at runtime. A count is never negative, so the
    // clamp is total.
    Ok(row
        .map(|row| row.try_get::<i64>("", "count"))
        .transpose()?
        .unwrap_or(0)
        .max(0) as u64)
}

/// Every matching cue in one video, in playback order and capped at 200 rows
/// by the function itself.
pub async fn moments(
    db: &DatabaseConnection,
    video_id: &str,
    text: &str,
    lang: Option<&str>,
    source: Option<TranscriptSource>,
) -> anyhow::Result<Vec<TranscriptMomentRow>> {
    let values = vec![
        video_id.to_string().into(),
        text.to_string().into(),
        lang.map(str::to_string).into(),
        source_value(source),
    ];

    let statement = Statement::from_sql_and_values(DbBackend::Postgres, MOMENTS, values);

    let rows = db
        .query_all_raw(statement)
        .await
        .map_err(|e| anyhow::anyhow!("transcript moments failed: {e}"))?;

    rows.iter().map(TranscriptMomentRow::from_row).collect()
}

/// The values the page call binds, in the order `SEARCH` names them.
fn page_values(q: &TranscriptQuery) -> Vec<sea_orm::Value> {
    vec![
        q.text.clone().into(),
        limit(q).into(),
        offset(q).into(),
        q.require_all.into(),
        optional(&q.video_id),
        optional(&q.lang),
        source_value(q.source),
        q.sort_by.as_str().into(),
        q.desc.into(),
        q.exact.into(),
    ]
}

/// The values the counting call binds, named one by one rather than sliced
/// off the page call: the two lists overlap in the middle and nowhere else.
fn count_values(q: &TranscriptQuery) -> Vec<sea_orm::Value> {
    vec![
        q.text.clone().into(),
        q.require_all.into(),
        optional(&q.video_id),
        optional(&q.lang),
        source_value(q.source),
        q.exact.into(),
    ]
}

/// `int`, not `bigint`: the functions declare `integer`, and Postgres will not
/// resolve a call across an implicit widening cast.
fn limit(q: &TranscriptQuery) -> i32 {
    i32::try_from(q.page_size).unwrap_or(i32::MAX)
}

/// The offset saturates rather than wrapping: a page large enough to overflow
/// would otherwise become a negative offset and read as the *beginning* of the
/// result set rather than past its end.
fn offset(q: &TranscriptQuery) -> i32 {
    let rows = u64::from(q.page.max(1) - 1) * u64::from(q.page_size);
    i32::try_from(rows).unwrap_or(i32::MAX)
}

/// A nullable text parameter. `Value::String(None)` is SQL NULL; the functions
/// treat NULL as "every value", which is the single definition of an unset
/// filter.
fn optional(value: &Option<String>) -> sea_orm::Value {
    match value {
        Some(value) => value.clone().into(),
        None => sea_orm::Value::String(None),
    }
}

fn source_value(source: Option<TranscriptSource>) -> sea_orm::Value {
    match source {
        Some(source) => source.as_str().to_string().into(),
        None => sea_orm::Value::String(None),
    }
}

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

    fn query() -> TranscriptQuery {
        TranscriptQuery {
            text: "root canal".into(),
            page: 1,
            page_size: DEFAULT_PAGE_SIZE,
            require_all: false,
            video_id: None,
            lang: None,
            source: None,
            sort_by: TranscriptSort::Rank,
            desc: true,
            exact: false,
        }
    }

    #[test]
    fn sort_keys_round_trip_through_the_function_spelling() {
        for sort in [
            TranscriptSort::Rank,
            TranscriptSort::PublishedAt,
            TranscriptSort::ViewCount,
            TranscriptSort::StartMs,
        ] {
            assert_eq!(TranscriptSort::parse(sort.as_str()).unwrap(), sort);
        }
    }

    #[test]
    fn an_unknown_sort_key_names_the_ones_that_exist() {
        let err = TranscriptSort::parse("relevance").unwrap_err().to_string();
        assert!(err.contains("rank"), "{err}");
        assert!(err.contains("published_at"), "{err}");
    }

    #[test]
    fn source_keys_round_trip_and_an_unknown_one_is_refused() {
        for source in [TranscriptSource::Manual, TranscriptSource::Auto] {
            assert_eq!(TranscriptSource::parse(source.as_str()).unwrap(), source);
        }
        assert!(TranscriptSource::parse("generated").is_err());
    }

    #[test]
    fn pages_are_one_based_and_the_offset_never_wraps() {
        let mut q = query();
        assert_eq!(offset(&q), 0);

        q.page = 3;
        assert_eq!(offset(&q), 48);

        // Page 0 reads as page 1, rather than as a negative offset.
        q.page = 0;
        assert_eq!(offset(&q), 0);

        q.page = u32::MAX;
        q.page_size = u32::MAX;
        assert_eq!(offset(&q), i32::MAX);
        assert_eq!(limit(&q), i32::MAX);
    }

    #[test]
    fn the_count_call_does_not_shift_the_page_filters_left() {
        // The bug this module exists to prevent: `search_transcripts` is
        // (p_query, p_limit, p_offset, p_require_all, ...) and
        // `count_transcripts` is (p_query, p_require_all, ...), so a shared
        // value list bound `p_limit` to `p_require_all`. The page size must
        // appear in one call and not the other, and `require_all` must be the
        // fourth argument of the page call and the second of the count.
        let mut q = query();
        q.require_all = true;

        let page = page_values(&q);
        assert_eq!(page.len(), 10);
        assert!(matches!(page[3], sea_orm::Value::Bool(Some(true))));

        let count = count_values(&q);
        assert_eq!(count.len(), 6);
        assert!(matches!(count[1], sea_orm::Value::Bool(Some(true))));
    }

    #[test]
    fn both_calls_bind_by_name() {
        // The convention rpc.md documents. Positional calls are what the by-
        // name arguments replace, and `SELECT * FROM f($1, $2)` here would be
        // a call whose meaning depends on the function's argument order.
        for (sql, args) in [(SEARCH, 10), (COUNT, 6), (MOMENTS, 4)] {
            assert!(sql.contains("=> "), "{sql}");
            assert!(sql.contains(&format!("${args}")), "{sql}");
            assert!(!sql.contains(&format!("${}", args + 1)), "{sql}");
        }
    }
}