Skip to content

feat: YAML feature builders, feature caching, importance/selection, pipeline audit - #821

Merged
gelluisaac merged 2 commits into
Traqora:mainfrom
abercrombie04:feat/features-yaml-cache-importance-audit-742-743-744-757
Sep 28, 2026
Merged

gelluisaac merged 2 commits into
Traqora:mainfrom
abercrombie04:feat/features-yaml-cache-importance-audit-742-743-744-757

Conversation

@abercrombie04

Copy link
Copy Markdown

Closes #742
Closes #743
Closes #744
Closes #757

Overview

This PR implements four assigned feature-store and governance issues in one coherent change. They form a natural progression: features become declaratively configurable (#742), configurable features gain a transparent cache (#743), results become analyzable and selectable (#744), and the pipeline operations that change any of it become auditable (#757).

Changes

#742 — Add configurable feature-builder definitions (YAML)

New: astroml/features/yaml_builders.py

  • FeatureBuilderSpec: a frozen dataclass capturing name, description, primitive, inputs (entity / source / columns), window (7d, 12h, 30m, 45s), output_column, feature_type, tags, owner, and primitive-specific params. Invalid windows and empty names are rejected at construction.
  • load_feature_builder_specs(path): strict YAML loader — missing files, malformed YAML, a missing builders list, unknown keys (typo protection), duplicate names, and invalid feature_type values all raise BuilderSpecError with the offending index.
  • Eight built-in primitives: count, sum, mean, max, min, std, unique_count, ratio (all window-agnostic; the caller passes rows already filtered to the entity/window). Custom primitives merge over the built-ins via an explicit primitives= mapping; passing an explicit mapping replaces built-ins so callers can restrict the surface.
  • register_feature_builder_specs(registry, specs): registers each spec as a FeatureDefinition with its computer attached, tagging yaml_builder and recording a definition_hash in metadata — this hash is the cache-invalidation hook for Add caching layer for expensive features #743.
  • New: configs/feature_builders.yaml — six fully documented example builders (transaction counts, volume sums, averages, max single transaction, distinct counterparties, inbound/outbound ratio) that double as the documentation of the format.

Caching / recompute semantics (documented in module, config, and docs/FEATURE_STORE.md): every output-affecting field is part of the definition hash; changing YAML never silently reuses old values.

#743 — Add caching layer for expensive features

New: astroml/features/cached_builders.py

  • CachedFeatureBuilder wraps any builder spec with the existing FeatureCache backend (memory, disk, or Redis — reused from astroml.features.feature_cache / astroml.cache, per the issue's instruction).
  • Cache keys are (feature, window, data_version, definition_hash, entity, extra context) — deterministic and complete. compute returns a FeatureCacheResult (value, cache_hit, cache_key) so callers can observe hit rates; compute_batch handles many entities.
  • Invalidation on recompute: invalidate(key), recompute(key) (invalidate + compute), and invalidate_all() for hard resets. Bumping data_version forces global recompute after a data refresh; changing the YAML definition naturally orphans old entries (they expire via TTL/LRU rather than being read).

#744 — Add feature importance and selection utilities

New: astroml/features/importance.py

  • compute_permutation_importance(predict, X, y, ...): model-agnostic permutation importance — shuffles one column at a time, records the scorer drop vs. baseline. Default scorer is accuracy for binary targets and R² otherwise; custom scorers are supported. Seeded RNG gives reproducible reports; results are plain dataclasses (FeatureImportanceReport, with ranked(), top_k(), to_frame()).
  • select_features(X, y, predict=None, ...): transparent selection combining
    • static filters — variance, missing-rate, and correlation (defaults mirror the thresholds already documented in configs/feature_engineering.yaml; the correlation filter handles constant/all-NaN columns safely under pandas 3.x),
    • optional importance threshold and top_k cuts when a predictor is supplied.
    • SelectionReport.dropped records a human-readable reason per dropped column, and .transform(X) applies the selection.

#757 — Add audit logging for critical pipeline operations

New: astroml/tracking/pipeline_audit.py

  • PipelineAuditLogger records frozen, who/what/when/result records for model_activated, model_deactivated, model_rolled_back, config_changed, config_rolled_back, and feature_config_changed.
  • Reuses the governance AuditStore backends (InMemoryAuditStore for tests, append-only FileAuditStore NDJSON for production) — no new infrastructure, aligned with docs/AUDIT_TRAIL.md conventions.
  • Tamper evidence: records are hash-chained (each stores its predecessor's hash plus a content hash); verify_chain() detects edits, deletions, or reordering. The chain survived a subtle bug hunt: timestamps must propagate through the store roundtrip and ordering must use the sequence id (timestamps can tie), both covered by tests.
  • docs/AUDIT_TRAIL.md gains a full "Pipeline Audit Logging (Issue Add audit logging for critical pipeline operations #757)" section (operations table, tamper-evidence, usage, retention).

Tests (85 new, all passing)

  • tests/features/test_yaml_builders.py — window parsing, strict YAML loading (9 error paths), every primitive's math including empty/degenerate inputs, definition-hash stability/sensitivity, registry integration, and a guard that the shipped example config always loads.
  • tests/features/test_cached_builders.py — key construction across all dimensions, hit/miss transitions, entity isolation, data-version bumps forcing recompute, invalidate/recompute semantics, batch API, stats, and unknown-primitive errors.
  • tests/features/test_importance.py — signal-dominates-noise ranking, exact baseline scoring, seed reproducibility, feature subsets, error paths, frame rendering, binary-target scoring, and each filter/selection path.
  • tests/tracking/test_pipeline_audit.py — who/what/when/result capture, record immutability, chain verification (including two tamper scenarios), query filters, file-store roundtrip, and UTC/monotonic timestamps.

Repo health fix (required for CI to run at all)

astroml/cache/graph_cache.py was left unimportable on current main — the #818 merge concatenated two module docstrings (leaving the second's em-dash as bare code, SyntaxError: invalid character '—') and interleaved class bodies from two incompatible implementations (self._lru/self._redis vs _MemoryGraphStore). Every pytest collection in CI would fail on import astroml.cache. This PR restores the last coherent implementation (the decorator + GraphCacheStats API that tests/test_cache_invalidation.py targets) and adds the cached_graph_computation decorator the package __init__ exports but no surviving version defined. All 15 cache-invalidation tests pass again.

Verification

  • pytest tests/features/test_yaml_builders.py tests/features/test_cached_builders.py tests/features/test_importance.py tests/tracking/test_pipeline_audit.py tests/test_cache_invalidation.py → 99 passed
  • black --check on all touched files → clean (remaining reformat candidates in astroml/features/ are pre-existing files this PR does not touch)
  • ruff check on all touched files → clean
  • mypy on the four new modules → clean
  • Documentation updated in docs/AUDIT_TRAIL.md, docs/FEATURE_STORE.md, and inline module/config docstrings

…ipeline audit

Implements four feature-store and governance issues in one coherent change.

Closes Traqora#742
Closes Traqora#743
Closes Traqora#744
Closes Traqora#757

Traqora#742 — YAML-configurable feature builders:
- astroml/features/yaml_builders.py defines FeatureBuilderSpec
  (name, description, primitive, inputs, window, output_column, tags),
  a strict loader (unknown keys, duplicate names, and bad windows fail
  loudly), eight built-in primitives (count, sum, mean, max, min, std,
  unique_count, ratio), and registration into FeatureRegistryService.
- configs/feature_builders.yaml ships six documented example builders.

Traqora#743 — caching layer for expensive features:
- astroml/features/cached_builders.py wraps builders with a transparent
  FeatureCache (memory/disk/Redis) keyed by
  (feature, window, data_version, definition_hash, entity). Definition
  changes produce new keys so stale entries expire naturally; explicit
  invalidate/recompute/invalidate_all cover forced refreshes.

Traqora#744 — feature importance and selection:
- astroml/features/importance.py adds model-agnostic permutation
  importance (R2 or accuracy scorer) and select_features with
  variance/missing/correlation filters plus importance-threshold and
  top-k cuts, mirroring configs/feature_engineering.yaml thresholds.

Traqora#757 — audit logging for critical pipeline operations:
- astroml/tracking/pipeline_audit.py records immutable, hash-chained
  who/what/when/result records for model activations, config changes,
  and rollbacks, reusing the governance AuditStore backends; verify_chain
  detects tampered history. Documented in docs/AUDIT_TRAIL.md; usage of
  all three feature modules documented in docs/FEATURE_STORE.md.

Also repairs astroml/cache/graph_cache.py, which was left unimportable on
main by an earlier merge (two concatenated module docstrings left bare
code and interleaved class bodies from two implementations). Restored the
last coherent version (decorators + GraphCacheStats API) and added the
cached_graph_computation decorator the package __init__ exports; all 15
tests in tests/test_cache_invalidation.py pass again.
@drips-wave

drips-wave Bot commented Sep 24, 2026

Copy link
Copy Markdown

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

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

Learn more about application limits

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

📏 Pull request size warning

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

Metric This PR Limit
Lines changed 2460 1000
Files changed 12 10

Why it matters

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

What to do

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

Legitimately large?

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

@gelluisaac
gelluisaac merged commit 6639624 into Traqora:main Sep 28, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants