|
| 1 | +"""Build and emit a ``misc.greenlight_pr_state`` row to S3 for replicator ingestion. |
| 2 | +
|
| 3 | +Two producers write state rows and MUST agree byte-for-byte on the JSONEachRow field |
| 4 | +order/values and the object-key layout, or the positional S3 -> ClickHouse replicator |
| 5 | +silently drops rows. This module is that single source: ``emit_row`` serializes the row and |
| 6 | +``object_key`` computes its bucket-relative key. The ``verdict`` command feeds its rows |
| 7 | +through here; the scan calls ``emit_ai_review_dispatched`` the instant it fires the reviewer |
| 8 | +workflow, so a queued run (which can sit in GitHub's Actions queue well past a scan interval) |
| 9 | +is recorded as in-flight immediately and never re-dispatched while it waits. |
| 10 | +
|
| 11 | +``verdict`` writes the row to a fixed local path that its workflow ``aws s3 cp``s after a |
| 12 | +``success()`` gate; the scan has no such gate, so its default ``upload`` puts the object to |
| 13 | +``s3://{S3_BUCKET}/{key}`` directly via boto3's default credential chain (the scan workflow's |
| 14 | +OIDC env supplies the AWS creds at runtime). |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import gzip |
| 20 | +import json |
| 21 | +import uuid |
| 22 | +from datetime import UTC, datetime |
| 23 | +from typing import TYPE_CHECKING, Protocol, cast |
| 24 | + |
| 25 | +from greenlight.constants import S3_BUCKET, S3_KEY_PREFIX, STATUS_AI_REVIEW_DISPATCHED |
| 26 | + |
| 27 | +if TYPE_CHECKING: |
| 28 | + from collections.abc import Callable |
| 29 | + |
| 30 | +__all__ = ["default_emit_id", "emit_ai_review_dispatched", "emit_row", "object_key"] |
| 31 | + |
| 32 | + |
| 33 | +class _S3Putter(Protocol): |
| 34 | + def put_object(self, *, Bucket: str, Key: str, Body: bytes) -> object: ... # pragma: no cover |
| 35 | + |
| 36 | + |
| 37 | +def _utcnow() -> datetime: |
| 38 | + return datetime.now(UTC) |
| 39 | + |
| 40 | + |
| 41 | +def default_emit_id() -> str: |
| 42 | + """The row schema's default emit-id: a fresh uuid4 hex, single-sourced for every producer.""" |
| 43 | + return uuid.uuid4().hex |
| 44 | + |
| 45 | + |
| 46 | +def object_key(repo: str, pr_number: int, version: str, emit_id: str) -> str: |
| 47 | + compact = version.replace("-", "").replace(":", "").replace(" ", "T").replace(".", "_") |
| 48 | + return f"{S3_KEY_PREFIX}/{repo}/{pr_number}/{compact}-{emit_id}.json.gz" |
| 49 | + |
| 50 | + |
| 51 | +def emit_row( |
| 52 | + *, |
| 53 | + repo: str, |
| 54 | + pr_number: int, |
| 55 | + head_sha: str, |
| 56 | + status: str, |
| 57 | + reason: str, |
| 58 | + eval_hash: str, |
| 59 | + message: str, |
| 60 | + eval_job: str, |
| 61 | + agent_job: str, |
| 62 | + run_id: int, |
| 63 | + now: Callable[[], datetime], |
| 64 | + emit: Callable[[bytes, str], None], |
| 65 | + new_emit_id: Callable[[], str], |
| 66 | +) -> str: |
| 67 | + """Serialize one state row as a gzipped single-line JSONEachRow and hand it to ``emit``. |
| 68 | +
|
| 69 | + Field order and values are the replicator contract; ``emit`` receives ``(gzip_bytes, key)`` |
| 70 | + where ``key`` is the bucket-relative object key. Returns that key for logging. |
| 71 | + """ |
| 72 | + version = now().replace(tzinfo=None).isoformat(sep=" ", timespec="milliseconds") |
| 73 | + # emit_id is a fresh per-emit UUID that uniquifies both storage keys: the ClickHouse sort key |
| 74 | + # (repo, pr_number, run_id, emit_id) so the ReplacingMergeTree never collapses a row, and the |
| 75 | + # S3 object key so two emits for the same (repo, pr_number) in the same millisecond do not |
| 76 | + # overwrite each other. It is storage-only and never read back. |
| 77 | + emit_id = new_emit_id() |
| 78 | + row = { |
| 79 | + "repo": repo, |
| 80 | + "pr_number": pr_number, |
| 81 | + "head_sha": head_sha, |
| 82 | + "status": status, |
| 83 | + "reason": reason, |
| 84 | + "eval_hash": eval_hash, |
| 85 | + "message": message, |
| 86 | + "eval_job": eval_job, |
| 87 | + "agent_job": agent_job, |
| 88 | + "version": version, |
| 89 | + "run_id": run_id, |
| 90 | + "emit_id": emit_id, |
| 91 | + } |
| 92 | + line = json.dumps(row, separators=(",", ":"), ensure_ascii=False) + "\n" |
| 93 | + key = object_key(repo, pr_number, version, emit_id) |
| 94 | + emit(gzip.compress(line.encode("utf-8"), mtime=0), key) |
| 95 | + return key |
| 96 | + |
| 97 | + |
| 98 | +def _s3_client() -> _S3Putter: |
| 99 | + import boto3 |
| 100 | + from botocore.config import Config |
| 101 | + |
| 102 | + # The emit runs on the scan's main thread; without explicit bounds a hung PUT would inherit |
| 103 | + # botocore's 60s connect/read defaults and stall dispatch of the remaining candidates, tripping |
| 104 | + # the iteration timeout. Cap both and bound retries so a slow S3 fails fast instead. |
| 105 | + config = Config(connect_timeout=5, read_timeout=5, retries={"max_attempts": 3, "mode": "standard"}) |
| 106 | + return cast("_S3Putter", boto3.client("s3", config=config)) |
| 107 | + |
| 108 | + |
| 109 | +def _default_upload(row_gzip: bytes, key: str) -> None: |
| 110 | + _s3_client().put_object(Bucket=S3_BUCKET, Key=key, Body=row_gzip) |
| 111 | + |
| 112 | + |
| 113 | +def emit_ai_review_dispatched( |
| 114 | + *, |
| 115 | + repo: str, |
| 116 | + pr_number: int, |
| 117 | + head_sha: str, |
| 118 | + eval_hash: str, |
| 119 | + run_id: int, |
| 120 | + upload: Callable[[bytes, str], None] | None = None, |
| 121 | +) -> None: |
| 122 | + """Emit an ``AI_REVIEW_DISPATCHED`` row the instant the scan fires the reviewer workflow. |
| 123 | +
|
| 124 | + ``run_id`` is supplied by the caller (the scan computes the next run id); reason/message and |
| 125 | + the job URLs are empty, matching the ``AI_REVIEW_STARTED`` marker. ``upload`` is an injectable |
| 126 | + ``(gzip_bytes, key)`` seam for tests; the default puts the object via boto3. |
| 127 | + """ |
| 128 | + emit_row( |
| 129 | + repo=repo, |
| 130 | + pr_number=pr_number, |
| 131 | + head_sha=head_sha, |
| 132 | + status=STATUS_AI_REVIEW_DISPATCHED, |
| 133 | + reason="", |
| 134 | + eval_hash=eval_hash, |
| 135 | + message="", |
| 136 | + eval_job="", |
| 137 | + agent_job="", |
| 138 | + run_id=run_id, |
| 139 | + now=_utcnow, |
| 140 | + emit=upload if upload is not None else _default_upload, |
| 141 | + new_emit_id=default_emit_id, |
| 142 | + ) |
0 commit comments