Repository navigation
feat: secrets gate, idempotent ingestion, total-ordered snapshots, flaky detection - #1026
Merged
Merged
Conversation
…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.
|
@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! 🚀 |
📏 Pull request size warningThis pull request exceeds the review-friendly size limits. CI is not blocked — this is guidance, not a gate.
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
Legitimately large?
Breached limits
|
| return EXIT_SCAN_ERROR | ||
|
|
||
| report = evaluate(scan_output, baseline) | ||
| print(report.format()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):
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 readnormalized_transactionsordered 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()andvalidate_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: addsix_normalized_transactions_timestamp_orderon(timestamp, ledger_sequence, operation_id, hop_index)so the total-order read is index-backed (reversible; drops the index on downgrade).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.pyupdated 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:
(ledger_sequence, operation_id, hop_index).astroml/ingestion/parsers.pygainsledger_sequence_from_operation_id()(Horizon operation ids are toids, so the ledger is derived from the id — no extra column to backfill by hand), andnormalizer.pystamps the key (_natural_key,hop_index=0for 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:NormalizedTransactionRepositorygainsget_by_natural_key(),upsert()andbatch_upsert()(INSERT … ON CONFLICT DO UPDATE on the natural key);batch.py/stream.pywrite through them, so re-processing an already-normalized ledger range updates in place instead of duplicating.migrations/versions/013_normalized_transaction_natural_key.py: addsledger_sequence,operation_id,hop_index, the unique constraintuq_normalized_transactions_natural_keyand helper indexix_normalized_transactions_operation, backfilling rows that already carry a parseable hash-link. Reversible.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:
astroml/ci/secrets_gate.py: diffs a live scan against.secrets.baselineand 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.xauditsection and legacystate.audit_data), and the gate never mutates the baseline.always_run), asmake secrets-scan, anddetect-secrets>=1.4.0is now declared inrequirements-dev.txt(the hook used it but it was never pinned)..secrets.baselinere-audited: 92 pre-existing detections across 70 files reviewed — all are placeholders/test fixtures/docs examples — recorded withis_secret: Falseplus a review note, so the gate passes today and any new secret blocks CI.SECRETS_SCANNING_GUIDE.mddocuments the gate, the exit codes, and the audit step when adding to the baseline.tests/ci/test_secrets_gate.py(new, 12 tests) — clean scan, new-secret detection, audited-false passes, legacy/unaudited formats fail,is_secret: truefails, CLI exit codes 0/1/2 end-to-end against a realdetect-secretsrun.#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:
astroml/testing/flaky.py:--flaky-retries Nre-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.tests/conftest.py; with the default--flaky-retries 0the plugin is completely inert — ordinarypytestruns are untouched.tests/known_flaky.txtseeds the registry.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..github/*requires theworkflowscope, 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.ymlPrerequisite repair (needed before any of the above could even be collected)
Three modules are broken on
mainitself — nothing that imports them can collect:astroml/cache/graph_cache.py— PRs feat: parallelize snapshots, add graph cache, optimise backfill memory, enrich artifact metadata #799 and feat: enriched artifact metadata, chunked backfill memory opt, graph computation cache, serving-worker HPA #809 each added the file and the merge spliced both versions together (second docstring mid-file). Rebuilt from both sides; matches the API the Add tests for cache invalidation in astroml/cache #711/test(cache): add comprehensive tests for cache invalidation (#711) #818 cache tests expect (tests/test_graph_cache.py,tests/test_cache_invalidation.pynow pass).astroml/ingestion/normalizer.py— the [testing] Snapshot restore test #978 and [testing] Snapshot restore test #985 helpers were interleaved mid-docstring. Restored to the original0fb80a6/3befd6bbodies verbatim.astroml/cli.py— lost its import block andmain()header in the same lineage of merges; reattached from its pre-corruption version (normalized to LF, imports sorted).tests/test_cli_help.pygoes 9-failing → 9-passing.These are separate commits on the branch and can be reviewed or extracted standalone.
Testing
Local venv on the pinned Python 3.12.
tests/ci,tests/testing,tests/ingestion/test_normalized_idempotency.py,tests/features/graph/test_snapshot_ordering.py, plus the restored normalizer round-trip tests.tests/test_migrations.py(it needs a live DB, same as onmain).origin/main(same worktree method, repairs copied in): zero new failures; the remaining failures (22) all reproduce onmainuntouched — e.g. the rfc7807_parse_window_sizegap,test_retry_logic.py, andtest_edge_typesEdgedataclass-acceptance are pre-existing upstream. This branch additionally fixestest_normalizer.py/test_stream.pycollection errors and 10test_cli_help/test_normalizertests.black/ruffare already red onmain(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-gatepasses on the real repo (exit 0).