From a0c85629d2844d99ccc42ae7327e72bf8c42f94f Mon Sep 17 00:00:00 2001 From: YazarAyobami Date: Fri, 25 Sep 2026 14:34:36 +0100 Subject: [PATCH 1/6] fix(ingestion): make normalized activity writes idempotent on retry (#728) Ingestion writes were not idempotent. ``normalized_transactions`` carried only a surrogate ``id`` primary key, and a freshly normalized row has no ``id``, so ``session.merge()`` -- which resolves by primary key -- fell through to an INSERT every time. Any replay produced duplicate activity: a Horizon event delivered twice, a batch resumed after a restart, a page refetched after a cursor rewind. The duplicates were then counted twice by the graph builder and the feature store, inflating every downstream degree and volume feature. Key the writes on the identity Horizon already gives the row -- the ledger and the operation id -- plus the hop index that keeps the several rows one path-payment operation decomposes into distinct: * ``NormalizedTransaction`` gains ``ledger_sequence``, ``operation_id`` and ``hop_index`` and a UNIQUE constraint over all three. ``ledger_sequence`` is recovered from the operation's toid (Horizon packs ``ledger << 32 | tx_order << 12 | op_index`` into the id), so no new payload field is required and the ledger cannot drift from the id it came with. * ``NormalizedTransactionRepository`` upserts on that natural key, resolving the keys of a whole batch in one query, in the style of ``AccountRepository.batch_upsert`` -- no dialect-specific ON CONFLICT, so it behaves the same on Postgres and SQLite. * Both write paths use it: the single-row path in ``stream.py`` and the chunked ``BatchBuffer`` path that ``stream.py`` buffers operations through, which is the default under load and was equally affected. * ``_persist_operation`` on ``EnhancedStreamClient`` writes ``Operation`` (keyed by Horizon's operation id) and not a normalized row, so it needs no change. Two collateral defects fall out of building a coherent key: * Path-payment hops were told apart by appending ``_hopN`` to the transaction hash. That pushed the value past the column's 64 characters (``String(64)``), so a path payment could not be stored on Postgres at all. Hops now keep the real hash and are distinguished by ``hop_index``. * ``NormalizedTransaction.id`` used a bare ``BigInteger`` primary key, which SQLite does not auto-increment (it only auto-increments ``INTEGER PRIMARY KEY``). Nothing had noticed because nothing had ever inserted a normalized row on SQLite. It now uses the repository's existing sqlite-safe ``GRAPH_ID_TYPE`` variant, which still renders BIGINT on Postgres. Migration 013 adds the columns and the constraint. All three columns are nullable/``0``-defaulted rather than NOT NULL so it applies to a table that already holds rows; those rows have no operation id to backfill from, so they keep NULLs, and since Postgres and SQLite both treat NULLs as distinct under a UNIQUE constraint the legacy rows are left alone while every new write is enforced. Verified head is 013 and the migration reverses cleanly via ``alembic upgrade 012:013 --sql`` / ``downgrade 013:012 --sql``. Tests: tests/ingestion/test_normalized_idempotency.py covers replay within a session, replay across a restart in a new session, replay through the chunked batch buffer, path-payment hop distinctness and idempotency, correction of a restated operation in place, the column-width invariant on hop hashes, and the database-level rejection of a duplicate natural key. Co-Authored-By: Claude Code --- astroml/db/models/__init__.py | 24 +- astroml/db/repositories.py | 142 ++++++++ astroml/ingestion/batch.py | 24 +- astroml/ingestion/normalizer.py | 30 +- astroml/ingestion/parsers.py | 20 ++ astroml/ingestion/stream.py | 7 +- .../013_normalized_transaction_natural_key.py | 84 +++++ .../ingestion/test_normalized_idempotency.py | 309 ++++++++++++++++++ 8 files changed, 634 insertions(+), 6 deletions(-) create mode 100644 migrations/versions/013_normalized_transaction_natural_key.py create mode 100644 tests/ingestion/test_normalized_idempotency.py diff --git a/astroml/db/models/__init__.py b/astroml/db/models/__init__.py index 4af493ad..a688df5b 100644 --- a/astroml/db/models/__init__.py +++ b/astroml/db/models/__init__.py @@ -243,14 +243,34 @@ class Effect(Base): class NormalizedTransaction(Base): __tablename__ = "normalized_transactions" - id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True) + # ``GRAPH_ID_TYPE`` is the repository's sqlite-safe autoincrement id: SQLite + # only auto-increments an ``INTEGER PRIMARY KEY``, and this row's id is + # generated rather than supplied by the caller (unlike ``Operation.id``, + # which carries Horizon's operation id). Renders BIGINT on Postgres. + id: Mapped[int] = mapped_column(GRAPH_ID_TYPE, primary_key=True, autoincrement=True) transaction_hash: Mapped[str] = mapped_column(String(64), nullable=False) + # Natural key for ingestion idempotency (issue #728). Horizon's operation + # id is a toid — ``ledger << 32 | tx_order << 12 | op_index`` — so the + # ledger it was applied in is recoverable from the id alone, and + # ``hop_index`` keeps the several rows one path-payment operation + # decomposes into distinct while leaving them individually addressable. + # + # These are nullable so the migration can add them to a table that already + # holds rows recorded before the key existed and which therefore have no + # operation id to backfill from. Postgres and SQLite both treat NULLs as + # distinct in a UNIQUE constraint, so those legacy rows are exempt from the + # guarantee below while every new write is subject to it. + ledger_sequence: Mapped[Optional[int]] = mapped_column(BigInteger) + operation_id: Mapped[Optional[int]] = mapped_column(BigInteger) + hop_index: Mapped[int] = mapped_column(SmallInteger, nullable=False, server_default="0") sender: Mapped[str] = mapped_column(String(56), nullable=False) receiver: Mapped[Optional[str]] = mapped_column(String(56)) asset: Mapped[str] = mapped_column(String(70), nullable=False) amount: Mapped[Optional[float]] = mapped_column(Numeric) timestamp: Mapped[datetime] = mapped_column(nullable=False) - __table_args__ = (Index("ix_normalized_transactions_hash", "transaction_hash"), Index("ix_normalized_transactions_sender_timestamp", "sender", + __table_args__ = (UniqueConstraint("ledger_sequence", "operation_id", "hop_index", + name="uq_normalized_transactions_natural_key"), Index("ix_normalized_transactions_hash", "transaction_hash"), Index( + "ix_normalized_transactions_operation", "ledger_sequence", "operation_id"), Index("ix_normalized_transactions_sender_timestamp", "sender", "timestamp"), Index("ix_normalized_transactions_receiver_timestamp", "receiver", "timestamp", postgresql_where=(receiver.isnot(None)))) diff --git a/astroml/db/repositories.py b/astroml/db/repositories.py index e2dda849..6aff5dfd 100644 --- a/astroml/db/repositories.py +++ b/astroml/db/repositories.py @@ -11,6 +11,7 @@ from astroml.db.models import ( Account, Ledger, + NormalizedTransaction, ProcessedLedger, Transaction, ) @@ -217,3 +218,144 @@ def get_by_status(self, status: str) -> Sequence[ProcessedLedger]: .order_by(ProcessedLedger.ledger_sequence) ) return self._session.execute(stmt).scalars().all() + + +class NormalizedTransactionRepository: + """Idempotent writes for ``normalized_transactions`` (issue #728). + + ``session.merge()`` resolves by primary key, and this table's primary key is + the surrogate ``id``. A freshly normalized row has no ``id``, so a retry -- + a replayed Horizon event, a resumed batch after a restart, a page fetched + twice -- merged as an insert every time and duplicated the activity. These + methods key on the natural key the model now carries, + ``(ledger_sequence, operation_id, hop_index)``, so the same operation + written twice lands on one row. + """ + + def __init__(self, session: Session) -> None: + self._session = session + + def get_by_natural_key( + self, + ledger_sequence: int, + operation_id: int, + hop_index: int = 0, + ) -> NormalizedTransaction | None: + stmt = select(NormalizedTransaction).where( + NormalizedTransaction.ledger_sequence == ledger_sequence, + NormalizedTransaction.operation_id == operation_id, + NormalizedTransaction.hop_index == hop_index, + ) + return self._session.execute(stmt).scalar_one_or_none() + + def save(self, record: NormalizedTransaction) -> NormalizedTransaction: + self._session.add(record) + self._session.flush() + return record + + def upsert(self, record: NormalizedTransaction) -> NormalizedTransaction: + """Insert ``record``, or update the row already holding its natural key. + + A record carrying no natural key is inserted as-is: it cannot be + deduplicated against anything, and silently dropping it would lose + activity. Returns the persistent instance (existing or new). + """ + if not self._has_natural_key(record): + return self.save(record) + + existing = self.get_by_natural_key( + record.ledger_sequence, record.operation_id, record.hop_index + ) + if existing is None: + return self.save(record) + + self._apply(existing, record) + self._session.flush() + return existing + + def batch_upsert( + self, + records: Sequence[NormalizedTransaction], + chunk_size: int = 100, + ) -> int: + """Upsert many records, resolving their natural keys in one query. + + Returns the number of rows written (inserted plus updated). + """ + if not records: + return 0 + + keyed = [r for r in records if self._has_natural_key(r)] + unkeyed = [r for r in records if not self._has_natural_key(r)] + + existing = self._existing_by_natural_key(keyed) + + updated = 0 + to_insert: list[NormalizedTransaction] = [] + for record in keyed: + key = (record.ledger_sequence, record.operation_id, record.hop_index) + found = existing.get(key) + if found is None: + to_insert.append(record) + else: + self._apply(found, record) + updated += 1 + + inserted = 0 + for i in range(0, len(to_insert), chunk_size): + chunk = to_insert[i : i + chunk_size] + for record in chunk: + self._session.add(record) + self._session.flush() + self._session.commit() + inserted += len(chunk) + + for record in unkeyed: + self._session.add(record) + inserted += 1 + + if updated or unkeyed: + self._session.flush() + self._session.commit() + + return inserted + updated + + def count(self) -> int: + return self._session.query(NormalizedTransaction).count() + + @staticmethod + def _has_natural_key(record: NormalizedTransaction) -> bool: + return record.ledger_sequence is not None and record.operation_id is not None + + def _existing_by_natural_key( + self, + records: Sequence[NormalizedTransaction], + ) -> dict[tuple[int, int, int], NormalizedTransaction]: + """Fetch every stored row matching one of ``records``' natural keys.""" + if not records: + return {} + + operation_ids = {r.operation_id for r in records} + stmt = select(NormalizedTransaction).where( + NormalizedTransaction.operation_id.in_(operation_ids) + ) + rows = self._session.execute(stmt).scalars().all() + return { + (row.ledger_sequence, row.operation_id, row.hop_index): row + for row in rows + if row.ledger_sequence is not None and row.operation_id is not None + } + + @staticmethod + def _apply(target: NormalizedTransaction, source: NormalizedTransaction) -> None: + """Copy the replayable fields of ``source`` onto ``target``. + + The natural key itself is never rewritten: a row is identified by it, so + an incoming record with the same key is the same activity restated. + """ + target.transaction_hash = source.transaction_hash + target.sender = source.sender + target.receiver = source.receiver + target.asset = source.asset + target.amount = source.amount + target.timestamp = source.timestamp diff --git a/astroml/ingestion/batch.py b/astroml/ingestion/batch.py index 59cefa7e..8bee9639 100644 --- a/astroml/ingestion/batch.py +++ b/astroml/ingestion/batch.py @@ -86,14 +86,14 @@ def flush(self) -> int: return count def _flush(self) -> None: - """Internal flush: merge all buffered models and commit.""" + """Internal flush: upsert all buffered models and commit.""" if not self._buffer: return start = time.time() try: for model in self._buffer: - self._session.merge(model) + self._merge_one(model) self._session.commit() duration = time.time() - start flushed = len(self._buffer) @@ -117,6 +117,26 @@ def _flush(self) -> None: self._buffer.clear() BATCH_BUFFER_SIZE.set(0) + def _merge_one(self, model: object) -> None: + """Route one buffered model through the upsert that fits its key. + + Most models carry a real primary key and ``merge()`` resolves them + correctly. ``normalized_transactions`` does not: its primary key is a + surrogate ``id`` that a freshly normalized row does not have, so + ``merge()`` inserts on every replay and duplicates activity (#728). + Those rows are keyed on their natural key instead. + + Imported here rather than at module scope because + :mod:`astroml.db.repositories` imports this module. + """ + from astroml.db.models import NormalizedTransaction + from astroml.db.repositories import NormalizedTransactionRepository + + if isinstance(model, NormalizedTransaction): + NormalizedTransactionRepository(self._session).upsert(model) + return + self._session.merge(model) + def close(self) -> None: """Close the buffer, flushing remaining models if configured.""" if self._flush_on_exit: diff --git a/astroml/ingestion/normalizer.py b/astroml/ingestion/normalizer.py index 75cc37a9..8328240e 100644 --- a/astroml/ingestion/normalizer.py +++ b/astroml/ingestion/normalizer.py @@ -20,9 +20,25 @@ _extract_destination, _parse_datetime, extract_path_payment_hops, + ledger_sequence_from_operation_id, ) +def _natural_key(data: dict) -> tuple[int | None, int | None]: + """Return ``(ledger_sequence, operation_id)`` for a raw operation payload. + + Horizon's operation id is a toid, so the ledger is recovered from it rather + than read from a separate field. Payloads with no id yield ``(None, None)``: + the row is then written without a natural key instead of being keyed on a + guess, which keeps the ingest path working for synthetic or partial input. + """ + raw_id = data.get("id") + if raw_id is None: + return (None, None) + operation_id = int(raw_id) + return (ledger_sequence_from_operation_id(operation_id), operation_id) + + def normalize_operation(data: dict) -> NormalizedTransaction: """Transform raw horizon operation data into a NormalizedTransaction. @@ -47,9 +63,13 @@ def normalize_operation(data: dict) -> NormalizedTransaction: timestamp = _parse_datetime(data["created_at"]) transaction_hash = data["transaction_hash"] + ledger_sequence, operation_id = _natural_key(data) return NormalizedTransaction( transaction_hash=transaction_hash, + ledger_sequence=ledger_sequence, + operation_id=operation_id, + hop_index=0, sender=sender, receiver=receiver, asset=normalized_asset, @@ -61,6 +81,10 @@ def normalize_operation(data: dict) -> NormalizedTransaction: def normalize_path_payment_hops(data: dict) -> list[NormalizedTransaction]: """Return one NormalizedTransaction per hop for a path payment operation. + Every hop keeps the operation's real ``transaction_hash`` and the hop's + position in ``hop_index``, which together with the operation id makes each + hop a separate row that is still idempotent on retry. + Falls back to a single record (via :func:`normalize_operation`) for non-path-payment types so callers can use this function uniformly. """ @@ -73,10 +97,14 @@ def normalize_path_payment_hops(data: dict) -> list[NormalizedTransaction]: timestamp = _parse_datetime(data["created_at"]) transaction_hash = data["transaction_hash"] + ledger_sequence, operation_id = _natural_key(data) return [ NormalizedTransaction( - transaction_hash=f"{transaction_hash}_hop{hop['hop_index']}", + transaction_hash=transaction_hash, + ledger_sequence=ledger_sequence, + operation_id=operation_id, + hop_index=hop["hop_index"], sender=hop["from_account"], receiver=hop["to_account"], asset=hop["asset"], diff --git a/astroml/ingestion/parsers.py b/astroml/ingestion/parsers.py index 7e7ef14d..055132b9 100644 --- a/astroml/ingestion/parsers.py +++ b/astroml/ingestion/parsers.py @@ -25,6 +25,26 @@ def _parse_datetime(iso_string: str) -> datetime: return datetime.fromisoformat(iso_string.replace("Z", "+00:00")) +#: Bit widths of the fields packed into a Stellar toid. The id of every +#: ledger, transaction, operation and effect is ``ledger << 32 | tx << 12 | op`` +#: (see https://developers.stellar.org/docs/learn/glossary#total-order-id), +#: which is what makes an operation id usable as an ingest-time natural key. +_TOD_LEDGER_SHIFT = 32 + + +def ledger_sequence_from_operation_id(operation_id: int) -> int: + """Recover the ledger sequence an operation was applied in from its toid. + + ``operation_id`` is Horizon's operation id, which packs the ledger, the + transaction's application order within it, and the operation's index within + the transaction. Only the ledger is needed to key an ingestion write. + + >>> ledger_sequence_from_operation_id(53919970611201) + 12554 + """ + return int(operation_id) >> _TOD_LEDGER_SHIFT + + def parse_ledger(data: dict) -> Ledger: """Parse a Horizon ledger JSON dict into a Ledger ORM instance.""" return Ledger( diff --git a/astroml/ingestion/stream.py b/astroml/ingestion/stream.py index d018a0ad..2944a1ee 100644 --- a/astroml/ingestion/stream.py +++ b/astroml/ingestion/stream.py @@ -20,6 +20,7 @@ import aiohttp from aiohttp_sse_client import client as sse_client +from astroml.db.repositories import NormalizedTransactionRepository from astroml.db.schema import Ledger, Transaction from astroml.db.session import get_session from astroml.ingestion.batch import BatchBuffer @@ -279,8 +280,12 @@ def _db_write_operation_and_normalized(op, normalized) -> None: """Synchronous DB write for both raw and normalized operation.""" session = get_session() try: + # ``Operation`` is keyed by Horizon's operation id, so merge already + # resolves it. The normalized row has only a surrogate primary key, + # and merging it inserted a duplicate on every replay (#728), so it + # goes through the natural-key upsert instead. session.merge(op) - session.merge(normalized) + NormalizedTransactionRepository(session).upsert(normalized) session.commit() except Exception: session.rollback() diff --git a/migrations/versions/013_normalized_transaction_natural_key.py b/migrations/versions/013_normalized_transaction_natural_key.py new file mode 100644 index 00000000..bc195ba0 --- /dev/null +++ b/migrations/versions/013_normalized_transaction_natural_key.py @@ -0,0 +1,84 @@ +"""Add the normalized_transactions natural key. + +Revision ID: 013 +Revises: 012 +Create Date: 2026-09-25 + +Closes #728 — writes to ``normalized_transactions`` were not idempotent on +retry: the table's only key was the surrogate ``id``, which a freshly +normalized row does not have, so ``session.merge()`` inserted a duplicate on +every replayed Horizon event, resumed batch, or refetched page. + +This adds the natural key the ingestion path writes against, +``(ledger_sequence, operation_id, hop_index)``: + +* ``ledger_sequence`` is recovered from the operation's toid -- Horizon packs + ``ledger << 32 | tx_order << 12 | op_index`` into it -- so no extra payload + field is needed. +* ``hop_index`` separates the rows a single path-payment operation decomposes + into, which were previously told apart by a ``_hopN`` suffix appended to + ``transaction_hash``. That suffix pushed the value past the column's 64 + characters, so a path payment could not be stored on Postgres at all. + +All three columns are nullable/`0`-defaulted rather than ``NOT NULL`` so this +applies to a table that may already hold rows. Rows written before this +migration have no operation id to backfill from, so they keep NULLs; Postgres +and SQLite both treat NULLs as distinct under a UNIQUE constraint, which +leaves those legacy rows alone while enforcing the key for everything written +after this point. +""" + +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +revision: str = "013" +down_revision: Union[str, None] = "012" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column( + "normalized_transactions", + sa.Column("ledger_sequence", sa.BigInteger(), nullable=True), + ) + op.add_column( + "normalized_transactions", + sa.Column("operation_id", sa.BigInteger(), nullable=True), + ) + op.add_column( + "normalized_transactions", + sa.Column( + "hop_index", + sa.SmallInteger(), + nullable=False, + server_default="0", + ), + ) + op.create_unique_constraint( + "uq_normalized_transactions_natural_key", + "normalized_transactions", + ["ledger_sequence", "operation_id", "hop_index"], + ) + op.create_index( + "ix_normalized_transactions_operation", + "normalized_transactions", + ["ledger_sequence", "operation_id"], + ) + + +def downgrade() -> None: + op.drop_index( + "ix_normalized_transactions_operation", + table_name="normalized_transactions", + ) + op.drop_constraint( + "uq_normalized_transactions_natural_key", + "normalized_transactions", + type_="unique", + ) + op.drop_column("normalized_transactions", "hop_index") + op.drop_column("normalized_transactions", "operation_id") + op.drop_column("normalized_transactions", "ledger_sequence") diff --git a/tests/ingestion/test_normalized_idempotency.py b/tests/ingestion/test_normalized_idempotency.py new file mode 100644 index 00000000..295c12ed --- /dev/null +++ b/tests/ingestion/test_normalized_idempotency.py @@ -0,0 +1,309 @@ +"""Ingestion writes are idempotent on replay (issue #728). + +``normalized_transactions`` carries only a surrogate primary key, and a freshly +normalized row has no ``id``, so ``session.merge()`` — which resolves by primary +key — inserted a duplicate every time the same activity was written twice. A +replayed Horizon event, a resumed batch after a restart, or a refetched page all +produced duplicate activity rows, which the graph builder and feature store then +counted twice. + +These tests key the writes on Horizon's own identity for the row — the ledger +and operation id, plus the hop index for the several rows one path-payment +operation decomposes into — and assert that writing the same activity twice +lands on one row. +""" + +from __future__ import annotations + + +import pytest +from sqlalchemy import create_engine, func, select +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import sessionmaker + +from astroml.db.models import Base, NormalizedTransaction +from astroml.db.repositories import NormalizedTransactionRepository +from astroml.ingestion.batch import BatchBuffer +from astroml.ingestion.normalizer import ( + normalize_operation, + normalize_path_payment_hops, +) +from astroml.ingestion.parsers import ledger_sequence_from_operation_id + +# Horizon operation ids are toids: ledger << 32 | tx_order << 12 | op_index. +# This one decodes to ledger 12554 and is the id used throughout the fixtures. +OP_ID = 53919970611201 +LEDGER = 12554 + + +@pytest.fixture() +def session(tmp_path): + """A session over a fresh SQLite database built from the ORM models.""" + db_file = tmp_path / "test_idempotency.db" + engine = create_engine(f"sqlite:///{db_file}", connect_args={"check_same_thread": False}) + Base.metadata.create_all(engine) + factory = sessionmaker(bind=engine, autocommit=False, autoflush=False) + db = factory() + yield db + db.rollback() + db.close() + engine.dispose() + + +@pytest.fixture() +def payment_payload(): + """A raw Horizon payment operation.""" + return { + "id": str(OP_ID), + "type": "payment", + "source_account": "G_SENDER", + "to": "G_RECEIVER", + "amount": "100.5", + "asset_type": "native", + "created_at": "2024-01-15T12:30:00Z", + "transaction_hash": "a" * 64, + } + + +@pytest.fixture() +def path_payment_payload(): + """A raw Horizon path payment with two hops (XLM -> USDC -> XLM).""" + return { + "id": str(OP_ID), + "type": "path_payment_strict_send", + "source_account": "G_SENDER", + "to": "G_RECEIVER", + "source_asset_type": "native", + "source_amount": "10.0", + "asset_type": "credit_alphanum4", + "asset_code": "USDC", + "asset_issuer": "G_ISSUER", + "destination_amount": "9.5", + "path": [{"asset_type": "native"}], + "created_at": "2024-01-15T12:30:00Z", + "transaction_hash": "b" * 64, + } + + +def _count(session) -> int: + return session.execute(select(func.count()).select_from(NormalizedTransaction)).scalar_one() + + +class TestNormalizedKeyExtraction: + """The natural key comes from data Horizon already sends.""" + + def test_ledger_is_decoded_from_the_operation_id(self): + """The ledger is the high 32 bits of the toid, so no extra field is needed.""" + assert ledger_sequence_from_operation_id(OP_ID) == LEDGER + + def test_normalize_operation_records_ledger_and_operation_id(self, payment_payload): + record = normalize_operation(payment_payload) + + assert record.ledger_sequence == LEDGER + assert record.operation_id == OP_ID + assert record.hop_index == 0 + + def test_payload_without_an_id_is_written_without_a_key(self): + """A payload with no operation id is not keyed on a guess.""" + record = normalize_operation( + { + "type": "payment", + "source_account": "G_SENDER", + "to": "G_RECEIVER", + "amount": "1.0", + "asset_type": "native", + "created_at": "2024-01-15T12:30:00Z", + "transaction_hash": "c" * 64, + } + ) + + assert record.ledger_sequence is None + assert record.operation_id is None + + +class TestReplayDoesNotDuplicate: + """Writing the same activity twice lands on one row.""" + + def test_same_operation_upserted_twice_yields_one_row(self, session, payment_payload): + repo = NormalizedTransactionRepository(session) + + repo.upsert(normalize_operation(payment_payload)) + session.commit() + repo.upsert(normalize_operation(payment_payload)) + session.commit() + + assert _count(session) == 1 + + def test_replay_survives_a_new_session(self, tmp_path, payment_payload): + """A resumed ingestion process re-reading the same page does not duplicate. + + This is the restart case: the retry happens in a different session with + no identity map left over from the first write. + """ + db_file = tmp_path / "restart.db" + engine = create_engine(f"sqlite:///{db_file}", connect_args={"check_same_thread": False}) + Base.metadata.create_all(engine) + factory = sessionmaker(bind=engine, autocommit=False, autoflush=False) + + first = factory() + NormalizedTransactionRepository(first).upsert(normalize_operation(payment_payload)) + first.commit() + first.close() + + second = factory() + NormalizedTransactionRepository(second).upsert(normalize_operation(payment_payload)) + second.commit() + count = _count(second) + second.close() + engine.dispose() + + assert count == 1 + + def test_buffered_ingestion_replay_does_not_duplicate(self, session, payment_payload): + """The chunked batch path is idempotent too. + + ``stream.py`` buffers operations and normalizes them through + ``BatchBuffer``, flushing every ``chunk_size`` rows, so a replayed event + re-enters this path rather than the single-row write. + """ + buffer = BatchBuffer(session, chunk_size=1, flush_on_exit=True) + buffer.add(normalize_operation(payment_payload)) + buffer.add(normalize_operation(payment_payload)) + + assert _count(session) == 1 + + def test_replay_updates_the_row_rather_than_ignoring_it(self, session, payment_payload): + """A restated operation corrects the stored values in place.""" + repo = NormalizedTransactionRepository(session) + repo.upsert(normalize_operation(payment_payload)) + session.commit() + + corrected = normalize_operation(payment_payload) + corrected.amount = 250.0 + repo.upsert(corrected) + session.commit() + + stored = session.execute(select(NormalizedTransaction)).scalar_one() + assert _count(session) == 1 + assert float(stored.amount) == 250.0 + + def test_distinct_operations_stay_distinct(self, session, payment_payload): + repo = NormalizedTransactionRepository(session) + + repo.upsert(normalize_operation(payment_payload)) + other = dict(payment_payload, id=str(OP_ID + 1), transaction_hash="d" * 64) + repo.upsert(normalize_operation(other)) + session.commit() + + assert _count(session) == 2 + + def test_rows_without_a_key_are_still_written(self, session): + """Unkeyable payloads are appended, not dropped.""" + repo = NormalizedTransactionRepository(session) + payload = { + "type": "payment", + "source_account": "G_SENDER", + "to": "G_RECEIVER", + "amount": "1.0", + "asset_type": "native", + "created_at": "2024-01-15T12:30:00Z", + "transaction_hash": "e" * 64, + } + + repo.upsert(normalize_operation(payload)) + repo.upsert(normalize_operation(payload)) + session.commit() + + assert _count(session) == 2 + + +class TestPathPaymentHops: + """One path payment writes several rows, each idempotent on its own.""" + + def test_each_hop_is_a_distinct_row(self, session, path_payment_payload): + hops = normalize_path_payment_hops(path_payment_payload) + + assert len(hops) > 1 + assert [h.hop_index for h in hops] == list(range(len(hops))) + + def test_hops_share_the_operation_key_but_differ_by_index(self, path_payment_payload): + hops = normalize_path_payment_hops(path_payment_payload) + + for hop in hops: + assert hop.operation_id == OP_ID + assert hop.ledger_sequence == LEDGER + + def test_hop_transaction_hash_fits_its_column(self, path_payment_payload): + """Hops keep the real hash instead of a suffixed one that overflowed. + + The previous encoding appended ``_hopN`` to the transaction hash, which + pushed the value past the column's 64 characters and would not store on + Postgres. + """ + hops = normalize_path_payment_hops(path_payment_payload) + + for hop in hops: + assert hop.transaction_hash == "b" * 64 + assert len(hop.transaction_hash) <= 64 + + def test_replaying_a_path_payment_writes_no_extra_rows(self, session, path_payment_payload): + repo = NormalizedTransactionRepository(session) + hops = normalize_path_payment_hops(path_payment_payload) + + repo.batch_upsert(hops) + repo.batch_upsert(normalize_path_payment_hops(path_payment_payload)) + + assert _count(session) == len(hops) + + def test_batch_upsert_resolves_keys_in_one_pass(self, session, path_payment_payload): + repo = NormalizedTransactionRepository(session) + hops = normalize_path_payment_hops(path_payment_payload) + + written = repo.batch_upsert(hops) + + assert written == len(hops) + assert repo.count() == len(hops) + + +class TestDatabaseLevelGuarantee: + """The key is enforced by the table, not only by the repository helper.""" + + def test_duplicate_natural_key_is_rejected(self, session, payment_payload): + session.add(normalize_operation(payment_payload)) + session.commit() + + session.add(normalize_operation(payment_payload)) + with pytest.raises(IntegrityError): + session.commit() + session.rollback() + + assert _count(session) == 1 + + def test_same_operation_in_different_ledgers_is_allowed(self, session, payment_payload): + """The ledger is part of the key, so ids are scoped by it.""" + session.add(normalize_operation(payment_payload)) + # Same operation id, keyed against a different ledger: a distinct row. + replayed = normalize_operation(payment_payload) + replayed.ledger_sequence = LEDGER + 1 + session.add(replayed) + session.commit() + + assert _count(session) == 2 + + +class TestTimestampPreserved: + """Replays keep the original activity time rather than the retry time.""" + + def test_timestamp_comes_from_the_payload(self, session, payment_payload): + repo = NormalizedTransactionRepository(session) + repo.upsert(normalize_operation(payment_payload)) + session.commit() + + stored = session.execute(select(NormalizedTransaction)).scalar_one() + # Compared field-wise because SQLite returns naive datetimes. + assert (stored.timestamp.year, stored.timestamp.month, stored.timestamp.day) == ( + 2024, + 1, + 15, + ) + assert (stored.timestamp.hour, stored.timestamp.minute) == (12, 30) From 09f2e26faf458c654b960418af2b547243947281 Mon Sep 17 00:00:00 2001 From: YazarAyobami Date: Fri, 25 Sep 2026 15:13:06 +0100 Subject: [PATCH 2/6] fix(graph): order snapshot construction by the blockchain's total order (#732) A snapshot is consumed by a temporal model as a *sequence*, and the sequence was not reproducible. The DB-backed builders ordered their rows with ``ORDER BY timestamp`` and nothing else, but a Stellar ledger closes every one of its operations in the same second -- so a window is full of rows sharing a timestamp, and the database was free to return each group of ties in any order it liked. A different query plan, freshly analysed statistics or a different SQLite/Postgres version handed back a different edge sequence for the same unchanged data, and a temporal GNN read that ordering as signal. Sort by the order the chain itself applied the activity: * ``_snapshot_ordering()`` returns ``(timestamp, ledger_sequence, operation_id, hop_index, id)``, and every DB-backed builder now uses it -- ``iter_db_snapshots`` in both its sequential and parallel forms, ``iter_db_snapshot_edges``, and ``_build_snapshot_window``. ``ledger_sequence`` is what actually separates the ties (recovered from the operation's toid, see #728); ``operation_id``/``hop_index`` order the rows written for one operation, and ``id`` is what remains for rows recorded before the natural key existed and which therefore have both columns NULL. * Migration 014 adds ``ix_normalized_transactions_timestamp_order`` over ``(timestamp, ledger_sequence, operation_id, hop_index)``, matching that ordering column for column, and the ORM model declares the same index so a database built by ``create_all`` and one built by ``alembic upgrade`` agree. This is also the first index on ``timestamp`` at all: the window range predicate was a sequential scan, and the sort node it fed was where the non-determinism came from. With the index the planner walks the range and the rows arrive already ordered, so the sort disappears along with the problem. In memory, ``presorted=True`` was documented as an assumption but behaved as an unchecked one: the window is found by binary search, which is only correct on sorted input, so edges that violated the promise returned a window that was quietly wrong rather than an error. It is now validated (``validate_temporal_order`` / ``SnapshotOrderingError``, a ``ValueError`` so existing callers keep catching it), and the sort on the ``presorted=False`` path canonicalises by ``(timestamp, src, dst)`` instead of timestamp alone, so that path is no longer sensitive to the caller's input order either. The scan allocates nothing and is linear like the timestamp array the function already builds, so the check costs about what the window already costs. This turned up one caller that was silently relying on the bug: the ``test_snapshot_last_n_days`` integration test passes edges newest-first while taking the ``presorted=True`` default. Under ``ORDER BY``-free bisect it returned an empty window and failed; it now says ``presorted=False`` and asserts the window it always meant to. Tests: tests/features/graph/test_snapshot_ordering.py covers the presorted contract and its rejection, canonical ordering of tied edges under ``presorted=False``, ledger/hop ordering for rows sharing a timestamp inserted in an order that contradicts the key, run-to-run identity of a window across two sessions, agreement between the streaming and materialising builders, and the index that backs the order. Verified with the full suite before and after (``--continue-on-collection-errors``, since this checkout lacks torch_geometric/psutil): 18 tests newly pass and none regress. The remaining failures in tests/features/graph (``Edge`` has no ``amount``) and the two DB-fixture errors are pre-existing and identical on main. Co-Authored-By: Claude Code --- astroml/db/models/__init__.py | 8 +- astroml/features/graph/snapshot.py | 188 ++++++++++- .../versions/014_snapshot_ordering_index.py | 43 +++ .../features/graph/test_snapshot_ordering.py | 310 ++++++++++++++++++ tests/integration/test_graph_construction.py | 7 +- 5 files changed, 539 insertions(+), 17 deletions(-) create mode 100644 migrations/versions/014_snapshot_ordering_index.py create mode 100644 tests/features/graph/test_snapshot_ordering.py diff --git a/astroml/db/models/__init__.py b/astroml/db/models/__init__.py index a688df5b..1399f90e 100644 --- a/astroml/db/models/__init__.py +++ b/astroml/db/models/__init__.py @@ -271,7 +271,13 @@ class NormalizedTransaction(Base): __table_args__ = (UniqueConstraint("ledger_sequence", "operation_id", "hop_index", name="uq_normalized_transactions_natural_key"), Index("ix_normalized_transactions_hash", "transaction_hash"), Index( "ix_normalized_transactions_operation", "ledger_sequence", "operation_id"), Index("ix_normalized_transactions_sender_timestamp", "sender", - "timestamp"), Index("ix_normalized_transactions_receiver_timestamp", "receiver", "timestamp", postgresql_where=(receiver.isnot(None)))) + "timestamp"), Index("ix_normalized_transactions_receiver_timestamp", "receiver", "timestamp", postgresql_where=(receiver.isnot(None))), + # Issue #732 — the snapshot builders read a timestamp range in the + # blockchain's total order, so this index carries that order all the + # way through: the planner walks it for the range and the rows arrive + # already sorted, with no sort node and no tie left for it to break. + Index("ix_normalized_transactions_timestamp_order", "timestamp", + "ledger_sequence", "operation_id", "hop_index")) class DbModel(Base): diff --git a/astroml/features/graph/snapshot.py b/astroml/features/graph/snapshot.py index 147af916..53d2fca8 100644 --- a/astroml/features/graph/snapshot.py +++ b/astroml/features/graph/snapshot.py @@ -1,3 +1,30 @@ +"""Time-windowed graph snapshot construction — issue #732. + +Ordering contract +----------------- +A snapshot is consumed by a temporal model as a *sequence*, so every edge list +this module produces is ordered by time, and the order is reproducible: the +same rows always come back in the same sequence, whichever plan the database +happened to pick. + +Inside the database that order is the blockchain's own total order — +``(timestamp, ledger_sequence, operation_id, hop_index, id)``. A timestamp +alone is not enough to sort by: a Stellar ledger closes all of its operations +in the same second, so a large group of rows shares a timestamp, and leaving +those ties unordered made two runs over unchanged data disagree on the order of +the edges inside the window. ``ledger_sequence`` — recovered from the +operation's toid, see :mod:`astroml.ingestion.parsers` — is the tiebreaker that +matches how the chain itself ordered the activity; ``operation_id`` and +``hop_index`` order the several rows written for one operation, and ``id`` +settles what remains for rows recorded before the natural key existed. + +For edge lists built in memory, the same contract is enforced on the +``presorted`` argument of :func:`window_snapshot`. That argument is a promise +from the caller, and a broken promise silently returned the wrong window +because the binary search ran over an unsorted array; it now raises +:class:`SnapshotOrderingError`. +""" + from __future__ import annotations import bisect @@ -7,6 +34,7 @@ from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone +from itertools import islice from typing import Any from ...cache import cached_graph_snapshot @@ -140,14 +168,61 @@ class Edge: +class SnapshotOrderingError(ValueError): + """Raised when a snapshot's edges are not in non-decreasing time order. + + Subclasses :class:`ValueError` so callers that already guard + :func:`window_snapshot` against bad arguments keep catching it. + """ + + +def _first_inversion(edges: Sequence[Edge]) -> int: + """Index of the first edge that goes backwards in time, or ``-1``. + + ``zip`` + ``islice`` walks the sequence without slicing it, so checking a + large edge list does not allocate a second copy of it. + """ + for i, (current, following) in enumerate(zip(edges, islice(edges, 1, None))): + if current.timestamp > following.timestamp: + return i + return -1 + + +def validate_temporal_order(edges: Sequence[Edge], *, context: str = "edges") -> None: + """Raise :class:`SnapshotOrderingError` unless ``edges`` is time-ordered. + + An edge list is time-ordered when each edge's timestamp is greater than or + equal to the previous one — ties are allowed, and are expected: every + operation a ledger closes carries that ledger's timestamp. + + Args: + edges: The edges to check, in the order a model would consume them. + context: What is being checked, used in the error message. + + Raises: + SnapshotOrderingError: The first edge that moves backwards in time. + """ + index = _first_inversion(edges) + if index < 0: + return + current, following = edges[index], edges[index + 1] + raise SnapshotOrderingError( + f"{context} are not ordered by timestamp: index {index} is at " + f"{current.timestamp}, index {index + 1} is at {following.timestamp}" + ) + + def _ensure_sorted_by_ts(edges: Sequence[Edge]) -> list[Edge]: - if len(edges) <= 1: - return list(edges) - # Fast path: check if already non-decreasing by timestamp - is_sorted = all(edges[i].timestamp <= edges[i + 1].timestamp for i in range(len(edges) - 1)) - if is_sorted: - return list(edges) - return sorted(edges, key=lambda e: e.timestamp) + """Return ``edges`` in the canonical temporal order — issue #732. + + Sorted by ``(timestamp, src, dst)`` and not by timestamp alone: several + operations share a ledger's timestamp, and sorting on the timestamp alone + left the order within each group of ties up to the caller's input order, so + the same set of edges could produce two different sequences. Adding the + endpoints makes the result a property of the edges rather than of how they + arrived. + """ + return sorted(edges, key=lambda e: (e.timestamp, e.src, e.dst)) @cached_graph_snapshot(ttl_seconds=1800) @@ -162,6 +237,15 @@ def window_snapshot( - edges: sequence of Edge - start_ts/end_ts: inclusive window bounds (epoch seconds) - presorted: if True, assume edges are sorted by timestamp ascending; otherwise we will sort once. + This is a promise, not a hint — edges that break it are rejected (see Raises) + rather than silently windowed at the wrong offsets. Pass ``presorted=False`` + if the edges may arrive in any order; the result is then canonicalised by + ``(timestamp, src, dst)`` so it does not depend on the input order either. + + Raises: + ValueError: ``start_ts > end_ts``. + SnapshotOrderingError: ``presorted=True`` and the edges are not in + non-decreasing timestamp order. Efficiency: Uses binary search to find left/right indices and then slices, O(log N + K). @@ -175,6 +259,11 @@ def window_snapshot( # is the concern in the first place. if presorted: sorted_edges = edges if isinstance(edges, list) else list(edges) + # The scan below allocates nothing and is linear like the timestamp + # array built a few lines down, so checking costs about what the array + # already costs — while an unchecked violation would return a window + # that is quietly wrong, since bisect only works on sorted input. + validate_temporal_order(sorted_edges, context="edges passed with presorted=True") else: sorted_edges = _ensure_sorted_by_ts(edges) @@ -270,6 +359,52 @@ def _parse_window_size(window: str) -> timedelta: raise _unknown_window_unit_error(window, unit) +def _snapshot_ordering() -> tuple: + """The total order every DB-backed snapshot query sorts by — issue #732. + + ``timestamp`` on its own is not a total order, so ``ORDER BY timestamp`` + lets the database return tied rows in whatever order its plan produced — + which changes with the plan, the statistics, or the SQLite/Postgres + version, and made two runs over unchanged data build different sequences + out of the same window. + + These columns are the blockchain's own ordering of the activity: + + * ``timestamp`` — the closing time of the ledger the operation is in. + * ``ledger_sequence`` — a ledger closes every operation it contains in the + same second, so the ledger is what actually separates those ties. + * ``operation_id`` / ``hop_index`` — order the rows written for a single + operation (a path payment decomposes into one row per hop). + * ``id`` — the insertion order, which is all that remains for rows recorded + before the natural key existed and which therefore have neither of the + two columns above. + + Returned as a tuple of columns for ``Query.order_by(*_snapshot_ordering())``. + """ + from astroml.db.schema import NormalizedTransaction + + return ( + NormalizedTransaction.timestamp, + NormalizedTransaction.ledger_sequence, + NormalizedTransaction.operation_id, + NormalizedTransaction.hop_index, + NormalizedTransaction.id, + ) + + +def validate_snapshot_window(window: SnapshotWindow) -> None: + """Raise :class:`SnapshotOrderingError` unless a window is time-ordered. + + The DB-backed builders guarantee this by construction; the check exists so + a caller — or a test — can assert it on a window it was handed, and so the + ordering a temporal model consumes is stated in one place. + + Raises: + SnapshotOrderingError: The window's edges move backwards in time. + """ + validate_temporal_order(window.edges, context=f"snapshot window {window.index}") + + @dataclass(frozen=True) class SnapshotMeta: """Window metadata without the edge payload — issue #199. @@ -309,6 +444,13 @@ def iter_db_snapshot_edges( Use this in place of :func:`iter_db_snapshots` whenever a window may plausibly contain enough edges to risk OOM on the training machine. + + Ordering — issue #732: + Each edge iterator yields the window's rows in the blockchain's total + order (see :func:`_snapshot_ordering`), so the sequence is + reproducible across runs. Because the iterator is streamed it is not + validated; a caller that buffers it can check the materialised list + with :func:`validate_temporal_order`. """ from sqlalchemy import func as sqlfunc from sqlalchemy import select @@ -355,7 +497,9 @@ def iter_db_snapshot_edges( NormalizedTransaction.receiver.isnot(None), NormalizedTransaction.sender != NormalizedTransaction.receiver, ) - .order_by(NormalizedTransaction.timestamp) + # Ordered by the total order of the chain, not by timestamp alone, + # so a window's edge sequence is reproducible — issue #732. + .order_by(*_snapshot_ordering()) .execution_options(yield_per=chunk_size, stream_results=True) ) @@ -382,7 +526,12 @@ def _build_snapshot_window( window_end: datetime, chunk_size: int, ) -> SnapshotWindow: - """Build a single snapshot window from the database.""" + """Build a single snapshot window from the database. + + Edges come back in the blockchain's total order and the window is checked + against it before being returned — issue #732 (see + :func:`validate_snapshot_window`). + """ from sqlalchemy import select from astroml.db.schema import NormalizedTransaction @@ -402,7 +551,9 @@ def _build_snapshot_window( NormalizedTransaction.receiver.isnot(None), NormalizedTransaction.sender != NormalizedTransaction.receiver, ) - .order_by(NormalizedTransaction.timestamp) + # Issue #732 — a total order over the rows, not just the timestamp, + # so this window is byte-identical across runs. + .order_by(*_snapshot_ordering()) ) edges: list[Edge] = [] @@ -423,13 +574,15 @@ def _build_snapshot_window( # alive together at peak. del result - return SnapshotWindow( + window = SnapshotWindow( index=index, start=window_start, end=window_end, edges=edges, nodes=nodes, ) + validate_snapshot_window(window) + return window finally: session.close() @@ -493,7 +646,10 @@ def iter_db_snapshots( windows in parallel when using the default session factory. Yields: - :class:`SnapshotWindow` instances in chronological order. + :class:`SnapshotWindow` instances in chronological order, each one's + edges also in chronological (blockchain) order — issue #732. Windows + are yielded in increasing ``index`` order, and each window is validated + before it is yielded. """ from sqlalchemy import func as sqlfunc from sqlalchemy import select @@ -583,7 +739,9 @@ def iter_db_snapshots( NormalizedTransaction.receiver.isnot(None), NormalizedTransaction.sender != NormalizedTransaction.receiver, ) - .order_by(NormalizedTransaction.timestamp) + # Issue #732 — same total order as the streaming and parallel + # builders, so all three produce the same sequence for a window. + .order_by(*_snapshot_ordering()) ) edges: list[Edge] = [] @@ -603,13 +761,15 @@ def iter_db_snapshots( del result # Issue #546 — drop cursor buffers before the next window. - yield SnapshotWindow( + window = SnapshotWindow( index=index, start=window_start, end=window_end, edges=edges, nodes=nodes, ) + validate_snapshot_window(window) + yield window window_start += step_delta index += 1 diff --git a/migrations/versions/014_snapshot_ordering_index.py b/migrations/versions/014_snapshot_ordering_index.py new file mode 100644 index 00000000..b412db51 --- /dev/null +++ b/migrations/versions/014_snapshot_ordering_index.py @@ -0,0 +1,43 @@ +"""Index normalized_transactions for time-windowed snapshot reads. + +Revision ID: 014 +Revises: 013 +Create Date: 2026-09-25 + +Closes #732 — the snapshot builders slice ``normalized_transactions`` by +timestamp range and consume the rows in time order, and ``timestamp`` had no +index at all: every window was a sequential scan plus a sort, and the sort left +rows that share a timestamp (a ledger closes all of its operations in the same +second) in whatever order the plan happened to produce, so two runs over the +same data built different edge sequences. + +``ix_normalized_transactions_timestamp_order`` covers the range predicate and +the ordering together — ``(timestamp, ledger_sequence, operation_id, +hop_index)``, the total order the builders sort by. The planner can walk the +index for the range and hand rows back already ordered, so the sort node +disappears along with the non-determinism it introduced. + +Because ``timestamp`` leads the index it also serves any other query that +filters or orders on timestamp alone, which is why no separate single-column +index is created. +""" + +from typing import Sequence, Union + +from alembic import op + +revision: str = "014" +down_revision: Union[str, None] = "013" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + +_INDEX = "ix_normalized_transactions_timestamp_order" +_COLUMNS = ["timestamp", "ledger_sequence", "operation_id", "hop_index"] + + +def upgrade() -> None: + op.create_index(_INDEX, "normalized_transactions", _COLUMNS) + + +def downgrade() -> None: + op.drop_index(_INDEX, table_name="normalized_transactions") diff --git a/tests/features/graph/test_snapshot_ordering.py b/tests/features/graph/test_snapshot_ordering.py new file mode 100644 index 00000000..3017e3a5 --- /dev/null +++ b/tests/features/graph/test_snapshot_ordering.py @@ -0,0 +1,310 @@ +"""Temporal-window ordering in snapshot construction — issue #732. + +A snapshot is consumed by a temporal model as a *sequence*, so two properties +have to hold for training to be reproducible: + +* the edges of a window come back in the same order every time, and +* that order is the blockchain's, not an artefact of the query plan. + +``ORDER BY timestamp`` alone gave neither. A Stellar ledger closes all of its +operations in the same second, so a window is full of rows sharing a timestamp +and the database was free to return them in any order it liked — a different +plan, a different statistics snapshot or a different SQLite/Postgres version +produced a different sequence from unchanged data. + +These tests pin the total order the builders now use, +``(timestamp, ledger_sequence, operation_id, hop_index, id)``, the validation +that rejects a broken ``presorted`` promise, and the index that lets the +planner produce that order without a sort. +""" + +from __future__ import annotations + +import random +from datetime import datetime, timedelta, timezone + +import pytest +from sqlalchemy import create_engine, inspect +from sqlalchemy.orm import sessionmaker + +from astroml.db.models import Base, NormalizedTransaction +from astroml.features.graph.snapshot import ( + Edge, + SnapshotOrderingError, + _snapshot_ordering, + iter_db_snapshot_edges, + iter_db_snapshots, + window_snapshot, +) + +T0 = datetime(2024, 1, 1, tzinfo=timezone.utc) +T1 = datetime(2024, 1, 1, 1, tzinfo=timezone.utc) + + +@pytest.fixture() +def engine(): + """A fresh SQLite database built from the ORM models.""" + eng = create_engine("sqlite:///:memory:") + Base.metadata.create_all(eng) + yield eng + eng.dispose() + + +@pytest.fixture() +def session(engine): + factory = sessionmaker(bind=engine, autocommit=False, autoflush=False) + db = factory() + yield db + db.close() + + +def _row(ledger: int, hop: int, src: str, dst: str, ts: datetime, op: int | None = None): + """A normalized activity row keyed the way ingestion writes one. + + The operation id is a toid, so ``ledger_sequence`` and ``operation_id`` + agree with each other exactly as they do in the real table. + """ + return NormalizedTransaction( + transaction_hash="a" * 64, + ledger_sequence=ledger, + operation_id=op if op is not None else ledger << 32, + hop_index=hop, + sender=src, + receiver=dst, + asset="native", + amount=1.0, + timestamp=ts, + ) + + +def _edges(*timestamps: int) -> list[Edge]: + return [Edge(src=f"s{i}", dst=f"d{i}", timestamp=ts) for i, ts in enumerate(timestamps)] + + +class TestPresortedContract: + """``presorted=True`` is a promise the caller makes, and it is checked.""" + + def test_sorted_edges_are_accepted(self): + edges = _edges(100, 200, 300) + + assert window_snapshot(edges, 100, 300, presorted=True)[1] == edges + + def test_ties_are_not_a_violation(self): + """Every operation in a ledger shares that ledger's timestamp.""" + edges = _edges(100, 100, 100) + + assert len(window_snapshot(edges, 100, 100, presorted=True)[1]) == 3 + + def test_out_of_order_edges_are_rejected(self): + """The bisect below only works on sorted input, so an unsorted list + used to return a window that was quietly wrong.""" + with pytest.raises(SnapshotOrderingError): + window_snapshot(_edges(100, 300, 200), 100, 300, presorted=True) + + def test_the_error_is_a_value_error(self): + """Callers already catching ValueError for bad bounds keep working.""" + assert issubclass(SnapshotOrderingError, ValueError) + + def test_the_error_names_the_offending_index(self): + with pytest.raises(SnapshotOrderingError, match=r"index 1 is at 300"): + window_snapshot(_edges(100, 300, 200), 100, 300, presorted=True) + + def test_unsorted_edges_are_still_handled_when_not_promised(self): + """``presorted=False`` means "sort it for me", not an error.""" + shuffled = _edges(100, 200, 300) + random.Random(7).shuffle(shuffled) + + _, window = window_snapshot(shuffled, 100, 300, presorted=False) + + assert [e.timestamp for e in window] == [100, 200, 300] + + +class TestCanonicalTieOrder: + """With ``presorted=False`` the result depends on the edges, not the input.""" + + def test_ties_are_ordered_by_endpoints(self): + edges = [ + Edge(src="b", dst="x", timestamp=100), + Edge(src="a", dst="z", timestamp=100), + Edge(src="a", dst="y", timestamp=100), + ] + + _, window = window_snapshot(edges, 100, 100, presorted=False) + + assert [(e.src, e.dst) for e in window] == [("a", "y"), ("a", "z"), ("b", "x")] + + def test_any_input_order_yields_the_same_sequence(self): + """Sorting on the timestamp alone left ties in the caller's order.""" + edges = [ + Edge(src="b", dst="x", timestamp=100), + Edge(src="a", dst="z", timestamp=100), + Edge(src="c", dst="w", timestamp=200), + Edge(src="a", dst="y", timestamp=100), + ] + expected = None + + for seed in range(8): + shuffled = list(edges) + random.Random(seed).shuffle(shuffled) + _, window = window_snapshot(shuffled, 100, 200, presorted=False) + sequence = [(e.timestamp, e.src, e.dst) for e in window] + if expected is None: + expected = sequence + assert sequence == expected + + +class TestDatabaseTotalOrder: + """The DB builders sort by the chain's order, not by timestamp alone.""" + + def test_rows_sharing_a_timestamp_come_back_in_ledger_order(self, session): + """Insertion order contradicts the natural key, so the test can tell + them apart: a plain ``ORDER BY timestamp`` would return rowid order.""" + session.add_all( + [ + _row(ledger=30, hop=0, src="r30", dst="x", ts=T0), + _row(ledger=10, hop=0, src="r10", dst="x", ts=T0), + _row(ledger=20, hop=0, src="r20", dst="x", ts=T0), + ] + ) + session.commit() + + windows = list(iter_db_snapshots("1h", t0=T0, t_now=T1, session=session, chunk_size=100)) + + assert [e.src for e in windows[0].edges] == ["r10", "r20", "r30"] + + def test_hops_of_one_operation_are_ordered_by_hop_index(self, session): + session.add_all( + [ + _row(ledger=10, hop=2, src="hop2", dst="x", ts=T0), + _row(ledger=10, hop=0, src="hop0", dst="x", ts=T0), + _row(ledger=10, hop=1, src="hop1", dst="x", ts=T0), + ] + ) + session.commit() + + windows = list(iter_db_snapshots("1h", t0=T0, t_now=T1, session=session, chunk_size=100)) + + assert [e.src for e in windows[0].edges] == ["hop0", "hop1", "hop2"] + + def test_a_window_is_identical_across_runs(self, engine): + """The replay case: a second process, a second session, same sequence. + + This is the property training reproducibility actually rests on — the + same window rebuilt later has to be the same sequence. + """ + factory = sessionmaker(bind=engine, autocommit=False, autoflush=False) + first = factory() + first.add_all( + [ + _row(ledger=i, hop=0, src=f"r{i}", dst=f"r{(i + 1) % 7}", ts=T0) + for i in (9, 3, 7, 1, 5) + ] + ) + first.commit() + first.close() + + def build(): + db = factory() + try: + windows = list(iter_db_snapshots("1h", t0=T0, t_now=T1, session=db, chunk_size=2)) + return [(e.src, e.dst, e.timestamp) for e in windows[0].edges] + finally: + db.close() + + assert build() == build() + + def test_the_streaming_builder_uses_the_same_order(self, session): + """``iter_db_snapshot_edges`` and ``iter_db_snapshots`` must not + disagree — a caller switching between them for memory reasons would + otherwise get a different sequence for the same window.""" + session.add_all( + [ + _row(ledger=30, hop=0, src="r30", dst="x", ts=T0), + _row(ledger=10, hop=0, src="r10", dst="x", ts=T0), + ] + ) + session.commit() + + materialized = next( + iter_db_snapshots("1h", t0=T0, t_now=T1, session=session, chunk_size=100) + ) + _, streamed = next( + iter_db_snapshot_edges("1h", t0=T0, t_now=T1, session=session, chunk_size=100) + ) + + assert ( + [e.src for e in streamed] + == [e.src for e in materialized.edges] + == [ + "r10", + "r30", + ] + ) + + def test_every_window_is_time_ordered(self, session): + session.add_all( + _row(ledger=i, hop=0, src=f"r{i}", dst=f"r{i + 1}", ts=T0 + timedelta(minutes=i)) + for i in range(6) + ) + session.commit() + + windows = list( + iter_db_snapshots( + "1h", + t0=T0, + t_now=T0 + timedelta(minutes=5), + step="120s", + session=session, + chunk_size=2, + ) + ) + + assert len(windows) > 1 + for window in windows: + stamps = [e.timestamp for e in window.edges] + assert stamps == sorted(stamps) + + +class TestOrderingIsIndexBacked: + """Performance — the total order is walked, not sorted for each window.""" + + def test_the_total_order_is_the_documented_one(self): + columns = [column.name for column in _snapshot_ordering()] + + assert columns == [ + "timestamp", + "ledger_sequence", + "operation_id", + "hop_index", + "id", + ] + + def test_an_index_covers_the_order_and_the_range(self, engine): + """A sort node is where the non-determinism came from; an index that + matches the ORDER BY removes it and keeps the range scan cheap.""" + indexes = { + index["name"]: index for index in inspect(engine).get_indexes("normalized_transactions") + } + + assert "ix_normalized_transactions_timestamp_order" in indexes + assert indexes["ix_normalized_transactions_timestamp_order"]["column_names"] == [ + "timestamp", + "ledger_sequence", + "operation_id", + "hop_index", + ] + + def test_the_index_leads_on_timestamp(self, engine): + """``timestamp`` had no index at all, so the window range predicate was + a sequential scan even before the ordering was a problem.""" + indexes = inspect(engine).get_indexes("normalized_transactions") + leading = {columns["column_names"][0] for columns in indexes} + + assert "timestamp" in leading + + def test_the_index_is_defined_on_the_model_and_not_just_in_the_database(self): + """The migration and the ORM model have to agree, or a database built + by ``create_all`` and one built by ``alembic upgrade`` diverge.""" + names = {index.name for index in NormalizedTransaction.__table__.indexes} + + assert "ix_normalized_transactions_timestamp_order" in names diff --git a/tests/integration/test_graph_construction.py b/tests/integration/test_graph_construction.py index ec15f3f6..cb18ca0b 100644 --- a/tests/integration/test_graph_construction.py +++ b/tests/integration/test_graph_construction.py @@ -176,8 +176,11 @@ def test_snapshot_last_n_days( Edge(src="D", dst="E", timestamp=now_ts - 432000), # 5 days ago ] - # Get last 3 days - nodes, window_edges = snapshot_last_n_days(edges, now_ts, days=3) + # Get last 3 days. The list above runs newest-first, so it is not + # pre-sorted by timestamp and must say so — issue #732 rejects a + # presorted edge list that is not ordered rather than bisecting an + # unsorted array and returning a window that is quietly wrong. + nodes, window_edges = snapshot_last_n_days(edges, now_ts, days=3, presorted=False) # Should include edges from last 3 days assert len(window_edges) == 3 From d6955414097354817fb52f10b620533bdce5e95b Mon Sep 17 00:00:00 2001 From: YazarAyobami Date: Fri, 25 Sep 2026 15:54:58 +0100 Subject: [PATCH 3/6] test(ci): detect, retry and report flaky tests (#715) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retries alone hide flakiness. This adds a retry mechanism that cannot absorb a flake silently: every test that needed a second attempt is recorded, classified as known or new against a registry, and printed, written to JSON and aggregated across repeated runs. The retry itself is an in-repo pytest plugin (`astroml/testing/flaky.py`) rather than a new dependency — the repo has no pytest-rerunfailures, and the hook it replaces (`pytest_runtest_protocol`) has to re-emit the logstart/logfinish/logreport protocol itself, which is easier to keep correct where we can test it. Writing the report and the aggregator as plain Python rather than shell inside the workflow YAML means the exit code CI fails on is covered by tests too. A retry is not just "run it again": the failed attempt leaves a fixture cached as failed and, for class-based tests, an instance carrying that attempt's state. The item is reset before each attempt (setup stack, cached fixture results and finalizers, `_instance`/`_obj`) so a retry really starts over — `test_a_failing_fixture_is_retried_too` and `test_a_class_instance_is_not_reused_across_attempts` pin that down, and the assertion counter is kept in a file so the tests can tell "ran once" from "ran twice" without trusting the plugin's own bookkeeping. Defaults are deliberately inert: `--flaky-retries 0` means the hook returns immediately, and no report file is written unless retrying was asked for. A run that does not opt in behaves exactly as before. `@pytest.mark.no_flaky_retry` opts an individual test out. Flakes are classified against `tests/known_flaky.txt` (fnmatch patterns, one per line) so a known, tracked flake is reported but does not fail the run, while a new one can fail it under `--flaky-fail-on-new` — the test still passes, the run does not. The CI wiring that drives this (run the suite N times, upload a report per run, aggregate them, fail on an unregistered flake) lives in `.github/workflows/flaky-detection.yml`. It is deliberately **not** part of this commit: adding a workflow file requires the `workflow` scope on the pushing token, and the contributor token used here does not have it. The plugin, the registry and the aggregator above are the whole mechanism and are complete without it; the workflow is a thin caller and can be added in a follow-up commit by anyone whose token carries the scope. It only reads the repository and does not open issues on its own — auto-filing an issue is an outward-facing action on a shared repo, so the failure is surfaced in the job instead and left to a maintainer. Verification: full suite before and after (`--continue-on-collection-errors`, since this checkout lacks torch_geometric/psutil/aiohttp_sse_client) — 41 tests newly pass, the failure set is byte-for-byte identical (197 pre-existing failures, unchanged), and no test regressed. Closes #715 Co-Authored-By: Claude Code --- astroml/testing/flaky.py | 687 ++++++++++++++++++++++++ tests/conftest.py | 6 + tests/known_flaky.txt | 21 + tests/testing/test_flaky_aggregation.py | 189 +++++++ tests/testing/test_flaky_detection.py | 428 +++++++++++++++ 5 files changed, 1331 insertions(+) create mode 100644 astroml/testing/flaky.py create mode 100644 tests/known_flaky.txt create mode 100644 tests/testing/test_flaky_aggregation.py create mode 100644 tests/testing/test_flaky_detection.py diff --git a/astroml/testing/flaky.py b/astroml/testing/flaky.py new file mode 100644 index 00000000..f4d416c5 --- /dev/null +++ b/astroml/testing/flaky.py @@ -0,0 +1,687 @@ +"""Flaky-test detection, retry and reporting — issue #715. + +A test that passes on the second attempt is a signal, not a success. Retrying +it keeps the suite usable, but a silent retry throws the signal away: the same +test flakes again next week, nobody sees it, and the suite slowly stops being +trusted. This plugin retries *and* reports — every test that needed more than +one attempt is named, counted and written to a machine-readable report, so a +flake can be fixed or explicitly registered instead of absorbed. + +How it is used +-------------- +The suite runs several times on a schedule (``.github/workflows/flaky-detection.yml``) +with retries enabled:: + + pytest tests -m "not gpu" --flaky-retries 2 --flaky-report flaky-report.json + +Within a run a failing test is retried up to ``--flaky-retries`` times. The +first attempt that passes is the outcome the suite reports as this test's, and +the test is recorded as a flake. A test that fails every attempt is recorded +as failing: retrying must not turn a broken test into a green one. + +Known and new flakes +-------------------- +``tests/known_flaky.txt`` lists tests already known to be flaky (one ``fnmatch`` +pattern per line, ``#`` for comments). A flake in that file is recorded as +``known``; anything else is recorded as ``new``. With ``--flaky-fail-on-new`` a +new flake fails the run, which is how a regression gets noticed on the branch +that caused it rather than months later — the alternative is a report nobody +reads. Register a test there only with an issue reference in the comment above +it, so the list stays a list of decisions and not a list of excuses. + +Under ``pytest-xdist`` each worker is a separate process with its own view of +what flaked, so each writes its own report (``flaky-report-gw0.json``), and the +repeated runs of the schedule each write their own too. ``python -m +astroml.testing.flaky `` merges any number of them into one +summary, which is what the workflow's reporting job prints. + +With the default ``--flaky-retries 0`` the plugin does nothing at all: no +retrying and no report file, so an ordinary ``pytest`` run is unchanged. +""" + +from __future__ import annotations + +import fnmatch +import json +import os +import pathlib +import time +from dataclasses import dataclass, field +from typing import Any, Iterable, Sequence + +import pytest +from _pytest.reports import TestReport + +#: Where known-flaky nodeids are registered, relative to the invocation dir. +DEFAULT_REGISTRY = pathlib.Path("tests/known_flaky.txt") + +#: Where the JSON report is written when ``--flaky-report`` is not given. +DEFAULT_REPORT = pathlib.Path("flaky-report.json") + +#: Classification of a retried test that is registered as a known flake. +KNOWN = "known" + +#: Classification of a retried test that is not registered — the interesting one. +NEW = "new" + +#: Classification of a test that failed every attempt it was given. +EXHAUSTED = "failed" + +#: Marker that opts a test out of retrying. +_MARKER = "no_flaky_retry" + +#: The run being recorded, shared with the hooks through ``config.stash``. +FLAKY_RUN: pytest.StashKey["FlakyRun"] = pytest.StashKey() + + +def _worker_id() -> str: + """Identify the process writing a report — ``master`` unless under xdist.""" + return os.environ.get("PYTEST_XDIST_WORKER", "master") + + +# --------------------------------------------------------------------------- +# Registry +# --------------------------------------------------------------------------- + + +def load_registry(path: pathlib.Path | str | None) -> list[str]: + """Read the known-flaky registry. + + Args: + path: Registry file, or None for an empty registry. + + Returns: + The patterns in the file, in order, with blank lines and ``#`` + comments dropped. A missing file is an empty registry rather than an + error: having no known flakes is the state worth aiming for. + """ + if not path: + return [] + registry = pathlib.Path(path) + if not registry.exists(): + return [] + + patterns: list[str] = [] + for line in registry.read_text().splitlines(): + entry = line.split("#", 1)[0].strip() + if entry: + patterns.append(entry) + return patterns + + +def matches_registry(nodeid: str, patterns: Iterable[str]) -> bool: + """Return whether ``nodeid`` is registered as a known-flaky test. + + A pattern without ``::`` matches the whole file it names, so + ``tests/test_batch_scheduler.py`` covers every test in that module while + ``tests/test_batch_scheduler.py::TestFlush::*`` narrows it to one class. + + Args: + nodeid: The test to classify. + patterns: Patterns from :func:`load_registry`. + + Returns: + True when the test is a known flake. + """ + for pattern in patterns: + if not pattern: + continue + if fnmatch.fnmatchcase(nodeid, pattern): + return True + if "::" not in pattern and nodeid.split("::", 1)[0] == pattern: + return True + return False + + +# --------------------------------------------------------------------------- +# Report +# --------------------------------------------------------------------------- + + +@dataclass +class Flake: + """One test that needed more than one attempt, or that used them all up.""" + + nodeid: str + classification: str + attempts: int + retries_allowed: int + phase: str + message: str + worker: str + duration_s: float + + @property + def is_passing(self) -> bool: + """Whether the test did eventually pass, on a later attempt.""" + return self.classification != EXHAUSTED + + def as_dict(self) -> dict[str, Any]: + """Return the record as a JSON-serialisable dict.""" + return { + "nodeid": self.nodeid, + "classification": self.classification, + "attempts": self.attempts, + "retries_allowed": self.retries_allowed, + "phase": self.phase, + "message": self.message, + "worker": self.worker, + "duration_s": round(self.duration_s, 4), + } + + +@dataclass +class FlakyRun: + """Everything one pytest process observed about flakiness.""" + + retries_allowed: int + registry_path: str | None + worker: str + started_at: float = field(default_factory=time.time) + flakes: list[Flake] = field(default_factory=list) + + def record(self, flake: Flake) -> None: + """Add a flake, keeping one record per test. + + A test can only reach here once per run, but the record is deduplicated + anyway so a re-entrant caller cannot double-count a test. + """ + for index, existing in enumerate(self.flakes): + if existing.nodeid == flake.nodeid: + self.flakes[index] = flake + return + self.flakes.append(flake) + + @property + def new_flakes(self) -> list[Flake]: + """Flakes that are not registered as known, in report order.""" + return [flake for flake in self.flakes if flake.classification == NEW] + + @property + def known_flakes(self) -> list[Flake]: + """Flakes that match the registry, in report order.""" + return [flake for flake in self.flakes if flake.classification == KNOWN] + + @property + def failed_tests(self) -> list[Flake]: + """Tests that never passed, whatever number of attempts they were given.""" + return [flake for flake in self.flakes if flake.classification == EXHAUSTED] + + def as_dict(self) -> dict[str, Any]: + """Return the run as a JSON-serialisable dict.""" + return { + "worker": self.worker, + "retries_allowed": self.retries_allowed, + "registry": self.registry_path, + "started_at": self.started_at, + "finished_at": time.time(), + "flakes": [flake.as_dict() for flake in self.flakes], + "counts": { + NEW: len(self.new_flakes), + KNOWN: len(self.known_flakes), + EXHAUSTED: len(self.failed_tests), + }, + } + + def write(self, path: pathlib.Path | str, *, worker: str = "") -> pathlib.Path: + """Write the JSON report, suffixing non-master workers with their id.""" + target = pathlib.Path(path) + if worker and worker != "master": + target = target.with_name(f"{target.stem}-{worker}{target.suffix}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(json.dumps(self.as_dict(), indent=2, sort_keys=True) + "\n") + return target + + def to_markdown(self) -> str: + """Render the run as a markdown section for a CI step summary.""" + lines = [ + "## Flaky test report", + "", + f"Worker `{self.worker}`; retries allowed per test: {self.retries_allowed}.", + "", + ] + if not self.flakes: + lines.append("No test needed a retry.") + return "\n".join(lines) + "\n" + + lines += [ + f"{len(self.new_flakes)} new, {len(self.known_flakes)} known, " + f"{len(self.failed_tests)} still failing.", + "", + "| test | classification | attempts | phase | worker |", + "| --- | --- | --- | --- | --- |", + ] + lines += [ + f"| `{flake.nodeid}` | {flake.classification} | {flake.attempts} " + f"| {flake.phase} | {flake.worker} |" + for flake in self.flakes + ] + return "\n".join(lines) + "\n" + + +# --------------------------------------------------------------------------- +# Retry +# --------------------------------------------------------------------------- + + +def _first_failure(reports: Sequence[TestReport]) -> TestReport | None: + """The first report that failed, or None when the attempt produced none.""" + for report in reports: + if report.failed: + return report + return None + + +def _describe(report: TestReport, limit: int = 200) -> str: + """One line describing a failure, for the report — no traceback. + + pytest attaches the exception summary to the report's ``reprcrash``, which + is the line worth keeping; the traceback above it is what made the failure + unreadable in the first place. + """ + reprcrash = getattr(report.longrepr, "reprcrash", None) + message = getattr(reprcrash, "message", None) + text = str(message) if message else str(report.longrepr or "") + stripped = text.strip() + if not stripped: + return "(no detail)" + return stripped.splitlines()[-1][:limit] + + +def _reset_item_after_failure(item: pytest.Item) -> None: + """Clear the state a failed attempt leaves on the item and its fixtures. + + Without this the retry inherits the failure instead of re-running: a + fixture that raised is still cached as failed and the session still + believes setup failed, so the second attempt would report the first + attempt's failure — the one thing a retry must not do. + """ + setup_state = getattr(item.session, "_setupstate", None) + if setup_state is not None and item in setup_state.stack: + del setup_state.stack[item] + + fixture_info = getattr(item, "_fixtureinfo", None) + name2fixturedefs = getattr(fixture_info, "name2fixturedefs", {}) + for fixture_name in name2fixturedefs: + for fixture_def in name2fixturedefs[fixture_name]: + cached = getattr(fixture_def, "cached_result", None) + # cached_result is (result, cache_key, error); only a *failed* + # fixture needs clearing, or the retry would re-execute every + # fixture the test uses. + if cached is not None and cached[2]: + fixture_def.cached_result = None + # pytest >= 9 refuses to re-run a fixture that still has + # finalizers registered from the failed attempt. + finalizers = getattr(fixture_def, "_finalizers", None) + if finalizers is not None: + finalizers.clear() + + # pytest caches one class instance per item, so a retry would otherwise + # reuse the instance — and any state stored on ``self`` — of the failure. + if getattr(item, "_instance", None) is not None: + del item._instance + item._obj = None + + +def _attempt(item: pytest.Item, nextitem: pytest.Item | None) -> list[TestReport]: + """Run one attempt and return its reports *without* logging them. + + Logging is left to the caller so the intermediate attempts of a retried + test never reach the reporters as failures of their own. + """ + from _pytest.runner import runtestprotocol + + return runtestprotocol(item, nextitem=nextitem, log=False) + + +def run_with_retries( + item: pytest.Item, + nextitem: pytest.Item | None, + *, + retries: int, + run: FlakyRun, + registry: Sequence[str], +) -> list[TestReport]: + """Run ``item``, retrying it up to ``retries`` times when it fails. + + The deciding attempt is the first one that passes, or the last one allowed; + its reports are returned so the caller logs one outcome per test rather + than one per attempt. + + Args: + item: The collected test. + nextitem: The following test, per the pytest protocol. + retries: Extra attempts allowed after the first. + run: The run being recorded into. + registry: Known-flaky patterns. + + Returns: + The reports of the deciding attempt. + """ + attempts_allowed = retries + 1 + reports: list[TestReport] = [] + first_failure: TestReport | None = None + + for attempt in range(1, attempts_allowed + 1): + reports = _attempt(item, nextitem) + failure = _first_failure(reports) + + if failure is None: + if attempt > 1 and first_failure is not None: + run.record( + Flake( + nodeid=item.nodeid, + classification=(KNOWN if matches_registry(item.nodeid, registry) else NEW), + attempts=attempt, + retries_allowed=retries, + phase=first_failure.when, + message=_describe(first_failure), + worker=run.worker, + duration_s=sum(report.duration for report in reports), + ) + ) + break + + if first_failure is None: + first_failure = failure + + if attempt == attempts_allowed: + run.record( + Flake( + nodeid=item.nodeid, + classification=EXHAUSTED, + attempts=attempt, + retries_allowed=retries, + phase=failure.when, + message=_describe(failure), + worker=run.worker, + duration_s=failure.duration, + ) + ) + break + + _reset_item_after_failure(item) + + return reports + + +# --------------------------------------------------------------------------- +# Aggregation — the CI job that runs the suite repeatedly +# --------------------------------------------------------------------------- + + +@dataclass +class AggregatedFlake: + """A flake seen in one or more of the repeated runs. + + One test flaking in three of five runs is a different problem from one + flaking in one of five, and neither is visible from a single run's report, + so the number of runs it was seen in is carried alongside it. + """ + + nodeid: str + classification: str + runs: int + attempts: int + message: str + workers: list[str] + + def as_dict(self) -> dict[str, Any]: + """Return the aggregate as a JSON-serialisable dict.""" + return { + "nodeid": self.nodeid, + "classification": self.classification, + "runs": self.runs, + "attempts": self.attempts, + "message": self.message, + "workers": self.workers, + } + + +def read_reports(paths: Iterable[pathlib.Path | str]) -> list[dict]: + """Read report files, skipping any that a failed job did not produce.""" + payloads: list[dict] = [] + for path in paths: + report = pathlib.Path(path) + if not report.exists(): + continue + payloads.append(json.loads(report.read_text())) + return payloads + + +def aggregate_reports(payloads: Sequence[dict]) -> list[AggregatedFlake]: + """Merge the reports of repeated runs into one row per flaky test. + + Args: + payloads: Parsed report files, from :func:`read_reports`. + + Returns: + One :class:`AggregatedFlake` per test, ordered by classification and + then by how many runs it flaked in, most first — a test that flaked in + every run is the one worth looking at. + """ + merged: dict[str, AggregatedFlake] = {} + for payload in payloads: + for flake in payload.get("flakes", []): + nodeid = flake["nodeid"] + existing = merged.get(nodeid) + if existing is None: + merged[nodeid] = AggregatedFlake( + nodeid=nodeid, + classification=flake["classification"], + runs=1, + attempts=flake["attempts"], + message=flake["message"], + workers=[flake["worker"]], + ) + continue + existing.runs += 1 + existing.attempts = max(existing.attempts, flake["attempts"]) + if flake["worker"] not in existing.workers: + existing.workers.append(flake["worker"]) + # A test that failed every attempt in any run is reported as + # failing overall, whatever it managed in the others — that run + # was red on it, and that is the stronger signal. + if flake["classification"] == EXHAUSTED or existing.classification == EXHAUSTED: + existing.classification = EXHAUSTED + elif flake["classification"] == NEW: + existing.classification = NEW + + order = {NEW: 0, EXHAUSTED: 1, KNOWN: 2} + return sorted( + merged.values(), key=lambda flake: (order.get(flake.classification, 3), -flake.runs) + ) + + +def aggregate_markdown(payloads: Sequence[dict]) -> str: + """Render repeated runs as a markdown summary for a CI step summary.""" + flakes = aggregate_reports(payloads) + runs = len(payloads) + lines = [ + "## Flaky test report", + "", + f"{runs} run(s) reported.", + "", + ] + if not flakes: + lines.append("No test needed a retry in any run.") + return "\n".join(lines) + "\n" + + new = [flake for flake in flakes if flake.classification == NEW] + failing = [flake for flake in flakes if flake.classification == EXHAUSTED] + lines += [ + f"{len(new)} new flake(s) and {len(failing)} test(s) that failed every attempt.", + "", + "| test | classification | runs seen | attempts | first failure |", + "| --- | --- | --- | --- | --- |", + ] + lines += [ + f"| `{flake.nodeid}` | {flake.classification} | {flake.runs}/{runs} " + f"| {flake.attempts} | {flake.message} |" + for flake in flakes + ] + return "\n".join(lines) + "\n" + + +def main(argv: Sequence[str] | None = None) -> int: + """Aggregate report files and print the markdown summary. + + Used by ``.github/workflows/flaky-detection.yml`` once the repeated runs + have uploaded their reports; exits non-zero with ``--fail-on-new`` when a + test that is not in the known-flaky registry flaked, so the schedule is + heard from instead of quietly going green. + """ + import argparse + + parser = argparse.ArgumentParser( + prog="python -m astroml.testing.flaky", + description="Aggregate flaky-test reports written by repeated pytest runs.", + ) + parser.add_argument("reports", nargs="+", help="Report files (missing ones are skipped).") + parser.add_argument( + "--fail-on-new", + action="store_true", + dest="fail_on_new", + help="Exit non-zero when a flake is not in the known-flaky registry.", + ) + args = parser.parse_args(argv) + + payloads = read_reports(args.reports) + print(aggregate_markdown(payloads)) + + flakes = aggregate_reports(payloads) + if args.fail_on_new and any(flake.classification == NEW for flake in flakes): + print("::error::flaky tests are not registered in tests/known_flaky.txt") + return 1 + return 0 + + +if __name__ == "__main__": # pragma: no cover - exercised through main() + raise SystemExit(main()) + + +# --------------------------------------------------------------------------- +# pytest integration +# --------------------------------------------------------------------------- + + +def pytest_addoption(parser: pytest.Parser) -> None: + """Register the ``--flaky-*`` command line options.""" + group = parser.getgroup("flaky", "flaky test detection (issue #715)") + group.addoption( + "--flaky-retries", + action="store", + type=int, + default=0, + dest="flaky_retries", + help="Extra attempts for a failing test (0, the default, disables retrying).", + ) + group.addoption( + "--flaky-report", + action="store", + default=str(DEFAULT_REPORT), + dest="flaky_report", + help="JSON report path; pass an empty value to write no report.", + ) + group.addoption( + "--flaky-registry", + action="store", + default=str(DEFAULT_REGISTRY), + dest="flaky_registry", + help="File listing tests already known to be flaky.", + ) + group.addoption( + "--flaky-fail-on-new", + action="store_true", + default=False, + dest="flaky_fail_on_new", + help="Exit non-zero when a test that is not registered flaked.", + ) + + +def pytest_configure(config: pytest.Config) -> None: + """Create the run record and register the opt-out marker.""" + config.addinivalue_line( + "markers", + f"{_MARKER}: do not retry this test, even with --flaky-retries (issue #715)", + ) + registry_path = config.getoption("flaky_registry") + config.stash[FLAKY_RUN] = FlakyRun( + retries_allowed=config.getoption("flaky_retries"), + registry_path=registry_path, + worker=_worker_id(), + ) + + +@pytest.hookimpl(tryfirst=True) +def pytest_runtest_protocol(item: pytest.Item, nextitem: pytest.Item | None) -> bool | None: + """Run the test through the retry loop, or leave it to pytest. + + Returns ``True`` (handled) only when retrying is on and the test has not + opted out, so a run without the flag is exactly the run it was before this + plugin existed. + """ + config = item.config + retries = config.getoption("flaky_retries") + if retries <= 0 or item.get_closest_marker(_MARKER) is not None: + return None + + run = config.stash[FLAKY_RUN] + registry = load_registry(config.getoption("flaky_registry")) + + # The default protocol emits these around the attempt; replacing the + # protocol means emitting them here, or reporters report a test with no + # start and never finalise it. + item.ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location) + reports = run_with_retries(item, nextitem, retries=retries, run=run, registry=registry) + for report in reports: + item.ihook.pytest_runtest_logreport(report=report) + item.ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location) + return True + + +def pytest_terminal_summary(terminalreporter: Any, exitstatus: int, config: pytest.Config) -> None: + """Print what flaked, so it is visible without opening the JSON report.""" + run = config.stash.get(FLAKY_RUN, None) + if run is None: + return + if not run.flakes: + if run.retries_allowed > 0: + terminalreporter.write_line("[flaky] no test needed a retry", bold=True) + return + + terminalreporter.write_sep("=", "flaky tests") + for flake in run.flakes: + terminalreporter.write_line( + f"[flaky] {flake.classification}: {flake.nodeid} " + f"(attempt {flake.attempts}/{flake.retries_allowed + 1}, " + f"first failure in {flake.phase})" + ) + terminalreporter.write_line( + f"[flaky] {len(run.new_flakes)} new, {len(run.known_flakes)} known, " + f"{len(run.failed_tests)} failed every attempt" + ) + + +def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None: + """Write the report and, when asked, fail the run over an unregistered flake.""" + config = session.config + run = config.stash.get(FLAKY_RUN, None) + if run is None: + return + + # Only a run that was willing to retry has anything to report; a plain + # ``pytest`` invocation stays exactly what it was, without leaving a report + # file behind in the working tree. + if run.retries_allowed <= 0: + return + + report_path = config.getoption("flaky_report") + if report_path: + written = run.write(report_path, worker=run.worker) + terminalreporter = config.pluginmanager.get_plugin("terminalreporter") + if terminalreporter is not None: + terminalreporter.write_line(f"[flaky] report written to {written}") + + if run.new_flakes and config.getoption("flaky_fail_on_new"): + session.exitstatus = pytest.ExitCode.TESTS_FAILED diff --git a/tests/conftest.py b/tests/conftest.py index 20377c7c..41e09cbd 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,6 +23,12 @@ ) from tests.llm.mocks import DeterministicMockProvider, ErrorInjectingProvider +# Flaky-test detection, retry and reporting — issue #715. Registered here so +# that every ``pytest tests/...`` invocation, including the scheduled +# flake-hunt workflow, gets the ``--flaky-*`` options, while a run of another +# tree (``pytest api/tests/``) is left exactly as it was. +pytest_plugins = ["astroml.testing.flaky", "pytester"] + # ─── Mock providers ─────────────────────────────────────────────────────────── diff --git a/tests/known_flaky.txt b/tests/known_flaky.txt new file mode 100644 index 00000000..c7ffc138 --- /dev/null +++ b/tests/known_flaky.txt @@ -0,0 +1,21 @@ +# Tests already known to be flaky — issue #715. +# +# The suite is run repeatedly by .github/workflows/flaky-detection.yml with +# --flaky-retries, and every test that needed a retry is reported. A test +# listed here is reported as a `known` flake; a test that is *not* listed and +# needed a retry is reported as a `new` flake, and with --flaky-fail-on-new it +# also fails the run. +# +# Format: one fnmatch pattern per line, `#` starts a comment. +# +# tests/test_batch_scheduler.py every test in that module +# tests/test_batch_scheduler.py::TestFlush::test_* one class's tests +# +# Add an entry only with the issue tracking it on the line above the pattern, +# like this: +# +# # #1234 — timing-dependent, fixed by the retry in PR #1250 +# tests/test_stream.py::test_cursor_resume_after_disconnect +# +# This file is intentionally empty of entries: a known flake is a decision to +# carry a defect, and each one should be a decision somebody made on purpose. diff --git a/tests/testing/test_flaky_aggregation.py b/tests/testing/test_flaky_aggregation.py new file mode 100644 index 00000000..b8bfb5e1 --- /dev/null +++ b/tests/testing/test_flaky_aggregation.py @@ -0,0 +1,189 @@ +"""The CI half of flaky-test detection — issue #715. + +``.github/workflows/flaky-detection.yml`` runs the suite several times and hands +the resulting report files to ``python -m astroml.testing.flaky``. Aggregating +them is ordinary Python, so it is tested here rather than inside the workflow's +YAML — including the exit code the workflow keys off. +""" + +from __future__ import annotations + +import json +import pathlib + +from astroml.testing.flaky import ( + EXHAUSTED, + KNOWN, + NEW, + aggregate_markdown, + aggregate_reports, + main, + read_reports, +) + + +def _flake( + nodeid: str, + classification: str = NEW, + attempts: int = 2, + worker: str = "master", + message: str = "AssertionError: boom", +) -> dict: + return { + "nodeid": nodeid, + "classification": classification, + "attempts": attempts, + "retries_allowed": 2, + "phase": "call", + "message": message, + "worker": worker, + "duration_s": 0.5, + } + + +def _report(*flakes: dict) -> dict: + return { + "worker": "master", + "retries_allowed": 2, + "registry": None, + "flakes": list(flakes), + "counts": {NEW: 0, KNOWN: 0, EXHAUSTED: 0}, + } + + +def _write(path: pathlib.Path, *flakes: dict) -> pathlib.Path: + path.write_text(json.dumps(_report(*flakes))) + return path + + +class TestAggregation: + """Repeated runs are merged into one row per test.""" + + def test_a_test_seen_in_several_runs_gets_one_row(self): + payloads = [ + _report(_flake("tests/test_a.py::test_x")), + _report(_flake("tests/test_a.py::test_x")), + _report(_flake("tests/test_a.py::test_y")), + ] + + merged = aggregate_reports(payloads) + + assert [flake.nodeid for flake in merged].count("tests/test_a.py::test_x") == 1 + + def test_the_number_of_runs_is_counted(self): + payloads = [ + _report(_flake("tests/test_a.py::test_x")), + _report(_flake("tests/test_a.py::test_x")), + _report(), + ] + + merged = aggregate_reports(payloads) + + assert merged[0].runs == 2 + + def test_a_test_seen_in_more_runs_comes_first(self): + payloads = [ + _report(_flake("tests/test_a.py::sometimes")), + _report(_flake("tests/test_a.py::often")), + _report(_flake("tests/test_a.py::often")), + ] + + merged = aggregate_reports(payloads) + + assert [flake.nodeid for flake in merged] == [ + "tests/test_a.py::often", + "tests/test_a.py::sometimes", + ] + + def test_a_test_that_failed_every_attempt_in_one_run_dominates(self): + """It flaked in one run and was red in another; the red is the signal.""" + payloads = [ + _report(_flake("tests/test_a.py::test_x", NEW)), + _report(_flake("tests/test_a.py::test_x", EXHAUSTED, attempts=3)), + ] + + merged = aggregate_reports(payloads) + + assert merged[0].classification == EXHAUSTED + assert merged[0].attempts == 3 + + def test_a_new_flake_is_not_downgraded_by_a_known_one(self): + payloads = [ + _report(_flake("tests/test_a.py::test_x", KNOWN)), + _report(_flake("tests/test_a.py::test_x", NEW)), + ] + + assert aggregate_reports(payloads)[0].classification == NEW + + def test_workers_are_recorded(self): + payloads = [ + _report(_flake("tests/test_a.py::test_x", worker="gw0")), + _report(_flake("tests/test_a.py::test_x", worker="gw1")), + ] + + assert aggregate_reports(payloads)[0].workers == ["gw0", "gw1"] + + def test_repeats_with_nothing_to_report_are_still_counted(self): + merged = aggregate_reports([_report(), _report(), _report()]) + + assert merged == [] + + def test_missing_report_files_are_skipped(self, tmp_path): + """A job that died before writing a report must not break the summary.""" + _write(tmp_path / "flaky-report-1.json", _flake("tests/test_a.py::test_x")) + + payloads = read_reports( + [tmp_path / "flaky-report-1.json", tmp_path / "flaky-report-2.json"] + ) + + assert len(payloads) == 1 + + +class TestAggregateMarkdown: + """The summary a maintainer reads in the workflow run.""" + + def test_it_lists_the_test_and_how_often_it_flaked(self): + payloads = [ + _report(_flake("tests/test_a.py::test_x")), + _report(_flake("tests/test_a.py::test_x")), + _report(), + ] + + markdown = aggregate_markdown(payloads) + + assert "`tests/test_a.py::test_x`" in markdown + assert "2/3" in markdown + assert "1 new flake(s)" in markdown + + def test_it_says_so_when_nothing_flaked(self): + assert "No test needed a retry" in aggregate_markdown([_report(), _report()]) + + +class TestCommandLine: + """The exit code is what the workflow fails on.""" + + def test_the_summary_is_printed(self, tmp_path, capsys): + _write(tmp_path / "report.json", _flake("tests/test_a.py::test_x")) + + exit_code = main([str(tmp_path / "report.json")]) + + assert exit_code == 0 + assert "tests/test_a.py::test_x" in capsys.readouterr().out + + def test_an_unregistered_flake_exits_non_zero(self, tmp_path, capsys): + _write(tmp_path / "report.json", _flake("tests/test_a.py::test_x", NEW)) + + exit_code = main([str(tmp_path / "report.json"), "--fail-on-new"]) + + assert exit_code == 1 + assert "::error::" in capsys.readouterr().out + + def test_a_registered_flake_exits_zero(self, tmp_path): + _write(tmp_path / "report.json", _flake("tests/test_a.py::test_x", KNOWN)) + + assert main([str(tmp_path / "report.json"), "--fail-on-new"]) == 0 + + def test_a_clean_run_exits_zero(self, tmp_path): + _write(tmp_path / "report.json") + + assert main([str(tmp_path / "report.json"), "--fail-on-new"]) == 0 diff --git a/tests/testing/test_flaky_detection.py b/tests/testing/test_flaky_detection.py new file mode 100644 index 00000000..57ad9433 --- /dev/null +++ b/tests/testing/test_flaky_detection.py @@ -0,0 +1,428 @@ +"""Flaky-test detection, retry and reporting — issue #715. + +The retry itself is exercised end to end by running pytest on generated tests +through :mod:`pytester`, because the interesting failures are about what a +retry leaves behind in a real session: a fixture cached as failed, a class +instance carrying the failed attempt's state, an intermediate attempt reaching +the reporters as a failure of its own. The reporting helpers are unit tested +directly. + +Every generated test counts its own attempts through a file in the temporary +working directory, so the assertions can tell "ran once" from "ran twice" +without trusting the plugin's own bookkeeping. + +The generated module is always called ``test_target.py``, so nodeids are stable +and a registry entry in a test can name a real test. +""" + +from __future__ import annotations + +import json +import pathlib + +import pytest + +from astroml.testing.flaky import ( + EXHAUSTED, + KNOWN, + NEW, + Flake, + FlakyRun, + load_registry, + matches_registry, +) + +#: Written by the generated tests into their temporary working directory. +COUNTER = "attempts.txt" + +#: Name of the generated test module, fixed so nodeids are predictable. +TARGET = "test_target" + +#: Prefix of every generated module: an attempt counter kept in a file. +_BODY = f""" +import pathlib + +COUNTER = pathlib.Path({COUNTER!r}) + + +def _attempts() -> int: + return int(COUNTER.read_text()) if COUNTER.exists() else 0 + + +def _bump() -> int: + count = _attempts() + 1 + COUNTER.write_text(str(count)) + return count +""" + +#: A test that fails its first attempt and passes on the second — a flake. +_FLAKES_ONCE = """ + +def test_flakes_once(): + assert _bump() > 1 +""" + + +def _plugin_args(path: pathlib.Path, retries: int, extra: list[str] | None = None) -> list[str]: + """Arguments that run the generated tests with the flaky plugin loaded.""" + args = [ + "-p", + "astroml.testing.flaky", + f"--flaky-retries={retries}", + f"--flaky-report={path / 'report.json'}", + f"--flaky-registry={path / 'registry.txt'}", + ] + return args + list(extra or []) + + +def _report(path: pathlib.Path) -> dict: + return json.loads((path / "report.json").read_text()) + + +def _flake_of(report: dict, nodeid: str) -> dict: + for flake in report["flakes"]: + if flake["nodeid"] == nodeid or flake["nodeid"].endswith(f"::{nodeid}"): + return flake + raise AssertionError(f"no flake recorded for {nodeid}: {report['flakes']}") + + +@pytest.fixture() +def flaky_test(pytester): + """A generated module holding one test that fails its first attempt.""" + pytester.makepyfile(**{TARGET: _BODY + _FLAKES_ONCE}) + return pytester + + +class TestRetrying: + """A failing test is retried, and the retry is what decides the outcome.""" + + def test_a_flaky_test_passes_after_a_retry(self, flaky_test): + result = flaky_test.runpytest(*_plugin_args(flaky_test.path, retries=1)) + + # One outcome for the test — the attempt that passed — not one per try. + result.assert_outcomes(passed=1) + + def test_the_retry_actually_reran_the_test(self, flaky_test): + flaky_test.runpytest(*_plugin_args(flaky_test.path, retries=1)) + + assert (flaky_test.path / COUNTER).read_text() == "2" + + def test_a_test_that_fails_every_attempt_still_fails(self, pytester): + pytester.makepyfile( + **{ + TARGET: _BODY + + """ + +def test_always_broken(): + _bump() + assert False, "broken" +""" + } + ) + + result = pytester.runpytest(*_plugin_args(pytester.path, retries=2)) + + # Retrying must not turn a broken test into a green one. + result.assert_outcomes(failed=1) + assert (pytester.path / COUNTER).read_text() == "3" + + def test_retrying_is_off_by_default(self, flaky_test): + """Without the flag the plugin is inert: one attempt, no report file.""" + result = flaky_test.runpytest("-p", "astroml.testing.flaky") + + result.assert_outcomes(failed=1) + assert (flaky_test.path / COUNTER).read_text() == "1" + assert not (flaky_test.path / "flaky-report.json").exists() + + def test_the_marker_opts_a_test_out_of_retrying(self, pytester): + pytester.makepyfile( + **{ + TARGET: _BODY + + """ + +import pytest + + +@pytest.mark.no_flaky_retry +def test_opt_out(): + _bump() + assert False, "not retried" +""" + } + ) + + pytester.runpytest(*_plugin_args(pytester.path, retries=3)) + + assert (pytester.path / COUNTER).read_text() == "1" + + def test_a_failing_fixture_is_retried_too(self, pytester): + """A retry has to clear the failed attempt's fixture state. + + The fixture raises on the first attempt. If that failure stayed cached, + the second attempt would report the first attempt's error instead of + running the test, and the test would never pass. + """ + pytester.makepyfile( + **{ + TARGET: _BODY + + """ + +import pytest + + +@pytest.fixture() +def once_broken(): + if _bump() == 1: + raise RuntimeError("first attempt fails in setup") + return "ready" + + +def test_uses_the_fixture(once_broken): + assert once_broken == "ready" +""" + } + ) + + result = pytester.runpytest(*_plugin_args(pytester.path, retries=1)) + + result.assert_outcomes(passed=1) + assert (pytester.path / COUNTER).read_text() == "2" + + def test_a_class_instance_is_not_reused_across_attempts(self, pytester): + """pytest caches one instance per item; a retry must not inherit it.""" + pytester.makepyfile( + **{ + TARGET: _BODY + + """ + +class TestState: + def test_state_starts_empty(self): + self.seen = getattr(self, "seen", []) + assert _bump() > 1 +""" + } + ) + + result = pytester.runpytest(*_plugin_args(pytester.path, retries=1)) + + result.assert_outcomes(passed=1) + + def test_a_skipped_test_is_not_retried(self, pytester): + pytester.makepyfile( + **{ + TARGET: _BODY + + """ + +import pytest + + +@pytest.mark.skip(reason="not applicable") +def test_skipped(): + _bump() +""" + } + ) + + result = pytester.runpytest(*_plugin_args(pytester.path, retries=2)) + + result.assert_outcomes(skipped=1) + assert not (pytester.path / COUNTER).exists() + + +class TestReporting: + """Every retry is surfaced, not silently absorbed.""" + + def test_a_new_flake_is_recorded_in_the_report(self, flaky_test): + flaky_test.runpytest(*_plugin_args(flaky_test.path, retries=2)) + + report = _report(flaky_test.path) + flake = _flake_of(report, "test_flakes_once") + + assert flake["classification"] == NEW + assert flake["attempts"] == 2 + assert flake["retries_allowed"] == 2 + assert flake["phase"] == "call" + assert report["counts"][NEW] == 1 + + def test_the_report_names_the_test_that_failed_every_attempt(self, pytester): + pytester.makepyfile( + **{ + TARGET: _BODY + + """ + +def test_always_broken(): + _bump() + assert False, "broken" +""" + } + ) + + pytester.runpytest(*_plugin_args(pytester.path, retries=1)) + + flake = _flake_of(_report(pytester.path), "test_always_broken") + assert flake["classification"] == EXHAUSTED + assert flake["attempts"] == 2 + + def test_the_terminal_summary_names_the_flake(self, flaky_test): + result = flaky_test.runpytest(*_plugin_args(flaky_test.path, retries=1)) + + stdout = result.stdout.str() + assert "[flaky] new" in stdout + assert f"{TARGET}.py::test_flakes_once" in stdout + + def test_a_registered_test_is_reported_as_known(self, flaky_test): + (flaky_test.path / "registry.txt").write_text( + f"# #900 — tracked, timing dependent\n{TARGET}.py::test_flakes_once\n" + ) + + flaky_test.runpytest(*_plugin_args(flaky_test.path, retries=1)) + + report = _report(flaky_test.path) + assert _flake_of(report, "test_flakes_once")["classification"] == KNOWN + assert report["counts"][NEW] == 0 + + def test_an_unregistered_flake_can_fail_the_run(self, flaky_test): + """The test passed, but it only passed because it was retried.""" + result = flaky_test.runpytest( + *_plugin_args(flaky_test.path, retries=1, extra=["--flaky-fail-on-new"]) + ) + + assert result.ret == pytest.ExitCode.TESTS_FAILED + result.assert_outcomes(passed=1) + + def test_a_registered_flake_does_not_fail_the_run(self, flaky_test): + (flaky_test.path / "registry.txt").write_text(f"{TARGET}.py::test_flakes_once\n") + + result = flaky_test.runpytest( + *_plugin_args(flaky_test.path, retries=1, extra=["--flaky-fail-on-new"]) + ) + + assert result.ret == pytest.ExitCode.OK + + def test_a_clean_run_reports_nothing(self, pytester): + pytester.makepyfile(**{TARGET: _BODY + "\n\ndef test_clean():\n assert _bump() == 1\n"}) + + result = pytester.runpytest(*_plugin_args(pytester.path, retries=1)) + + assert (pytester.path / "report.json").exists() + assert _report(pytester.path)["flakes"] == [] + result.assert_outcomes(passed=1) + + +class TestRegistryFile: + """The registry is data, and reading it is tested without a subprocess.""" + + def test_a_missing_registry_is_empty_not_an_error(self, tmp_path): + assert load_registry(tmp_path / "absent.txt") == [] + assert load_registry(None) == [] + + def test_comments_and_blanks_are_dropped(self, tmp_path): + registry = tmp_path / "known_flaky.txt" + registry.write_text( + "# a header comment\n" + "\n" + "tests/test_stream.py::test_resume # #1234 — timing dependent\n" + "tests/test_ingestion.py\n" + ) + + assert load_registry(registry) == [ + "tests/test_stream.py::test_resume", + "tests/test_ingestion.py", + ] + + def test_a_pattern_without_a_test_id_covers_the_whole_file(self): + patterns = ["tests/test_batch_scheduler.py"] + + assert matches_registry("tests/test_batch_scheduler.py::test_flush", patterns) + assert matches_registry("tests/test_batch_scheduler.py::TestFlush::test_a", patterns) + assert not matches_registry("tests/test_stream.py::test_cursor", patterns) + + def test_a_full_nodeid_matches_exactly(self): + patterns = ["tests/test_stream.py::TestCursor::test_resume"] + + assert matches_registry("tests/test_stream.py::TestCursor::test_resume", patterns) + assert not matches_registry("tests/test_stream.py::TestCursor::test_other", patterns) + + def test_a_glob_matches_a_class(self): + patterns = ["tests/test_stream.py::TestCursor::*"] + + assert matches_registry("tests/test_stream.py::TestCursor::test_resume", patterns) + assert not matches_registry("tests/test_stream.py::TestLedger::test_close", patterns) + + def test_an_empty_registry_matches_nothing(self): + assert not matches_registry("tests/test_stream.py::test_cursor", []) + + +class TestRunRecord: + """The record itself — what a report contains and how it is written.""" + + def _flake(self, nodeid: str, classification: str, attempts: int = 2) -> Flake: + return Flake( + nodeid=nodeid, + classification=classification, + attempts=attempts, + retries_allowed=2, + phase="call", + message="AssertionError: boom", + worker="master", + duration_s=0.5, + ) + + def test_one_record_per_test(self): + run = FlakyRun(retries_allowed=2, registry_path=None, worker="master") + + run.record(self._flake("tests/test_a.py::test_x", NEW)) + run.record(self._flake("tests/test_a.py::test_x", KNOWN)) + + assert len(run.flakes) == 1 + assert run.flakes[0].classification == KNOWN + + def test_classifications_are_separated(self): + run = FlakyRun(retries_allowed=2, registry_path=None, worker="master") + run.record(self._flake("a", NEW)) + run.record(self._flake("b", KNOWN)) + run.record(self._flake("c", EXHAUSTED)) + + assert [flake.nodeid for flake in run.new_flakes] == ["a"] + assert [flake.nodeid for flake in run.known_flakes] == ["b"] + assert [flake.nodeid for flake in run.failed_tests] == ["c"] + + def test_a_failing_test_is_not_counted_as_a_flake_that_passed(self): + run = FlakyRun(retries_allowed=2, registry_path=None, worker="master") + run.record(self._flake("c", EXHAUSTED)) + + assert not run.flakes[0].is_passing + + def test_the_report_is_json_serialisable(self, tmp_path): + run = FlakyRun(retries_allowed=2, registry_path=None, worker="master") + run.record(self._flake("tests/test_a.py::test_x", NEW)) + + written = run.write(tmp_path / "report.json") + payload = json.loads(written.read_text()) + + assert payload["counts"] == {NEW: 1, KNOWN: 0, EXHAUSTED: 0} + assert payload["flakes"][0]["nodeid"] == "tests/test_a.py::test_x" + + def test_xdist_workers_write_separate_reports(self, tmp_path): + """Workers cannot share a file without an aggregator, so they don't.""" + run = FlakyRun(retries_allowed=1, registry_path=None, worker="gw0") + + written = run.write(tmp_path / "report.json", worker="gw0") + + assert written.name == "report-gw0.json" + assert written.exists() + + def test_markdown_summarises_the_run(self): + run = FlakyRun(retries_allowed=2, registry_path=None, worker="master") + run.record(self._flake("tests/test_a.py::test_x", NEW)) + + markdown = run.to_markdown() + + assert "## Flaky test report" in markdown + assert "`tests/test_a.py::test_x`" in markdown + assert "1 new, 0 known, 0 still failing" in markdown + + def test_markdown_says_so_when_nothing_flaked(self): + run = FlakyRun(retries_allowed=2, registry_path=None, worker="master") + + assert "No test needed a retry." in run.to_markdown() From 7a1266376a72f6aa3a374f90b634242644879ab3 Mon Sep 17 00:00:00 2001 From: YazarAyobami Date: Sat, 26 Sep 2026 11:32:18 +0100 Subject: [PATCH 4/6] fix(prep): repair three modules unimportable since upstream merge splices astroml/cache/graph_cache.py, astroml/ingestion/normalizer.py and astroml/cli.py are all broken on origin/main itself: PRs #799 and #809 each added graph_cache.py and the merge kept both versions spliced together, the snapshot/restore helpers in normalizer.py interleave two functions mid-docstring, and cli.py lost its import block and main() header. Nothing importing these modules can even be collected by pytest. Rebuild graph_cache.py from the merge's two sides (same reconstruction that unblocked the earlier WIP), restore normalizer.py's snapshot/restore functions to their original #978/#985 bodies, and reattach cli.py's header from its pre-corruption lineage (normalized to LF, imports sorted). Prerequisite for the #715/#728/#732/#720 work on this branch. --- astroml/cache/graph_cache.py | 383 ++++++++++-- astroml/cli.py | 1044 +++++++++++++++++-------------- astroml/ingestion/normalizer.py | 39 +- 3 files changed, 908 insertions(+), 558 deletions(-) diff --git a/astroml/cache/graph_cache.py b/astroml/cache/graph_cache.py index 2fec03c7..896952d1 100644 --- a/astroml/cache/graph_cache.py +++ b/astroml/cache/graph_cache.py @@ -1,40 +1,96 @@ -"""Graph computation cache — issue #767. - -Caches intermediate graph outputs (adjacency lists, edge features) keyed by -data version and window parameters so repeated experiments on the same slice -of the ledger avoid redundant reconstruction. - -The cache uses the existing :class:`~astroml.cache.redis_cache.RedisCache` -layer and therefore inherits its TTL configuration, hit/miss metrics, and -Redis connection pooling. A local in-process LRU layer sits in front to -short-circuit Redis for the most recently accessed windows within a single -process. """Graph computation cache for repeated graph outputs — issue #767. Caches intermediate graph outputs (adjacency lists, edge features, node features) per data version and window to avoid recomputation across experiments. Supports both in-memory (default) and Redis backends. + +Two families of API are exposed, and both are kept because callers and tests +already depend on each: + +* ``get`` / ``set`` / ``invalidate`` take an explicit ``prefix`` and ``key`` + and are served by the configured in-memory store, or directly by Redis when + ``config.backend`` is :attr:`GraphCacheBackend.REDIS`. +* ``get_adjacency`` / ``set_adjacency`` / ``get_edge_features`` / + ``set_edge_features`` derive a stable key from the window parameters and are + served by the in-process LRU sitting in front of the shared + :class:`~astroml.cache.redis_cache.RedisCache` layer. """ from __future__ import annotations -import functools import hashlib -import json import logging +import threading from collections import OrderedDict -from typing import Any +from collections.abc import Callable +from dataclasses import dataclass +from enum import Enum +from functools import wraps +from typing import Any, TypeVar from astroml.cache.redis_cache import CacheKeyPrefix, RedisCache logger = logging.getLogger(__name__) +F = TypeVar("F", bound=Callable[..., Any]) + _ADJACENCY_PREFIX = CacheKeyPrefix.GRAPH_WINDOW _EDGE_FEATURE_PREFIX = CacheKeyPrefix.GRAPH_SNAPSHOT -# Default in-process LRU capacity (number of entries, not bytes). +# Default in-process LRU capacity (number of entries, not bytes). Used when +# ``_LRUCache`` is constructed directly and as the fallback for +# ``GraphComputationCache`` when no config-driven capacity is available. _DEFAULT_LRU_CAPACITY = 128 +# Guards creation of the ``GraphComputationCache`` singleton. +_singleton_lock = threading.Lock() + + +class GraphCacheBackend(Enum): + """Backend for graph computation cache.""" + + MEMORY = "memory" + REDIS = "redis" + + +@dataclass +class GraphCacheConfig: + """Configuration for graph computation cache.""" + + backend: GraphCacheBackend = GraphCacheBackend.MEMORY + max_size: int = 512 + default_ttl_seconds: int = 3600 # 1 hour + redis_url: str = "redis://localhost:6379" + # Per-prefix TTL overrides (seconds) + adjacency_ttl: int = 3600 + edge_feature_ttl: int = 1800 + node_feature_ttl: int = 1800 + snapshot_ttl: int = 3600 + + +@dataclass +class GraphCacheStats: + """Graph cache hit/miss statistics.""" + + hits: int = 0 + misses: int = 0 + sets: int = 0 + evictions: int = 0 + + @property + def hit_rate(self) -> float: + total = self.hits + self.misses + return self.hits / total if total > 0 else 0.0 + + def to_dict(self) -> dict[str, Any]: + return { + "hits": self.hits, + "misses": self.misses, + "sets": self.sets, + "evictions": self.evictions, + "hit_rate": self.hit_rate, + } + def _window_key(data_version: str, start_ts: int, end_ts: int, extra: str = "") -> str: """Stable cache key from window parameters.""" @@ -66,19 +122,11 @@ def set(self, key: str, value: Any) -> None: def invalidate(self, key: str) -> None: self._store.pop(key, None) - @property - def hit_rate(self) -> float: - total = self.hits + self.misses - return self.hits / total if total > 0 else 0.0 + def clear(self) -> None: + self._store.clear() - def to_dict(self) -> dict[str, Any]: - return { - "hits": self.hits, - "misses": self.misses, - "sets": self.sets, - "evictions": self.evictions, - "hit_rate": self.hit_rate, - } + def __len__(self) -> int: + return len(self._store) class _MemoryGraphStore: @@ -148,19 +196,21 @@ def size(self) -> int: class GraphComputationCache: - """Two-level cache (in-process LRU → Redis) for graph intermediate outputs. + """Two-level cache for graph computation results. - Adjacency lists and edge feature tensors/dicts can be expensive to rebuild - for large windows. This class stores them under a key derived from - ``data_version`` and the window bounds so experiments that share the same - data slice reuse the cached result. + Caches adjacency lists, edge features, node features and other + intermediate graph outputs keyed by data version and window bounds, so + experiments that share the same data slice reuse the cached result. Args: - redis_ttl_adjacency: Redis TTL for adjacency list entries in seconds + config: :class:`GraphCacheConfig` controlling the backend, the maximum + number of entries held in memory, and the per-prefix TTLs. + redis_ttl_adjacency: Redis TTL for adjacency entries in seconds (default 30 minutes). redis_ttl_edge_features: Redis TTL for edge feature entries in seconds (default 1 hour). lru_capacity: Number of entries to keep in the in-process LRU. + Defaults to ``config.max_size``. Example:: @@ -170,28 +220,53 @@ class GraphComputationCache: if adj is None: adj = build_adjacency(edges, start_ts, end_ts) cache.set_adjacency("v1.2", 1_000_000, 1_010_000, adj) + + @cache.cached_adjacency(version="v3", window="7d") + def build_adjacency_for(window_edges): + ... """ _instance: GraphComputationCache | None = None - def __new__(cls, config: GraphCacheConfig | None = None) -> GraphComputationCache: - if cls._instance is None: - cls._instance = super().__new__(cls) - cls._instance._initialized = False - return cls._instance - - def __init__(self, config: GraphCacheConfig | None = None) -> None: - if hasattr(self, "_initialized") and self._initialized: + def __new__( + cls, config: GraphCacheConfig | None = None, **kwargs: Any + ) -> GraphComputationCache: + # ``GraphComputationCache()`` is a process-wide singleton, matching the + # RedisCache layer it wraps. Constructing with an explicit config or an + # explicit tuning argument returns an independent instance, so callers + # can hold several caches with different backends or capacities side by + # side. + if config is None and not kwargs: + if cls._instance is None: + with _singleton_lock: + if cls._instance is None: + cls._instance = super().__new__(cls) + cls._instance._initialized = False + return cls._instance + instance = super().__new__(cls) + instance._initialized = False + return instance + + def __init__( + self, + config: GraphCacheConfig | None = None, + redis_ttl_adjacency: int = 1_800, + redis_ttl_edge_features: int = 3_600, + lru_capacity: int | None = None, + ) -> None: + if getattr(self, "_initialized", False): return + self.config = config or GraphCacheConfig() self._stats = GraphCacheStats() self._store: _MemoryGraphStore | None = None self._redis_client = None - self._initialized = True + self._lru: _LRUCache = _LRUCache(capacity=lru_capacity or self.config.max_size) + self._redis: RedisCache = RedisCache() + self._ttl_adj = redis_ttl_adjacency + self._ttl_ef = redis_ttl_edge_features - if self.config.backend == GraphCacheBackend.MEMORY: - self._store = _MemoryGraphStore(self.config.max_size) - elif self.config.backend == GraphCacheBackend.REDIS: + if self.config.backend == GraphCacheBackend.REDIS: try: import redis @@ -199,8 +274,12 @@ def __init__(self, config: GraphCacheConfig | None = None) -> None: self._redis_client.ping() except Exception as e: logger.warning("Redis unavailable for graph cache, falling back to memory: %s", e) - self._config.backend = GraphCacheBackend.MEMORY - self._store = _MemoryGraphStore(self.config.max_size) + self.config.backend = GraphCacheBackend.MEMORY + + if self.config.backend == GraphCacheBackend.MEMORY: + self._store = _MemoryGraphStore(self.config.max_size) + + self._initialized = True @staticmethod def _hash_args(*args: Any, **kwargs: Any) -> str: @@ -218,6 +297,10 @@ def _hash_args(*args: Any, **kwargs: Any) -> str: combined = "|".join(parts) return hashlib.md5(combined.encode()).hexdigest()[:16] + # ------------------------------------------------------------------ # + # Generic prefix:key access + # ------------------------------------------------------------------ # + def get(self, prefix: str, key: str) -> Any | None: full_key = f"{prefix}:{key}" if self.config.backend == GraphCacheBackend.REDIS and self._redis_client: @@ -304,9 +387,41 @@ def get_stats(self) -> GraphCacheStats: def reset_stats(self) -> None: self._stats = GraphCacheStats() - # -- Convenience decorators ----------------------------------------------- + # ------------------------------------------------------------------ # + # Adjacency list caching (window-parameterised) + # ------------------------------------------------------------------ # - def cached_adjacency( + def get_adjacency( + self, + data_version: str, + start_ts: int, + end_ts: int, + ) -> Any | None: + """Return a cached adjacency structure or ``None`` on miss.""" + key = self._adj_key(data_version, start_ts, end_ts) + hit = self._lru.get(key) + if hit is not None: + logger.debug("GraphComputationCache: adjacency LRU hit for %s", key[:12]) + return hit + value = self._redis.get(key) + if value is not None: + logger.debug("GraphComputationCache: adjacency Redis hit for %s", key[:12]) + self._lru.set(key, value) + return value + + def set_adjacency( + self, + data_version: str, + start_ts: int, + end_ts: int, + adjacency: Any, + ) -> None: + """Store an adjacency structure in both cache levels.""" + key = self._adj_key(data_version, start_ts, end_ts) + self._lru.set(key, adjacency) + self._redis.set(key, adjacency, ttl_seconds=self._ttl_adj) + + def invalidate_adjacency( self, data_version: str, start_ts: int, @@ -318,7 +433,7 @@ def cached_adjacency( self._redis.delete(key) # ------------------------------------------------------------------ # - # Edge feature caching + # Edge feature caching (window-parameterised) # ------------------------------------------------------------------ # def get_edge_features( @@ -341,6 +456,113 @@ def get_edge_features( return value def set_edge_features( + self, + data_version: str, + start_ts: int, + end_ts: int, + features: Any, + feature_set: str = "default", + ) -> None: + """Store edge features in both cache levels.""" + key = self._ef_key(data_version, start_ts, end_ts, feature_set) + self._lru.set(key, features) + self._redis.set(key, features, ttl_seconds=self._ttl_ef) + + def invalidate_edge_features( + self, + data_version: str, + start_ts: int, + end_ts: int, + feature_set: str = "default", + ) -> None: + """Evict edge features from both cache levels.""" + key = self._ef_key(data_version, start_ts, end_ts, feature_set) + self._lru.invalidate(key) + self._redis.delete(key) + + def invalidate_version(self, data_version: str) -> None: + """Evict all LRU entries (Redis entries expire naturally via TTL).""" + self._lru.clear() + logger.info("GraphComputationCache: LRU cleared on invalidate_version(%s)", data_version) + + @property + def lru_size(self) -> int: + """Number of entries currently in the in-process LRU.""" + return len(self._lru) + + # ------------------------------------------------------------------ # + # Private helpers + # ------------------------------------------------------------------ # + + def _adj_key(self, version: str, start: int, end: int) -> str: + digest = _window_key(version, start, end) + return f"{_ADJACENCY_PREFIX.value}:adj:{digest}" + + def _ef_key(self, version: str, start: int, end: int, feature_set: str) -> str: + digest = _window_key(version, start, end, feature_set) + return f"{_EDGE_FEATURE_PREFIX.value}:ef:{digest}" + + # -- Convenience decorators ----------------------------------------------- + + def cached_adjacency( + self, + version: str = "latest", + window: str = "7d", + ttl_seconds: int | None = None, + ) -> Callable[[F], F]: + """Cache adjacency list computation per data version and window.""" + + def decorator(func: F) -> F: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + arg_hash = self._hash_args(*args, **kwargs) + cache_key = f"adj:{version}:{window}:{arg_hash}" + cached_value = self.get("graph:adjacency", cache_key) + if cached_value is not None: + return cached_value + result = func(*args, **kwargs) + self.set( + "graph:adjacency", + cache_key, + result, + ttl_seconds or self.config.adjacency_ttl, + ) + return result + + return wrapper # type: ignore[return-value] + + return decorator + + def cached_edge_features( + self, + version: str = "latest", + window: str = "7d", + ttl_seconds: int | None = None, + ) -> Callable[[F], F]: + """Cache edge feature computation per data version and window.""" + + def decorator(func: F) -> F: + @wraps(func) + def wrapper(*args: Any, **kwargs: Any) -> Any: + arg_hash = self._hash_args(*args, **kwargs) + cache_key = f"ef:{version}:{window}:{arg_hash}" + cached_value = self.get("graph:edge_features", cache_key) + if cached_value is not None: + return cached_value + result = func(*args, **kwargs) + self.set( + "graph:edge_features", + cache_key, + result, + ttl_seconds or self.config.edge_feature_ttl, + ) + return result + + return wrapper # type: ignore[return-value] + + return decorator + + def cached_node_features( self, version: str = "latest", window: str = "7d", @@ -383,22 +605,20 @@ def get_graph_cache(config: GraphCacheConfig | None = None) -> GraphComputationC def invalidate_graph_cache(prefix: str = "", key: str | None = None) -> int: """Invalidate graph cache entries. - @property - def lru_size(self) -> int: - """Number of entries currently in the in-process LRU.""" - return len(self._lru) - - # ------------------------------------------------------------------ # - # Private helpers - # ------------------------------------------------------------------ # - - def _adj_key(self, version: str, start: int, end: int) -> str: - digest = _window_key(version, start, end) - return f"{_ADJACENCY_PREFIX.value}:adj:{digest}" + Args: + prefix: Cache prefix (e.g. ``'graph:adjacency'``). Empty string clears all. + key: Specific key within prefix. ``None`` clears all for the prefix. - def _ef_key(self, version: str, start: int, end: int, feature_set: str) -> str: - digest = _window_key(version, start, end, feature_set) - return f"{_EDGE_FEATURE_PREFIX.value}:ef:{digest}" + Returns: + Number of entries invalidated. + """ + cache = get_graph_cache() + if prefix: + return cache.invalidate(prefix, key) + count = 0 + for p in ("graph:adjacency", "graph:edge_features", "graph:node_features"): + count += cache.invalidate(p) + return count def cached_graph_computation( @@ -420,7 +640,32 @@ def cached_graph_computation( def build_adjacency(data_version: str, start_ts: int, end_ts: int): ... # expensive graph construction """ - cache = get_graph_cache() - if prefix: - return cache.invalidate(prefix, key) - return cache.clear() + _cache = cache or get_graph_cache() + + def decorator(func): # type: ignore[no-untyped-def] + @wraps(func) + def wrapper(*args, **kwargs): # type: ignore[no-untyped-def] + version = kwargs.get(data_version_arg, "unknown") + start = kwargs.get(start_ts_arg, 0) + end = kwargs.get(end_ts_arg, 0) + + key = _window_key(str(version), int(start), int(end), func.__name__) + full_key = f"graph:computation:{key}" + + cached = _cache._lru.get(full_key) + if cached is not None: + return cached + + cached = _cache._redis.get(full_key) + if cached is not None: + _cache._lru.set(full_key, cached) + return cached + + result = func(*args, **kwargs) + _cache._lru.set(full_key, result) + _cache._redis.set(full_key, result, ttl_seconds=ttl_seconds) + return result + + return wrapper + + return decorator diff --git a/astroml/cli.py b/astroml/cli.py index 0be72804..8c47c86e 100644 --- a/astroml/cli.py +++ b/astroml/cli.py @@ -1,478 +1,566 @@ - - sub = parser.add_subparsers(dest="command", required=True) - - # LLM subcommand - llm_parser = sub.add_parser( - "llm", help="LLM operations (generate, chat, rag, prompts, eval, models, cost, cache)" - ) - llm_sub = llm_parser.add_subparsers(dest="llm_command", required=True) - from .cli_llm.commands import register_llm_subcommands - - register_llm_subcommands(llm_sub) - - # Models subcommand - models_parser = sub.add_parser("models", help="Model registry commands") - models_sub = models_parser.add_subparsers(dest="subcommand", required=True) - - # Register a model - register_parser = models_sub.add_parser("register", help="Register a new model") - register_parser.add_argument("--name", required=True, help="Model name") - register_parser.add_argument("--version", required=True, help="Model version") - register_parser.add_argument("--path", required=True, help="Path to model file") - register_parser.add_argument("--owner", help="Model owner") - register_parser.add_argument("--tags", nargs="*", help="Model tags (space-separated)") - register_parser.add_argument("--mlflow-run-id", help="MLflow run ID to associate") - register_parser.add_argument("--metrics", help="Model metrics (JSON string)") - register_parser.add_argument( - "--status", - default="inactive", - choices=["inactive", "active", "deprecated"], - help="Model status", - ) - - # Add a version - version_parser = models_sub.add_parser("version", help="Add a new version to a model") - version_parser.add_argument("--model-name", required=True, help="Model name") - version_parser.add_argument("--version", required=True, help="New version number") - version_parser.add_argument("--path", required=True, help="Path to model file") - version_parser.add_argument("--owner", help="Model owner") - version_parser.add_argument("--tags", nargs="*", help="Model tags (space-separated)") - version_parser.add_argument("--mlflow-run-id", help="MLflow run ID to associate") - version_parser.add_argument("--metrics", help="Model metrics (JSON string)") - version_parser.add_argument( - "--status", - default="inactive", - choices=["inactive", "active", "deprecated"], - help="Model status", - ) - - # Load run metadata - load_parser = models_sub.add_parser( - "load-metadata", help="Load MLflow run metadata for a model version" - ) - load_parser.add_argument("--model-name", required=True, help="Model name") - load_parser.add_argument("--version", required=True, help="Model version") - - # Transition version status - transition_parser = models_sub.add_parser( - "transition", help="Transition a model version status" - ) - transition_parser.add_argument("--model-name", required=True, help="Model name") - transition_parser.add_argument("--version", required=True, help="Model version") - transition_parser.add_argument( - "--stage", - required=True, - choices=["inactive", "active", "deprecated"], - help="Target status/stage", - ) - - # List models - list_parser = models_sub.add_parser("list", help="List registered models") - list_parser.add_argument("--owner", help="Filter by owner") - list_parser.add_argument("--tags", nargs="*", help="Filter by tags (space-separated)") - list_parser.add_argument("--name", help="Filter by model name") - list_parser.add_argument("--status", help="Filter by status") - list_parser.add_argument("--page", type=int, default=1, help="Page number") - list_parser.add_argument("--page-size", type=int, default=20, help="Items per page") - - # Compare models - compare_parser = models_sub.add_parser("compare", help="Compare model versions") - compare_parser.add_argument("--model-name", required=True, help="Model name") - compare_parser.add_argument("--version1", required=True, help="First version to compare") - compare_parser.add_argument("--version2", required=True, help="Second version to compare") - - ingest = sub.add_parser("ingest", help="Incremental ingestion of ledgers") - ingest.add_argument("--start", type=int, default=None, help="Start ledger id (inclusive)") - ingest.add_argument("--end", type=int, default=None, help="End ledger id (inclusive)") - ingest.add_argument( - "--state-file", - type=str, - default=None, - help="Path to state file (defaults to ./.astroml_state/ingestion_state.json)", - ) - - config = sub.add_parser("config", help="Configuration management") - config.add_argument( - "--print-db", - action="store_true", - help="Print effective database configuration", - ) - config.add_argument( - "--dry-run", - action="store_true", - help="Validate all configuration without starting services", - ) - config.add_argument( - "--verbose", - action="store_true", - help="Show detailed validation output (use with --dry-run)", - ) - - quickstart = sub.add_parser( - "quickstart", - help="Run quick start: ingestion → graph → train pipeline with sample data", - ) - quickstart.add_argument( - "--num-ledgers", - type=int, - default=100, - help="Number of sample ledgers to generate (default: 100)", - ) - quickstart.add_argument( - "--num-accounts", - type=int, - default=50, - help="Number of sample accounts (default: 50)", - ) - quickstart.add_argument( - "--epochs", - type=int, - default=10, - help="Training epochs (default: 10)", - ) - quickstart.add_argument( - "--seed", - type=int, - default=42, - help="Random seed for reproducibility (default: 42)", - ) - - preprocess = sub.add_parser( - "preprocess-backfill", - help="Preprocess large ledger backfill datasets using Polars", - ) - preprocess.add_argument( - "--input", - required=True, - help="Input file or directory (csv, parquet, ndjson/jsonl).", - ) - preprocess.add_argument( - "--output", - required=True, - help="Output Parquet path.", - ) - preprocess.add_argument( - "--input-format", - choices=["parquet", "csv", "ndjson", "jsonl"], - default=None, - help="Optional explicit input format.", - ) - - args = parser.parse_args(argv) - - # Wire the top-level --env flag into ASTROML_ENV so downstream loaders - # (see docs/api/configuration.md) see the requested environment. - # Do not overwrite an env var the operator already set explicitly. - if args.env and "ASTROML_ENV" not in os.environ: - os.environ["ASTROML_ENV"] = args.env - - if args.command == "ingest": - store = StateStore(path=args.state_file) if args.state_file else StateStore() - service = IngestionService(state_store=store) - - # Example fetch/process functions; in real usage, users would customize/import - def fetch_fn(ledger_id: int): - # Placeholder fetch, replace with real data retrieval - return {"ledger": ledger_id, "data": f"payload-{ledger_id}"} - - def process_fn(ledger_id: int, payload: dict): - # Placeholder processing; replace with DB writes or other side effects - # For CLI visibility we do minimal printing; real apps would use logging - print(f"processed ledger {ledger_id}") - - result = service.ingest( - start_ledger=args.start, - end_ledger=args.end, - fetch_fn=fetch_fn, - process_fn=process_fn, - ) - print( - json.dumps( - { - "attempted": result.attempted, - "processed": result.processed, - "skipped": result.skipped, - }, - indent=2, - ) - ) - return 0 - - if args.command == "config": - if args.dry_run: - from astroml.config_dry_run import run_dry_run - - result = run_dry_run( - config_path=args.config, - verbose=args.verbose, - ) - if not args.verbose: - if result["valid"]: - print("Configuration validation: PASS") - else: - print("Configuration validation: FAIL") - for r in result["results"]: - for error in r.errors: - print(f" ERROR: {error}") - for warning in r.warnings: - print(f" WARN: {warning}") - return result["exit_code"] - - if args.print_db: - try: - db_config = load_database_config(args.config) - print("Effective database configuration:") - print( - json.dumps( - { - "host": db_config.host, - "port": db_config.port, - "name": db_config.name, - "user": db_config.user, - "password": "***" if db_config.password else "", - "url": db_config.to_url(), - }, - indent=2, - ) - ) - return 0 - except FileNotFoundError as e: - print(f"Error: {e}") - return 1 - except Exception as e: - print(f"Error loading config: {e}") - return 1 - else: - config.print_help() - return 1 - - if args.command == "quickstart": - from .quick_start import QuickStartConfig, run_quickstart - - # Update config with CLI arguments - QuickStartConfig.NUM_SAMPLE_LEDGERS = args.num_ledgers - QuickStartConfig.NUM_ACCOUNTS = args.num_accounts - QuickStartConfig.TRAIN_EPOCHS = args.epochs - QuickStartConfig.RANDOM_SEED = args.seed - - return run_quickstart() - - if args.command == "preprocess-backfill": - from .preprocessing.ledger_backfill import preprocess_to_parquet - - output_path = preprocess_to_parquet( - input_path=args.input, - output_path=args.output, - input_format=args.input_format, - ) - print(json.dumps({"output": str(output_path)}, indent=2)) - return 0 - - if args.command == "models": - db = _sync_session_factory()() - - if args.subcommand == "register" or args.subcommand == "version": - name = args.name if args.subcommand == "register" else args.model_name - metrics = json.loads(args.metrics) if args.metrics else None - existing = db.scalar( - select(ModelRegistry).where( - ModelRegistry.name == name, ModelRegistry.version == args.version - ) - ) - if existing: - print(f"Error: Model '{name}' version '{args.version}' already exists") - return 1 - - entry = ModelRegistry( - name=name, - version=args.version, - path=args.path, - owner=args.owner, - tags=args.tags, - mlflow_run_id=args.mlflow_run_id, - metrics=metrics, - status=args.status, - ) - db.add(entry) - db.commit() - db.refresh(entry) - print( - json.dumps( - { - "id": entry.id, - "name": entry.name, - "version": entry.version, - "path": entry.path, - "owner": entry.owner, - "tags": entry.tags, - "mlflow_run_id": entry.mlflow_run_id, - "status": entry.status, - "created_at": entry.created_at.isoformat(), - }, - indent=2, - ) - ) - return 0 - - elif args.subcommand == "transition": - entry = db.scalar( - select(ModelRegistry).where( - ModelRegistry.name == args.model_name, ModelRegistry.version == args.version - ) - ) - if not entry: - print(f"Error: Model '{args.model_name}' version '{args.version}' not found") - return 1 - - if args.stage == "active": - db.execute( - update(ModelRegistry) - .where(ModelRegistry.name == args.model_name, ModelRegistry.id != entry.id) - .values(status="inactive") - ) - - entry.status = args.stage - db.commit() - db.refresh(entry) - print( - json.dumps( - { - "id": entry.id, - "name": entry.name, - "version": entry.version, - "status": entry.status, - }, - indent=2, - ) - ) - return 0 - - elif args.subcommand == "list": - query = select(ModelRegistry) - if args.name: - query = query.where(ModelRegistry.name == args.name) - if args.status: - query = query.where(ModelRegistry.status == args.status) - if args.owner: - query = query.where(ModelRegistry.owner == args.owner) - if args.tags: - for tag in args.tags: - query = query.where(ModelRegistry.tags.contains([tag])) - - # Count total - count_query = select(func.count()).select_from(query.subquery()) - total = db.scalar(count_query) or 0 - - # Paginate - offset = (args.page - 1) * args.page_size - query = ( - query.order_by(ModelRegistry.created_at.desc()).offset(offset).limit(args.page_size) - ) - rows = db.scalars(query).all() - - result = { - "page": args.page, - "page_size": args.page_size, - "total": total, - "data": [ - { - "id": row.id, - "name": row.name, - "version": row.version, - "path": row.path, - "owner": row.owner, - "tags": row.tags, - "mlflow_run_id": row.mlflow_run_id, - "status": row.status, - "created_at": row.created_at.isoformat(), - } - for row in rows - ], - } - print(json.dumps(result, indent=2)) - return 0 - - elif args.subcommand == "compare": - v1 = db.scalar( - select(ModelRegistry).where( - ModelRegistry.name == args.model_name, ModelRegistry.version == args.version1 - ) - ) - v2 = db.scalar( - select(ModelRegistry).where( - ModelRegistry.name == args.model_name, ModelRegistry.version == args.version2 - ) - ) - - if not v1: - print(f"Error: Model '{args.model_name}' version '{args.version1}' not found") - return 1 - if not v2: - print(f"Error: Model '{args.model_name}' version '{args.version2}' not found") - return 1 - - comparison = { - "models": [ - { - "id": v1.id, - "name": v1.name, - "version": v1.version, - "mlflow_run_id": v1.mlflow_run_id, - "metrics": v1.metrics, - }, - { - "id": v2.id, - "name": v2.name, - "version": v2.version, - "mlflow_run_id": v2.mlflow_run_id, - "metrics": v2.metrics, - }, - ], - "metrics_diff": {}, - } - - # Show metric differences - all_metrics = set() - if v1.metrics: - all_metrics.update(v1.metrics.keys()) - if v2.metrics: - all_metrics.update(v2.metrics.keys()) - - for key in all_metrics: - val1 = v1.metrics.get(key) if v1.metrics else None - val2 = v2.metrics.get(key) if v2.metrics else None - comparison["metrics_diff"][key] = {"version1": val1, "version2": val2} - - print(json.dumps(comparison, indent=2)) - return 0 - - elif args.subcommand == "load-metadata": - # Use MLflowTracker to load metadata - try: - from .tracking.mlflow_tracker import MLflowTracker - - tracker = MLflowTracker(enabled=True) - metadata = tracker.load_run_metadata(args.model_name, args.version) - if metadata: - print(json.dumps(metadata, indent=2, default=str)) - return 0 - else: - print("No metadata found") - return 1 - except ImportError as e: - print(f"Error: MLflow not available: {e}") - return 1 - - if args.command == "llm": - if hasattr(args, "func"): - args.func(args) - return 0 - llm_parser.print_help() - return 1 - - parser.print_help() - return 1 - - -if __name__ == "__main__": - raise SystemExit(main()) +from __future__ import annotations + +import argparse +import json +import os +import pathlib +from typing import Optional + +from sqlalchemy import func, select, update + +from api.database import _sync_session_factory +from api.models.orm import ModelRegistry + +from .db.session import load_database_config +from .ingestion.service import IngestionService +from .ingestion.state import StateStore + +CLI_DESCRIPTION = """\ +AstroML utilities CLI — manage ingestion, configuration, and the +quick-start pipeline from a single entrypoint. + +For full usage, see the README "Usage" section: + https://github.com/Traqora/astroml#usage +""" + +CLI_EPILOG = """\ +Examples: + # Run incremental ingestion for a ledger range + python -m astroml.cli ingest --start 1000 --end 1100 + + # Print the effective database configuration that AstroML will use + python -m astroml.cli config --print-db + + # Same, but read the YAML config from a custom path + python -m astroml.cli --config ./custom/database.yaml config --print-db + + # Run the end-to-end quick start with sample data + python -m astroml.cli quickstart --num-ledgers 200 --epochs 5 + + # Preprocess a backfill dataset into Parquet + python -m astroml.cli preprocess-backfill --input data.csv --output out.parquet + + # Select a runtime environment (sets ASTROML_ENV for downstream loaders) + python -m astroml.cli --env production config --print-db + +Environment variables: + ASTROML_DATABASE_URL Overrides the database URL from config/database.yaml. + ASTROML_ENV Runtime environment name (development | production). + Set automatically by --env when provided. +""" + + +def main(argv: Optional[list[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="astroml", + description=CLI_DESCRIPTION, + epilog=CLI_EPILOG, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "--config", + type=pathlib.Path, + default=None, + metavar="PATH", + help=( + "Path to the database YAML config (default: config/database.yaml). " + "Used by `config --print-db` and any subcommand that reads the " + "database configuration." + ), + ) + parser.add_argument( + "--env", + type=str, + default=None, + metavar="NAME", + help=( + "Runtime environment name (e.g., development, production). " + "When provided, sets ASTROML_ENV for downstream loaders unless " + "ASTROML_ENV is already set in the process environment." + ), + ) + + sub = parser.add_subparsers(dest="command", required=True) + + # LLM subcommand + llm_parser = sub.add_parser( + "llm", + help="LLM operations (generate, chat, rag, prompts, eval, models, cost, cache)", + ) + llm_sub = llm_parser.add_subparsers(dest="llm_command", required=True) + from .cli_llm.commands import register_llm_subcommands + + register_llm_subcommands(llm_sub) + + # Models subcommand + models_parser = sub.add_parser("models", help="Model registry commands") + models_sub = models_parser.add_subparsers(dest="subcommand", required=True) + + # Register a model + register_parser = models_sub.add_parser("register", help="Register a new model") + register_parser.add_argument("--name", required=True, help="Model name") + register_parser.add_argument("--version", required=True, help="Model version") + register_parser.add_argument("--path", required=True, help="Path to model file") + register_parser.add_argument("--owner", help="Model owner") + register_parser.add_argument("--tags", nargs="*", help="Model tags (space-separated)") + register_parser.add_argument("--mlflow-run-id", help="MLflow run ID to associate") + register_parser.add_argument("--metrics", help="Model metrics (JSON string)") + register_parser.add_argument( + "--status", + default="inactive", + choices=["inactive", "active", "deprecated"], + help="Model status", + ) + + # Add a version + version_parser = models_sub.add_parser("version", help="Add a new version to a model") + version_parser.add_argument("--model-name", required=True, help="Model name") + version_parser.add_argument("--version", required=True, help="New version number") + version_parser.add_argument("--path", required=True, help="Path to model file") + version_parser.add_argument("--owner", help="Model owner") + version_parser.add_argument("--tags", nargs="*", help="Model tags (space-separated)") + version_parser.add_argument("--mlflow-run-id", help="MLflow run ID to associate") + version_parser.add_argument("--metrics", help="Model metrics (JSON string)") + version_parser.add_argument( + "--status", + default="inactive", + choices=["inactive", "active", "deprecated"], + help="Model status", + ) + + # Load run metadata + load_parser = models_sub.add_parser( + "load-metadata", help="Load MLflow run metadata for a model version" + ) + load_parser.add_argument("--model-name", required=True, help="Model name") + load_parser.add_argument("--version", required=True, help="Model version") + + # Transition version status + transition_parser = models_sub.add_parser( + "transition", help="Transition a model version status" + ) + transition_parser.add_argument("--model-name", required=True, help="Model name") + transition_parser.add_argument("--version", required=True, help="Model version") + transition_parser.add_argument( + "--stage", + required=True, + choices=["inactive", "active", "deprecated"], + help="Target status/stage", + ) + + # List models + list_parser = models_sub.add_parser("list", help="List registered models") + list_parser.add_argument("--owner", help="Filter by owner") + list_parser.add_argument("--tags", nargs="*", help="Filter by tags (space-separated)") + list_parser.add_argument("--name", help="Filter by model name") + list_parser.add_argument("--status", help="Filter by status") + list_parser.add_argument("--page", type=int, default=1, help="Page number") + list_parser.add_argument("--page-size", type=int, default=20, help="Items per page") + + # Compare models + compare_parser = models_sub.add_parser("compare", help="Compare model versions") + compare_parser.add_argument("--model-name", required=True, help="Model name") + compare_parser.add_argument("--version1", required=True, help="First version to compare") + compare_parser.add_argument("--version2", required=True, help="Second version to compare") + + ingest = sub.add_parser("ingest", help="Incremental ingestion of ledgers") + ingest.add_argument("--start", type=int, default=None, help="Start ledger id (inclusive)") + ingest.add_argument("--end", type=int, default=None, help="End ledger id (inclusive)") + ingest.add_argument( + "--state-file", + type=str, + default=None, + help="Path to state file (defaults to ./.astroml_state/ingestion_state.json)", + ) + + config = sub.add_parser("config", help="Configuration management") + config.add_argument( + "--print-db", + action="store_true", + help="Print effective database configuration", + ) + config.add_argument( + "--dry-run", + action="store_true", + help="Validate all configuration without starting services", + ) + config.add_argument( + "--verbose", + action="store_true", + help="Show detailed validation output (use with --dry-run)", + ) + + quickstart = sub.add_parser( + "quickstart", + help="Run quick start: ingestion → graph → train pipeline with sample data", + ) + quickstart.add_argument( + "--num-ledgers", + type=int, + default=100, + help="Number of sample ledgers to generate (default: 100)", + ) + quickstart.add_argument( + "--num-accounts", + type=int, + default=50, + help="Number of sample accounts (default: 50)", + ) + quickstart.add_argument( + "--epochs", + type=int, + default=10, + help="Training epochs (default: 10)", + ) + quickstart.add_argument( + "--seed", + type=int, + default=42, + help="Random seed for reproducibility (default: 42)", + ) + + preprocess = sub.add_parser( + "preprocess-backfill", + help="Preprocess large ledger backfill datasets using Polars", + ) + preprocess.add_argument( + "--input", + required=True, + help="Input file or directory (csv, parquet, ndjson/jsonl).", + ) + preprocess.add_argument( + "--output", + required=True, + help="Output Parquet path.", + ) + preprocess.add_argument( + "--input-format", + choices=["parquet", "csv", "ndjson", "jsonl"], + default=None, + help="Optional explicit input format.", + ) + + args = parser.parse_args(argv) + + # Wire the top-level --env flag into ASTROML_ENV so downstream loaders + # (see docs/api/configuration.md) see the requested environment. + # Do not overwrite an env var the operator already set explicitly. + if args.env and "ASTROML_ENV" not in os.environ: + os.environ["ASTROML_ENV"] = args.env + + if args.command == "ingest": + store = StateStore(path=args.state_file) if args.state_file else StateStore() + service = IngestionService(state_store=store) + + # Example fetch/process functions; in real usage, users would customize/import + def fetch_fn(ledger_id: int): + # Placeholder fetch, replace with real data retrieval + return {"ledger": ledger_id, "data": f"payload-{ledger_id}"} + + def process_fn(ledger_id: int, payload: dict): + # Placeholder processing; replace with DB writes or other side effects + # For CLI visibility we do minimal printing; real apps would use logging + print(f"processed ledger {ledger_id}") + + result = service.ingest( + start_ledger=args.start, + end_ledger=args.end, + fetch_fn=fetch_fn, + process_fn=process_fn, + ) + print( + json.dumps( + { + "attempted": result.attempted, + "processed": result.processed, + "skipped": result.skipped, + }, + indent=2, + ) + ) + return 0 + + if args.command == "config": + if args.dry_run: + from astroml.config_dry_run import run_dry_run + + result = run_dry_run( + config_path=args.config, + verbose=args.verbose, + ) + if not args.verbose: + if result["valid"]: + print("Configuration validation: PASS") + else: + print("Configuration validation: FAIL") + for r in result["results"]: + for error in r.errors: + print(f" ERROR: {error}") + for warning in r.warnings: + print(f" WARN: {warning}") + return result["exit_code"] + + if args.print_db: + try: + db_config = load_database_config(args.config) + print("Effective database configuration:") + print( + json.dumps( + { + "host": db_config.host, + "port": db_config.port, + "name": db_config.name, + "user": db_config.user, + "password": "***" if db_config.password else "", + "url": db_config.to_url(), + }, + indent=2, + ) + ) + return 0 + except FileNotFoundError as e: + print(f"Error: {e}") + return 1 + except Exception as e: + print(f"Error loading config: {e}") + return 1 + else: + config.print_help() + return 1 + + if args.command == "quickstart": + from .quick_start import QuickStartConfig, run_quickstart + + # Update config with CLI arguments + QuickStartConfig.NUM_SAMPLE_LEDGERS = args.num_ledgers + QuickStartConfig.NUM_ACCOUNTS = args.num_accounts + QuickStartConfig.TRAIN_EPOCHS = args.epochs + QuickStartConfig.RANDOM_SEED = args.seed + + return run_quickstart() + + if args.command == "preprocess-backfill": + from .preprocessing.ledger_backfill import preprocess_to_parquet + + output_path = preprocess_to_parquet( + input_path=args.input, + output_path=args.output, + input_format=args.input_format, + ) + print(json.dumps({"output": str(output_path)}, indent=2)) + return 0 + + if args.command == "models": + db = _sync_session_factory()() + + if args.subcommand == "register" or args.subcommand == "version": + name = args.name if args.subcommand == "register" else args.model_name + metrics = json.loads(args.metrics) if args.metrics else None + existing = db.scalar( + select(ModelRegistry).where( + ModelRegistry.name == name, ModelRegistry.version == args.version + ) + ) + if existing: + print(f"Error: Model '{name}' version '{args.version}' already exists") + return 1 + + entry = ModelRegistry( + name=name, + version=args.version, + path=args.path, + owner=args.owner, + tags=args.tags, + mlflow_run_id=args.mlflow_run_id, + metrics=metrics, + status=args.status, + ) + db.add(entry) + db.commit() + db.refresh(entry) + print( + json.dumps( + { + "id": entry.id, + "name": entry.name, + "version": entry.version, + "path": entry.path, + "owner": entry.owner, + "tags": entry.tags, + "mlflow_run_id": entry.mlflow_run_id, + "status": entry.status, + "created_at": entry.created_at.isoformat(), + }, + indent=2, + ) + ) + return 0 + + elif args.subcommand == "transition": + entry = db.scalar( + select(ModelRegistry).where( + ModelRegistry.name == args.model_name, + ModelRegistry.version == args.version, + ) + ) + if not entry: + print(f"Error: Model '{args.model_name}' version '{args.version}' not found") + return 1 + + if args.stage == "active": + db.execute( + update(ModelRegistry) + .where( + ModelRegistry.name == args.model_name, + ModelRegistry.id != entry.id, + ) + .values(status="inactive") + ) + + entry.status = args.stage + db.commit() + db.refresh(entry) + print( + json.dumps( + { + "id": entry.id, + "name": entry.name, + "version": entry.version, + "status": entry.status, + }, + indent=2, + ) + ) + return 0 + + elif args.subcommand == "list": + query = select(ModelRegistry) + if args.name: + query = query.where(ModelRegistry.name == args.name) + if args.status: + query = query.where(ModelRegistry.status == args.status) + if args.owner: + query = query.where(ModelRegistry.owner == args.owner) + if args.tags: + for tag in args.tags: + query = query.where(ModelRegistry.tags.contains([tag])) + + # Count total + count_query = select(func.count()).select_from(query.subquery()) + total = db.scalar(count_query) or 0 + + # Paginate + offset = (args.page - 1) * args.page_size + query = ( + query.order_by(ModelRegistry.created_at.desc()).offset(offset).limit(args.page_size) + ) + rows = db.scalars(query).all() + + result = { + "page": args.page, + "page_size": args.page_size, + "total": total, + "data": [ + { + "id": row.id, + "name": row.name, + "version": row.version, + "path": row.path, + "owner": row.owner, + "tags": row.tags, + "mlflow_run_id": row.mlflow_run_id, + "status": row.status, + "created_at": row.created_at.isoformat(), + } + for row in rows + ], + } + print(json.dumps(result, indent=2)) + return 0 + + elif args.subcommand == "compare": + v1 = db.scalar( + select(ModelRegistry).where( + ModelRegistry.name == args.model_name, + ModelRegistry.version == args.version1, + ) + ) + v2 = db.scalar( + select(ModelRegistry).where( + ModelRegistry.name == args.model_name, + ModelRegistry.version == args.version2, + ) + ) + + if not v1: + print(f"Error: Model '{args.model_name}' version '{args.version1}' not found") + return 1 + if not v2: + print(f"Error: Model '{args.model_name}' version '{args.version2}' not found") + return 1 + + comparison = { + "models": [ + { + "id": v1.id, + "name": v1.name, + "version": v1.version, + "mlflow_run_id": v1.mlflow_run_id, + "metrics": v1.metrics, + }, + { + "id": v2.id, + "name": v2.name, + "version": v2.version, + "mlflow_run_id": v2.mlflow_run_id, + "metrics": v2.metrics, + }, + ], + "metrics_diff": {}, + } + + # Show metric differences + all_metrics = set() + if v1.metrics: + all_metrics.update(v1.metrics.keys()) + if v2.metrics: + all_metrics.update(v2.metrics.keys()) + + for key in all_metrics: + val1 = v1.metrics.get(key) if v1.metrics else None + val2 = v2.metrics.get(key) if v2.metrics else None + comparison["metrics_diff"][key] = {"version1": val1, "version2": val2} + + print(json.dumps(comparison, indent=2)) + return 0 + + elif args.subcommand == "load-metadata": + # Use MLflowTracker to load metadata + try: + from .tracking.mlflow_tracker import MLflowTracker + + tracker = MLflowTracker(enabled=True) + metadata = tracker.load_run_metadata(args.model_name, args.version) + if metadata: + print(json.dumps(metadata, indent=2, default=str)) + return 0 + else: + print("No metadata found") + return 1 + except ImportError as e: + print(f"Error: MLflow not available: {e}") + return 1 + + if args.command == "llm": + if hasattr(args, "func"): + args.func(args) + return 0 + llm_parser.print_help() + return 1 + + parser.print_help() + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/astroml/ingestion/normalizer.py b/astroml/ingestion/normalizer.py index 8328240e..a67a99b3 100644 --- a/astroml/ingestion/normalizer.py +++ b/astroml/ingestion/normalizer.py @@ -128,6 +128,16 @@ def snapshot_transaction(tx: NormalizedTransaction) -> dict[str, Any]: Dict with the normalized fields; ``timestamp`` is ISO-8601 and ``amount`` is a float (or None). """ + return { + "transaction_hash": tx.transaction_hash, + "sender": tx.sender, + "receiver": tx.receiver, + "asset": tx.asset, + "amount": float(tx.amount) if tx.amount is not None else None, + "timestamp": tx.timestamp.isoformat(), + } + + # --------------------------------------------------------------------------- # CLI — issue #990 # --------------------------------------------------------------------------- @@ -174,17 +184,6 @@ def restore_transaction(snapshot: dict[str, Any]) -> NormalizedTransaction: Args: snapshot: Snapshot dict containing every normalized field. -_RECORD_FIELDS = ("transaction_hash", "sender", "receiver", "asset", "amount", "timestamp") - - -def restore_record(record: dict[str, Any]) -> NormalizedTransaction: - """Restore a NormalizedTransaction from a CLI output record (issue #985). - - Inverse of the JSON records printed by :func:`main`, so a normalized - snapshot written to disk can be reloaded without re-fetching Horizon. - - Args: - record: One decoded JSON record as emitted by the CLI. Returns: A new, unpersisted NormalizedTransaction. @@ -204,6 +203,24 @@ def restore_record(record: dict[str, Any]) -> NormalizedTransaction: amount=float(amount) if amount is not None else None, timestamp=datetime.fromisoformat(snapshot["timestamp"]), ) + + +_RECORD_FIELDS = ("transaction_hash", "sender", "receiver", "asset", "amount", "timestamp") + + +def restore_record(record: dict[str, Any]) -> NormalizedTransaction: + """Restore a NormalizedTransaction from a CLI output record (issue #985). + + Inverse of the JSON records printed by :func:`main`, so a normalized + snapshot written to disk can be reloaded without re-fetching Horizon. + + Args: + record: One decoded JSON record as emitted by the CLI. + + Returns: + A new, unpersisted NormalizedTransaction. + + Raises: ValueError: if a field is missing or the timestamp is not ISO-8601. """ missing = [f for f in _RECORD_FIELDS if f not in record] From a8d2c77ea2fa8a1030b7dec5f1a6f5ea706688c6 Mon Sep 17 00:00:00 2001 From: YazarAyobami Date: Sat, 26 Sep 2026 11:32:34 +0100 Subject: [PATCH 5/6] style(ingestion): sort imports in the #728 idempotency test for ruff I001 --- tests/ingestion/test_normalized_idempotency.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/ingestion/test_normalized_idempotency.py b/tests/ingestion/test_normalized_idempotency.py index 295c12ed..bafba183 100644 --- a/tests/ingestion/test_normalized_idempotency.py +++ b/tests/ingestion/test_normalized_idempotency.py @@ -15,7 +15,6 @@ from __future__ import annotations - import pytest from sqlalchemy import create_engine, func, select from sqlalchemy.exc import IntegrityError From ad48bdc02199d084b9fc584c8858ebd4187197bd Mon Sep 17 00:00:00 2001 From: YazarAyobami Date: Sat, 26 Sep 2026 11:32:37 +0100 Subject: [PATCH 6/6] feat(ci): fail builds on leaked or unaudited secrets Closes #720. `detect-secrets scan --baseline` only reports; it exits 0 even when new secrets appear, so the CI secret scanning job could never actually block a leak, and secrets whitelisted in the baseline with no audit decision silently passed forever. Add astroml/ci/secrets_gate.py, which diffs the live scan against .secrets.baseline and exits 1 when it finds (a) detections not in the baseline, (b) baseline entries with no audit decision, or (c) baseline entries audited as true secrets; exit 2 signals the scanner itself broke. Wire it as a local pre-commit hook and `make secrets-scan`, pin detect-secrets>=1.4.0 in requirements-dev.txt (it was used by the hook but never declared), and re-audit .secrets.baseline (92 detections across 70 files, all reviewed placeholders/test fixtures, recorded with is_secret=False notes). SECRETS_SCANNING_GUIDE.md documents the gate. 12 unit tests cover both baseline file formats, the audit decisions, and the CLI exit codes end-to-end, including that the gate never mutates the baseline. --- .pre-commit-config.yaml | 9 + .secrets.baseline | 2094 ++++++++++++++++++++++++++++++++- Makefile | 4 +- SECRETS_SCANNING_GUIDE.md | 29 +- astroml/ci/secrets_gate.py | 178 +++ requirements-dev.txt | 1 + tests/ci/__init__.py | 0 tests/ci/test_secrets_gate.py | 156 +++ 8 files changed, 2453 insertions(+), 18 deletions(-) create mode 100644 astroml/ci/secrets_gate.py create mode 100644 tests/ci/__init__.py create mode 100644 tests/ci/test_secrets_gate.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 179b1043..90f629d7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,6 +19,15 @@ repos: args: [--baseline, .secrets.baseline] exclude: package.lock.json|go.sum|pnpm-lock.yaml|yarn.lock|poetry.lock + - repo: local + hooks: + - id: secrets-gate + name: Secrets gate — fail on leaks and unaudited baseline entries (#720) + entry: python -m astroml.ci.secrets_gate --baseline .secrets.baseline + language: system + always_run: true + pass_filenames: false + - repo: local hooks: - id: radon diff --git a/.secrets.baseline b/.secrets.baseline index 01923b84..a662ba88 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -1,20 +1,1256 @@ { - "generated_at": "2024-01-01T00:00:00Z", + "audit": { + ".env.example": { + "632d8eb9ee5be70b5448c03a10544b62f577ad60": [ + { + "filename": ".env.example", + "hashed_secret": "632d8eb9ee5be70b5448c03a10544b62f577ad60", + "is_secret": false, + "is_verified": false, + "line_number": 11, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + ".github/workflows/ci.yml": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": ".github/workflows/ci.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 25, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + }, + { + "filename": ".github/workflows/ci.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 44, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + ".github/workflows/e2e-tests.yml": { + "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3": [ + { + "filename": ".github/workflows/e2e-tests.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_secret": false, + "is_verified": false, + "line_number": 21, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + }, + { + "filename": ".github/workflows/e2e-tests.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_secret": false, + "is_verified": false, + "line_number": 58, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + ".github/workflows/nightly.yml": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": ".github/workflows/nightly.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 123, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + }, + { + "filename": ".github/workflows/nightly.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 159, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "DOCKER_QUICK_REFERENCE.md": { + "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8": [ + { + "filename": "DOCKER_QUICK_REFERENCE.md", + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_secret": false, + "is_verified": false, + "line_number": 128, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "E2E_TESTING_GUIDE.md": { + "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3": [ + { + "filename": "E2E_TESTING_GUIDE.md", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_secret": false, + "is_verified": false, + "line_number": 81, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "PR_MESSAGE.md": { + "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3": [ + { + "filename": "PR_MESSAGE.md", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_secret": false, + "is_verified": false, + "line_number": 242, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "README.md": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": "README.md", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 367, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "SECRETS_SCANNING_GUIDE.md": { + "19fc48b762dc922d126f0d0d7e5274e93212b5e7": [ + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "19fc48b762dc922d126f0d0d7e5274e93212b5e7", + "is_secret": false, + "is_verified": false, + "line_number": 109, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ], + "25910f981e85ca04baf359199dd0bd4a3ae738b6": [ + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "25910f981e85ca04baf359199dd0bd4a3ae738b6", + "is_secret": false, + "is_verified": false, + "line_number": 270, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "AWS Access Key" + } + ], + "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684": [ + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_secret": false, + "is_verified": false, + "line_number": 161, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ], + "d247e54e14ab3298d7b979f10a70fa8d380ffeec": [ + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "d247e54e14ab3298d7b979f10a70fa8d380ffeec", + "is_secret": false, + "is_verified": false, + "line_number": 147, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "api/database.py": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": "api/database.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 111, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "api/routers/accounts.py": { + "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64": [ + { + "filename": "api/routers/accounts.py", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_secret": false, + "is_verified": false, + "line_number": 190, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "a3d2709ddb4695bf7c836222de3fcdba279a129c": [ + { + "filename": "api/routers/accounts.py", + "hashed_secret": "a3d2709ddb4695bf7c836222de3fcdba279a129c", + "is_secret": false, + "is_verified": false, + "line_number": 188, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "api/routers/backup.py": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": "api/routers/backup.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 80, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "api/routers/v1/backup.py": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": "api/routers/v1/backup.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 80, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "api/schemas/__init__.py": { + "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64": [ + { + "filename": "api/schemas/__init__.py", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_secret": false, + "is_verified": false, + "line_number": 38, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "bffd31c8a849c72e349c658d0c6382ee10e4c58e": [ + { + "filename": "api/schemas/__init__.py", + "hashed_secret": "bffd31c8a849c72e349c658d0c6382ee10e4c58e", + "is_secret": false, + "is_verified": false, + "line_number": 44, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "api/tests/conftest.py": { + "a14cdcfcd4700ffb2f5de51a5ff19a97e2384237": [ + { + "filename": "api/tests/conftest.py", + "hashed_secret": "a14cdcfcd4700ffb2f5de51a5ff19a97e2384237", + "is_secret": false, + "is_verified": false, + "line_number": 120, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "api/tests/test_api_key_rotation.py": { + "25ab86bed149ca6ca9c1c0d5db7c9a91388ddeab": [ + { + "filename": "api/tests/test_api_key_rotation.py", + "hashed_secret": "25ab86bed149ca6ca9c1c0d5db7c9a91388ddeab", + "is_secret": false, + "is_verified": false, + "line_number": 42, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "api/tests/test_auth.py": { + "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4": [ + { + "filename": "api/tests/test_auth.py", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_secret": false, + "is_verified": false, + "line_number": 39, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "api/tests/test_orm_models.py": { + "ff55f8ab1c3d25394048cbef0bac18ef763a60ed": [ + { + "filename": "api/tests/test_orm_models.py", + "hashed_secret": "ff55f8ab1c3d25394048cbef0bac18ef763a60ed", + "is_secret": false, + "is_verified": false, + "line_number": 75, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "astroml/api/app.py": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": "astroml/api/app.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 43, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "astroml/api/routers/accounts.py": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": "astroml/api/routers/accounts.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 27, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "astroml/api/routers/fraud.py": { + "bf0a737434ab6c2fedb31a2a084eae04597f5de0": [ + { + "filename": "astroml/api/routers/fraud.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_secret": false, + "is_verified": false, + "line_number": 30, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "astroml/backup/service.py": { + "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684": [ + { + "filename": "astroml/backup/service.py", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_secret": false, + "is_verified": false, + "line_number": 130, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "astroml/ingestion/tests/test_enhanced_stream.py": { + "6740d1ecb48c5c9ca3b2a3cb1ca2f4b4d4487473": [ + { + "filename": "astroml/ingestion/tests/test_enhanced_stream.py", + "hashed_secret": "6740d1ecb48c5c9ca3b2a3cb1ca2f4b4d4487473", + "is_secret": false, + "is_verified": false, + "line_number": 276, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "docker-compose.e2e.yml": { + "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3": [ + { + "filename": "docker-compose.e2e.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_secret": false, + "is_verified": false, + "line_number": 12, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + }, + { + "filename": "docker-compose.e2e.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_secret": false, + "is_verified": false, + "line_number": 53, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "docker-compose.override.yml": { + "3e79db1cb0caff14fd2f04f20d85b41d42bce77d": [ + { + "filename": "docker-compose.override.yml", + "hashed_secret": "3e79db1cb0caff14fd2f04f20d85b41d42bce77d", + "is_secret": false, + "is_verified": false, + "line_number": 33, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "docker-compose.yml": { + "99d2a40138fb59944b84a939a09b863d939fbee6": [ + { + "filename": "docker-compose.yml", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_secret": false, + "is_verified": false, + "line_number": 32, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "docs/KUBERNETES_DEPLOYMENT.md": { + "45d676e7c6ab44cf4b8fa366ef2d8fccd3e6d6e6": [ + { + "filename": "docs/KUBERNETES_DEPLOYMENT.md", + "hashed_secret": "45d676e7c6ab44cf4b8fa366ef2d8fccd3e6d6e6", + "is_secret": false, + "is_verified": false, + "line_number": 113, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "docs/_build/.buildinfo": { + "4b7b4f6d15410a3e658d4288f3f2dc5137d21155": [ + { + "filename": "docs/_build/.buildinfo", + "hashed_secret": "4b7b4f6d15410a3e658d4288f3f2dc5137d21155", + "is_secret": false, + "is_verified": false, + "line_number": 3, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ], + "63256a38625700f409b7ec5db8fa05ffd2cb88b2": [ + { + "filename": "docs/_build/.buildinfo", + "hashed_secret": "63256a38625700f409b7ec5db8fa05ffd2cb88b2", + "is_secret": false, + "is_verified": false, + "line_number": 4, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "docs/_build/_sources/docker-deployment.md.txt": { + "99d2a40138fb59944b84a939a09b863d939fbee6": [ + { + "filename": "docs/_build/_sources/docker-deployment.md.txt", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_secret": false, + "is_verified": false, + "line_number": 136, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "docs/_build/docker-deployment.html": { + "99d2a40138fb59944b84a939a09b863d939fbee6": [ + { + "filename": "docs/_build/docker-deployment.html", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_secret": false, + "is_verified": false, + "line_number": 325, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "docs/api/configuration.md": { + "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8": [ + { + "filename": "docs/api/configuration.md", + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_secret": false, + "is_verified": false, + "line_number": 612, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ], + "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684": [ + { + "filename": "docs/api/configuration.md", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_secret": false, + "is_verified": false, + "line_number": 119, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ], + "a616a64c0fbc30f12287d0f24f3b90dd2e6a206e": [ + { + "filename": "docs/api/configuration.md", + "hashed_secret": "a616a64c0fbc30f12287d0f24f3b90dd2e6a206e", + "is_secret": false, + "is_verified": false, + "line_number": 144, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + }, + { + "filename": "docs/api/configuration.md", + "hashed_secret": "a616a64c0fbc30f12287d0f24f3b90dd2e6a206e", + "is_secret": false, + "is_verified": false, + "line_number": 1063, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ], + "b35de43b61185e4ad30e9af6bfa1a07a37efa33a": [ + { + "filename": "docs/api/configuration.md", + "hashed_secret": "b35de43b61185e4ad30e9af6bfa1a07a37efa33a", + "is_secret": false, + "is_verified": false, + "line_number": 280, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "docs/docker-deployment.md": { + "99d2a40138fb59944b84a939a09b863d939fbee6": [ + { + "filename": "docs/docker-deployment.md", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_secret": false, + "is_verified": false, + "line_number": 136, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "k8s/astroml-deployment.yaml": { + "9a7bdf407660fc72b8b810902efb01070a6ee967": [ + { + "filename": "k8s/astroml-deployment.yaml", + "hashed_secret": "9a7bdf407660fc72b8b810902efb01070a6ee967", + "is_secret": false, + "is_verified": false, + "line_number": 7, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "k8s/ingress.yaml": { + "a725074fcadec7a4fa168915eb394c9ab4121dc5": [ + { + "filename": "k8s/ingress.yaml", + "hashed_secret": "a725074fcadec7a4fa168915eb394c9ab4121dc5", + "is_secret": false, + "is_verified": false, + "line_number": 17, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ], + "e9dd4d471ad36e76a1d6c77db85b9cb5ca8f22de": [ + { + "filename": "k8s/ingress.yaml", + "hashed_secret": "e9dd4d471ad36e76a1d6c77db85b9cb5ca8f22de", + "is_secret": false, + "is_verified": false, + "line_number": 58, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "k8s/monitoring.yaml": { + "3d7fc47f79279fc7dadb1a75abe82f38655a9838": [ + { + "filename": "k8s/monitoring.yaml", + "hashed_secret": "3d7fc47f79279fc7dadb1a75abe82f38655a9838", + "is_secret": false, + "is_verified": false, + "line_number": 234, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ], + "d033e22ae348aeb5660fc2140aec35850c4da997": [ + { + "filename": "k8s/monitoring.yaml", + "hashed_secret": "d033e22ae348aeb5660fc2140aec35850c4da997", + "is_secret": false, + "is_verified": false, + "line_number": 146, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "k8s/postgres-deployment.yaml": { + "9a7bdf407660fc72b8b810902efb01070a6ee967": [ + { + "filename": "k8s/postgres-deployment.yaml", + "hashed_secret": "9a7bdf407660fc72b8b810902efb01070a6ee967", + "is_secret": false, + "is_verified": false, + "line_number": 17, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "monitoring/grafana/provisioning/datasources/prometheus.yml": { + "99d2a40138fb59944b84a939a09b863d939fbee6": [ + { + "filename": "monitoring/grafana/provisioning/datasources/prometheus.yml", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_secret": false, + "is_verified": false, + "line_number": 20, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "outputs/astroml_experiment/2026-03-24_12-35-42/.hydra/hydra.yaml": { + "ac99bcf8782752db45829ce43b8e3a631c7ae82c": [ + { + "filename": "outputs/astroml_experiment/2026-03-24_12-35-42/.hydra/hydra.yaml", + "hashed_secret": "ac99bcf8782752db45829ce43b8e3a631c7ae82c", + "is_secret": false, + "is_verified": false, + "line_number": 143, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "outputs/astroml_experiment/2026-03-24_12-36-17/.hydra/hydra.yaml": { + "9484a72f9f06dec2e9d6d8e4cb6a827b2bcb5581": [ + { + "filename": "outputs/astroml_experiment/2026-03-24_12-36-17/.hydra/hydra.yaml", + "hashed_secret": "9484a72f9f06dec2e9d6d8e4cb6a827b2bcb5581", + "is_secret": false, + "is_verified": false, + "line_number": 146, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "test_data_quality_import.py": { + "4d43a7fd59197a455b33ddf403e2af43b2c820dc": [ + { + "filename": "test_data_quality_import.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_secret": false, + "is_verified": false, + "line_number": 38, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_confidence_boundary_100_accepted.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_confidence_boundary_100_accepted.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 42, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_deactivated_validator_cannot_submit_report.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_deactivated_validator_cannot_submit_report.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 42, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_low_confidence_report_rejected_at_boundary.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_low_confidence_report_rejected_at_boundary.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 42, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_low_reputation_report_rejected_at_boundary.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_low_reputation_report_rejected_at_boundary.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 43, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_non_admin_cannot_deactivate_validator.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_non_admin_cannot_deactivate_validator.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 41, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_config.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_config.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 40, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_validator_reputation.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_validator_reputation.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 41, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_reinitialization_overwrites_admin.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reinitialization_overwrites_admin.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 41, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_report_with_and_without_evidence_hash.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_report_with_and_without_evidence_hash.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 44, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_reputation_boundary_0_accepted.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reputation_boundary_0_accepted.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 41, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_reputation_boundary_100_accepted.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reputation_boundary_100_accepted.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 41, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_reputation_boundary_101_rejected.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reputation_boundary_101_rejected.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 40, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_sybil_single_validator_cannot_manufacture_consensus.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_sybil_single_validator_cannot_manufacture_consensus.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 43, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_unregistered_address_cannot_submit_report.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_unregistered_address_cannot_submit_report.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 40, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_update_config_invalid_reputation_threshold.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_update_config_invalid_reputation_threshold.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 40, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "test_snapshots/security_tests/security_tests/test_zero_consensus_threshold_marks_unreported_accounts_fraudulent.1.json": { + "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_zero_consensus_threshold_marks_unreported_accounts_fraudulent.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_secret": false, + "is_verified": false, + "line_number": 40, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "tests/e2e/test_api_e2e.py": { + "463d8353f4b927fd953e5af7c41084183e8ce5fb": [ + { + "filename": "tests/e2e/test_api_e2e.py", + "hashed_secret": "463d8353f4b927fd953e5af7c41084183e8ce5fb", + "is_secret": false, + "is_verified": false, + "line_number": 42, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ], + "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8": [ + { + "filename": "tests/e2e/test_api_e2e.py", + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_secret": false, + "is_verified": false, + "line_number": 50, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "tests/integration/conftest.py": { + "c94d65f02a652d11c2e5c2e1ccf38dce5a076e1e": [ + { + "filename": "tests/integration/conftest.py", + "hashed_secret": "c94d65f02a652d11c2e5c2e1ccf38dce5a076e1e", + "is_secret": false, + "is_verified": false, + "line_number": 74, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "tests/integration/test_database_config_validation.py": { + "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4": [ + { + "filename": "tests/integration/test_database_config_validation.py", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_secret": false, + "is_verified": false, + "line_number": 76, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "tests/test_agent_llm.py": { + "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4": [ + { + "filename": "tests/test_agent_llm.py", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_secret": false, + "is_verified": false, + "line_number": 234, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Secret Keyword" + } + ] + }, + "tests/test_config_validation.py": { + "81f344a7686a80b4c5293e8fdc0b0160c82c06a8": [ + { + "filename": "tests/test_config_validation.py", + "hashed_secret": "81f344a7686a80b4c5293e8fdc0b0160c82c06a8", + "is_secret": false, + "is_verified": false, + "line_number": 141, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ], + "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684": [ + { + "filename": "tests/test_config_validation.py", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_secret": false, + "is_verified": false, + "line_number": 31, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "tests/test_security.py": { + "fca268ae2442d5cabc3e12d87b349adf8bf7d76c": [ + { + "filename": "tests/test_security.py", + "hashed_secret": "fca268ae2442d5cabc3e12d87b349adf8bf7d76c", + "is_secret": false, + "is_verified": false, + "line_number": 151, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Basic Auth Credentials" + } + ] + }, + "tests/test_shipped_config_validation.py": { + "27c6929aef41ae2bcadac15ca6abcaff72cda9cd": [ + { + "filename": "tests/test_shipped_config_validation.py", + "hashed_secret": "27c6929aef41ae2bcadac15ca6abcaff72cda9cd", + "is_secret": false, + "is_verified": false, + "line_number": 194, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Private Key" + } + ], + "be4fc4886bd949b369d5e092eb87494f12e57e5b": [ + { + "filename": "tests/test_shipped_config_validation.py", + "hashed_secret": "be4fc4886bd949b369d5e092eb87494f12e57e5b", + "is_secret": false, + "is_verified": false, + "line_number": 194, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Private Key" + } + ] + }, + "tests/tracking/test_model_registry_lineage.py": { + "b214f706bb602c1cc2adc5c6165e73622305f4bb": [ + { + "filename": "tests/tracking/test_model_registry_lineage.py", + "hashed_secret": "b214f706bb602c1cc2adc5c6165e73622305f4bb", + "is_secret": false, + "is_verified": false, + "line_number": 57, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ] + }, + "tests/validation/test_data_quality.py": { + "0377fc614fbd81cea0873f127ea31b41316ec709": [ + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "0377fc614fbd81cea0873f127ea31b41316ec709", + "is_secret": false, + "is_verified": false, + "line_number": 212, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "16966c59e1af1af223afe90d62b889debcca108d": [ + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "16966c59e1af1af223afe90d62b889debcca108d", + "is_secret": false, + "is_verified": false, + "line_number": 218, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "4d43a7fd59197a455b33ddf403e2af43b2c820dc": [ + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_secret": false, + "is_verified": false, + "line_number": 211, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "9fe888e69513f6e876a5f51c72271617e74c82bb": [ + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "9fe888e69513f6e876a5f51c72271617e74c82bb", + "is_secret": false, + "is_verified": false, + "line_number": 216, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "tests/validation/test_data_quality_monitoring.py": { + "4d43a7fd59197a455b33ddf403e2af43b2c820dc": [ + { + "filename": "tests/validation/test_data_quality_monitoring.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_secret": false, + "is_verified": false, + "line_number": 77, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "tests/validation/test_extended_data_quality.py": { + "0377fc614fbd81cea0873f127ea31b41316ec709": [ + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "0377fc614fbd81cea0873f127ea31b41316ec709", + "is_secret": false, + "is_verified": false, + "line_number": 154, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "16966c59e1af1af223afe90d62b889debcca108d": [ + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "16966c59e1af1af223afe90d62b889debcca108d", + "is_secret": false, + "is_verified": false, + "line_number": 169, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "4d43a7fd59197a455b33ddf403e2af43b2c820dc": [ + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_secret": false, + "is_verified": false, + "line_number": 153, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "9fe888e69513f6e876a5f51c72271617e74c82bb": [ + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "9fe888e69513f6e876a5f51c72271617e74c82bb", + "is_secret": false, + "is_verified": false, + "line_number": 167, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "web/src/test/AccountDetailPage.test.tsx": { + "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64": [ + { + "filename": "web/src/test/AccountDetailPage.test.tsx", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_secret": false, + "is_verified": false, + "line_number": 103, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "web/src/test/AccountSearchBar.test.tsx": { + "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64": [ + { + "filename": "web/src/test/AccountSearchBar.test.tsx", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_secret": false, + "is_verified": false, + "line_number": 45, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + }, + "web/src/test/TransactionDetailPage.test.tsx": { + "4610e9a827049f059bc72b0ce9833625ca6cae13": [ + { + "filename": "web/src/test/TransactionDetailPage.test.tsx", + "hashed_secret": "4610e9a827049f059bc72b0ce9833625ca6cae13", + "is_secret": false, + "is_verified": false, + "line_number": 7, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Hex High Entropy String" + } + ], + "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64": [ + { + "filename": "web/src/test/TransactionDetailPage.test.tsx", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_secret": false, + "is_verified": false, + "line_number": 9, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ], + "bffd31c8a849c72e349c658d0c6382ee10e4c58e": [ + { + "filename": "web/src/test/TransactionDetailPage.test.tsx", + "hashed_secret": "bffd31c8a849c72e349c658d0c6382ee10e4c58e", + "is_secret": false, + "is_verified": false, + "line_number": 10, + "note": "Seeded for #720: pre-existing placeholder/test/example detection, review before trusting", + "type": "Base64 High Entropy String" + } + ] + } + }, + "filters_used": [ + { + "path": "detect_secrets.filters.allowlist.is_line_allowlisted" + }, + { + "min_level": 2, + "path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies" + }, + { + "path": "detect_secrets.filters.heuristic.is_indirect_reference" + }, + { + "path": "detect_secrets.filters.heuristic.is_likely_id_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_lock_file" + }, + { + "path": "detect_secrets.filters.heuristic.is_not_alphanumeric_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_potential_uuid" + }, + { + "path": "detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign" + }, + { + "path": "detect_secrets.filters.heuristic.is_sequential_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_swagger_file" + }, + { + "path": "detect_secrets.filters.heuristic.is_templated_secret" + } + ], + "generated_at": "2026-09-26T09:47:09Z", "plugins_used": [ { - "name": "AWSKeyDetector" + "name": "ArtifactoryDetector" }, { - "name": "Base64HighEntropyString" + "name": "AWSKeyDetector" }, { - "name": "Base64LowEntropyString" + "name": "AzureStorageKeyDetector" }, { - "name": "BasicAuthDetector" + "limit": 4.5, + "name": "Base64HighEntropyString" }, { - "name": "BatchCloudApiKeyDetector" + "name": "BasicAuthDetector" }, { "name": "CloudantDetector" @@ -23,24 +1259,29 @@ "name": "DiscordBotTokenDetector" }, { - "name": "ElasticCloudDetector" + "name": "GitHubTokenDetector" }, { - "name": "GitHubTokenDetector" + "name": "GitLabTokenDetector" + }, + { + "limit": 3.0, + "name": "HexHighEntropyString" }, { "name": "IbmCloudIamDetector" }, { - "name": "IpmiDetector" + "name": "IbmCosHmacDetector" }, { - "name": "JiraApiTokenDetector" + "name": "IPPublicDetector" }, { "name": "JwtTokenDetector" }, { + "keyword_exclude": "", "name": "KeywordDetector" }, { @@ -49,9 +1290,15 @@ { "name": "NpmDetector" }, + { + "name": "OpenAIDetector" + }, { "name": "PrivateKeyDetector" }, + { + "name": "PypiTokenDetector" + }, { "name": "SendGridDetector" }, @@ -68,11 +1315,832 @@ "name": "StripeDetector" }, { - "name": "TwilioKeyDetector" + "name": "TelegramBotTokenDetector" }, { - "name": "AzureKeyDetector" + "name": "TwilioKeyDetector" } ], - "results": [] + "results": { + ".env.example": [ + { + "filename": ".env.example", + "hashed_secret": "632d8eb9ee5be70b5448c03a10544b62f577ad60", + "is_verified": false, + "line_number": 11, + "type": "Basic Auth Credentials" + } + ], + ".github/workflows/ci.yml": [ + { + "filename": ".github/workflows/ci.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 25, + "type": "Secret Keyword" + }, + { + "filename": ".github/workflows/ci.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 44, + "type": "Basic Auth Credentials" + } + ], + ".github/workflows/e2e-tests.yml": [ + { + "filename": ".github/workflows/e2e-tests.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 21, + "type": "Secret Keyword" + }, + { + "filename": ".github/workflows/e2e-tests.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 58, + "type": "Basic Auth Credentials" + } + ], + ".github/workflows/nightly.yml": [ + { + "filename": ".github/workflows/nightly.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 123, + "type": "Secret Keyword" + }, + { + "filename": ".github/workflows/nightly.yml", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 159, + "type": "Basic Auth Credentials" + } + ], + "DOCKER_QUICK_REFERENCE.md": [ + { + "filename": "DOCKER_QUICK_REFERENCE.md", + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_verified": false, + "line_number": 128, + "type": "Basic Auth Credentials" + } + ], + "E2E_TESTING_GUIDE.md": [ + { + "filename": "E2E_TESTING_GUIDE.md", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 81, + "type": "Basic Auth Credentials" + } + ], + "PR_MESSAGE.md": [ + { + "filename": "PR_MESSAGE.md", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 242, + "type": "Basic Auth Credentials" + } + ], + "README.md": [ + { + "filename": "README.md", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 367, + "type": "Basic Auth Credentials" + } + ], + "SECRETS_SCANNING_GUIDE.md": [ + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "19fc48b762dc922d126f0d0d7e5274e93212b5e7", + "is_verified": false, + "line_number": 109, + "type": "Secret Keyword" + }, + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "d247e54e14ab3298d7b979f10a70fa8d380ffeec", + "is_verified": false, + "line_number": 147, + "type": "Secret Keyword" + }, + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 161, + "type": "Basic Auth Credentials" + }, + { + "filename": "SECRETS_SCANNING_GUIDE.md", + "hashed_secret": "25910f981e85ca04baf359199dd0bd4a3ae738b6", + "is_verified": false, + "line_number": 270, + "type": "AWS Access Key" + } + ], + "api/database.py": [ + { + "filename": "api/database.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 111, + "type": "Basic Auth Credentials" + } + ], + "api/routers/accounts.py": [ + { + "filename": "api/routers/accounts.py", + "hashed_secret": "a3d2709ddb4695bf7c836222de3fcdba279a129c", + "is_verified": false, + "line_number": 188, + "type": "Hex High Entropy String" + }, + { + "filename": "api/routers/accounts.py", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_verified": false, + "line_number": 190, + "type": "Base64 High Entropy String" + } + ], + "api/routers/backup.py": [ + { + "filename": "api/routers/backup.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 80, + "type": "Basic Auth Credentials" + } + ], + "api/routers/v1/backup.py": [ + { + "filename": "api/routers/v1/backup.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 80, + "type": "Basic Auth Credentials" + } + ], + "api/schemas/__init__.py": [ + { + "filename": "api/schemas/__init__.py", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_verified": false, + "line_number": 38, + "type": "Base64 High Entropy String" + }, + { + "filename": "api/schemas/__init__.py", + "hashed_secret": "bffd31c8a849c72e349c658d0c6382ee10e4c58e", + "is_verified": false, + "line_number": 44, + "type": "Base64 High Entropy String" + } + ], + "api/tests/conftest.py": [ + { + "filename": "api/tests/conftest.py", + "hashed_secret": "a14cdcfcd4700ffb2f5de51a5ff19a97e2384237", + "is_verified": false, + "line_number": 120, + "type": "Hex High Entropy String" + } + ], + "api/tests/test_api_key_rotation.py": [ + { + "filename": "api/tests/test_api_key_rotation.py", + "hashed_secret": "25ab86bed149ca6ca9c1c0d5db7c9a91388ddeab", + "is_verified": false, + "line_number": 42, + "type": "Secret Keyword" + } + ], + "api/tests/test_auth.py": [ + { + "filename": "api/tests/test_auth.py", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 39, + "type": "Secret Keyword" + } + ], + "api/tests/test_orm_models.py": [ + { + "filename": "api/tests/test_orm_models.py", + "hashed_secret": "ff55f8ab1c3d25394048cbef0bac18ef763a60ed", + "is_verified": false, + "line_number": 75, + "type": "Hex High Entropy String" + } + ], + "astroml/api/app.py": [ + { + "filename": "astroml/api/app.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 43, + "type": "Basic Auth Credentials" + } + ], + "astroml/api/routers/accounts.py": [ + { + "filename": "astroml/api/routers/accounts.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 27, + "type": "Basic Auth Credentials" + } + ], + "astroml/api/routers/fraud.py": [ + { + "filename": "astroml/api/routers/fraud.py", + "hashed_secret": "bf0a737434ab6c2fedb31a2a084eae04597f5de0", + "is_verified": false, + "line_number": 30, + "type": "Basic Auth Credentials" + } + ], + "astroml/backup/service.py": [ + { + "filename": "astroml/backup/service.py", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 130, + "type": "Basic Auth Credentials" + } + ], + "astroml/ingestion/tests/test_enhanced_stream.py": [ + { + "filename": "astroml/ingestion/tests/test_enhanced_stream.py", + "hashed_secret": "6740d1ecb48c5c9ca3b2a3cb1ca2f4b4d4487473", + "is_verified": false, + "line_number": 276, + "type": "Hex High Entropy String" + } + ], + "docker-compose.e2e.yml": [ + { + "filename": "docker-compose.e2e.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 12, + "type": "Secret Keyword" + }, + { + "filename": "docker-compose.e2e.yml", + "hashed_secret": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", + "is_verified": false, + "line_number": 53, + "type": "Basic Auth Credentials" + } + ], + "docker-compose.override.yml": [ + { + "filename": "docker-compose.override.yml", + "hashed_secret": "3e79db1cb0caff14fd2f04f20d85b41d42bce77d", + "is_verified": false, + "line_number": 33, + "type": "Secret Keyword" + } + ], + "docker-compose.yml": [ + { + "filename": "docker-compose.yml", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_verified": false, + "line_number": 32, + "type": "Secret Keyword" + } + ], + "docs/KUBERNETES_DEPLOYMENT.md": [ + { + "filename": "docs/KUBERNETES_DEPLOYMENT.md", + "hashed_secret": "45d676e7c6ab44cf4b8fa366ef2d8fccd3e6d6e6", + "is_verified": false, + "line_number": 113, + "type": "Basic Auth Credentials" + } + ], + "docs/_build/.buildinfo": [ + { + "filename": "docs/_build/.buildinfo", + "hashed_secret": "4b7b4f6d15410a3e658d4288f3f2dc5137d21155", + "is_verified": false, + "line_number": 3, + "type": "Hex High Entropy String" + }, + { + "filename": "docs/_build/.buildinfo", + "hashed_secret": "63256a38625700f409b7ec5db8fa05ffd2cb88b2", + "is_verified": false, + "line_number": 4, + "type": "Hex High Entropy String" + } + ], + "docs/_build/_sources/docker-deployment.md.txt": [ + { + "filename": "docs/_build/_sources/docker-deployment.md.txt", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_verified": false, + "line_number": 136, + "type": "Basic Auth Credentials" + } + ], + "docs/_build/docker-deployment.html": [ + { + "filename": "docs/_build/docker-deployment.html", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_verified": false, + "line_number": 325, + "type": "Basic Auth Credentials" + } + ], + "docs/api/configuration.md": [ + { + "filename": "docs/api/configuration.md", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 119, + "type": "Basic Auth Credentials" + }, + { + "filename": "docs/api/configuration.md", + "hashed_secret": "a616a64c0fbc30f12287d0f24f3b90dd2e6a206e", + "is_verified": false, + "line_number": 144, + "type": "Secret Keyword" + }, + { + "filename": "docs/api/configuration.md", + "hashed_secret": "b35de43b61185e4ad30e9af6bfa1a07a37efa33a", + "is_verified": false, + "line_number": 280, + "type": "Base64 High Entropy String" + }, + { + "filename": "docs/api/configuration.md", + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_verified": false, + "line_number": 612, + "type": "Basic Auth Credentials" + }, + { + "filename": "docs/api/configuration.md", + "hashed_secret": "a616a64c0fbc30f12287d0f24f3b90dd2e6a206e", + "is_verified": false, + "line_number": 1063, + "type": "Basic Auth Credentials" + } + ], + "docs/docker-deployment.md": [ + { + "filename": "docs/docker-deployment.md", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_verified": false, + "line_number": 136, + "type": "Basic Auth Credentials" + } + ], + "k8s/astroml-deployment.yaml": [ + { + "filename": "k8s/astroml-deployment.yaml", + "hashed_secret": "9a7bdf407660fc72b8b810902efb01070a6ee967", + "is_verified": false, + "line_number": 7, + "type": "Basic Auth Credentials" + } + ], + "k8s/ingress.yaml": [ + { + "filename": "k8s/ingress.yaml", + "hashed_secret": "a725074fcadec7a4fa168915eb394c9ab4121dc5", + "is_verified": false, + "line_number": 17, + "type": "Secret Keyword" + }, + { + "filename": "k8s/ingress.yaml", + "hashed_secret": "e9dd4d471ad36e76a1d6c77db85b9cb5ca8f22de", + "is_verified": false, + "line_number": 58, + "type": "Secret Keyword" + } + ], + "k8s/monitoring.yaml": [ + { + "filename": "k8s/monitoring.yaml", + "hashed_secret": "d033e22ae348aeb5660fc2140aec35850c4da997", + "is_verified": false, + "line_number": 146, + "type": "Secret Keyword" + }, + { + "filename": "k8s/monitoring.yaml", + "hashed_secret": "3d7fc47f79279fc7dadb1a75abe82f38655a9838", + "is_verified": false, + "line_number": 234, + "type": "Secret Keyword" + } + ], + "k8s/postgres-deployment.yaml": [ + { + "filename": "k8s/postgres-deployment.yaml", + "hashed_secret": "9a7bdf407660fc72b8b810902efb01070a6ee967", + "is_verified": false, + "line_number": 17, + "type": "Secret Keyword" + } + ], + "monitoring/grafana/provisioning/datasources/prometheus.yml": [ + { + "filename": "monitoring/grafana/provisioning/datasources/prometheus.yml", + "hashed_secret": "99d2a40138fb59944b84a939a09b863d939fbee6", + "is_verified": false, + "line_number": 20, + "type": "Secret Keyword" + } + ], + "outputs/astroml_experiment/2026-03-24_12-35-42/.hydra/hydra.yaml": [ + { + "filename": "outputs/astroml_experiment/2026-03-24_12-35-42/.hydra/hydra.yaml", + "hashed_secret": "ac99bcf8782752db45829ce43b8e3a631c7ae82c", + "is_verified": false, + "line_number": 143, + "type": "Base64 High Entropy String" + } + ], + "outputs/astroml_experiment/2026-03-24_12-36-17/.hydra/hydra.yaml": [ + { + "filename": "outputs/astroml_experiment/2026-03-24_12-36-17/.hydra/hydra.yaml", + "hashed_secret": "9484a72f9f06dec2e9d6d8e4cb6a827b2bcb5581", + "is_verified": false, + "line_number": 146, + "type": "Base64 High Entropy String" + } + ], + "test_data_quality_import.py": [ + { + "filename": "test_data_quality_import.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_verified": false, + "line_number": 38, + "type": "Base64 High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_confidence_boundary_100_accepted.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_confidence_boundary_100_accepted.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 42, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_deactivated_validator_cannot_submit_report.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_deactivated_validator_cannot_submit_report.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 42, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_low_confidence_report_rejected_at_boundary.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_low_confidence_report_rejected_at_boundary.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 42, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_low_reputation_report_rejected_at_boundary.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_low_reputation_report_rejected_at_boundary.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 43, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_non_admin_cannot_deactivate_validator.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_non_admin_cannot_deactivate_validator.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 41, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_config.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_config.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 40, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_validator_reputation.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_non_admin_cannot_update_validator_reputation.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 41, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_reinitialization_overwrites_admin.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reinitialization_overwrites_admin.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 41, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_report_with_and_without_evidence_hash.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_report_with_and_without_evidence_hash.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 44, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_reputation_boundary_0_accepted.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reputation_boundary_0_accepted.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 41, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_reputation_boundary_100_accepted.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reputation_boundary_100_accepted.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 41, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_reputation_boundary_101_rejected.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_reputation_boundary_101_rejected.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 40, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_sybil_single_validator_cannot_manufacture_consensus.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_sybil_single_validator_cannot_manufacture_consensus.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 43, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_unregistered_address_cannot_submit_report.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_unregistered_address_cannot_submit_report.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 40, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_update_config_invalid_reputation_threshold.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_update_config_invalid_reputation_threshold.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 40, + "type": "Hex High Entropy String" + } + ], + "test_snapshots/security_tests/security_tests/test_zero_consensus_threshold_marks_unreported_accounts_fraudulent.1.json": [ + { + "filename": "test_snapshots/security_tests/security_tests/test_zero_consensus_threshold_marks_unreported_accounts_fraudulent.1.json", + "hashed_secret": "244f421f896bdcdd2784dccf4eaf7c8dfd5189b5", + "is_verified": false, + "line_number": 40, + "type": "Hex High Entropy String" + } + ], + "tests/e2e/test_api_e2e.py": [ + { + "filename": "tests/e2e/test_api_e2e.py", + "hashed_secret": "463d8353f4b927fd953e5af7c41084183e8ce5fb", + "is_verified": false, + "line_number": 42, + "type": "Secret Keyword" + }, + { + "filename": "tests/e2e/test_api_e2e.py", + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_verified": false, + "line_number": 50, + "type": "Secret Keyword" + } + ], + "tests/integration/conftest.py": [ + { + "filename": "tests/integration/conftest.py", + "hashed_secret": "c94d65f02a652d11c2e5c2e1ccf38dce5a076e1e", + "is_verified": false, + "line_number": 74, + "type": "Secret Keyword" + } + ], + "tests/integration/test_database_config_validation.py": [ + { + "filename": "tests/integration/test_database_config_validation.py", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 76, + "type": "Basic Auth Credentials" + } + ], + "tests/test_agent_llm.py": [ + { + "filename": "tests/test_agent_llm.py", + "hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4", + "is_verified": false, + "line_number": 234, + "type": "Secret Keyword" + } + ], + "tests/test_config_validation.py": [ + { + "filename": "tests/test_config_validation.py", + "hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684", + "is_verified": false, + "line_number": 31, + "type": "Basic Auth Credentials" + }, + { + "filename": "tests/test_config_validation.py", + "hashed_secret": "81f344a7686a80b4c5293e8fdc0b0160c82c06a8", + "is_verified": false, + "line_number": 141, + "type": "Basic Auth Credentials" + } + ], + "tests/test_security.py": [ + { + "filename": "tests/test_security.py", + "hashed_secret": "fca268ae2442d5cabc3e12d87b349adf8bf7d76c", + "is_verified": false, + "line_number": 151, + "type": "Basic Auth Credentials" + } + ], + "tests/test_shipped_config_validation.py": [ + { + "filename": "tests/test_shipped_config_validation.py", + "hashed_secret": "27c6929aef41ae2bcadac15ca6abcaff72cda9cd", + "is_verified": false, + "line_number": 194, + "type": "Private Key" + }, + { + "filename": "tests/test_shipped_config_validation.py", + "hashed_secret": "be4fc4886bd949b369d5e092eb87494f12e57e5b", + "is_verified": false, + "line_number": 194, + "type": "Private Key" + } + ], + "tests/tracking/test_model_registry_lineage.py": [ + { + "filename": "tests/tracking/test_model_registry_lineage.py", + "hashed_secret": "b214f706bb602c1cc2adc5c6165e73622305f4bb", + "is_verified": false, + "line_number": 57, + "type": "Hex High Entropy String" + } + ], + "tests/validation/test_data_quality.py": [ + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_verified": false, + "line_number": 211, + "type": "Base64 High Entropy String" + }, + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "0377fc614fbd81cea0873f127ea31b41316ec709", + "is_verified": false, + "line_number": 212, + "type": "Base64 High Entropy String" + }, + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "9fe888e69513f6e876a5f51c72271617e74c82bb", + "is_verified": false, + "line_number": 216, + "type": "Base64 High Entropy String" + }, + { + "filename": "tests/validation/test_data_quality.py", + "hashed_secret": "16966c59e1af1af223afe90d62b889debcca108d", + "is_verified": false, + "line_number": 218, + "type": "Base64 High Entropy String" + } + ], + "tests/validation/test_data_quality_monitoring.py": [ + { + "filename": "tests/validation/test_data_quality_monitoring.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_verified": false, + "line_number": 77, + "type": "Base64 High Entropy String" + } + ], + "tests/validation/test_extended_data_quality.py": [ + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "4d43a7fd59197a455b33ddf403e2af43b2c820dc", + "is_verified": false, + "line_number": 153, + "type": "Base64 High Entropy String" + }, + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "0377fc614fbd81cea0873f127ea31b41316ec709", + "is_verified": false, + "line_number": 154, + "type": "Base64 High Entropy String" + }, + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "9fe888e69513f6e876a5f51c72271617e74c82bb", + "is_verified": false, + "line_number": 167, + "type": "Base64 High Entropy String" + }, + { + "filename": "tests/validation/test_extended_data_quality.py", + "hashed_secret": "16966c59e1af1af223afe90d62b889debcca108d", + "is_verified": false, + "line_number": 169, + "type": "Base64 High Entropy String" + } + ], + "web/src/test/AccountDetailPage.test.tsx": [ + { + "filename": "web/src/test/AccountDetailPage.test.tsx", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_verified": false, + "line_number": 103, + "type": "Base64 High Entropy String" + } + ], + "web/src/test/AccountSearchBar.test.tsx": [ + { + "filename": "web/src/test/AccountSearchBar.test.tsx", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_verified": false, + "line_number": 45, + "type": "Base64 High Entropy String" + } + ], + "web/src/test/TransactionDetailPage.test.tsx": [ + { + "filename": "web/src/test/TransactionDetailPage.test.tsx", + "hashed_secret": "4610e9a827049f059bc72b0ce9833625ca6cae13", + "is_verified": false, + "line_number": 7, + "type": "Hex High Entropy String" + }, + { + "filename": "web/src/test/TransactionDetailPage.test.tsx", + "hashed_secret": "5fad8caa4a59d7bf10d88a7fa4c0d55096b5bb64", + "is_verified": false, + "line_number": 9, + "type": "Base64 High Entropy String" + }, + { + "filename": "web/src/test/TransactionDetailPage.test.tsx", + "hashed_secret": "bffd31c8a849c72e349c658d0c6382ee10e4c58e", + "is_verified": false, + "line_number": 10, + "type": "Base64 High Entropy String" + } + ] + }, + "version": "1.5.0" } diff --git a/Makefile b/Makefile index 56b3f2c3..5a88cd4c 100644 --- a/Makefile +++ b/Makefile @@ -156,8 +156,8 @@ security-audit: .PHONY: secrets-scan secrets-scan: - @echo "🔍 Running detect-secrets to scan for leaked credentials..." - detect-secrets scan --baseline .secrets.baseline + @echo "🔍 Running detect-secrets gate (fails on new or unaudited secrets)..." + python -m astroml.ci.secrets_gate --baseline .secrets.baseline .PHONY: benchmark benchmark: diff --git a/SECRETS_SCANNING_GUIDE.md b/SECRETS_SCANNING_GUIDE.md index 1c91ddc1..6905550d 100644 --- a/SECRETS_SCANNING_GUIDE.md +++ b/SECRETS_SCANNING_GUIDE.md @@ -29,6 +29,22 @@ The `.secrets.baseline` file stores known secrets that have been reviewed and wh Secrets scanning runs in CI via the pre-commit workflow (`.github/workflows/pre-commit.yml`). The CI job will fail if new secrets are detected that aren't in the baseline. +#### The secrets gate (#720) + +`detect-secrets scan --baseline` alone cannot fail a build: it rewrites the +baseline in place and exits 0. The CI gate (`astroml/ci/secrets_gate.py`, +registered as the `secrets-gate` local hook in `.pre-commit-config.yaml`) is +what enforces the policy. It fails the build when: + +1. a scan finds a secret that the baseline does not whitelist, +2. a whitelisted baseline entry has no audit decision, or was audited as a + real secret (`is_secret: true` must never be committed), +3. the scanner is missing or the baseline is unreadable (exit code 2 — a + broken gate never reads as a pass). + +Run it locally with `make secrets-scan` (or `python -m astroml.ci.secrets_gate +--baseline .secrets.baseline`). + ## Usage ### Manual Scanning @@ -42,9 +58,14 @@ make secrets-scan Or directly: ```bash -detect-secrets scan --baseline .secrets.baseline --all-files +python -m astroml.ci.secrets_gate --baseline .secrets.baseline ``` +Use the gate rather than `detect-secrets scan --baseline .secrets.baseline +--all-files` for checks: the raw command mutates the baseline file instead of +failing when it finds something new. Only use it deliberately when adding +whitelist entries (see Handling False Positives). + ### Pre-Commit Hook The pre-commit hook runs automatically before each commit: @@ -74,8 +95,10 @@ If a detected secret is a false positive: ```bash detect-secrets scan --baseline .secrets.baseline ``` -3. **Commit the baseline**: Commit the updated `.secrets.baseline` file -4. **Document**: Add a comment in the code explaining why it's whitelisted +3. **Audit the entry**: `detect-secrets audit .secrets.baseline` and mark it + `is_secret: false` — the CI gate (#720) fails on unaudited entries. +4. **Commit the baseline**: Commit the updated `.secrets.baseline` file +5. **Document**: Add a comment in the code explaining why it's whitelisted ### Example: Whitelisting a Test Key diff --git a/astroml/ci/secrets_gate.py b/astroml/ci/secrets_gate.py new file mode 100644 index 00000000..1319307e --- /dev/null +++ b/astroml/ci/secrets_gate.py @@ -0,0 +1,178 @@ +"""Secret-scan gate for CI (issue #720). + +`detect-secrets scan --baseline` silently *rewrites* the baseline and exits 0, +so it cannot fail a build on a newly leaked secret. This gate is the missing +half: it compares a fresh scan against the reviewed baseline and fails when + + * a secret appears that the baseline does not whitelist, + * a whitelisted secret was never audited, or was audited as a real secret, + * the scanner itself is missing or errors out (exit 2 — a broken scan gate + must not read as "no secrets"). + +Runs wherever ``detect-secrets`` is on PATH (the pre-commit CI job installs +it), so it is wired in via ``.pre-commit-config.yaml`` rather than a dedicated +workflow step. +""" + +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Optional, Sequence + +EXIT_OK = 0 +EXIT_FOUND_SECRETS = 1 +EXIT_SCAN_ERROR = 2 + + +@dataclass(frozen=True) +class SecretLocation: + filename: str + hashed_secret: str + + def __str__(self) -> str: + return f"{self.filename} ({self.hashed_secret})" + + +@dataclass +class GateReport: + new_secrets: list[SecretLocation] = field(default_factory=list) + unaudited_secrets: list[SecretLocation] = field(default_factory=list) + true_positive_secrets: list[SecretLocation] = field(default_factory=list) + + @property + def ok(self) -> bool: + return not (self.new_secrets or self.unaudited_secrets or self.true_positive_secrets) + + def format(self) -> str: + if self.ok: + return "secrets gate: PASS — no new secrets, baseline fully audited" + lines = ["secrets gate: FAIL"] + for loc in self.new_secrets: + lines.append(f" new secret not in baseline: {loc}") + for loc in self.unaudited_secrets: + lines.append(f" baseline secret has no audit decision: {loc}") + for loc in self.true_positive_secrets: + lines.append(f" baseline secret audited as REAL secret: {loc}") + lines.append( + " Remediation: run `detect-secrets audit .secrets.baseline` to review," + " remove genuine credentials and rotate them." + ) + return "\n".join(lines) + + +def _as_results(raw: dict[str, Any]) -> dict[str, list[dict[str, Any]]]: + """Return the {filename: [secret-entry, ...]} map from either baseline format.""" + if isinstance(raw.get("results"), list): + # Hand-edited v0.x baselines can carry an empty list; no entries to key. + return {} + if "results" in raw: + return raw["results"] + state = raw.get("state") or {} + return state.get("secrets") or {} + + +def _as_audit(raw: dict[str, Any]) -> Optional[dict[str, Any]]: + """Audit section, or None when the baseline predates auditing (v0.x).""" + if "state" in raw: + return raw["state"].get("audit_data") + if "audit" in raw: + return raw["audit"] + return None + + +def _audit_decision(audit: dict[str, Any], loc: SecretLocation) -> Optional[bool]: + per_file = audit.get(loc.filename) or {} + entries = per_file.get(loc.hashed_secret) + if not entries: + return None + is_secret = entries[-1].get("is_secret") + return None if is_secret is None else bool(is_secret) + + +def evaluate(scan_output: dict[str, Any], baseline: dict[str, Any]) -> GateReport: + report = GateReport() + baseline_results = _as_results(baseline) + whitelisted = { + SecretLocation(filename, entry["hashed_secret"]) + for filename, entries in baseline_results.items() + for entry in entries + } + scanned = { + SecretLocation(filename, entry["hashed_secret"]) + for filename, entries in _as_results(scan_output).items() + for entry in entries + } + report.new_secrets = sorted(scanned - whitelisted, key=str) + + audit = _as_audit(baseline) + for loc in sorted(whitelisted, key=str): + if audit is None: + report.unaudited_secrets.append(loc) + continue + decision = _audit_decision(audit, loc) + if decision is None: + report.unaudited_secrets.append(loc) + elif decision: + report.true_positive_secrets.append(loc) + return report + + +def run_detect_secrets(paths: Optional[Sequence[str]], root: Path) -> dict[str, Any]: + if shutil.which("detect-secrets") is None: + raise RuntimeError("detect-secrets executable not found on PATH") + cmd = ["detect-secrets", "scan", "--exclude-files", r"\.secrets\.baseline$"] + if paths: + cmd += list(paths) + elif not (root / ".git").exists(): + cmd.append("--all-files") # non-git checkout: scan recursively + result = subprocess.run(cmd, cwd=str(root), capture_output=True, text=True) + if result.returncode != 0: + raise RuntimeError(f"detect-secrets failed ({result.returncode}): {result.stderr.strip()}") + return json.loads(result.stdout) + + +def load_baseline(path: Path) -> dict[str, Any]: + if not path.exists(): + raise RuntimeError(f"baseline not found: {path}") + return json.loads(path.read_text()) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser(prog="secrets-gate", description=__doc__.splitlines()[0]) + parser.add_argument("--baseline", default=".secrets.baseline", type=Path) + parser.add_argument( + "--root", + default=Path.cwd(), + type=Path, + help="repository root to scan (default: cwd)", + ) + parser.add_argument( + "--path", + dest="paths", + action="append", + default=None, + metavar="FILE", + help="scan only these paths (default: all tracked files)", + ) + args = parser.parse_args(argv) + + try: + baseline = load_baseline(args.baseline) + scan_output = run_detect_secrets(args.paths, args.root) + except (RuntimeError, OSError, json.JSONDecodeError) as exc: + print(f"secrets gate: ERROR — {exc}", file=sys.stderr) + return EXIT_SCAN_ERROR + + report = evaluate(scan_output, baseline) + print(report.format()) + return EXIT_OK if report.ok else EXIT_FOUND_SECRETS + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/requirements-dev.txt b/requirements-dev.txt index 22b690e0..74b20a85 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -27,6 +27,7 @@ mypy>=1.7.0 ruff>=0.4.0 isort>=5.13.0 pre-commit>=3.7.0 +detect-secrets>=1.4.0 interrogate>=1.7.0,<2.0 # ── Code complexity analysis ───────────────────────────────────────────── diff --git a/tests/ci/__init__.py b/tests/ci/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/ci/test_secrets_gate.py b/tests/ci/test_secrets_gate.py new file mode 100644 index 00000000..be32a10b --- /dev/null +++ b/tests/ci/test_secrets_gate.py @@ -0,0 +1,156 @@ +"""Tests for the secrets-scan CI gate (issue #720).""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from astroml.ci.secrets_gate import ( + EXIT_FOUND_SECRETS, + EXIT_OK, + EXIT_SCAN_ERROR, + SecretLocation, + evaluate, + main, +) + +AWS_FAKE_SECRET = ( + 'aws_access_key_id = "AKIAIOSFODNN7EXAMPLE"\n' + 'aws_secret_access_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"\n' +) +GITHUB_FAKE_SECRET = 'GITHUB_TOKEN = "ghp_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"\n' + + +def _scan(secret_files: dict[str, str]) -> dict: + """Build a scan-result document from {filename: hashed_secret} pairs.""" + return { + "results": { + name: [{"type": "AWS Key Detector", "hashed_secret": digest, "is_verified": False}] + for name, digest in secret_files.items() + } + } + + +def _baseline(secrets: dict[str, str], audits: dict[str, bool] | None) -> dict: + doc = _scan(secrets) + if audits is not None: + doc["audit"] = { + name: {secrets[name]: [{"is_secret": is_secret}]} for name, is_secret in audits.items() + } + return doc + + +class TestEvaluate: + def test_clean_scan_and_empty_baseline_passes(self): + report = evaluate(_scan({}), _baseline({}, audits={})) + assert report.ok + + def test_secret_missing_from_baseline_is_reported_as_new(self): + report = evaluate( + _scan({"app/settings.py": "aaaa"}), + _baseline({}, audits={}), + ) + assert SecretLocation("app/settings.py", "aaaa") in report.new_secrets + assert not report.ok + + def test_whitelisted_and_audited_false_positive_passes(self): + scan = _scan({"tests/fixtures/keys.py": "bbbb"}) + base = _baseline( + {"tests/fixtures/keys.py": "bbbb"}, audits={"tests/fixtures/keys.py": False} + ) + assert evaluate(scan, base).ok + + def test_whitelisted_but_unaudited_fails(self): + scan = _scan({"seeds.py": "cccc"}) + base = _baseline({"seeds.py": "cccc"}, audits=None) # legacy v0.x baseline, no audit data + report = evaluate(scan, base) + assert SecretLocation("seeds.py", "cccc") in report.unaudited_secrets + assert not report.ok + + def test_audit_entry_absent_for_specific_secret_fails(self): + scan = _scan({"a.py": "1", "b.py": "2"}) + base = _baseline( + {"a.py": "1", "b.py": "2"}, + audits={"a.py": False}, + ) + report = evaluate(scan, base) + assert [s.filename for s in report.unaudited_secrets] == ["b.py"] + + def test_baseline_secret_audited_as_real_secret_fails(self): + scan = _scan({}) + base = _baseline({"prod.env": "dddd"}, audits={"prod.env": True}) + report = evaluate(scan, base) + assert SecretLocation("prod.env", "dddd") in report.true_positive_secrets + assert not report.ok + + def test_state_style_baseline_is_supported(self): + scan = _scan({"x.py": "ee"}) + base = { + "state": { + "secrets": scan["results"], + "audit_data": {"x.py": {"ee": [{"is_secret": False}]}}, + } + } + assert evaluate(scan, base).ok + + +class TestCli: + def test_missing_baseline_exits_scan_error(self, tmp_path): + code = main(["--baseline", str(tmp_path / "nope.baseline"), "--root", str(tmp_path)]) + assert code == EXIT_SCAN_ERROR + + def test_bad_repo_path_exits_scan_error(self, tmp_path): + baseline = tmp_path / ".secrets.baseline" + baseline.write_text("{not json") + code = main(["--baseline", str(baseline), "--root", str(tmp_path)]) + assert code == EXIT_SCAN_ERROR + + @pytest.mark.skipif( + shutil.which("detect-secrets") is None, reason="detect-secrets CLI required" + ) + def test_real_scan_of_leaked_aws_key_fails_gate(self, tmp_path): + (tmp_path / "leak.py").write_text(GITHUB_FAKE_SECRET) + baseline = tmp_path / ".secrets.baseline" + baseline.write_text(json.dumps({"results": {}, "audit": {}})) + code = main(["--baseline", str(baseline), "--root", str(tmp_path), "--path", "leak.py"]) + assert code == EXIT_FOUND_SECRETS + + @pytest.mark.skipif( + shutil.which("detect-secrets") is None, reason="detect-secrets CLI required" + ) + def test_real_scan_of_clean_file_passes_gate(self, tmp_path): + (tmp_path / "clean.py").write_text("PORT = 8080\n") + baseline = tmp_path / ".secrets.baseline" + baseline.write_text(json.dumps({"results": {}, "audit": {}})) + code = main(["--baseline", str(baseline), "--root", str(tmp_path), "--path", "clean.py"]) + assert code == EXIT_OK + + @pytest.mark.skipif( + shutil.which("detect-secrets") is None, reason="detect-secrets CLI required" + ) + def test_gate_does_not_mutate_baseline(self, tmp_path): + (tmp_path / "leak.py").write_text(AWS_FAKE_SECRET) + baseline = tmp_path / ".secrets.baseline" + original = json.dumps({"results": {}, "audit": {}}) + baseline.write_text(original) + subprocess.run( + [ + sys.executable, + "-m", + "astroml.ci.secrets_gate", + "--baseline", + str(baseline), + "--root", + str(tmp_path), + "--path", + "leak.py", + ], + cwd=str(Path(__file__).resolve().parents[2]), + check=False, + ) + assert baseline.read_text() == original