2024-02-27 18:54:14 -07:00
|
|
|
import asyncio
|
|
|
|
|
import random
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
import time
|
2024-02-27 18:54:14 -07:00
|
|
|
from datetime import timedelta
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
from typing import Tuple, Optional, List, Dict, Callable
|
2021-11-01 16:42:52 -06:00
|
|
|
|
2024-02-27 18:54:14 -07:00
|
|
|
import yt_dlp
|
|
|
|
|
from sqlalchemy import or_
|
2021-11-01 16:42:52 -06:00
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
2025-02-19 14:52:50 -07:00
|
|
|
from modules.videos.models import Video, Channel
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
from wrolpi import fts
|
2025-01-26 12:44:16 -07:00
|
|
|
from wrolpi.common import logger, limit_concurrent, wrol_mode_check
|
2024-02-27 18:54:14 -07:00
|
|
|
from wrolpi.dates import now
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
from wrolpi.db import get_db_session, get_db_curs
|
2024-02-27 18:54:14 -07:00
|
|
|
from wrolpi.downloader import download_manager
|
2026-05-03 18:50:22 -06:00
|
|
|
from wrolpi.files.lib import handle_file_group_search_results
|
2024-02-27 18:54:14 -07:00
|
|
|
from wrolpi.files.models import FileGroup
|
2026-05-03 18:50:22 -06:00
|
|
|
from wrolpi.tags import tag_append_sub_select_where
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
from wrolpi.vars import VIDEO_COMMENTS_FETCH_COUNT, YTDLP_CACHE_DIR, PYTEST
|
2026-02-20 14:37:58 -07:00
|
|
|
from ..cookies import cookies_unlocked, cookies_for_download
|
|
|
|
|
from ..lib import get_yt_dlp_http_headers, get_yt_dlp_sleep_opts
|
2021-11-01 16:42:52 -06:00
|
|
|
|
|
|
|
|
logger.getChild(__name__)
|
|
|
|
|
|
|
|
|
|
|
2026-03-20 20:17:27 -06:00
|
|
|
def get_video_for_app(file_group_id: int, skip_viewed: bool = False) -> Tuple[dict, Optional[dict], Optional[dict]]:
|
2021-11-01 16:42:52 -06:00
|
|
|
"""
|
2026-03-20 15:38:32 -06:00
|
|
|
Get a Video by its FileGroup ID, with its prev/next videos. Mark the Video as viewed.
|
2021-11-01 16:42:52 -06:00
|
|
|
"""
|
|
|
|
|
with get_db_session(commit=True) as session:
|
2026-03-20 15:38:32 -06:00
|
|
|
video = Video.find_by_file_group_id(session, file_group_id)
|
2026-03-20 20:17:27 -06:00
|
|
|
if not skip_viewed:
|
|
|
|
|
video.file_group.set_viewed()
|
2021-11-01 16:42:52 -06:00
|
|
|
previous_video, next_video = video.get_surrounding_videos()
|
|
|
|
|
|
2023-03-24 08:58:18 -06:00
|
|
|
video = video.__json__()
|
|
|
|
|
previous_video = previous_video.__json__() if previous_video and previous_video.file_group else None
|
|
|
|
|
next_video = next_video.__json__() if next_video and next_video.file_group else None
|
2021-11-01 16:42:52 -06:00
|
|
|
|
|
|
|
|
return video, previous_video, next_video
|
|
|
|
|
|
|
|
|
|
|
2026-03-20 15:38:32 -06:00
|
|
|
def get_video(file_group_id: int) -> Video:
|
2025-01-26 12:44:16 -07:00
|
|
|
"""
|
2026-03-20 15:38:32 -06:00
|
|
|
Get a Video by its FileGroup ID.
|
2025-01-26 12:44:16 -07:00
|
|
|
"""
|
|
|
|
|
with get_db_session() as session:
|
2026-03-20 15:38:32 -06:00
|
|
|
video = Video.find_by_file_group_id(session, file_group_id)
|
2025-01-26 12:44:16 -07:00
|
|
|
return video
|
|
|
|
|
|
|
|
|
|
|
2021-11-01 16:42:52 -06:00
|
|
|
VIDEO_ORDERS = {
|
2026-07-14 07:46:29 -06:00
|
|
|
# fg.id (the rowid) is the pagination tiebreaker: it is present in every index, so these
|
|
|
|
|
# orders stay index-only. LOWER(fg.primary_path) forced SQLite to read every (large) row.
|
2025-08-16 11:13:45 -06:00
|
|
|
# Sometimes we don't have a published_datetime. This is equivalent to COALESCE(fg.published_datetime, fg.download_datetime)
|
2026-07-14 07:46:29 -06:00
|
|
|
'published_datetime': 'fg.effective_datetime ASC, fg.id ASC',
|
|
|
|
|
'-published_datetime': 'fg.effective_datetime DESC NULLS LAST, fg.id ASC',
|
|
|
|
|
'rank': '2 DESC, fg.id DESC',
|
|
|
|
|
'-rank': '2 ASC, fg.id ASC',
|
|
|
|
|
'size': 'fg.size ASC, fg.id ASC',
|
|
|
|
|
'-size': 'fg.size DESC, fg.id DESC',
|
|
|
|
|
'length': 'fg.length ASC, fg.id ASC',
|
|
|
|
|
'-length': 'fg.length DESC, fg.id DESC',
|
|
|
|
|
'size_to_duration': 'CASE WHEN fg.length > 0 THEN CAST(fg.size AS REAL) / fg.length ELSE fg.size END ASC, fg.id ASC',
|
|
|
|
|
'-size_to_duration': 'CASE WHEN fg.length > 0 THEN CAST(fg.size AS REAL) / fg.length ELSE fg.size END DESC, fg.id DESC',
|
2023-10-24 10:20:06 -06:00
|
|
|
'viewed': 'fg.viewed ASC',
|
|
|
|
|
'-viewed': 'fg.viewed DESC',
|
2022-08-06 05:22:07 +00:00
|
|
|
'view_count': 'v.view_count ASC',
|
|
|
|
|
'-view_count': 'v.view_count DESC',
|
2026-07-14 07:46:29 -06:00
|
|
|
'download_datetime': 'fg.download_datetime ASC, fg.id ASC',
|
|
|
|
|
'-download_datetime': 'fg.download_datetime DESC NULLS LAST, fg.id ASC',
|
2021-11-01 16:42:52 -06:00
|
|
|
}
|
|
|
|
|
NO_NULL_ORDERS = {
|
2023-10-24 10:20:06 -06:00
|
|
|
'viewed': 'fg.viewed IS NOT NULL',
|
|
|
|
|
'-viewed': 'fg.viewed IS NOT NULL',
|
|
|
|
|
'length': 'fg.length IS NOT NULL',
|
|
|
|
|
'-length': 'fg.length IS NOT NULL',
|
2023-03-24 08:58:18 -06:00
|
|
|
'size': 'fg.size IS NOT NULL',
|
|
|
|
|
'-size': 'fg.size IS NOT NULL',
|
2025-06-07 17:36:00 -06:00
|
|
|
'size_to_duration': 'fg.size IS NOT NULL AND fg.length IS NOT NULL',
|
|
|
|
|
'-size_to_duration': 'fg.size IS NOT NULL AND fg.length IS NOT NULL',
|
2022-08-06 05:22:07 +00:00
|
|
|
'view_count': 'v.view_count IS NOT NULL',
|
|
|
|
|
'-view_count': 'v.view_count IS NOT NULL',
|
2021-11-01 16:42:52 -06:00
|
|
|
}
|
2024-03-12 11:06:30 -06:00
|
|
|
JOIN_ORDERS = ('view_count', '-view_count')
|
2021-11-01 16:42:52 -06:00
|
|
|
DEFAULT_VIDEO_ORDER = 'rank'
|
2022-08-06 05:22:07 +00:00
|
|
|
VIDEO_QUERY_LIMIT = 24
|
2021-11-01 16:42:52 -06:00
|
|
|
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
# Orders the unfiltered Videos page can serve straight from the (mimetype, effective_datetime) index.
|
|
|
|
|
INDEXED_DATE_ORDERS = ('published_datetime', '-published_datetime')
|
|
|
|
|
VIDEO_MIMETYPE_PREFIXES = ('video/', 'audio/')
|
|
|
|
|
|
|
|
|
|
# The unfiltered Videos page total, cached for a short time. Counting every video walks the whole
|
|
|
|
|
# mimetype index, which costs seconds cold on a large library on a spinning disk; pagination can
|
|
|
|
|
# tolerate a total that is a minute stale. Bypassed under pytest so tests see exact totals.
|
|
|
|
|
TOTALS_CACHE_SECONDS = 60
|
|
|
|
|
_TOTALS_CACHE: Dict[str, Tuple[float, int]] = dict()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _cached_total(key: str, compute: Callable[[], int]) -> int:
|
|
|
|
|
if not PYTEST:
|
|
|
|
|
hit = _TOTALS_CACHE.get(key)
|
|
|
|
|
if hit and time.monotonic() - hit[0] < TOTALS_CACHE_SECONDS:
|
|
|
|
|
return hit[1]
|
|
|
|
|
total = compute()
|
|
|
|
|
_TOTALS_CACHE[key] = (time.monotonic(), total)
|
|
|
|
|
return total
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _video_mimetypes() -> List[str]:
|
|
|
|
|
"""Every distinct video/* and audio/* mimetype in the library (a handful; served by the mimetype index)."""
|
|
|
|
|
mimetypes = []
|
|
|
|
|
with get_db_curs() as curs:
|
|
|
|
|
for prefix in VIDEO_MIMETYPE_PREFIXES:
|
|
|
|
|
# '0' is the character after '/', so this is the half-open range of the prefix.
|
|
|
|
|
curs.execute('SELECT DISTINCT mimetype FROM file_group WHERE mimetype >= ? AND mimetype < ?',
|
|
|
|
|
(prefix, prefix[:-1] + '0'))
|
|
|
|
|
mimetypes.extend(i[0] for i in curs.fetchall())
|
|
|
|
|
return mimetypes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _count_videos() -> int:
|
|
|
|
|
ranges = ' OR '.join(f'(mimetype >= :p{i} AND mimetype < :e{i})' for i in range(len(VIDEO_MIMETYPE_PREFIXES)))
|
|
|
|
|
params = dict()
|
|
|
|
|
for i, prefix in enumerate(VIDEO_MIMETYPE_PREFIXES):
|
|
|
|
|
params[f'p{i}'], params[f'e{i}'] = prefix, prefix[:-1] + '0'
|
|
|
|
|
with get_db_curs() as curs:
|
|
|
|
|
curs.execute(f'SELECT COUNT(*) FROM file_group WHERE {ranges}', params)
|
|
|
|
|
return curs.fetchone()[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _search_videos_by_date(order: str, limit: int, offset: int) -> Tuple[List[dict], int]:
|
|
|
|
|
"""The unfiltered Videos page, ordered by date, without visiting every video.
|
|
|
|
|
|
|
|
|
|
The generic query (`mimetype LIKE 'video/%' OR ...` + `COUNT(*) OVER()`) must visit every
|
|
|
|
|
video's index entry before it can apply LIMIT, which scales with the library rather than the
|
|
|
|
|
page. Here each exact mimetype is a pure covering-index seek on (mimetype, effective_datetime)
|
|
|
|
|
that reads only `limit + offset` entries; those few rows are then merged. Results must be
|
|
|
|
|
identical to the generic query's (same ORDER BY, including the id tiebreaker and NULL placement).
|
|
|
|
|
The total is a separate, cached count."""
|
|
|
|
|
order_by = VIDEO_ORDERS[order]
|
|
|
|
|
mimetypes = _video_mimetypes()
|
|
|
|
|
if not mimetypes:
|
|
|
|
|
return [], 0
|
|
|
|
|
|
|
|
|
|
n = limit + offset
|
|
|
|
|
params = {f'mt{i}': mimetype for i, mimetype in enumerate(mimetypes)}
|
|
|
|
|
params['offset'] = offset
|
|
|
|
|
members = '\n UNION ALL\n'.join(
|
|
|
|
|
f'SELECT * FROM (SELECT fg.id, fg.effective_datetime FROM file_group fg'
|
|
|
|
|
f' WHERE fg.mimetype = :mt{i} ORDER BY {order_by} LIMIT {n})'
|
|
|
|
|
for i in range(len(mimetypes))
|
|
|
|
|
)
|
|
|
|
|
stmt = f'''
|
|
|
|
|
SELECT fg.id
|
|
|
|
|
FROM ({members}) fg
|
|
|
|
|
ORDER BY {order_by}
|
|
|
|
|
LIMIT {limit} OFFSET :offset
|
|
|
|
|
'''.strip()
|
|
|
|
|
logger.debug(f'{stmt} {params}')
|
|
|
|
|
|
|
|
|
|
total = _cached_total('videos', _count_videos)
|
|
|
|
|
return handle_file_group_search_results(stmt, params, total=total)
|
|
|
|
|
|
2021-11-01 16:42:52 -06:00
|
|
|
|
2022-10-24 15:34:13 -06:00
|
|
|
def search_videos(
|
2021-11-01 16:42:52 -06:00
|
|
|
search_str: str = None,
|
|
|
|
|
offset: int = None,
|
|
|
|
|
limit: int = VIDEO_QUERY_LIMIT,
|
2022-04-08 09:57:04 -06:00
|
|
|
channel_id: int = None,
|
2023-03-24 08:58:18 -06:00
|
|
|
order: str = None,
|
|
|
|
|
tag_names: List[str] = None,
|
2023-04-12 18:51:26 -06:00
|
|
|
headline: bool = False,
|
2026-06-27 09:48:21 -06:00
|
|
|
censored: bool = False,
|
Search: fast ABC mode by default, opt-in deep search
The file_group.textsearch tsvector indexes all four text columns;
d_text (captions, document text, zip contents) is ~90% of the data,
making ts_rank searches take seconds on large libraries. Add a
textsearch_abc generated column (title/author/description only, ~8x
smaller) and default all searches to it, with deep=true opting into the
full column.
Database:
- Migration adds the generated column and a GIN index (rewrites the
table; a few minutes on large libraries).
Backend:
- FilesSearchRequest, VideoSearchRequest, ArchiveSearchRequest, and
DocSearchRequest accept `deep`; each search function picks the column.
- /api/search_file_estimates returns both counts in one index-bound
query (COUNT FILTER on the abc subset): `file_groups` (fast) and
`file_groups_deep`.
UI (one coherent story across the count surfaces):
- The typing dropdown always suggests the deep count (what is findable).
- The tab badge shows the active mode's count so it matches the result
list.
- The gap is reconciled by a hint offering deep search: count-aware on
the global search ("No results in fast search. N results available in
deep search." / "N more results available..."), generic on the module
pages (no deep estimate there). The hint resets pagination.
- "Search Depth" toggle in the search filter modals, persisted as
?deep=true.
Tests that relied on d_text matches now pass deep=True, with fast-mode
assertions alongside. Also skip flaky test_download_channel on
CircleCI.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 10:09:08 -06:00
|
|
|
deep: bool = False,
|
2021-11-01 16:42:52 -06:00
|
|
|
) -> Tuple[List[dict], int]:
|
2023-03-24 08:58:18 -06:00
|
|
|
tag_names = tag_names or []
|
2026-04-14 15:00:49 -06:00
|
|
|
# Search videos and audio-only files.
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
wheres = ["(fg.mimetype LIKE 'video/%' OR fg.mimetype LIKE 'audio/%')"]
|
2026-06-27 09:48:21 -06:00
|
|
|
if censored:
|
|
|
|
|
# Only return videos which are no longer available for download.
|
|
|
|
|
wheres.append('fg.censored = TRUE')
|
2023-03-24 08:58:18 -06:00
|
|
|
joins = list()
|
|
|
|
|
join_video = False
|
2022-08-06 05:22:07 +00:00
|
|
|
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
# Explicit JSON nulls bypass the schema defaults; SQLite rejects LIMIT/OFFSET NULL.
|
|
|
|
|
limit = int(limit) if limit else 20
|
Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page (#678)
* Fix API stalls: non-blocking switch worker, threaded searches, indexed Videos page
Three response-time fixes found by benchmarking the read-only API endpoints
hot and cold on real libraries:
* `switch_worker` runs on the Sanic worker's event loop every 0.1s and called
the blocking `multiprocessing.Event.wait(timeout=1)`. With no switch pending
(the normal state) this froze the loop for a second at a time; about a third
of all requests, including trivial ones, took ~1,000 ms. It now polls
`is_set()` and returns immediately.
* The search handlers (videos, files, archives, docs, zims) and `/api/statistics`
ran synchronous SQLite queries on the event loop, so one slow search stalled
every other request on that worker. They now run via `asyncio.to_thread`.
* The unfiltered Videos page (`POST /api/videos/search` with only an order)
used `mimetype LIKE 'video/%' OR ...` plus `COUNT(*) OVER()`, which visits
every video's index entry before LIMIT applies: seconds cold on a large
library on a spinning disk, and ~10 s hot for a deep page. It now seeks each
exact mimetype on the (mimetype, effective_datetime) index for `limit + offset`
rows and merges them, with the total from a separate count cached for 60 s.
Results are identical to the generic query.
Also adds `scripts/api_perf.py` (times every read-only endpoint against a host,
optionally restarting the API over SSH for cold numbers) and
`scripts/api_perf_compare.py` (merges per-host results). Host profiles live in a
gitignored JSON file; an example is included.
Measured on an 8-core docker host with a 10 GB library: median hot request
1,007 ms -> 22 ms; Videos page 1 hot 287 -> 108 ms, page 50 1,345 -> 120 ms.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Serve the video description from its own endpoint instead of Video.__json__
`Video.__json__` computed `description` as `c_text or get_video_description()`,
where the fallback opens and parses the video's info json from disk. The list
endpoints serialize every result with `__json__`, so any page containing videos
without an indexed description (common: many videos have none) read their info
json files on every request, cold, for a field the list never displays. The
description is not part of search either: search runs against the FTS copy of
`c_text`, so the fallback never fed the index.
Drop `description` from `__json__` and serve it from
`GET /api/videos/<id>/description`, like comments and captions. The endpoint
returns the indexed `c_text`, falling back to the info json only there, for a
row indexed before descriptions were stored. The player page fetches it through
`useVideoExtras` alongside the comments.
Tests assert the list and detail responses never touch the info json, and cover
the endpoint's indexed, fallback, and not-found cases.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Address review: thread-local zim sessions, fast-path equivalence test, comments
* Zim search, single-zim search, and search estimates run libzim off the event
loop, each opening its own session inside the worker thread rather than
passing the request's SQLAlchemy Session across threads.
* The Videos fast-path test now runs the same requests through the generic
query and asserts identical rows and paging for both date orders. The one
intentional difference is documented: past the end, the fast path still
reports the true total.
* switch_worker returns before its try block so the empty path does not clear
the event; its comment states the invariant only. The copied "synchronous
SQLite" comments are reduced to one line in one place.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 16:17:41 -06:00
|
|
|
offset = int(offset) if offset else 0
|
|
|
|
|
if not search_str and not tag_names and not channel_id and not censored and order in INDEXED_DATE_ORDERS:
|
|
|
|
|
# The Videos page with no filters, in date order.
|
|
|
|
|
return _search_videos_by_date(order, limit, offset)
|
|
|
|
|
|
|
|
|
|
params = dict(search_str=search_str, offset=offset)
|
2022-08-06 05:22:07 +00:00
|
|
|
if channel_id:
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
wheres.append('v.channel_id = :channel_id')
|
2023-03-24 08:58:18 -06:00
|
|
|
joins.append('LEFT JOIN channel c ON c.id = v.channel_id')
|
|
|
|
|
join_video = True
|
2022-08-06 05:22:07 +00:00
|
|
|
params['channel_id'] = channel_id
|
|
|
|
|
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
# `deep` searches d_text (captions) as well; the default abc search is much smaller and faster.
|
|
|
|
|
# The subquery join is required: snippet() cannot coexist with COUNT(*) OVER() in one SELECT.
|
|
|
|
|
fts_search = fts.file_group_search_join(search_str, deep=deep, headlines=bool(headline)) \
|
|
|
|
|
if search_str else None
|
|
|
|
|
if fts_search:
|
2022-08-06 05:22:07 +00:00
|
|
|
# A search_str was provided by the user, modify the query to filter by it.
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
select_columns = f'fg.id, {fts_search.rank_select}, COUNT(*) OVER() AS total'
|
|
|
|
|
joins.append(fts_search.join)
|
|
|
|
|
params.update(fts_search.params)
|
2022-08-06 05:22:07 +00:00
|
|
|
else:
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
# No (usable) search_str provided. Get id and total only.
|
2023-03-24 08:58:18 -06:00
|
|
|
select_columns = 'fg.id, COUNT(*) OVER() AS total'
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2024-07-22 16:36:57 -06:00
|
|
|
wheres, params = tag_append_sub_select_where(wheres, params, tag_names)
|
2022-08-06 05:22:07 +00:00
|
|
|
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
if fts_search and headline:
|
|
|
|
|
# The title headline is computed in Python by `handle_file_group_search_results`.
|
|
|
|
|
headline_selects = ', fts.b_headline, fts.c_headline, fts.d_headline'
|
2023-04-12 18:51:26 -06:00
|
|
|
else:
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
headline_selects = ''
|
2023-04-12 18:51:26 -06:00
|
|
|
|
2022-08-06 05:22:07 +00:00
|
|
|
# Convert the user-friendly order by into a real order by, restrict what can be interpolated by using the
|
|
|
|
|
# whitelist.
|
2023-03-24 08:58:18 -06:00
|
|
|
order_by = VIDEO_ORDERS[DEFAULT_VIDEO_ORDER]
|
|
|
|
|
if order:
|
2021-11-01 16:42:52 -06:00
|
|
|
try:
|
2023-03-24 08:58:18 -06:00
|
|
|
order_by = VIDEO_ORDERS[order]
|
2022-08-06 05:22:07 +00:00
|
|
|
except KeyError:
|
|
|
|
|
raise
|
2023-03-24 08:58:18 -06:00
|
|
|
if order in NO_NULL_ORDERS:
|
|
|
|
|
wheres.append(NO_NULL_ORDERS[order])
|
|
|
|
|
if order in JOIN_ORDERS:
|
|
|
|
|
join_video = True
|
|
|
|
|
|
|
|
|
|
if join_video:
|
|
|
|
|
joins.insert(0, 'LEFT JOIN video v on v.file_group_id = fg.id')
|
2022-08-06 05:22:07 +00:00
|
|
|
|
|
|
|
|
wheres = '\n AND '.join(wheres)
|
|
|
|
|
where = f'WHERE\n{wheres}' if wheres else ''
|
2023-03-24 08:58:18 -06:00
|
|
|
join = '\n'.join(joins)
|
2022-08-06 05:22:07 +00:00
|
|
|
stmt = f'''
|
|
|
|
|
SELECT
|
2023-04-12 18:51:26 -06:00
|
|
|
{select_columns}
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
{headline_selects}
|
2023-03-24 08:58:18 -06:00
|
|
|
FROM file_group fg
|
2022-08-06 05:22:07 +00:00
|
|
|
{join}
|
|
|
|
|
{where}
|
2023-03-24 08:58:18 -06:00
|
|
|
ORDER BY {order_by}
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
LIMIT {int(limit)} OFFSET :offset
|
2022-08-06 05:22:07 +00:00
|
|
|
'''.strip()
|
Postgres -> SQLite hard cutover: the database moves into the media directory.
The database now lives at <media>/config/wrolpi.db so a library (files,
configs, AND database) travels with the drive between WROLPi systems.
Core:
- wrolpi/db.py: lazy SQLite engine factory (WAL, busy_timeout=30s,
foreign_keys=ON); get_db_curs yields a plain sqlite3.Cursor; native
sqlite3 paramstyle everywhere (no compatibility shims); global sqlite3
adapters keep raw-SQL datetime formats identical to the ORM's.
- wrolpi/fts.py: FTS5 external-content search replacing tsvector/GIN.
Injection-proof websearch->FTS5 translator, bm25(10,4,2,1) reproducing
A/B/C/D weighting, fast(abc)/deep column filtering, snippet headlines.
Stemming contract pinned by dedicated tests (watch/watches/watched/
watching are interchangeable).
- wrolpi/schema_ddl.py: SQLite triggers shared verbatim by the alembic
baseline and test DBs; fixes the channel video_count DELETE/UPDATE
bugs and a latent total_size bug (it used the video id as channel id).
- wrolpi/db_bootstrap.py: startup auto-create/migrate; refuses databases
written by a newer WROLPi (db_version_mismatch); SQLite 3.40 floor;
network-filesystem refusal; never creates/migrates/trusts a database
beneath an unmounted production media directory (shadow-DB guard).
- Alembic: 85 Postgres-era migrations squashed into one baseline;
revision ids are dates (2026_07_10_1350) so filenames self-sort and
alembic_version says when a schema was created; render_as_batch=True.
- All raw Postgres SQL rewritten (ANY->json_each IN, array_agg @> ->
HAVING COUNT(DISTINCT), unnest->executemany/UPDATE..FROM,
generate_series histograms->strftime GROUP BY, DISTINCT ON->
row_number(), writable CTEs->two statements, jsonb_*->json_*, explicit
NULLS FIRST/LAST, LIMIT-before-OFFSET). Simple statements converted
to SQLAlchemy instead (flag upsert, download retry/summary/tag checks,
channel-by-tag estimate, Directory delete).
- Config imports count skipped entries; background dumps are blocked
after a lossy import so partial imports can never overwrite YAML
configs (they are the sole source of truth for rebuilds now).
- Search tolerates explicit JSON nulls for limit/offset (Postgres
treated OFFSET NULL as 0; SQLite errors).
- file_group.id/doc_section.id render as INTEGER PRIMARY KEY on SQLite
(BIGINT is not a rowid alias; FTS5 content_rowid requires it).
Ops teardown: docker-compose db service, CI postgres sidecars,
initialize_api_db.sh, controller postgresql service, psycopg2-binary all
removed. upgrade.sh stops/disables postgresql (data is NOT deleted;
`systemctl enable --now postgresql` restores it); systemd units no
longer Want postgresql.service.
Existing-user upgrade: first boot creates+migrates the DB, configs
import (tags recreate their FileGroups from disk), a refresh rebuilds
the library index. QA'd on the 10.0.0.8 RPi: rebuild matched the
Postgres baseline exactly; survived an uncontrolled hard reboot with
clean integrity checks.
Accepted behavior changes: FTS5 has no stopwords; bm25 length
normalization shifts some rank orders; fast-path d_headline is
un-highlighted; all-negative queries match nothing.
Deferred: Debian/trixie package lists (incl. sqlite3 CLI), Cypress
re-baseline, VACUUM INTO snapshots, exFAT/NTFS warning, auto-kicked
rebuild refresh with progress UX.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 13:59:20 -06:00
|
|
|
logger.debug(f'{stmt} {params}')
|
2022-08-06 05:22:07 +00:00
|
|
|
|
2023-03-24 08:58:18 -06:00
|
|
|
results, total = handle_file_group_search_results(stmt, params)
|
2021-11-01 16:42:52 -06:00
|
|
|
return results, total
|
|
|
|
|
|
|
|
|
|
|
2026-02-20 14:37:58 -07:00
|
|
|
def download_video_info_json(url: str) -> dict:
|
|
|
|
|
"""Download video info JSON, using encrypted cookies for authentication if available."""
|
2024-02-27 18:54:14 -07:00
|
|
|
ydl_opts = dict(
|
|
|
|
|
getcomments=True,
|
|
|
|
|
skip_download=True,
|
|
|
|
|
extractor_args={'youtube': {'max_comments': ['all', '20', 'all', '10'], 'comment_sort': ['top']}},
|
2024-03-12 16:52:26 -06:00
|
|
|
cachedir=YTDLP_CACHE_DIR,
|
2026-02-20 14:37:58 -07:00
|
|
|
**get_yt_dlp_sleep_opts(),
|
2024-02-27 18:54:14 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
ydl_logger = logger.getChild('youtube-dl')
|
|
|
|
|
|
2026-02-20 14:37:58 -07:00
|
|
|
if cookies_unlocked():
|
|
|
|
|
logger.info(f'Using encrypted cookies for video info: {url}')
|
|
|
|
|
with cookies_for_download() as cookies_path:
|
|
|
|
|
ydl_opts['cookiefile'] = str(cookies_path)
|
|
|
|
|
http_headers = get_yt_dlp_http_headers()
|
|
|
|
|
if http_headers:
|
|
|
|
|
ydl_opts['http_headers'] = http_headers
|
|
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
|
|
|
ydl.params['logger'] = ydl_logger
|
|
|
|
|
info = ydl.extract_info(url, download=False)
|
|
|
|
|
ydl.sanitize_info(info)
|
|
|
|
|
return info
|
|
|
|
|
|
|
|
|
|
logger.info(f'No cookies available for video info: {url}')
|
|
|
|
|
|
2024-02-27 18:54:14 -07:00
|
|
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
|
|
|
|
ydl.params['logger'] = ydl_logger
|
|
|
|
|
info = ydl.extract_info(url, download=False)
|
|
|
|
|
ydl.sanitize_info(info)
|
|
|
|
|
return info
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@limit_concurrent(1)
|
|
|
|
|
@wrol_mode_check
|
|
|
|
|
async def get_missing_videos_comments(limit: int = VIDEO_COMMENTS_FETCH_COUNT):
|
|
|
|
|
"""
|
|
|
|
|
Fetches Video info json for videos without comments, if comments are found then the info json file is replaced.
|
2026-02-20 14:37:58 -07:00
|
|
|
Uses encrypted cookies for authentication if available.
|
2024-02-27 18:54:14 -07:00
|
|
|
"""
|
|
|
|
|
one_month_ago = now() - timedelta(days=30)
|
|
|
|
|
|
|
|
|
|
# Get any videos over a month old that do not have comments.
|
|
|
|
|
with get_db_session() as session:
|
|
|
|
|
videos = session.query(Video).filter(
|
|
|
|
|
# Have yet to get comments.
|
2024-06-25 22:12:13 -06:00
|
|
|
Video.have_comments != True,
|
|
|
|
|
Video.comments_failed != True,
|
|
|
|
|
# Needs to be downloadable.
|
2024-02-27 18:54:14 -07:00
|
|
|
FileGroup.url != None, # noqa
|
2024-06-25 22:12:13 -06:00
|
|
|
FileGroup.censored != True,
|
2024-02-27 18:54:14 -07:00
|
|
|
# We want old videos (time for comments to accumulate), or those which we don't know the published date.
|
|
|
|
|
or_(
|
|
|
|
|
one_month_ago > FileGroup.published_datetime,
|
|
|
|
|
FileGroup.published_datetime == None,
|
|
|
|
|
),
|
2025-02-19 14:52:50 -07:00
|
|
|
# Do not download a Videos with a Channel and Channel.download_missing_data is False.
|
|
|
|
|
or_(
|
|
|
|
|
Channel.download_missing_data == True,
|
|
|
|
|
Channel.id == None,
|
|
|
|
|
)
|
2024-02-27 18:54:14 -07:00
|
|
|
).join(FileGroup) \
|
2025-02-19 14:52:50 -07:00
|
|
|
.outerjoin(Channel) \
|
2024-02-27 18:54:14 -07:00
|
|
|
.order_by(FileGroup.published_datetime.nullsfirst()) \
|
|
|
|
|
.limit(limit)
|
|
|
|
|
video_urls = [i.file_group.url for i in videos]
|
|
|
|
|
|
|
|
|
|
logger.info(f'Found {len(video_urls)} videos missing comments')
|
|
|
|
|
|
2024-06-22 10:46:45 -06:00
|
|
|
def add_video_to_skip_list(video_url: str, censored: bool = False):
|
2024-02-27 18:54:14 -07:00
|
|
|
"""Do not attempt to get comments of the provided Video again."""
|
|
|
|
|
with get_db_session(commit=True) as session_:
|
2024-06-22 10:46:45 -06:00
|
|
|
for video_, fg in session_.query(Video, FileGroup).join(FileGroup).filter_by(url=video_url).all():
|
2024-02-27 18:54:14 -07:00
|
|
|
video_.comments_failed = True
|
2024-06-22 10:46:45 -06:00
|
|
|
fg.censored = censored
|
2024-03-06 17:41:04 -07:00
|
|
|
download_manager.add_to_skip_list(video_url)
|
2024-06-22 10:46:45 -06:00
|
|
|
logger.debug(f'add_video_to_skip_list: {video_url=} {censored=}')
|
2024-02-27 18:54:14 -07:00
|
|
|
|
|
|
|
|
for url in video_urls:
|
|
|
|
|
# Sleep to catch cancel.
|
|
|
|
|
await asyncio.sleep(0)
|
|
|
|
|
|
|
|
|
|
if download_manager.is_skipped(url):
|
|
|
|
|
# This video is skipped, do not try to get comments again.
|
|
|
|
|
add_video_to_skip_list(url)
|
|
|
|
|
|
2024-06-12 16:39:23 -06:00
|
|
|
if download_manager.is_disabled or download_manager.is_stopped:
|
|
|
|
|
logger.info('Downloads disabled, stop getting comments...')
|
|
|
|
|
return
|
|
|
|
|
|
2024-02-27 18:54:14 -07:00
|
|
|
with get_db_session(commit=True) as session:
|
|
|
|
|
have_comments = False
|
|
|
|
|
for video in session.query(Video).join(FileGroup).filter_by(url=url).all():
|
|
|
|
|
if (comments := video.get_comments()) and len(comments) >= 5:
|
|
|
|
|
# We already have enough comments. DB may have been wiped, we don't want to fetch comments again.
|
|
|
|
|
logger.info(f'Already have comments for Video: {url=}')
|
|
|
|
|
have_comments = video.have_comments = True
|
|
|
|
|
|
|
|
|
|
if have_comments:
|
|
|
|
|
download_manager.add_to_skip_list(url)
|
|
|
|
|
continue
|
|
|
|
|
|
2024-06-25 22:12:13 -06:00
|
|
|
logger.info(f'Getting comments for: {url}')
|
|
|
|
|
|
2024-05-31 23:54:00 -06:00
|
|
|
try:
|
2024-06-12 16:39:23 -06:00
|
|
|
# Get info json about the video.
|
2026-02-20 14:37:58 -07:00
|
|
|
info = download_video_info_json(url)
|
2024-03-06 17:41:04 -07:00
|
|
|
|
2024-05-31 23:54:00 -06:00
|
|
|
if not info or not isinstance(info.get('comments'), list):
|
|
|
|
|
logger.error(f'Unable to get comments for video: {url=}')
|
|
|
|
|
add_video_to_skip_list(url)
|
|
|
|
|
continue
|
|
|
|
|
except Exception as e:
|
|
|
|
|
if 'no longer available' in str(e):
|
|
|
|
|
logger.error(f'Giving up on downloading comments because video does not exist: {url=}', exc_info=e)
|
2024-06-22 10:46:45 -06:00
|
|
|
add_video_to_skip_list(url, censored=True)
|
2024-05-31 23:54:00 -06:00
|
|
|
elif 'Comments are turned off' in str(e):
|
|
|
|
|
logger.error(f'Giving up on downloading comments because comments are disabled: {url=}', exc_info=e)
|
2024-06-12 16:39:23 -06:00
|
|
|
add_video_to_skip_list(url)
|
2024-05-31 23:54:00 -06:00
|
|
|
elif 'Private video' in str(e):
|
|
|
|
|
logger.error(f'Giving up on downloading comments because video is private: {url=}', exc_info=e)
|
2024-06-22 10:46:45 -06:00
|
|
|
add_video_to_skip_list(url, censored=True)
|
2024-05-31 23:54:00 -06:00
|
|
|
elif 'Video unavailable' in str(e):
|
|
|
|
|
logger.error(f'Giving up on downloading comments because video is unavailable: {url=}', exc_info=e)
|
2024-06-22 10:46:45 -06:00
|
|
|
add_video_to_skip_list(url, censored=True)
|
|
|
|
|
elif 'video has been removed' in str(e):
|
|
|
|
|
logger.error(f'Giving up on downloading comments because video is removed: {url=}', exc_info=e)
|
|
|
|
|
add_video_to_skip_list(url, censored=True)
|
|
|
|
|
elif ' members' in str(e):
|
2024-05-31 23:54:00 -06:00
|
|
|
logger.error(f'Giving up on downloading comments because video is members-only: {url=}', exc_info=e)
|
2024-06-22 10:46:45 -06:00
|
|
|
add_video_to_skip_list(url, censored=True)
|
|
|
|
|
elif 'rumble.com' in url and "'bool' object has no attribute 'get'" in str(e):
|
|
|
|
|
logger.error(f'Rumble error in yt-dlp', exc_info=e)
|
|
|
|
|
add_video_to_skip_list(url, censored=False)
|
|
|
|
|
elif 'not a valid URL' in str(e):
|
|
|
|
|
logger.error(f'URL is not valid: {url=}', exc_info=e)
|
|
|
|
|
add_video_to_skip_list(url, censored=True)
|
2024-07-14 09:54:02 -06:00
|
|
|
elif ' Sign in ' in str(e):
|
|
|
|
|
logger.error(f'Video requires sign-in: {url=}', exc_info=e)
|
|
|
|
|
add_video_to_skip_list(url, censored=True)
|
2024-05-31 23:54:00 -06:00
|
|
|
else:
|
|
|
|
|
logger.error(f'Got error when attempting to download video comments: {url=}', exc_info=e)
|
2024-02-27 18:54:14 -07:00
|
|
|
continue
|
|
|
|
|
|
2024-05-31 23:54:00 -06:00
|
|
|
logger.info(f'Got {len(info["comments"])} comments for Video: {url=}')
|
2024-02-27 18:54:14 -07:00
|
|
|
|
|
|
|
|
with get_db_session(commit=True) as session:
|
2024-05-31 23:54:00 -06:00
|
|
|
videos = list(session.query(Video).join(FileGroup).filter_by(url=url).all())
|
|
|
|
|
for video in videos:
|
|
|
|
|
if video.video_path.is_file():
|
|
|
|
|
video.replace_info_json(info)
|
|
|
|
|
video.have_comments = True
|
2024-06-25 22:12:13 -06:00
|
|
|
video.comments_failed = False
|
2024-05-31 23:54:00 -06:00
|
|
|
else:
|
|
|
|
|
logger.error(f'Attempting to replace comments for non-existent video! {video}')
|
|
|
|
|
if len(videos) == 1:
|
2024-06-22 10:46:45 -06:00
|
|
|
download_manager.add_to_skip_list(url)
|
2024-05-31 23:54:00 -06:00
|
|
|
video.comments_failed = True
|
2024-02-27 18:54:14 -07:00
|
|
|
|
|
|
|
|
# Sleep a random amount of time, so we don't spam.
|
|
|
|
|
await asyncio.sleep(random.randint(2, 20))
|