intfile 0.0.5a1__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.
- intfile/__init__.py +103 -0
- intfile/_adapters.py +136 -0
- intfile/_address.py +237 -0
- intfile/_context.py +207 -0
- intfile/_discovery.py +257 -0
- intfile/_file.py +267 -0
- intfile/_frames.py +645 -0
- intfile/_history.py +251 -0
- intfile/_history_store.py +236 -0
- intfile/_kernel.py +108 -0
- intfile/_merge.py +230 -0
- intfile/_model.py +198 -0
- intfile/_navigation_records.py +107 -0
- intfile/_profiles.py +262 -0
- intfile/_result.py +514 -0
- intfile/_rows.py +419 -0
- intfile/_storage.py +169 -0
- intfile/_values.py +293 -0
- intfile/_wire.py +323 -0
- intfile-0.0.5a1.dist-info/METADATA +83 -0
- intfile-0.0.5a1.dist-info/RECORD +23 -0
- intfile-0.0.5a1.dist-info/WHEEL +4 -0
- intfile-0.0.5a1.dist-info/licenses/LICENSE +202 -0
intfile/__init__.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# packages/python/src/intfile/__init__.py
|
|
2
|
+
"""Author, read and version self-contained experimental INT files."""
|
|
3
|
+
|
|
4
|
+
from ._address import JsonPointer, RegionSelector, ResourceAddress, SqliteCell
|
|
5
|
+
from ._discovery import NavigationDefinition, NavigationFact, NavigationMap, NavigationPage
|
|
6
|
+
from ._file import Draft, IntFile, IntFrame, draft, load
|
|
7
|
+
from ._history import (
|
|
8
|
+
Diff,
|
|
9
|
+
HistoryDraft,
|
|
10
|
+
HistoryFile,
|
|
11
|
+
ResourceChange,
|
|
12
|
+
StaleHeadError,
|
|
13
|
+
create,
|
|
14
|
+
)
|
|
15
|
+
from ._history_store import Revision
|
|
16
|
+
from ._merge import (
|
|
17
|
+
MergeBaseError,
|
|
18
|
+
MergeConflict,
|
|
19
|
+
MergeConflictError,
|
|
20
|
+
MergeDescription,
|
|
21
|
+
MergePlan,
|
|
22
|
+
Side,
|
|
23
|
+
)
|
|
24
|
+
from ._model import JSONValue, Kind, Pin, Ref, Resource, UnavailableError
|
|
25
|
+
from ._rows import (
|
|
26
|
+
Aggregate,
|
|
27
|
+
Grouped,
|
|
28
|
+
Row,
|
|
29
|
+
RowFrame,
|
|
30
|
+
collect,
|
|
31
|
+
count,
|
|
32
|
+
count_distinct,
|
|
33
|
+
distinct,
|
|
34
|
+
from_records,
|
|
35
|
+
)
|
|
36
|
+
from ._values import (
|
|
37
|
+
AmbiguousValue,
|
|
38
|
+
Cell,
|
|
39
|
+
CellState,
|
|
40
|
+
Column,
|
|
41
|
+
ComputeError,
|
|
42
|
+
Hop,
|
|
43
|
+
IncompleteScope,
|
|
44
|
+
Path,
|
|
45
|
+
Schema,
|
|
46
|
+
UnsupportedProfile,
|
|
47
|
+
ValueType,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"Aggregate",
|
|
52
|
+
"AmbiguousValue",
|
|
53
|
+
"Cell",
|
|
54
|
+
"CellState",
|
|
55
|
+
"Column",
|
|
56
|
+
"ComputeError",
|
|
57
|
+
"Diff",
|
|
58
|
+
"Draft",
|
|
59
|
+
"Grouped",
|
|
60
|
+
"HistoryDraft",
|
|
61
|
+
"HistoryFile",
|
|
62
|
+
"Hop",
|
|
63
|
+
"IncompleteScope",
|
|
64
|
+
"IntFile",
|
|
65
|
+
"IntFrame",
|
|
66
|
+
"JSONValue",
|
|
67
|
+
"JsonPointer",
|
|
68
|
+
"Kind",
|
|
69
|
+
"MergeBaseError",
|
|
70
|
+
"MergeConflict",
|
|
71
|
+
"MergeConflictError",
|
|
72
|
+
"MergeDescription",
|
|
73
|
+
"MergePlan",
|
|
74
|
+
"NavigationDefinition",
|
|
75
|
+
"NavigationFact",
|
|
76
|
+
"NavigationMap",
|
|
77
|
+
"NavigationPage",
|
|
78
|
+
"Path",
|
|
79
|
+
"Pin",
|
|
80
|
+
"Ref",
|
|
81
|
+
"RegionSelector",
|
|
82
|
+
"Resource",
|
|
83
|
+
"ResourceAddress",
|
|
84
|
+
"ResourceChange",
|
|
85
|
+
"Revision",
|
|
86
|
+
"Row",
|
|
87
|
+
"RowFrame",
|
|
88
|
+
"Schema",
|
|
89
|
+
"Side",
|
|
90
|
+
"SqliteCell",
|
|
91
|
+
"StaleHeadError",
|
|
92
|
+
"UnavailableError",
|
|
93
|
+
"UnsupportedProfile",
|
|
94
|
+
"ValueType",
|
|
95
|
+
"collect",
|
|
96
|
+
"count",
|
|
97
|
+
"count_distinct",
|
|
98
|
+
"create",
|
|
99
|
+
"distinct",
|
|
100
|
+
"draft",
|
|
101
|
+
"from_records",
|
|
102
|
+
"load",
|
|
103
|
+
]
|
intfile/_adapters.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# packages/python/src/intfile/_adapters.py
|
|
2
|
+
"""Detached data exports. Optional dependencies are imported only on requested calls."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
|
|
8
|
+
from ._model import Ref, canonical, ref_record
|
|
9
|
+
from ._values import CellState, Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _path(value):
|
|
13
|
+
return {
|
|
14
|
+
"start": ref_record(value.start),
|
|
15
|
+
"hops": [
|
|
16
|
+
{
|
|
17
|
+
"edge": ref_record(hop.edge),
|
|
18
|
+
"source": ref_record(hop.source),
|
|
19
|
+
"target": ref_record(hop.target),
|
|
20
|
+
"direction": hop.direction,
|
|
21
|
+
}
|
|
22
|
+
for hop in value.hops
|
|
23
|
+
],
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def detached(value, declared=None):
|
|
28
|
+
"""Unambiguous record cell, recursively detached from every native container."""
|
|
29
|
+
if isinstance(value, CellState):
|
|
30
|
+
return {"tag": value.value}
|
|
31
|
+
if isinstance(value, Ref):
|
|
32
|
+
record = ref_record(value)
|
|
33
|
+
return record if declared == "ref" else {"tag": "ref", "value": record}
|
|
34
|
+
if isinstance(value, Path):
|
|
35
|
+
record = _path(value)
|
|
36
|
+
return record if declared == "path" else {"tag": "path", "value": record}
|
|
37
|
+
if isinstance(value, (list, tuple)):
|
|
38
|
+
return {"tag": "list", "value": [detached(x) for x in value]}
|
|
39
|
+
if isinstance(value, Mapping):
|
|
40
|
+
return {"tag": "map", "value": {k: detached(x) for k, x in value.items()}}
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def to_records(frame):
|
|
45
|
+
return [
|
|
46
|
+
{
|
|
47
|
+
col.name: detached(value, col.type)
|
|
48
|
+
for col, value in zip(frame.schema.columns, row, strict=True)
|
|
49
|
+
}
|
|
50
|
+
for row in frame._records
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def to_pandas(frame):
|
|
55
|
+
try:
|
|
56
|
+
import pandas as pd
|
|
57
|
+
except ImportError as exc:
|
|
58
|
+
raise ImportError("to_pandas() requires intfile[pandas]") from exc
|
|
59
|
+
cols = frame.schema.columns
|
|
60
|
+
result = pd.DataFrame(
|
|
61
|
+
to_records(frame),
|
|
62
|
+
columns=[c.name for c in cols],
|
|
63
|
+
index=pd.RangeIndex(frame.count()),
|
|
64
|
+
dtype=object,
|
|
65
|
+
)
|
|
66
|
+
result.attrs["int.schema"] = schema_record(frame.schema)
|
|
67
|
+
return result
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def schema_record(schema):
|
|
71
|
+
return [
|
|
72
|
+
{"name": c.name, "type": c.type, "nullable": c.nullable, "unit": c.unit}
|
|
73
|
+
for c in schema.columns
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def to_arrow(frame):
|
|
78
|
+
try:
|
|
79
|
+
import pyarrow as pa
|
|
80
|
+
except ImportError as exc:
|
|
81
|
+
raise ImportError("to_arrow() requires intfile[arrow]") from exc
|
|
82
|
+
ref = pa.struct(
|
|
83
|
+
[
|
|
84
|
+
pa.field(k, pa.string(), nullable=False)
|
|
85
|
+
for k in ("file_id", "revision_id", "unit_id")
|
|
86
|
+
]
|
|
87
|
+
)
|
|
88
|
+
hop = pa.struct(
|
|
89
|
+
[pa.field(k, ref, nullable=False) for k in ("edge", "source", "target")]
|
|
90
|
+
+ [pa.field("direction", pa.string(), nullable=False)]
|
|
91
|
+
)
|
|
92
|
+
path = pa.struct(
|
|
93
|
+
[
|
|
94
|
+
pa.field("start", ref, nullable=False),
|
|
95
|
+
pa.field("hops", pa.list_(hop), nullable=False),
|
|
96
|
+
]
|
|
97
|
+
)
|
|
98
|
+
physical = {
|
|
99
|
+
"str": pa.string(),
|
|
100
|
+
"bool": pa.bool_(),
|
|
101
|
+
"int": pa.int64(),
|
|
102
|
+
"float": pa.float64(),
|
|
103
|
+
"ref": ref,
|
|
104
|
+
"path": path,
|
|
105
|
+
}
|
|
106
|
+
fields, arrays = [], []
|
|
107
|
+
for index, col in enumerate(frame.schema.columns):
|
|
108
|
+
wrapped = pa.struct(
|
|
109
|
+
[
|
|
110
|
+
pa.field("state", pa.string(), nullable=False),
|
|
111
|
+
pa.field("value", physical.get(col.type, pa.string())),
|
|
112
|
+
]
|
|
113
|
+
)
|
|
114
|
+
metadata = {"int.type": col.type, "int.nullable": str(col.nullable).lower()}
|
|
115
|
+
if col.unit is not None:
|
|
116
|
+
metadata["int.unit"] = col.unit
|
|
117
|
+
fields.append(pa.field(col.name, wrapped, nullable=False, metadata=metadata))
|
|
118
|
+
transport = []
|
|
119
|
+
for row in frame._records:
|
|
120
|
+
cell = row[index]
|
|
121
|
+
if isinstance(cell, CellState):
|
|
122
|
+
transport.append({"state": cell.value, "value": None})
|
|
123
|
+
elif cell is None:
|
|
124
|
+
transport.append({"state": "null", "value": None})
|
|
125
|
+
else:
|
|
126
|
+
value = detached(cell, col.type)
|
|
127
|
+
if col.type not in physical:
|
|
128
|
+
value = canonical(value).decode("utf-8")
|
|
129
|
+
if col.type == "int" and not -(1 << 63) <= value < (1 << 63):
|
|
130
|
+
raise OverflowError(f"{col.name!r} exceeds Arrow int64")
|
|
131
|
+
transport.append({"state": "present", "value": value})
|
|
132
|
+
arrays.append(pa.array(transport, type=wrapped))
|
|
133
|
+
if not fields:
|
|
134
|
+
# Starting with one null column retains row count for a zero-column table.
|
|
135
|
+
return pa.table({"_": pa.nulls(frame.count())}).select([])
|
|
136
|
+
return pa.Table.from_arrays(arrays, schema=pa.schema(fields))
|
intfile/_address.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# packages/python/src/intfile/_address.py
|
|
2
|
+
"""Portable occurrence addresses and verified offline capture bindings."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TYPE_CHECKING, ClassVar, Literal, TypeAlias
|
|
10
|
+
|
|
11
|
+
from ._model import Asset, Pin, Ref, UnavailableError, canonical, parse_json, ref_record, valid_digest
|
|
12
|
+
from ._storage import _fields
|
|
13
|
+
from ._values import UnsupportedProfile
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from ._file import Draft, IntFile
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _name(value: object) -> None:
|
|
20
|
+
if type(value) is not str or not 1 <= len(value) <= 1024:
|
|
21
|
+
raise ValueError("An address name must contain 1 to 1024 characters")
|
|
22
|
+
value.encode("utf-8")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class JsonPointer:
|
|
27
|
+
"""RFC 6901 string coordinates in one immutable JSON capture."""
|
|
28
|
+
|
|
29
|
+
pointer: str
|
|
30
|
+
type: ClassVar[Literal["json-pointer/1"]] = "json-pointer/1"
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
if (type(self.pointer) is not str or len(self.pointer) > 2048
|
|
34
|
+
or re.fullmatch(r"(?:/(?:[^~/]|~[01])*)*", self.pointer) is None):
|
|
35
|
+
raise ValueError("Invalid json-pointer/1 coordinates")
|
|
36
|
+
self.pointer.encode("utf-8")
|
|
37
|
+
|
|
38
|
+
def to_record(self) -> dict:
|
|
39
|
+
return {"type": self.type, "pointer": self.pointer}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class SqliteCell:
|
|
44
|
+
"""One table, declared primary-key value and column in a frozen capture."""
|
|
45
|
+
|
|
46
|
+
table: str
|
|
47
|
+
key_column: str
|
|
48
|
+
key: int | str
|
|
49
|
+
column: str
|
|
50
|
+
type: ClassVar[Literal["sqlite-cell/1"]] = "sqlite-cell/1"
|
|
51
|
+
|
|
52
|
+
def __post_init__(self) -> None:
|
|
53
|
+
for field in (self.table, self.key_column, self.column):
|
|
54
|
+
_name(field)
|
|
55
|
+
if type(self.key) not in (str, int):
|
|
56
|
+
raise ValueError("A sqlite-cell/1 key must be integer or text")
|
|
57
|
+
if isinstance(self.key, str):
|
|
58
|
+
self.key.encode("utf-8")
|
|
59
|
+
|
|
60
|
+
def to_record(self) -> dict:
|
|
61
|
+
return {"type": self.type, "table": self.table, "key_column": self.key_column,
|
|
62
|
+
"key": self.key, "column": self.column}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
RegionSelector: TypeAlias = JsonPointer | SqliteCell
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _selector(record: object) -> RegionSelector:
|
|
69
|
+
if not isinstance(record, dict) or type(record.get("type")) is not str or not record["type"]:
|
|
70
|
+
raise ValueError("Expected a versioned selector")
|
|
71
|
+
if record["type"] == JsonPointer.type:
|
|
72
|
+
fields = _fields(record, "type", "pointer")
|
|
73
|
+
return JsonPointer(fields["pointer"])
|
|
74
|
+
if record["type"] == SqliteCell.type:
|
|
75
|
+
fields = _fields(record, "type", "table", "key_column", "key", "column")
|
|
76
|
+
return SqliteCell(fields["table"], fields["key_column"], fields["key"], fields["column"])
|
|
77
|
+
raise UnsupportedProfile(f"Unsupported selector edition: {record['type']!r}")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class ResourceAddress:
|
|
82
|
+
"""An immutable native Ref, its expected descriptor version and optional coordinates."""
|
|
83
|
+
|
|
84
|
+
ref: Ref
|
|
85
|
+
version_id: str
|
|
86
|
+
selector: RegionSelector | None = None
|
|
87
|
+
|
|
88
|
+
def __post_init__(self) -> None:
|
|
89
|
+
if not isinstance(self.ref, Ref) or not isinstance(self.ref.pin, Pin):
|
|
90
|
+
raise TypeError("A ResourceAddress requires a qualified Ref")
|
|
91
|
+
_name(self.ref.pin.file_id)
|
|
92
|
+
_name(self.ref.unit_id)
|
|
93
|
+
if not valid_digest(self.ref.pin.revision_id) or not valid_digest(self.version_id):
|
|
94
|
+
raise ValueError("Invalid address revision or descriptor version")
|
|
95
|
+
if self.selector is not None and type(self.selector) not in (JsonPointer, SqliteCell):
|
|
96
|
+
raise TypeError("Expected a typed region selector")
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def pin(self) -> Pin:
|
|
100
|
+
return self.ref.pin
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def unit_id(self) -> str:
|
|
104
|
+
return self.ref.unit_id
|
|
105
|
+
|
|
106
|
+
def to_record(self) -> dict:
|
|
107
|
+
record = {**ref_record(self.ref), "version_id": self.version_id}
|
|
108
|
+
if self.selector is not None:
|
|
109
|
+
record["selector"] = self.selector.to_record()
|
|
110
|
+
return record
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def from_record(cls, value: object) -> ResourceAddress:
|
|
114
|
+
required = ("file_id", "revision_id", "unit_id", "version_id")
|
|
115
|
+
keys = (*required, "selector") if isinstance(value, dict) and "selector" in value else required
|
|
116
|
+
record = _fields(value, *keys)
|
|
117
|
+
selector = record.get("selector")
|
|
118
|
+
return cls(Ref(Pin(record["file_id"], record["revision_id"]), record["unit_id"]),
|
|
119
|
+
record["version_id"], None if selector is None else _selector(selector))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def address(file: IntFile, unit_id: str, *, selector: RegionSelector | None = None) -> ResourceAddress:
|
|
123
|
+
descriptor = file.get(unit_id)
|
|
124
|
+
assert file.pin is not None
|
|
125
|
+
return ResourceAddress(Ref(file.pin, unit_id), descriptor.version_id, selector)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _verify(asset: Asset, target: ResourceAddress) -> Asset:
|
|
129
|
+
if asset.descriptor.unit_id != target.unit_id or asset.descriptor.version_id != target.version_id:
|
|
130
|
+
raise UnavailableError("Capture does not match the qualified descriptor version")
|
|
131
|
+
return asset
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _structural_source(copy: Asset, target: ResourceAddress) -> Asset | None:
|
|
135
|
+
# A structural export appends the copied occurrence to the prior origins.
|
|
136
|
+
# Derive its descriptor from the preserved fields and require a hash match.
|
|
137
|
+
# The origin label by itself gives no guarantee about the copied bytes.
|
|
138
|
+
descriptor = copy.descriptor
|
|
139
|
+
if target.ref not in descriptor.origins:
|
|
140
|
+
return None
|
|
141
|
+
prior_origins = descriptor.origins[:descriptor.origins.index(target.ref)]
|
|
142
|
+
original = Asset.build(target.unit_id, descriptor.kind, copy.body, descriptor.links,
|
|
143
|
+
descriptor.dependencies, prior_origins)
|
|
144
|
+
return original if original.descriptor.version_id == target.version_id else None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _capture(file: IntFile, target: ResourceAddress) -> Asset:
|
|
148
|
+
"""Use the loaded backing only. The path may now identify a different file."""
|
|
149
|
+
from ._history import HistoryFile
|
|
150
|
+
|
|
151
|
+
ref = target.ref
|
|
152
|
+
if file.pin is None:
|
|
153
|
+
raise UnavailableError("Reader has no resource backing")
|
|
154
|
+
bound = file if file.pin == ref.pin else None
|
|
155
|
+
if bound is None and isinstance(file, HistoryFile):
|
|
156
|
+
if file.pin.file_id == ref.pin.file_id:
|
|
157
|
+
if ref.pin.revision_id in file._store.revisions:
|
|
158
|
+
bound = file.at(ref.pin.revision_id)
|
|
159
|
+
else:
|
|
160
|
+
# Explicit promotion copies the source snapshot into genesis without
|
|
161
|
+
# altering its descriptor versions. Later branch contents may differ.
|
|
162
|
+
for revision in file._store.revisions.values():
|
|
163
|
+
if revision.source == ref.pin:
|
|
164
|
+
bound = file.at(revision.revision_id)
|
|
165
|
+
promoted = bound._snapshot.assets.get(ref.unit_id)
|
|
166
|
+
# The foreign source pin is a recorded claim. Independent
|
|
167
|
+
# copies retained under that occurrence must agree with it.
|
|
168
|
+
for root in file._store.roots.values():
|
|
169
|
+
retained = root.retained.get(ref)
|
|
170
|
+
if retained is not None and retained != promoted:
|
|
171
|
+
raise UnavailableError("Promoted and retained bindings disagree")
|
|
172
|
+
break
|
|
173
|
+
if bound is not None:
|
|
174
|
+
try:
|
|
175
|
+
return _verify(bound._asset(ref.unit_id), target)
|
|
176
|
+
except KeyError as exc:
|
|
177
|
+
raise UnavailableError("Resource absent at the addressed revision") from exc
|
|
178
|
+
retained = file._snapshot.retained.get(ref)
|
|
179
|
+
if retained is not None:
|
|
180
|
+
return _verify(retained, target)
|
|
181
|
+
|
|
182
|
+
from ._context import Context
|
|
183
|
+
from ._result import source_bindings
|
|
184
|
+
|
|
185
|
+
context = Context((file,))
|
|
186
|
+
for descriptor in file.inventory():
|
|
187
|
+
if ref not in descriptor.origins:
|
|
188
|
+
continue
|
|
189
|
+
# Materialization can remap IDs, links and names inside a scope's body.
|
|
190
|
+
# Walk the verified bindings through each enclosing result. A recovered
|
|
191
|
+
# intermediate descriptor can itself belong to a structural derivative.
|
|
192
|
+
for origin, _, originals in source_bindings(context, Ref(file.pin, descriptor.unit_id)):
|
|
193
|
+
source = originals[origin]
|
|
194
|
+
if origin == ref:
|
|
195
|
+
return _verify(source, target)
|
|
196
|
+
original = _structural_source(source, target)
|
|
197
|
+
if original is not None:
|
|
198
|
+
return original
|
|
199
|
+
original = _structural_source(file._asset(descriptor.unit_id), target)
|
|
200
|
+
if original is not None:
|
|
201
|
+
return original
|
|
202
|
+
raise UnavailableError("No verified backing for the qualified resource")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def read_address(file: IntFile, address: ResourceAddress) -> bytes:
|
|
206
|
+
if not isinstance(address, ResourceAddress):
|
|
207
|
+
raise TypeError("Expected a ResourceAddress")
|
|
208
|
+
asset = _capture(file, address)
|
|
209
|
+
body = asset.read()
|
|
210
|
+
if address.selector is not None:
|
|
211
|
+
raise UnsupportedProfile(f"Reading {address.selector.type} requires an inspection adapter")
|
|
212
|
+
return body
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def validate_region(asset: Asset, retained: Mapping[Ref, Asset]) -> None:
|
|
216
|
+
"""Check a recognized int.region/1 citation against its self-contained source promise."""
|
|
217
|
+
record = _fields(parse_json(asset.read()), "$type", "address")
|
|
218
|
+
if record["$type"] != "int.region/1":
|
|
219
|
+
raise ValueError("Expected an int.region/1 record")
|
|
220
|
+
target = ResourceAddress.from_record(record["address"])
|
|
221
|
+
if target.selector is None or asset.descriptor.links or asset.descriptor.dependencies != (target.ref,):
|
|
222
|
+
raise ValueError("A region requires a selector and its single qualified capture dependency")
|
|
223
|
+
capture = retained.get(target.ref)
|
|
224
|
+
if capture is None:
|
|
225
|
+
raise ValueError("Region is missing its promised capture")
|
|
226
|
+
_verify(capture, target).read()
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def add_region(draft: Draft, capture: IntFile, unit_id: str, *, selector: RegionSelector) -> str:
|
|
230
|
+
target = address(capture, unit_id, selector=selector)
|
|
231
|
+
if target.selector is None:
|
|
232
|
+
raise ValueError("A region citation requires a selector")
|
|
233
|
+
record = {"$type": "int.region/1", "address": target.to_record()}
|
|
234
|
+
# Validate serialization before retaining anything in the mutable draft.
|
|
235
|
+
canonical(record)
|
|
236
|
+
ref = draft.retain(capture, unit_id)
|
|
237
|
+
return draft.add(record, dependencies=(ref,))
|
intfile/_context.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
# packages/python/src/intfile/_context.py
|
|
2
|
+
"""Pinned resource storage and immutable computational ancestry."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from copy import copy
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
|
|
10
|
+
from ._model import Asset, Pin, Ref, ref_record
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from ._file import IntFile
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, eq=False)
|
|
17
|
+
class Step:
|
|
18
|
+
operation: str
|
|
19
|
+
parents: tuple[Step, ...]
|
|
20
|
+
pins: tuple[Pin, ...]
|
|
21
|
+
inputs: tuple[Ref, ...]
|
|
22
|
+
params: dict
|
|
23
|
+
observation: tuple | None = None
|
|
24
|
+
domain_inputs: tuple[Ref, ...] | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Context:
|
|
28
|
+
"""Share backing stores across immutable results; only derivation advances."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, readers: tuple[IntFile, ...] = ()):
|
|
31
|
+
self.readers = {f.pin: f for f in readers if f.pin is not None}
|
|
32
|
+
self._originals: dict[Ref, Asset] = {}
|
|
33
|
+
self._retained: dict[Ref, Asset] = {}
|
|
34
|
+
self.pins = tuple(self.readers)
|
|
35
|
+
self._parents: tuple[Step, ...] = ()
|
|
36
|
+
self._binding_cache = {}
|
|
37
|
+
self.domain_allowed = True
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def terminal(self) -> Step | None:
|
|
41
|
+
return self._parents[0] if len(self._parents) == 1 else None
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_assets(cls, originals, retained, pins, terminal, domain_allowed):
|
|
45
|
+
context = cls()
|
|
46
|
+
context._originals = dict(originals)
|
|
47
|
+
context._retained = dict(retained)
|
|
48
|
+
context.pins = tuple(dict.fromkeys(pins))
|
|
49
|
+
context._parents = (terminal,)
|
|
50
|
+
context.domain_allowed = domain_allowed
|
|
51
|
+
return context
|
|
52
|
+
|
|
53
|
+
def complete(self, pin):
|
|
54
|
+
return pin in self.readers
|
|
55
|
+
|
|
56
|
+
def refs(self, pin=None):
|
|
57
|
+
found = {}
|
|
58
|
+
for key, file in self.readers.items():
|
|
59
|
+
if pin is None or key == pin:
|
|
60
|
+
found.update((Ref(key, unit), None) for unit in file._snapshot.assets)
|
|
61
|
+
found.update(
|
|
62
|
+
(ref, None)
|
|
63
|
+
for ref in self._originals
|
|
64
|
+
if (ref.pin in self.pins if pin is None else ref.pin == pin)
|
|
65
|
+
)
|
|
66
|
+
return tuple(found)
|
|
67
|
+
|
|
68
|
+
def asset(self, ref):
|
|
69
|
+
if not isinstance(ref, Ref):
|
|
70
|
+
raise TypeError("Expected a qualified Ref")
|
|
71
|
+
reader = self.readers.get(ref.pin)
|
|
72
|
+
if reader is not None and ref.unit_id in reader._snapshot.assets:
|
|
73
|
+
return reader._asset(ref.unit_id)
|
|
74
|
+
if ref in self._originals:
|
|
75
|
+
return self._originals[ref]
|
|
76
|
+
if ref in self._retained:
|
|
77
|
+
return self._retained[ref]
|
|
78
|
+
for reader in self.readers.values():
|
|
79
|
+
if ref in reader._snapshot.retained:
|
|
80
|
+
return reader._snapshot.retained[ref]
|
|
81
|
+
raise KeyError(ref)
|
|
82
|
+
|
|
83
|
+
def combine(self, other):
|
|
84
|
+
new = Context(tuple(self.readers.values()) + tuple(other.readers.values()))
|
|
85
|
+
for table_name in ("_originals", "_retained"):
|
|
86
|
+
merged = dict(getattr(self, table_name))
|
|
87
|
+
for ref, asset in getattr(other, table_name).items():
|
|
88
|
+
if ref in merged and merged[ref] != asset:
|
|
89
|
+
raise ValueError("Conflicting evidence at one qualified address")
|
|
90
|
+
merged[ref] = asset
|
|
91
|
+
setattr(new, table_name, merged)
|
|
92
|
+
new.pins = tuple(dict.fromkeys((*self.pins, *other.pins)))
|
|
93
|
+
new.domain_allowed = self.domain_allowed and other.domain_allowed
|
|
94
|
+
new._parents = (*self._parents, *other._parents)
|
|
95
|
+
return new
|
|
96
|
+
|
|
97
|
+
def step(
|
|
98
|
+
self,
|
|
99
|
+
operation,
|
|
100
|
+
*,
|
|
101
|
+
inputs=(),
|
|
102
|
+
params=None,
|
|
103
|
+
observation=None,
|
|
104
|
+
pins=None,
|
|
105
|
+
domain_inputs=None,
|
|
106
|
+
):
|
|
107
|
+
new = copy(self)
|
|
108
|
+
if pins is not None:
|
|
109
|
+
new.pins = tuple(pins)
|
|
110
|
+
new._parents = (
|
|
111
|
+
Step(
|
|
112
|
+
operation,
|
|
113
|
+
self._parents,
|
|
114
|
+
self.pins if pins is None else tuple(pins),
|
|
115
|
+
tuple(inputs),
|
|
116
|
+
{} if params is None else params,
|
|
117
|
+
observation,
|
|
118
|
+
None if domain_inputs is None else tuple(domain_inputs),
|
|
119
|
+
),
|
|
120
|
+
)
|
|
121
|
+
if operation == "int.from_records@1":
|
|
122
|
+
new.domain_allowed = False
|
|
123
|
+
return new
|
|
124
|
+
|
|
125
|
+
def selection_snapshot(self, witnesses, refs, *, semantic):
|
|
126
|
+
scope = copy(self)
|
|
127
|
+
scope._parents = ()
|
|
128
|
+
params = {"count": len(refs)}
|
|
129
|
+
if semantic:
|
|
130
|
+
params["semantic_members"] = [ref_record(ref) for ref in refs]
|
|
131
|
+
return scope.step(
|
|
132
|
+
"int.selection_snapshot@1",
|
|
133
|
+
inputs=dict.fromkeys((*refs, *witnesses)),
|
|
134
|
+
params=params,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def _binding(self, record):
|
|
138
|
+
if record not in self._binding_cache:
|
|
139
|
+
from ._result import original_binding
|
|
140
|
+
|
|
141
|
+
self._binding_cache[record] = original_binding(self, record)
|
|
142
|
+
return self._binding_cache[record]
|
|
143
|
+
|
|
144
|
+
def captured_semantics(self):
|
|
145
|
+
from ._storage import _ref
|
|
146
|
+
from ._wire import ordered_steps
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
_ref(address)
|
|
150
|
+
for parent in self._parents
|
|
151
|
+
for step in ordered_steps(parent)
|
|
152
|
+
if step.operation == "int.selection_snapshot@1"
|
|
153
|
+
for address in step.params.get("semantic_members", ())
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
def property_observed(self, subject, key):
|
|
157
|
+
if self.complete(subject.pin) or subject in self.captured_semantics():
|
|
158
|
+
return True
|
|
159
|
+
from ._wire import ordered_steps
|
|
160
|
+
|
|
161
|
+
address = ref_record(subject)
|
|
162
|
+
return any(
|
|
163
|
+
address in step.params.get("property_subjects", {}).get(key, ())
|
|
164
|
+
for parent in self._parents
|
|
165
|
+
for step in ordered_steps(parent)
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def observed_adjacencies(self, predicate, direction):
|
|
169
|
+
"""Recover only those bounded expansions witnessed for all missing graph scopes."""
|
|
170
|
+
from ._storage import _ref
|
|
171
|
+
from ._wire import ordered_steps
|
|
172
|
+
|
|
173
|
+
missing = set(self.pins) - self.readers.keys()
|
|
174
|
+
if not missing:
|
|
175
|
+
return None
|
|
176
|
+
observed = {}
|
|
177
|
+
for parent in self._parents:
|
|
178
|
+
for step in ordered_steps(parent):
|
|
179
|
+
if (
|
|
180
|
+
step.operation == "int.follow@1"
|
|
181
|
+
and step.params.get("predicate") == predicate
|
|
182
|
+
and step.params.get("direction") == direction
|
|
183
|
+
):
|
|
184
|
+
for address in step.params.get("expanded", ()):
|
|
185
|
+
observed.setdefault(_ref(address), set()).update(step.pins)
|
|
186
|
+
return {node for node, pins in observed.items() if missing <= pins}
|
|
187
|
+
|
|
188
|
+
def local_endpoint(self, record, endpoint):
|
|
189
|
+
binding = self._binding(record)
|
|
190
|
+
if binding and endpoint in binding[1]:
|
|
191
|
+
return Ref(record.pin, binding[1][endpoint])
|
|
192
|
+
return endpoint
|
|
193
|
+
|
|
194
|
+
def record_subject(self, record, original_id, position):
|
|
195
|
+
resource = self.asset(record).descriptor
|
|
196
|
+
if position >= len(resource.links):
|
|
197
|
+
raise ValueError("Missing structural endpoint in profile descriptor")
|
|
198
|
+
local = Ref(record.pin, resource.links[position])
|
|
199
|
+
if original_id == local.unit_id:
|
|
200
|
+
return local
|
|
201
|
+
binding = self._binding(record)
|
|
202
|
+
if (
|
|
203
|
+
binding
|
|
204
|
+
and binding[1].get(Ref(binding[0].pin, original_id)) == local.unit_id
|
|
205
|
+
):
|
|
206
|
+
return local
|
|
207
|
+
raise ValueError("Profile endpoint disagrees with its local source binding")
|