windowcross 0.1.2__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.
- windowcross/__init__.py +5 -0
- windowcross/__main__.py +87 -0
- windowcross/core.py +209 -0
- windowcross-0.1.2.dist-info/METADATA +230 -0
- windowcross-0.1.2.dist-info/RECORD +9 -0
- windowcross-0.1.2.dist-info/WHEEL +5 -0
- windowcross-0.1.2.dist-info/entry_points.txt +2 -0
- windowcross-0.1.2.dist-info/licenses/LICENSE +21 -0
- windowcross-0.1.2.dist-info/top_level.txt +1 -0
windowcross/__init__.py
ADDED
windowcross/__main__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Complete audit JSON or exit 2 if an audit or its output is incomplete."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .core import AuditError, Limits, audit
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _write_text(stream, text):
|
|
11
|
+
if stream is None:
|
|
12
|
+
raise OSError("output stream is unavailable")
|
|
13
|
+
written = stream.write(text)
|
|
14
|
+
if type(written) is not int or written != len(text):
|
|
15
|
+
raise OSError("output stream did not accept the complete text")
|
|
16
|
+
stream.flush()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _ArgumentParser(argparse.ArgumentParser):
|
|
20
|
+
def _print_message(self, message, file=None):
|
|
21
|
+
# argparse can suppress immediate write errors. They must reach main's
|
|
22
|
+
# output boundary even when help is written without Python buffering.
|
|
23
|
+
if message:
|
|
24
|
+
_write_text(sys.stderr if file is None else file, message)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _error(message):
|
|
28
|
+
# Do not echo raw I/O errors, paths or manifest contents. A broken diagnostic
|
|
29
|
+
# destination must not replace the incomplete-audit status with a traceback.
|
|
30
|
+
try:
|
|
31
|
+
_write_text(sys.stderr, "windowcross: audit incomplete; " + message + "\n")
|
|
32
|
+
except (OSError, ValueError):
|
|
33
|
+
pass
|
|
34
|
+
return 2
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main(argv=None):
|
|
38
|
+
parser = _ArgumentParser(
|
|
39
|
+
description="Audit explicit half-open windows across fixed partitions"
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument("manifest")
|
|
42
|
+
parser.add_argument("--examples", type=int, default=0)
|
|
43
|
+
for name, value in vars(Limits()).items():
|
|
44
|
+
parser.add_argument("--" + name.replace("_", "-"), type=int, default=value)
|
|
45
|
+
try:
|
|
46
|
+
args = parser.parse_args(argv)
|
|
47
|
+
except (OSError, ValueError):
|
|
48
|
+
return _error("output delivery failed")
|
|
49
|
+
try:
|
|
50
|
+
limits = Limits(**{name: getattr(args, name) for name in vars(Limits())})
|
|
51
|
+
report = audit(args.manifest, examples=args.examples, limits=limits)
|
|
52
|
+
text = json.dumps(report, ensure_ascii=True, sort_keys=True, indent=2) + "\n"
|
|
53
|
+
except AuditError as exc:
|
|
54
|
+
return _error(str(exc))
|
|
55
|
+
except MemoryError:
|
|
56
|
+
return _error("memory exhausted")
|
|
57
|
+
try:
|
|
58
|
+
_write_text(sys.stdout, text)
|
|
59
|
+
except (OSError, ValueError):
|
|
60
|
+
return _error("output delivery failed")
|
|
61
|
+
return 0 if report["passed"] else 1
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def cli(argv=None):
|
|
65
|
+
"""Terminating process boundary, including argparse and final flushes."""
|
|
66
|
+
try:
|
|
67
|
+
status = main(argv)
|
|
68
|
+
except SystemExit as exc:
|
|
69
|
+
status = exc.code if isinstance(exc.code, int) else 0 if exc.code is None else 1
|
|
70
|
+
for name in ("stdout", "stderr"):
|
|
71
|
+
stream = getattr(sys, name)
|
|
72
|
+
if stream is None:
|
|
73
|
+
continue
|
|
74
|
+
try:
|
|
75
|
+
stream.flush()
|
|
76
|
+
except (OSError, ValueError):
|
|
77
|
+
if name == "stdout" and status in (0, 1):
|
|
78
|
+
_error("output delivery failed")
|
|
79
|
+
# Only the process entry point changes streams. Prevent Python from
|
|
80
|
+
# retrying the failed flush at shutdown and replacing exit 2 by 120.
|
|
81
|
+
setattr(sys, name, None)
|
|
82
|
+
status = 2
|
|
83
|
+
return status
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
sys.exit(cli())
|
windowcross/core.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Exact cross-split overlap audit of caller-declared half-open time windows."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import hashlib
|
|
5
|
+
import heapq
|
|
6
|
+
import io
|
|
7
|
+
import re
|
|
8
|
+
from collections import Counter, defaultdict
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from itertools import groupby, islice
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AuditError(ValueError):
|
|
16
|
+
"""The manifest cannot be completely audited under the declared contract."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _integer(name, value, minimum):
|
|
20
|
+
if type(value) is not int or value < minimum:
|
|
21
|
+
raise AuditError(f"{name} must be an integer >= {minimum}")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Limits:
|
|
26
|
+
"""Acceptance limits, not hard process memory or time bounds."""
|
|
27
|
+
|
|
28
|
+
max_bytes: int = 16777216
|
|
29
|
+
max_records: int = 100000
|
|
30
|
+
max_field_chars: int = 1024
|
|
31
|
+
max_splits: int = 100
|
|
32
|
+
|
|
33
|
+
def __post_init__(self):
|
|
34
|
+
for name, value in vars(self).items():
|
|
35
|
+
_integer(name, value, 1)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_TIME = re.compile(
|
|
39
|
+
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})\Z",
|
|
40
|
+
re.ASCII,
|
|
41
|
+
)
|
|
42
|
+
_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def instant(text):
|
|
46
|
+
"""Parse the fixed timestamp grammar into integer UTC microseconds."""
|
|
47
|
+
if not isinstance(text, str) or not _TIME.fullmatch(text):
|
|
48
|
+
raise AuditError("timestamp needs ISO date, seconds and explicit offset")
|
|
49
|
+
if int(text[11:13]) > 23 or int(text[14:16]) > 59 or int(text[17:19]) > 59:
|
|
50
|
+
raise AuditError("invalid timestamp clock fields")
|
|
51
|
+
if text[-1] != "Z" and (int(text[-5:-3]) > 23 or int(text[-2:]) > 59):
|
|
52
|
+
raise AuditError("invalid timestamp offset")
|
|
53
|
+
# Python 3.9/3.10 accept only 3 or 6 fractional digits. Normalize the
|
|
54
|
+
# already validated grammar to six without float conversion or rounding.
|
|
55
|
+
normalized = text[:-1] + "+00:00" if text[-1] == "Z" else text
|
|
56
|
+
if normalized[19] == ".":
|
|
57
|
+
clock, offset = normalized[:-6], normalized[-6:]
|
|
58
|
+
whole, fraction = clock.split(".")
|
|
59
|
+
normalized = whole + "." + fraction.ljust(6, "0") + offset
|
|
60
|
+
try:
|
|
61
|
+
dt = datetime.fromisoformat(normalized)
|
|
62
|
+
delta = dt.astimezone(timezone.utc) - _EPOCH
|
|
63
|
+
except (ValueError, OverflowError) as exc:
|
|
64
|
+
raise AuditError("invalid or out-of-range timestamp") from exc
|
|
65
|
+
return (delta.days * 86400 + delta.seconds) * 1000000 + delta.microseconds
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _load(path, limits):
|
|
69
|
+
try:
|
|
70
|
+
with Path(path).open("rb") as stream:
|
|
71
|
+
raw = stream.read(limits.max_bytes + 1)
|
|
72
|
+
if len(raw) > limits.max_bytes:
|
|
73
|
+
raise AuditError("manifest byte limit exceeded")
|
|
74
|
+
text = raw.decode("utf-8-sig")
|
|
75
|
+
if "\x00" in text:
|
|
76
|
+
raise AuditError("manifest must not contain NUL")
|
|
77
|
+
reader = csv.reader(io.StringIO(text, newline=""), strict=True)
|
|
78
|
+
if next(reader, None) != ["id", "entity", "split", "start_at", "end_at"]:
|
|
79
|
+
raise AuditError("expected exact header id,entity,split,start_at,end_at")
|
|
80
|
+
seen, rows, splits = set(), [], Counter()
|
|
81
|
+
for number, row in enumerate(reader, 2):
|
|
82
|
+
if len(rows) >= limits.max_records:
|
|
83
|
+
raise AuditError("manifest record limit exceeded")
|
|
84
|
+
if len(row) != 5 or any(
|
|
85
|
+
not cell.strip() or len(cell) > limits.max_field_chars for cell in row
|
|
86
|
+
):
|
|
87
|
+
raise AuditError(
|
|
88
|
+
f"invalid field count, blank or oversized field at record {number}"
|
|
89
|
+
)
|
|
90
|
+
key, entity, split, start, end = row
|
|
91
|
+
if key in seen:
|
|
92
|
+
raise AuditError(f"duplicate id at record {number}")
|
|
93
|
+
seen.add(key)
|
|
94
|
+
a, b = instant(start), instant(end)
|
|
95
|
+
if a >= b:
|
|
96
|
+
raise AuditError(f"interval must have start < end at record {number}")
|
|
97
|
+
rows.append((entity, a, b, key, split))
|
|
98
|
+
splits[split] += 1
|
|
99
|
+
if len(splits) > limits.max_splits:
|
|
100
|
+
raise AuditError("manifest split limit exceeded")
|
|
101
|
+
if not rows:
|
|
102
|
+
raise AuditError("manifest needs at least one record")
|
|
103
|
+
except (OSError, UnicodeError, csv.Error, OverflowError) as exc:
|
|
104
|
+
raise AuditError("unreadable or invalid UTF-8 CSV manifest") from exc
|
|
105
|
+
return rows, splits, {"sha256": hashlib.sha256(raw).hexdigest(), "bytes": len(raw)}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def audit(path, *, examples=0, limits=None):
|
|
109
|
+
"""Return a complete report or raise AuditError, never a partial audit.
|
|
110
|
+
|
|
111
|
+
Positive half-open [start_at,end_at) intervals, same exact entity, different
|
|
112
|
+
exact split. All split pairs are symmetric. No embargo or automatic repair.
|
|
113
|
+
"""
|
|
114
|
+
_integer("examples", examples, 0)
|
|
115
|
+
if examples > 1000:
|
|
116
|
+
raise AuditError("examples must be <= 1000")
|
|
117
|
+
if limits is None:
|
|
118
|
+
limits = Limits()
|
|
119
|
+
if type(limits) is not Limits:
|
|
120
|
+
raise AuditError("limits must be a Limits instance")
|
|
121
|
+
rows, totals, receipt = _load(path, limits)
|
|
122
|
+
rows.sort() # entity, start, end, id; globally unique ID breaks all ties.
|
|
123
|
+
pairs, affected, samples = Counter(), Counter(), []
|
|
124
|
+
entities = affected_entities = 0
|
|
125
|
+
for entity, records in groupby(rows, key=lambda row: row[0]):
|
|
126
|
+
entities += 1
|
|
127
|
+
ends = []
|
|
128
|
+
active = Counter()
|
|
129
|
+
witnesses = defaultdict(dict) if examples else None
|
|
130
|
+
unmarked = defaultdict(dict)
|
|
131
|
+
entity_bad = False
|
|
132
|
+
for _, start, end, key, split in records:
|
|
133
|
+
# Endpoints touching at start do not share a half-open instant.
|
|
134
|
+
while ends and ends[0][0] <= start:
|
|
135
|
+
_, old_key, old_split = heapq.heappop(ends)
|
|
136
|
+
active[old_split] -= 1
|
|
137
|
+
if not active[old_split]:
|
|
138
|
+
# Only currently live splits need to be sorted and scanned.
|
|
139
|
+
del active[old_split]
|
|
140
|
+
if witnesses is not None:
|
|
141
|
+
del witnesses[old_split][old_key]
|
|
142
|
+
unmarked[old_split].pop(old_key, None)
|
|
143
|
+
current_bad = False
|
|
144
|
+
for other in sorted(active):
|
|
145
|
+
if other == split or not active[other]:
|
|
146
|
+
continue
|
|
147
|
+
pair = tuple(sorted((split, other)))
|
|
148
|
+
pairs[pair] += active[other]
|
|
149
|
+
current_bad = entity_bad = True
|
|
150
|
+
# Every pending prior record is newly affected at most once,
|
|
151
|
+
# regardless of how many crossing pairs it participates in.
|
|
152
|
+
affected[other] += len(unmarked[other])
|
|
153
|
+
unmarked[other].clear()
|
|
154
|
+
if witnesses is not None:
|
|
155
|
+
for old_key, (old_start, old_end) in islice(
|
|
156
|
+
witnesses[other].items(), examples - len(samples)
|
|
157
|
+
):
|
|
158
|
+
samples.append(
|
|
159
|
+
{
|
|
160
|
+
"entity": entity,
|
|
161
|
+
"earlier_id": old_key,
|
|
162
|
+
"earlier_split": other,
|
|
163
|
+
"earlier_start_us": old_start,
|
|
164
|
+
"earlier_end_us": old_end,
|
|
165
|
+
"later_id": key,
|
|
166
|
+
"later_split": split,
|
|
167
|
+
"later_start_us": start,
|
|
168
|
+
"later_end_us": end,
|
|
169
|
+
"overlap_us": min(end, old_end) - start,
|
|
170
|
+
}
|
|
171
|
+
)
|
|
172
|
+
if len(samples) == examples:
|
|
173
|
+
# Counts need split multiplicities, not record metadata.
|
|
174
|
+
# Once the evidence cap is full, stop retaining witnesses.
|
|
175
|
+
witnesses = None
|
|
176
|
+
if current_bad:
|
|
177
|
+
affected[split] += 1
|
|
178
|
+
else:
|
|
179
|
+
unmarked[split][key] = None
|
|
180
|
+
active[split] += 1
|
|
181
|
+
if witnesses is not None:
|
|
182
|
+
witnesses[split][key] = (start, end)
|
|
183
|
+
heapq.heappush(ends, (end, key, split))
|
|
184
|
+
affected_entities += entity_bad
|
|
185
|
+
count = sum(pairs.values())
|
|
186
|
+
return {
|
|
187
|
+
"schema_version": 1,
|
|
188
|
+
"passed": not count,
|
|
189
|
+
"policy": "same_entity_different_split_positive_half_open_overlap",
|
|
190
|
+
"counts": {
|
|
191
|
+
"records": len(rows),
|
|
192
|
+
"entities": entities,
|
|
193
|
+
"cross_split_pairs": count,
|
|
194
|
+
"affected_records": sum(affected.values()),
|
|
195
|
+
"affected_entities": affected_entities,
|
|
196
|
+
},
|
|
197
|
+
"splits": {
|
|
198
|
+
split: {"records": totals[split], "affected_records": affected[split]}
|
|
199
|
+
for split in sorted(totals)
|
|
200
|
+
},
|
|
201
|
+
"split_pairs": [
|
|
202
|
+
{"left_split": a, "right_split": b, "overlap_pairs": n}
|
|
203
|
+
for (a, b), n in sorted(pairs.items())
|
|
204
|
+
],
|
|
205
|
+
"examples": samples,
|
|
206
|
+
"examples_omitted": count - len(samples),
|
|
207
|
+
"settings": {"examples": examples, "limits": dict(vars(limits))},
|
|
208
|
+
"input": receipt,
|
|
209
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: windowcross
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Offline exact cross-partition time-window overlap audit
|
|
5
|
+
Author: Anish Pentyala
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/anishpentyala/windowcross
|
|
8
|
+
Project-URL: Repository, https://github.com/anishpentyala/windowcross
|
|
9
|
+
Project-URL: Issues, https://github.com/anishpentyala/windowcross/issues
|
|
10
|
+
Keywords: time-series,data-leakage,csv,data-validation
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# windowcross
|
|
17
|
+
|
|
18
|
+
[](https://github.com/anishpentyala/windowcross/actions)
|
|
19
|
+
|
|
20
|
+
Audit whether explicitly assigned time windows overlap across dataset partitions.
|
|
21
|
+
|
|
22
|
+
## Quickstart
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
python -m pip install "git+https://github.com/anishpentyala/windowcross.git"
|
|
26
|
+
cat > windows.csv <<'CSV'
|
|
27
|
+
id,entity,split,start_at,end_at
|
|
28
|
+
a,x,train,2026-01-01T00:00:00Z,2026-01-03T00:00:00Z
|
|
29
|
+
b,x,test,2026-01-02T00:00:00Z,2026-01-04T00:00:00Z
|
|
30
|
+
c,x,test,2026-01-04T00:00:00Z,2026-01-05T00:00:00Z
|
|
31
|
+
CSV
|
|
32
|
+
windowcross windows.csv --examples 1
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
This exits 1: one cross-split pair overlaps, affecting two records. The intervals
|
|
36
|
+
for `b` and `c` only touch and do not overlap. Comparisons require the same exact
|
|
37
|
+
entity and different splits. This audits declared windows, not every kind of
|
|
38
|
+
training leakage or statistical independence.
|
|
39
|
+
|
|
40
|
+
A PyPI release is being prepared. Until its package page is linked here, use the
|
|
41
|
+
source-install command above.
|
|
42
|
+
|
|
43
|
+
A label might depend on an outcome observed after its prediction time. Two rows
|
|
44
|
+
assigned to different splits can therefore use overlapping outcome windows even
|
|
45
|
+
if their prediction times are ordered. `windowcross` checks the declared windows
|
|
46
|
+
without creating or changing the split.
|
|
47
|
+
|
|
48
|
+
It reads one local CSV, validates the entire input, and reports exact pair and
|
|
49
|
+
affected-record counts. It uses Python's standard library and makes no network
|
|
50
|
+
calls. This is source-only software, not a hosted service or registry release.
|
|
51
|
+
|
|
52
|
+
## Run from source
|
|
53
|
+
|
|
54
|
+
Python 3.9 or newer:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
python -m pip install .
|
|
58
|
+
windowcross examples/crossing.csv
|
|
59
|
+
windowcross examples/crossing.csv --examples 5
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Or, without installing:
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
PYTHONPATH=src python -m windowcross examples/crossing.csv
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Exit statuses: `0` means no crossing under this policy, `1` means at least one
|
|
69
|
+
crossing, and `2` means invalid input/options or an incomplete audit. Invalid
|
|
70
|
+
input does not emit partial report JSON. Do not treat missing output, an error,
|
|
71
|
+
or an unrecognized status as a pass. Output delivery can itself fail, so consumers
|
|
72
|
+
must also successfully parse a complete report. The CLI checks complete writes and
|
|
73
|
+
flushes before reporting an audit status. Failed report, help or diagnostic
|
|
74
|
+
delivery exits 2, including closed streams and full output devices. Some bytes
|
|
75
|
+
may already have reached the destination before a later delivery error; a
|
|
76
|
+
partial report is never a usable audit. Embedded callers can use `main(argv)`;
|
|
77
|
+
the `cli(argv)` process wrapper also handles final flushes and may disable a
|
|
78
|
+
failed standard stream to avoid another flush during interpreter shutdown.
|
|
79
|
+
|
|
80
|
+
## Input and exact scope
|
|
81
|
+
|
|
82
|
+
```csv
|
|
83
|
+
id,entity,split,start_at,end_at
|
|
84
|
+
p1,account-7,train,2026-01-01T00:00:00Z,2026-01-03T00:00:00Z
|
|
85
|
+
p2,account-7,test,2026-01-02T00:00:00Z,2026-01-04T00:00:00Z
|
|
86
|
+
p3,account-7,test,2026-01-04T00:00:00Z,2026-01-05T00:00:00Z
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The first two rows overlap for one day. The second and third only touch; they do
|
|
90
|
+
not overlap. Rows in the same split are not violations even when they overlap.
|
|
91
|
+
|
|
92
|
+
- Header names and order must match exactly. No extra columns.
|
|
93
|
+
- IDs must be globally unique. Entity and split comparisons use exact strings,
|
|
94
|
+
with no numeric conversion, case folding, trimming or Unicode normalization.
|
|
95
|
+
A leading/trailing space is significant; whitespace-only fields are invalid.
|
|
96
|
+
- Each interval is positive and half-open: `[start_at, end_at)`. Empty and reversed
|
|
97
|
+
intervals are errors. Equal end/start boundaries do not overlap.
|
|
98
|
+
- Compare only rows with the **same entity and different splits**, symmetrically.
|
|
99
|
+
The entity is a caller-declared comparison scope. If every row should be
|
|
100
|
+
compared, use one constant entity. Different entities are never compared;
|
|
101
|
+
this is not evidence they are independent.
|
|
102
|
+
- Timestamps require `YYYY-MM-DDTHH:MM:SS`, optional 1-6 fractional digits, and
|
|
103
|
+
`Z` or a numeric `+HH:MM`/`-HH:MM` offset. They are converted to integer UTC
|
|
104
|
+
microseconds, never floats. Numeric offsets denote a known fixed offset
|
|
105
|
+
(`-00:00` is treated as zero), not a timezone or unknown-local-offset marker.
|
|
106
|
+
Leap seconds, more than six fractional digits, missing offsets, invalid dates,
|
|
107
|
+
and instants outside Python's UTC year 1-9999 range are rejected.
|
|
108
|
+
- UTF-8 CSV only, with an optional UTF-8 BOM. Quoted commas, newlines and Unicode
|
|
109
|
+
identifiers are allowed. NUL is rejected. At least one data row is required.
|
|
110
|
+
Blank records are errors, not ignored rows.
|
|
111
|
+
|
|
112
|
+
## Report and evidence
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
from windowcross import audit, Limits, AuditError
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
report = audit("examples/crossing.csv", examples=2,
|
|
119
|
+
limits=Limits(max_records=100_000))
|
|
120
|
+
except AuditError:
|
|
121
|
+
raise # Not a clean audit.
|
|
122
|
+
print(report["counts"]["cross_split_pairs"])
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Schema version 1 includes:
|
|
126
|
+
|
|
127
|
+
- `passed`: true only when cross-split pair count is zero.
|
|
128
|
+
- `counts`: records, distinct entities, overlapping cross-split pairs, distinct
|
|
129
|
+
affected records and affected entities. A record with many partners counts
|
|
130
|
+
once as affected. Pair counts are unordered, not doubled.
|
|
131
|
+
- `splits`: total and affected records for every split, including clean ones.
|
|
132
|
+
- `split_pairs`: nonzero pair counts, ordered by lexical split names.
|
|
133
|
+
- `input`: SHA-256 and byte length of the exact bytes read, including BOM and
|
|
134
|
+
newline choices. This receipt identifies input bytes, not their truth or source.
|
|
135
|
+
- `settings`: effective limits and requested evidence cap.
|
|
136
|
+
- `examples` and `examples_omitted`: bounded witnesses and exact remaining pair
|
|
137
|
+
count. Default cap is zero. Counts are still complete when evidence is capped.
|
|
138
|
+
|
|
139
|
+
Evidence ordering is deterministic, not a ranking of severity. Rows are scanned
|
|
140
|
+
by `(entity, UTC start, UTC end, id)`. For each current row, prior active split
|
|
141
|
+
names are visited lexically; records in that split retain their scan/insertion
|
|
142
|
+
order. The first requested pairs in that order are emitted. `earlier`/`later`
|
|
143
|
+
refer to this scan order, including tie-breaking, not strict time inequality.
|
|
144
|
+
Evidence has entity, both IDs, split names, UTC start/end microseconds, and exact
|
|
145
|
+
overlap duration. Reordering input rows preserves all report contents except the
|
|
146
|
+
byte receipt. For timestamps before 1970, epoch microseconds are negative.
|
|
147
|
+
|
|
148
|
+
**Privacy:** the default omits record IDs, entity values and timestamps from the
|
|
149
|
+
report. Split names, sizes, overlap counts and a hash remain visible. This is not
|
|
150
|
+
an anonymization promise. `--examples` explicitly includes potentially sensitive
|
|
151
|
+
record-level evidence. Error messages avoid echoing field contents or the path;
|
|
152
|
+
the invoked shell command and filesystem can still expose the path. Keep reports
|
|
153
|
+
and source manifests in an appropriate location.
|
|
154
|
+
|
|
155
|
+
## Limits and cost
|
|
156
|
+
|
|
157
|
+
Defaults: 16 MiB input bytes, 100,000 records, 1,024 characters per field and 100
|
|
158
|
+
distinct splits. Set `--max-bytes`, `--max-records`, `--max-field-chars`, and
|
|
159
|
+
`--max-splits` to positive integers. `--examples` accepts 0 through 1000. The API
|
|
160
|
+
uses the same `Limits` defaults and rejects booleans for integer settings.
|
|
161
|
+
|
|
162
|
+
The file is read up to the byte cap plus one, decoded and fully parsed, then
|
|
163
|
+
sorted in memory. This is **not streaming**, and these acceptance caps are **not
|
|
164
|
+
hard RAM or runtime bounds**. Python's CSV parser field limit can also reject a
|
|
165
|
+
large field, even if the configured field cap would allow it; the audit fails
|
|
166
|
+
rather than modifying the process-wide CSV limit.
|
|
167
|
+
|
|
168
|
+
For N rows, S splits, and E emitted examples, sorting plus the sweep costs
|
|
169
|
+
`O(N log N + N S log S + E)` worst case. The S term matters when increasing
|
|
170
|
+
`max_splits`. Sorting active split labels is included in that bound. Expired splits are removed
|
|
171
|
+
from that index as soon as their live count reaches zero, then reinserted if
|
|
172
|
+
they return. Each row scans only currently live split labels rather than every
|
|
173
|
+
split previously seen for the entity. This can save work on sparse histories
|
|
174
|
+
with many split labels, but does not improve the dense worst-case bound.
|
|
175
|
+
Deleting and reinserting labels adds work, so it is not a universal speedup. Memory is
|
|
176
|
+
`O(input bytes + N + S² + E)`, including the per-split-pair report. Counts are
|
|
177
|
+
Python integers. Split multiplicities and an end heap avoid materializing all
|
|
178
|
+
crossing pairs. Per-record active start/end witness maps are omitted when
|
|
179
|
+
`examples=0`, and dropped once the evidence cap is filled. Unfilled evidence
|
|
180
|
+
requests retain those maps. The end heap, parsed rows and pending affected-record
|
|
181
|
+
IDs still take memory; this is not a hard RAM guarantee or a claim of lower
|
|
182
|
+
whole-process peak memory. Every newly affected prior record is cleared from a pending map
|
|
183
|
+
at most once; dense overlap still produces exact affected counts. This does not
|
|
184
|
+
make large inputs or large split counts cheap.
|
|
185
|
+
|
|
186
|
+
## What a pass does not mean
|
|
187
|
+
|
|
188
|
+
This is not a leakage certificate, statistical independence test, or validation
|
|
189
|
+
of a model's evaluation procedure. It does not infer label horizons, build or
|
|
190
|
+
purge folds, add embargoes or gaps, choose entity scope, inspect feature
|
|
191
|
+
availability, find duplicate content, or check dependencies between different
|
|
192
|
+
entities. A contaminated manifest can omit the relevant windows or assign
|
|
193
|
+
misleading scopes and still pass. Select boundaries and scopes from the actual
|
|
194
|
+
meaning of the data before using this check.
|
|
195
|
+
|
|
196
|
+
## Related work and boundaries
|
|
197
|
+
|
|
198
|
+
This is a narrow audit format, not a claim of a new interval algorithm or better
|
|
199
|
+
cross-validation method. Existing tools cover broader or different workflows:
|
|
200
|
+
|
|
201
|
+
- [scikit-learn TimeSeriesSplit](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html)
|
|
202
|
+
creates time-ordered folds and offers a sample-count `gap`; its documentation
|
|
203
|
+
discusses equally spaced samples for comparable fold metrics.
|
|
204
|
+
- [purged-cross-validation](https://eslazarev.github.io/purged-cross-validation/api/splitters/)
|
|
205
|
+
already offers label-horizon-aware splitters, purging and embargoes. If you need
|
|
206
|
+
fold construction, inspect it rather than treating this audit as a substitute.
|
|
207
|
+
- [bedtools intersect](https://bedtools.readthedocs.io/en/latest/content/tools/intersect.html)
|
|
208
|
+
already uses a sorted sweep for interval intersection in genomic workflows.
|
|
209
|
+
- [pandas Interval.overlaps](https://pandas.pydata.org/docs/reference/api/pandas.Interval.overlaps.html)
|
|
210
|
+
documents open/closed boundary behavior. This tool fixes one convention and
|
|
211
|
+
rejects empty windows rather than offering all closure types.
|
|
212
|
+
|
|
213
|
+
Boundary conventions and purge direction differ across published workflows.
|
|
214
|
+
This tool's symmetric positive half-open policy must not be assumed equivalent
|
|
215
|
+
to them. See [EVIDENCE.md](EVIDENCE.md) for the checked sources and limits.
|
|
216
|
+
|
|
217
|
+
## Development
|
|
218
|
+
|
|
219
|
+
```sh
|
|
220
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
221
|
+
ruff check src tests proof
|
|
222
|
+
ruff format --check src tests proof
|
|
223
|
+
python -m build
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
The suite compares complete reports against a separate pair-enumerating oracle,
|
|
227
|
+
including deterministic witness order, dense counts, invalid inputs, UTC bounds,
|
|
228
|
+
privacy defaults and CLI exit behavior. See [VALIDATION.md](VALIDATION.md) for
|
|
229
|
+
what has actually been run. No dependency, registry or Marketplace publication
|
|
230
|
+
is implied by this repository.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
windowcross/__init__.py,sha256=C8C3ta2xjdFwMrRBKKaeFbq4RUsV4lKLl3MR9wJlMb4,147
|
|
2
|
+
windowcross/__main__.py,sha256=KarFAbnE_4BFT3aQUYXWBtdJcx2rnIgFtkzf4_GCSAs,3032
|
|
3
|
+
windowcross/core.py,sha256=LKKqGwcQ7x0Bs1YIPg954EiSnDIWpR2j0jHHFimECZw,8865
|
|
4
|
+
windowcross-0.1.2.dist-info/licenses/LICENSE,sha256=5yembAmR4hjWu7NOBFMDqvjvtnM8Ta_OGaPrAsVcI-I,1071
|
|
5
|
+
windowcross-0.1.2.dist-info/METADATA,sha256=JE_Z6S8z8VJn3ZIZB5CQWBQyqa9BB2o_IXaSYF9AFPc,11676
|
|
6
|
+
windowcross-0.1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
windowcross-0.1.2.dist-info/entry_points.txt,sha256=K0Gkcy1Uw6VJVkSKSn_X7ZfWF61iRpW_qn_ev4EfI8Q,57
|
|
8
|
+
windowcross-0.1.2.dist-info/top_level.txt,sha256=sVvDvg87Iu5zUE0HHp5MuaIy0caZ76mP96mM-BpxgWc,12
|
|
9
|
+
windowcross-0.1.2.dist-info/RECORD,,
|
|
@@ -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
|
+
windowcross
|