feat(summarizer): score articles in the map phase, brief only the important ones #53

Merged
sirius merged 1 commit from wt/t_87992985 into master 2026-11-14 02:49:24 +00:00
Owner

What this changes

The reduce phase no longer sees every article in the window. The map phase grades each article 0-100 against an explicit rubric, the summarizer parses that score, and only the blocks at or above SUMMARY_MIN_SCORE reach the brief, best first.

1. Map prompt emits a machine-parsable score

MAP_PROMPT_DEFAULT now carries the rubric verbatim, and - Score: <0-100> / - Importance: critical|high|medium|low|none are the first two lines of every article block:

  • 90–100 breaking geopolitical/military/security or major disaster
  • 70–89 significant national/international politics, conflict, security, infrastructure, disaster
  • 40–69 notable regional/economic/tech/health with real consequences
  • 10–39 routine/minor/single-incident crime, local interest
  • 0–9 noise: sport, celebrity, entertainment, market tape, promotional or event-calendar/schedule listings

Existing bullets, location, entities, category, OSINT-signal lines and the Batch theme: trailer are unchanged.

2. Parse and select (news/summerizer/intel.py, pure, no DB)

parse_map_scores(raw, *, articles, batch_index, batch_size) splits on Article <n>: (case-insensitive, markdown/whitespace tolerant), reads the first Score: (clamped 0–100), falls back to the Importance: label (critical 95 / high 78 / medium 50 / low 22 / none 5), then to 50, and never raises. Block n of batch b maps to articles[b*BATCH_SIZE + n - 1]; blocks whose number does not land in the batch are counted as unattributed and dropped (nothing to attribute them to).

select_graded(blocks, *, min_score, top_n, fallback_top) sorts score-desc (stable on ties), keeps score >= min_score capped at top_n; when nothing clears the bar it returns the top fallback_top blocks. SUMMARY_FALLBACK_TOP=0 returns an empty selection and the reduce phase receives an empty DATA section.

join_blocks() builds the reduce DATA text from the selected blocks only, original text (Score line included), highest score first. {final_input} contract unchanged.

3. Reduce prompts stop demanding filler

SUMMARY_PROMPT_DEFAULT and RECAP_PROMPT_DEFAULT lost "fill the brief/recap with minor incidents and crime reports" and "fill ticker with medium then low incidents and crime". They now state that DATA is pre-filtered by score and ordered best-first, to lead with the highest-scoring breaking stories, never promote an item above its score, and to return {"summary_en":"No significant developments in this window.","ticker":[],"map_items":[]} for empty DATA. JSON shape, ticker/map caps and the never-truncate rule are unchanged.

4. Grades persisted

New article_scores table (article_id, summary_id, score, category, selected, model, created_at, PK (article_id, created_at), index on summary_id), created in ensure_tables() and as alembic 012_article_scores (down_revision 011_geofence_alerts_fence). save_batch() now returns the new summary id; persist_article_scores() writes one row per graded article after it (selected true/false). Insert failure is logged and does not abort the run.

get_recent_news() now also selects articles.id — needed for attribution. Nothing else about the query changed.

5. Config

SUMMARY_MIN_SCORE (60), SUMMARY_TOP_N (12), SUMMARY_FALLBACK_TOP (3), read per run via _env_int/selection_config(), documented in .env.example next to NEWS_BATCH_SIZE and in docs/news.md ("Grading and selection" + config table). No homek8s edits.

Non-goals respected: no extra LLM calls, no app/requirements.txt, BATCH_SIZE, scraper, urls.txt, app/main.py models, news_items schema or nous_client.py changes, no new dependency.

Verification (real output)

1. pytest -q in the repo — before: 344 passed, 17 skipped (master). After: 344 passed, 17 skipped (the default run does not collect news/summerizer/tests — see next block).

$ python -m pytest -q
344 passed, 17 skipped in 3.10s

2. Summarizer suite (before this branch: 29 passed):

$ PYTHONPATH=news/summerizer python -m pytest -q news/summerizer/tests
60 passed in 0.09s

New/updated: test_grading.py (score present / missing per Importance label / garbage / clamp / markdown+case tolerance / batch attribution / omitted+reordered / out-of-range+duplicate / never raises; threshold+cap, stable ties, fallback, fallback_top=0, no leaked low-score block), test_grading_pipeline.py (offline end-to-end, monkeypatched call_llm, recording fake psycopg2: multi-batch attribution, reduce prompt contains only selected blocks best-first, all-low fallback, SUMMARY_FALLBACK_TOP=0 empty DATA, score-insert failure does not abort), test_prompts.py (rubric lines present and Score first in the block; neither reduce prompt contains the old filler sentences).

3. Offline end-to-end assertions (fake DB, 6 articles, BATCH_SIZE=3, scripted scores 92/34/81 + 12/66/no-Score→low): reduce prompt contains Score: 92, Score: 81, Score: 66 in that order and none of Score: 34, Score: 12, Importance: low; article_scores rows selected = articles {1,3,5} with summary_id=42 and the run's model.

4. Scratch Postgres (postgres:16 container), real DB writes, monkeypatched LLM — 6 seeded articles incl. a wiseye.org event-calendar listing and one article with no Score: line:

=== article_summaries ===
(1, 'interval', 'meituan/longcat-2.5:free', 'Kyiv endured a missile barrage overnight; parliament passed an emergency infrastructure bi')

=== article_scores ===   -- select score, selected from article_scores order by score desc limit 10;
(93, True)
(78, True)
(71, True)
(6, False)
(4, False)
(2, False)

=== attribution ===
(1, 'Kyiv struck by missile barrage, power grid down',   93, True,  'military/conflict', 1)
(5, 'Cabinet reshuffle after minister resigns',          78, True,  'politics',          1)   <- Importance: high fallback
(3, 'Parliament passes emergency infrastructure bill',   71, True,  'politics',          1)
(2, 'Brent crude ticks up 0.3% in quiet trading',         6, False, 'economy',           1)
(4, 'Local 5K charity run draws 300 runners',             4, False, 'society',           1)
(6, 'Community calendar: weekly schedule of events',      2, False, 'other',             1)

=== news_items ===
('ticker', 'Missile barrage hits Kyiv, power grid down', 'critical')
('map', 'Missile barrage hits Kyiv', 'critical')

The reduce prompt's DATA section contained exactly Article 1 (93), Article 5 (78, label fallback) and Article 3 (71) — the Brent tape, the 5K and the event-calendar listing were dropped.

5. Alembic: alembic heads → 012_article_scores (head) (single head, linear after 011_geofence_alerts_fence). On a scratch PostGIS 16 DB stamped at 011, alembic upgrade head applies 012 and \d article_scores shows PK (article_id, created_at) plus ix_article_scores_summary. (A full 001→head replay needs the PostGIS and TimescaleDB extensions, unavailable in the scratch images; that is an environment limit, not a diff issue.)

Premise flag (not silently widened)

I have not run this against the live free-tier model (meituan/longcat-2.5:free) — that check needs the cluster and the real key, and belongs to the post-merge live verification. The Importance:-label fallback is implemented and unit-tested precisely so a model that drops Score: still yields a usable ranking, and every fallback is counted per batch in the logs (map batch N graded x/y (score fallback=k, unattributed=u)). If the live model drops Score: for most articles, the evidence to look for is fallback=k ≈ graded; the fix then should be a second, tiny grading request over titles only — not a wider rubric squeezed into the map prompt.

Merge policy

PR only. Do not merge — the operator merges, rebuilds the amd64 news-summarizer image, pins it in sirius/homek8s apps/base/osint/news-summarizer-deployment.yaml and does the live prompt-quality check. The red Pi compose workflow on master pushes is the known-broken unrelated job.

