Skip to content

Commit ecbe059

Browse files
committed
Prewarm Asteria headline board
1 parent 9f16ac4 commit ecbe059

3 files changed

Lines changed: 231 additions & 21 deletions

File tree

‎news_pipeline/news_pipeline/cli/commands/heartbeat_prepare_one.py‎

Lines changed: 182 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from __future__ import annotations
22

33
from collections import Counter
4-
from datetime import UTC, datetime
4+
from datetime import UTC, datetime, timedelta
55
import json
6+
import os
67
from pathlib import Path
78
import re
89
from typing import Any
@@ -19,6 +20,7 @@
1920
from news_pipeline.storage.json_store import JsonStore
2021

2122
MAX_PER_SOURCE = 3
23+
DEFAULT_PREWARM_BOARD_PATH = "news_pipeline/data/heartbeat/prepared-board.json"
2224
MIN_HEALTHY_BOARD_ELIGIBLE = 6
2325
HOT_CATEGORY_RECENT_WINDOW = 3
2426
HOT_CATEGORY_REPEAT_THRESHOLD = 2
@@ -673,22 +675,18 @@ def _full_collect_retry_reason(
673675
return None
674676

675677

676-
def prepare_one_command(
677-
collect: bool = typer.Option(True, "--collect/--no-collect", help="Run collect before preparing the editorial pack."),
678-
process: bool = typer.Option(True, "--process/--no-process", help="Run process before preparing the editorial pack."),
679-
cleanup: bool = typer.Option(True, "--cleanup/--no-cleanup", help="Run queue cleanup before preparing the editorial pack."),
680-
full_collect: bool = typer.Option(False, "--full-collect", help="Bypass source cadence during collect."),
681-
min_score: float = typer.Option(0.68, "--min-score", help="Strict publish threshold used for diagnostics."),
682-
max_source_age_hours: int = typer.Option(24, "--max-source-age-hours", help="Maximum source age for headline board freshness and auto publish diagnostics."),
683-
limit: int = typer.Option(20, "--limit", help="How many headline candidates to return."),
684-
json_output: bool = typer.Option(False, "--json", help="Emit machine-readable JSON."),
685-
) -> None:
686-
"""Prepare a compact editorial pack for Asteria to rewrite/review before publishing.
687-
688-
This command does technical prep only. It intentionally does not publish and does
689-
not replace Asteria's editorial judgment.
690-
"""
691-
root = Path.cwd()
678+
def _prepare_one_payload(
679+
root: Path,
680+
*,
681+
collect: bool,
682+
process: bool,
683+
cleanup: bool,
684+
full_collect: bool,
685+
min_score: float,
686+
max_source_age_hours: int,
687+
limit: int,
688+
command: str = "heartbeat prepare-one",
689+
) -> dict[str, Any]:
692690
steps = _run_prepare_pipeline(collect, process, cleanup, full_collect)
693691
packs, skipped, board_meta = _build_editorial_packs(
694692
root,
@@ -715,9 +713,9 @@ def prepare_one_command(
715713
)
716714

717715
result = "ready" if packs else "no_candidates"
718-
payload = {
716+
return {
719717
"schemaVersion": 1,
720-
"command": "heartbeat prepare-one",
718+
"command": command,
721719
"result": result,
722720
"instruction": "Headline board only. Asteria must choose promising headlines, fetch/read the selected article herself, write Turkish title/description/body/facts plus heroPrompt/heroAlt, apply them with `queue polish`, then run `heartbeat publish-one --execute --no-collect --json`. Python summaries and drafts are intentionally hidden to avoid anchoring.",
723721
"steps": [_compact_step(step) for step in steps],
@@ -731,7 +729,171 @@ def prepare_one_command(
731729
},
732730
"skippedSamples": skipped,
733731
}
732+
733+
734+
def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
735+
path.parent.mkdir(parents=True, exist_ok=True)
736+
tmp_path = path.with_name(f".{path.name}.{os.getpid()}.tmp")
737+
tmp_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
738+
tmp_path.replace(path)
739+
740+
741+
def _parse_datetime(value: Any) -> datetime | None:
742+
if not isinstance(value, str) or not value.strip():
743+
return None
744+
try:
745+
parsed = datetime.fromisoformat(value)
746+
except ValueError:
747+
return None
748+
if parsed.tzinfo is None:
749+
return parsed.replace(tzinfo=UTC)
750+
return parsed.astimezone(UTC)
751+
752+
753+
def _board_read_payload(path: Path, *, max_age_minutes: int) -> dict[str, Any]:
754+
now = datetime.now(UTC)
755+
base: dict[str, Any] = {
756+
"schemaVersion": 1,
757+
"command": "heartbeat board-read",
758+
"artifactPath": str(path),
759+
"readAt": now.isoformat(),
760+
"fresh": False,
761+
}
762+
if not path.exists():
763+
return {**base, "result": "missing", "reason": "prewarm board artifact not found"}
764+
try:
765+
payload = json.loads(path.read_text(encoding="utf-8"))
766+
except json.JSONDecodeError as exc:
767+
return {**base, "result": "invalid", "reason": f"invalid JSON: {exc.msg}"}
768+
if not isinstance(payload, dict):
769+
return {**base, "result": "invalid", "reason": "prewarm board artifact is not a JSON object"}
770+
if payload.get("command") != "heartbeat board-prewarm":
771+
return {**base, "result": "invalid", "reason": f"unexpected command: {payload.get('command')}"}
772+
773+
prewarm = payload.get("prewarm") if isinstance(payload.get("prewarm"), dict) else {}
774+
generated_at = _parse_datetime(prewarm.get("generatedAt") if prewarm else None)
775+
expires_at = _parse_datetime(prewarm.get("expiresAt") if prewarm else None)
776+
if generated_at is None:
777+
return {**base, "result": "invalid", "reason": "missing prewarm.generatedAt"}
778+
if now - generated_at > timedelta(minutes=max_age_minutes):
779+
return {
780+
**base,
781+
"result": "stale",
782+
"reason": f"prewarm board older than {max_age_minutes}m",
783+
"generatedAt": generated_at.isoformat(),
784+
}
785+
if expires_at is not None and now > expires_at:
786+
return {
787+
**base,
788+
"result": "stale",
789+
"reason": "prewarm board expired",
790+
"generatedAt": generated_at.isoformat(),
791+
"expiresAt": expires_at.isoformat(),
792+
}
793+
794+
payload["consumerRead"] = {
795+
"command": "heartbeat board-read",
796+
"readAt": now.isoformat(),
797+
"fresh": True,
798+
"maxAgeMinutes": max_age_minutes,
799+
}
800+
return payload
801+
802+
803+
def prepare_one_command(
804+
collect: bool = typer.Option(True, "--collect/--no-collect", help="Run collect before preparing the editorial pack."),
805+
process: bool = typer.Option(True, "--process/--no-process", help="Run process before preparing the editorial pack."),
806+
cleanup: bool = typer.Option(True, "--cleanup/--no-cleanup", help="Run queue cleanup before preparing the editorial pack."),
807+
full_collect: bool = typer.Option(False, "--full-collect", help="Bypass source cadence during collect."),
808+
min_score: float = typer.Option(0.68, "--min-score", help="Strict publish threshold used for diagnostics."),
809+
max_source_age_hours: int = typer.Option(24, "--max-source-age-hours", help="Maximum source age for headline board freshness and auto publish diagnostics."),
810+
limit: int = typer.Option(20, "--limit", help="How many headline candidates to return."),
811+
json_output: bool = typer.Option(False, "--json", help="Emit machine-readable JSON."),
812+
) -> None:
813+
"""Prepare a compact editorial pack for Asteria to rewrite/review before publishing.
814+
815+
This command does technical prep only. It intentionally does not publish and does
816+
not replace Asteria's editorial judgment.
817+
"""
818+
root = Path.cwd()
819+
payload = _prepare_one_payload(
820+
root,
821+
collect=collect,
822+
process=process,
823+
cleanup=cleanup,
824+
full_collect=full_collect,
825+
min_score=min_score,
826+
max_source_age_hours=max_source_age_hours,
827+
limit=limit,
828+
)
829+
if json_output:
830+
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2))
831+
else:
832+
typer.echo(f"{payload['result']}: {len(payload['candidates'])} candidate(s) prepared")
833+
834+
835+
def board_read_command(
836+
input_path: Path = typer.Option(Path(DEFAULT_PREWARM_BOARD_PATH), "--input", "-i", help="Prewarmed board artifact path."),
837+
max_age_minutes: int = typer.Option(15, "--max-age-minutes", min=1, help="Maximum acceptable board age."),
838+
json_output: bool = typer.Option(False, "--json", help="Emit machine-readable JSON."),
839+
) -> None:
840+
"""Read a prewarmed board only when it is fresh enough for Asteria."""
841+
root = Path.cwd()
842+
path = input_path if input_path.is_absolute() else root / input_path
843+
payload = _board_read_payload(path, max_age_minutes=max_age_minutes)
844+
if json_output:
845+
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2))
846+
return
847+
if payload.get("fresh"):
848+
typer.echo(f"{payload.get('result')}: {len(payload.get('candidates') or [])} fresh candidate(s) from {path}")
849+
else:
850+
typer.echo(f"{payload.get('result')}: {payload.get('reason')} ({path})")
851+
852+
853+
def board_prewarm_command(
854+
collect: bool = typer.Option(True, "--collect/--no-collect", help="Run collect before preparing the prewarmed board."),
855+
process: bool = typer.Option(True, "--process/--no-process", help="Run process before preparing the prewarmed board."),
856+
cleanup: bool = typer.Option(True, "--cleanup/--no-cleanup", help="Run queue cleanup before preparing the prewarmed board."),
857+
full_collect: bool = typer.Option(False, "--full-collect", help="Bypass source cadence during collect."),
858+
min_score: float = typer.Option(0.68, "--min-score", help="Strict publish threshold used for diagnostics."),
859+
max_source_age_hours: int = typer.Option(24, "--max-source-age-hours", help="Maximum source age for headline board freshness and auto publish diagnostics."),
860+
limit: int = typer.Option(6, "--limit", help="How many headline candidates to return."),
861+
output: Path = typer.Option(Path(DEFAULT_PREWARM_BOARD_PATH), "--output", "-o", help="Prewarmed board artifact path."),
862+
max_age_minutes: int = typer.Option(15, "--max-age-minutes", min=1, help="Freshness window consumers should enforce."),
863+
json_output: bool = typer.Option(False, "--json", help="Emit the written payload as JSON."),
864+
) -> None:
865+
"""Precompute Asteria's headline board outside the model session.
866+
867+
The output is written atomically so the scheduled Asteria run never consumes
868+
a partially-written board.
869+
"""
870+
root = Path.cwd()
871+
started_at = datetime.now(UTC)
872+
payload = _prepare_one_payload(
873+
root,
874+
collect=collect,
875+
process=process,
876+
cleanup=cleanup,
877+
full_collect=full_collect,
878+
min_score=min_score,
879+
max_source_age_hours=max_source_age_hours,
880+
limit=limit,
881+
command="heartbeat board-prewarm",
882+
)
883+
generated_at = datetime.now(UTC)
884+
expires_at = generated_at + timedelta(minutes=max_age_minutes)
885+
output_path = output if output.is_absolute() else root / output
886+
payload["prewarm"] = {
887+
"artifactPath": str(output_path),
888+
"startedAt": started_at.isoformat(),
889+
"generatedAt": generated_at.isoformat(),
890+
"expiresAt": expires_at.isoformat(),
891+
"maxAgeMinutes": max_age_minutes,
892+
"consumer": "Asteria isolated cron",
893+
}
894+
_atomic_write_json(output_path, payload)
895+
734896
if json_output:
735897
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2))
736898
else:
737-
typer.echo(f"{result}: {len(packs)} candidate(s) prepared")
899+
typer.echo(f"{payload['result']}: wrote {len(payload['candidates'])} candidate(s) to {output_path}")

