splitwitness 0.2.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.
- splitwitness/__init__.py +7 -0
- splitwitness/__main__.py +51 -0
- splitwitness/core.py +227 -0
- splitwitness/memberships.py +172 -0
- splitwitness-0.2.2.dist-info/METADATA +254 -0
- splitwitness-0.2.2.dist-info/RECORD +10 -0
- splitwitness-0.2.2.dist-info/WHEEL +5 -0
- splitwitness-0.2.2.dist-info/entry_points.txt +2 -0
- splitwitness-0.2.2.dist-info/licenses/LICENSE +21 -0
- splitwitness-0.2.2.dist-info/top_level.txt +1 -0
splitwitness/__init__.py
ADDED
splitwitness/__main__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from .core import AuditError, Limits, audit
|
|
6
|
+
from .memberships import audit_memberships
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main(argv=None):
|
|
10
|
+
parser = argparse.ArgumentParser(
|
|
11
|
+
description="Audit fixed split assignments against declared co-location links."
|
|
12
|
+
)
|
|
13
|
+
parser.add_argument("records", help="UTF-8 CSV with exact header id,split")
|
|
14
|
+
parser.add_argument("links", help="CSV: left_id,right_id,relation")
|
|
15
|
+
parser.add_argument(
|
|
16
|
+
"--memberships",
|
|
17
|
+
action="store_true",
|
|
18
|
+
help="Interpret second input as record_id,namespace,group_id; require all records covered",
|
|
19
|
+
)
|
|
20
|
+
parser.add_argument("--examples", type=int, default=0)
|
|
21
|
+
parser.add_argument("--max-witness-edges", type=int, default=20)
|
|
22
|
+
for name, value in vars(Limits()).items():
|
|
23
|
+
parser.add_argument("--" + name.replace("_", "-"), type=int, default=value)
|
|
24
|
+
args = parser.parse_args(argv)
|
|
25
|
+
try:
|
|
26
|
+
limits = Limits(**{name: getattr(args, name) for name in vars(Limits())})
|
|
27
|
+
auditor = audit_memberships if args.memberships else audit
|
|
28
|
+
report = auditor(
|
|
29
|
+
args.records,
|
|
30
|
+
args.links,
|
|
31
|
+
examples=args.examples,
|
|
32
|
+
max_witness_edges=args.max_witness_edges,
|
|
33
|
+
limits=limits,
|
|
34
|
+
)
|
|
35
|
+
output = json.dumps(report, ensure_ascii=True, sort_keys=True, indent=2) + "\n"
|
|
36
|
+
except AuditError as exc:
|
|
37
|
+
# AuditError messages contain only static labels and record numbers.
|
|
38
|
+
print(f"splitwitness: audit incomplete; {exc}", file=sys.stderr)
|
|
39
|
+
return 2
|
|
40
|
+
except MemoryError:
|
|
41
|
+
print("splitwitness: audit incomplete; memory exhausted", file=sys.stderr)
|
|
42
|
+
return 2
|
|
43
|
+
try:
|
|
44
|
+
sys.stdout.write(output)
|
|
45
|
+
except BrokenPipeError:
|
|
46
|
+
return 2
|
|
47
|
+
return 0 if report["passed"] else 1
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
if __name__ == "__main__":
|
|
51
|
+
sys.exit(main())
|
splitwitness/core.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Audit fixed partition assignments against explicit undirected constraints."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import hashlib
|
|
5
|
+
import io
|
|
6
|
+
from collections import Counter, defaultdict, deque
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AuditError(ValueError):
|
|
12
|
+
"""The supplied manifests cannot be completely audited."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _integer(name, value, minimum):
|
|
16
|
+
if type(value) is not int or value < minimum:
|
|
17
|
+
raise AuditError(f"{name} must be an integer >= {minimum}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Limits:
|
|
22
|
+
"""Acceptance caps, not a process memory or runtime guarantee."""
|
|
23
|
+
|
|
24
|
+
max_bytes: int = 16 * 1024 * 1024
|
|
25
|
+
max_records: int = 100_000
|
|
26
|
+
max_links: int = 500_000
|
|
27
|
+
max_field_chars: int = 1024
|
|
28
|
+
max_splits: int = 100
|
|
29
|
+
|
|
30
|
+
def __post_init__(self):
|
|
31
|
+
for name, value in vars(self).items():
|
|
32
|
+
_integer(name, value, 1)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _rows(path, header, label, limits, row_cap):
|
|
36
|
+
try:
|
|
37
|
+
with Path(path).open("rb") as source:
|
|
38
|
+
raw = source.read(limits.max_bytes + 1)
|
|
39
|
+
if len(raw) > limits.max_bytes:
|
|
40
|
+
raise AuditError(f"{label}: byte limit exceeded")
|
|
41
|
+
text = raw.decode("utf-8")
|
|
42
|
+
if "\x00" in text:
|
|
43
|
+
raise AuditError(f"{label}: NUL is not allowed")
|
|
44
|
+
reader = csv.reader(io.StringIO(text, newline=""), strict=True)
|
|
45
|
+
if next(reader, None) != header:
|
|
46
|
+
raise AuditError(f"{label}: expected exact header {','.join(header)}")
|
|
47
|
+
rows = []
|
|
48
|
+
for number, row in enumerate(reader, 2):
|
|
49
|
+
if len(rows) >= row_cap:
|
|
50
|
+
raise AuditError(f"{label}: row limit exceeded")
|
|
51
|
+
if len(row) != len(header):
|
|
52
|
+
raise AuditError(f"{label}: wrong field count at record {number}")
|
|
53
|
+
if any(not cell or len(cell) > limits.max_field_chars for cell in row):
|
|
54
|
+
raise AuditError(
|
|
55
|
+
f"{label}: empty or oversized field at record {number}"
|
|
56
|
+
)
|
|
57
|
+
rows.append(row)
|
|
58
|
+
except (OSError, UnicodeError, csv.Error, OverflowError) as exc:
|
|
59
|
+
raise AuditError(f"{label}: unreadable or invalid UTF-8 CSV") from exc
|
|
60
|
+
return rows, {"sha256": hashlib.sha256(raw).hexdigest(), "bytes": len(raw)}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _Groups:
|
|
64
|
+
def __init__(self, keys):
|
|
65
|
+
self.parent = {key: key for key in keys}
|
|
66
|
+
self.size = dict.fromkeys(keys, 1)
|
|
67
|
+
|
|
68
|
+
def find(self, key):
|
|
69
|
+
while key != self.parent[key]:
|
|
70
|
+
self.parent[key] = self.parent[self.parent[key]]
|
|
71
|
+
key = self.parent[key]
|
|
72
|
+
return key
|
|
73
|
+
|
|
74
|
+
def join(self, left, right):
|
|
75
|
+
left, right = self.find(left), self.find(right)
|
|
76
|
+
if left == right:
|
|
77
|
+
return
|
|
78
|
+
if self.size[left] < self.size[right]:
|
|
79
|
+
left, right = right, left
|
|
80
|
+
self.parent[right] = left
|
|
81
|
+
self.size[left] += self.size[right]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _witness(members, splits, adjacency, edge_cap):
|
|
85
|
+
"""Shortest path to smallest differently assigned ID, lexical BFS ties."""
|
|
86
|
+
start = members[0]
|
|
87
|
+
end = next(key for key in members if splits[key] != splits[start])
|
|
88
|
+
queue = deque([start])
|
|
89
|
+
previous = {start: None}
|
|
90
|
+
while queue:
|
|
91
|
+
key = queue.popleft()
|
|
92
|
+
if key == end:
|
|
93
|
+
break
|
|
94
|
+
for neighbor, relation in sorted(adjacency[key]):
|
|
95
|
+
if neighbor not in previous:
|
|
96
|
+
previous[neighbor] = (key, relation)
|
|
97
|
+
queue.append(neighbor)
|
|
98
|
+
hops = 0
|
|
99
|
+
key = end
|
|
100
|
+
while key != start:
|
|
101
|
+
key = previous[key][0]
|
|
102
|
+
hops += 1
|
|
103
|
+
path = None
|
|
104
|
+
if hops <= edge_cap:
|
|
105
|
+
path = []
|
|
106
|
+
key = end
|
|
107
|
+
while key != start:
|
|
108
|
+
before, relation = previous[key]
|
|
109
|
+
path.append({"left_id": before, "right_id": key, "relation": relation})
|
|
110
|
+
key = before
|
|
111
|
+
path.reverse()
|
|
112
|
+
return {
|
|
113
|
+
"start_id": start,
|
|
114
|
+
"start_split": splits[start],
|
|
115
|
+
"end_id": end,
|
|
116
|
+
"end_split": splits[end],
|
|
117
|
+
"hops": hops,
|
|
118
|
+
"path_omitted": hops > edge_cap,
|
|
119
|
+
"path": path,
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def audit(records_path, links_path, *, examples=0, max_witness_edges=20, limits=None):
|
|
124
|
+
"""Return a complete JSON-ready report or raise AuditError.
|
|
125
|
+
|
|
126
|
+
Links assert that endpoints must share a partition. All links participate;
|
|
127
|
+
relation strings label evidence and do not select or weaken constraints.
|
|
128
|
+
"""
|
|
129
|
+
_integer("examples", examples, 0)
|
|
130
|
+
_integer("max_witness_edges", max_witness_edges, 0)
|
|
131
|
+
if limits is None:
|
|
132
|
+
limits = Limits()
|
|
133
|
+
if type(limits) is not Limits:
|
|
134
|
+
raise AuditError("limits must be a Limits instance")
|
|
135
|
+
rows, records_receipt = _rows(
|
|
136
|
+
records_path, ["id", "split"], "records", limits, limits.max_records
|
|
137
|
+
)
|
|
138
|
+
if not rows:
|
|
139
|
+
raise AuditError("records: at least one record is required")
|
|
140
|
+
splits = {}
|
|
141
|
+
for number, (key, split) in enumerate(rows, 2):
|
|
142
|
+
if key in splits:
|
|
143
|
+
raise AuditError(f"records: duplicate id at record {number}")
|
|
144
|
+
splits[key] = split
|
|
145
|
+
del rows
|
|
146
|
+
split_totals = Counter(splits.values())
|
|
147
|
+
if len(split_totals) > limits.max_splits:
|
|
148
|
+
raise AuditError("records: split limit exceeded")
|
|
149
|
+
rows, links_receipt = _rows(
|
|
150
|
+
links_path,
|
|
151
|
+
["left_id", "right_id", "relation"],
|
|
152
|
+
"links",
|
|
153
|
+
limits,
|
|
154
|
+
limits.max_links,
|
|
155
|
+
)
|
|
156
|
+
groups = _Groups(splits)
|
|
157
|
+
seen = set()
|
|
158
|
+
adjacency = defaultdict(list) if examples else None
|
|
159
|
+
incident = set()
|
|
160
|
+
crossing_links = 0
|
|
161
|
+
for number, (left, right, relation) in enumerate(rows, 2):
|
|
162
|
+
if left not in splits or right not in splits:
|
|
163
|
+
raise AuditError(f"links: unknown endpoint at record {number}")
|
|
164
|
+
edge = (*sorted((left, right)), relation)
|
|
165
|
+
if edge in seen:
|
|
166
|
+
raise AuditError(f"links: duplicate undirected link at record {number}")
|
|
167
|
+
seen.add(edge)
|
|
168
|
+
groups.join(left, right)
|
|
169
|
+
incident.update((left, right))
|
|
170
|
+
if adjacency is not None:
|
|
171
|
+
adjacency[left].append((right, relation))
|
|
172
|
+
adjacency[right].append((left, relation))
|
|
173
|
+
crossing_links += splits[left] != splits[right]
|
|
174
|
+
link_count = len(rows)
|
|
175
|
+
del rows, seen
|
|
176
|
+
components = defaultdict(list)
|
|
177
|
+
for key in sorted(splits):
|
|
178
|
+
components[groups.find(key)].append(key)
|
|
179
|
+
affected = Counter()
|
|
180
|
+
bad = []
|
|
181
|
+
cross_pairs = 0
|
|
182
|
+
for members in components.values():
|
|
183
|
+
counts = Counter(splits[key] for key in members)
|
|
184
|
+
if len(counts) > 1:
|
|
185
|
+
affected.update(counts)
|
|
186
|
+
bad.append((members, counts))
|
|
187
|
+
cross_pairs += (
|
|
188
|
+
len(members) ** 2 - sum(n * n for n in counts.values())
|
|
189
|
+
) // 2
|
|
190
|
+
bad.sort(key=lambda item: item[0][0])
|
|
191
|
+
samples = []
|
|
192
|
+
for members, counts in bad[:examples]:
|
|
193
|
+
samples.append(
|
|
194
|
+
{
|
|
195
|
+
"component_id": members[0],
|
|
196
|
+
"records": len(members),
|
|
197
|
+
"split_counts": dict(sorted(counts.items())),
|
|
198
|
+
"witness": _witness(members, splits, adjacency, max_witness_edges),
|
|
199
|
+
}
|
|
200
|
+
)
|
|
201
|
+
return {
|
|
202
|
+
"schema_version": 1,
|
|
203
|
+
"passed": not bad,
|
|
204
|
+
"policy": "all_declared_links_must_stay_within_one_split",
|
|
205
|
+
"counts": {
|
|
206
|
+
"records": len(splits),
|
|
207
|
+
"links": link_count,
|
|
208
|
+
"components": len(components),
|
|
209
|
+
"isolated_records": len(splits) - len(incident),
|
|
210
|
+
"violating_components": len(bad),
|
|
211
|
+
"affected_records": sum(affected.values()),
|
|
212
|
+
"crossing_links": crossing_links,
|
|
213
|
+
"cross_split_record_pairs": cross_pairs,
|
|
214
|
+
},
|
|
215
|
+
"splits": {
|
|
216
|
+
split: {"records": split_totals[split], "affected_records": affected[split]}
|
|
217
|
+
for split in sorted(split_totals)
|
|
218
|
+
},
|
|
219
|
+
"examples": samples,
|
|
220
|
+
"examples_omitted": len(bad) - len(samples),
|
|
221
|
+
"settings": {
|
|
222
|
+
"examples": examples,
|
|
223
|
+
"max_witness_edges": max_witness_edges,
|
|
224
|
+
"limits": dict(vars(limits)),
|
|
225
|
+
},
|
|
226
|
+
"inputs": {"records": records_receipt, "links": links_receipt},
|
|
227
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Audit long-form namespaced group memberships without expanding cliques."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter, defaultdict, deque
|
|
4
|
+
|
|
5
|
+
from .core import AuditError, Limits, _Groups, _integer, _rows
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _path(start, end, by_record, by_group, cap):
|
|
9
|
+
# A bipartite BFS: each group is expanded at most once. Sorting both sides
|
|
10
|
+
# chooses a reproducible shortest path in number of group-sharing hops.
|
|
11
|
+
queue = deque([start])
|
|
12
|
+
previous = {start: None}
|
|
13
|
+
expanded = set()
|
|
14
|
+
while queue:
|
|
15
|
+
current = queue.popleft()
|
|
16
|
+
if current == end:
|
|
17
|
+
break
|
|
18
|
+
for group in sorted(by_record[current]):
|
|
19
|
+
if group in expanded:
|
|
20
|
+
continue
|
|
21
|
+
expanded.add(group)
|
|
22
|
+
for neighbor in sorted(by_group[group]):
|
|
23
|
+
if neighbor not in previous:
|
|
24
|
+
previous[neighbor] = (current, group)
|
|
25
|
+
queue.append(neighbor)
|
|
26
|
+
hops = 0
|
|
27
|
+
current = end
|
|
28
|
+
while current != start:
|
|
29
|
+
current = previous[current][0]
|
|
30
|
+
hops += 1
|
|
31
|
+
path = None
|
|
32
|
+
if hops <= cap:
|
|
33
|
+
current = end
|
|
34
|
+
path = []
|
|
35
|
+
while current != start:
|
|
36
|
+
before, (namespace, group_id) = previous[current]
|
|
37
|
+
path.append(
|
|
38
|
+
{
|
|
39
|
+
"left_id": before,
|
|
40
|
+
"right_id": current,
|
|
41
|
+
"namespace": namespace,
|
|
42
|
+
"group_id": group_id,
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
current = before
|
|
46
|
+
path.reverse()
|
|
47
|
+
return {
|
|
48
|
+
"start_id": start,
|
|
49
|
+
"end_id": end,
|
|
50
|
+
"hops": hops,
|
|
51
|
+
"path_omitted": hops > cap,
|
|
52
|
+
"path": path,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def audit_memberships(
|
|
57
|
+
records_path, memberships_path, *, examples=0, max_witness_edges=20, limits=None
|
|
58
|
+
):
|
|
59
|
+
"""Check every assigned record's declared groups stay within one split.
|
|
60
|
+
|
|
61
|
+
All records must have at least one membership, including otherwise isolated
|
|
62
|
+
singleton records. A group is the exact tuple (namespace, group_id).
|
|
63
|
+
max_links caps membership rows in this mode, not generated graph edges.
|
|
64
|
+
"""
|
|
65
|
+
_integer("examples", examples, 0)
|
|
66
|
+
_integer("max_witness_edges", max_witness_edges, 0)
|
|
67
|
+
if limits is None:
|
|
68
|
+
limits = Limits()
|
|
69
|
+
if type(limits) is not Limits:
|
|
70
|
+
raise AuditError("limits must be a Limits instance")
|
|
71
|
+
records, receipt = _rows(
|
|
72
|
+
records_path, ["id", "split"], "records", limits, limits.max_records
|
|
73
|
+
)
|
|
74
|
+
if not records:
|
|
75
|
+
raise AuditError("records: at least one record is required")
|
|
76
|
+
splits = {}
|
|
77
|
+
for number, (key, split) in enumerate(records, 2):
|
|
78
|
+
if key in splits:
|
|
79
|
+
raise AuditError(f"records: duplicate id at record {number}")
|
|
80
|
+
splits[key] = split
|
|
81
|
+
del records
|
|
82
|
+
totals = Counter(splits.values())
|
|
83
|
+
if len(totals) > limits.max_splits:
|
|
84
|
+
raise AuditError("records: split limit exceeded")
|
|
85
|
+
rows, membership_receipt = _rows(
|
|
86
|
+
memberships_path,
|
|
87
|
+
["record_id", "namespace", "group_id"],
|
|
88
|
+
"memberships",
|
|
89
|
+
limits,
|
|
90
|
+
limits.max_links,
|
|
91
|
+
)
|
|
92
|
+
by_record = defaultdict(set) if examples else None
|
|
93
|
+
by_group = defaultdict(set)
|
|
94
|
+
covered = set()
|
|
95
|
+
for number, (key, namespace, group_id) in enumerate(rows, 2):
|
|
96
|
+
if key not in splits:
|
|
97
|
+
raise AuditError(f"memberships: unknown record at record {number}")
|
|
98
|
+
group = (namespace, group_id)
|
|
99
|
+
if key in by_group[group]:
|
|
100
|
+
raise AuditError(f"memberships: duplicate membership at record {number}")
|
|
101
|
+
if by_record is not None:
|
|
102
|
+
by_record[key].add(group)
|
|
103
|
+
by_group[group].add(key)
|
|
104
|
+
covered.add(key)
|
|
105
|
+
count = len(rows)
|
|
106
|
+
del rows
|
|
107
|
+
if len(covered) != len(splits):
|
|
108
|
+
raise AuditError("memberships: every assigned record needs a membership")
|
|
109
|
+
del covered
|
|
110
|
+
groups = _Groups(splits)
|
|
111
|
+
violating_groups = 0
|
|
112
|
+
for members in by_group.values():
|
|
113
|
+
representative = next(iter(members))
|
|
114
|
+
for key in members:
|
|
115
|
+
groups.join(representative, key)
|
|
116
|
+
violating_groups += len({splits[key] for key in members}) > 1
|
|
117
|
+
components = defaultdict(list)
|
|
118
|
+
for key in sorted(splits):
|
|
119
|
+
components[groups.find(key)].append(key)
|
|
120
|
+
affected = Counter()
|
|
121
|
+
violations = []
|
|
122
|
+
pairs = 0
|
|
123
|
+
for members in components.values():
|
|
124
|
+
counts = Counter(splits[key] for key in members)
|
|
125
|
+
if len(counts) > 1:
|
|
126
|
+
affected.update(counts)
|
|
127
|
+
violations.append((members, counts))
|
|
128
|
+
pairs += (len(members) ** 2 - sum(n * n for n in counts.values())) // 2
|
|
129
|
+
violations.sort(key=lambda item: item[0][0])
|
|
130
|
+
samples = []
|
|
131
|
+
for members, counts in violations[:examples]:
|
|
132
|
+
start = members[0]
|
|
133
|
+
end = next(key for key in members if splits[key] != splits[start])
|
|
134
|
+
witness = _path(start, end, by_record, by_group, max_witness_edges)
|
|
135
|
+
witness.update(start_split=splits[start], end_split=splits[end])
|
|
136
|
+
samples.append(
|
|
137
|
+
{
|
|
138
|
+
"component_id": start,
|
|
139
|
+
"records": len(members),
|
|
140
|
+
"split_counts": dict(sorted(counts.items())),
|
|
141
|
+
"witness": witness,
|
|
142
|
+
}
|
|
143
|
+
)
|
|
144
|
+
return {
|
|
145
|
+
"schema_version": 1,
|
|
146
|
+
"mode": "memberships",
|
|
147
|
+
"policy": "all_declared_groups_must_stay_within_one_split",
|
|
148
|
+
"passed": not violations,
|
|
149
|
+
"counts": {
|
|
150
|
+
"records": len(splits),
|
|
151
|
+
"memberships": count,
|
|
152
|
+
"groups": len(by_group),
|
|
153
|
+
"components": len(components),
|
|
154
|
+
"singleton_components": sum(len(m) == 1 for m in components.values()),
|
|
155
|
+
"cross_split_groups": violating_groups,
|
|
156
|
+
"violating_components": len(violations),
|
|
157
|
+
"affected_records": sum(affected.values()),
|
|
158
|
+
"cross_split_record_pairs": pairs,
|
|
159
|
+
},
|
|
160
|
+
"splits": {
|
|
161
|
+
s: {"records": totals[s], "affected_records": affected[s]}
|
|
162
|
+
for s in sorted(totals)
|
|
163
|
+
},
|
|
164
|
+
"examples": samples,
|
|
165
|
+
"examples_omitted": len(violations) - len(samples),
|
|
166
|
+
"settings": {
|
|
167
|
+
"examples": examples,
|
|
168
|
+
"max_witness_edges": max_witness_edges,
|
|
169
|
+
"limits": dict(vars(limits)),
|
|
170
|
+
},
|
|
171
|
+
"inputs": {"records": receipt, "memberships": membership_receipt},
|
|
172
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: splitwitness
|
|
3
|
+
Version: 0.2.2
|
|
4
|
+
Summary: Offline transitive split-constraint audits with bounded witness paths
|
|
5
|
+
Author: Anish Pentyala
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/anishpentyala/splitwitness
|
|
8
|
+
Project-URL: Repository, https://github.com/anishpentyala/splitwitness
|
|
9
|
+
Project-URL: Issues, https://github.com/anishpentyala/splitwitness/issues
|
|
10
|
+
Keywords: machine-learning,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
|
+
# splitwitness
|
|
17
|
+
|
|
18
|
+
[](https://github.com/anishpentyala/splitwitness/actions)
|
|
19
|
+
|
|
20
|
+
Audit an existing train/validation/test assignment against explicit links that
|
|
21
|
+
must stay in one partition. Get exact component counts and optional short,
|
|
22
|
+
reproducible evidence paths. Runs offline, with Python's standard library.
|
|
23
|
+
|
|
24
|
+
## Quickstart
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
python -m pip install "git+https://github.com/anishpentyala/splitwitness.git"
|
|
28
|
+
cat > records.csv <<'CSV'
|
|
29
|
+
id,split
|
|
30
|
+
a,train
|
|
31
|
+
b,train
|
|
32
|
+
c,test
|
|
33
|
+
CSV
|
|
34
|
+
cat > links.csv <<'CSV'
|
|
35
|
+
left_id,right_id,relation
|
|
36
|
+
a,b,same-person
|
|
37
|
+
b,c,duplicate-export
|
|
38
|
+
CSV
|
|
39
|
+
splitwitness records.csv links.csv --examples 1
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
This exits 1: all three records belong to one component spanning train and test.
|
|
43
|
+
Only one link crosses directly, but two unordered cross-split record pairs are
|
|
44
|
+
connected. Checking the grouping columns independently would miss the transitive
|
|
45
|
+
relationship. The report checks only the links you supplied, not identity,
|
|
46
|
+
statistical independence or all possible leakage.
|
|
47
|
+
|
|
48
|
+
A PyPI release is being prepared. Until its package page is linked here, use the
|
|
49
|
+
source-install command above.
|
|
50
|
+
|
|
51
|
+
A duplicate export can connect two patient groups even when the patient IDs do
|
|
52
|
+
not overlap. Checking each grouping column separately misses the full affected
|
|
53
|
+
family. splitwitness follows all supplied links transitively, reports the whole
|
|
54
|
+
connected component and counts each affected record once.
|
|
55
|
+
|
|
56
|
+
This is a constraint checker, not an identity detector or an independence test.
|
|
57
|
+
The caller decides which relationships should prohibit crossing a split. A clean
|
|
58
|
+
report only says those **declared** links stayed within partitions. It says
|
|
59
|
+
nothing about missing links, false identity claims, model quality, statistical
|
|
60
|
+
independence, temporal leakage, feature leakage or contamination from pretraining.
|
|
61
|
+
|
|
62
|
+
## Install and run
|
|
63
|
+
|
|
64
|
+
Python 3.9 or newer. From a copy of this source tree:
|
|
65
|
+
|
|
66
|
+
```sh
|
|
67
|
+
python -m pip install .
|
|
68
|
+
splitwitness examples/records.csv examples/links.csv --examples 2
|
|
69
|
+
# exits 1: a complete report found a violated constraint
|
|
70
|
+
splitwitness examples/records.csv examples/clean-links.csv
|
|
71
|
+
# exits 0: all supplied constraints satisfied
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The first example has five records in two connected components. Four records
|
|
75
|
+
belong to a component spanning train and test. Only one input link crosses the
|
|
76
|
+
boundary, but all four records are affected. There are four unordered cross-split
|
|
77
|
+
record pairs in that component. The fifth record is isolated and not affected.
|
|
78
|
+
The example witness goes from photo-001 to photo-003 in two hops, through
|
|
79
|
+
same-patient and duplicate-export links.
|
|
80
|
+
|
|
81
|
+
## Group inventories
|
|
82
|
+
|
|
83
|
+
Opt-in `--memberships` accepts complete namespaced group inventories instead of
|
|
84
|
+
explicit link pairs, without expanding each group into a quadratic clique.
|
|
85
|
+
See [MEMBERSHIPS.md](MEMBERSHIPS.md) for its separate counts, shortest group-hop
|
|
86
|
+
witnesses and additional disclosure of group IDs in opt-in examples. Link mode
|
|
87
|
+
and its report stay unchanged.
|
|
88
|
+
|
|
89
|
+
## Manifests
|
|
90
|
+
|
|
91
|
+
`records.csv`, with this exact ordered header:
|
|
92
|
+
|
|
93
|
+
```csv
|
|
94
|
+
id,split
|
|
95
|
+
photo-001,train
|
|
96
|
+
photo-002,train
|
|
97
|
+
photo-003,test
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`links.csv`, with this exact ordered header:
|
|
101
|
+
|
|
102
|
+
```csv
|
|
103
|
+
left_id,right_id,relation
|
|
104
|
+
photo-001,photo-002,same-patient
|
|
105
|
+
photo-002,photo-003,duplicate-export
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
- Every record has exactly one assignment. Empty record manifests and duplicate
|
|
109
|
+
IDs are errors, including repeated IDs with the same split.
|
|
110
|
+
- Every endpoint must exist in records. Unknown endpoints fail the entire audit.
|
|
111
|
+
- Links are undirected co-location constraints. Every relation participates.
|
|
112
|
+
Labels are descriptive, not trusted provenance, confidence scores or filters.
|
|
113
|
+
A low-confidence match should be reviewed before including it.
|
|
114
|
+
- Reverse duplicates with the same relation are errors. Different relations on
|
|
115
|
+
the same pair are allowed and counted as separate input links, not extra
|
|
116
|
+
record pairs. Self-links are allowed, redundant constraints.
|
|
117
|
+
- Header-only links are valid: all records are isolated. This does not verify
|
|
118
|
+
that the caller supplied a complete relationship inventory.
|
|
119
|
+
- IDs, splits and relations are exact nonempty strings. No trimming, numeric
|
|
120
|
+
conversion, case folding, whitespace collapse or Unicode normalization occurs.
|
|
121
|
+
`01`, `1`, ` a` and `a` are distinct. Even whitespace-only fields are strings.
|
|
122
|
+
- UTF-8, comma-separated CSV with Python `csv.reader(strict=True)` semantics.
|
|
123
|
+
Quoted commas, quotes and newlines work. NUL, BOM-prefixed headers, blank data
|
|
124
|
+
records, wrong headers, ragged records and invalid UTF-8 fail. This is not a
|
|
125
|
+
promise to implement every RFC interpretation; Python accepts bare quotes in
|
|
126
|
+
some unquoted fields. The process's native CSV field cap is an additional
|
|
127
|
+
parser bound and is not changed by this library.
|
|
128
|
+
|
|
129
|
+
## Report and exit codes
|
|
130
|
+
|
|
131
|
+
The CLI writes one complete JSON report to stdout after both manifests pass
|
|
132
|
+
validation. It never edits inputs, repairs splits, trains models, downloads data
|
|
133
|
+
or executes relation labels.
|
|
134
|
+
|
|
135
|
+
- `0`: complete audit, constraints satisfied.
|
|
136
|
+
- `1`: complete audit, at least one connected component spans splits.
|
|
137
|
+
- `2`: audit incomplete, invalid invocation/input/resource cap, or broken output
|
|
138
|
+
pipe. Validation failures emit a diagnostic on stderr and **no JSON**.
|
|
139
|
+
|
|
140
|
+
`counts` includes records, accepted links, connected components, isolated records
|
|
141
|
+
(no incident link, so a self-linked record is not isolated), violating components,
|
|
142
|
+
affected records, direct crossing links, and unordered cross-split record pairs
|
|
143
|
+
within components. All counts cover the full validated inputs, not a sample.
|
|
144
|
+
`cross_split_record_pairs` counts connected pairs in different splits, whether or
|
|
145
|
+
not they share a direct link. It is a constraint exposure count, not a measure of
|
|
146
|
+
leakage probability or model-score inflation. `splits` gives total and affected
|
|
147
|
+
records for each exact split label. No train/test semantics are assumed.
|
|
148
|
+
|
|
149
|
+
Examples default to zero. `--examples N` selects the first N violating components
|
|
150
|
+
by their smallest record ID (Python Unicode code-point ordering). An example has
|
|
151
|
+
that ID, component size, split counts, and one witness. The witness starts at the
|
|
152
|
+
smallest component ID and ends at the smallest ID in a different split. It is a
|
|
153
|
+
shortest path **between those chosen endpoints**, not the closest cross-split
|
|
154
|
+
pair. Breadth-first search visits neighbor-ID/relation pairs in sorted order to
|
|
155
|
+
break ties. Input order, edge orientation and union-find root choice do not change
|
|
156
|
+
semantic results.
|
|
157
|
+
|
|
158
|
+
`--max-witness-edges N` defaults to 20. A longer path is omitted entirely, with
|
|
159
|
+
`path: null`, `path_omitted: true` and its exact hop count. It is not presented as
|
|
160
|
+
a clipped proof. This bounds report evidence size, not traversal cost. The predecessor chain is
|
|
161
|
+
counted before edge dictionaries are built; an omitted path does not allocate
|
|
162
|
+
those dictionaries. Breadth-first search still retains its queue and predecessor
|
|
163
|
+
map, and graph storage remains in memory. A retained path is walked a second time
|
|
164
|
+
to build its evidence. This is not a hard RAM bound or a general speed claim.
|
|
165
|
+
Increasing examples or the path limit can expose more identifiers and make
|
|
166
|
+
reports large.
|
|
167
|
+
|
|
168
|
+
`inputs` contains SHA-256 and byte counts of the exact bytes parsed from each
|
|
169
|
+
file, including headers/newlines. Permuting equivalent CSV changes the receipts,
|
|
170
|
+
not the semantic counts or witness selection. Digests are not signatures and do
|
|
171
|
+
not authenticate provenance, completeness or an immutable simultaneous snapshot
|
|
172
|
+
of both files. Each input is read once, sequentially.
|
|
173
|
+
|
|
174
|
+
## Limits and privacy
|
|
175
|
+
|
|
176
|
+
Acceptance caps are configurable with `--max-bytes` (per file, default 16 MiB),
|
|
177
|
+
`--max-records` (100,000), `--max-links` (500,000), `--max-field-chars` (1,024 per
|
|
178
|
+
field) and `--max-splits` (100). Positive integers only; examples and witness-edge
|
|
179
|
+
caps also allow zero. Caps fail closed; nothing is silently clipped or skipped.
|
|
180
|
+
An empty links file still needs the header. A single populated split is accepted.
|
|
181
|
+
|
|
182
|
+
The graph, CSV bytes and parsed strings live in process memory. This is not a
|
|
183
|
+
streaming/disk-backed implementation and caps are **not** hard RAM or runtime
|
|
184
|
+
bounds. Memory use is O(input bytes + records + links); retained graph adjacency
|
|
185
|
+
includes both orientations. Sorting and witness searches add work. Each sampled
|
|
186
|
+
component is searched separately. Membership mode has its own incidence-graph
|
|
187
|
+
costs described in MEMBERSHIPS.md. Avoid untrusted device/FIFO paths or files that
|
|
188
|
+
may block indefinitely. There is no timeout or sandbox for filesystem reads.
|
|
189
|
+
|
|
190
|
+
No network calls, telemetry, persistent cache or scratch database. No payload
|
|
191
|
+
columns are accepted. Still, identifiers, split labels and relationships can be
|
|
192
|
+
sensitive. Default reports include split labels, counts and input digests;
|
|
193
|
+
opt-in examples include record IDs and relation labels. Library exceptions and
|
|
194
|
+
CLI diagnostics identify input roles and record numbers, not field values or
|
|
195
|
+
paths. Python tracebacks from misuse are not a private reporting channel. Do not
|
|
196
|
+
share reports without checking them. There is no secure memory erasure guarantee.
|
|
197
|
+
|
|
198
|
+
One erroneous edge can connect large unrelated families. The report proves only
|
|
199
|
+
reachability under the declared undirected constraints, not real-world identity.
|
|
200
|
+
Do not automatically repair data or move evaluation rows based on this output.
|
|
201
|
+
|
|
202
|
+
## Python API
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
from splitwitness import AuditError, Limits, audit
|
|
206
|
+
|
|
207
|
+
try:
|
|
208
|
+
report = audit("records.csv", "links.csv", examples=2,
|
|
209
|
+
max_witness_edges=10,
|
|
210
|
+
limits=Limits(max_records=50_000))
|
|
211
|
+
except AuditError as error:
|
|
212
|
+
print(error) # incomplete, not a clean audit
|
|
213
|
+
else:
|
|
214
|
+
assert report["passed"], report["counts"]
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
`audit` returns a JSON-ready dictionary or raises `AuditError` for invalid
|
|
218
|
+
manifests/options or ordinary filesystem/parser failures. It expects filesystem
|
|
219
|
+
paths. Programming errors, interruptions and process memory exhaustion may still
|
|
220
|
+
raise their normal exceptions. The CLI catches memory exhaustion before JSON
|
|
221
|
+
serialization completes; an OS kill cannot be caught. Output I/O failures are not
|
|
222
|
+
an atomic-output guarantee: a consumer can receive a partial write if the pipe or
|
|
223
|
+
filesystem fails while stdout is being written.
|
|
224
|
+
|
|
225
|
+
## Development
|
|
226
|
+
|
|
227
|
+
```sh
|
|
228
|
+
python -m unittest discover -s tests -v # after install, or PYTHONPATH=src
|
|
229
|
+
ruff check src tests
|
|
230
|
+
ruff format --check src tests
|
|
231
|
+
python -m build
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Tests include a separate set-expansion graph oracle and shuffled/orientation-
|
|
235
|
+
reversed inputs. See [DESIGN.md](DESIGN.md) for algorithms and [EVIDENCE.md](EVIDENCE.md)
|
|
236
|
+
for motivation and existing alternatives. This project does not claim a new graph
|
|
237
|
+
algorithm or unique leakage detection. Source install only; no registry release
|
|
238
|
+
or outside adoption is implied.
|
|
239
|
+
|
|
240
|
+
## Counts-only link storage (0.2.1)
|
|
241
|
+
|
|
242
|
+
In explicit-link mode, the default `examples=0` audit does not retain the
|
|
243
|
+
bidirectional adjacency entries used only for witness paths. A set of incident
|
|
244
|
+
record IDs still distinguishes a self-linked record from an isolated record.
|
|
245
|
+
All links still take part in duplicate/endpoint validation, union-find grouping,
|
|
246
|
+
crossing-link counts, transitive violations and pair counts. This does not skip
|
|
247
|
+
constraint checks or return a partial audit.
|
|
248
|
+
|
|
249
|
+
Requesting any examples retains witness adjacency as before, even when the
|
|
250
|
+
path-output cap is zero. Membership-mode storage is unchanged. Parsed CSV rows,
|
|
251
|
+
undirected-link duplicate detection, component members and other report state
|
|
252
|
+
still consume memory; this is not streaming input or a hard RAM/time bound.
|
|
253
|
+
Actual memory and time depend on graph shape and requested evidence, so no
|
|
254
|
+
portable reduction or speedup is promised.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
splitwitness/__init__.py,sha256=enb9uMigrFTLLMHhr8InOIGoG6ak53qwNS-aRB4M2fA,235
|
|
2
|
+
splitwitness/__main__.py,sha256=yXxytC8n9ckv2rmN27W5thMd_jdibmRY53NjEFGbbh8,1860
|
|
3
|
+
splitwitness/core.py,sha256=qH63vBqcSEawh3XsdAJgUAo1aQidiLePr4GUkU-HVTE,8026
|
|
4
|
+
splitwitness/memberships.py,sha256=3gFtj7alm3sxiXUXrKLKaSuWtoCtMghkEGRx0EqloFk,6255
|
|
5
|
+
splitwitness-0.2.2.dist-info/licenses/LICENSE,sha256=5yembAmR4hjWu7NOBFMDqvjvtnM8Ta_OGaPrAsVcI-I,1071
|
|
6
|
+
splitwitness-0.2.2.dist-info/METADATA,sha256=Z3khD2UnV0mTfcL1gUrmXX7pfvy9-yYOAcijYn6ww8w,12215
|
|
7
|
+
splitwitness-0.2.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
splitwitness-0.2.2.dist-info/entry_points.txt,sha256=zgHuipnWv3PUE1QwBC1ljTEGsMEcWqEAV6Z9DvLa-Q0,60
|
|
9
|
+
splitwitness-0.2.2.dist-info/top_level.txt,sha256=1cVIFYETMIr5pyZrlanZjqL7QncXbdGufH7PN39br0s,13
|
|
10
|
+
splitwitness-0.2.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
|
+
splitwitness
|