sqllocks-shape 0.9.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.
- shape/__init__.py +84 -0
- shape/api.py +65 -0
- shape/artifact/__init__.py +36 -0
- shape/artifact/canonical.py +30 -0
- shape/artifact/io.py +120 -0
- shape/artifact/migrate.py +53 -0
- shape/artifact/secure.py +58 -0
- shape/artifact/shape_file.py +63 -0
- shape/capture/__init__.py +5 -0
- shape/capture/core.py +75 -0
- shape/capture/vectorized.py +82 -0
- shape/cli/__init__.py +1 -0
- shape/cli/main.py +320 -0
- shape/connectors/__init__.py +31 -0
- shape/connectors/dbapi.py +55 -0
- shape/connectors/eventhubs.py +34 -0
- shape/connectors/files.py +69 -0
- shape/connectors/kafka.py +36 -0
- shape/connectors/qualification.py +70 -0
- shape/connectors/registry.py +22 -0
- shape/contracts/__init__.py +18 -0
- shape/contracts/core.py +147 -0
- shape/contracts/v1.py +350 -0
- shape/diff/__init__.py +4 -0
- shape/diff/core.py +29 -0
- shape/drift/__init__.py +6 -0
- shape/drift/core.py +62 -0
- shape/drift/policy.py +22 -0
- shape/errors.py +21 -0
- shape/generation/__init__.py +195 -0
- shape/generation/address_vectorized.py +77 -0
- shape/generation/advanced.py +60 -0
- shape/generation/certificate.py +109 -0
- shape/generation/compiler.py +154 -0
- shape/generation/core.py +43 -0
- shape/generation/distribution_fidelity.py +30 -0
- shape/generation/evolution.py +33 -0
- shape/generation/fidelity.py +127 -0
- shape/generation/future.py +14 -0
- shape/generation/geo_fidelity.py +21 -0
- shape/generation/joint.py +49 -0
- shape/generation/levels.py +51 -0
- shape/generation/relational.py +83 -0
- shape/generation/relational_fidelity.py +33 -0
- shape/generation/release.py +18 -0
- shape/generation/strategies.py +144 -0
- shape/generation/timeline.py +63 -0
- shape/generation/vectorized.py +31 -0
- shape/geospatial/__init__.py +5 -0
- shape/geospatial/core.py +40 -0
- shape/kernel/__init__.py +4 -0
- shape/kernel/batches.py +25 -0
- shape/location/__init__.py +51 -0
- shape/location/core.py +167 -0
- shape/location/reference.py +106 -0
- shape/model/__init__.py +14 -0
- shape/model/core.py +69 -0
- shape/packs/__init__.py +86 -0
- shape/packs/address.py +228 -0
- shape/packs/base.py +35 -0
- shape/packs/domains.py +241 -0
- shape/packs/person.py +20 -0
- shape/packs/sdk.py +26 -0
- shape/packs/verify.py +17 -0
- shape/plugins/__init__.py +13 -0
- shape/plugins/core.py +52 -0
- shape/plugins/runtime.py +53 -0
- shape/privacy/__init__.py +77 -0
- shape/privacy/advanced.py +8 -0
- shape/privacy/classification.py +17 -0
- shape/privacy/core.py +35 -0
- shape/privacy/detect.py +59 -0
- shape/privacy/measure.py +58 -0
- shape/privacy/policy.py +100 -0
- shape/privacy/propagate.py +14 -0
- shape/privacy/release.py +54 -0
- shape/profile/__init__.py +57 -0
- shape/profile/advanced.py +81 -0
- shape/profile/bounded_dependencies.py +67 -0
- shape/profile/datetime.py +28 -0
- shape/profile/dependence.py +52 -0
- shape/profile/dependencies.py +61 -0
- shape/profile/error.py +22 -0
- shape/profile/numeric.py +104 -0
- shape/profile/reference/__init__.py +13 -0
- shape/profile/reference/column.py +626 -0
- shape/profile/reference/model.py +70 -0
- shape/profile/reference/numerics.py +805 -0
- shape/profile/reference/profile.py +300 -0
- shape/profile/reference/readers.py +152 -0
- shape/profile/reference/sources.py +125 -0
- shape/profile/reference/table.py +328 -0
- shape/profile/semantic_future.py +16 -0
- shape/profile/sketches.py +173 -0
- shape/profile/temporal.py +12 -0
- shape/profile/text.py +37 -0
- shape/profile/text_vectorized.py +49 -0
- shape/py.typed +0 -0
- shape/quality/__init__.py +18 -0
- shape/quality/core.py +39 -0
- shape/quality/infer.py +21 -0
- shape/quality/policy.py +71 -0
- shape/query/__init__.py +3 -0
- shape/query/core.py +75 -0
- shape/registry/__init__.py +2 -0
- shape/registry/local.py +104 -0
- shape/relations/__init__.py +3 -0
- shape/relations/core.py +62 -0
- shape/report/__init__.py +7 -0
- shape/report/html.py +232 -0
- shape/schemas/LOCATION_SPEC.md +3 -0
- shape/schemas/ONE_ZERO_CONTRACT.md +14 -0
- shape/schemas/PACK_SPEC.md +3 -0
- shape/schemas/PLUGIN_PROTOCOL.md +5 -0
- shape/schemas/SHAPE_1_0.md +17 -0
- shape/schemas/SHAPE_1_0_GA.md +49 -0
- shape/schemas/SHAPE_ARTIFACT_SPEC.md +13 -0
- shape/schemas/STREAMING_SEMANTICS.md +3 -0
- shape/schemas/requirements.yaml +719 -0
- shape/schemas/shape-v1-ga.schema.json +83 -0
- shape/schemas/shape-v1.schema.json +82 -0
- shape/security/__init__.py +87 -0
- shape/security/crypto.py +57 -0
- shape/security/hardening.py +100 -0
- shape/security/labels.py +31 -0
- shape/spec/__init__.py +11 -0
- shape/spec/capabilities.py +18 -0
- shape/spec/io.py +35 -0
- shape/spec/migrate.py +13 -0
- shape/spec/model.py +58 -0
- shape/streaming/__init__.py +107 -0
- shape/streaming/aggregate_windows.py +85 -0
- shape/streaming/checkpoint.py +38 -0
- shape/streaming/core.py +47 -0
- shape/streaming/evidence.py +110 -0
- shape/streaming/failure.py +20 -0
- shape/streaming/full_engine.py +72 -0
- shape/streaming/keyed.py +103 -0
- shape/streaming/monitor.py +27 -0
- shape/streaming/online.py +26 -0
- shape/streaming/platinum.py +343 -0
- shape/streaming/vectorized.py +51 -0
- shape/streaming/windows.py +72 -0
- shape/types.py +110 -0
- shape/validation/__init__.py +23 -0
- shape/validation/adversarial.py +35 -0
- shape/validation/conformance.py +24 -0
- shape/validation/fuzz.py +26 -0
- shape/validation/invariants.py +46 -0
- shape/validation/statistics.py +51 -0
- shape/validation/suite.py +36 -0
- sqllocks_shape-0.9.0.dist-info/METADATA +78 -0
- sqllocks_shape-0.9.0.dist-info/RECORD +158 -0
- sqllocks_shape-0.9.0.dist-info/WHEEL +4 -0
- sqllocks_shape-0.9.0.dist-info/entry_points.txt +2 -0
- sqllocks_shape-0.9.0.dist-info/licenses/LICENSE +21 -0
- sqllocks_shape-0.9.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +20 -0
- sqllocks_shape-0.9.0.dist-info/top_level.txt +1 -0
shape/__init__.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Shape: Shape as Code for data behavior."""
|
|
2
|
+
|
|
3
|
+
from .api import (
|
|
4
|
+
certify as certify,
|
|
5
|
+
)
|
|
6
|
+
from .api import (
|
|
7
|
+
check as check,
|
|
8
|
+
)
|
|
9
|
+
from .api import (
|
|
10
|
+
diff as diff,
|
|
11
|
+
)
|
|
12
|
+
from .api import (
|
|
13
|
+
generate as generate,
|
|
14
|
+
)
|
|
15
|
+
from .api import (
|
|
16
|
+
load as load,
|
|
17
|
+
)
|
|
18
|
+
from .api import (
|
|
19
|
+
plan as plan,
|
|
20
|
+
)
|
|
21
|
+
from .api import (
|
|
22
|
+
profile as profile,
|
|
23
|
+
)
|
|
24
|
+
from .api import (
|
|
25
|
+
query as query,
|
|
26
|
+
)
|
|
27
|
+
from .api import (
|
|
28
|
+
save as save,
|
|
29
|
+
)
|
|
30
|
+
from .api import (
|
|
31
|
+
timeline as timeline,
|
|
32
|
+
)
|
|
33
|
+
from .api import (
|
|
34
|
+
view as view,
|
|
35
|
+
)
|
|
36
|
+
from .model import (
|
|
37
|
+
Evidence as Evidence,
|
|
38
|
+
)
|
|
39
|
+
from .model import (
|
|
40
|
+
Provenance as Provenance,
|
|
41
|
+
)
|
|
42
|
+
from .model import (
|
|
43
|
+
Shape as Shape,
|
|
44
|
+
)
|
|
45
|
+
from .model import (
|
|
46
|
+
ShapeBuilder as ShapeBuilder,
|
|
47
|
+
)
|
|
48
|
+
from .security import Sensitivity as Sensitivity
|
|
49
|
+
from .types import (
|
|
50
|
+
FieldType as FieldType,
|
|
51
|
+
)
|
|
52
|
+
from .types import (
|
|
53
|
+
LogicalType as LogicalType,
|
|
54
|
+
)
|
|
55
|
+
from .types import (
|
|
56
|
+
from_arrow_type as from_arrow_type,
|
|
57
|
+
)
|
|
58
|
+
from .types import (
|
|
59
|
+
schema_from_arrow as schema_from_arrow,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
__version__ = "0.9.0"
|
|
63
|
+
__all__ = [
|
|
64
|
+
"Evidence",
|
|
65
|
+
"FieldType",
|
|
66
|
+
"LogicalType",
|
|
67
|
+
"Provenance",
|
|
68
|
+
"Sensitivity",
|
|
69
|
+
"Shape",
|
|
70
|
+
"ShapeBuilder",
|
|
71
|
+
"from_arrow_type",
|
|
72
|
+
"schema_from_arrow",
|
|
73
|
+
"profile",
|
|
74
|
+
"save",
|
|
75
|
+
"load",
|
|
76
|
+
"diff",
|
|
77
|
+
"generate",
|
|
78
|
+
"timeline",
|
|
79
|
+
"view",
|
|
80
|
+
"query",
|
|
81
|
+
"certify",
|
|
82
|
+
"plan",
|
|
83
|
+
"check",
|
|
84
|
+
]
|
shape/api.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Small stable public API for Shape."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import types
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from shape.contracts.v1 import check as check
|
|
10
|
+
from shape.contracts.v1 import diff as diff
|
|
11
|
+
from shape.profile.reference import load as load
|
|
12
|
+
from shape.profile.reference import profile as profile
|
|
13
|
+
from shape.profile.reference import save as save
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def generate(shape: Any, n: Any = None, seed: int = 0, relationships: Any = None) -> Any:
|
|
17
|
+
from shape.generation import generate_from_shape
|
|
18
|
+
|
|
19
|
+
return generate_from_shape(shape, n, seed, relationships)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def timeline(versions: Any) -> Any:
|
|
23
|
+
from shape.generation import ShapeTimeline
|
|
24
|
+
|
|
25
|
+
return ShapeTimeline(versions) # type: ignore[no-untyped-call]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def view(shape: Any) -> Any:
|
|
29
|
+
from shape.query import ShapeView
|
|
30
|
+
|
|
31
|
+
return ShapeView(shape) # type: ignore[no-untyped-call]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def query(shape: Any, expression: Any) -> Any:
|
|
35
|
+
from shape.query import query as _query
|
|
36
|
+
|
|
37
|
+
return _query(shape, expression) # type: ignore[no-untyped-call]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def certify(target: Any, observed: Any, **kwargs: Any) -> Any:
|
|
41
|
+
from shape.generation.fidelity import certify_shapes
|
|
42
|
+
|
|
43
|
+
return certify_shapes(target, observed, **kwargs) # type: ignore[no-untyped-call]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def plan(shape: Any) -> Any:
|
|
47
|
+
from shape.generation.fidelity import plan_reconstruction
|
|
48
|
+
|
|
49
|
+
return plan_reconstruction(shape) # type: ignore[no-untyped-call]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _CallableModule(types.ModuleType):
|
|
53
|
+
"""Makes the legacy ``shape.diff`` subpackage callable.
|
|
54
|
+
|
|
55
|
+
``shape.diff`` is both this API function and an old subpackage. Importing the subpackage
|
|
56
|
+
(``import shape.diff``) rebinds the attribute ``shape.diff`` to the module, which would
|
|
57
|
+
break ``shape.diff(a, b)``. Giving that module a ``__call__`` keeps the call working
|
|
58
|
+
either way. The clash goes away when the legacy package is cut (plan P0-04).
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __call__(self, baseline: Any, current: Any, **kwargs: Any) -> Any:
|
|
62
|
+
return diff(baseline, current, **kwargs)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
importlib.import_module("shape.diff").__class__ = _CallableModule
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from .io import (
|
|
2
|
+
ArtifactError as ArtifactError,
|
|
3
|
+
)
|
|
4
|
+
from .io import (
|
|
5
|
+
read_artifact as read_artifact,
|
|
6
|
+
)
|
|
7
|
+
from .io import (
|
|
8
|
+
write_artifact as write_artifact,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__all__ = ["ArtifactError", "canonical_json", "read_artifact", "write_artifact"]
|
|
12
|
+
from .canonical import canonical_json as canonical_json
|
|
13
|
+
from .migrate import (
|
|
14
|
+
MIGRATIONS as MIGRATIONS,
|
|
15
|
+
)
|
|
16
|
+
from .migrate import (
|
|
17
|
+
Migration as Migration,
|
|
18
|
+
)
|
|
19
|
+
from .migrate import (
|
|
20
|
+
MigrationRegistry as MigrationRegistry,
|
|
21
|
+
)
|
|
22
|
+
from .secure import SecureEnvelope as SecureEnvelope
|
|
23
|
+
from .secure import open_envelope as open_envelope
|
|
24
|
+
from .secure import seal as seal
|
|
25
|
+
from .shape_file import (
|
|
26
|
+
FORMAT as FORMAT,
|
|
27
|
+
)
|
|
28
|
+
from .shape_file import (
|
|
29
|
+
FORMAT_VERSION as FORMAT_VERSION,
|
|
30
|
+
)
|
|
31
|
+
from .shape_file import (
|
|
32
|
+
read_shape as read_shape,
|
|
33
|
+
)
|
|
34
|
+
from .shape_file import (
|
|
35
|
+
write_shape as write_shape,
|
|
36
|
+
)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Deterministic JSON canonicalization subset for Shape manifests.
|
|
2
|
+
|
|
3
|
+
Rejects floats so canonical numeric formatting cannot vary by runtime.
|
|
4
|
+
Evidence requiring floating values must serialize them through explicit typed
|
|
5
|
+
representations before entering the signed manifest.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def canonical_json(value) -> bytes:
|
|
14
|
+
def reject_float(x):
|
|
15
|
+
if isinstance(x, float):
|
|
16
|
+
raise TypeError("floats require typed canonical representation")
|
|
17
|
+
if isinstance(x, dict):
|
|
18
|
+
if any(not isinstance(k, str) for k in x):
|
|
19
|
+
raise TypeError("object keys must be strings")
|
|
20
|
+
return {k: reject_float(v) for k, v in x.items()}
|
|
21
|
+
if isinstance(x, (list, tuple)):
|
|
22
|
+
return [reject_float(v) for v in x]
|
|
23
|
+
if x is None or isinstance(x, (str, int, bool)):
|
|
24
|
+
return x
|
|
25
|
+
raise TypeError(f"unsupported canonical type: {type(x).__name__}")
|
|
26
|
+
|
|
27
|
+
clean = reject_float(value)
|
|
28
|
+
return json.dumps(clean, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
|
|
29
|
+
"utf-8"
|
|
30
|
+
)
|
shape/artifact/io.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import zipfile
|
|
6
|
+
from pathlib import PurePosixPath
|
|
7
|
+
|
|
8
|
+
from shape.errors import ShapeError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ArtifactError(ShapeError):
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def canonical_json(obj) -> bytes:
|
|
16
|
+
return json.dumps(
|
|
17
|
+
obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
18
|
+
).encode()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def sha256(b: bytes) -> str:
|
|
22
|
+
return hashlib.sha256(b).hexdigest()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _safe(n):
|
|
26
|
+
if not isinstance(n, str) or not n or "\x00" in n or "\\" in n:
|
|
27
|
+
return False
|
|
28
|
+
p = PurePosixPath(n)
|
|
29
|
+
if p.is_absolute() or ".." in p.parts or "." in p.parts:
|
|
30
|
+
return False
|
|
31
|
+
if any(not x for x in p.parts):
|
|
32
|
+
return False
|
|
33
|
+
first = p.parts[0]
|
|
34
|
+
if ":" in first:
|
|
35
|
+
return False
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def write_artifact(path, manifest: dict, components: dict[str, bytes]):
|
|
40
|
+
if len(components) > 10000:
|
|
41
|
+
raise ArtifactError("too many components")
|
|
42
|
+
for k in components:
|
|
43
|
+
if not _safe(k) or k == "manifest.json":
|
|
44
|
+
raise ArtifactError("unsafe/reserved component path")
|
|
45
|
+
hashes = {k: sha256(v) for k, v in components.items()}
|
|
46
|
+
m = dict(manifest)
|
|
47
|
+
m["content_hashes"] = hashes
|
|
48
|
+
with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as z:
|
|
49
|
+
z.writestr("manifest.json", canonical_json(m))
|
|
50
|
+
for k, v in sorted(components.items()):
|
|
51
|
+
z.writestr(k, v)
|
|
52
|
+
return m
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def read_artifact(
|
|
56
|
+
path,
|
|
57
|
+
max_member_bytes=512 * 1024 * 1024,
|
|
58
|
+
max_total_bytes=1024 * 1024 * 1024,
|
|
59
|
+
max_ratio=200,
|
|
60
|
+
max_members=10000,
|
|
61
|
+
):
|
|
62
|
+
with zipfile.ZipFile(path) as z:
|
|
63
|
+
infos = z.infolist()
|
|
64
|
+
names = [i.filename for i in infos]
|
|
65
|
+
if len(infos) > max_members:
|
|
66
|
+
raise ArtifactError("too many archive members")
|
|
67
|
+
if len(names) != len(set(names)):
|
|
68
|
+
raise ArtifactError("duplicate archive member")
|
|
69
|
+
if any(not _safe(n) for n in names):
|
|
70
|
+
raise ArtifactError("unsafe archive path")
|
|
71
|
+
if "manifest.json" not in names:
|
|
72
|
+
raise ArtifactError("missing manifest")
|
|
73
|
+
mi = z.getinfo("manifest.json")
|
|
74
|
+
if mi.file_size > 4 * 1024 * 1024:
|
|
75
|
+
raise ArtifactError("manifest too large")
|
|
76
|
+
if mi.compress_size and mi.file_size / mi.compress_size > max_ratio:
|
|
77
|
+
raise ArtifactError("manifest compression ratio limit")
|
|
78
|
+
try:
|
|
79
|
+
rawm = z.read("manifest.json")
|
|
80
|
+
m = json.loads(rawm)
|
|
81
|
+
except Exception as e:
|
|
82
|
+
raise ArtifactError("invalid manifest") from e
|
|
83
|
+
if not isinstance(m, dict):
|
|
84
|
+
raise ArtifactError("manifest must be object")
|
|
85
|
+
hashes = m.get("content_hashes", {})
|
|
86
|
+
if not isinstance(hashes, dict) or len(hashes) > max_members - 1:
|
|
87
|
+
raise ArtifactError("invalid content_hashes")
|
|
88
|
+
if any(
|
|
89
|
+
not isinstance(k, str) or not isinstance(v, str) or not re_full_sha(v)
|
|
90
|
+
for k, v in hashes.items()
|
|
91
|
+
):
|
|
92
|
+
raise ArtifactError("invalid content hash entry")
|
|
93
|
+
expected = {"manifest.json", *hashes.keys()}
|
|
94
|
+
unexpected = set(names) - expected
|
|
95
|
+
if unexpected:
|
|
96
|
+
raise ArtifactError(f"unexpected archive members: {sorted(unexpected)[:3]}")
|
|
97
|
+
total = 0
|
|
98
|
+
out = {}
|
|
99
|
+
for n, h in hashes.items():
|
|
100
|
+
if not _safe(n) or n not in names:
|
|
101
|
+
raise ArtifactError(f"missing/unsafe component {n}")
|
|
102
|
+
i = z.getinfo(n)
|
|
103
|
+
total += i.file_size
|
|
104
|
+
if i.file_size > max_member_bytes or total > max_total_bytes:
|
|
105
|
+
raise ArtifactError("artifact size limit")
|
|
106
|
+
if i.compress_size == 0 and i.file_size > 0:
|
|
107
|
+
raise ArtifactError("invalid compressed member")
|
|
108
|
+
if i.compress_size and i.file_size / i.compress_size > max_ratio:
|
|
109
|
+
raise ArtifactError("compression ratio limit")
|
|
110
|
+
b = z.read(n)
|
|
111
|
+
if len(b) != i.file_size:
|
|
112
|
+
raise ArtifactError("truncated archive member")
|
|
113
|
+
if sha256(b) != h:
|
|
114
|
+
raise ArtifactError(f"checksum mismatch {n}")
|
|
115
|
+
out[n] = b
|
|
116
|
+
return m, out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def re_full_sha(x):
|
|
120
|
+
return len(x) == 64 and all(c in "0123456789abcdef" for c in x.lower())
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Deterministic .shape format migration registry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True, slots=True)
|
|
10
|
+
class Migration:
|
|
11
|
+
source: int
|
|
12
|
+
target: int
|
|
13
|
+
name: str
|
|
14
|
+
fn: Callable[[dict, dict], tuple[dict, dict]]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MigrationRegistry:
|
|
18
|
+
def __init__(self):
|
|
19
|
+
self._m = {}
|
|
20
|
+
|
|
21
|
+
def register(self, source, target, name, fn):
|
|
22
|
+
if target != source + 1:
|
|
23
|
+
raise ValueError("migrations must advance exactly one format version")
|
|
24
|
+
if source in self._m:
|
|
25
|
+
raise ValueError(f"migration already registered from {source}")
|
|
26
|
+
self._m[source] = Migration(source, target, name, fn)
|
|
27
|
+
return fn
|
|
28
|
+
|
|
29
|
+
def path(self, source, target):
|
|
30
|
+
if target < source:
|
|
31
|
+
raise ValueError("downgrade is not supported")
|
|
32
|
+
out = []
|
|
33
|
+
v = source
|
|
34
|
+
while v < target:
|
|
35
|
+
if v not in self._m:
|
|
36
|
+
raise KeyError(f"no migration from format {v}")
|
|
37
|
+
m = self._m[v]
|
|
38
|
+
out.append(m)
|
|
39
|
+
v = m.target
|
|
40
|
+
return tuple(out)
|
|
41
|
+
|
|
42
|
+
def migrate(self, manifest, shape, target):
|
|
43
|
+
m = dict(manifest)
|
|
44
|
+
s = dict(shape)
|
|
45
|
+
applied = []
|
|
46
|
+
for x in self.path(int(m.get("format_version", 1)), target):
|
|
47
|
+
m, s = x.fn(m, s)
|
|
48
|
+
m["format_version"] = x.target
|
|
49
|
+
applied.append(x.name)
|
|
50
|
+
return m, s, tuple(applied)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
MIGRATIONS = MigrationRegistry()
|
shape/artifact/secure.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Signed/encrypted Shape payload envelope."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from shape.artifact.canonical import canonical_json
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True, slots=True)
|
|
13
|
+
class SecureEnvelope:
|
|
14
|
+
header: dict
|
|
15
|
+
nonce: bytes
|
|
16
|
+
ciphertext: bytes
|
|
17
|
+
signature: bytes
|
|
18
|
+
|
|
19
|
+
def to_bytes(self) -> bytes:
|
|
20
|
+
return canonical_json(
|
|
21
|
+
{
|
|
22
|
+
"header": self.header,
|
|
23
|
+
"nonce": base64.b64encode(self.nonce).decode(),
|
|
24
|
+
"ciphertext": base64.b64encode(self.ciphertext).decode(),
|
|
25
|
+
"signature": base64.b64encode(self.signature).decode(),
|
|
26
|
+
}
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def from_bytes(cls, data: bytes):
|
|
31
|
+
o = json.loads(data)
|
|
32
|
+
return cls(
|
|
33
|
+
o["header"],
|
|
34
|
+
base64.b64decode(o["nonce"]),
|
|
35
|
+
base64.b64decode(o["ciphertext"]),
|
|
36
|
+
base64.b64decode(o["signature"]),
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def seal(
|
|
41
|
+
plaintext: bytes, encryption_key: bytes, signing_private_key: bytes, header: dict
|
|
42
|
+
) -> SecureEnvelope:
|
|
43
|
+
from shape.security.crypto import encrypt_aes_gcm, sign_ed25519
|
|
44
|
+
|
|
45
|
+
h = canonical_json(header)
|
|
46
|
+
p = encrypt_aes_gcm(plaintext, encryption_key, h)
|
|
47
|
+
signed = h + p.nonce + p.ciphertext
|
|
48
|
+
return SecureEnvelope(
|
|
49
|
+
dict(header), p.nonce, p.ciphertext, sign_ed25519(signed, signing_private_key)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def open_envelope(env: SecureEnvelope, encryption_key: bytes, signing_public_key: bytes) -> bytes:
|
|
54
|
+
from shape.security.crypto import EncryptedPayload, decrypt_aes_gcm, verify_ed25519
|
|
55
|
+
|
|
56
|
+
h = canonical_json(env.header)
|
|
57
|
+
verify_ed25519(h + env.nonce + env.ciphertext, env.signature, signing_public_key)
|
|
58
|
+
return decrypt_aes_gcm(EncryptedPayload(env.nonce, env.ciphertext), encryption_key, h)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Canonical RC .shape artifact contract."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
|
|
8
|
+
from shape.privacy.policy import LEVELS
|
|
9
|
+
from shape.security import enforce_no_secrets, validate_structure
|
|
10
|
+
|
|
11
|
+
from .io import canonical_json, read_artifact, write_artifact
|
|
12
|
+
|
|
13
|
+
FORMAT = "shape"
|
|
14
|
+
FORMAT_VERSION = 1
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _classification(x):
|
|
18
|
+
x = str(x).upper()
|
|
19
|
+
if x not in LEVELS:
|
|
20
|
+
raise ValueError("unknown classification")
|
|
21
|
+
return x
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def write_shape(
|
|
25
|
+
path, shape: dict, *, name="shape", fidelity="gold", classification="PUBLIC", metadata=None
|
|
26
|
+
):
|
|
27
|
+
classification = _classification(classification)
|
|
28
|
+
validate_structure(shape)
|
|
29
|
+
enforce_no_secrets(shape)
|
|
30
|
+
metadata = metadata or {}
|
|
31
|
+
validate_structure(metadata)
|
|
32
|
+
enforce_no_secrets(metadata)
|
|
33
|
+
body = canonical_json(shape)
|
|
34
|
+
content_id = hashlib.sha256(body).hexdigest()
|
|
35
|
+
manifest = {
|
|
36
|
+
"format": FORMAT,
|
|
37
|
+
"format_version": FORMAT_VERSION,
|
|
38
|
+
"name": str(name),
|
|
39
|
+
"shape_content_id": content_id,
|
|
40
|
+
"fidelity": str(fidelity),
|
|
41
|
+
"classification": classification,
|
|
42
|
+
"metadata": metadata,
|
|
43
|
+
}
|
|
44
|
+
write_artifact(path, manifest, {"shape.json": body})
|
|
45
|
+
return content_id
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def read_shape(path):
|
|
49
|
+
m, c = read_artifact(path)
|
|
50
|
+
if m.get("format") != FORMAT:
|
|
51
|
+
raise ValueError("not a Shape artifact")
|
|
52
|
+
if not isinstance(m.get("format_version"), int):
|
|
53
|
+
raise ValueError("invalid Shape format version")
|
|
54
|
+
if int(m["format_version"]) < 1 or int(m["format_version"]) > FORMAT_VERSION:
|
|
55
|
+
raise ValueError("unsupported Shape artifact version")
|
|
56
|
+
_classification(m.get("classification", "PUBLIC"))
|
|
57
|
+
obj = json.loads(c["shape.json"])
|
|
58
|
+
validate_structure(obj)
|
|
59
|
+
expected = m.get("shape_content_id")
|
|
60
|
+
actual = hashlib.sha256(c["shape.json"]).hexdigest()
|
|
61
|
+
if not isinstance(expected, str) or expected != actual:
|
|
62
|
+
raise ValueError("Shape content identity mismatch")
|
|
63
|
+
return m, obj
|
shape/capture/core.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Bounded single-pass capture."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from shape.profile.error import hll_error, kll_error
|
|
6
|
+
from shape.profile.numeric import NumericProfile
|
|
7
|
+
from shape.profile.text import TextProfile
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class CapturedShape:
|
|
12
|
+
rows: int
|
|
13
|
+
columns: dict
|
|
14
|
+
|
|
15
|
+
def to_dict(self):
|
|
16
|
+
return {"rows": self.rows, "columns": self.columns}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _kind(v):
|
|
20
|
+
return "numeric" if isinstance(v, (int, float)) and not isinstance(v, bool) else "text"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def capture_rows(rows, batch_size=10000):
|
|
24
|
+
if batch_size < 1:
|
|
25
|
+
raise ValueError("batch_size must be positive")
|
|
26
|
+
profiles = {}
|
|
27
|
+
kinds = {}
|
|
28
|
+
count = 0
|
|
29
|
+
for raw in rows:
|
|
30
|
+
row = dict(raw)
|
|
31
|
+
count += 1
|
|
32
|
+
for key, p in list(profiles.items()):
|
|
33
|
+
if key not in row:
|
|
34
|
+
p.update_value(None)
|
|
35
|
+
for key, v in row.items():
|
|
36
|
+
if key not in profiles:
|
|
37
|
+
kinds[key] = _kind(v) if v is not None else "text"
|
|
38
|
+
profiles[key] = NumericProfile() if kinds[key] == "numeric" else TextProfile()
|
|
39
|
+
if count > 1:
|
|
40
|
+
profiles[key].update([None] * (count - 1))
|
|
41
|
+
p = profiles[key]
|
|
42
|
+
if (
|
|
43
|
+
kinds[key] == "numeric"
|
|
44
|
+
and v is not None
|
|
45
|
+
and not (isinstance(v, (int, float)) and not isinstance(v, bool))
|
|
46
|
+
):
|
|
47
|
+
old = p
|
|
48
|
+
np = TextProfile()
|
|
49
|
+
np.count = old.count - 1
|
|
50
|
+
np.null_count = old.null_count
|
|
51
|
+
profiles[key] = p = np
|
|
52
|
+
kinds[key] = "text"
|
|
53
|
+
p.update_value(v)
|
|
54
|
+
cols = {}
|
|
55
|
+
for k, p in profiles.items():
|
|
56
|
+
if kinds[k] == "numeric":
|
|
57
|
+
cols[k] = {
|
|
58
|
+
"kind": "numeric",
|
|
59
|
+
**p.summary(),
|
|
60
|
+
"error_models": {
|
|
61
|
+
"cardinality": hll_error(p.cardinality.p).to_dict(),
|
|
62
|
+
"quantiles": kll_error(p.quantiles.k).to_dict(),
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
else:
|
|
66
|
+
cols[k] = {
|
|
67
|
+
"kind": "text",
|
|
68
|
+
"count": p.count,
|
|
69
|
+
"null_count": p.null_count,
|
|
70
|
+
"length": p.lengths.summary(),
|
|
71
|
+
"distinct_estimate": p.cardinality.estimate(),
|
|
72
|
+
"topk": p.topk.top(10),
|
|
73
|
+
"error_models": {"cardinality": hll_error(p.cardinality.p).to_dict()},
|
|
74
|
+
}
|
|
75
|
+
return CapturedShape(count, cols)
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""High-throughput in-memory columnar profiler.
|
|
2
|
+
Exact NumPy fast path for numeric arrays; reference streaming capture remains bounded-memory."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from shape.profile.error import ErrorModel
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _numeric(a):
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
arr = np.asarray(a)
|
|
13
|
+
if arr.dtype.kind not in "iuf":
|
|
14
|
+
raise TypeError("not numeric")
|
|
15
|
+
n = int(arr.size)
|
|
16
|
+
if arr.dtype.kind == "f":
|
|
17
|
+
nan = int(np.isnan(arr).sum())
|
|
18
|
+
pos = int(np.isposinf(arr).sum())
|
|
19
|
+
neg = int(np.isneginf(arr).sum())
|
|
20
|
+
finite = arr[np.isfinite(arr)]
|
|
21
|
+
else:
|
|
22
|
+
nan = pos = neg = 0
|
|
23
|
+
finite = arr
|
|
24
|
+
nulls = 0
|
|
25
|
+
fc = int(finite.size)
|
|
26
|
+
if fc:
|
|
27
|
+
qs = np.quantile(finite, [0.25, 0.5, 0.75])
|
|
28
|
+
mn = finite.min().item()
|
|
29
|
+
mx = finite.max().item()
|
|
30
|
+
mean = float(finite.mean())
|
|
31
|
+
var = float(finite.var())
|
|
32
|
+
distinct = int(np.unique(finite).size)
|
|
33
|
+
else:
|
|
34
|
+
qs = [None] * 3
|
|
35
|
+
mn = mx = mean = var = None
|
|
36
|
+
distinct = 0
|
|
37
|
+
return {
|
|
38
|
+
"kind": "numeric",
|
|
39
|
+
"count": n,
|
|
40
|
+
"null_count": nulls,
|
|
41
|
+
"nan_count": nan,
|
|
42
|
+
"pos_inf_count": pos,
|
|
43
|
+
"neg_inf_count": neg,
|
|
44
|
+
"finite_count": fc,
|
|
45
|
+
"min": mn,
|
|
46
|
+
"max": mx,
|
|
47
|
+
"mean": mean,
|
|
48
|
+
"variance_population": var,
|
|
49
|
+
"q25": None if qs[0] is None else float(qs[0]),
|
|
50
|
+
"q50": None if qs[1] is None else float(qs[1]),
|
|
51
|
+
"q75": None if qs[2] is None else float(qs[2]),
|
|
52
|
+
"distinct_estimate": distinct,
|
|
53
|
+
"topk": [],
|
|
54
|
+
"error_models": {
|
|
55
|
+
"cardinality": ErrorModel("numpy-unique", True).to_dict(),
|
|
56
|
+
"quantiles": ErrorModel("numpy-quantile", True).to_dict(),
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def capture_columns(columns: dict):
|
|
62
|
+
"""
|
|
63
|
+
Profile equal-length column arrays. This API is optimized for ETL engines that already hold
|
|
64
|
+
columnar batches.
|
|
65
|
+
"""
|
|
66
|
+
if not columns:
|
|
67
|
+
return {"rows": 0, "columns": {}}
|
|
68
|
+
lengths = {len(v) for v in columns.values()}
|
|
69
|
+
if len(lengths) != 1:
|
|
70
|
+
raise ValueError("columns must have equal length")
|
|
71
|
+
n = next(iter(lengths))
|
|
72
|
+
out = {}
|
|
73
|
+
for name, v in columns.items():
|
|
74
|
+
try:
|
|
75
|
+
out[name] = _numeric(v)
|
|
76
|
+
except (TypeError, ValueError):
|
|
77
|
+
# correctness fallback; callers seeking maximum throughput should supply
|
|
78
|
+
# encoded/category arrays.
|
|
79
|
+
from shape.capture import capture_rows
|
|
80
|
+
|
|
81
|
+
out[name] = capture_rows({name: x} for x in v).to_dict()["columns"][name]
|
|
82
|
+
return {"rows": n, "columns": out}
|
shape/cli/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .main import main as main
|