‎news_pipeline/news_pipeline/cli/main.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from news_pipeline.cli.commands.queue_summary import queue_summary_command
1919
from news_pipeline.cli.commands.queue_polish import queue_polish_command
2020
from news_pipeline.cli.commands.queue_source_text import queue_source_text_command
21-
from news_pipeline.cli.commands.heartbeat_prepare_one import prepare_one_command
21+
from news_pipeline.cli.commands.heartbeat_prepare_one import board_prewarm_command, board_read_command, prepare_one_command
2222
from news_pipeline.cli.commands.heartbeat_publish_one import publish_one_command
2323

2424
app = typer.Typer(help="Editorial-first news pipeline CLI")
@@ -42,6 +42,8 @@
4242
queue_app.command("polish")(queue_polish_command)
4343
queue_app.command("source-text")(queue_source_text_command)
4444
heartbeat_app.command("prepare-one")(prepare_one_command)
45+
heartbeat_app.command("board-prewarm")(board_prewarm_command)
46+
heartbeat_app.command("board-read")(board_read_command)
4547
heartbeat_app.command("publish-one")(publish_one_command)
4648
demo_app.command("seed")(demo_seed_command)
4749
demo_app.command("walkthrough")(demo_walkthrough_command)

‎news_pipeline/tests/test_safety_gates.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
from datetime import UTC, datetime, timedelta
4+
import json
45
from pathlib import Path
56

