Skip to content

perf(providers): make background work yield, and give it a counter - #22

Merged
Digit4w merged 4 commits into
devfrom
perf/background-warming-progress
Sep 13, 2026
Merged

Digit4w merged 4 commits into
devfrom
perf/background-warming-progress

Conversation

@Digit4w

@Digit4w Digit4w commented Sep 13, 2026

Copy link
Copy Markdown
Owner

Fecha o item 11 da fila do dono no lado do servidor: gargalo, progresso do aquecimento e as tarefas de atualização.

O que medir estabeleceu, antes de qualquer linha:

  • runBatch não é gargalo — 14,2ms de pior parada, 57ms para escrever 1.200 obras. A segunda hipótese da fila está descartada.
  • A suposição de que a pausa de 100ms "não alivia nada a 3/s" está invertida: é ela, somada à latência real, que segura o aquecimento em 1,07 req/s de um orçamento de 3. A causa nunca foi a pausa — era não haver precedência.
  • O import grande não é lento importando; é lento enriquecendo, e o enriquecimento era invisível: 18,7 min no MyAnimeList e 52 min no AniList para 1.200 obras, com o status indo a done e o sino disparando antes de ele começar.

O que entra, em quatro commits:

  1. Prioridade de fichas — trabalho de fundo deixa metade do burst intocada e nunca gasta ficha do futuro. Medido: no AniList uma grade fria de 20 cartas sai de 2 para 5 servidas, contra um teto de 7 sem aquecimento nenhum.
  2. O aquecimento vira job com contador (kind em import_jobs, migration 0053). Duas fases com dois contadores — importar termina quando importou, que é a decisão de 07/09 escrita no runner. O índice único tinha de mudar junto: ele cobria só status, então um aquecimento de 52 min passaria a recusar todo import novo por uma hora.
  3. Compressão HTTP — GET /api/entries responde 347 KB para 1.200 obras e não pagina por decisão de escopo. Medido depois: 15,5 KB.
  4. Refresh, de uma obra e da biblioteca (itens 11c e 11d). Reusa o laço do aquecimento em vez de copiá-lo: mesmo percurso, duas perguntas. O total atravessa do provedor para a obra só para cima (decisão do dono) — crescer é o que a realidade faz, e encolher apagaria a correção manual de alguém e poria obras em 340 / 12.

A varredura é sob demanda; o cron vem depois (decisão do dono). O que este ciclo deixa pronto para ele é o corte por idade em refreshTargets, lido de title_snapshots.fetched_at — hoje sem chamador, e está escrito por quê.

source vira nulável (0054): uma varredura relê vários provedores, então não há uma fonte. Gravar 'csv' para satisfazer o NOT NULL seria mentira plausível no banco. Migration rodada contra um banco com dados reais — as linhas existentes atravessam intactas.

Contraparte: Digit4w/watchpile-client#2 (a tela). Mergear este primeiro — dev com API sem consumidor é inofensivo; o contrário, não.

Testes: 811 (eram 790). Cada regra nova teve a quebra deliberada conferida — inclusive as duas do limitador, que falham de forma independente.

🤖 Generated with Claude Code

Art warming and the screen drew from the same token bucket with no
precedence, and warming always arrives first because it has been running
for minutes. Measured with a cold 20-card grid and a 5s budget: on
AniList (0.5/s) warming dropped served cards from 7 to 2; on MyAnimeList
and Kitsu (3/s) it did not interfere, because real network latency
already holds it at 1.07 req/s out of 3.

Background work now leaves half the burst untouched and never spends a
future token. Reserving the future is what turns a crowd into a queue,
and a queue of a thousand titles ahead of someone opening the grid is
the thing to avoid. It is declared by the caller rather than inferred
from the wait budget: a long budget is a proxy for "nobody is waiting",
and a proxy holds until the case where the two come apart.

Measured after: AniList goes to 5 of 20, against a 7 ceiling with no
warming at all.
Art warming was invisible from start to finish: the import status went
to done and the bell fired before it even began. Measured against 1,200
titles, it takes 18.7 min on MyAnimeList and 52 min on AniList — time in
which someone has already read "finished" and closed the screen.

Two phases with two counters, never one number. Folding warming into the
import counter would undo the 07/09 decision written in the runner —
holding done there would park the counter at 426/426 for minutes and let
a CDN outage fail an import that succeeded — and it would land on "a
number that sums two reasons verifies nothing".

The enrich job reuses import_jobs through a kind column instead of
getting its own table: status, total, processed, the cancel stamp and
the zombie reconciliation all live there already, and a second table
would copy six columns and two rules.

The unique index had to move with it. It covered status alone, so it
meant "one running row per installation" — with warming as a job, a
52-minute run would have refused every new import for an hour. The
original argument decides the shape rather than falling: one-at-a-time
exists because the import freezes the server (14.2ms per 200-row batch,
measured), and warming is paced network I/O. So the two coexist and the
index now forbids two of the same kind.
GET /api/entries answers 347 KB for a 1,200-title library, and the route
does not paginate by scope decision. On a LAN that never shows; over a
remote connection — half the point of self-hosting — it is 347 KB every
time /library opens. Measured after: 15.5 KB.

It registers before everything else, because it wraps whatever comes
after: added midway, routes mounted earlier would answer uncompressed
and the difference would only show in a header.

Nothing changes for the client. The browser negotiates through the
Accept-Encoding it already sends, and without that header the response
goes out raw exactly as before.
…brary

Items 11(c) and 11(d) of the owner's queue. A title's data was written
once and never revisited: a manga that gained chapters kept the old
total forever, and nothing in the app offered to ask again.

Refreshing reuses the warming loop rather than copying it. Warming asks
"what is missing?", refreshing asks "what changed?" — same path (token,
detail, art, snapshot, pause, event-loop yield, per-title failure), two
questions. WarmMode separates them without separating the path.

The manual action bypasses the 6h response cache. Without that, clicking
Refresh inside the window would return exactly what was already on
screen — a button that lies.

The total crosses a boundary on purpose, and only upward (owner's
decision). Snapshots are installation rows with no owner; entries.total
belongs to a person and may have been typed by hand. Growing is what
reality does; shrinking would erase someone's correction and could park
a title at 340 / 12, which is the pair the counter reads.

The sweep is a third job kind rather than enrich with a flag, because
the screen says different things about each and the per-kind index lets
them coexist — refusing a sweep someone asked for because an automatic
warming is still running would be the side effect outranking the
gesture. It is on demand only; the cron comes later, and what this cycle
leaves ready for it is the staleness cut in refreshTargets.

source becomes nullable (0054): a sweep rereads whatever providers the
titles point at, so there is no single source. Writing 'csv' to satisfy
NOT NULL would be a plausible lie in the database.
@Digit4w
Digit4w merged commit a7fa18d into dev Sep 13, 2026
2 checks passed
@Digit4w
Digit4w deleted the perf/background-warming-progress branch September 13, 2026 20:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant