fix(summarizer): fail loudly on a rejected model id; parallel map phase
The analyst produced no briefs for nine days because SUMMARY_MODEL had been retired: every chat completion returned 404, nous_client.chat() swallowed it into "", and the map phase "succeeded" with zero blocks. - nous_client.chat(): log status_code + a 500-char body slice for every non-200. 400/404/422 now raise NousAPIError (bad model id / payload cannot succeed on a retry); 429/5xx are retried with backoff inside the call; 401/other keep the old empty-return contract. - Startup validation: one GET /models per process; if SUMMARY_MODEL is absent the run logs an ERROR with the configured id plus near matches and returns rc=2 before issuing any chat call. Fails open (warning) when /models itself is unreachable. - Map phase: ThreadPoolExecutor fan-out capped by SUMMARY_MAP_CONCURRENCY (default 16). Grading still runs in batch order on the main thread; reduce stays serial; the 60 s per-call timeout is unchanged. - summarize_news() now returns an exit code and __main__ sys.exit()s it: zero parsed map blocks, an empty reduce, or an unpersisted brief all exit non-zero. The scheduler logs rc at ERROR when it is not 0. - Map calls start at 8192 completion tokens (they escalate to 16384): ~60% of real batches overflowed 4096 and were regenerated at 8192, doubling their wall time for no benefit. Measured on the real backlog: NEWS_RECAP=1 NEWS_SUMMARIZE_FORCE=1 python summarizer.py over 2984 articles / 746 batches finished in 951 s (15m51s), rc=0, 746/746 batches non-empty, 0 warnings. Prompts, BATCH_SIZE=4, grading/rubric behaviour and the DB schema are untouched (article_summaries.kind stays interval / daily_recap).
This commit is contained in:
parent
6066ac8e0d
commit
625c935c80
6 changed files with 781 additions and 51 deletions
|
|
@ -21,6 +21,7 @@ of each summarize_news() — env wins, else api_keys / app_settings:
|
|||
SUMMARY_DEDUPE "0" disables syndication dedupe (default on)
|
||||
SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85)
|
||||
BATCH_SIZE articles per map-phase batch (default 50)
|
||||
SUMMARY_MAP_CONCURRENCY concurrent map calls in flight (default 16)
|
||||
SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set)
|
||||
NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt)
|
||||
NEWS_SUMMARIZE_FORCE "1" to ignore the interval/recap idempotency skip
|
||||
|
|
@ -32,6 +33,9 @@ from __future__ import annotations
|
|||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
|
@ -51,7 +55,7 @@ from intel import (
|
|||
select_map,
|
||||
select_ticker,
|
||||
)
|
||||
from nous_client import chat
|
||||
from nous_client import NousAPIError, chat, model_available
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger("news.summarizer")
|
||||
|
|
@ -79,6 +83,14 @@ DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40
|
|||
DEFAULT_SUMMARY_DEDUPE_SIMILARITY = 0.85
|
||||
_FALSY = ("0", "false", "no", "off")
|
||||
|
||||
# Map-phase fan-out. 745 batches at ~16 s serial is 3.3 h; the nightly recap
|
||||
# has to finish long before morning, so map calls run concurrently while the
|
||||
# reduce stays serial (it is one call). Measured on the real 24h backlog
|
||||
# (2985 articles / 745 batches, deepseek/deepseek-v4.1-flash-1017): each call
|
||||
# is ~20 s wall, so throughput tracks the concurrency; 16 lands the recap
|
||||
# under 20 minutes.
|
||||
DEFAULT_SUMMARY_MAP_CONCURRENCY = 16
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
raw = (os.getenv(name) or "").strip()
|
||||
|
|
@ -102,6 +114,11 @@ def _env_float(name: str, default: float) -> float:
|
|||
return default
|
||||
|
||||
|
||||
def map_concurrency() -> int:
|
||||
"""Concurrent map calls in flight (SUMMARY_MAP_CONCURRENCY, default 8)."""
|
||||
return max(1, _env_int("SUMMARY_MAP_CONCURRENCY", DEFAULT_SUMMARY_MAP_CONCURRENCY))
|
||||
|
||||
|
||||
def dedupe_config() -> tuple[bool, float]:
|
||||
"""(enabled, similarity) from env. SUMMARY_DEDUPE=0 skips dedupe entirely."""
|
||||
enabled = (os.getenv("SUMMARY_DEDUPE") or "1").strip().lower() not in _FALSY
|
||||
|
|
@ -693,10 +710,72 @@ def build_master_prompt(final_input: str, recap: bool = False) -> str:
|
|||
return template
|
||||
|
||||
|
||||
def summarize_news() -> None:
|
||||
"""Map-reduce summarize recent articles and store brief + ticker + map."""
|
||||
def map_phase(
|
||||
articles: list[dict],
|
||||
*,
|
||||
api_key: str,
|
||||
model: str,
|
||||
base_url: str,
|
||||
concurrency: int | None = None,
|
||||
) -> tuple[list[tuple[int, str]], int, int]:
|
||||
"""Run the map calls concurrently and return ([(batch_index, response)], empty, total).
|
||||
|
||||
At most ``concurrency`` calls are in flight (a fixed-size thread pool is the
|
||||
cap, not a suggestion). Responses come back in batch order so grading stays
|
||||
deterministic. ``NousAPIError`` (400/404/422 — e.g. a retired model id)
|
||||
aborts the phase: the remaining queued batches are cancelled and the
|
||||
exception propagates to the caller.
|
||||
"""
|
||||
total = -(-len(articles) // BATCH_SIZE)
|
||||
workers = max(1, concurrency if concurrency is not None else map_concurrency())
|
||||
|
||||
def run_batch(batch_index: int) -> tuple[int, str]:
|
||||
batch = articles[batch_index * BATCH_SIZE : (batch_index + 1) * BATCH_SIZE]
|
||||
return batch_index, call_llm(
|
||||
build_map_prompt(batch),
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
base_url=base_url,
|
||||
json_mode=False,
|
||||
)
|
||||
|
||||
logger.info("map phase: %d batches (%d articles), concurrency=%d", total, len(articles), workers)
|
||||
responses: dict[int, str] = {}
|
||||
empty = 0
|
||||
pool = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="news-map")
|
||||
futures = [pool.submit(run_batch, i) for i in range(total)]
|
||||
try:
|
||||
for done, future in enumerate(as_completed(futures), start=1):
|
||||
batch_index, response = future.result()
|
||||
if response:
|
||||
responses[batch_index] = response
|
||||
else:
|
||||
empty += 1
|
||||
logger.warning("map batch %d/%d returned empty", batch_index + 1, total)
|
||||
if done % 10 == 0 or done == total:
|
||||
logger.info(
|
||||
"map progress %d/%d batches (ok=%d empty=%d)",
|
||||
done, total, len(responses), empty,
|
||||
)
|
||||
except BaseException:
|
||||
for future in futures:
|
||||
future.cancel()
|
||||
raise
|
||||
finally:
|
||||
pool.shutdown(wait=True, cancel_futures=True)
|
||||
return [(i, responses[i]) for i in sorted(responses)], empty, total
|
||||
|
||||
|
||||
def summarize_news() -> int:
|
||||
"""Map-reduce summarize recent articles and store brief + ticker + map.
|
||||
|
||||
Returns a process exit code: 0 on success or an intentional skip, non-zero
|
||||
when no brief could be produced — the scheduler logs rc != 0, so a dead
|
||||
model or API never again looks like a quiet, empty success.
|
||||
"""
|
||||
recap = is_recap_run()
|
||||
window = effective_window_minutes(recap=recap)
|
||||
started = time.monotonic()
|
||||
ensure_tables()
|
||||
if recap:
|
||||
if _already_recapped_today():
|
||||
|
|
@ -704,26 +783,34 @@ def summarize_news() -> None:
|
|||
"Skipping recap: article_summaries already has daily_recap today "
|
||||
"(set NEWS_SUMMARIZE_FORCE=1 to override)"
|
||||
)
|
||||
return
|
||||
return 0
|
||||
elif _already_summarized_this_interval():
|
||||
logger.info(
|
||||
"Skipping summarize: article_summaries already has a row in the last %ss "
|
||||
"(set NEWS_SUMMARIZE_FORCE=1 to override)",
|
||||
_summarize_interval_seconds(),
|
||||
)
|
||||
return
|
||||
return 0
|
||||
|
||||
api_key = resolve_api_key()
|
||||
model = resolve_model()
|
||||
base_url = resolve_base_url()
|
||||
if not api_key:
|
||||
logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run")
|
||||
return
|
||||
logger.error("NOUS_API_KEY unset in env and api_keys — cannot summarize (rc=1)")
|
||||
return 1
|
||||
# One GET /models per process. A retired SUMMARY_MODEL disables the run
|
||||
# here instead of turning into 745 silent 404s.
|
||||
if not model_available(api_key=api_key, base_url=base_url, model=model):
|
||||
logger.error(
|
||||
"SUMMARY_MODEL=%s is not offered by %s — skipping this run (rc=2)",
|
||||
model, base_url,
|
||||
)
|
||||
return 2
|
||||
|
||||
articles = get_recent_news(window)
|
||||
if not articles:
|
||||
logger.info("No new articles found in the last %s min.", window)
|
||||
return
|
||||
return 0
|
||||
|
||||
min_score, top_n, fallback_top, fallback_min_score = selection_config()
|
||||
logger.info(
|
||||
|
|
@ -734,22 +821,19 @@ def summarize_news() -> None:
|
|||
)
|
||||
|
||||
graded: list[dict] = []
|
||||
for i in range(0, len(articles), BATCH_SIZE):
|
||||
batch = articles[i : i + BATCH_SIZE]
|
||||
batch_index = i // BATCH_SIZE
|
||||
logger.info(
|
||||
"map batch %d/%d (%d articles)",
|
||||
batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch),
|
||||
try:
|
||||
mapped, empty, total_batches = map_phase(
|
||||
articles, api_key=api_key, model=model, base_url=base_url
|
||||
)
|
||||
response = call_llm(
|
||||
build_map_prompt(batch),
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
base_url=base_url,
|
||||
json_mode=False,
|
||||
except NousAPIError as exc:
|
||||
logger.error(
|
||||
"map phase aborted on a non-retryable Nous API error (%s) — run failed (rc=1)",
|
||||
exc,
|
||||
)
|
||||
if not response:
|
||||
continue
|
||||
return 1
|
||||
|
||||
for batch_index, response in mapped:
|
||||
batch = articles[batch_index * BATCH_SIZE : (batch_index + 1) * BATCH_SIZE]
|
||||
blocks, stats = parse_map_scores(
|
||||
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
||||
)
|
||||
|
|
@ -766,8 +850,12 @@ def summarize_news() -> None:
|
|||
graded.extend(blocks)
|
||||
|
||||
if not graded:
|
||||
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
|
||||
return
|
||||
logger.error(
|
||||
"map phase produced no article blocks (%d/%d batches empty) — "
|
||||
"nothing to reduce, run failed (rc=1)",
|
||||
empty, total_batches,
|
||||
)
|
||||
return 1
|
||||
|
||||
dedupe_enabled, dedupe_similarity = dedupe_config()
|
||||
distinct, dedupe_stats = dedupe_blocks(
|
||||
|
|
@ -826,8 +914,8 @@ def summarize_news() -> None:
|
|||
json_mode=True,
|
||||
)
|
||||
if not master_raw:
|
||||
logger.warning("Reduce phase returned empty — nothing to persist.")
|
||||
return
|
||||
logger.error("Reduce phase returned empty — nothing to persist, run failed (rc=1)")
|
||||
return 1
|
||||
parsed = parse_reduce_json(master_raw)
|
||||
selected_articles = [
|
||||
block["article"]
|
||||
|
|
@ -843,7 +931,22 @@ def summarize_news() -> None:
|
|||
articles=selected_articles,
|
||||
)
|
||||
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
|
||||
elapsed = time.monotonic() - started
|
||||
if not summary_id:
|
||||
logger.error(
|
||||
"summarize failed: brief was not persisted (kind=%s, %.1fs) (rc=1)",
|
||||
"daily_recap" if recap else "interval", elapsed,
|
||||
)
|
||||
return 1
|
||||
logger.info(
|
||||
"summarize done kind=%s summary_id=%s model=%s batches=%d/%d articles=%d "
|
||||
"ticker=%d map=%d elapsed=%.1fs",
|
||||
"daily_recap" if recap else "interval", summary_id, model,
|
||||
len(mapped), total_batches, len(articles),
|
||||
len(parsed["ticker"]), len(parsed["map_items"]), elapsed,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
summarize_news()
|
||||
sys.exit(summarize_news())
|
||||
|
|
|
|||
Loading…
Reference in a new issue