## What this changes The reduce phase no longer sees every article in the window. The map phase grades each article 0-100 against an explicit rubric, the summarizer parses that score, and only the blocks at or above `SUMMARY_MIN_SCORE` reach the brief, best first. ### 1. Map prompt emits a machine-parsable score `MAP_PROMPT_DEFAULT` now carries the rubric verbatim, and `- Score: <0-100>` / `- Importance: critical|high|medium|low|none` are the **first two lines** of every article block: - 90–100 breaking geopolitical/military/security or major disaster - 70–89 significant national/international politics, conflict, security, infrastructure, disaster - 40–69 notable regional/economic/tech/health with real consequences - 10–39 routine/minor/single-incident crime, local interest - 0–9 noise: sport, celebrity, entertainment, market tape, promotional or event-calendar/schedule listings Existing bullets, location, entities, category, OSINT-signal lines and the `Batch theme:` trailer are unchanged. ### 2. Parse and select (`news/summerizer/intel.py`, pure, no DB) `parse_map_scores(raw, *, articles, batch_index, batch_size)` splits on `Article <n>:` (case-insensitive, markdown/whitespace tolerant), reads the first `Score:` (clamped 0–100), falls back to the `Importance:` label (critical 95 / high 78 / medium 50 / low 22 / none 5), then to 50, and never raises. Block `n` of batch `b` maps to `articles[b*BATCH_SIZE + n - 1]`; blocks whose number does not land in the batch are counted as `unattributed` and dropped (nothing to attribute them to). `select_graded(blocks, *, min_score, top_n, fallback_top)` sorts score-desc (stable on ties), keeps `score >= min_score` capped at `top_n`; when nothing clears the bar it returns the top `fallback_top` blocks. `SUMMARY_FALLBACK_TOP=0` returns an empty selection and the reduce phase receives an empty DATA section. `join_blocks()` builds the reduce DATA text from the selected blocks only, original text (Score line included), highest score first. `{final_input}` contract unchanged. ### 3. Reduce prompts stop demanding filler `SUMMARY_PROMPT_DEFAULT` and `RECAP_PROMPT_DEFAULT` lost "fill the brief/recap with minor incidents and crime reports" and "fill ticker with medium then low incidents and crime". They now state that DATA is pre-filtered by score and ordered best-first, to lead with the highest-scoring breaking stories, never promote an item above its score, and to return `{"summary_en":"No significant developments in this window.","ticker":[],"map_items":[]}` for empty DATA. JSON shape, ticker/map caps and the never-truncate rule are unchanged. ### 4. Grades persisted New `article_scores` table (`article_id, summary_id, score, category, selected, model, created_at`, PK `(article_id, created_at)`, index on `summary_id`), created in `ensure_tables()` and as alembic `012_article_scores` (down_revision `011_geofence_alerts_fence`). `save_batch()` now returns the new summary id; `persist_article_scores()` writes one row per graded article after it (selected true/false). Insert failure is logged and does not abort the run. `get_recent_news()` now also selects `articles.id` — needed for attribution. Nothing else about the query changed. ### 5. Config `SUMMARY_MIN_SCORE` (60), `SUMMARY_TOP_N` (12), `SUMMARY_FALLBACK_TOP` (3), read per run via `_env_int`/`selection_config()`, documented in `.env.example` next to `NEWS_BATCH_SIZE` and in `docs/news.md` ("Grading and selection" + config table). No `homek8s` edits. Non-goals respected: no extra LLM calls, no `app/requirements.txt`, `BATCH_SIZE`, scraper, `urls.txt`, `app/main.py` models, `news_items` schema or `nous_client.py` changes, no new dependency. ## Verification (real output) **1. `pytest -q` in the repo** — before: `344 passed, 17 skipped` (master). After: `344 passed, 17 skipped` (the default run does not collect `news/summerizer/tests` — see next block). ``` $ python -m pytest -q 344 passed, 17 skipped in 3.10s ``` **2. Summarizer suite** (before this branch: `29 passed`): ``` $ PYTHONPATH=news/summerizer python -m pytest -q news/summerizer/tests 60 passed in 0.09s ``` New/updated: `test_grading.py` (score present / missing per Importance label / garbage / clamp / markdown+case tolerance / batch attribution / omitted+reordered / out-of-range+duplicate / never raises; threshold+cap, stable ties, fallback, `fallback_top=0`, no leaked low-score block), `test_grading_pipeline.py` (offline end-to-end, monkeypatched `call_llm`, recording fake psycopg2: multi-batch attribution, reduce prompt contains only selected blocks best-first, all-low fallback, `SUMMARY_FALLBACK_TOP=0` empty DATA, score-insert failure does not abort), `test_prompts.py` (rubric lines present and Score first in the block; neither reduce prompt contains the old filler sentences). **3. Offline end-to-end assertions** (fake DB, 6 articles, BATCH_SIZE=3, scripted scores 92/34/81 + 12/66/no-Score→low): reduce prompt contains `Score: 92`, `Score: 81`, `Score: 66` in that order and none of `Score: 34`, `Score: 12`, `Importance: low`; `article_scores` rows selected = articles {1,3,5} with `summary_id=42` and the run's model. **4. Scratch Postgres (postgres:16 container), real DB writes, monkeypatched LLM** — 6 seeded articles incl. a `wiseye.org` event-calendar listing and one article with no `Score:` line: ``` === article_summaries === (1, 'interval', 'meituan/longcat-2.5:free', 'Kyiv endured a missile barrage overnight; parliament passed an emergency infrastructure bi') === article_scores === -- select score, selected from article_scores order by score desc limit 10; (93, True) (78, True) (71, True) (6, False) (4, False) (2, False) === attribution === (1, 'Kyiv struck by missile barrage, power grid down', 93, True, 'military/conflict', 1) (5, 'Cabinet reshuffle after minister resigns', 78, True, 'politics', 1) <- Importance: high fallback (3, 'Parliament passes emergency infrastructure bill', 71, True, 'politics', 1) (2, 'Brent crude ticks up 0.3% in quiet trading', 6, False, 'economy', 1) (4, 'Local 5K charity run draws 300 runners', 4, False, 'society', 1) (6, 'Community calendar: weekly schedule of events', 2, False, 'other', 1) === news_items === ('ticker', 'Missile barrage hits Kyiv, power grid down', 'critical') ('map', 'Missile barrage hits Kyiv', 'critical') ``` The reduce prompt's DATA section contained exactly `Article 1` (93), `Article 5` (78, label fallback) and `Article 3` (71) — the Brent tape, the 5K and the event-calendar listing were dropped. **5. Alembic**: `alembic heads` → `012_article_scores (head)` (single head, linear after `011_geofence_alerts_fence`). On a scratch PostGIS 16 DB stamped at 011, `alembic upgrade head` applies 012 and `\d article_scores` shows PK `(article_id, created_at)` plus `ix_article_scores_summary`. (A full `001→head` replay needs the PostGIS **and** TimescaleDB extensions, unavailable in the scratch images; that is an environment limit, not a diff issue.) ## Premise flag (not silently widened) I have **not** run this against the live free-tier model (`meituan/longcat-2.5:free`) — that check needs the cluster and the real key, and belongs to the post-merge live verification. The `Importance:`-label fallback is implemented and unit-tested precisely so a model that drops `Score:` still yields a usable ranking, and every fallback is counted per batch in the logs (`map batch N graded x/y (score fallback=k, unattributed=u)`). If the live model drops `Score:` for most articles, the evidence to look for is `fallback=k` ≈ `graded`; the fix then should be a second, tiny grading request over titles only — not a wider rubric squeezed into the map prompt. ## Merge policy PR only. Do not merge — the operator merges, rebuilds the amd64 `news-summarizer` image, pins it in `sirius/homek8s apps/base/osint/news-summarizer-deployment.yaml` and does the live prompt-quality check. The red Pi compose workflow on master pushes is the known-broken unrelated job.
The map prompt now grades every article 0-100 against an explicit rubric as
the first line of its block; the summarizer parses Score:, falls back to the
Importance: label when the line is missing, ranks blocks best-first and passes
only score >= SUMMARY_MIN_SCORE (capped at SUMMARY_TOP_N) to the reduce phase.

- new pure helpers in intel.py: parse_map_scores(), select_graded(), join_blocks()
- reduce prompts drop the 'fill the brief with minor incidents and crime'
  filler instructions and the 'fill ticker with medium then low' clause
- new article_scores table (ensure_tables + alembic 012) persists every grade
  with selected/summary_id/model so thresholds can be tuned from data
- SUMMARY_MIN_SCORE (60), SUMMARY_TOP_N (12), SUMMARY_FALLBACK_TOP (3) env knobs
sirius merged commit 2c41737d42 into master 2026-11-14 02:49:24 +00:00
sirius deleted branch wt/t_87992985 2026-11-14 02:49:25 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sirius/osint-dashboard!53
No description provided.