agentsor-file 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentsor_file-0.2.0.dist-info/METADATA +247 -0
- agentsor_file-0.2.0.dist-info/RECORD +18 -0
- agentsor_file-0.2.0.dist-info/WHEEL +5 -0
- agentsor_file-0.2.0.dist-info/entry_points.txt +3 -0
- agentsor_file-0.2.0.dist-info/licenses/LICENSE +21 -0
- agentsor_file-0.2.0.dist-info/top_level.txt +1 -0
- parquet_guard/__init__.py +28 -0
- parquet_guard/cli.py +75 -0
- parquet_guard/config.py +176 -0
- parquet_guard/contracts.py +256 -0
- parquet_guard/file_cli.py +279 -0
- parquet_guard/file_contracts.py +685 -0
- parquet_guard/fingerprints.py +50 -0
- parquet_guard/hosted.py +485 -0
- parquet_guard/pipeline.py +425 -0
- parquet_guard/py.typed +1 -0
- parquet_guard/schemas/error-envelope-v1.schema.json +38 -0
- parquet_guard/schemas/result-envelope-v1.schema.json +255 -0
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentsor-file
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Local CSV and Parquet contracts with redacted hosted receipts
|
|
5
|
+
Author: Agentsor
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://agentsor.ai/file-contracts
|
|
8
|
+
Project-URL: Repository, https://github.com/linkoinsight/agentsor-file
|
|
9
|
+
Project-URL: Issues, https://github.com/linkoinsight/agentsor-file/issues
|
|
10
|
+
Keywords: csv,parquet,data-contracts,schema-validation
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: pyarrow<24,>=16
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: build<2,>=1.2; extra == "dev"
|
|
25
|
+
Requires-Dist: jsonschema<5,>=4.23; extra == "dev"
|
|
26
|
+
Requires-Dist: pytest<10,>=8; extra == "dev"
|
|
27
|
+
Requires-Dist: ruff<0.14,>=0.12; extra == "dev"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# Agentsor File Contracts
|
|
31
|
+
|
|
32
|
+
Agentsor File Contracts is a free, MIT-licensed command-line tool for checking
|
|
33
|
+
one local CSV or Parquet file against an explicit TOML contract. It checks:
|
|
34
|
+
|
|
35
|
+
- file readability;
|
|
36
|
+
- required columns and Arrow types;
|
|
37
|
+
- unexpected columns;
|
|
38
|
+
- row and byte bounds;
|
|
39
|
+
- optional event-time freshness; and
|
|
40
|
+
- optional duplicate history.
|
|
41
|
+
|
|
42
|
+
`init`, `check`, and `schema` run offline. The separate `report` command checks
|
|
43
|
+
the file locally and sends only the fixed redacted result envelope to the
|
|
44
|
+
single Agentsor collector. The package has no file-upload or telemetry path.
|
|
45
|
+
|
|
46
|
+
## Local quickstart
|
|
47
|
+
|
|
48
|
+
Python 3.11 or newer is required. From this checkout:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
python -m venv .venv
|
|
52
|
+
. .venv/bin/activate
|
|
53
|
+
python -m pip install .
|
|
54
|
+
agentsor-file init \
|
|
55
|
+
--format parquet \
|
|
56
|
+
--contract file-contract.toml \
|
|
57
|
+
--fingerprint-key-file .agentsor-file.key
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`init` refuses to replace either target or follow a target symlink. It creates
|
|
61
|
+
a random 32-byte fingerprint key with mode `0600` and never prints the key.
|
|
62
|
+
Edit the generated `[schema]` table to describe the file, then run:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
agentsor-file check YOUR_FILE.parquet \
|
|
66
|
+
--contract file-contract.toml \
|
|
67
|
+
--fingerprint-key-file .agentsor-file.key \
|
|
68
|
+
--state .agentsor-file-state.json
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The `init`, `check`, and `schema` commands make no network requests. The CLI
|
|
72
|
+
requires the fingerprint key to be an owner-only regular file and refuses
|
|
73
|
+
links or group/world-readable modes. Keep it private and stable within one
|
|
74
|
+
project. Back it up if fingerprint continuity matters.
|
|
75
|
+
|
|
76
|
+
The CLI exits `0` for a passed contract, `1` for a failed or inconclusive
|
|
77
|
+
result, and `2` for a usage, contract, credential, input, transport, or hosted
|
|
78
|
+
receipt error.
|
|
79
|
+
|
|
80
|
+
## Hosted deadline reporting
|
|
81
|
+
|
|
82
|
+
After creating a free monitor at
|
|
83
|
+
[agentsor.ai/file-contracts](https://agentsor.ai/file-contracts), put the
|
|
84
|
+
one-time ingest token in an owner-only credential file without placing it in a
|
|
85
|
+
shell argument:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
mkdir -m 700 -p ~/.config/agentsor
|
|
89
|
+
umask 077
|
|
90
|
+
${EDITOR:-vi} ~/.config/agentsor/file-token
|
|
91
|
+
chmod 600 ~/.config/agentsor/file-token
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Then check and submit one redacted result:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
agentsor-file report YOUR_FILE.parquet \
|
|
98
|
+
--contract file-contract.toml \
|
|
99
|
+
--fingerprint-key-file .agentsor-file.key \
|
|
100
|
+
--token-file ~/.config/agentsor/file-token
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`report` has a fixed HTTPS destination, disables inherited proxies and
|
|
104
|
+
redirects, verifies TLS, bounds request/response sizes, validates the complete
|
|
105
|
+
result before network I/O, and never prints the token. It prints a fixed
|
|
106
|
+
acknowledgement containing the run ID, local overall result, duplicate-receipt
|
|
107
|
+
flag, and next hosted deadline.
|
|
108
|
+
|
|
109
|
+
Hosted reporting does not currently accept `--state`; configure
|
|
110
|
+
`reject_duplicates = false` for that command. Use offline `check --state` when
|
|
111
|
+
local duplicate-output detection is required. This avoids mutating duplicate
|
|
112
|
+
state before a network failure can be retried safely.
|
|
113
|
+
|
|
114
|
+
## Contract format
|
|
115
|
+
|
|
116
|
+
```toml
|
|
117
|
+
[contract]
|
|
118
|
+
format = "parquet"
|
|
119
|
+
allow_extra_columns = false
|
|
120
|
+
min_rows = 1
|
|
121
|
+
max_rows = 1000000
|
|
122
|
+
min_bytes = 1
|
|
123
|
+
max_bytes = 104857600
|
|
124
|
+
csv_delimiter = ","
|
|
125
|
+
reject_duplicates = false
|
|
126
|
+
|
|
127
|
+
# Optional; configure both together.
|
|
128
|
+
# event_time_column = "event_time"
|
|
129
|
+
# max_age_seconds = 86400
|
|
130
|
+
|
|
131
|
+
[schema]
|
|
132
|
+
id = "string"
|
|
133
|
+
amount = "double"
|
|
134
|
+
# event_time = "timestamp[ms]"
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`format` may be `csv` or `parquet`, or omitted when one contract intentionally
|
|
138
|
+
supports both. Schema values use PyArrow type aliases. Parquet physical types
|
|
139
|
+
must match exactly. CSV has no physical type metadata, so required CSV columns
|
|
140
|
+
must safely cast to their configured Arrow types.
|
|
141
|
+
|
|
142
|
+
Freshness uses the newest non-null event time. Timestamp columns without a
|
|
143
|
+
timezone are interpreted as UTC. `reject_duplicates = true` requires
|
|
144
|
+
`--state`; without usable state, the result is inconclusive. State contains
|
|
145
|
+
only project-keyed output fingerprints and retains the latest 4,096 unique
|
|
146
|
+
values.
|
|
147
|
+
|
|
148
|
+
## Redacted result envelope
|
|
149
|
+
|
|
150
|
+
`check` writes exactly one JSON object to stdout. The v1 envelope contains a
|
|
151
|
+
canonical run UUID and UTC timestamps, format, bounded row/byte counts, six
|
|
152
|
+
fixed check statuses, fixed reason codes, and three fingerprints. It does not
|
|
153
|
+
contain file paths, file names, column names, raw values, exception messages,
|
|
154
|
+
or arbitrary text.
|
|
155
|
+
|
|
156
|
+
The contract, schema, and output fingerprints are domain-separated
|
|
157
|
+
HMAC-SHA256 values keyed by the supplied project key. They support equality
|
|
158
|
+
and drift checks inside that project without exposing a global raw SHA-256
|
|
159
|
+
that could correlate low-entropy files or schemas across projects.
|
|
160
|
+
|
|
161
|
+
Redaction is not zero knowledge: row/byte counts, timing, outcomes, and
|
|
162
|
+
within-project equality can still reveal metadata. Review that boundary
|
|
163
|
+
before sharing a result.
|
|
164
|
+
|
|
165
|
+
Print the installed formal JSON Schema with:
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
agentsor-file schema
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The fixed checks are `readability`, `schema`, `rowBounds`, `byteBounds`,
|
|
172
|
+
`eventFreshness`, and `duplicate`. Required checks use
|
|
173
|
+
`passed|failed|inconclusive`; the two optional checks may also use
|
|
174
|
+
`not_configured`. Overall status is:
|
|
175
|
+
|
|
176
|
+
- `passed` when every check is passed or not configured and reasons are empty;
|
|
177
|
+
- `failed` when at least one check failed; or
|
|
178
|
+
- `inconclusive` when none failed and at least one could not complete.
|
|
179
|
+
|
|
180
|
+
## Python API
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
from pathlib import Path
|
|
184
|
+
|
|
185
|
+
from parquet_guard import check_file, load_file_contract
|
|
186
|
+
|
|
187
|
+
contract = load_file_contract("file-contract.toml")
|
|
188
|
+
key = Path(".agentsor-file.key").read_bytes()
|
|
189
|
+
result = check_file("output.parquet", contract, fingerprint_key=key)
|
|
190
|
+
print(result.as_dict())
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Applications should protect the key at least as carefully as the local CLI
|
|
194
|
+
does and should not log it.
|
|
195
|
+
|
|
196
|
+
## Deliberate limits
|
|
197
|
+
|
|
198
|
+
- Files larger than 1 TiB and row counts above 1 trillion are outside the v1
|
|
199
|
+
result envelope.
|
|
200
|
+
- Files are read locally by PyArrow; set a realistic `max_bytes` to establish
|
|
201
|
+
a resource boundary before parsing.
|
|
202
|
+
- Duplicate state is atomic and fail-closed but assumes one writer at a time.
|
|
203
|
+
- This release checks completed files; it does not watch producer directories
|
|
204
|
+
or establish that a producer has finished writing.
|
|
205
|
+
- A same-size file that changes during a run is detected by a second keyed
|
|
206
|
+
fingerprint and produces an inconclusive result.
|
|
207
|
+
- Hosted reporting sends only aggregate result metadata; it does not send the
|
|
208
|
+
file, its name or path, column names, values, storage location, or arbitrary
|
|
209
|
+
notes.
|
|
210
|
+
|
|
211
|
+
## Historical Parquet demonstration
|
|
212
|
+
|
|
213
|
+
This repository began as an owned engineering demonstration of a fail-closed,
|
|
214
|
+
idempotent Parquet batch pipeline. That truthful history remains available
|
|
215
|
+
through the compatibility command:
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
python examples/generate_sample.py
|
|
219
|
+
parquet-guard --config examples/config.toml
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
It demonstrates validation, deterministic decimal transformation, quarantine,
|
|
223
|
+
atomic output/state, and rerun integrity. It is not client work and is not
|
|
224
|
+
evidence that customer data has been processed. Agentsor File Contracts does
|
|
225
|
+
not silently invoke or quarantine files through that historical command.
|
|
226
|
+
|
|
227
|
+
## Development
|
|
228
|
+
|
|
229
|
+
```bash
|
|
230
|
+
python -m pip install -e '.[dev]'
|
|
231
|
+
pytest
|
|
232
|
+
ruff check src tests
|
|
233
|
+
python -m build
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
The tests cover both formats, config validation, redaction, formal envelope
|
|
237
|
+
validation, project-key isolation, schema stability, bounds, freshness,
|
|
238
|
+
duplicate state, fail-closed state handling, CLI exit behavior, secure init,
|
|
239
|
+
and the historical batch demonstration.
|
|
240
|
+
|
|
241
|
+
For bounded implementation work, see
|
|
242
|
+
[Agentsor Automation Reliability](https://agentsor.ai/automation-reliability).
|
|
243
|
+
Do not send
|
|
244
|
+
credentials, source code, personal data, production records, or confidential
|
|
245
|
+
material by email.
|
|
246
|
+
|
|
247
|
+
License: MIT.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
agentsor_file-0.2.0.dist-info/licenses/LICENSE,sha256=6IPSBYHE6H43vEEeQf7EuUy6ZteosiENo2f1a5QJZX4,1065
|
|
2
|
+
parquet_guard/__init__.py,sha256=sagb0CpHaB_BYG8NVk0v02ROE9SzAz8XIeovFbukU8c,766
|
|
3
|
+
parquet_guard/cli.py,sha256=9F0JPsBENiU_-BC-4caxq7nR5VruttvWZyGzg6VmS6M,2145
|
|
4
|
+
parquet_guard/config.py,sha256=mr4n8w3BsZ9dQc6i3RMzWXfB6LKZn5g304mpdD9Eboo,7070
|
|
5
|
+
parquet_guard/contracts.py,sha256=xOtPuMRr9do8uV3JvRl84cEUZIME7vMMRje2tMOIUrs,9792
|
|
6
|
+
parquet_guard/file_cli.py,sha256=_o3-jCNJzZZi0cZH-0XVyYLDgFGElFZRH2tpaRkS_00,8837
|
|
7
|
+
parquet_guard/file_contracts.py,sha256=5Ixk5kjDFDdhleHqImmsTvfr-rxCIdiEvAyt67qI9IE,22440
|
|
8
|
+
parquet_guard/fingerprints.py,sha256=687YT3XCMBdb4mIk2evmyhw5q0xc3Mn5SPbY52EzHyQ,1552
|
|
9
|
+
parquet_guard/hosted.py,sha256=tqwPFnhKhNZW6JrhZdqKl24JLDRt5WN95Myamo4SZzM,16752
|
|
10
|
+
parquet_guard/pipeline.py,sha256=X_XTOpUwYCf-HnKmlFfiU05kX2ADbnsQ5CdRuXfznPM,13887
|
|
11
|
+
parquet_guard/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
12
|
+
parquet_guard/schemas/error-envelope-v1.schema.json,sha256=1UjfvJtJ4-_UhQGq0_tZS_ELA-_wnRXxGbfxTM11uoY,1001
|
|
13
|
+
parquet_guard/schemas/result-envelope-v1.schema.json,sha256=2gcvGHJpEGRTS0-lFbiY-AThaHbEfAnpP2alcg-mZXs,7073
|
|
14
|
+
agentsor_file-0.2.0.dist-info/METADATA,sha256=2QzxRTGasrgw1Rv8zQxEMFeKnjZkW8vfp4iwh5qCgbo,8748
|
|
15
|
+
agentsor_file-0.2.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
16
|
+
agentsor_file-0.2.0.dist-info/entry_points.txt,sha256=ufwXlFdGw7SL_oWPXTil8gEEb44AVln8D5atMMKbXgE,101
|
|
17
|
+
agentsor_file-0.2.0.dist-info/top_level.txt,sha256=_KMYeKeboLcrR6Lu73fwwg46QX3AC7Mo1s7NEUaTPAw,14
|
|
18
|
+
agentsor_file-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Agentsor
|
|
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
|
+
parquet_guard
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Offline file contracts and the historical Parquet batch demonstration."""
|
|
2
|
+
|
|
3
|
+
from .config import PipelineConfig, load_config
|
|
4
|
+
from .contracts import ContractConfigError, FileContract, load_file_contract
|
|
5
|
+
from .file_contracts import (
|
|
6
|
+
ContractResult,
|
|
7
|
+
DuplicateStateError,
|
|
8
|
+
FileContractInputError,
|
|
9
|
+
check_file,
|
|
10
|
+
)
|
|
11
|
+
from .fingerprints import FingerprintKeyError, project_fingerprint
|
|
12
|
+
from .pipeline import PipelineSummary, run_pipeline
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ContractConfigError",
|
|
16
|
+
"ContractResult",
|
|
17
|
+
"DuplicateStateError",
|
|
18
|
+
"FileContract",
|
|
19
|
+
"FileContractInputError",
|
|
20
|
+
"FingerprintKeyError",
|
|
21
|
+
"PipelineConfig",
|
|
22
|
+
"PipelineSummary",
|
|
23
|
+
"check_file",
|
|
24
|
+
"load_config",
|
|
25
|
+
"load_file_contract",
|
|
26
|
+
"project_fingerprint",
|
|
27
|
+
"run_pipeline",
|
|
28
|
+
]
|
parquet_guard/cli.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .config import ConfigError, load_config
|
|
13
|
+
from .pipeline import run_pipeline, summary_dict
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class JsonFormatter(logging.Formatter):
|
|
17
|
+
"""Emit one small structured event per log line."""
|
|
18
|
+
|
|
19
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
20
|
+
value: dict[str, Any] = {
|
|
21
|
+
"timestamp": datetime.fromtimestamp(
|
|
22
|
+
record.created, tz=timezone.utc
|
|
23
|
+
).isoformat(),
|
|
24
|
+
"level": record.levelname.lower(),
|
|
25
|
+
"event": getattr(record, "event", record.getMessage()),
|
|
26
|
+
}
|
|
27
|
+
for key in (
|
|
28
|
+
"run_id",
|
|
29
|
+
"file",
|
|
30
|
+
"reason",
|
|
31
|
+
"rows",
|
|
32
|
+
"discovered",
|
|
33
|
+
"succeeded",
|
|
34
|
+
"quarantined",
|
|
35
|
+
"skipped",
|
|
36
|
+
"failed",
|
|
37
|
+
):
|
|
38
|
+
if hasattr(record, key):
|
|
39
|
+
value[key] = getattr(record, key)
|
|
40
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _parser() -> argparse.ArgumentParser:
|
|
44
|
+
parser = argparse.ArgumentParser(
|
|
45
|
+
description="Process, validate, transform, and quarantine Parquet inputs."
|
|
46
|
+
)
|
|
47
|
+
parser.add_argument(
|
|
48
|
+
"--config", required=True, help="Path to the TOML configuration"
|
|
49
|
+
)
|
|
50
|
+
return parser
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def main() -> int:
|
|
54
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
55
|
+
handler.setFormatter(JsonFormatter())
|
|
56
|
+
logger = logging.getLogger("parquet_guard")
|
|
57
|
+
logger.handlers[:] = [handler]
|
|
58
|
+
logger.setLevel(logging.INFO)
|
|
59
|
+
logger.propagate = False
|
|
60
|
+
|
|
61
|
+
arguments = _parser().parse_args()
|
|
62
|
+
try:
|
|
63
|
+
summary = run_pipeline(load_config(arguments.config))
|
|
64
|
+
except ConfigError as exc:
|
|
65
|
+
print(
|
|
66
|
+
json.dumps({"error": "invalid_config", "message": str(exc)}),
|
|
67
|
+
file=sys.stderr,
|
|
68
|
+
)
|
|
69
|
+
return 2
|
|
70
|
+
print(json.dumps(summary_dict(summary), sort_keys=True))
|
|
71
|
+
return 0 if summary.quarantined == 0 and summary.failed == 0 else 1
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
if __name__ == "__main__":
|
|
75
|
+
raise SystemExit(main())
|
parquet_guard/config.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""External configuration for the demonstration pipeline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from decimal import Decimal, InvalidOperation
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import tomllib
|
|
9
|
+
|
|
10
|
+
import pyarrow as pa
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConfigError(ValueError):
|
|
14
|
+
"""Raised when a configuration cannot be used safely."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class PipelineConfig:
|
|
19
|
+
"""Validated runtime configuration."""
|
|
20
|
+
|
|
21
|
+
input_dir: Path
|
|
22
|
+
output_dir: Path
|
|
23
|
+
quarantine_dir: Path
|
|
24
|
+
state_dir: Path
|
|
25
|
+
required_schema: dict[str, str]
|
|
26
|
+
output_compression: str = "zstd"
|
|
27
|
+
allow_extra_columns: bool = False
|
|
28
|
+
amount_column: str | None = None
|
|
29
|
+
amount_multiplier: str = "100"
|
|
30
|
+
amount_output_column: str = "amount_cents"
|
|
31
|
+
amount_rounding: str = "half_even"
|
|
32
|
+
|
|
33
|
+
def validate(self) -> "PipelineConfig":
|
|
34
|
+
directories = (
|
|
35
|
+
self.input_dir.resolve(),
|
|
36
|
+
self.output_dir.resolve(),
|
|
37
|
+
self.quarantine_dir.resolve(),
|
|
38
|
+
self.state_dir.resolve(),
|
|
39
|
+
)
|
|
40
|
+
if len(set(directories)) != len(directories):
|
|
41
|
+
raise ConfigError("pipeline directories must be distinct")
|
|
42
|
+
if not self.required_schema:
|
|
43
|
+
raise ConfigError("schema must contain at least one required column")
|
|
44
|
+
for column, type_name in self.required_schema.items():
|
|
45
|
+
if not column or not isinstance(column, str):
|
|
46
|
+
raise ConfigError("schema column names must be non-empty strings")
|
|
47
|
+
try:
|
|
48
|
+
pa.type_for_alias(type_name)
|
|
49
|
+
except (ValueError, TypeError) as exc:
|
|
50
|
+
raise ConfigError(
|
|
51
|
+
f"unsupported Arrow type alias for {column!r}: {type_name!r}"
|
|
52
|
+
) from exc
|
|
53
|
+
if self.amount_column is not None:
|
|
54
|
+
configured_type = self.required_schema.get(self.amount_column)
|
|
55
|
+
if configured_type not in {"double", "float64", "float", "float32"}:
|
|
56
|
+
raise ConfigError(
|
|
57
|
+
"amount_column must name a required floating-point column"
|
|
58
|
+
)
|
|
59
|
+
if (
|
|
60
|
+
not isinstance(self.amount_output_column, str)
|
|
61
|
+
or not self.amount_output_column.strip()
|
|
62
|
+
):
|
|
63
|
+
raise ConfigError("amount_output_column must be a non-empty string")
|
|
64
|
+
if self.amount_output_column in self.required_schema:
|
|
65
|
+
raise ConfigError(
|
|
66
|
+
"amount_output_column must not overwrite a required input column"
|
|
67
|
+
)
|
|
68
|
+
if isinstance(self.amount_multiplier, bool):
|
|
69
|
+
raise ConfigError("amount_multiplier must be a decimal number")
|
|
70
|
+
try:
|
|
71
|
+
multiplier = Decimal(self.amount_multiplier)
|
|
72
|
+
except (InvalidOperation, TypeError, ValueError) as exc:
|
|
73
|
+
raise ConfigError("amount_multiplier must be a decimal number") from exc
|
|
74
|
+
if not multiplier.is_finite():
|
|
75
|
+
raise ConfigError("amount_multiplier must be finite")
|
|
76
|
+
if self.amount_rounding not in {
|
|
77
|
+
"half_even",
|
|
78
|
+
"half_up",
|
|
79
|
+
"half_down",
|
|
80
|
+
"down",
|
|
81
|
+
"up",
|
|
82
|
+
}:
|
|
83
|
+
raise ConfigError("unsupported amount_rounding rule")
|
|
84
|
+
if self.output_compression not in {
|
|
85
|
+
"none",
|
|
86
|
+
"snappy",
|
|
87
|
+
"gzip",
|
|
88
|
+
"brotli",
|
|
89
|
+
"zstd",
|
|
90
|
+
"lz4",
|
|
91
|
+
}:
|
|
92
|
+
raise ConfigError("unsupported Parquet output compression")
|
|
93
|
+
if self.output_compression != "none" and not pa.Codec.is_available(
|
|
94
|
+
self.output_compression
|
|
95
|
+
):
|
|
96
|
+
raise ConfigError(
|
|
97
|
+
f"Parquet compression codec is unavailable: {self.output_compression}"
|
|
98
|
+
)
|
|
99
|
+
return self
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _required_string(table: dict[str, object], key: str) -> str:
|
|
103
|
+
value = table.get(key)
|
|
104
|
+
if not isinstance(value, str) or not value.strip():
|
|
105
|
+
raise ConfigError(f"pipeline.{key} must be a non-empty string")
|
|
106
|
+
return value.strip()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def load_config(path: Path | str) -> PipelineConfig:
|
|
110
|
+
"""Load a TOML configuration, resolving paths relative to that file."""
|
|
111
|
+
|
|
112
|
+
config_path = Path(path).resolve()
|
|
113
|
+
try:
|
|
114
|
+
raw = tomllib.loads(config_path.read_text(encoding="utf-8"))
|
|
115
|
+
except (OSError, tomllib.TOMLDecodeError) as exc:
|
|
116
|
+
raise ConfigError(f"could not load configuration: {exc}") from exc
|
|
117
|
+
|
|
118
|
+
pipeline = raw.get("pipeline")
|
|
119
|
+
schema = raw.get("schema")
|
|
120
|
+
if not isinstance(pipeline, dict) or not isinstance(schema, dict):
|
|
121
|
+
raise ConfigError("configuration requires [pipeline] and [schema] tables")
|
|
122
|
+
|
|
123
|
+
base = config_path.parent
|
|
124
|
+
|
|
125
|
+
def configured_path(key: str) -> Path:
|
|
126
|
+
value = Path(_required_string(pipeline, key))
|
|
127
|
+
return value.resolve() if value.is_absolute() else (base / value).resolve()
|
|
128
|
+
|
|
129
|
+
if not all(
|
|
130
|
+
isinstance(key, str) and isinstance(value, str) for key, value in schema.items()
|
|
131
|
+
):
|
|
132
|
+
raise ConfigError("schema entries must map column names to Arrow type aliases")
|
|
133
|
+
|
|
134
|
+
amount_column = pipeline.get("amount_column")
|
|
135
|
+
if amount_column is not None and (
|
|
136
|
+
not isinstance(amount_column, str) or not amount_column.strip()
|
|
137
|
+
):
|
|
138
|
+
raise ConfigError("pipeline.amount_column must be a non-empty string")
|
|
139
|
+
|
|
140
|
+
allow_extra = pipeline.get("allow_extra_columns", False)
|
|
141
|
+
if not isinstance(allow_extra, bool):
|
|
142
|
+
raise ConfigError("pipeline.allow_extra_columns must be true or false")
|
|
143
|
+
|
|
144
|
+
compression = pipeline.get("output_compression", "zstd")
|
|
145
|
+
if not isinstance(compression, str):
|
|
146
|
+
raise ConfigError("pipeline.output_compression must be a string")
|
|
147
|
+
|
|
148
|
+
amount_multiplier = pipeline.get("amount_multiplier", "100")
|
|
149
|
+
if isinstance(amount_multiplier, (int, float)):
|
|
150
|
+
amount_multiplier = str(amount_multiplier)
|
|
151
|
+
if not isinstance(amount_multiplier, str) or not amount_multiplier.strip():
|
|
152
|
+
raise ConfigError(
|
|
153
|
+
"pipeline.amount_multiplier must be a decimal string or number"
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
amount_output_column = pipeline.get("amount_output_column", "amount_cents")
|
|
157
|
+
if not isinstance(amount_output_column, str) or not amount_output_column.strip():
|
|
158
|
+
raise ConfigError("pipeline.amount_output_column must be a non-empty string")
|
|
159
|
+
|
|
160
|
+
amount_rounding = pipeline.get("amount_rounding", "half_even")
|
|
161
|
+
if not isinstance(amount_rounding, str):
|
|
162
|
+
raise ConfigError("pipeline.amount_rounding must be a string")
|
|
163
|
+
|
|
164
|
+
return PipelineConfig(
|
|
165
|
+
input_dir=configured_path("input_dir"),
|
|
166
|
+
output_dir=configured_path("output_dir"),
|
|
167
|
+
quarantine_dir=configured_path("quarantine_dir"),
|
|
168
|
+
state_dir=configured_path("state_dir"),
|
|
169
|
+
required_schema=dict(schema),
|
|
170
|
+
output_compression=compression.lower(),
|
|
171
|
+
allow_extra_columns=allow_extra,
|
|
172
|
+
amount_column=amount_column.strip() if isinstance(amount_column, str) else None,
|
|
173
|
+
amount_multiplier=amount_multiplier.strip(),
|
|
174
|
+
amount_output_column=amount_output_column.strip(),
|
|
175
|
+
amount_rounding=amount_rounding.strip().lower(),
|
|
176
|
+
).validate()
|