security-anomaly-ml 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.
- security_anomaly/__init__.py +64 -0
- security_anomaly/__main__.py +6 -0
- security_anomaly/aggregation.py +99 -0
- security_anomaly/cli.py +255 -0
- security_anomaly/contracts.py +157 -0
- security_anomaly/detector.py +185 -0
- security_anomaly/model_bundle.py +230 -0
- security_anomaly/package_resources.py +39 -0
- security_anomaly/resources/__init__.py +1 -0
- security_anomaly/resources/feature-contract-cicflow-v2-128.json +423 -0
- security_anomaly/resources/incident-v1.schema.json +55 -0
- security_anomaly/resources/model-manifest-context-rf-v2.json +93 -0
- security_anomaly/results.py +57 -0
- security_anomaly/serialization.py +169 -0
- security_anomaly/temporal.py +290 -0
- security_anomaly/validation.py +202 -0
- security_anomaly_ml-0.1.0.dist-info/METADATA +280 -0
- security_anomaly_ml-0.1.0.dist-info/RECORD +22 -0
- security_anomaly_ml-0.1.0.dist-info/WHEEL +5 -0
- security_anomaly_ml-0.1.0.dist-info/entry_points.txt +2 -0
- security_anomaly_ml-0.1.0.dist-info/licenses/LICENSE +201 -0
- security_anomaly_ml-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Production-oriented inference primitives for Security Anomaly ML v0.1."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib import import_module
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
__version__ = "0.1.0"
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"ArtifactIntegrityError",
|
|
12
|
+
"CausalTemporalFeatureBuilder",
|
|
13
|
+
"ContractError",
|
|
14
|
+
"BatchAnalysisResult",
|
|
15
|
+
"FlowDetection",
|
|
16
|
+
"FrozenOperationalPolicy",
|
|
17
|
+
"FeatureBatch",
|
|
18
|
+
"FeatureContract",
|
|
19
|
+
"FrozenModelBundle",
|
|
20
|
+
"IncidentDetection",
|
|
21
|
+
"InputContractError",
|
|
22
|
+
"ModelCompatibilityError",
|
|
23
|
+
"SecurityAnomalyDetector",
|
|
24
|
+
"ValidatedFlowBatch",
|
|
25
|
+
"validate_flow_records",
|
|
26
|
+
"read_and_validate_flow_csv",
|
|
27
|
+
"incident_to_v1",
|
|
28
|
+
"promoted_incidents_to_v1",
|
|
29
|
+
"write_incidents_jsonl",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
_EXPORTS = {
|
|
33
|
+
"ContractError": (".contracts", "ContractError"),
|
|
34
|
+
"FeatureContract": (".contracts", "FeatureContract"),
|
|
35
|
+
"ArtifactIntegrityError": (".model_bundle", "ArtifactIntegrityError"),
|
|
36
|
+
"FrozenModelBundle": (".model_bundle", "FrozenModelBundle"),
|
|
37
|
+
"ModelCompatibilityError": (".model_bundle", "ModelCompatibilityError"),
|
|
38
|
+
"CausalTemporalFeatureBuilder": (".temporal", "CausalTemporalFeatureBuilder"),
|
|
39
|
+
"FeatureBatch": (".temporal", "FeatureBatch"),
|
|
40
|
+
"InputContractError": (".temporal", "InputContractError"),
|
|
41
|
+
"FlowDetection": (".results", "FlowDetection"),
|
|
42
|
+
"IncidentDetection": (".results", "IncidentDetection"),
|
|
43
|
+
"BatchAnalysisResult": (".results", "BatchAnalysisResult"),
|
|
44
|
+
"FrozenOperationalPolicy": (".detector", "FrozenOperationalPolicy"),
|
|
45
|
+
"SecurityAnomalyDetector": (".detector", "SecurityAnomalyDetector"),
|
|
46
|
+
"ValidatedFlowBatch": (".validation", "ValidatedFlowBatch"),
|
|
47
|
+
"validate_flow_records": (".validation", "validate_flow_records"),
|
|
48
|
+
"read_and_validate_flow_csv": (".validation", "read_and_validate_flow_csv"),
|
|
49
|
+
"incident_to_v1": (".serialization", "incident_to_v1"),
|
|
50
|
+
"promoted_incidents_to_v1": (".serialization", "promoted_incidents_to_v1"),
|
|
51
|
+
"write_incidents_jsonl": (".serialization", "write_incidents_jsonl"),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def __getattr__(name: str) -> Any:
|
|
56
|
+
"""Load public primitives lazily so ``python -m`` entry points stay clean."""
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
module_name, attribute = _EXPORTS[name]
|
|
60
|
+
except KeyError as error:
|
|
61
|
+
raise AttributeError(name) from error
|
|
62
|
+
value = getattr(import_module(module_name, __name__), attribute)
|
|
63
|
+
globals()[name] = value
|
|
64
|
+
return value
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Frozen Policy B incident aggregation for product inference."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import defaultdict
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from datetime import timedelta
|
|
8
|
+
from statistics import fmean
|
|
9
|
+
from typing import Iterable
|
|
10
|
+
|
|
11
|
+
from .results import FlowDetection, IncidentDetection
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
POLICY_B_GROUPING_KEY = ("src_ip", "dst_ip", "dst_port")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _incident_from_members(
|
|
18
|
+
members: list[FlowDetection],
|
|
19
|
+
*,
|
|
20
|
+
promotion_threshold: float,
|
|
21
|
+
) -> IncidentDetection:
|
|
22
|
+
if not members:
|
|
23
|
+
raise ValueError("Cannot create an incident without alert flows")
|
|
24
|
+
first = members[0]
|
|
25
|
+
scores = [flow.attack_score for flow in members]
|
|
26
|
+
maximum = max(scores)
|
|
27
|
+
return IncidentDetection(
|
|
28
|
+
incident_sequence=-1,
|
|
29
|
+
first_seen=first.timestamp,
|
|
30
|
+
last_seen=members[-1].timestamp,
|
|
31
|
+
src_ip=first.src_ip,
|
|
32
|
+
dst_ip=first.dst_ip,
|
|
33
|
+
dst_port=first.dst_port,
|
|
34
|
+
protocols=tuple(sorted({flow.protocol for flow in members})),
|
|
35
|
+
flow_count=len(members),
|
|
36
|
+
max_attack_score=maximum,
|
|
37
|
+
mean_attack_score=fmean(scores),
|
|
38
|
+
promoted=maximum >= promotion_threshold,
|
|
39
|
+
source_row_ids=tuple(flow.source_row_id for flow in members),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def aggregate_policy_b_alerts(
|
|
44
|
+
flows: Iterable[FlowDetection],
|
|
45
|
+
*,
|
|
46
|
+
window_seconds: int,
|
|
47
|
+
promotion_threshold: float,
|
|
48
|
+
) -> tuple[IncidentDetection, ...]:
|
|
49
|
+
"""Aggregate only alerts using consecutive-alert inactivity gaps.
|
|
50
|
+
|
|
51
|
+
Protocol is deliberately evidence only and never participates in the key.
|
|
52
|
+
A gap equal to ``window_seconds`` remains in the existing incident; only a
|
|
53
|
+
strictly greater gap starts a new one.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
if window_seconds <= 0:
|
|
57
|
+
raise ValueError("Incident window must be positive")
|
|
58
|
+
if promotion_threshold < 0 or promotion_threshold > 1:
|
|
59
|
+
raise ValueError("Promotion threshold must be in [0, 1]")
|
|
60
|
+
|
|
61
|
+
alerts_by_key: dict[tuple[str, str, int], list[FlowDetection]] = defaultdict(list)
|
|
62
|
+
for flow in flows:
|
|
63
|
+
if flow.is_alert:
|
|
64
|
+
alerts_by_key[(flow.src_ip, flow.dst_ip, flow.dst_port)].append(flow)
|
|
65
|
+
|
|
66
|
+
drafts: list[IncidentDetection] = []
|
|
67
|
+
maximum_gap = timedelta(seconds=window_seconds)
|
|
68
|
+
for members in alerts_by_key.values():
|
|
69
|
+
ordered = sorted(members, key=lambda flow: (flow.timestamp, flow.source_row_id))
|
|
70
|
+
session: list[FlowDetection] = []
|
|
71
|
+
previous: FlowDetection | None = None
|
|
72
|
+
for flow in ordered:
|
|
73
|
+
if previous is not None and flow.timestamp - previous.timestamp > maximum_gap:
|
|
74
|
+
drafts.append(
|
|
75
|
+
_incident_from_members(
|
|
76
|
+
session, promotion_threshold=promotion_threshold
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
session = []
|
|
80
|
+
session.append(flow)
|
|
81
|
+
previous = flow
|
|
82
|
+
if session:
|
|
83
|
+
drafts.append(
|
|
84
|
+
_incident_from_members(session, promotion_threshold=promotion_threshold)
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
drafts.sort(
|
|
88
|
+
key=lambda incident: (
|
|
89
|
+
incident.first_seen,
|
|
90
|
+
incident.src_ip,
|
|
91
|
+
incident.dst_ip,
|
|
92
|
+
incident.dst_port,
|
|
93
|
+
incident.source_row_ids[0],
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
return tuple(
|
|
97
|
+
replace(incident, incident_sequence=sequence)
|
|
98
|
+
for sequence, incident in enumerate(drafts)
|
|
99
|
+
)
|
security_anomaly/cli.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Command-line interface for label-free Security Anomaly ML v0.1 analysis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import traceback
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Sequence
|
|
13
|
+
|
|
14
|
+
from .contracts import ContractError
|
|
15
|
+
from .detector import SecurityAnomalyDetector
|
|
16
|
+
from .model_bundle import ArtifactIntegrityError, ModelCompatibilityError
|
|
17
|
+
from .package_resources import (
|
|
18
|
+
FEATURE_CONTRACT_RESOURCE,
|
|
19
|
+
MODEL_MANIFEST_RESOURCE,
|
|
20
|
+
materialized_resource,
|
|
21
|
+
resource_json,
|
|
22
|
+
)
|
|
23
|
+
from .serialization import (
|
|
24
|
+
INCIDENT_SCHEMA_VERSION,
|
|
25
|
+
IncidentSerializationError,
|
|
26
|
+
OutputWriteError,
|
|
27
|
+
promoted_incidents_to_v1,
|
|
28
|
+
write_incidents_jsonl,
|
|
29
|
+
)
|
|
30
|
+
from .validation import InputContractError, read_and_validate_flow_csv
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
EXIT_SUCCESS = 0
|
|
34
|
+
EXIT_USAGE = 2
|
|
35
|
+
EXIT_INPUT = 3
|
|
36
|
+
EXIT_MODEL = 4
|
|
37
|
+
EXIT_OUTPUT = 5
|
|
38
|
+
EXIT_RUNTIME = 10
|
|
39
|
+
MODEL_ENVIRONMENT_VARIABLE = "SECURITY_ANOMALY_MODEL"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ModelResolutionError(RuntimeError):
|
|
43
|
+
"""Raised when a local frozen model cannot be located or verified."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _json_stdout(value: object) -> None:
|
|
47
|
+
print(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def resolve_model_path(explicit: Path | None) -> Path:
|
|
51
|
+
"""Resolve the model using CLI > environment > conventional local paths."""
|
|
52
|
+
|
|
53
|
+
if explicit is not None:
|
|
54
|
+
candidate = explicit.expanduser().resolve()
|
|
55
|
+
if not candidate.is_file():
|
|
56
|
+
raise ModelResolutionError(f"Model artifact not found: {candidate}")
|
|
57
|
+
return candidate
|
|
58
|
+
environment_value = os.environ.get(MODEL_ENVIRONMENT_VARIABLE)
|
|
59
|
+
if environment_value:
|
|
60
|
+
candidate = Path(environment_value).expanduser().resolve()
|
|
61
|
+
if not candidate.is_file():
|
|
62
|
+
raise ModelResolutionError(
|
|
63
|
+
f"{MODEL_ENVIRONMENT_VARIABLE} does not point to a file: {candidate}"
|
|
64
|
+
)
|
|
65
|
+
return candidate
|
|
66
|
+
candidates = (
|
|
67
|
+
Path.cwd() / "models" / "context-rf-v2.joblib",
|
|
68
|
+
Path.cwd() / "models" / "v2_context_random_forest.joblib",
|
|
69
|
+
Path.cwd() / "context-rf-v2.joblib",
|
|
70
|
+
)
|
|
71
|
+
for candidate in candidates:
|
|
72
|
+
if candidate.is_file():
|
|
73
|
+
return candidate.resolve()
|
|
74
|
+
raise ModelResolutionError(
|
|
75
|
+
"Frozen model asset is missing. Supply --model PATH or set "
|
|
76
|
+
f"{MODEL_ENVIRONMENT_VARIABLE}; no download is performed."
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _load_detector(model_path: Path) -> SecurityAnomalyDetector:
|
|
81
|
+
try:
|
|
82
|
+
with materialized_resource(MODEL_MANIFEST_RESOURCE) as manifest_path:
|
|
83
|
+
with materialized_resource(FEATURE_CONTRACT_RESOURCE) as contract_path:
|
|
84
|
+
return SecurityAnomalyDetector.load(
|
|
85
|
+
model_path=model_path,
|
|
86
|
+
manifest_path=manifest_path,
|
|
87
|
+
feature_contract_path=contract_path,
|
|
88
|
+
)
|
|
89
|
+
except (
|
|
90
|
+
ArtifactIntegrityError,
|
|
91
|
+
ContractError,
|
|
92
|
+
FileNotFoundError,
|
|
93
|
+
ModelCompatibilityError,
|
|
94
|
+
OSError,
|
|
95
|
+
) as error:
|
|
96
|
+
raise ModelResolutionError(str(error)) from error
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _version_payload() -> dict[str, object]:
|
|
100
|
+
manifest = resource_json(MODEL_MANIFEST_RESOURCE)
|
|
101
|
+
contract = resource_json(FEATURE_CONTRACT_RESOURCE)
|
|
102
|
+
return {
|
|
103
|
+
"product_version": manifest["product_version"],
|
|
104
|
+
"feature_contract": contract["feature_contract"],
|
|
105
|
+
"feature_builder_version": contract["feature_builder_version"],
|
|
106
|
+
"incident_contract": INCIDENT_SCHEMA_VERSION,
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _command_version(_args: argparse.Namespace) -> int:
|
|
111
|
+
_json_stdout(_version_payload())
|
|
112
|
+
return EXIT_SUCCESS
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _command_validate(args: argparse.Namespace) -> int:
|
|
116
|
+
batch = read_and_validate_flow_csv(args.input)
|
|
117
|
+
payload: dict[str, object] = {
|
|
118
|
+
"valid": True,
|
|
119
|
+
"rows": batch.row_count,
|
|
120
|
+
"input_contract": "CICFlowMeter-compatible-v0.1",
|
|
121
|
+
"feature_contract": batch.contract_version,
|
|
122
|
+
}
|
|
123
|
+
if batch.timestamp_min is not None:
|
|
124
|
+
payload["timestamp_min"] = batch.timestamp_min.to_pydatetime().isoformat(
|
|
125
|
+
timespec="seconds"
|
|
126
|
+
)
|
|
127
|
+
payload["timestamp_max"] = batch.timestamp_max.to_pydatetime().isoformat(
|
|
128
|
+
timespec="seconds"
|
|
129
|
+
)
|
|
130
|
+
_json_stdout(payload)
|
|
131
|
+
return EXIT_SUCCESS
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _command_analyze(args: argparse.Namespace) -> int:
|
|
135
|
+
started = time.perf_counter()
|
|
136
|
+
batch = read_and_validate_flow_csv(args.input)
|
|
137
|
+
model_path = resolve_model_path(args.model)
|
|
138
|
+
output = args.output.expanduser().resolve()
|
|
139
|
+
if Path(args.input).expanduser().resolve() == output:
|
|
140
|
+
raise OutputWriteError("Output path must differ from input CSV path")
|
|
141
|
+
detector = _load_detector(model_path)
|
|
142
|
+
result = detector.analyze_batch(batch.frame)
|
|
143
|
+
public_incidents = promoted_incidents_to_v1(result)
|
|
144
|
+
write_incidents_jsonl(output, public_incidents)
|
|
145
|
+
summary = {
|
|
146
|
+
"validation_status": "valid",
|
|
147
|
+
"rejected_rows": 0,
|
|
148
|
+
"flows_processed": result.flows_processed,
|
|
149
|
+
"flow_alerts": result.flow_alert_count,
|
|
150
|
+
"aggregated_incidents": result.incident_count,
|
|
151
|
+
"promoted_incidents": result.promoted_incident_count,
|
|
152
|
+
"elapsed_seconds": round(time.perf_counter() - started, 6),
|
|
153
|
+
"product_version": result.product_version,
|
|
154
|
+
"model_version": result.model_version,
|
|
155
|
+
"feature_contract": result.feature_contract,
|
|
156
|
+
"incident_contract": INCIDENT_SCHEMA_VERSION,
|
|
157
|
+
"output": str(output),
|
|
158
|
+
}
|
|
159
|
+
print(json.dumps(summary, allow_nan=False, separators=(",", ":")), file=sys.stderr)
|
|
160
|
+
return EXIT_SUCCESS
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _command_model_info(args: argparse.Namespace) -> int:
|
|
164
|
+
model_path = resolve_model_path(args.model)
|
|
165
|
+
detector = _load_detector(model_path)
|
|
166
|
+
metadata = detector.bundle.metadata()
|
|
167
|
+
policy = detector.policy
|
|
168
|
+
_json_stdout(
|
|
169
|
+
{
|
|
170
|
+
"product_version": metadata["product_version"],
|
|
171
|
+
"model_version": metadata["model_version"],
|
|
172
|
+
"model_sha256": metadata["model_sha256"],
|
|
173
|
+
"model_path": str(model_path),
|
|
174
|
+
"feature_contract": metadata["feature_contract"],
|
|
175
|
+
"feature_builder_version": metadata["feature_builder_version"],
|
|
176
|
+
"flow_threshold": policy.flow_threshold,
|
|
177
|
+
"aggregation_policy": policy.incident_policy,
|
|
178
|
+
"grouping_key": list(policy.grouping_key),
|
|
179
|
+
"incident_window_seconds": policy.incident_window_seconds,
|
|
180
|
+
"promotion_threshold": policy.promotion_threshold,
|
|
181
|
+
"serialization": metadata["serialization"],
|
|
182
|
+
}
|
|
183
|
+
)
|
|
184
|
+
return EXIT_SUCCESS
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
188
|
+
parser = argparse.ArgumentParser(
|
|
189
|
+
prog="security-anomaly",
|
|
190
|
+
description=(
|
|
191
|
+
"Validate and analyze unlabeled CICFlowMeter-compatible flow CSV files "
|
|
192
|
+
"with the frozen context-rf-v2 detector."
|
|
193
|
+
),
|
|
194
|
+
epilog=(
|
|
195
|
+
"Example: security-anomaly analyze flows.csv --model context-rf-v2.joblib "
|
|
196
|
+
"--output incidents.jsonl"
|
|
197
|
+
),
|
|
198
|
+
)
|
|
199
|
+
parser.add_argument(
|
|
200
|
+
"--debug",
|
|
201
|
+
action="store_true",
|
|
202
|
+
help="show a traceback for unexpected failures",
|
|
203
|
+
)
|
|
204
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
205
|
+
|
|
206
|
+
analyze = subparsers.add_parser(
|
|
207
|
+
"analyze", help="validate, score, aggregate, and write promoted incidents"
|
|
208
|
+
)
|
|
209
|
+
analyze.add_argument("input", type=Path, help="unlabeled CICFlowMeter CSV")
|
|
210
|
+
analyze.add_argument("--model", type=Path, help="frozen context-rf-v2 joblib path")
|
|
211
|
+
analyze.add_argument("--output", required=True, type=Path, help="output JSONL path")
|
|
212
|
+
analyze.set_defaults(handler=_command_analyze)
|
|
213
|
+
|
|
214
|
+
validate = subparsers.add_parser(
|
|
215
|
+
"validate", help="validate input without loading a model"
|
|
216
|
+
)
|
|
217
|
+
validate.add_argument("input", type=Path, help="CICFlowMeter CSV to validate")
|
|
218
|
+
validate.set_defaults(handler=_command_validate)
|
|
219
|
+
|
|
220
|
+
version = subparsers.add_parser(
|
|
221
|
+
"version", help="show product and contract versions without loading a model"
|
|
222
|
+
)
|
|
223
|
+
version.set_defaults(handler=_command_version)
|
|
224
|
+
|
|
225
|
+
model_info = subparsers.add_parser(
|
|
226
|
+
"model-info", help="verify the selected frozen model and show its metadata"
|
|
227
|
+
)
|
|
228
|
+
model_info.add_argument("--model", type=Path, help="frozen context-rf-v2 joblib path")
|
|
229
|
+
model_info.set_defaults(handler=_command_model_info)
|
|
230
|
+
return parser
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
234
|
+
parser = build_parser()
|
|
235
|
+
args = parser.parse_args(argv)
|
|
236
|
+
try:
|
|
237
|
+
return int(args.handler(args))
|
|
238
|
+
except InputContractError as error:
|
|
239
|
+
print(f"input validation failed: {error}", file=sys.stderr)
|
|
240
|
+
return EXIT_INPUT
|
|
241
|
+
except ModelResolutionError as error:
|
|
242
|
+
print(f"model error: {error}", file=sys.stderr)
|
|
243
|
+
return EXIT_MODEL
|
|
244
|
+
except (IncidentSerializationError, OutputWriteError) as error:
|
|
245
|
+
print(f"output error: {error}", file=sys.stderr)
|
|
246
|
+
return EXIT_OUTPUT
|
|
247
|
+
except Exception as error: # pragma: no cover - final CLI safety boundary
|
|
248
|
+
print(f"unexpected runtime failure: {error}", file=sys.stderr)
|
|
249
|
+
if args.debug:
|
|
250
|
+
traceback.print_exc()
|
|
251
|
+
return EXIT_RUNTIME
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
if __name__ == "__main__": # pragma: no cover
|
|
255
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Load and validate versioned feature contracts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from .package_resources import FEATURE_CONTRACT_RESOURCE, resource_bytes, resource_ref
|
|
12
|
+
|
|
13
|
+
# Backward-compatible name, now resolving inside the installed package rather
|
|
14
|
+
# than relying on PROJECT_ROOT/contracts being present.
|
|
15
|
+
DEFAULT_FEATURE_CONTRACT_PATH = Path(str(resource_ref(FEATURE_CONTRACT_RESOURCE)))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ContractError(ValueError):
|
|
19
|
+
"""Raised when a versioned feature contract is malformed or incompatible."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sha256_file(path: str | Path) -> str:
|
|
23
|
+
digest = hashlib.sha256()
|
|
24
|
+
with Path(path).open("rb") as handle:
|
|
25
|
+
for block in iter(lambda: handle.read(1024 * 1024), b""):
|
|
26
|
+
digest.update(block)
|
|
27
|
+
return digest.hexdigest()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_json(path: str | Path) -> dict[str, Any]:
|
|
31
|
+
with Path(path).open("r", encoding="utf-8") as handle:
|
|
32
|
+
value = json.load(handle)
|
|
33
|
+
if not isinstance(value, dict):
|
|
34
|
+
raise ContractError(f"Expected a JSON object in {path}")
|
|
35
|
+
return value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class FeatureContract:
|
|
40
|
+
"""Validated ordered feature contract used by the frozen Context model."""
|
|
41
|
+
|
|
42
|
+
path: Path | None
|
|
43
|
+
sha256: str
|
|
44
|
+
document: dict[str, Any]
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def load(
|
|
48
|
+
cls,
|
|
49
|
+
path: str | Path | None = None,
|
|
50
|
+
*,
|
|
51
|
+
expected_version: str | None = None,
|
|
52
|
+
expected_sha256: str | None = None,
|
|
53
|
+
) -> "FeatureContract":
|
|
54
|
+
if path is None:
|
|
55
|
+
raw = resource_bytes(FEATURE_CONTRACT_RESOURCE)
|
|
56
|
+
actual_sha256 = hashlib.sha256(raw).hexdigest()
|
|
57
|
+
if expected_sha256 and actual_sha256 != expected_sha256:
|
|
58
|
+
raise ContractError(
|
|
59
|
+
"Feature contract SHA256 mismatch: "
|
|
60
|
+
f"expected {expected_sha256}, got {actual_sha256}"
|
|
61
|
+
)
|
|
62
|
+
document = json.loads(raw.decode("utf-8"))
|
|
63
|
+
if not isinstance(document, dict):
|
|
64
|
+
raise ContractError("Packaged feature contract must be a JSON object")
|
|
65
|
+
contract = cls(None, actual_sha256, document)
|
|
66
|
+
contract._validate(expected_version=expected_version)
|
|
67
|
+
return contract
|
|
68
|
+
resolved = Path(path).resolve()
|
|
69
|
+
if not resolved.is_file():
|
|
70
|
+
raise FileNotFoundError(f"Feature contract not found: {resolved}")
|
|
71
|
+
actual_sha256 = sha256_file(resolved)
|
|
72
|
+
if expected_sha256 and actual_sha256 != expected_sha256:
|
|
73
|
+
raise ContractError(
|
|
74
|
+
"Feature contract SHA256 mismatch: "
|
|
75
|
+
f"expected {expected_sha256}, got {actual_sha256}"
|
|
76
|
+
)
|
|
77
|
+
contract = cls(resolved, actual_sha256, load_json(resolved))
|
|
78
|
+
contract._validate(expected_version=expected_version)
|
|
79
|
+
return contract
|
|
80
|
+
|
|
81
|
+
def _validate(self, *, expected_version: str | None) -> None:
|
|
82
|
+
document = self.document
|
|
83
|
+
version = document.get("feature_contract")
|
|
84
|
+
if not isinstance(version, str) or not version:
|
|
85
|
+
raise ContractError("feature_contract must be a non-empty string")
|
|
86
|
+
if expected_version is not None and version != expected_version:
|
|
87
|
+
raise ContractError(
|
|
88
|
+
f"Feature contract version mismatch: expected {expected_version}, got {version}"
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
groups = document.get("feature_groups")
|
|
92
|
+
if not isinstance(groups, dict):
|
|
93
|
+
raise ContractError("feature_groups must be a JSON object")
|
|
94
|
+
expected_group_counts = {"baseline": 76, "static_behavioral": 9, "temporal": 43}
|
|
95
|
+
concatenated: list[str] = []
|
|
96
|
+
for name, expected_count in expected_group_counts.items():
|
|
97
|
+
group = groups.get(name)
|
|
98
|
+
if not isinstance(group, dict) or not isinstance(group.get("features"), list):
|
|
99
|
+
raise ContractError(f"feature_groups.{name}.features must be a list")
|
|
100
|
+
features = group["features"]
|
|
101
|
+
if group.get("count") != expected_count or len(features) != expected_count:
|
|
102
|
+
raise ContractError(
|
|
103
|
+
f"feature_groups.{name} must contain exactly {expected_count} features"
|
|
104
|
+
)
|
|
105
|
+
if not all(isinstance(value, str) and value for value in features):
|
|
106
|
+
raise ContractError(f"feature_groups.{name} contains an invalid name")
|
|
107
|
+
concatenated.extend(features)
|
|
108
|
+
|
|
109
|
+
ordered = document.get("model_features")
|
|
110
|
+
if ordered != concatenated:
|
|
111
|
+
raise ContractError("model_features does not match the ordered feature groups")
|
|
112
|
+
if document.get("model_feature_count") != 128 or len(ordered) != 128:
|
|
113
|
+
raise ContractError("The frozen model contract must contain exactly 128 features")
|
|
114
|
+
if len(set(ordered)) != len(ordered):
|
|
115
|
+
raise ContractError("The frozen model feature list contains duplicates")
|
|
116
|
+
|
|
117
|
+
input_contract = document.get("input")
|
|
118
|
+
if not isinstance(input_contract, dict):
|
|
119
|
+
raise ContractError("input must be a JSON object")
|
|
120
|
+
required_context = input_contract.get("required_identity_context_columns")
|
|
121
|
+
required_model = input_contract.get("required_model_columns")
|
|
122
|
+
if not isinstance(required_context, list) or not isinstance(required_model, list):
|
|
123
|
+
raise ContractError("Input required-column lists are missing")
|
|
124
|
+
if required_model != self.baseline_features:
|
|
125
|
+
raise ContractError("Required model columns differ from baseline features")
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def version(self) -> str:
|
|
129
|
+
return str(self.document["feature_contract"])
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def builder_version(self) -> str:
|
|
133
|
+
return str(self.document["feature_builder_version"])
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def model_features(self) -> list[str]:
|
|
137
|
+
return list(self.document["model_features"])
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def baseline_features(self) -> list[str]:
|
|
141
|
+
return list(self.document["feature_groups"]["baseline"]["features"])
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def static_features(self) -> list[str]:
|
|
145
|
+
return list(self.document["feature_groups"]["static_behavioral"]["features"])
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def temporal_features(self) -> list[str]:
|
|
149
|
+
return list(self.document["feature_groups"]["temporal"]["features"])
|
|
150
|
+
|
|
151
|
+
@property
|
|
152
|
+
def required_input_columns(self) -> list[str]:
|
|
153
|
+
input_contract = self.document["input"]
|
|
154
|
+
return [
|
|
155
|
+
*input_contract["required_identity_context_columns"],
|
|
156
|
+
*input_contract["required_model_columns"],
|
|
157
|
+
]
|