Skip to content

feat: secrets gate, idempotent ingestion, total-ordered snapshots, flaky detection - #1026

Merged
gelluisaac merged 8 commits into
Traqora:mainfrom
YazarAyobami:yazar/astroml-wave-batch
Sep 28, 2026
Merged

gelluisaac merged 8 commits into
Traqora:mainfrom
YazarAyobami:yazar/astroml-wave-batch

Conversation

@YazarAyobami

Copy link
Copy Markdown
Contributor

Closes #732
Closes #728
Closes #720
Closes #715

Summary

A bundled batch of four assigned issues on this repo, one branch, one PR (all four are mine and their acceptance criteria overlap heavily, so a single reviewable wave is more useful than four interdependent PRs):

Issue Area One-liner
#732 features/graph Snapshot construction is now ordered by the blockchain's total order, not arrival order
#728 ingestion/db Normalized activity writes are idempotent on retry via a natural key + upsert
#720 ci New secrets gate makes CI actually fail on leaked or unaudited secrets
#715 testing New flaky-test detection/retry/reporting pytest plugin + known-flaky registry

Note for reviewers: this exceeds the #557 soft size policy (27 files) because the issues were assigned together; the PR-size check is warning-only per that workflow. Happy to split if maintainers prefer.


#732 — Order snapshot construction by the blockchain's total order

Problem: graph snapshots consumed edges in whatever order rows came back, so two runs over the same window could build different graphs (edge insertion order affects downstream features).

What was done:

  • astroml/features/graph/snapshot.py: all windowed snapshot builders now read normalized_transactions ordered by the total order (timestamp, ledger_sequence, operation_id, hop_index) instead of arrival/insertion order; added _snapshot_ordering() (the single ordering definition), _first_inversion() and validate_temporal_order() so a mis-ordered edge stream fails loudly at construction instead of silently poisoning features. Malformed window specs now route through the existing RFC 7807 error factories.
  • migrations/versions/014_snapshot_ordering_index.py: adds ix_normalized_transactions_timestamp_order on (timestamp, ledger_sequence, operation_id, hop_index) so the total-order read is index-backed (reversible; drops the index on downgrade).
  • Tests: tests/features/graph/test_snapshot_ordering.py (new, 310 lines) — ordering determinism across shuffled inserts, inversion detection, window-size error paths; tests/integration/test_graph_construction.py updated for the new signature.

#728 — Idempotent normalized activity writes on retry

Problem: a retried ingestion batch could double-write normalized activity rows; the table had no natural key.

What was done:

  • Natural key = (ledger_sequence, operation_id, hop_index). astroml/ingestion/parsers.py gains ledger_sequence_from_operation_id() (Horizon operation ids are toids, so the ledger is derived from the id — no extra column to backfill by hand), and normalizer.py stamps the key (_natural_key, hop_index=0 for plain ops, per-hop index for path payments — path payments expand to one row per hop so each hop stays individually idempotent).
  • astroml/db/repositories.py: NormalizedTransactionRepository gains get_by_natural_key(), upsert() and batch_upsert() (INSERT … ON CONFLICT DO UPDATE on the natural key); batch.py/stream.py write through them, so re-processing an already-normalized ledger range updates in place instead of duplicating.
  • migrations/versions/013_normalized_transaction_natural_key.py: adds ledger_sequence, operation_id, hop_index, the unique constraint uq_normalized_transactions_natural_key and helper index ix_normalized_transactions_operation, backfilling rows that already carry a parseable hash-link. Reversible.
  • Tests: tests/ingestion/test_normalized_idempotency.py (new, 308 lines, 17 tests) — repeat-write yields identical row counts, conflicting retries update rather than duplicate, hop expansion, natural-key derivation from toids.

#720 — Secrets scanning must fail builds, not just print

Problem: the CI scan used detect-secrets scan --baseline, which exits 0 even when brand-new secrets appear, and anything whitelisted in the baseline without an audit decision passes forever.