67
import pytest
@@ -1114,6 +1115,51 @@ def test_queue_source_text_returns_bounded_extracted_text(tmp_path: Path, monkey
11141115
assert '"text": "Temiz kaynak metni."' in output
11151116

11161117

1118+
def test_board_prewarm_writes_atomic_artifact(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
1119+
monkeypatch.chdir(tmp_path)
1120+
article = _article("prewarm-article", url="https://example.org/demo/prewarm")
1121+
item = _item("prewarm-demo", normalized_id=article.id, url="https://example.org/demo/prewarm")
1122+
_save_runtime(tmp_path, item, article)
1123+
1124+
output = Path("news_pipeline/data/heartbeat/prepared-board.json")
1125+
heartbeat_prepare_one.board_prewarm_command(
1126+
collect=False,
1127+
process=False,
1128+
cleanup=False,
1129+
full_collect=False,
1130+
min_score=0.68,
1131+
max_source_age_hours=72,
1132+
limit=6,
1133+
output=output,
1134+
max_age_minutes=15,
1135+
json_output=False,
1136+
)
1137+
1138+
artifact = tmp_path / output
1139+
payload = json.loads(artifact.read_text(encoding="utf-8"))
1140+
1141+
assert payload["schemaVersion"] == 1
1142+
assert payload["command"] == "heartbeat board-prewarm"
1143+
assert payload["result"] == "ready"
1144+
assert payload["candidates"][0]["queueId"] == "prewarm-demo"
1145+
assert payload["prewarm"]["artifactPath"] == str(artifact)
1146+
assert payload["prewarm"]["maxAgeMinutes"] == 15
1147+
assert not list(artifact.parent.glob("*.tmp"))
1148+
1149+
read_payload = heartbeat_prepare_one._board_read_payload(artifact, max_age_minutes=15)
1150+
assert read_payload["command"] == "heartbeat board-prewarm"
1151+
assert read_payload["consumerRead"]["fresh"] is True
1152+
assert read_payload["candidates"][0]["queueId"] == "prewarm-demo"
1153+
1154+
1155+
def test_board_read_reports_missing_artifact(tmp_path: Path) -> None:
1156+
payload = heartbeat_prepare_one._board_read_payload(tmp_path / "missing-board.json", max_age_minutes=15)
1157+
1158+
assert payload["command"] == "heartbeat board-read"
1159+
assert payload["result"] == "missing"
1160+
assert payload["fresh"] is False
1161+
1162+
11171163
def test_prepare_one_compacts_success_step_logs_in_json_payload(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
11181164
monkeypatch.setattr(
11191165
heartbeat_prepare_one,

0 commit comments

Comments
 (0)