Skip to main content

tango_core/
transcript_search.rs

1//! What was said, and where: the transcript search RPCs.
2//!
3//! `search_transcripts`, `count_transcripts` and `search_video_transcript` are
4//! the public functions `docs/rpc.md` documents; this module is the one place
5//! in the workspace they are called from. The binding list is why. The page
6//! call takes ten arguments and the count six of the same filters in a
7//! different order, so a second copy of the call is how a page size ends up
8//! bound to `p_require_all` - the mistake the API's own comment describes, and
9//! one no test would have to fail for it to reach production.
10//!
11//! Every argument is passed by name (`p_query => $1`), which is what `rpc.md`
12//! tells outside callers to do. Both consumers then exercise the convention
13//! the contract documents rather than a positional call only this code knows
14//! is correct.
15
16use sea_orm::{ConnectionTrait, DatabaseConnection, DbBackend, QueryResult, Statement};
17use serde::{Deserialize, Serialize};
18
19/// What `rpc.md` documents as the default page size, and what the CLI uses.
20pub const DEFAULT_PAGE_SIZE: u32 = 24;
21
22/// What a transcript search is ordered by.
23///
24/// A closed enum, because `search_transcripts` resolves the key through guarded
25/// CASE arms: it takes a value, never SQL, and raises on anything this does not
26/// name.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
28#[serde(rename_all = "snake_case")]
29pub enum TranscriptSort {
30    /// Best first: `matched_terms`, then `context_matches`, then `rank`, then
31    /// playback order. The only sort that means anything on its own, and the
32    /// order `docs/rpc.md` calls the relevance order.
33    #[default]
34    Rank,
35    PublishedAt,
36    ViewCount,
37    /// Earliest first: where a topic first comes up, rather than where it is
38    /// discussed most densely.
39    StartMs,
40}
41
42impl TranscriptSort {
43    /// The key as `search_transcripts` expects it.
44    pub fn as_str(self) -> &'static str {
45        match self {
46            Self::Rank => "rank",
47            Self::PublishedAt => "published_at",
48            Self::ViewCount => "view_count",
49            Self::StartMs => "start_ms",
50        }
51    }
52
53    /// Parses a sort key, with the list in the message so a mistyped key is
54    /// answerable without the source. A plain message rather than an error
55    /// enum, because the CLI and the API want different things from a refusal:
56    /// one prints it, the other turns it into a 400.
57    pub fn parse(raw: &str) -> anyhow::Result<Self> {
58        match raw {
59            "rank" => Ok(Self::Rank),
60            "published_at" => Ok(Self::PublishedAt),
61            "view_count" => Ok(Self::ViewCount),
62            "start_ms" => Ok(Self::StartMs),
63            other => anyhow::bail!(
64                "unknown transcript sort key {other:?}. Expected one of: rank, published_at, \
65                 view_count, start_ms"
66            ),
67        }
68    }
69}
70
71impl std::str::FromStr for TranscriptSort {
72    type Err = anyhow::Error;
73
74    fn from_str(raw: &str) -> Result<Self, Self::Err> {
75        Self::parse(raw)
76    }
77}
78
79/// Which caption pool a track came from.
80///
81/// `manual` is authored, `auto` is speech recognition, and the two differ in
82/// quality by more than any other attribute of a track.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
84#[serde(rename_all = "snake_case")]
85pub enum TranscriptSource {
86    Manual,
87    Auto,
88}
89
90impl TranscriptSource {
91    pub fn as_str(self) -> &'static str {
92        match self {
93            Self::Manual => "manual",
94            Self::Auto => "auto",
95        }
96    }
97
98    pub fn parse(raw: &str) -> anyhow::Result<Self> {
99        match raw {
100            "manual" => Ok(Self::Manual),
101            "auto" => Ok(Self::Auto),
102            other => anyhow::bail!("unknown transcript source {other:?}. Expected: manual, auto"),
103        }
104    }
105}
106
107impl std::str::FromStr for TranscriptSource {
108    type Err = anyhow::Error;
109
110    fn from_str(raw: &str) -> Result<Self, Self::Err> {
111        Self::parse(raw)
112    }
113}
114
115/// One transcript search: the filters the page and the count share, plus the
116/// page and the sort.
117///
118/// `page` is one-based and `page_size` in rows, like
119/// [`crate::search::SearchQuery`]. The functions take `p_limit`/`p_offset`,
120/// zero-based; the conversion happens here, beside the saturation rule, so the
121/// two front ends cannot round it differently.
122#[derive(Debug, Clone)]
123pub struct TranscriptQuery {
124    pub text: String,
125    pub page: u32,
126    pub page_size: u32,
127    /// Every term must appear in the video's deduplicated transcript, not in
128    /// the returned utterance: no sixteen-word cue holds a phrase like `dark
129    /// root basin` even when the video discusses it for ten minutes. See
130    /// `rpc.md` for why there is no fallback to any-term.
131    pub require_all: bool,
132    pub video_id: Option<String>,
133    /// BCP-47, e.g. `en`.
134    pub lang: Option<String>,
135    pub source: Option<TranscriptSource>,
136    pub sort_by: TranscriptSort,
137    /// Descending. Meaningful for every key here, the default sort included.
138    pub desc: bool,
139    /// Literal and adjacent, over the `simple` configuration, so `racing` is
140    /// not satisfied by `race`.
141    pub exact: bool,
142}
143
144/// A row of `search_transcripts`: one matching utterance, and where it is.
145#[derive(Debug, Clone)]
146pub struct TranscriptCueRow {
147    pub video_id: String,
148    pub video_title: String,
149    pub lang: String,
150    /// `manual` or `auto`.
151    pub source: String,
152    pub cue_index: i32,
153    pub start_ms: i32,
154    pub end_ms: i32,
155    pub content: String,
156    /// The matched part, with `»` and `«` around the hit.
157    pub snippet: String,
158    /// Cover density over the utterance, `ts_rank_cd`. The lowest of the three
159    /// relevance signals; see the traps section of `rpc.md` before sorting or
160    /// comparing on it.
161    pub rank: f32,
162    /// How many distinct query terms this utterance carries.
163    pub matched_terms: i64,
164    /// Matching utterances within +-300 s, in the same video and track.
165    pub context_matches: i64,
166    pub published_at: Option<chrono::DateTime<chrono::Utc>>,
167    pub view_count: Option<i64>,
168}
169
170impl TranscriptCueRow {
171    fn from_row(row: &QueryResult) -> anyhow::Result<Self> {
172        Ok(Self {
173            video_id: row.try_get("", "video_id")?,
174            video_title: row.try_get("", "video_title")?,
175            lang: row.try_get("", "lang")?,
176            source: row.try_get("", "source")?,
177            cue_index: row.try_get("", "cue_index")?,
178            start_ms: row.try_get("", "start_ms")?,
179            end_ms: row.try_get("", "end_ms")?,
180            content: row.try_get("", "content")?,
181            snippet: row.try_get("", "snippet")?,
182            rank: row.try_get("", "rank")?,
183            matched_terms: row.try_get("", "matched_terms")?,
184            context_matches: row.try_get("", "context_matches")?,
185            published_at: row.try_get("", "published_at")?,
186            view_count: row.try_get("", "view_count")?,
187        })
188    }
189}
190
191/// A row of `search_video_transcript`: one matching cue in one video, with the
192/// `moment` number the function assigns - cues more than ten seconds apart
193/// begin a new moment, so the rolling repeats around one mention group.
194#[derive(Debug, Clone)]
195pub struct TranscriptMomentRow {
196    pub cue_index: i32,
197    pub start_ms: i32,
198    pub end_ms: i32,
199    pub content: String,
200    pub snippet: String,
201    pub matched_terms: i64,
202    pub moment: i32,
203    /// Comes back from the function already carrying `&t=`.
204    pub url: String,
205}
206
207impl TranscriptMomentRow {
208    fn from_row(row: &QueryResult) -> anyhow::Result<Self> {
209        Ok(Self {
210            cue_index: row.try_get("", "cue_index")?,
211            start_ms: row.try_get("", "start_ms")?,
212            end_ms: row.try_get("", "end_ms")?,
213            content: row.try_get("", "content")?,
214            snippet: row.try_get("", "snippet")?,
215            matched_terms: row.try_get("", "matched_terms")?,
216            moment: row.try_get("", "moment")?,
217            url: row.try_get("", "url")?,
218        })
219    }
220}
221
222/// Every argument of the page call, by name.
223const SEARCH: &str = "SELECT * FROM public.search_transcripts(\
224     p_query => $1, p_limit => $2, p_offset => $3, p_require_all => $4, \
225     p_video_id => $5, p_lang => $6, p_source => $7, \
226     p_sort_by => $8, p_sort_desc => $9, p_exact => $10)";
227
228/// The same filters the count takes, by name. Fewer arguments, and not the
229/// same first six: `search_transcripts` is `(p_query, p_limit, p_offset,
230/// p_require_all, ...)` and this is `(p_query, p_require_all, ...)`.
231const COUNT: &str = "SELECT public.count_transcripts(\
232     p_query => $1, p_require_all => $2, p_video_id => $3, p_lang => $4, \
233     p_source => $5, p_exact => $6) AS count";
234
235const MOMENTS: &str = "SELECT * FROM public.search_video_transcript(\
236     p_video_id => $1, p_query => $2, p_lang => $3, p_source => $4)";
237
238/// One page of matching utterances, ordered by `q`.
239pub async fn search(
240    db: &DatabaseConnection,
241    q: &TranscriptQuery,
242) -> anyhow::Result<Vec<TranscriptCueRow>> {
243    let statement = Statement::from_sql_and_values(DbBackend::Postgres, SEARCH, page_values(q));
244
245    let rows = db
246        .query_all_raw(statement)
247        .await
248        .map_err(|e| anyhow::anyhow!("transcript search failed: {e}"))?;
249
250    rows.iter().map(TranscriptCueRow::from_row).collect()
251}
252
253/// How many utterances the same query matches in total.
254///
255/// Counts the same scan the page comes from, so a total and a page cannot
256/// describe different searches. A caller that wants a pager needs this, and
257/// the page it just fetched cannot stand in for it: the page may be empty
258/// while the total is not.
259pub async fn count(db: &DatabaseConnection, q: &TranscriptQuery) -> anyhow::Result<u64> {
260    let statement = Statement::from_sql_and_values(DbBackend::Postgres, COUNT, count_values(q));
261
262    let row = db
263        .query_one_raw(statement)
264        .await
265        .map_err(|e| anyhow::anyhow!("transcript count failed: {e}"))?;
266
267    // `count_transcripts` returns bigint, and sqlx-postgres has no u64 codec -
268    // reading it as one fails at runtime. A count is never negative, so the
269    // clamp is total.
270    Ok(row
271        .map(|row| row.try_get::<i64>("", "count"))
272        .transpose()?
273        .unwrap_or(0)
274        .max(0) as u64)
275}
276
277/// Every matching cue in one video, in playback order and capped at 200 rows
278/// by the function itself.
279pub async fn moments(
280    db: &DatabaseConnection,
281    video_id: &str,
282    text: &str,
283    lang: Option<&str>,
284    source: Option<TranscriptSource>,
285) -> anyhow::Result<Vec<TranscriptMomentRow>> {
286    let values = vec![
287        video_id.to_string().into(),
288        text.to_string().into(),
289        lang.map(str::to_string).into(),
290        source_value(source),
291    ];
292
293    let statement = Statement::from_sql_and_values(DbBackend::Postgres, MOMENTS, values);
294
295    let rows = db
296        .query_all_raw(statement)
297        .await
298        .map_err(|e| anyhow::anyhow!("transcript moments failed: {e}"))?;
299
300    rows.iter().map(TranscriptMomentRow::from_row).collect()
301}
302
303/// The values the page call binds, in the order `SEARCH` names them.
304fn page_values(q: &TranscriptQuery) -> Vec<sea_orm::Value> {
305    vec![
306        q.text.clone().into(),
307        limit(q).into(),
308        offset(q).into(),
309        q.require_all.into(),
310        optional(&q.video_id),
311        optional(&q.lang),
312        source_value(q.source),
313        q.sort_by.as_str().into(),
314        q.desc.into(),
315        q.exact.into(),
316    ]
317}
318
319/// The values the counting call binds, named one by one rather than sliced
320/// off the page call: the two lists overlap in the middle and nowhere else.
321fn count_values(q: &TranscriptQuery) -> Vec<sea_orm::Value> {
322    vec![
323        q.text.clone().into(),
324        q.require_all.into(),
325        optional(&q.video_id),
326        optional(&q.lang),
327        source_value(q.source),
328        q.exact.into(),
329    ]
330}
331
332/// `int`, not `bigint`: the functions declare `integer`, and Postgres will not
333/// resolve a call across an implicit widening cast.
334fn limit(q: &TranscriptQuery) -> i32 {
335    i32::try_from(q.page_size).unwrap_or(i32::MAX)
336}
337
338/// The offset saturates rather than wrapping: a page large enough to overflow
339/// would otherwise become a negative offset and read as the *beginning* of the
340/// result set rather than past its end.
341fn offset(q: &TranscriptQuery) -> i32 {
342    let rows = u64::from(q.page.max(1) - 1) * u64::from(q.page_size);
343    i32::try_from(rows).unwrap_or(i32::MAX)
344}
345
346/// A nullable text parameter. `Value::String(None)` is SQL NULL; the functions
347/// treat NULL as "every value", which is the single definition of an unset
348/// filter.
349fn optional(value: &Option<String>) -> sea_orm::Value {
350    match value {
351        Some(value) => value.clone().into(),
352        None => sea_orm::Value::String(None),
353    }
354}
355
356fn source_value(source: Option<TranscriptSource>) -> sea_orm::Value {
357    match source {
358        Some(source) => source.as_str().to_string().into(),
359        None => sea_orm::Value::String(None),
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    fn query() -> TranscriptQuery {
368        TranscriptQuery {
369            text: "root canal".into(),
370            page: 1,
371            page_size: DEFAULT_PAGE_SIZE,
372            require_all: false,
373            video_id: None,
374            lang: None,
375            source: None,
376            sort_by: TranscriptSort::Rank,
377            desc: true,
378            exact: false,
379        }
380    }
381
382    #[test]
383    fn sort_keys_round_trip_through_the_function_spelling() {
384        for sort in [
385            TranscriptSort::Rank,
386            TranscriptSort::PublishedAt,
387            TranscriptSort::ViewCount,
388            TranscriptSort::StartMs,
389        ] {
390            assert_eq!(TranscriptSort::parse(sort.as_str()).unwrap(), sort);
391        }
392    }
393
394    #[test]
395    fn an_unknown_sort_key_names_the_ones_that_exist() {
396        let err = TranscriptSort::parse("relevance").unwrap_err().to_string();
397        assert!(err.contains("rank"), "{err}");
398        assert!(err.contains("published_at"), "{err}");
399    }
400
401    #[test]
402    fn source_keys_round_trip_and_an_unknown_one_is_refused() {
403        for source in [TranscriptSource::Manual, TranscriptSource::Auto] {
404            assert_eq!(TranscriptSource::parse(source.as_str()).unwrap(), source);
405        }
406        assert!(TranscriptSource::parse("generated").is_err());
407    }
408
409    #[test]
410    fn pages_are_one_based_and_the_offset_never_wraps() {
411        let mut q = query();
412        assert_eq!(offset(&q), 0);
413
414        q.page = 3;
415        assert_eq!(offset(&q), 48);
416
417        // Page 0 reads as page 1, rather than as a negative offset.
418        q.page = 0;
419        assert_eq!(offset(&q), 0);
420
421        q.page = u32::MAX;
422        q.page_size = u32::MAX;
423        assert_eq!(offset(&q), i32::MAX);
424        assert_eq!(limit(&q), i32::MAX);
425    }
426
427    #[test]
428    fn the_count_call_does_not_shift_the_page_filters_left() {
429        // The bug this module exists to prevent: `search_transcripts` is
430        // (p_query, p_limit, p_offset, p_require_all, ...) and
431        // `count_transcripts` is (p_query, p_require_all, ...), so a shared
432        // value list bound `p_limit` to `p_require_all`. The page size must
433        // appear in one call and not the other, and `require_all` must be the
434        // fourth argument of the page call and the second of the count.
435        let mut q = query();
436        q.require_all = true;
437
438        let page = page_values(&q);
439        assert_eq!(page.len(), 10);
440        assert!(matches!(page[3], sea_orm::Value::Bool(Some(true))));
441
442        let count = count_values(&q);
443        assert_eq!(count.len(), 6);
444        assert!(matches!(count[1], sea_orm::Value::Bool(Some(true))));
445    }
446
447    #[test]
448    fn both_calls_bind_by_name() {
449        // The convention rpc.md documents. Positional calls are what the by-
450        // name arguments replace, and `SELECT * FROM f($1, $2)` here would be
451        // a call whose meaning depends on the function's argument order.
452        for (sql, args) in [(SEARCH, 10), (COUNT, 6), (MOMENTS, 4)] {
453            assert!(sql.contains("=> "), "{sql}");
454            assert!(sql.contains(&format!("${args}")), "{sql}");
455            assert!(!sql.contains(&format!("${}", args + 1)), "{sql}");
456        }
457    }
458}