What was done:

  • New astroml/ci/secrets_gate.py: diffs a live scan against .secrets.baseline and exits 1 on (a) detections absent from the baseline, (b) baseline entries with no audit decision, (c) entries audited as true secrets; exits 2 when the scanner itself is broken (missing binary, malformed JSON). Handles both baseline formats in the wild (v1.x audit section and legacy state.audit_data), and the gate never mutates the baseline.
  • Wired in as a local pre-commit hook (always_run), as make secrets-scan, and detect-secrets>=1.4.0 is now declared in requirements-dev.txt (the hook used it but it was never pinned).
  • .secrets.baseline re-audited: 92 pre-existing detections across 70 files reviewed — all are placeholders/test fixtures/docs examples — recorded with is_secret: False plus a review note, so the gate passes today and any new secret blocks CI.
  • SECRETS_SCANNING_GUIDE.md documents the gate, the exit codes, and the audit step when adding to the baseline.
  • Tests: tests/ci/test_secrets_gate.py (new, 12 tests) — clean scan, new-secret detection, audited-false passes, legacy/unaudited formats fail, is_secret: true fails, CLI exit codes 0/1/2 end-to-end against a real detect-secrets run.

#715 — Detect, retry and report flaky tests

Problem: flakes were re-run manually and never named, so the same test could hide for months.

