asofaudit 0.4.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.
asofaudit/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Audit explicit feature selections; no payload evaluation or network access."""
2
+
3
+ from .core import AuditError, audit
4
+
5
+ __all__ = ["AuditError", "audit"]
asofaudit/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import cli
2
+
3
+ raise SystemExit(cli())
asofaudit/cli.py ADDED
@@ -0,0 +1,112 @@
1
+ """Command-line audit. Invalid input never emits a plausible partial report."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+
7
+ from .core import AuditError, audit
8
+
9
+ _POLICY_BYTES = 1048576
10
+
11
+
12
+ def _duplicate_checked_object(pairs):
13
+ result = {}
14
+ for key, value in pairs:
15
+ if key in result:
16
+ raise AuditError("duplicate feature age policy key")
17
+ result[key] = value
18
+ return result
19
+
20
+
21
+ def _reject_constant(value):
22
+ raise AuditError("non-finite numbers are invalid JSON policy values")
23
+
24
+
25
+ def _load_age_limits(path):
26
+ try:
27
+ with open(path, "rb") as stream:
28
+ raw = stream.read(_POLICY_BYTES + 1)
29
+ if len(raw) > _POLICY_BYTES:
30
+ raise AuditError("feature age policy exceeds 1 MiB byte limit")
31
+ return json.loads(
32
+ raw.decode("utf-8-sig"),
33
+ object_pairs_hook=_duplicate_checked_object,
34
+ parse_constant=_reject_constant,
35
+ )
36
+ except (OSError, ValueError, RecursionError) as exc:
37
+ raise AuditError("invalid feature age policy: %s" % exc) from exc
38
+
39
+
40
+ def main(argv=None):
41
+ parser = argparse.ArgumentParser(
42
+ description="Audit selected feature versions against event and known time"
43
+ )
44
+ parser.add_argument("history")
45
+ parser.add_argument("requests")
46
+ parser.add_argument("selections")
47
+ parser.add_argument("--feature", action="append", required=True, dest="features")
48
+ ages = parser.add_mutually_exclusive_group()
49
+ ages.add_argument("--max-age-us", type=int)
50
+ ages.add_argument("--feature-age-limits", metavar="JSON_FILE")
51
+ parser.add_argument(
52
+ "--strict-event-before",
53
+ action="store_true",
54
+ help="exclude event_at equal to prediction_at; known time remains inclusive",
55
+ )
56
+ parser.add_argument("--examples", type=int, default=0)
57
+ parser.add_argument("--max-rows", type=int, default=1000000)
58
+ parser.add_argument("--max-bytes", type=int, default=268435456)
59
+ parser.add_argument("--max-pairs", type=int, default=1000000)
60
+ parser.add_argument("--temp-dir")
61
+ args = parser.parse_args(argv)
62
+ try:
63
+ policy_path = args.feature_age_limits
64
+ del args.feature_age_limits
65
+ if policy_path is not None:
66
+ args.feature_max_age_us = _load_age_limits(policy_path)
67
+ if args.feature_max_age_us is None:
68
+ raise AuditError("feature age policy must be a complete JSON object")
69
+ report = audit(**vars(args))
70
+ # Serialize completely before the first write, then check buffered I/O.
71
+ output = json.dumps(report, ensure_ascii=True, sort_keys=True, indent=2) + "\n"
72
+ sys.stdout.write(output)
73
+ sys.stdout.flush()
74
+ return 0 if report["ok"] else 1
75
+ except (AuditError, MemoryError) as exc:
76
+ try:
77
+ print(
78
+ "asofaudit: %s" % (str(exc) or "insufficient memory"),
79
+ file=sys.stderr,
80
+ flush=True,
81
+ )
82
+ except OSError:
83
+ pass
84
+ return 2
85
+ except OSError:
86
+ return 2
87
+
88
+
89
+ def cli():
90
+ """Process entrypoint: a failed final flush must retain exit2.
91
+
92
+ main() leaves streams open for its caller. Only the executable entrypoint
93
+ closes already-failing streams so interpreter shutdown cannot retry them
94
+ and replace the documented exit code with CPython's exit120.
95
+ """
96
+ try:
97
+ code = main()
98
+ except SystemExit as exc:
99
+ # argparse also writes buffered help and error output.
100
+ code = exc.code
101
+ except OSError:
102
+ code = 2
103
+ for stream in (sys.stdout, sys.stderr):
104
+ try:
105
+ stream.flush()
106
+ except OSError:
107
+ code = 2
108
+ try:
109
+ stream.close()
110
+ except OSError:
111
+ pass
112
+ return code
asofaudit/core.py ADDED
@@ -0,0 +1,435 @@
1
+ """Strict CSV manifests and a SQLite-backed bitemporal selection oracle."""
2
+
3
+ import csv
4
+ import hashlib
5
+ import heapq
6
+ import io
7
+ import os
8
+ import re
9
+ import sqlite3
10
+ import tempfile
11
+ from collections.abc import Mapping
12
+ from contextlib import contextmanager
13
+ from datetime import datetime, timezone
14
+
15
+
16
+ class AuditError(ValueError):
17
+ """Input is invalid/incomplete or storage could not finish the audit."""
18
+
19
+
20
+ _TIME = re.compile(
21
+ r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})\Z",
22
+ re.ASCII,
23
+ )
24
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
25
+ _HEADERS = {
26
+ "history": ("version_id", "entity_id", "feature", "event_at", "known_at"),
27
+ "requests": ("request_id", "entity_id", "prediction_at"),
28
+ "selections": ("request_id", "feature", "version_id"),
29
+ }
30
+
31
+
32
+ def instant(value):
33
+ """Return UTC integer microseconds, accepting only the documented grammar."""
34
+ if not isinstance(value, str) or not _TIME.fullmatch(value):
35
+ raise AuditError("timestamp must have ISO date, seconds and explicit offset")
36
+ # Validate clock fields explicitly: newer Python versions accept 24:00:00,
37
+ # while older versions reject it. Keep one grammar across interpreters.
38
+ if int(value[11:13]) > 23 or int(value[14:16]) > 59 or int(value[17:19]) > 59:
39
+ raise AuditError("invalid timestamp clock fields")
40
+ # datetime permits offsets with minute components >=60; reject those aliases.
41
+ if value[-1] != "Z" and (int(value[-5:-3]) > 23 or int(value[-2:]) > 59):
42
+ raise AuditError("invalid timestamp offset")
43
+ # Python 3.9/3.10 accept only three or six fractional digits. Pad the
44
+ # already validated 1-6 digit grammar, without rounding or float conversion.
45
+ normalized = value[:-1] + "+00:00" if value[-1] == "Z" else value
46
+ if normalized[19] == ".":
47
+ clock, offset = normalized[:-6], normalized[-6:]
48
+ whole, fraction = clock.split(".")
49
+ normalized = whole + "." + fraction.ljust(6, "0") + offset
50
+ try:
51
+ dt = datetime.fromisoformat(normalized)
52
+ delta = dt.astimezone(timezone.utc) - _EPOCH
53
+ except (ValueError, OverflowError) as exc:
54
+ raise AuditError("invalid or out-of-range timestamp") from exc
55
+ return (delta.days * 86400 + delta.seconds) * 1000000 + delta.microseconds
56
+
57
+
58
+ def _integer(value, name, minimum):
59
+ if type(value) is not int or value < minimum:
60
+ raise AuditError("%s must be an integer >= %s" % (name, minimum))
61
+
62
+
63
+ class _DigestReader(io.RawIOBase):
64
+ def __init__(self, source, limit):
65
+ self.source = source
66
+ self.limit = limit
67
+ self.count = 0
68
+ self.digest = hashlib.sha256()
69
+
70
+ def readable(self):
71
+ return True
72
+
73
+ def readinto(self, buffer):
74
+ data = self.source.read(min(len(buffer), self.limit - self.count + 1))
75
+ self.count += len(data)
76
+ if self.count > self.limit:
77
+ raise AuditError("input byte limit exceeded")
78
+ self.digest.update(data)
79
+ buffer[: len(data)] = data
80
+ return len(data)
81
+
82
+
83
+ @contextmanager
84
+ def _rows(path, kind, receipts, max_bytes, max_rows):
85
+ try:
86
+ with open(path, "rb") as source:
87
+ digest = _DigestReader(source, max_bytes)
88
+ with io.TextIOWrapper(
89
+ io.BufferedReader(digest), encoding="utf-8-sig", newline=""
90
+ ) as text:
91
+ reader = csv.reader(text, strict=True)
92
+ header = next(reader, None)
93
+ if (
94
+ header is None
95
+ or len(header) != len(set(header))
96
+ or set(header) != set(_HEADERS[kind])
97
+ ):
98
+ raise AuditError(
99
+ "%s: expected exactly columns %s"
100
+ % (kind, ",".join(_HEADERS[kind]))
101
+ )
102
+ positions = [header.index(name) for name in _HEADERS[kind]]
103
+
104
+ def generate():
105
+ count = 0
106
+ for row in reader:
107
+ count += 1
108
+ if count > max_rows:
109
+ raise AuditError("%s: row limit exceeded" % kind)
110
+ if len(row) != len(header):
111
+ raise AuditError(
112
+ "%s record %s: ragged or blank record" % (kind, count)
113
+ )
114
+ ordered = tuple(row[index] for index in positions)
115
+ required = ordered[:-1] if kind == "selections" else ordered
116
+ if any(
117
+ not value.strip() or "\x00" in value for value in required
118
+ ):
119
+ raise AuditError(
120
+ "%s record %s: blank or NUL-containing field"
121
+ % (kind, count)
122
+ )
123
+ if kind == "selections" and "\x00" in ordered[-1]:
124
+ raise AuditError("selections: NUL-containing version_id")
125
+ yield ordered
126
+ receipts[kind] = {
127
+ "sha256": digest.digest.hexdigest(),
128
+ "bytes": digest.count,
129
+ "rows": count,
130
+ }
131
+
132
+ yield generate()
133
+ if kind not in receipts:
134
+ raise AuditError("%s: input was not completely consumed" % kind)
135
+ except AuditError:
136
+ raise
137
+ except (OSError, UnicodeError, csv.Error) as exc:
138
+ raise AuditError("%s: %s" % (kind, exc)) from exc
139
+
140
+
141
+ def _reason(selected, expected, db, entity, feature, when, ttl, strict_event_before):
142
+ if selected == expected:
143
+ return None
144
+ if not selected:
145
+ return "missing_selection"
146
+ event = db.execute(
147
+ "SELECT entity, feature, event, known FROM history WHERE version=?", (selected,)
148
+ ).fetchone()
149
+ if event[0] != entity:
150
+ return "wrong_entity"
151
+ if event[1] != feature:
152
+ return "wrong_feature"
153
+ if event[2] > when:
154
+ return "future_event"
155
+ if strict_event_before and event[2] == when:
156
+ return "event_at_prediction"
157
+ if event[3] > when:
158
+ return "not_yet_known"
159
+ if ttl is not None and when - event[2] > ttl:
160
+ return "expired"
161
+ return "not_latest"
162
+
163
+
164
+ class _EarlierEvidence:
165
+ """Reverse key comparison keeps the latest retained example at heap root."""
166
+
167
+ def __init__(self, key, value):
168
+ self.key = key
169
+ self.value = value
170
+
171
+ def __lt__(self, other):
172
+ return self.key > other.key
173
+
174
+
175
+ def audit(
176
+ history,
177
+ requests,
178
+ selections,
179
+ *,
180
+ features,
181
+ max_age_us=None,
182
+ feature_max_age_us=None,
183
+ strict_event_before=False,
184
+ examples=0,
185
+ max_rows=1000000,
186
+ max_bytes=268435456,
187
+ max_pairs=1000000,
188
+ temp_dir=None,
189
+ ):
190
+ """Return a complete report, or raise AuditError without a partial report.
191
+
192
+ Sources are CSV paths. Features must be an explicit unique sequence of names.
193
+ max_age_us is inclusive event age, not age since ingestion. All limits are per
194
+ input except max_pairs. Scratch contains plaintext identifiers and times.
195
+ feature_max_age_us optionally maps EVERY requested feature to integer event
196
+ microseconds or None (unlimited), instead of a global max_age_us.
197
+ strict_event_before excludes equal event timestamps only. Known-time and
198
+ maximum event age remain inclusive. It must be an actual bool.
199
+ """
200
+ try:
201
+ history, requests, selections = [
202
+ os.fspath(path) for path in (history, requests, selections)
203
+ ]
204
+ if temp_dir is not None:
205
+ temp_dir = os.fsdecode(os.fspath(temp_dir))
206
+ except TypeError as exc:
207
+ raise AuditError("input and scratch paths must be filesystem paths") from exc
208
+ if isinstance(features, (str, bytes)):
209
+ raise AuditError("features must be a sequence, not a string")
210
+ try:
211
+ features = tuple(features)
212
+ except TypeError as exc:
213
+ raise AuditError("features must be a sequence") from exc
214
+ if not features or any(
215
+ not isinstance(f, str) or not f.strip() or "\x00" in f for f in features
216
+ ):
217
+ raise AuditError("features must contain nonblank strings")
218
+ if len(set(features)) != len(features):
219
+ raise AuditError("duplicate requested feature")
220
+ for name, value, minimum in (
221
+ ("examples", examples, 0),
222
+ ("max_rows", max_rows, 1),
223
+ ("max_bytes", max_bytes, 1),
224
+ ("max_pairs", max_pairs, 1),
225
+ ):
226
+ _integer(value, name, minimum)
227
+ if examples > 1000:
228
+ raise AuditError("examples must be <= 1000")
229
+ if len(features) > max_pairs:
230
+ raise AuditError("requested feature count exceeds pair limit")
231
+ if max_age_us is not None:
232
+ _integer(max_age_us, "max_age_us", 0)
233
+ if max_age_us > 315537897599999999:
234
+ raise AuditError("max_age_us exceeds supported datetime range")
235
+ if feature_max_age_us is not None:
236
+ if max_age_us is not None:
237
+ raise AuditError("global and per-feature age limits are mutually exclusive")
238
+ if not isinstance(feature_max_age_us, Mapping):
239
+ raise AuditError("feature_max_age_us must be a complete mapping")
240
+ if set(feature_max_age_us) != set(features):
241
+ raise AuditError("feature age limits must cover exactly requested features")
242
+ # Copy in declared feature order so caller mutation cannot change policy
243
+ # partway through an audit, and report the exact normalized policy used.
244
+ age_limits = {feature: feature_max_age_us[feature] for feature in features}
245
+ for limit in age_limits.values():
246
+ if limit is not None:
247
+ _integer(limit, "feature age limit", 0)
248
+ if limit > 315537897599999999:
249
+ raise AuditError(
250
+ "feature age limit exceeds supported datetime range"
251
+ )
252
+ else:
253
+ age_limits = {feature: max_age_us for feature in features}
254
+ if type(strict_event_before) is not bool:
255
+ raise AuditError("strict_event_before must be a boolean")
256
+ event_operator = "<" if strict_event_before else "<="
257
+ receipts = {}
258
+ try:
259
+ with tempfile.TemporaryDirectory(prefix="asofaudit-", dir=temp_dir) as scratch:
260
+ os.chmod(scratch, 0o700)
261
+ filename = os.path.join(scratch, "audit.sqlite3")
262
+ # Pre-create with private permissions before SQLite opens it.
263
+ fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
264
+ os.close(fd)
265
+ db = sqlite3.connect(filename)
266
+ try:
267
+ db.execute("PRAGMA temp_store=MEMORY")
268
+ db.execute("PRAGMA cache_size=-8192")
269
+ db.executescript("""
270
+ CREATE TABLE history(version TEXT PRIMARY KEY, entity TEXT NOT NULL,
271
+ feature TEXT NOT NULL, event INTEGER NOT NULL, known INTEGER NOT NULL,
272
+ eligible INTEGER NOT NULL DEFAULT 0,
273
+ UNIQUE(entity,feature,event,known));
274
+ CREATE INDEX lookup ON history(entity,feature,event DESC,known DESC) WHERE eligible=1;
275
+ CREATE INDEX arrival ON history(known);
276
+ CREATE TABLE requests(id TEXT PRIMARY KEY, entity TEXT NOT NULL, at INTEGER NOT NULL);
277
+ CREATE INDEX request_time ON requests(at,id);
278
+ CREATE TABLE selections(request TEXT NOT NULL, feature TEXT NOT NULL,
279
+ version TEXT NOT NULL, PRIMARY KEY(request,feature));
280
+ """)
281
+ with _rows(history, "history", receipts, max_bytes, max_rows) as rows:
282
+ for version, entity, feature, event, known in rows:
283
+ db.execute(
284
+ "INSERT INTO history(version,entity,feature,event,known) VALUES(?,?,?,?,?)",
285
+ (version, entity, feature, instant(event), instant(known)),
286
+ )
287
+ with _rows(requests, "requests", receipts, max_bytes, max_rows) as rows:
288
+ count = 0
289
+ for request, entity, when in rows:
290
+ count += 1
291
+ if count * len(features) > max_pairs:
292
+ raise AuditError("request-feature pair limit exceeded")
293
+ db.execute(
294
+ "INSERT INTO requests VALUES(?,?,?)",
295
+ (request, entity, instant(when)),
296
+ )
297
+ if not count:
298
+ raise AuditError("at least one request is required")
299
+ requested = set(features)
300
+ with _rows(
301
+ selections, "selections", receipts, max_bytes, max_rows
302
+ ) as rows:
303
+ for request, feature, version in rows:
304
+ if feature not in requested:
305
+ raise AuditError("selection has an unrequested feature")
306
+ if not db.execute(
307
+ "SELECT 1 FROM requests WHERE id=?", (request,)
308
+ ).fetchone():
309
+ raise AuditError("selection has an unknown request")
310
+ if (
311
+ version
312
+ and not db.execute(
313
+ "SELECT 1 FROM history WHERE version=?", (version,)
314
+ ).fetchone()
315
+ ):
316
+ raise AuditError("selection has an unknown version")
317
+ db.execute(
318
+ "INSERT INTO selections VALUES(?,?,?)",
319
+ (request, feature, version),
320
+ )
321
+ expected_pairs = count * len(features)
322
+ if receipts["selections"]["rows"] != expected_pairs:
323
+ raise AuditError(
324
+ "selection coverage incomplete: expected %s pairs, received %s"
325
+ % (expected_pairs, receipts["selections"]["rows"])
326
+ )
327
+ reasons = {}
328
+ evidence = []
329
+ checked = 0
330
+ expected_missing = 0
331
+ by_feature = {
332
+ feature: {"checked": 0, "violations": 0, "expected_missing": 0}
333
+ for feature in features
334
+ }
335
+ # Activate each history row at most once. The partial lookup index
336
+ # contains only versions already known at the current request time.
337
+ # Requests are chronological internally; examples retain the public
338
+ # request-ID/feature-order contract through a bounded max heap.
339
+ previous = -9223372036854775808
340
+ for request, entity, when in db.execute(
341
+ "SELECT id,entity,at FROM requests ORDER BY at,id"
342
+ ):
343
+ if when != previous:
344
+ db.execute(
345
+ "UPDATE history SET eligible=1 WHERE known>? AND known<=?",
346
+ (previous, when),
347
+ )
348
+ previous = when
349
+ for position, feature in enumerate(features):
350
+ params = [entity, feature, when, when]
351
+ query = (
352
+ "SELECT version FROM history WHERE entity=? AND feature=? AND event"
353
+ + event_operator
354
+ + "? AND known<=? AND eligible=1"
355
+ )
356
+ age_limit = age_limits[feature]
357
+ if age_limit is not None:
358
+ query += " AND event>=?"
359
+ params.append(when - age_limit)
360
+ query += " ORDER BY event DESC, known DESC LIMIT 1"
361
+ found = db.execute(query, params).fetchone()
362
+ expected = found[0] if found else ""
363
+ selected = db.execute(
364
+ "SELECT version FROM selections WHERE request=? AND feature=?",
365
+ (request, feature),
366
+ ).fetchone()[0]
367
+ checked += 1
368
+ by_feature[feature]["checked"] += 1
369
+ if not expected:
370
+ expected_missing += 1
371
+ by_feature[feature]["expected_missing"] += 1
372
+ reason = _reason(
373
+ selected,
374
+ expected,
375
+ db,
376
+ entity,
377
+ feature,
378
+ when,
379
+ age_limit,
380
+ strict_event_before,
381
+ )
382
+ if reason:
383
+ reasons[reason] = reasons.get(reason, 0) + 1
384
+ by_feature[feature]["violations"] += 1
385
+ if examples:
386
+ item = _EarlierEvidence(
387
+ (request, position),
388
+ {
389
+ "request_id": request,
390
+ "feature": feature,
391
+ "selected_version": selected,
392
+ "expected_version": expected,
393
+ "reason": reason,
394
+ },
395
+ )
396
+ if len(evidence) < examples:
397
+ heapq.heappush(evidence, item)
398
+ elif item.key < evidence[0].key:
399
+ heapq.heapreplace(evidence, item)
400
+ evidence = [
401
+ item.value for item in sorted(evidence, key=lambda item: item.key)
402
+ ]
403
+ violations = sum(reasons.values())
404
+ report = {
405
+ "schema_version": 1,
406
+ "ok": not violations,
407
+ "policy": {
408
+ "features": list(features),
409
+ "max_age_us": max_age_us,
410
+ "eligibility": (
411
+ "event_at "
412
+ + event_operator
413
+ + " prediction_at and known_at <= prediction_at"
414
+ ),
415
+ "selection": "maximum (event_at, known_at); equal pairs invalid",
416
+ },
417
+ "inputs": receipts,
418
+ "requests": count,
419
+ "checked_pairs": checked,
420
+ "expected_missing": expected_missing,
421
+ "violations": violations,
422
+ "reasons": dict(sorted(reasons.items())),
423
+ "by_feature": by_feature,
424
+ "examples": evidence,
425
+ "examples_omitted": violations - len(evidence),
426
+ }
427
+ if feature_max_age_us is not None:
428
+ report["policy"]["feature_max_age_us"] = age_limits
429
+ finally:
430
+ db.close()
431
+ return report
432
+ except AuditError:
433
+ raise
434
+ except (OSError, sqlite3.Error) as exc:
435
+ raise AuditError("audit storage/input constraint failure: %s" % exc) from exc
@@ -0,0 +1,276 @@
1
+ Metadata-Version: 2.4
2
+ Name: asofaudit
3
+ Version: 0.4.0
4
+ Summary: Offline bitemporal feature-selection audit against explicit version histories
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
10
+
11
+ # asofaudit
12
+
13
+ Check whether a training-data pipeline selected the feature versions that were
14
+ actually eligible at each prediction time, including late-arriving corrections.
15
+ No feature values, feature-store server, pandas, network access, or input code
16
+ execution are needed. Python 3.9+ with the standard-library `sqlite3` module.
17
+
18
+ This is a **version-selection audit**, not proof that a dataset is leakage-free.
19
+ It trusts your version history, identifiers, timestamps, and declared policy.
20
+
21
+ ## A correction from the future
22
+
23
+ A customer's balance event happened January 1. The original version was known
24
+ that day. A correction was written January 10. Selecting the correction for a
25
+ January 2 prediction uses a version that was not yet known, even though its event
26
+ time is before the prediction. Selecting an older version after a newer eligible
27
+ event is another error that checking only `feature_time <= prediction_time` misses.
28
+
29
+ ```sh
30
+ python -m pip install .
31
+ asofaudit examples/history.csv examples/requests.csv examples/selected.csv \
32
+ --feature balance --examples 5
33
+ ```
34
+
35
+ The example exits 1, with two violations: `not_yet_known` for `prediction-1` and
36
+ `not_latest` for `prediction-2`. The explicit empty selection for `prediction-3`
37
+ is correct because that entity has no eligible history. Replacing `selected.csv`
38
+ with `correct.csv` exits 0. This is source installation, not a PyPI release.
39
+
40
+ ## Three explicit CSV manifests
41
+
42
+ | Input | Required columns |
43
+ |---|---|
44
+ | History | `version_id,entity_id,feature,event_at,known_at` |
45
+ | Requests | `request_id,entity_id,prediction_at` |
46
+ | Selections | `request_id,feature,version_id` |
47
+
48
+ - Headers must contain exactly these columns, in any order, without duplicates.
49
+ - UTF-8 or UTF-8 BOM, comma-delimited CSV with Python's strict CSV parser.
50
+ Quoted commas and multiline fields work. Ragged/blank data records are invalid.
51
+ This does not implement a separate complete CSV grammar validator.
52
+ - IDs and feature names are exact strings, without trimming or case folding.
53
+ `001` and `1` are different. Required fields cannot be blank/whitespace-only or
54
+ contain NUL. Only selection `version_id` may be empty, meaning no feature value.
55
+ There are no inferred null tokens: `NA` is an ordinary identifier.
56
+ - Version IDs are globally unique. Request IDs are unique. Each entity/feature
57
+ `(event_at, known_at)` pair must be unique after UTC normalization. Ambiguous
58
+ ties are invalid, even if they would not affect a requested prediction.
59
+ - Supply each desired feature with a repeated `--feature` option. Every request
60
+ must have **exactly one selection for every requested feature**, including an
61
+ empty version for no value. Missing rows are invalid, never silently skipped.
62
+ - Unknown selected version IDs, unknown requests, unrequested features, duplicate
63
+ selections, empty request files, and invalid history rows are input errors.
64
+ History may be empty. Extra history features/entities are allowed and validated.
65
+
66
+ Timestamps must have exactly the form `YYYY-MM-DDTHH:MM:SS[.ffffff](Z|+HH:MM|-HH:MM)`.
67
+ Fractions have 1-6 digits. Four-digit years 0001-9999, valid dates, seconds 00-59,
68
+ hours 00-23, and explicit offsets are required. No naive times, leap seconds,
69
+ 24:00:00, timezone names, DST inference, or sub-microsecond rounding. All comparisons
70
+ use integer UTC microseconds, including dates before 1970. Fractional seconds
71
+ with 1-6 digits are padded exactly to microseconds on all supported Python
72
+ versions, including 3.9 and 3.10; no precision is rounded or truncated.
73
+
74
+ ## Declared selection policy
75
+
76
+ For the request's exact entity and feature:
77
+
78
+ 1. Keep versions with both `event_at <= prediction_at` and
79
+ `known_at <= prediction_at`. Equality is eligible.
80
+ 2. With `--max-age-us N`, also require `prediction_at - event_at <= N`.
81
+ This is an inclusive, nonnegative **event-age** limit in microseconds, not an
82
+ ingestion-age limit. Omit it for no age limit.
83
+ 3. Select the maximum `(event_at, known_at)` in that order. A newer eligible
84
+ event wins over a more recently learned correction to an older event.
85
+ 4. If no version is eligible, expect an explicit empty selected version.
86
+
87
+ This policy is fixed, not inferred from the manifests. If your pipeline uses
88
+ strict known-before times, global snapshot cutoffs, aggregation windows, deletions,
89
+ priorities, or another tie-breaker, this model is not sufficient.
90
+ A version whose known time precedes its event time is permitted but still must
91
+ pass both eligibility comparisons.
92
+
93
+ ### Different age limits for different features
94
+
95
+ Use `--feature-age-limits ages.json` instead of `--max-age-us` when features
96
+ have different declared freshness requirements:
97
+
98
+ ```json
99
+ {"balance": 86400000000, "plan": null}
100
+ ```
101
+
102
+ ```sh
103
+ asofaudit history.csv requests.csv selected.csv \
104
+ --feature balance --feature plan --feature-age-limits ages.json --examples 5
105
+ ```
106
+
107
+ A complete synthetic example is included:
108
+
109
+ ```sh
110
+ asofaudit examples/feature-ages/history.csv examples/feature-ages/requests.csv \
111
+ examples/feature-ages/selected.csv --feature balance --feature plan \
112
+ --feature-age-limits examples/feature-ages/ages.json --examples 5
113
+ ```
114
+
115
+ It exits 0: the two-day-old balance is explicitly absent and the equally old plan
116
+ is still eligible. Replacing `selected.csv` with `stale.csv` exits 1 with one
117
+ `expired` balance selection and an empty expected version.
118
+
119
+ This declares an inclusive one-day event-age limit for `balance` and explicitly
120
+ no age limit for `plan`. Both still require event and known times at or before
121
+ the prediction. It does not use the current clock or age since ingestion.
122
+
123
+ The JSON object must contain **exactly every requested feature**, with exact
124
+ names. No missing features, extras, defaults, or inheritance. Values are integer
125
+ microseconds from 0 through 315537897599999999, or `null` for unlimited. Booleans,
126
+ floats (including `1.0`), strings, negative or out-of-range values, duplicate
127
+ keys (including escaped aliases), and non-finite numbers are invalid. The file
128
+ must be UTF-8 (optional BOM), at most 1 MiB, and contain one JSON object. Invalid
129
+ policy or manifests exit 2 without a partial JSON report. The policy file is
130
+ read once and does not change the three CSV per-input byte/row limits.
131
+
132
+ The library equivalent is
133
+ `audit(..., features=['balance', 'plan'], feature_max_age_us={'balance': 86400000000, 'plan': None})`.
134
+ It copies the complete mapping before reading inputs. This mode cannot be
135
+ combined with a non-`None` global `max_age_us`. Omitting it preserves the existing
136
+ global/no-limit mode and report shape.
137
+
138
+ In this opt-in mode, schema-version-1 `policy` additionally contains the complete
139
+ normalized `feature_max_age_us` mapping; `max_age_us` is `null` because there is no
140
+ global limit. Consumers must read the per-feature mapping when present, not
141
+ interpret that global `null` as making every feature unlimited. The normalized
142
+ values are the policy used by the audit; the JSON file's raw bytes are not hashed
143
+ or added to the three CSV receipts. Keep the report if policy provenance matters.
144
+ This is explicit caller configuration, not an import of Feast feature-view TTLs
145
+ or a complete feature-store compatibility adapter.
146
+
147
+ A known selected version that violates the policy produces one reason, in this
148
+ precedence: `wrong_entity`, `wrong_feature`, `future_event`, `not_yet_known`,
149
+ `expired`, `not_latest`. An empty selection when a value exists is
150
+ `missing_selection`. The report lists the expected version only when examples
151
+ are requested. A wrong version can violate several rules; reason counts are
152
+ mutually exclusive, not a count of every possible defect.
153
+
154
+ ## Reports and CI
155
+
156
+ ```sh
157
+ asofaudit history.csv requests.csv selected.csv \
158
+ --feature balance --feature plan --max-age-us 604800000000 > audit.json
159
+ ```
160
+
161
+ - Exit **0**: complete audit, every requested pair matches this policy.
162
+ - Exit **1**: complete audit, some pairs violate this policy. JSON remains complete.
163
+ - Exit **2**: invalid/incomplete inputs, bad options, resource limit, storage
164
+ error, or output I/O failure. Invalid input emits no JSON report on stdout.
165
+ Output failures cannot retract bytes already written to a failing pipe or
166
+ filesystem; those bytes are not a complete report. Diagnostics on stderr are
167
+ best effort if that destination also fails.
168
+
169
+ JSON schema version 1 includes counts, per-feature counts, mutually exclusive
170
+ reason counts, declared policy, and SHA256/byte/row counts of each input. Digests
171
+ bind the bytes actually read. They are not signatures, proof of history
172
+ completeness, or an atomic cross-file snapshot. Freeze the three manifests before
173
+ auditing; concurrent source edits are outside the guarantee.
174
+
175
+ Examples default to **0**. Use `--examples N` (0-1000) for bounded evidence in
176
+ request-ID order and then supplied feature order. Examples expose request IDs,
177
+ feature names, selected versions, and expected versions. Counts also disclose
178
+ feature names and dataset sizes. Treat reports as private when appropriate.
179
+
180
+ ```python
181
+ from asofaudit import audit
182
+
183
+ report = audit('history.csv', 'requests.csv', 'selected.csv',
184
+ features=['balance'], examples=0)
185
+ assert report['ok'] # Only the stated version-selection policy.
186
+ ```
187
+
188
+ ## Disk, limits, and privacy
189
+
190
+ Inputs are streamed into a new temporary SQLite database. There is no extraction,
191
+ network, telemetry, input modification, or automatic repair. Identifiers and
192
+ timestamps are written to disk in plaintext; feature values are never requested.
193
+ `--temp-dir DIR` selects an existing scratch parent. On POSIX, the new directory
194
+ is mode 0700 and database 0600. Windows permission equivalence is not claimed.
195
+
196
+ Normal completion and errors close/remove the database and scratch directory.
197
+ Removal is not secure erasure. Forced termination/power loss can leave files;
198
+ backups, filesystem snapshots and elevated access can expose them. Cleanup failure
199
+ is an error and may mask an earlier error. Choose scratch storage accordingly.
200
+
201
+ Limits default to 1,000,000 rows **per input**, 256 MiB bytes **per input**, and
202
+ 1,000,000 request-feature pairs. Configure with `--max-rows`, `--max-bytes`, and
203
+ `--max-pairs`. Python's CSV field-size limit also applies. Crossing any limit fails
204
+ the whole audit. SQLite cache is advisory 8 MiB; this is not a hard RAM/disk/time
205
+ bound. SQLite indexes consume extra disk. Requests are evaluated internally in prediction-time order. Each history row
206
+ enters a partial lookup index only when its known time has arrived, avoiding
207
+ repeated scans over future corrections for every prediction. Bounded examples
208
+ still use request-ID order and supplied feature order, independent of evaluation
209
+ order. The database writes an eligibility flag and maintains an extra known-time
210
+ index; this can add disk/I/O cost on ordinary histories. No runtime bound or
211
+ large-scale performance claim is made.
212
+
213
+ ## What this does not establish
214
+
215
+ The audit cannot prove that source timestamps are true, records are complete,
216
+ version IDs bind immutable payloads, or logged selections match the data actually
217
+ used by a model. It does not inspect values, aggregation/preprocessing code,
218
+ labels, train/test groups, semantic duplicates, model memory, or online serving.
219
+ A clean report is only agreement between the three supplied manifests and the
220
+ explicit two-clock selection policy.
221
+
222
+ Feast documents why filtering the created/known timestamp matters in addition to
223
+ event time: [point-in-time joins](https://docs.feast.dev/getting-started/concepts/point-in-time-joins).
224
+ Tools such as [Timefence](https://timefence.dev/api/audit/) cover timestamp audits
225
+ and rebuild-and-compare workflows. asofaudit is a narrower independent check of
226
+ **selected version identity and complete request-feature coverage** against a
227
+ separate version history. It does not replace those tools or claim new research.
228
+
229
+ ## Develop
230
+
231
+ ```sh
232
+ python -m pip install -e . coverage ruff build
233
+ python -m unittest discover -s tests -v
234
+ coverage run --branch --source=asofaudit -m unittest discover -s tests
235
+ coverage report -m
236
+ ruff check src tests
237
+ ruff format --check src tests
238
+ python -m build
239
+ ```
240
+
241
+ Tests include an independent integer-day nested-loop oracle, late corrections,
242
+ wrong entity/feature and absent selections, exact age boundaries, UTC offsets,
243
+ invalid inputs, complete pair coverage, storage errors, cleanup, input-byte
244
+ preservation, and POSIX scratch modes. Linux local verification is separate from
245
+ hosted CI. No Windows, macOS, deployment, adoption, or real-production-data claims.
246
+
247
+
248
+ ## Opt-in strict event boundary
249
+
250
+ Some backward as-of pipelines deliberately exclude events at the exact prediction
251
+ instant. [pandas documents this choice as `allow_exact_matches=False`](https://pandas.pydata.org/docs/reference/api/pandas.merge_asof.html).
252
+ To audit that event-time policy, add `--strict-event-before`, or call
253
+ `audit(..., strict_event_before=True)`. The default remains `False`.
254
+
255
+ This changes **only** event eligibility to `event_at < prediction_at`. Known time
256
+ remains inclusive: `known_at <= prediction_at`, including corrections learned at
257
+ the prediction instant. The maximum `(event_at, known_at)` choice, exact UTC
258
+ microseconds, complete coverage, input receipts and example order stay the same.
259
+ This is not a full pandas compatibility adapter or a strict known-time policy.
260
+
261
+ Global and per-feature age limits still use inclusive event age. With age zero
262
+ and strict event eligibility, no version is eligible. At age one microsecond,
263
+ an event exactly one microsecond earlier is eligible if already known.
264
+ The API option must be an actual boolean; `0`, `1`, strings and `None` are invalid.
265
+
266
+ The report's existing `policy.eligibility` string records `<` instead of `<=` for
267
+ the event clause. No extra report fields are added. Default-mode reports remain
268
+ unchanged. A selected version whose event equals prediction time has the new
269
+ mutually exclusive reason `event_at_prediction`, between `future_event` and
270
+ `not_yet_known` in the documented precedence, only in strict mode. UTC-equivalent
271
+ strings compare equal. Future events still use `future_event`.
272
+
273
+ Tests include 150 seeded histories in both boundary modes, checked against an
274
+ independent nested-loop integer-microsecond oracle with per-feature ages, exact
275
+ selection replay, equality/UTC boundaries, reason precedence and CLI behavior.
276
+ This is local synthetic verification, not real-data validation or adoption.
@@ -0,0 +1,10 @@
1
+ asofaudit/__init__.py,sha256=-xYEtyI1y1kiFH89pWJViAFa7Hcxhqb_zPZbLDwZrMY,154
2
+ asofaudit/__main__.py,sha256=TOJrcKFbI6FZfkCu5urVrBqu8GnpP45SUDpJFE4cCDE,46
3
+ asofaudit/cli.py,sha256=RqNhSOKIkSkVMhTzPf9GlyL0P0hAbw5h7XG07SejuyM,3765
4
+ asofaudit/core.py,sha256=M5AYhuwjya607M_DTO6BvV9XO85xhLnKWvfrn31LuhM,19553
5
+ asofaudit-0.4.0.dist-info/licenses/LICENSE,sha256=5yembAmR4hjWu7NOBFMDqvjvtnM8Ta_OGaPrAsVcI-I,1071
6
+ asofaudit-0.4.0.dist-info/METADATA,sha256=tCgoWbdfc7omHrP9vjAig8Ts91EwEpKSknt-33_GoRQ,14583
7
+ asofaudit-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ asofaudit-0.4.0.dist-info/entry_points.txt,sha256=PG1_fG_72vdODlDw_jZ5KwfYY_ErnETKcT7DE7h_4lg,48
9
+ asofaudit-0.4.0.dist-info/top_level.txt,sha256=ra6Dkt2SCiQZSWH7uml99TAt3sXT_A-vCbpwjpWo_nw,10
10
+ asofaudit-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ asofaudit = asofaudit.cli:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anish Pentyala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ asofaudit