targeted-sampler 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,32 @@
1
+ """Stratified, reason-bucketed sample collector with pinning and disk-budget rotation."""
2
+
3
+ from .config import CaptureConfig, TargetRule, load_targets, load_pinned_ids
4
+ from .decision import should_capture
5
+ from .models import (
6
+ BucketKey,
7
+ CaptureDecision,
8
+ RecordOutcome,
9
+ SampleEvent,
10
+ SampleRecord,
11
+ SamplerState,
12
+ compute_fingerprint,
13
+ )
14
+ from .store import SampleStore
15
+
16
+ __all__ = [
17
+ "BucketKey",
18
+ "CaptureConfig",
19
+ "CaptureDecision",
20
+ "RecordOutcome",
21
+ "SampleEvent",
22
+ "SampleRecord",
23
+ "SampleStore",
24
+ "SamplerState",
25
+ "TargetRule",
26
+ "compute_fingerprint",
27
+ "load_pinned_ids",
28
+ "load_targets",
29
+ "should_capture",
30
+ ]
31
+
32
+ __version__ = "0.1.0"
@@ -0,0 +1,104 @@
1
+ """Command-line interface for inspecting and maintaining a SampleStore."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from typing import Sequence
9
+
10
+ from .config import CaptureConfig
11
+ from .store import SampleStore
12
+
13
+
14
+ def _build_parser() -> argparse.ArgumentParser:
15
+ parser = argparse.ArgumentParser(
16
+ prog="targeted-sampler",
17
+ description="Inspect, verify, and prune stratified reason-bucketed sample stores.",
18
+ )
19
+ sub = parser.add_subparsers(dest="command", required=True)
20
+
21
+ for cmd_name, help_text in (
22
+ ("stats", "Show per-bucket sample counts and disk usage."),
23
+ ("verify", "Verify metadata integrity and artifact references."),
24
+ ("prune", "Enforce bucket limits and disk budget without deleting pinned samples."),
25
+ ):
26
+ p = sub.add_parser(cmd_name, help=help_text)
27
+ p.add_argument("--root", required=True, help="Path to sample store directory.")
28
+ p.add_argument("--targets", default=None, help="Optional path to capture_targets.json.")
29
+ p.add_argument("--pinned", default=None, help="Optional path to pinned labels JSON.")
30
+ p.add_argument("--bucket-limit", type=int, default=15, help="Default per-bucket limit.")
31
+ p.add_argument("--max-mb", type=float, default=200.0, help="Global disk budget in MB.")
32
+ p.add_argument(
33
+ "--format",
34
+ choices=("table", "json"),
35
+ default="table",
36
+ help="Output format (table or json).",
37
+ )
38
+ return parser
39
+
40
+
41
+ def _render_stats_table(data: dict) -> str:
42
+ lines = [
43
+ f"Root: {data['root_dir']}",
44
+ f"Samples: {data['total_samples']} (pinned={data['pinned_samples']}, unpinned={data['unpinned_samples']})",
45
+ f"Disk: {data['total_bytes']} / {data['max_total_bytes']} bytes (corrupt_meta={data['corrupt_metadata_count']})",
46
+ "",
47
+ f"{'BUCKET':<52} {'TOTAL':>5} {'PIN':>4} {'BYTES':>10}",
48
+ "-" * 75,
49
+ ]
50
+ for key, info in sorted(data["buckets"].items()):
51
+ lines.append(f"{key:<52} {info['total']:>5} {info['pinned']:>4} {info['bytes']:>10}")
52
+ return "\n".join(lines)
53
+
54
+
55
+ def main(argv: Sequence[str] | None = None) -> int:
56
+ parser = _build_parser()
57
+ args = parser.parse_args(argv)
58
+
59
+ cfg = CaptureConfig(
60
+ bucket_limit=args.bucket_limit,
61
+ max_total_bytes=max(1, int(args.max_mb * 1024 * 1024)),
62
+ )
63
+ store = SampleStore(
64
+ root_dir=args.root,
65
+ config=cfg,
66
+ targets_path=args.targets,
67
+ pinned_path=args.pinned,
68
+ )
69
+
70
+ if args.command == "stats":
71
+ result = store.stats()
72
+ if args.format == "json":
73
+ print(json.dumps(result, ensure_ascii=False, indent=2))
74
+ else:
75
+ print(_render_stats_table(result))
76
+ return 0
77
+
78
+ if args.command == "verify":
79
+ result = store.verify()
80
+ if args.format == "json":
81
+ print(json.dumps(result, ensure_ascii=False, indent=2))
82
+ else:
83
+ status = "OK" if result["ok"] else "ISSUES FOUND"
84
+ print(
85
+ f"Verify: {status} (valid={result['valid_samples']}, "
86
+ f"corrupt={len(result['corrupt_metadata_files'])}, "
87
+ f"missing_artifacts={len(result['missing_artifacts'])})"
88
+ )
89
+ return 0 if result["ok"] else 1
90
+
91
+ if args.command == "prune":
92
+ evicted = store.prune()
93
+ result = {"evicted_count": len(evicted), "evicted_ids": list(evicted)}
94
+ if args.format == "json":
95
+ print(json.dumps(result, ensure_ascii=False, indent=2))
96
+ else:
97
+ print(f"Pruned {len(evicted)} unpinned sample(s).")
98
+ return 0
99
+
100
+ return 2
101
+
102
+
103
+ if __name__ == "__main__":
104
+ sys.exit(main())
@@ -0,0 +1,191 @@
1
+ """Configuration and dynamic target-rule loading for targeted-sampler."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import json
7
+ import logging
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .models import BucketKey
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class CaptureConfig:
18
+ """Global sampling and disk-budget settings."""
19
+
20
+ bucket_limit: int = 15
21
+ single_blocker_bucket_limit: int | None = None
22
+ max_total_bytes: int = 200 * 1024 * 1024 # 200 MB
23
+ single_blocker_only: bool = False
24
+
25
+ def __post_init__(self) -> None:
26
+ if self.bucket_limit < 0:
27
+ raise ValueError("bucket_limit must be >= 0")
28
+ if self.single_blocker_bucket_limit is not None and self.single_blocker_bucket_limit < 0:
29
+ raise ValueError("single_blocker_bucket_limit must be >= 0")
30
+ if self.max_total_bytes <= 0:
31
+ raise ValueError("max_total_bytes must be > 0")
32
+
33
+ def default_limit_for(self, bucket: BucketKey) -> int:
34
+ if bucket.single_blocker and self.single_blocker_bucket_limit is not None:
35
+ return self.single_blocker_bucket_limit
36
+ return self.bucket_limit
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class TargetRule:
41
+ """Dynamic priority/force-capture override for matching buckets.
42
+
43
+ Any pattern field set to ``"*"`` or ``None`` acts as a wildcard.
44
+ """
45
+
46
+ name: str
47
+ kind: str | None = None
48
+ single_blocker: bool | None = None
49
+ primary_key: str | None = None
50
+ reason_code: str | None = None
51
+ bucket_limit: int | None = None
52
+ force_capture: bool = False
53
+ priority: int = 100
54
+ enabled: bool = True
55
+
56
+ def matches(self, bucket: BucketKey) -> bool:
57
+ if not self.enabled:
58
+ return False
59
+ if self.kind not in (None, "*") and self.kind != bucket.kind:
60
+ return False
61
+ if self.single_blocker is not None and self.single_blocker != bucket.single_blocker:
62
+ return False
63
+ if self.primary_key not in (None, "*") and self.primary_key != bucket.primary_key:
64
+ return False
65
+ if self.reason_code not in (None, "*") and self.reason_code != bucket.reason_code:
66
+ return False
67
+ return True
68
+
69
+ @classmethod
70
+ def from_dict(cls, payload: dict[str, Any], index: int = 0) -> TargetRule:
71
+ bucket_limit_raw = payload.get("bucket_limit")
72
+ bucket_limit = int(bucket_limit_raw) if bucket_limit_raw is not None else None
73
+ if bucket_limit is not None and bucket_limit < 0:
74
+ raise ValueError("TargetRule.bucket_limit must be >= 0")
75
+ sb = payload.get("single_blocker")
76
+ if sb is not None and not isinstance(sb, bool):
77
+ raise ValueError("TargetRule.single_blocker must be bool or null")
78
+ return cls(
79
+ name=str(payload.get("name") or f"target-{index}"),
80
+ kind=payload.get("kind"),
81
+ single_blocker=sb,
82
+ primary_key=payload.get("primary_key"),
83
+ reason_code=payload.get("reason_code"),
84
+ bucket_limit=bucket_limit,
85
+ force_capture=bool(payload.get("force_capture", False)),
86
+ priority=int(payload.get("priority", 100)),
87
+ enabled=bool(payload.get("enabled", True)),
88
+ )
89
+
90
+
91
+ def load_targets(path: str | Path | None) -> tuple[TargetRule, ...]:
92
+ """Load dynamic capture targets from a JSON file.
93
+
94
+ Returns an empty tuple on missing or corrupt files (fail-safe).
95
+ Supported schemas:
96
+ - ``{"targets": [{...}, ...]}``
97
+ - ``[{...}, ...]``
98
+ """
99
+ if path is None:
100
+ return ()
101
+ target_path = Path(path)
102
+ if not target_path.exists():
103
+ return ()
104
+ try:
105
+ raw = json.loads(target_path.read_text(encoding="utf-8"))
106
+ except (OSError, json.JSONDecodeError) as exc:
107
+ logger.warning("Failed to load capture targets from %s: %s", target_path, exc)
108
+ return ()
109
+
110
+ items = raw.get("targets") if isinstance(raw, dict) else raw
111
+ if not isinstance(items, list):
112
+ logger.warning("Invalid capture targets format in %s: expected list", target_path)
113
+ return ()
114
+
115
+ rules: list[TargetRule] = []
116
+ for idx, entry in enumerate(items):
117
+ if not isinstance(entry, dict):
118
+ logger.warning("Skipping non-object target rule at index %d in %s", idx, target_path)
119
+ continue
120
+ try:
121
+ rules.append(TargetRule.from_dict(entry, index=idx))
122
+ except (TypeError, ValueError) as exc:
123
+ logger.warning("Skipping invalid target rule at index %d in %s: %s", idx, target_path, exc)
124
+ return tuple(rules)
125
+
126
+
127
+ def load_pinned_ids(path: str | Path | None) -> tuple[frozenset[str], frozenset[str]]:
128
+ """Load pinned fingerprints and sample IDs from an external JSON file.
129
+
130
+ Supports flexible schemas so upstream label/regression registries can be
131
+ plugged in without coupling:
132
+ - ``{"pinned_fingerprints": [...], "pinned_sample_ids": [...]}``
133
+ - ``{"labels": [{"sample_id": ..., "fingerprint": ...}, ...]}``
134
+ - ``[{"sample_id": ..., "fingerprint": ...}, ...]``
135
+ Returns ``(pinned_fingerprints, pinned_sample_ids)``; fails safe to empty sets.
136
+ """
137
+ if path is None:
138
+ return (frozenset(), frozenset())
139
+ pin_path = Path(path)
140
+ if not pin_path.exists():
141
+ return (frozenset(), frozenset())
142
+ try:
143
+ raw = json.loads(pin_path.read_text(encoding="utf-8"))
144
+ except (OSError, json.JSONDecodeError) as exc:
145
+ logger.warning("Failed to load pinned IDs from %s: %s", pin_path, exc)
146
+ return (frozenset(), frozenset())
147
+
148
+ fingerprints: set[str] = set()
149
+ sample_ids: set[str] = set()
150
+
151
+ if isinstance(raw, dict):
152
+ for fp in raw.get("pinned_fingerprints", []):
153
+ if isinstance(fp, str) and fp:
154
+ fingerprints.add(fp)
155
+ for sid in raw.get("pinned_sample_ids", []):
156
+ if isinstance(sid, str) and sid:
157
+ sample_ids.add(sid)
158
+ entries = raw.get("labels") or raw.get("items") or raw.get("records")
159
+ if isinstance(entries, list):
160
+ _collect_from_entries(entries, fingerprints, sample_ids)
161
+ elif isinstance(entries, dict):
162
+ for key, val in entries.items():
163
+ if isinstance(key, str) and key:
164
+ sample_ids.add(key)
165
+ if isinstance(val, dict):
166
+ _collect_entry(val, fingerprints, sample_ids)
167
+ elif isinstance(raw, list):
168
+ _collect_from_entries(raw, fingerprints, sample_ids)
169
+
170
+ return (frozenset(fingerprints), frozenset(sample_ids))
171
+
172
+
173
+ def _collect_from_entries(
174
+ entries: list[Any], fingerprints: set[str], sample_ids: set[str]
175
+ ) -> None:
176
+ for item in entries:
177
+ if isinstance(item, dict):
178
+ _collect_entry(item, fingerprints, sample_ids)
179
+ elif isinstance(item, str) and item:
180
+ sample_ids.add(item)
181
+
182
+
183
+ def _collect_entry(
184
+ item: dict[str, Any], fingerprints: set[str], sample_ids: set[str]
185
+ ) -> None:
186
+ fp = item.get("fingerprint") or item.get("sha256")
187
+ if isinstance(fp, str) and fp:
188
+ fingerprints.add(fp)
189
+ sid = item.get("sample_id") or item.get("id")
190
+ if isinstance(sid, str) and sid:
191
+ sample_ids.add(sid)
@@ -0,0 +1,210 @@
1
+ """Pure, deterministic capture and eviction decision logic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Sequence
6
+
7
+ from .config import CaptureConfig, TargetRule
8
+ from .models import BucketKey, CaptureDecision, SampleEvent, SampleRecord, SamplerState
9
+
10
+
11
+ def _match_best_target(
12
+ bucket: BucketKey, targets: Sequence[TargetRule]
13
+ ) -> TargetRule | None:
14
+ matched = [rule for rule in targets if rule.matches(bucket)]
15
+ if not matched:
16
+ return None
17
+ # Higher priority wins; ties broken by declaration order.
18
+ matched.sort(key=lambda r: -r.priority)
19
+ return matched[0]
20
+
21
+
22
+ def _effective_bucket_limit(
23
+ bucket: BucketKey, config: CaptureConfig, target: TargetRule | None
24
+ ) -> int:
25
+ if target is not None and target.bucket_limit is not None:
26
+ return target.bucket_limit
27
+ return config.default_limit_for(bucket)
28
+
29
+
30
+ def _is_targeted(bucket: BucketKey, targets: Sequence[TargetRule]) -> bool:
31
+ return _match_best_target(bucket, targets) is not None
32
+
33
+
34
+ def should_capture(
35
+ event: SampleEvent,
36
+ state: SamplerState,
37
+ config: CaptureConfig | None = None,
38
+ targets: Sequence[TargetRule] = (),
39
+ ) -> CaptureDecision:
40
+ """Decide whether to capture ``event`` and which unpinned records to evict.
41
+
42
+ This function is completely pure (no filesystem, clock, or network side effects).
43
+ """
44
+ cfg = config or CaptureConfig()
45
+ target = _match_best_target(event.bucket, targets)
46
+ limit = _effective_bucket_limit(event.bucket, cfg, target)
47
+ target_name = target.name if target is not None else None
48
+
49
+ if event.size_bytes < 0:
50
+ return CaptureDecision(
51
+ capture=False,
52
+ reason="invalid_size_bytes",
53
+ effective_bucket_limit=limit,
54
+ matched_target=target_name,
55
+ )
56
+
57
+ if event.size_bytes > cfg.max_total_bytes:
58
+ return CaptureDecision(
59
+ capture=False,
60
+ reason="single_sample_exceeds_disk_budget",
61
+ effective_bucket_limit=limit,
62
+ matched_target=target_name,
63
+ )
64
+
65
+ # Deduplicate by SHA-256 fingerprint
66
+ if event.fingerprint in state.fingerprints:
67
+ return CaptureDecision(
68
+ capture=False,
69
+ reason="duplicate_fingerprint",
70
+ effective_bucket_limit=limit,
71
+ matched_target=target_name,
72
+ )
73
+
74
+ # Optional single-blocker-only mode unless overridden by target force_capture
75
+ if cfg.single_blocker_only and not event.bucket.single_blocker:
76
+ if target is None or not target.force_capture:
77
+ return CaptureDecision(
78
+ capture=False,
79
+ reason="non_single_blocker_filtered",
80
+ effective_bucket_limit=limit,
81
+ matched_target=target_name,
82
+ )
83
+
84
+ if limit == 0 and (target is None or not target.force_capture):
85
+ return CaptureDecision(
86
+ capture=False,
87
+ reason="bucket_limit_zero",
88
+ effective_bucket_limit=limit,
89
+ matched_target=target_name,
90
+ )
91
+
92
+ evict_ids: list[str] = []
93
+ evicted_set: set[str] = set()
94
+
95
+ # Step 1: Per-bucket ring buffer cap (only unpinned records count toward eviction;
96
+ # pinned records are NEVER evicted).
97
+ bucket_records = state.records_in_bucket(event.bucket)
98
+ unpinned_in_bucket = sorted(
99
+ (r for r in bucket_records if not state.is_pinned(r)),
100
+ key=lambda r: (r.timestamp, r.sample_id),
101
+ )
102
+
103
+ if limit > 0 and len(unpinned_in_bucket) >= limit:
104
+ # Ring buffer: make room for the incoming newest sample by evicting oldest unpinned
105
+ excess = len(unpinned_in_bucket) - limit + 1
106
+ for victim in unpinned_in_bucket[:excess]:
107
+ evict_ids.append(victim.sample_id)
108
+ evicted_set.add(victim.sample_id)
109
+
110
+ # Step 2: Enforce global disk capacity cap (never evicting pinned samples).
111
+ remaining_records = [r for r in state.records if r.sample_id not in evicted_set]
112
+ projected_bytes = sum(r.size_bytes for r in remaining_records) + event.size_bytes
113
+
114
+ if projected_bytes > cfg.max_total_bytes:
115
+ candidates = [r for r in remaining_records if not state.is_pinned(r)]
116
+ # Eviction order:
117
+ # 1. Non-targeted, non-single-blocker oldest first
118
+ # 2. Non-targeted, single-blocker oldest first
119
+ # 3. Targeted oldest first (never evicting from same bucket unless necessary)
120
+ candidates.sort(
121
+ key=lambda r: (
122
+ 1 if _is_targeted(r.bucket, targets) else 0,
123
+ 1 if r.bucket.single_blocker else 0,
124
+ 1 if r.bucket == event.bucket else 0,
125
+ r.timestamp,
126
+ r.sample_id,
127
+ )
128
+ )
129
+ for victim in candidates:
130
+ if projected_bytes <= cfg.max_total_bytes:
131
+ break
132
+ evict_ids.append(victim.sample_id)
133
+ evicted_set.add(victim.sample_id)
134
+ projected_bytes -= victim.size_bytes
135
+
136
+ if projected_bytes > cfg.max_total_bytes:
137
+ return CaptureDecision(
138
+ capture=False,
139
+ reason="disk_budget_exhausted_by_pinned",
140
+ evict_ids=(),
141
+ effective_bucket_limit=limit,
142
+ matched_target=target_name,
143
+ )
144
+
145
+ if target is not None and target.force_capture:
146
+ reason = "capture_target_forced"
147
+ elif target is not None:
148
+ reason = "capture_target_priority"
149
+ elif evict_ids:
150
+ reason = "capture_with_rotation"
151
+ else:
152
+ reason = "capture_within_bucket_limit"
153
+
154
+ return CaptureDecision(
155
+ capture=True,
156
+ reason=reason,
157
+ evict_ids=tuple(evict_ids),
158
+ effective_bucket_limit=limit,
159
+ matched_target=target_name,
160
+ )
161
+
162
+
163
+ def plan_prune(
164
+ state: SamplerState,
165
+ config: CaptureConfig | None = None,
166
+ targets: Sequence[TargetRule] = (),
167
+ ) -> tuple[str, ...]:
168
+ """Compute which unpinned sample IDs should be evicted to satisfy current caps."""
169
+ cfg = config or CaptureConfig()
170
+ evict_ids: list[str] = []
171
+ evicted_set: set[str] = set()
172
+
173
+ # Per-bucket caps
174
+ buckets: dict[BucketKey, list[SampleRecord]] = {}
175
+ for rec in state.records:
176
+ buckets.setdefault(rec.bucket, []).append(rec)
177
+
178
+ for bucket, records in buckets.items():
179
+ target = _match_best_target(bucket, targets)
180
+ limit = _effective_bucket_limit(bucket, cfg, target)
181
+ unpinned = sorted(
182
+ (r for r in records if not state.is_pinned(r)),
183
+ key=lambda r: (r.timestamp, r.sample_id),
184
+ )
185
+ if len(unpinned) > limit:
186
+ for victim in unpinned[: len(unpinned) - limit]:
187
+ evict_ids.append(victim.sample_id)
188
+ evicted_set.add(victim.sample_id)
189
+
190
+ # Global disk budget
191
+ remaining = [r for r in state.records if r.sample_id not in evicted_set]
192
+ total_bytes = sum(r.size_bytes for r in remaining)
193
+ if total_bytes > cfg.max_total_bytes:
194
+ candidates = [r for r in remaining if not state.is_pinned(r)]
195
+ candidates.sort(
196
+ key=lambda r: (
197
+ 1 if _is_targeted(r.bucket, targets) else 0,
198
+ 1 if r.bucket.single_blocker else 0,
199
+ r.timestamp,
200
+ r.sample_id,
201
+ )
202
+ )
203
+ for victim in candidates:
204
+ if total_bytes <= cfg.max_total_bytes:
205
+ break
206
+ evict_ids.append(victim.sample_id)
207
+ evicted_set.add(victim.sample_id)
208
+ total_bytes -= victim.size_bytes
209
+
210
+ return tuple(evict_ids)
@@ -0,0 +1,173 @@
1
+ """Core data models for stratified reason-bucketed sample collection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime, timezone
7
+ import hashlib
8
+ from typing import Any
9
+
10
+
11
+ def utc_now_iso() -> str:
12
+ """Return current UTC timestamp in ISO-8601 format."""
13
+ return datetime.now(timezone.utc).isoformat()
14
+
15
+
16
+ def compute_fingerprint(data: bytes) -> str:
17
+ """Compute a canonical SHA-256 hex digest for deduplication."""
18
+ return hashlib.sha256(data).hexdigest()
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class BucketKey:
23
+ """Stratification key for grouping samples by document type and blocker reason."""
24
+
25
+ kind: str
26
+ single_blocker: bool
27
+ primary_key: str
28
+ reason_code: str
29
+
30
+ def canonical(self) -> str:
31
+ """Return a stable string representation."""
32
+ scope = "single" if self.single_blocker else "multi"
33
+ return f"{self.kind}|{scope}|{self.primary_key}|{self.reason_code}"
34
+
35
+ def to_dict(self) -> dict[str, Any]:
36
+ return {
37
+ "kind": self.kind,
38
+ "single_blocker": self.single_blocker,
39
+ "primary_key": self.primary_key,
40
+ "reason_code": self.reason_code,
41
+ }
42
+
43
+ @classmethod
44
+ def from_dict(cls, payload: dict[str, Any]) -> BucketKey:
45
+ return cls(
46
+ kind=str(payload["kind"]),
47
+ single_blocker=bool(payload["single_blocker"]),
48
+ primary_key=str(payload["primary_key"]),
49
+ reason_code=str(payload["reason_code"]),
50
+ )
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class SampleEvent:
55
+ """Incoming candidate sample to evaluate for capture."""
56
+
57
+ sample_id: str
58
+ bucket: BucketKey
59
+ fingerprint: str
60
+ size_bytes: int
61
+ timestamp: str = field(default_factory=utc_now_iso)
62
+ metadata: dict[str, Any] = field(default_factory=dict)
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class SampleRecord:
67
+ """Stored sample metadata tracked by SamplerState and SampleStore."""
68
+
69
+ sample_id: str
70
+ bucket: BucketKey
71
+ fingerprint: str
72
+ size_bytes: int
73
+ timestamp: str
74
+ pinned: bool = False
75
+ artifact_relpath: str | None = None
76
+ layout_relpath: str | None = None
77
+ metadata: dict[str, Any] = field(default_factory=dict)
78
+
79
+ def to_dict(self) -> dict[str, Any]:
80
+ return {
81
+ "sample_id": self.sample_id,
82
+ "bucket": self.bucket.to_dict(),
83
+ "fingerprint": self.fingerprint,
84
+ "size_bytes": self.size_bytes,
85
+ "timestamp": self.timestamp,
86
+ "pinned": self.pinned,
87
+ "artifact_relpath": self.artifact_relpath,
88
+ "layout_relpath": self.layout_relpath,
89
+ "metadata": dict(self.metadata),
90
+ }
91
+
92
+ @classmethod
93
+ def from_dict(cls, payload: dict[str, Any]) -> SampleRecord:
94
+ size_bytes = int(payload["size_bytes"])
95
+ if size_bytes < 0:
96
+ raise ValueError("size_bytes must be non-negative")
97
+ return cls(
98
+ sample_id=str(payload["sample_id"]),
99
+ bucket=BucketKey.from_dict(payload["bucket"]),
100
+ fingerprint=str(payload["fingerprint"]),
101
+ size_bytes=size_bytes,
102
+ timestamp=str(payload["timestamp"]),
103
+ pinned=bool(payload.get("pinned", False)),
104
+ artifact_relpath=payload.get("artifact_relpath"),
105
+ layout_relpath=payload.get("layout_relpath"),
106
+ metadata=dict(payload.get("metadata") or {}),
107
+ )
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class SamplerState:
112
+ """Immutable snapshot of currently stored samples and pinned identifiers."""
113
+
114
+ records: tuple[SampleRecord, ...] = ()
115
+ pinned_fingerprints: frozenset[str] = frozenset()
116
+ pinned_sample_ids: frozenset[str] = frozenset()
117
+
118
+ def is_pinned(self, record: SampleRecord) -> bool:
119
+ """Return True if a record is protected from eviction."""
120
+ return (
121
+ record.pinned
122
+ or record.fingerprint in self.pinned_fingerprints
123
+ or record.sample_id in self.pinned_sample_ids
124
+ )
125
+
126
+ @property
127
+ def total_bytes(self) -> int:
128
+ return sum(r.size_bytes for r in self.records)
129
+
130
+ @property
131
+ def fingerprints(self) -> frozenset[str]:
132
+ return frozenset(r.fingerprint for r in self.records)
133
+
134
+ def records_in_bucket(self, bucket: BucketKey) -> list[SampleRecord]:
135
+ return [r for r in self.records if r.bucket == bucket]
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class CaptureDecision:
140
+ """Pure, deterministic decision returned by should_capture()."""
141
+
142
+ capture: bool
143
+ reason: str
144
+ evict_ids: tuple[str, ...] = ()
145
+ effective_bucket_limit: int = 0
146
+ matched_target: str | None = None
147
+
148
+ def to_dict(self) -> dict[str, Any]:
149
+ return {
150
+ "capture": self.capture,
151
+ "reason": self.reason,
152
+ "evict_ids": list(self.evict_ids),
153
+ "effective_bucket_limit": self.effective_bucket_limit,
154
+ "matched_target": self.matched_target,
155
+ }
156
+
157
+
158
+ @dataclass(frozen=True)
159
+ class RecordOutcome:
160
+ """Result of SampleStore.safe_record() including non-fatal warnings."""
161
+
162
+ decision: CaptureDecision
163
+ stored: bool
164
+ evicted_ids: tuple[str, ...] = ()
165
+ warning: str | None = None
166
+
167
+ def to_dict(self) -> dict[str, Any]:
168
+ return {
169
+ "decision": self.decision.to_dict(),
170
+ "stored": self.stored,
171
+ "evicted_ids": list(self.evicted_ids),
172
+ "warning": self.warning,
173
+ }
File without changes
@@ -0,0 +1,274 @@
1
+ """Fail-safe local filesystem store for stratified samples."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from pathlib import Path
8
+ import re
9
+ from typing import Any
10
+
11
+ from .config import CaptureConfig, TargetRule, load_pinned_ids, load_targets
12
+ from .decision import plan_prune, should_capture
13
+ from .models import CaptureDecision, RecordOutcome, SampleEvent, SampleRecord, SamplerState
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ _SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
18
+
19
+
20
+ def _safe_filename(raw: str) -> str:
21
+ cleaned = _SAFE_NAME_RE.sub("_", raw).strip("._")
22
+ return cleaned or "sample"
23
+
24
+
25
+ class SampleStore:
26
+ """Manages stratified sample artifacts, metadata, and safe rotation on disk.
27
+
28
+ Directory layout under ``root_dir``:
29
+ - ``meta/<sample_id>.json``
30
+ - ``artifacts/<sample_id><ext>``
31
+ - ``layouts/<sample_id>.layout.json``
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ root_dir: str | Path,
37
+ config: CaptureConfig | None = None,
38
+ targets_path: str | Path | None = None,
39
+ pinned_path: str | Path | None = None,
40
+ targets: tuple[TargetRule, ...] | None = None,
41
+ pinned_fingerprints: frozenset[str] = frozenset(),
42
+ pinned_sample_ids: frozenset[str] = frozenset(),
43
+ ) -> None:
44
+ self.root_dir = Path(root_dir)
45
+ self.meta_dir = self.root_dir / "meta"
46
+ self.artifacts_dir = self.root_dir / "artifacts"
47
+ self.layouts_dir = self.root_dir / "layouts"
48
+ self.config = config or CaptureConfig()
49
+ self.targets_path = Path(targets_path) if targets_path is not None else None
50
+ self.pinned_path = Path(pinned_path) if pinned_path is not None else None
51
+ self._explicit_targets = targets
52
+ self._explicit_pinned_fps = frozenset(pinned_fingerprints)
53
+ self._explicit_pinned_ids = frozenset(pinned_sample_ids)
54
+
55
+ def _ensure_dirs(self) -> None:
56
+ self.meta_dir.mkdir(parents=True, exist_ok=True)
57
+ self.artifacts_dir.mkdir(parents=True, exist_ok=True)
58
+ self.layouts_dir.mkdir(parents=True, exist_ok=True)
59
+
60
+ def active_targets(self) -> tuple[TargetRule, ...]:
61
+ if self._explicit_targets is not None:
62
+ return self._explicit_targets
63
+ return load_targets(self.targets_path)
64
+
65
+ def active_pins(self) -> tuple[frozenset[str], frozenset[str]]:
66
+ file_fps, file_ids = load_pinned_ids(self.pinned_path)
67
+ return (
68
+ self._explicit_pinned_fps | file_fps,
69
+ self._explicit_pinned_ids | file_ids,
70
+ )
71
+
72
+ def scan(self) -> tuple[SamplerState, tuple[str, ...]]:
73
+ """Load current state from disk, isolating any corrupt metadata files."""
74
+ records: list[SampleRecord] = []
75
+ corrupt_files: list[str] = []
76
+
77
+ if self.meta_dir.exists():
78
+ for meta_file in sorted(self.meta_dir.glob("*.json")):
79
+ try:
80
+ payload = json.loads(meta_file.read_text(encoding="utf-8"))
81
+ if not isinstance(payload, dict):
82
+ raise ValueError("metadata root must be a JSON object")
83
+ records.append(SampleRecord.from_dict(payload))
84
+ except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
85
+ logger.warning("Ignoring corrupt metadata file %s: %s", meta_file, exc)
86
+ corrupt_files.append(str(meta_file))
87
+
88
+ pinned_fps, pinned_ids = self.active_pins()
89
+ state = SamplerState(
90
+ records=tuple(records),
91
+ pinned_fingerprints=pinned_fps,
92
+ pinned_sample_ids=pinned_ids,
93
+ )
94
+ return state, tuple(corrupt_files)
95
+
96
+ def load_state(self) -> SamplerState:
97
+ state, _ = self.scan()
98
+ return state
99
+
100
+ def safe_record(
101
+ self,
102
+ event: SampleEvent,
103
+ artifact_bytes: bytes | None = None,
104
+ artifact_ext: str = ".bin",
105
+ layout: dict[str, Any] | None = None,
106
+ pinned: bool = False,
107
+ ) -> RecordOutcome:
108
+ """Evaluate and persist a sample without ever raising I/O exceptions to callers."""
109
+ try:
110
+ self._ensure_dirs()
111
+ state = self.load_state()
112
+ targets = self.active_targets()
113
+ decision = should_capture(event, state, config=self.config, targets=targets)
114
+
115
+ if not decision.capture:
116
+ return RecordOutcome(decision=decision, stored=False)
117
+
118
+ evicted = self._evict_records(decision.evict_ids, state)
119
+ self._write_sample(
120
+ event=event,
121
+ artifact_bytes=artifact_bytes,
122
+ artifact_ext=artifact_ext,
123
+ layout=layout,
124
+ pinned=pinned,
125
+ )
126
+ return RecordOutcome(decision=decision, stored=True, evicted_ids=evicted)
127
+ except OSError as exc:
128
+ msg = f"Storage I/O error while recording {event.sample_id}: {exc}"
129
+ logger.warning(msg)
130
+ fallback = CaptureDecision(capture=False, reason="storage_io_error")
131
+ return RecordOutcome(decision=fallback, stored=False, warning=msg)
132
+ except Exception as exc: # noqa: BLE001 — worker safety boundary
133
+ msg = f"Unexpected sampler error while recording {event.sample_id}: {exc}"
134
+ logger.warning(msg)
135
+ fallback = CaptureDecision(capture=False, reason="unexpected_error")
136
+ return RecordOutcome(decision=fallback, stored=False, warning=msg)
137
+
138
+ def prune(self) -> tuple[str, ...]:
139
+ """Enforce bucket and disk caps on disk without touching pinned samples."""
140
+ state = self.load_state()
141
+ targets = self.active_targets()
142
+ to_evict = plan_prune(state, config=self.config, targets=targets)
143
+ return self._evict_records(to_evict, state)
144
+
145
+ def stats(self) -> dict[str, Any]:
146
+ """Return structured bucket and disk usage summary."""
147
+ state, corrupt = self.scan()
148
+ buckets: dict[str, dict[str, Any]] = {}
149
+ pinned_count = 0
150
+ for rec in state.records:
151
+ key = rec.bucket.canonical()
152
+ entry = buckets.setdefault(
153
+ key,
154
+ {
155
+ "bucket": rec.bucket.to_dict(),
156
+ "total": 0,
157
+ "pinned": 0,
158
+ "unpinned": 0,
159
+ "bytes": 0,
160
+ },
161
+ )
162
+ is_pin = state.is_pinned(rec)
163
+ entry["total"] += 1
164
+ entry["bytes"] += rec.size_bytes
165
+ if is_pin:
166
+ entry["pinned"] += 1
167
+ pinned_count += 1
168
+ else:
169
+ entry["unpinned"] += 1
170
+
171
+ return {
172
+ "root_dir": str(self.root_dir),
173
+ "total_samples": len(state.records),
174
+ "pinned_samples": pinned_count,
175
+ "unpinned_samples": len(state.records) - pinned_count,
176
+ "total_bytes": state.total_bytes,
177
+ "max_total_bytes": self.config.max_total_bytes,
178
+ "corrupt_metadata_count": len(corrupt),
179
+ "buckets": buckets,
180
+ }
181
+
182
+ def verify(self) -> dict[str, Any]:
183
+ """Inspect store health: corrupt metadata and missing artifact files."""
184
+ state, corrupt = self.scan()
185
+ missing_artifacts: list[str] = []
186
+ missing_layouts: list[str] = []
187
+ for rec in state.records:
188
+ if rec.artifact_relpath and not (self.root_dir / rec.artifact_relpath).exists():
189
+ missing_artifacts.append(rec.sample_id)
190
+ if rec.layout_relpath and not (self.root_dir / rec.layout_relpath).exists():
191
+ missing_layouts.append(rec.sample_id)
192
+ return {
193
+ "ok": not corrupt and not missing_artifacts and not missing_layouts,
194
+ "valid_samples": len(state.records),
195
+ "corrupt_metadata_files": list(corrupt),
196
+ "missing_artifacts": missing_artifacts,
197
+ "missing_layouts": missing_layouts,
198
+ }
199
+
200
+ def _write_sample(
201
+ self,
202
+ event: SampleEvent,
203
+ artifact_bytes: bytes | None,
204
+ artifact_ext: str,
205
+ layout: dict[str, Any] | None,
206
+ pinned: bool,
207
+ ) -> None:
208
+ safe_id = _safe_filename(event.sample_id)
209
+ ext = artifact_ext if artifact_ext.startswith(".") else f".{artifact_ext}"
210
+
211
+ artifact_rel: str | None = None
212
+ if artifact_bytes is not None:
213
+ artifact_path = self.artifacts_dir / f"{safe_id}{ext}"
214
+ self._atomic_write_bytes(artifact_path, artifact_bytes)
215
+ artifact_rel = str(artifact_path.relative_to(self.root_dir)).replace("\\", "/")
216
+
217
+ layout_rel: str | None = None
218
+ if layout is not None:
219
+ layout_path = self.layouts_dir / f"{safe_id}.layout.json"
220
+ layout_bytes = json.dumps(layout, ensure_ascii=False, indent=2).encode("utf-8")
221
+ self._atomic_write_bytes(layout_path, layout_bytes)
222
+ layout_rel = str(layout_path.relative_to(self.root_dir)).replace("\\", "/")
223
+
224
+ record = SampleRecord(
225
+ sample_id=event.sample_id,
226
+ bucket=event.bucket,
227
+ fingerprint=event.fingerprint,
228
+ size_bytes=event.size_bytes,
229
+ timestamp=event.timestamp,
230
+ pinned=pinned,
231
+ artifact_relpath=artifact_rel,
232
+ layout_relpath=layout_rel,
233
+ metadata=event.metadata,
234
+ )
235
+ meta_path = self.meta_dir / f"{safe_id}.json"
236
+ meta_bytes = json.dumps(record.to_dict(), ensure_ascii=False, indent=2).encode("utf-8")
237
+ self._atomic_write_bytes(meta_path, meta_bytes)
238
+
239
+ def _evict_records(
240
+ self, sample_ids: tuple[str, ...], state: SamplerState
241
+ ) -> tuple[str, ...]:
242
+ if not sample_ids:
243
+ return ()
244
+ by_id = {r.sample_id: r for r in state.records}
245
+ evicted: list[str] = []
246
+ for sid in sample_ids:
247
+ rec = by_id.get(sid)
248
+ if rec is None:
249
+ continue
250
+ # Defense-in-depth: never delete a pinned record even if requested.
251
+ if state.is_pinned(rec):
252
+ logger.warning("Refusing to evict pinned sample %s", sid)
253
+ continue
254
+ safe_id = _safe_filename(sid)
255
+ self._unlink_quiet(self.meta_dir / f"{safe_id}.json")
256
+ if rec.artifact_relpath:
257
+ self._unlink_quiet(self.root_dir / rec.artifact_relpath)
258
+ if rec.layout_relpath:
259
+ self._unlink_quiet(self.root_dir / rec.layout_relpath)
260
+ evicted.append(sid)
261
+ return tuple(evicted)
262
+
263
+ @staticmethod
264
+ def _atomic_write_bytes(path: Path, data: bytes) -> None:
265
+ tmp_path = path.with_suffix(path.suffix + ".tmp")
266
+ tmp_path.write_bytes(data)
267
+ tmp_path.replace(path)
268
+
269
+ @staticmethod
270
+ def _unlink_quiet(path: Path) -> None:
271
+ try:
272
+ path.unlink(missing_ok=True)
273
+ except OSError as exc:
274
+ logger.warning("Failed to remove %s during eviction: %s", path, exc)
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.1
2
+ Name: targeted-sampler
3
+ Version: 0.1.0
4
+ Summary: Stratified, reason-bucketed sample collector with pinning, deduplication, and disk-budget rotation.
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+
8
+ # targeted-sampler
9
+
10
+ A lightweight, deterministic, zero-dependency Python library and CLI for **stratified, reason-bucketed sample collection** in document processing and automated review pipelines.
11
+
12
+ ## Why?
13
+
14
+ Simple FIFO / global-cap sample collectors stop recording once an early limit (e.g. 200 items) is reached, starving newly emerging error reasons or high-priority single-blocker cases of real artifacts needed for evaluation and regression testing.
15
+
16
+ `targeted-sampler` solves this with:
17
+
18
+ - **Per-bucket ring buffers** keyed by `(kind, single_blocker, primary_key, reason_code)`
19
+ - **Dynamic target overrides** (`capture_targets.json`) for priority quotas and forced capture
20
+ - **Pinning protection** so audited/labeled or regression-referenced samples are never evicted
21
+ - **SHA-256 fingerprint deduplication**
22
+ - **Global disk-budget rotation** that evicts oldest unpinned samples safely
23
+ - **Pure decision API** (`should_capture(event, state, config, targets) -> CaptureDecision`) for deterministic unit testing
24
+ - **Fail-safe storage wrapper** (`SampleStore.safe_record(...)`) that never crashes caller workers on I/O errors or disk limits
25
+
26
+ ## Quick Start
27
+
28
+ ```python
29
+ from targeted_sampler import (
30
+ BucketKey,
31
+ CaptureConfig,
32
+ SampleEvent,
33
+ SampleStore,
34
+ compute_fingerprint,
35
+ )
36
+
37
+ store = SampleStore(root_dir="./samples", config=CaptureConfig(bucket_limit=15, max_total_bytes=50 * 1024 * 1024))
38
+ payload = b"synthetic-image-bytes"
39
+
40
+ event = SampleEvent(
41
+ sample_id="doc-001",
42
+ bucket=BucketKey(
43
+ kind="receipt",
44
+ single_blocker=True,
45
+ primary_key="items",
46
+ reason_code="sum_mismatch",
47
+ ),
48
+ fingerprint=compute_fingerprint(payload),
49
+ size_bytes=len(payload),
50
+ )
51
+
52
+ outcome = store.safe_record(event, artifact_bytes=payload, layout={"lines": []})
53
+ print(outcome.decision.capture, outcome.decision.reason)
54
+ ```
55
+
56
+ ## CLI Usage
57
+
58
+ ```bash
59
+ # Inspect bucket distribution and disk usage
60
+ targeted-sampler stats --root ./samples --format table
61
+ targeted-sampler stats --root ./samples --format json
62
+
63
+ # Verify metadata integrity and report corrupt entries
64
+ targeted-sampler verify --root ./samples --format json
65
+
66
+ # Enforce disk/bucket caps without touching pinned samples
67
+ targeted-sampler prune --root ./samples --max-mb 100 --format json
68
+ ```
69
+
70
+ ## Running Tests
71
+
72
+ ```bash
73
+ python -m unittest discover -s tests -v
74
+ ```
75
+
76
+ ## Security & Privacy Boundaries
77
+
78
+ - **Zero network access**: operates strictly on local storage.
79
+ - **No domain-specific coupling**: business identifiers, pricing, and external labels are injected at runtime via local configuration outside version control.
80
+ - **Safe failure**: storage errors and corrupt metadata files are isolated and logged without halting caller pipelines.
@@ -0,0 +1,12 @@
1
+ targeted_sampler/__init__.py,sha256=chxh_Moc5d5yrOVmNswT4oAjPfNaqdqvJT2-4zI5Fws,701
2
+ targeted_sampler/cli.py,sha256=Zy7Lwfpl2TQNzoq0GCrqQYKBoPygpYV4jnyMrWcHCEg,3715
3
+ targeted_sampler/config.py,sha256=NodApvqLqVqen4AqlJqw86AOjtQyBVCgJVhc9BhYxiM,7187
4
+ targeted_sampler/decision.py,sha256=sQCDXxZx2nxxoHsKxWAoq-1jekWMtiVyIXHHYarm638,7464
5
+ targeted_sampler/models.py,sha256=rkpzU-WERFbUjDbYwK_cFuuKlR4YGnTpf5W5zbeG8KY,5391
6
+ targeted_sampler/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ targeted_sampler/store.py,sha256=alM93ybclpTqixVxZuZcPofozRHdxdu-l5bozUeA4Fs,10954
8
+ targeted_sampler-0.1.0.dist-info/METADATA,sha256=4MhQIZzd0FPmSFTH1E5gm5s5WSrL7m2w9ubeXlH4TBM,3042
9
+ targeted_sampler-0.1.0.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
10
+ targeted_sampler-0.1.0.dist-info/entry_points.txt,sha256=YHDXMIyCVIPvMepLEKV-B-uJp5Z0hikvexjJDfLwhhE,63
11
+ targeted_sampler-0.1.0.dist-info/top_level.txt,sha256=slmh_x_MU7FkAx3UBFLZ9JjdkTxIVX5XHAX1y1BNl5U,17
12
+ targeted_sampler-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ targeted-sampler = targeted_sampler.cli:main
@@ -0,0 +1 @@
1
+ targeted_sampler