targeted-sampler 0.1.0__tar.gz
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.
- targeted_sampler-0.1.0/PKG-INFO +80 -0
- targeted_sampler-0.1.0/README.md +73 -0
- targeted_sampler-0.1.0/pyproject.toml +20 -0
- targeted_sampler-0.1.0/setup.cfg +4 -0
- targeted_sampler-0.1.0/src/targeted_sampler/__init__.py +32 -0
- targeted_sampler-0.1.0/src/targeted_sampler/cli.py +104 -0
- targeted_sampler-0.1.0/src/targeted_sampler/config.py +191 -0
- targeted_sampler-0.1.0/src/targeted_sampler/decision.py +210 -0
- targeted_sampler-0.1.0/src/targeted_sampler/models.py +173 -0
- targeted_sampler-0.1.0/src/targeted_sampler/py.typed +0 -0
- targeted_sampler-0.1.0/src/targeted_sampler/store.py +274 -0
- targeted_sampler-0.1.0/src/targeted_sampler.egg-info/PKG-INFO +80 -0
- targeted_sampler-0.1.0/src/targeted_sampler.egg-info/SOURCES.txt +17 -0
- targeted_sampler-0.1.0/src/targeted_sampler.egg-info/dependency_links.txt +1 -0
- targeted_sampler-0.1.0/src/targeted_sampler.egg-info/entry_points.txt +2 -0
- targeted_sampler-0.1.0/src/targeted_sampler.egg-info/top_level.txt +1 -0
- targeted_sampler-0.1.0/tests/test_decision.py +227 -0
- targeted_sampler-0.1.0/tests/test_sanitization.py +45 -0
- targeted_sampler-0.1.0/tests/test_store_and_cli.py +154 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
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,73 @@
|
|
|
1
|
+
# targeted-sampler
|
|
2
|
+
|
|
3
|
+
A lightweight, deterministic, zero-dependency Python library and CLI for **stratified, reason-bucketed sample collection** in document processing and automated review pipelines.
|
|
4
|
+
|
|
5
|
+
## Why?
|
|
6
|
+
|
|
7
|
+
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.
|
|
8
|
+
|
|
9
|
+
`targeted-sampler` solves this with:
|
|
10
|
+
|
|
11
|
+
- **Per-bucket ring buffers** keyed by `(kind, single_blocker, primary_key, reason_code)`
|
|
12
|
+
- **Dynamic target overrides** (`capture_targets.json`) for priority quotas and forced capture
|
|
13
|
+
- **Pinning protection** so audited/labeled or regression-referenced samples are never evicted
|
|
14
|
+
- **SHA-256 fingerprint deduplication**
|
|
15
|
+
- **Global disk-budget rotation** that evicts oldest unpinned samples safely
|
|
16
|
+
- **Pure decision API** (`should_capture(event, state, config, targets) -> CaptureDecision`) for deterministic unit testing
|
|
17
|
+
- **Fail-safe storage wrapper** (`SampleStore.safe_record(...)`) that never crashes caller workers on I/O errors or disk limits
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from targeted_sampler import (
|
|
23
|
+
BucketKey,
|
|
24
|
+
CaptureConfig,
|
|
25
|
+
SampleEvent,
|
|
26
|
+
SampleStore,
|
|
27
|
+
compute_fingerprint,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
store = SampleStore(root_dir="./samples", config=CaptureConfig(bucket_limit=15, max_total_bytes=50 * 1024 * 1024))
|
|
31
|
+
payload = b"synthetic-image-bytes"
|
|
32
|
+
|
|
33
|
+
event = SampleEvent(
|
|
34
|
+
sample_id="doc-001",
|
|
35
|
+
bucket=BucketKey(
|
|
36
|
+
kind="receipt",
|
|
37
|
+
single_blocker=True,
|
|
38
|
+
primary_key="items",
|
|
39
|
+
reason_code="sum_mismatch",
|
|
40
|
+
),
|
|
41
|
+
fingerprint=compute_fingerprint(payload),
|
|
42
|
+
size_bytes=len(payload),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
outcome = store.safe_record(event, artifact_bytes=payload, layout={"lines": []})
|
|
46
|
+
print(outcome.decision.capture, outcome.decision.reason)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## CLI Usage
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
# Inspect bucket distribution and disk usage
|
|
53
|
+
targeted-sampler stats --root ./samples --format table
|
|
54
|
+
targeted-sampler stats --root ./samples --format json
|
|
55
|
+
|
|
56
|
+
# Verify metadata integrity and report corrupt entries
|
|
57
|
+
targeted-sampler verify --root ./samples --format json
|
|
58
|
+
|
|
59
|
+
# Enforce disk/bucket caps without touching pinned samples
|
|
60
|
+
targeted-sampler prune --root ./samples --max-mb 100 --format json
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Running Tests
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
python -m unittest discover -s tests -v
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Security & Privacy Boundaries
|
|
70
|
+
|
|
71
|
+
- **Zero network access**: operates strictly on local storage.
|
|
72
|
+
- **No domain-specific coupling**: business identifiers, pricing, and external labels are injected at runtime via local configuration outside version control.
|
|
73
|
+
- **Safe failure**: storage errors and corrupt metadata files are isolated and logged without halting caller pipelines.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "targeted-sampler"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Stratified, reason-bucketed sample collector with pinning, deduplication, and disk-budget rotation."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = []
|
|
12
|
+
|
|
13
|
+
[project.scripts]
|
|
14
|
+
targeted-sampler = "targeted_sampler.cli:main"
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
where = ["src"]
|
|
18
|
+
|
|
19
|
+
[tool.setuptools.package-data]
|
|
20
|
+
targeted_sampler = ["py.typed"]
|
|
@@ -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)
|