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 a0303aff..85c652c6 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/cache/graph_cache.py b/astroml/cache/graph_cache.py index 1bc106d0..9b46fce4 100644 --- a/astroml/cache/graph_cache.py +++ b/astroml/cache/graph_cache.py @@ -343,6 +343,7 @@ def __init__( """ if getattr(self, "_initialized", False): return + self.config = config or GraphCacheConfig() self._stats = GraphCacheStats() self._store: _MemoryGraphStore | None = None 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/astroml/db/models/__init__.py b/astroml/db/models/__init__.py index 4af493ad..1399f90e 100644 --- a/astroml/db/models/__init__.py +++ b/astroml/db/models/__init__.py @@ -243,15 +243,41 @@ 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", - "timestamp"), Index("ix_normalized_transactions_receiver_timestamp", "receiver", "timestamp", postgresql_where=(receiver.isnot(None)))) + __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))), + # 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/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/features/graph/snapshot.py b/astroml/features/graph/snapshot.py index c3818cb1..e46ad6f0 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 @@ -8,6 +35,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 @@ -172,14 +200,61 @@ def __repr__(self) -> str: ) +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) @@ -194,6 +269,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). @@ -207,6 +291,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) @@ -302,6 +391,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. @@ -341,6 +476,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 @@ -387,7 +529,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) ) @@ -557,7 +701,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 @@ -647,7 +794,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] = [] @@ -667,13 +816,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/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 18c95001..17364fa8 100644 --- a/astroml/ingestion/normalizer.py +++ b/astroml/ingestion/normalizer.py @@ -20,9 +20,25 @@ _parse_datetime, extract_asset_string, 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. @@ -40,9 +56,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, @@ -54,6 +74,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. """ @@ -66,10 +90,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"], @@ -93,6 +121,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 # --------------------------------------------------------------------------- @@ -139,17 +177,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. @@ -169,6 +196,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] diff --git a/astroml/ingestion/parsers.py b/astroml/ingestion/parsers.py index fe534a7c..25480b20 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/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/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/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/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 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/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/ingestion/test_normalized_idempotency.py b/tests/ingestion/test_normalized_idempotency.py new file mode 100644 index 00000000..bafba183 --- /dev/null +++ b/tests/ingestion/test_normalized_idempotency.py @@ -0,0 +1,308 @@ +"""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) 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 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()