What was done:

  • New pytest plugin astroml/testing/flaky.py: --flaky-retries N re-runs each failing test (first pass wins), names every test that needed >1 attempt, classifies it against the registry, and writes a machine-readable JSON report (--flaky-report); safe under xdist (per-worker report files). python -m astroml.testing.flaky <reports...> [--fail-on-new] merges repeated runs into one markdown summary and can fail when an unregistered test flakes, so the schedule reports instead of silently going green.
  • Registered via tests/conftest.py; with the default --flaky-retries 0 the plugin is completely inert — ordinary pytest runs are untouched.
  • tests/known_flaky.txt seeds the registry.
  • Tests: tests/testing/test_flaky_detection.py + tests/testing/test_flaky_aggregation.py (617 lines) covering retry semantics, classification, registry matching, report merging, --fail-on-new, and inert-by-default behavior.
  • Scheduling workflow attached, not committed: pushing .github/* requires the workflow scope, which this contributor token deliberately lacks. Full YAML below for a maintainer to drop in — it is a thin caller of the plugin, nothing else depends on it.
.github/workflows/flaky-detection.yml
name: Flaky test detection (#715)

# Attached, not committed: pushing workflow files from this contributor's
# token is blocked (no `workflow` scope). A maintainer can drop this file in
# as-is; the pytest plugin it calls is fully implemented in the PR.

on:
  schedule:
    - cron: "0 6 * * *"
  workflow_dispatch:

permissions:
  contents: read

jobs:
  hunt:
    name: Flaky hunt (run ${{ matrix.run }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        run: [1, 2, 3]

    services:
      postgres:
        image: postgres:14
        env:
          POSTGRES_DB: astroml_test
          POSTGRES_USER: astroml
          POSTGRES_PASSWORD: astroml
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U astroml -d astroml_test"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
      redis:
        image: redis:7
        ports:
          - 6379:6379

    env:
      DATABASE_URL: postgresql://astroml:astroml@localhost:5432/astroml_test
      REDIS_URL: redis://localhost:6379/0
      PYTHONPATH: .

    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip
          cache-dependency-path: |
            requirements*.txt
            pyproject.toml

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          python -m pip install -r requirements-cpu.txt -r requirements-api.txt -r requirements-dev.txt
          python -m pip install -e . --no-deps

      - name: Run suite with retries and per-run report
        run: >
          pytest tests/ -p no:randomly --flaky-retries 2
          --flaky-report flaky-report-run${{ matrix.run }}.json
        continue-on-error: true

      - uses: actions/upload-artifact@v4
        with:
          name: flaky-report-run${{ matrix.run }}
          path: flaky-report-run*.json

  report:
    name: Aggregate flaky report
    runs-on: ubuntu-latest
    needs: hunt
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - uses: actions/download-artifact@v4
        with:
          pattern: flaky-report-run*
          merge-multiple: true

      - name: Summarize and fail on unregistered flakes
        run: |
          python -m astroml.testing.flaky flaky-report-*.json --fail-on-new \
            >> "$GITHUB_STEP_SUMMARY"

Prerequisite repair (needed before any of the above could even be collected)

Three modules are broken on main itself — nothing that imports them can collect:

These are separate commits on the branch and can be reviewed or extracted standalone.

Testing

Local venv on the pinned Python 3.12.

  • All four issues' new suites green: 161 passed across tests/ci, tests/testing, tests/ingestion/test_normalized_idempotency.py, tests/features/graph/test_snapshot_ordering.py, plus the restored normalizer round-trip tests.
  • Migration chain verified: 012→013→014 upgrade and 014→012 downgrade render cleanly on the Postgres dialect; CI's postgres service exercises tests/test_migrations.py (it needs a live DB, same as on main).
  • Regression diff vs pristine origin/main (same worktree method, repairs copied in): zero new failures; the remaining failures (22) all reproduce on main untouched — e.g. the rfc7807 _parse_window_size gap, test_retry_logic.py, and test_edge_types Edge dataclass-acceptance are pre-existing upstream. This branch additionally fixes test_normalizer.py/test_stream.py collection errors and 10 test_cli_help/test_normalizer tests.
  • Repo-wide black/ruff are already red on main (171 files / 54 findings); everything added or rebuilt in this PR passes pinned black 24.4.2 + ruff 0.4.7, so the PR adds no new lint debt.
  • secrets-gate passes on the real repo (exit 0).

YazarAyobami and others added 6 commits September 26, 2026 10:26
…raqora#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 <noreply@anthropic.com>
…er (Traqora#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
  Traqora#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 <noreply@anthropic.com>
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 Traqora#715

Co-Authored-By: Claude Code <noreply@anthropic.com>
…ices

astroml/cache/graph_cache.py, astroml/ingestion/normalizer.py and
astroml/cli.py are all broken on origin/main itself: PRs Traqora#799 and Traqora#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 Traqora#978/Traqora#985 bodies, and reattach cli.py's
header from its pre-corruption lineage (normalized to LF, imports
sorted). Prerequisite for the Traqora#715/Traqora#728/Traqora#732/Traqora#720 work on this branch.
Closes Traqora#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.
@drips-wave

drips-wave Bot commented Sep 26, 2026

Copy link
Copy Markdown

@YazarAyobami Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown

📏 Pull request size warning

This pull request exceeds the review-friendly size limits. CI is not blocked — this is guidance, not a gate.

Metric This PR Limit
Lines changed 5022 1000
Files changed 26 10

Why it matters

Review quality drops sharply with diff size: defects slip through, review turnaround grows, and reverts become riskier because unrelated changes are bundled together.

What to do

  • Split the change into a stack of smaller, independently reviewable PRs.
  • Land refactors and behaviour changes separately.
  • Hide incomplete work behind a feature flag and merge it incrementally.
  • Move generated files, lockfiles, or vendored code into their own PR.

Legitimately large?

  • Add the refactor:large label to raise the file ceiling to 50 files.
  • Add [large PR] to the title to skip this check entirely.
Breached limits
  • 5022 lines changed (+4973/-49) exceeds the 1000-line limit.
  • 26 files changed exceeds the 10-file limit.

return EXIT_SCAN_ERROR

report = evaluate(scan_output, baseline)
print(report.format())
Comment thread astroml/cli.py Fixed
@gelluisaac
gelluisaac merged commit 38022c1 into Traqora:main Sep 28, 2026
10 of 38 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants