joinforecast 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.
@@ -0,0 +1,231 @@
1
+ """Exact equality-join row forecasts from CSV key frequencies."""
2
+
3
+ import csv
4
+ import heapq
5
+ from collections import Counter
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ __version__ = "0.2.2"
11
+
12
+
13
+ class InputError(ValueError):
14
+ """Input could not be completely and unambiguously analyzed."""
15
+
16
+
17
+ @dataclass
18
+ class Profile:
19
+ counts: Mapping
20
+ rows: int
21
+ null_rows: int
22
+ columns: tuple
23
+
24
+
25
+ def read_csv(
26
+ path, columns, *, null_values=("",), delimiter=",", max_rows=10000000, max_keys=1000000
27
+ ):
28
+ """Read selected keys as exact strings; no trimming or type inference.
29
+
30
+ Empty fields are null by default. Configure null_values explicitly to match
31
+ the intended loader. Reject malformed or incomplete input, never sample.
32
+ """
33
+ return _read_csv(path, columns, Counter(), null_values, delimiter, max_rows, max_keys)
34
+
35
+
36
+ def _read_csv(path, columns, counts, null_values, delimiter, max_rows, max_keys, *, increment=None):
37
+ """Shared complete-input parser; counts may be a disk-backed mapping."""
38
+ columns = tuple(columns)
39
+ if not columns or len(set(columns)) != len(columns):
40
+ raise InputError("Key columns must be nonempty and distinct")
41
+ if len(delimiter) != 1 or delimiter in "\r\n\0":
42
+ raise InputError("Delimiter must be one non-newline character")
43
+ if any(isinstance(n, bool) or not isinstance(n, int) or n < 0 for n in (max_rows, max_keys)):
44
+ raise InputError("Resource limits must be nonnegative")
45
+ null_values = frozenset(null_values)
46
+ rows = null_rows = 0
47
+ try:
48
+ with Path(path).open(encoding="utf-8-sig", newline="") as stream:
49
+ reader = csv.reader(stream, delimiter=delimiter, strict=True)
50
+ header = next(reader, None)
51
+ if not header or any(not name for name in header):
52
+ raise InputError("CSV needs a nonempty header with no blank column names")
53
+ if len(set(header)) != len(header):
54
+ raise InputError("Duplicate CSV column names")
55
+ missing = [name for name in columns if name not in header]
56
+ if missing:
57
+ raise InputError("Missing key columns: " + ", ".join(missing))
58
+ positions = [header.index(name) for name in columns]
59
+ for row in reader:
60
+ if len(row) != len(header):
61
+ raise InputError("Ragged row ending at line %d" % reader.line_num)
62
+ rows += 1
63
+ if rows > max_rows:
64
+ raise InputError("Row limit exceeded; no complete forecast available")
65
+ key = tuple(None if row[i] in null_values else row[i] for i in positions)
66
+ if None in key:
67
+ null_rows += 1
68
+ if increment is None:
69
+ counts[key] = counts.get(key, 0) + 1
70
+ else:
71
+ increment(key)
72
+ if len(counts) > max_keys:
73
+ raise InputError("Distinct-key limit exceeded; no complete forecast available")
74
+ except (OSError, UnicodeError, csv.Error) as error:
75
+ raise InputError(str(error)) from error
76
+ return Profile(counts, rows, null_rows, columns)
77
+
78
+
79
+ def _profile_shape(profile):
80
+ if (
81
+ not isinstance(profile, Profile)
82
+ or not profile.columns
83
+ or len(set(profile.columns)) != len(profile.columns)
84
+ or any(not isinstance(name, str) or not name for name in profile.columns)
85
+ or any(
86
+ isinstance(n, bool) or not isinstance(n, int) or n < 0
87
+ for n in (profile.rows, profile.null_rows)
88
+ )
89
+ ):
90
+ raise InputError("Expected a Profile with key columns")
91
+
92
+
93
+ def _validated_items(profile):
94
+ rows = null_rows = 0
95
+ for key, count in profile.counts.items():
96
+ if (
97
+ not isinstance(key, tuple)
98
+ or len(key) != len(profile.columns)
99
+ or any(value is not None and not isinstance(value, str) for value in key)
100
+ or isinstance(count, bool)
101
+ or not isinstance(count, int)
102
+ or count <= 0
103
+ ):
104
+ raise InputError("Invalid key frequency")
105
+ rows += count
106
+ if None in key:
107
+ null_rows += count
108
+ yield key, count
109
+ if rows != profile.rows or null_rows != profile.null_rows:
110
+ raise InputError("Profile row totals do not match key frequencies")
111
+
112
+
113
+ def forecast(
114
+ left,
115
+ right,
116
+ *,
117
+ nulls="never",
118
+ top=10,
119
+ expectation=None,
120
+ max_output_rows=None,
121
+ require_match="none",
122
+ ):
123
+ """Forecast equality joins without materializing the output.
124
+
125
+ nulls='never': any null component prevents a match (SQL equality).
126
+ nulls='match': corresponding null components compare equal. Not an implicit
127
+ pandas CSV-loader simulation: string parsing and null tokens remain explicit.
128
+ Uniqueness contracts apply to joinable keys, including unmatched keys.
129
+ """
130
+ _profile_shape(left)
131
+ _profile_shape(right)
132
+ if len(left.columns) != len(right.columns):
133
+ raise InputError("Left and right key arities differ")
134
+ if nulls not in ("never", "match"):
135
+ raise InputError("nulls must be never or match")
136
+ if isinstance(top, bool) or not isinstance(top, int) or top < 0:
137
+ raise InputError("top must be a nonnegative integer")
138
+ if expectation not in (None, "one-to-one", "one-to-many", "many-to-one", "many-to-many"):
139
+ raise InputError("Unknown cardinality expectation")
140
+ if require_match not in ("none", "left", "right", "both"):
141
+ raise InputError("Unknown match requirement")
142
+ if max_output_rows is not None and (
143
+ isinstance(max_output_rows, bool)
144
+ or not isinstance(max_output_rows, int)
145
+ or max_output_rows < 0
146
+ ):
147
+ raise InputError("Output row limit must be a nonnegative integer")
148
+
149
+ def joinable(key):
150
+ return nulls == "match" or None not in key
151
+
152
+ inner = matched_left = matched_right = shared = many_many = 0
153
+ duplicate_left = 0
154
+ largest_heap = []
155
+ duplicate_right = sum(1 for k, n in _validated_items(right) if n > 1 and joinable(k))
156
+ for ordinal, (key, ln) in enumerate(_validated_items(left)):
157
+ duplicate_left += ln > 1 and joinable(key)
158
+ rn = right.counts.get(key, 0) if joinable(key) else 0
159
+ if rn:
160
+ inner += ln * rn
161
+ matched_left += ln
162
+ matched_right += rn
163
+ shared += 1
164
+ many_many += ln > 1 and rn > 1
165
+ if top:
166
+ # Earlier left first-seen keys win equal-contribution ties.
167
+ # Unique ordinal precedes the key, so mixed None/string values
168
+ # are never compared by the heap.
169
+ entry = (ln * rn, -ordinal, ln, rn, key)
170
+ if len(largest_heap) < top:
171
+ heapq.heappush(largest_heap, entry)
172
+ elif entry > largest_heap[0]:
173
+ heapq.heapreplace(largest_heap, entry)
174
+ unmatched_left = left.rows - matched_left
175
+ unmatched_right = right.rows - matched_right
176
+ predictions = {
177
+ "inner": inner,
178
+ "left": inner + unmatched_left,
179
+ "right": inner + unmatched_right,
180
+ "full": inner + unmatched_left + unmatched_right,
181
+ "left_anti": unmatched_left,
182
+ "right_anti": unmatched_right,
183
+ }
184
+
185
+ largest = [
186
+ {
187
+ "key": list(key),
188
+ "left_rows": ln,
189
+ "right_rows": rn,
190
+ "joined_rows": product,
191
+ "many_to_many": ln > 1 and rn > 1,
192
+ }
193
+ for product, _, ln, rn, key in sorted(largest_heap, reverse=True)
194
+ ]
195
+ violations = []
196
+ if expectation in ("one-to-one", "one-to-many") and duplicate_left:
197
+ violations.append("Left joinable keys are not unique")
198
+ if expectation in ("one-to-one", "many-to-one") and duplicate_right:
199
+ violations.append("Right joinable keys are not unique")
200
+ if require_match in ("left", "both") and unmatched_left:
201
+ violations.append("Left rows have no match")
202
+ if require_match in ("right", "both") and unmatched_right:
203
+ violations.append("Right rows have no match")
204
+ if max_output_rows is not None:
205
+ # A cap applies to every reported materializing join, not anti joins.
206
+ for how in ("inner", "left", "right", "full"):
207
+ if predictions[how] > max_output_rows:
208
+ violations.append("%s join exceeds output row limit" % how)
209
+ return {
210
+ "schema_version": 1,
211
+ "nulls": nulls,
212
+ "left_rows": left.rows,
213
+ "right_rows": right.rows,
214
+ "left_null_rows": left.null_rows,
215
+ "right_null_rows": right.null_rows,
216
+ "left_key_columns": list(left.columns),
217
+ "right_key_columns": list(right.columns),
218
+ "shared_keys": shared,
219
+ "left_duplicate_joinable_keys": duplicate_left,
220
+ "right_duplicate_joinable_keys": duplicate_right,
221
+ "many_to_many_keys": many_many,
222
+ "matched_left_rows": matched_left,
223
+ "matched_right_rows": matched_right,
224
+ "predicted_rows": predictions,
225
+ "top_contributors": largest,
226
+ "expectation": expectation,
227
+ "require_match": require_match,
228
+ "max_output_rows": max_output_rows,
229
+ "violations": violations,
230
+ "ok": not violations,
231
+ }
@@ -0,0 +1,147 @@
1
+ """Command-line interface. JSON stdout, errors stderr, no input mutation."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from contextlib import ExitStack
7
+
8
+ from . import InputError, __version__, forecast, read_csv
9
+
10
+
11
+ def _write_text(stream, text):
12
+ if stream is None:
13
+ raise OSError("output stream is unavailable")
14
+ written = stream.write(text)
15
+ if type(written) is not int or written != len(text):
16
+ raise OSError("output stream did not accept complete text")
17
+ stream.flush()
18
+
19
+
20
+ _DEFAULT_DESTINATION = object()
21
+
22
+
23
+ class _ArgumentParser(argparse.ArgumentParser):
24
+ def _print_message(self, message, file=_DEFAULT_DESTINATION):
25
+ # New argparse versions can suppress immediate write errors.
26
+ if message:
27
+ _write_text(sys.stderr if file is _DEFAULT_DESTINATION else file, message)
28
+
29
+
30
+ def main(argv=None):
31
+ """Embedded entry point. Never close or replace caller streams."""
32
+ try:
33
+ return _main(argv)
34
+ except (OSError, ValueError) as error:
35
+ try:
36
+ _write_text(sys.stderr, "joinforecast: " + str(error) + "\n")
37
+ except (OSError, ValueError):
38
+ pass
39
+ return 2
40
+
41
+
42
+ def _main(argv=None):
43
+ parser = _ArgumentParser(
44
+ description="Forecast equality-join row counts without building the join."
45
+ )
46
+ parser.add_argument("--version", action="version", version=__version__)
47
+ parser.add_argument("left")
48
+ parser.add_argument("right")
49
+ parser.add_argument(
50
+ "--left-key", action="append", required=True, help="Repeat for composite keys"
51
+ )
52
+ parser.add_argument("--right-key", action="append", help="Defaults to left key names")
53
+ parser.add_argument("--nulls", choices=("never", "match"), default="never")
54
+ parser.add_argument(
55
+ "--null-value", action="append", help="Repeat; replaces default empty-field null token"
56
+ )
57
+ parser.add_argument("--delimiter", default=",")
58
+ parser.add_argument(
59
+ "--expect", choices=("one-to-one", "one-to-many", "many-to-one", "many-to-many")
60
+ )
61
+ parser.add_argument(
62
+ "--require-match", choices=("none", "left", "right", "both"), default="none"
63
+ )
64
+ parser.add_argument("--max-output-rows", type=int, help="Cap all four reported join sizes")
65
+ parser.add_argument(
66
+ "--max-input-rows", type=int, default=10000000, help="Per file; fail rather than sample"
67
+ )
68
+ parser.add_argument(
69
+ "--max-keys", type=int, default=1000000, help="Per file; fail rather than sample"
70
+ )
71
+ parser.add_argument("--top", type=int, default=10)
72
+ parser.add_argument(
73
+ "--storage",
74
+ choices=("memory", "sqlite"),
75
+ default="memory",
76
+ help="sqlite writes sensitive key values to private temporary disk",
77
+ )
78
+ parser.add_argument("--temp-dir", help="Parent directory for sqlite temporary profiles")
79
+ args = parser.parse_args(argv)
80
+ try:
81
+ options = dict(
82
+ null_values=args.null_value if args.null_value is not None else ("",),
83
+ delimiter=args.delimiter,
84
+ max_rows=args.max_input_rows,
85
+ max_keys=args.max_keys,
86
+ )
87
+ if args.temp_dir is not None and args.storage != "sqlite":
88
+ raise InputError("--temp-dir requires --storage sqlite")
89
+ with ExitStack() as stack:
90
+ if args.storage == "sqlite":
91
+ try:
92
+ from .disk import sqlite_csv
93
+ except ImportError as error:
94
+ raise InputError(
95
+ "SQLite backend is unavailable in this Python build"
96
+ ) from error
97
+
98
+ def load(path, columns):
99
+ return stack.enter_context(
100
+ sqlite_csv(path, columns, temp_dir=args.temp_dir, **options)
101
+ )
102
+ else:
103
+
104
+ def load(path, columns):
105
+ return read_csv(path, columns, **options)
106
+
107
+ left = load(args.left, args.left_key)
108
+ right = load(args.right, args.right_key or args.left_key)
109
+ result = forecast(
110
+ left,
111
+ right,
112
+ nulls=args.nulls,
113
+ top=args.top,
114
+ expectation=args.expect,
115
+ max_output_rows=args.max_output_rows,
116
+ require_match=args.require_match,
117
+ )
118
+ result["csv_null_values"] = list(options["null_values"])
119
+ result["delimiter"] = args.delimiter
120
+ except InputError as error:
121
+ _write_text(sys.stderr, "joinforecast: " + str(error) + "\n")
122
+ return 2
123
+ _write_text(sys.stdout, json.dumps(result, ensure_ascii=True, indent=2) + "\n")
124
+ return 0 if result["ok"] else 1
125
+
126
+
127
+ def cli(argv=None):
128
+ """Process-owned shutdown, shared by console and module launchers."""
129
+ try:
130
+ code = main(argv)
131
+ except SystemExit as error:
132
+ code = error.code
133
+ for name in ("stdout", "stderr"):
134
+ stream = getattr(sys, name)
135
+ if stream is None:
136
+ continue
137
+ try:
138
+ stream.flush()
139
+ except (OSError, ValueError):
140
+ # Avoid CPython shutdown retry replacing documented exit2 with120.
141
+ setattr(sys, name, None)
142
+ code = 2
143
+ return code
144
+
145
+
146
+ if __name__ == "__main__":
147
+ raise SystemExit(cli())
joinforecast/disk.py ADDED
@@ -0,0 +1,142 @@
1
+ """Opt-in private temporary-disk profiles; cleanup is not secure erasure."""
2
+
3
+ import json
4
+ import sqlite3
5
+ from collections.abc import Mapping
6
+ from contextlib import contextmanager
7
+ from pathlib import Path
8
+ from tempfile import TemporaryDirectory
9
+
10
+ from . import InputError, _read_csv
11
+
12
+
13
+ def _storage_call(operation, *args, **kwargs):
14
+ try:
15
+ return operation(*args, **kwargs)
16
+ except (OSError, sqlite3.Error) as error:
17
+ raise InputError("Temporary profile storage: " + str(error)) from error
18
+
19
+
20
+ class _DiskCounts(Mapping):
21
+ def __init__(self, connection):
22
+ self.connection = connection
23
+ self.size = 0
24
+ self.closed = False
25
+
26
+ def _execute(self, statement, parameters=()):
27
+ if self.closed:
28
+ raise InputError("Disk profile is closed; use it inside its context")
29
+ try:
30
+ return self.connection.execute(statement, parameters)
31
+ except sqlite3.Error as error:
32
+ raise InputError("Temporary profile storage: " + str(error)) from error
33
+
34
+ @staticmethod
35
+ def _encode(key):
36
+ # Canonical array encoding is injective over tuples of strings and None.
37
+ return json.dumps(key, ensure_ascii=True, separators=(",", ":"))
38
+
39
+ def __getitem__(self, key):
40
+ sentinel = object()
41
+ value = self.get(key, sentinel)
42
+ if value is sentinel:
43
+ raise KeyError(key)
44
+ return value
45
+
46
+ def __iter__(self):
47
+ for key, _ in self.items():
48
+ yield key
49
+
50
+ def get(self, key, default=None):
51
+ row = self._execute("SELECT n FROM counts WHERE key = ?", (self._encode(key),)).fetchone()
52
+ return row[0] if row is not None else default
53
+
54
+ def __setitem__(self, key, count):
55
+ encoded = self._encode(key)
56
+ cursor = self._execute(
57
+ "INSERT OR IGNORE INTO counts(key, n) VALUES (?, ?)", (encoded, count)
58
+ )
59
+ if cursor.rowcount:
60
+ self.size += 1
61
+ else:
62
+ self._execute("UPDATE counts SET n = ? WHERE key = ?", (count, encoded))
63
+
64
+ def _increment(self, key):
65
+ # Parser-only single increment; do not change generic mapping writes.
66
+ # No RETURNING clause, to retain compatibility with older SQLite.
67
+ encoded = self._encode(key)
68
+ cursor = self._execute("INSERT OR IGNORE INTO counts(key, n) VALUES (?, 1)", (encoded,))
69
+ if cursor.rowcount:
70
+ self.size += 1
71
+ else:
72
+ self._execute("UPDATE counts SET n = n + 1 WHERE key = ?", (encoded,))
73
+
74
+ def __len__(self):
75
+ if self.closed:
76
+ raise InputError("Disk profile is closed; use it inside its context")
77
+ return self.size
78
+
79
+ def items(self):
80
+ # Preserve first-seen order, including stable top-contributor ties.
81
+ cursor = self._execute("SELECT key, n FROM counts ORDER BY rowid")
82
+ try:
83
+ for encoded, count in cursor:
84
+ yield tuple(json.loads(encoded)), count
85
+ except sqlite3.Error as error:
86
+ raise InputError("Temporary profile storage: " + str(error)) from error
87
+ finally:
88
+ cursor.close()
89
+
90
+
91
+ @contextmanager
92
+ def sqlite_csv(
93
+ path,
94
+ columns,
95
+ *,
96
+ null_values=("",),
97
+ delimiter=",",
98
+ max_rows=10000000,
99
+ max_keys=1000000,
100
+ temp_dir=None,
101
+ ):
102
+ """Yield a Profile whose frequencies live in a private temporary database.
103
+
104
+ Use only inside this context. Key values are written to disk, so choose a
105
+ suitable temp_dir for sensitive data. Normal exit and errors clean up the
106
+ database, not securely erase it. Forced termination can leave files behind.
107
+ Cache is bounded, not total process memory; long CSV fields still cost RAM.
108
+ Input limits have the same meaning as read_csv. No existing database is used.
109
+ """
110
+ temporary = _storage_call(TemporaryDirectory, prefix="joinforecast-", dir=temp_dir)
111
+ connection = counts = None
112
+ try:
113
+ database = Path(temporary.name) / "profile.sqlite3"
114
+ connection = _storage_call(sqlite3.connect, str(database))
115
+ counts = _DiskCounts(connection)
116
+ _storage_call(database.chmod, 0o600)
117
+ counts._execute("PRAGMA cache_size = -8192")
118
+ counts._execute("PRAGMA temp_store = FILE")
119
+ counts._execute("CREATE TABLE counts(key TEXT PRIMARY KEY, n INTEGER NOT NULL)")
120
+ # One transaction avoids a filesystem sync per input row.
121
+ counts._execute("BEGIN")
122
+ profile = _read_csv(
123
+ path,
124
+ columns,
125
+ counts,
126
+ null_values,
127
+ delimiter,
128
+ max_rows,
129
+ max_keys,
130
+ increment=counts._increment,
131
+ )
132
+ # Do not reinterpret an exception from the caller's with-body as storage
133
+ # failure. Only our own database and filesystem operations are wrapped.
134
+ yield profile
135
+ finally:
136
+ try:
137
+ if counts is not None:
138
+ counts.closed = True
139
+ if connection is not None:
140
+ _storage_call(connection.close)
141
+ finally:
142
+ _storage_call(temporary.cleanup)
@@ -0,0 +1,287 @@
1
+ Metadata-Version: 2.4
2
+ Name: joinforecast
3
+ Version: 0.2.2
4
+ Summary: Offline, exact CSV equality-join row-count preflight
5
+ Author: Anish Pentyala
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/anishpentyala/joinforecast
8
+ Project-URL: Repository, https://github.com/anishpentyala/joinforecast
9
+ Project-URL: Issues, https://github.com/anishpentyala/joinforecast/issues
10
+ Keywords: csv,join,data-quality,etl
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # joinforecast
17
+
18
+ Count CSV join rows before a many-to-many merge eats your memory.
19
+
20
+ [![Tests](https://github.com/anishpentyala/joinforecast/actions/workflows/tests.yml/badge.svg)](https://github.com/anishpentyala/joinforecast/actions)
21
+
22
+ ## Quickstart
23
+
24
+ ```sh
25
+ python -m pip install "git+https://github.com/anishpentyala/joinforecast.git"
26
+ printf 'customer_id\n001\n001\n002\n' > orders.csv
27
+ printf 'customer_id\n001\n001\n003\n' > customers.csv
28
+ joinforecast orders.csv customers.csv --left-key customer_id
29
+ ```
30
+
31
+ This prints a full JSON report. Selected fields for these exact files:
32
+
33
+ ```json
34
+ {"predicted_rows": {"inner": 4, "left": 5, "right": 5, "full": 6, "left_anti": 1, "right_anti": 1}}
35
+ ```
36
+
37
+ The four matching rows come from two orders times two customer records for `001`.
38
+ No join is built, and neither input is changed. Add `--expect many-to-one` to make
39
+ repeated lookup keys fail the contract (exit 1, with a complete report).
40
+
41
+ Installation is currently from source. A PyPI release is being prepared; do not
42
+ assume `pip install joinforecast` is available until its package page is linked here.
43
+
44
+ ## Details
45
+
46
+ Find a many-to-many row explosion before a CSV equality join, without building
47
+ that join or uploading either file.
48
+
49
+ `joinforecast` counts key frequencies and reports exact inner, left, right, full,
50
+ and anti-join row counts. It shows the largest matched-key contributions,
51
+ unmatched input rows, duplicate joinable keys, and optional contract violations.
52
+ It uses only Python's standard library. Python 3.9 or later is required.
53
+
54
+ ## Install from source
55
+
56
+ ```sh
57
+ git clone https://github.com/anishpentyala/joinforecast.git
58
+ cd joinforecast
59
+ python -m pip install .
60
+ ```
61
+
62
+ This is a source-installable tool, not a claimed PyPI release.
63
+
64
+ ## Catch a broken lookup
65
+
66
+ ```sh
67
+ joinforecast examples/orders.csv examples/customers.csv \
68
+ --left-key customer_id --expect many-to-one --require-match left
69
+ ```
70
+
71
+ The example has two orders for `001` and two customer records for `001`.
72
+ Their key alone contributes **four** output rows. With the default null policy,
73
+ counts are inner **5**, left **7**, right **7**, and full **9**. Two orders have
74
+ no match: customer `003` and the empty customer ID. The command exits **1** because
75
+ the right keys are not unique and some left rows have no match. The report is
76
+ still complete, machine-readable JSON.
77
+
78
+ Without contracts, a valid forecast exits 0, even when it finds duplicates.
79
+ This is a preflight, not a declaration that a join is safe for your analysis.
80
+
81
+ ## Specify the key and null semantics
82
+
83
+ ```sh
84
+ # Composite key; map differently named columns in order.
85
+ joinforecast left.csv right.csv \
86
+ --left-key account --left-key period \
87
+ --right-key customer --right-key month --nulls never
88
+
89
+ # Matching null components; explicitly recognize empty fields and NA as null.
90
+ joinforecast left.csv right.csv --left-key id \
91
+ --nulls match --null-value '' --null-value NA
92
+ ```
93
+
94
+ - Keys are **exact CSV strings**. `001`, `1`, ` 1`, and `1.0` stay different.
95
+ No numeric conversion, trimming, case folding, locale rules, or date parsing.
96
+ - Only empty fields are null by default. `--null-value` can be repeated and
97
+ **replaces**, rather than extends, that default. `--null-value NA` makes
98
+ an empty string an ordinary key. The library can use `null_values=()` for
99
+ no null tokens.
100
+ - `--nulls never` is SQL equality behavior: any null component prevents a match.
101
+ - `--nulls match` matches nulls at corresponding key positions. This models
102
+ null equality, **not a complete pandas CSV-loader simulation**. Set tokens and
103
+ types to match the loader you actually use. pandas warns that its null-key
104
+ matches differ from SQL: [pandas.merge documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge.html).
105
+ - UTF-8 and UTF-8 BOM input only. Comma delimiter by default; `--delimiter ';'`
106
+ is available. CSV quoting and multiline fields are supported.
107
+ - Blank/duplicate header names, missing key columns, ragged rows (including
108
+ blank data records), malformed quoting, and invalid UTF-8 are errors.
109
+ A header-only file is valid and has zero data rows.
110
+
111
+ No missing rows are silently dropped, sampled, or counted as success.
112
+
113
+ ## Contracts and resource limits
114
+
115
+ | Option | Meaning |
116
+ |---|---|
117
+ | `--expect one-to-one` | Both sides' joinable keys must be unique |
118
+ | `--expect one-to-many` | Left joinable keys must be unique |
119
+ | `--expect many-to-one` | Right joinable keys must be unique |
120
+ | `--expect many-to-many` | No uniqueness constraint |
121
+ | `--require-match left/right/both` | All rows on those sides must have a match |
122
+ | `--max-output-rows N` | Each of the four materializing join forecasts must be at most N |
123
+ | `--max-input-rows N` | Per-input row cap, default 10,000,000 |
124
+ | `--max-keys N` | Per-input distinct-key cap, default 1,000,000 |
125
+ | `--top N` | Return at most N matched-key contributors, default 10 |
126
+
127
+ Contracts check all joinable keys, even unmatched ones. Under `never`, null keys
128
+ are excluded from uniqueness checks, but still count as unmatched rows. Under
129
+ `match`, null keys participate normally. This is an explicit contract definition,
130
+ not a promise to duplicate a particular database's uniqueness constraint rules.
131
+
132
+ Input limits stop with exit 2 and **no JSON forecast**, rather than returning a
133
+ plausible partial count. They are safety bounds, not hard RAM guarantees: memory
134
+ is proportional to distinct keys and their lengths. One huge field is also
135
+ subject to Python's CSV parser field-size limit. Output row arithmetic uses
136
+ Python integers, with no floating-point rounding or output-row materialization.
137
+
138
+ Exit codes: **0** complete forecast satisfying requested contracts; **1** complete
139
+ forecast with contract violations; **2** invalid/incomplete input, bad options,
140
+ or output-delivery failure. A successful report write must accept the complete
141
+ text and flush before a normal verdict is returned. Help, version and argument
142
+ messages use the same checked output path. If output fails, partial bytes may
143
+ already have escaped; discard them, since they are not a delivered forecast.
144
+ Diagnostics are best effort if stderr fails too. Embedded `main(argv)` leaves
145
+ caller streams open and unchanged. The executable wrappers own shutdown and
146
+ avoid retrying failed flushes that would otherwise turn exit 2 into exit 120.
147
+ JSON `schema_version` is 1. `ok` means only that the requested contracts passed.
148
+
149
+ ## Opt-in disk-backed key frequencies
150
+
151
+ The default backend keeps key frequencies in memory. If the distinct-key index
152
+ is too large for that, use a private temporary SQLite database instead:
153
+
154
+ ```sh
155
+ joinforecast large-left.csv large-right.csv --left-key id \
156
+ --storage sqlite --max-keys 5000000 --temp-dir /path/to/private/scratch
157
+ ```
158
+
159
+ This uses Python's `sqlite3` module, not a database server. It writes exact key
160
+ values and their frequencies to temporary disk. Use a suitable scratch location
161
+ for sensitive data. The directory is private to the current user; normal success
162
+ and errors close and remove both databases. Removal is **not secure erasure**.
163
+ Forced termination or power loss can leave files behind. Other users with elevated
164
+ access, disk backups, and filesystem snapshots may still expose the data.
165
+
166
+ `--temp-dir` selects an existing parent directory, not a database filename. Omit
167
+ it to use Python's normal temporary location. It requires `--storage sqlite`.
168
+ An unwritable, missing, or full temporary location fails with exit 2 and no JSON
169
+ forecast. Neither CSV input is modified. The SQLite backend needs a Python build
170
+ with `sqlite3` support; the default memory backend does not.
171
+
172
+ Counts, null rules, top-contributor tie order, contracts, and input limits stay the
173
+ same. The default one-million distinct-key cap still applies: increase `--max-keys`
174
+ explicitly if needed. The disk backend reduces Python memory spent on the key
175
+ index, but adds database and disk I/O cost and may be much slower. SQLite's cache
176
+ is configured to about 8 MiB per profile, **not a hard process-memory limit**.
177
+ Long fields, database overhead, and `--top` also consume memory. Database storage
178
+ includes an index and journal; allow more space than the CSV key bytes alone.
179
+
180
+ Library callers use a context manager and keep every forecast inside it:
181
+
182
+ ```python
183
+ from joinforecast import forecast
184
+ from joinforecast.disk import sqlite_csv
185
+
186
+ with sqlite_csv('orders.csv', ['customer_id']) as left:
187
+ with sqlite_csv('customers.csv', ['id']) as right:
188
+ report = forecast(left, right, expectation='many-to-one')
189
+ # The JSON-compatible report is independent of the closed databases.
190
+ ```
191
+
192
+ Disk profile frequencies are a mapping, not an in-memory `Counter`. Access the
193
+ profile only inside its context; it cannot be used after cleanup. Normal
194
+ `read_csv` still returns an in-memory `Counter` profile as before.
195
+
196
+ ## Library
197
+
198
+ ```python
199
+ from joinforecast import read_csv, forecast
200
+
201
+ left = read_csv('orders.csv', ['customer_id'])
202
+ right = read_csv('customers.csv', ['id'])
203
+ report = forecast(left, right, nulls='never', expectation='many-to-one')
204
+ print(report['predicted_rows']['left'])
205
+ ```
206
+
207
+ Input files are read only. There is no network code or telemetry.
208
+ The opt-in SQLite backend writes key frequencies to temporary disk as described above. Reports include
209
+ actual key values in `top_contributors`; treat redirected JSON as sensitive when
210
+ your CSV contains private identifiers. `--top 0` omits those examples.
211
+
212
+ ## How counts work
213
+
214
+ For every joinable shared key with L left rows and R right rows, the inner join
215
+ contribution is L × R. Each left row with no right match adds one row to the left
216
+ and full joins; each unmatched right row adds one row to the right and full joins.
217
+ Composite keys are tuples, not delimiter-joined strings, so embedded separators
218
+ cannot create false matches. Top contributors are bounded with a heap.
219
+
220
+ This does not perform the join, validate non-key columns, estimate output bytes,
221
+ resolve suffix conflicts, check aggregates, or predict range/as-of/fuzzy/collation
222
+ joins. It cannot infer the semantics of a later loader or changed input files.
223
+ Run the preflight on the exact inputs and settings used by the eventual join.
224
+
225
+ ## Develop
226
+
227
+ ```sh
228
+ python -m pip install -e . coverage ruff build
229
+ python -m unittest discover -s tests -v
230
+ coverage run -m unittest discover -s tests
231
+ coverage report
232
+ ruff check src tests
233
+ ruff format --check src tests
234
+ python -m build
235
+ ```
236
+
237
+ The test suite includes a seeded independent SQLite relational oracle for
238
+ composite-key joins under SQL equality and null-equal semantics, hand-computed
239
+ fanout, huge exact counts, malformed CSV rejection, contract failures, CLI exit
240
+ codes, and input byte preservation. Disk tests compare complete reports with the
241
+ memory backend, use an independent relational oracle, and exercise private-file
242
+ cleanup and real storage-full/read-interruption failures. CI tests the installed package, not a
243
+ materialized large join. No database service is required.
244
+
245
+ ## Frequency-scan implementation (0.2.1)
246
+
247
+ After full profile validation, forecasting visits each left key once to count
248
+ matches, check left uniqueness and maintain the bounded top-contributor heap.
249
+ Each joinable left key needs one right-frequency lookup, regardless of `top`.
250
+ Equal-contribution ties still prefer the left input's first-seen key. Validation
251
+ and the right uniqueness scan remain complete, even with `top=0`.
252
+
253
+ The SQLite CSV parser encodes each key once, tries an insert, then increments
254
+ existing counts in SQL. It no longer reads a frequency back into Python for
255
+ each CSV row. The private parser callback is supplied explicitly by the SQLite
256
+ backend; ordinary mapping assignment still replaces a value rather than adding
257
+ to it. No SQLite `RETURNING` support is needed.
258
+
259
+ These are operation-count changes, not a promise of a particular speedup.
260
+ SQLite is still an opt-in lower-memory tradeoff and can be slower than the
261
+ in-memory backend. High `top` values retain up to that many contributor entries;
262
+ there is no hard process-memory guarantee. Parsing, null handling, report fields,
263
+ validation and contract failures are unchanged. Synthetic tests compare complete
264
+ reports and stable ties, and independently enumerate row pairs for small cases.
265
+
266
+
267
+ ## Combined validation and aggregation (0.2.2)
268
+
269
+ Forecasting now validates frequencies while using them, rather than scanning
270
+ both complete mappings once for validation and again for aggregation. Each
271
+ mapping's `items()` is traversed once. The right profile is fully checked while
272
+ counting duplicate keys, then the left profile is checked while counting matches
273
+ and selecting contributors. Totals are checked after each traversal. An invalid
274
+ last key or inconsistent row total still raises an error, including with
275
+ `top=0`; no partial forecast is returned.
276
+
277
+ Accepted inputs produce the same complete reports, null semantics, stable ties,
278
+ and contract results. If several inputs or options are invalid, which error is
279
+ reported first can change. Profiles and mappings are not atomic snapshots, so do
280
+ not mutate them during a forecast.
281
+
282
+ This removes two full SQLite key-decoding passes. In a local Linux CPython 3.14
283
+ measurement of the forecast alone over two 100,000-distinct-key profiles, the
284
+ median of three fresh-process runs changed from 0.718 to 0.564 seconds for disk
285
+ profiles. The in-memory case was slower, from 0.079 to 0.085 seconds. Input parsing
286
+ was outside that timing; peak process RSS was similar. These are synthetic local
287
+ measurements, not a universal speed or memory guarantee.
@@ -0,0 +1,9 @@
1
+ joinforecast/__init__.py,sha256=lL68OMIf83vk67lOn3AoR0qdcncBAa8-cHvTEv8z9PU,9253
2
+ joinforecast/__main__.py,sha256=SD8kjqpHOmyJIhPQU3ymPeqfMal-JcXR1wUUTVklsGs,5267
3
+ joinforecast/disk.py,sha256=h9Zn_a-bb2NuUDx7mNBCsLTe4T3OI2vMMZOVKMYI67Y,5057
4
+ joinforecast-0.2.2.dist-info/licenses/LICENSE,sha256=5yembAmR4hjWu7NOBFMDqvjvtnM8Ta_OGaPrAsVcI-I,1071
5
+ joinforecast-0.2.2.dist-info/METADATA,sha256=_oRfWpYusx88HDzwOqWBwbMT82VCf185dg7s3kWVphA,13961
6
+ joinforecast-0.2.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ joinforecast-0.2.2.dist-info/entry_points.txt,sha256=r5iF4GTEuZh9rPDPlVxkZ_1aWSrocFKpBT9-VwF-mAE,59
8
+ joinforecast-0.2.2.dist-info/top_level.txt,sha256=0kJC9wZuktmaUBb7r6qAUpvw2YbqZ7NRhtpZRgTwV44,13
9
+ joinforecast-0.2.2.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
+ joinforecast = joinforecast.__main__: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
+ joinforecast