kraph 7.1.1__tar.gz → 7.2.1__tar.gz

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.
Files changed (32) hide show
  1. {kraph-7.1.1 → kraph-7.2.1}/.gitignore +4 -1
  2. {kraph-7.1.1 → kraph-7.2.1}/PKG-INFO +2 -2
  3. {kraph-7.1.1 → kraph-7.2.1}/kraph/__init__.py +1 -3
  4. kraph-7.2.1/kraph/_tested.json +1 -0
  5. {kraph-7.1.1 → kraph-7.2.1}/kraph/arkitekt.py +61 -25
  6. {kraph-7.1.1 → kraph-7.2.1}/kraph/datalayer.py +11 -4
  7. {kraph-7.1.1 → kraph-7.2.1}/kraph/io/download.py +27 -6
  8. {kraph-7.1.1 → kraph-7.2.1}/kraph/io/obstore.py +20 -6
  9. {kraph-7.1.1 → kraph-7.2.1}/kraph/io/upload.py +30 -8
  10. {kraph-7.1.1 → kraph-7.2.1}/kraph/kraph.py +12 -8
  11. {kraph-7.1.1 → kraph-7.2.1}/kraph/links/upload.py +0 -1
  12. {kraph-7.1.1 → kraph-7.2.1}/kraph/middleware/base.py +3 -3
  13. {kraph-7.1.1 → kraph-7.2.1}/kraph/middleware/upload.py +63 -15
  14. {kraph-7.1.1 → kraph-7.2.1}/kraph/pairs.py +25 -7
  15. {kraph-7.1.1 → kraph-7.2.1}/kraph/rath.py +9 -5
  16. {kraph-7.1.1 → kraph-7.2.1}/kraph/refs.py +1 -1
  17. {kraph-7.1.1 → kraph-7.2.1}/kraph/scalars.py +12 -4
  18. {kraph-7.1.1 → kraph-7.2.1}/kraph/traits.py +93 -25
  19. {kraph-7.1.1 → kraph-7.2.1}/pyproject.toml +11 -43
  20. {kraph-7.1.1 → kraph-7.2.1}/README.md +0 -0
  21. {kraph-7.1.1 → kraph-7.2.1}/kraph/api/__init__.py +0 -0
  22. {kraph-7.1.1 → kraph-7.2.1}/kraph/api/project.json +0 -0
  23. {kraph-7.1.1 → kraph-7.2.1}/kraph/api/schema.graphql +0 -0
  24. {kraph-7.1.1 → kraph-7.2.1}/kraph/api/schema.py +0 -0
  25. {kraph-7.1.1 → kraph-7.2.1}/kraph/client.py +0 -0
  26. {kraph-7.1.1 → kraph-7.2.1}/kraph/contrib/fakts/__init__.py +0 -0
  27. {kraph-7.1.1 → kraph-7.2.1}/kraph/errors.py +0 -0
  28. {kraph-7.1.1 → kraph-7.2.1}/kraph/io/__init__.py +0 -0
  29. {kraph-7.1.1 → kraph-7.2.1}/kraph/links/__init__.py +0 -0
  30. {kraph-7.1.1 → kraph-7.2.1}/kraph/links/errors.py +0 -0
  31. {kraph-7.1.1 → kraph-7.2.1}/kraph/middleware/__init__.py +0 -0
  32. {kraph-7.1.1 → kraph-7.2.1}/kraph/py.typed +0 -0
@@ -144,4 +144,7 @@ cython_debug/
144
144
  media
145
145
  export
146
146
  static_collected
147
- data
147
+ data
148
+
149
+ # The server version the integration tests ran against, stamped into a release.
150
+ kraph/_tested.json
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: kraph
3
- Version: 7.1.1
3
+ Version: 7.2.1
4
4
  Summary: the arkitekt knowledge graph
5
5
  Author-email: jhnnsrs <jhnnsrs@gmail.com>
6
6
  License-Expression: GPL-3.0-or-later
7
7
  Requires-Python: <4.0,>=3.11
8
- Requires-Dist: arkitekt-spec>=5.0
8
+ Requires-Dist: arkitekt-spec>=12.9
9
9
  Requires-Dist: dokker>=2.8
10
10
  Requires-Dist: fakts>=6.1
11
11
  Requires-Dist: obstore>=0.11.0
@@ -1,7 +1,5 @@
1
- from .kraph import Kraph
2
-
3
-
4
1
  # The service is declared with arkitekt-spec, a core dependency: it is always there.
5
2
  from .arkitekt import kraph as kraph_service
3
+ from .kraph import Kraph
6
4
 
7
5
  __all__ = ["Kraph", "kraph_service"]
@@ -0,0 +1 @@
1
+ {"version": "7.7.1"}
@@ -25,9 +25,11 @@ table-query surface.
25
25
  import os
26
26
  from typing import Annotated
27
27
 
28
+ from arkitekt_spec.declare.app import AppRegistry
29
+ from arkitekt_spec.declare.tested import tested_against
30
+ from arkitekt_spec.declare.widgets import SearchWidget
28
31
  from fakts import Alias, Require, TokenLoader
29
32
  from fakts.contrib.rath.auth import FaktsAuthLink
30
- from graphql import OperationType
31
33
  from rath.links import compose
32
34
  from rath.links.aiohttp import AIOHttpLink
33
35
  from rath.links.dictinglink import DictingLink
@@ -35,12 +37,11 @@ from rath.links.graphql_ws import GraphQLWSLink
35
37
  from rath.links.shrink import ShrinkingLink
36
38
  from rath.links.split import SplitLink
37
39
 
38
- from arkitekt_spec.declare.app import AppRegistry
39
- from arkitekt_spec.declare.widgets import SearchWidget
40
-
40
+ from graphql import OperationType
41
41
  from kraph.api.schema import (
42
42
  EntityCategory,
43
43
  Graph,
44
+ GraphPairsQuery,
44
45
  Instance,
45
46
  Link,
46
47
  MeasurementCategory,
@@ -48,17 +49,16 @@ from kraph.api.schema import (
48
49
  MetricKind,
49
50
  Model,
50
51
  NaturalEventCategory,
51
- GraphPairsQuery,
52
52
  PairsQueryRun,
53
53
  ProtocolEventCategory,
54
54
  RelationCategory,
55
55
  SearchEntityCategoriesQuery,
56
+ SearchGraphPairsQueriesQuery,
56
57
  SearchGraphsQuery,
57
58
  SearchMeasurementCategoriesQuery,
58
59
  SearchMetricKindsQuery,
59
60
  SearchModelsQuery,
60
61
  SearchNaturalEventCategoriesQuery,
61
- SearchGraphPairsQueriesQuery,
62
62
  SearchPairsQueryRunsQuery,
63
63
  SearchProtocolEventCategoriesQuery,
64
64
  SearchRelationCategoriesQuery,
@@ -71,7 +71,6 @@ from kraph.api.schema import (
71
71
  StructureRelationCategory,
72
72
  Term,
73
73
  )
74
-
75
74
  from kraph.datalayer import DataLayer
76
75
  from kraph.kraph import Kraph
77
76
  from kraph.links.upload import UploadLink
@@ -88,6 +87,10 @@ registry = AppRegistry()
88
87
  """What kraph brings to an app: its service, and the types it can send by id."""
89
88
 
90
89
 
90
+ TESTED = tested_against("kraph")
91
+ """The kraph server this release wants: the one its release job tested it against."""
92
+
93
+
91
94
  @registry.service(
92
95
  schema=build_relative_path("api", "schema.graphql"),
93
96
  turms=build_relative_path("api", "project.json"),
@@ -95,11 +98,17 @@ registry = AppRegistry()
95
98
  def kraph(
96
99
  kraph: Annotated[
97
100
  Alias,
98
- Require("live.arkitekt.kraph", "Where the knowledge graph relating entities lives"),
101
+ Require(
102
+ "live.arkitekt.kraph",
103
+ "Where the knowledge graph relating entities lives",
104
+ version=TESTED,
105
+ ),
99
106
  ],
100
107
  datalayer: Annotated[
101
108
  Alias | None,
102
- Require("live.arkitekt.s3", "Where the graph's files are stored", optional=True),
109
+ Require(
110
+ "live.arkitekt.s3", "Where the graph's files are stored", optional=True
111
+ ),
103
112
  ],
104
113
  tokens: TokenLoader,
105
114
  ) -> Kraph:
@@ -120,11 +129,19 @@ def kraph(
120
129
  FaktsAuthLink(token_loader=tokens),
121
130
  UploadLink(datalayer=store),
122
131
  SplitLink(
123
- left=AIOHttpLink(endpoint_url=kraph.to_http_path("graphql"), proxy=kraph.proxy, ssl_context=kraph.ssl_context()),
124
- right=GraphQLWSLink(ws_endpoint_url=kraph.to_ws_path("graphql"), proxy=kraph.proxy, ssl_context=kraph.ssl_context()),
132
+ left=AIOHttpLink(
133
+ endpoint_url=kraph.to_http_path("graphql"),
134
+ proxy=kraph.proxy,
135
+ ssl_context=kraph.ssl_context(),
136
+ ),
137
+ right=GraphQLWSLink(
138
+ ws_endpoint_url=kraph.to_ws_path("graphql"),
139
+ proxy=kraph.proxy,
140
+ ssl_context=kraph.ssl_context(),
141
+ ),
125
142
  split=lambda o: o.node.operation != OperationType.SUBSCRIPTION,
126
143
  ),
127
- )
144
+ ),
128
145
  ),
129
146
  datalayer=store,
130
147
  )
@@ -144,14 +161,16 @@ async def expand_graph(id: str, kraph: Kraph) -> Graph:
144
161
  return await kraph.aget_graph(id)
145
162
 
146
163
 
147
- @registry.structure("@kraph/entitycategory", widget=_search(SearchEntityCategoriesQuery)
164
+ @registry.structure(
165
+ "@kraph/entitycategory", widget=_search(SearchEntityCategoriesQuery)
148
166
  )
149
167
  async def expand_entity_category(id: str, kraph: Kraph) -> EntityCategory:
150
168
  """An entity category, by id."""
151
169
  return await kraph.aget_entity_category(id)
152
170
 
153
171
 
154
- @registry.structure("@kraph/relationcategory",
172
+ @registry.structure(
173
+ "@kraph/relationcategory",
155
174
  widget=_search(SearchRelationCategoriesQuery),
156
175
  )
157
176
  async def expand_relation_category(id: str, kraph: Kraph) -> RelationCategory:
@@ -159,7 +178,8 @@ async def expand_relation_category(id: str, kraph: Kraph) -> RelationCategory:
159
178
  return await kraph.aget_relation_category(id)
160
179
 
161
180
 
162
- @registry.structure("@kraph/measurementcategory",
181
+ @registry.structure(
182
+ "@kraph/measurementcategory",
163
183
  widget=_search(SearchMeasurementCategoriesQuery),
164
184
  )
165
185
  async def expand_measurement_category(id: str, kraph: Kraph) -> MeasurementCategory:
@@ -167,7 +187,8 @@ async def expand_measurement_category(id: str, kraph: Kraph) -> MeasurementCateg
167
187
  return await kraph.aget_measurement_category(id)
168
188
 
169
189
 
170
- @registry.structure("@kraph/structurerelationcategory",
190
+ @registry.structure(
191
+ "@kraph/structurerelationcategory",
171
192
  widget=_search(SearchStructureRelationCategoriesQuery),
172
193
  )
173
194
  async def expand_structure_relation_category(
@@ -177,7 +198,8 @@ async def expand_structure_relation_category(
177
198
  return await kraph.aget_structure_relation_category(id)
178
199
 
179
200
 
180
- @registry.structure("@kraph/naturaleventcategory",
201
+ @registry.structure(
202
+ "@kraph/naturaleventcategory",
181
203
  widget=_search(SearchNaturalEventCategoriesQuery),
182
204
  )
183
205
  async def expand_natural_event_category(id: str, kraph: Kraph) -> NaturalEventCategory:
@@ -185,16 +207,20 @@ async def expand_natural_event_category(id: str, kraph: Kraph) -> NaturalEventCa
185
207
  return await kraph.aget_natural_event_category(id)
186
208
 
187
209
 
188
- @registry.structure("@kraph/protocoleventcategory",
210
+ @registry.structure(
211
+ "@kraph/protocoleventcategory",
189
212
  widget=_search(SearchProtocolEventCategoriesQuery),
190
213
  )
191
- async def expand_protocol_event_category(id: str, kraph: Kraph) -> ProtocolEventCategory:
214
+ async def expand_protocol_event_category(
215
+ id: str, kraph: Kraph
216
+ ) -> ProtocolEventCategory:
192
217
  """A protocol event category, by id."""
193
218
  return await kraph.aget_protocol_event_category(id)
194
219
 
195
220
 
196
221
  # --- claims ----------------------------------------------------------------------
197
222
 
223
+
198
224
  # `Instance` has no scalar label -- its name lives at `term { key }` -- so it gets no
199
225
  # search widget: a two-field `value`/`label` projection cannot reach it.
200
226
  @registry.structure("@kraph/entity")
@@ -231,7 +257,8 @@ async def expand_term(id: str, kraph: Kraph) -> Term:
231
257
 
232
258
 
233
259
  # Identifier kept for wire compatibility; the type behind it is now StructureKind.
234
- @registry.structure("@kraph/structurecategory", widget=_search(SearchStructureKindsQuery)
260
+ @registry.structure(
261
+ "@kraph/structurecategory", widget=_search(SearchStructureKindsQuery)
235
262
  )
236
263
  async def expand_structure_kind(id: str, kraph: Kraph) -> StructureKind:
237
264
  """A structure kind, by id -- it travels as `@kraph/structurecategory`."""
@@ -239,8 +266,7 @@ async def expand_structure_kind(id: str, kraph: Kraph) -> StructureKind:
239
266
 
240
267
 
241
268
  # Identifier kept for wire compatibility; the type behind it is now MetricKind.
242
- @registry.structure("@kraph/metriccategory", widget=_search(SearchMetricKindsQuery)
243
- )
269
+ @registry.structure("@kraph/metriccategory", widget=_search(SearchMetricKindsQuery))
244
270
  async def expand_metric_kind(id: str, kraph: Kraph) -> MetricKind:
245
271
  """A metric kind, by id -- it travels as `@kraph/metriccategory`."""
246
272
  return await kraph.aget_metric_kind(id)
@@ -261,7 +287,11 @@ def describe_pairs_query(query: GraphPairsQuery) -> dict:
261
287
 
262
288
  # The search widgets forward a port's `requires` ($requires), so a picker for a typed port
263
289
  # offers only the queries and runs that port accepts.
264
- @registry.structure("@kraph/pairsquery", widget=_search(SearchGraphPairsQueriesQuery), describe=describe_pairs_query)
290
+ @registry.structure(
291
+ "@kraph/pairsquery",
292
+ widget=_search(SearchGraphPairsQueriesQuery),
293
+ describe=describe_pairs_query,
294
+ )
265
295
  async def expand_pairs_query(id: str, kraph: Kraph) -> GraphPairsQuery:
266
296
  """A pairs query, by id: an insight over a view that selects pairs from its drawing."""
267
297
  return await kraph.aget_graph_pairs_query(id)
@@ -272,7 +302,11 @@ def describe_pairs_run(run: PairsQueryRun) -> dict:
272
302
  return dict(run.descriptors or {})
273
303
 
274
304
 
275
- @registry.structure("@kraph/pairsrun", widget=_search(SearchPairsQueryRunsQuery), describe=describe_pairs_run)
305
+ @registry.structure(
306
+ "@kraph/pairsrun",
307
+ widget=_search(SearchPairsQueryRunsQuery),
308
+ describe=describe_pairs_run,
309
+ )
276
310
  async def expand_pairs_run(id: str, kraph: Kraph) -> PairsQueryRun:
277
311
  """A run, by id: a pairs query's answer stored with where the drawing stood."""
278
312
  return await kraph.aget_pairs_query_run(id)
@@ -288,7 +322,9 @@ def describe_model(model: Model) -> dict:
288
322
  return dict(model.descriptors or {})
289
323
 
290
324
 
291
- @registry.structure("@kraph/model", widget=_search(SearchModelsQuery), describe=describe_model)
325
+ @registry.structure(
326
+ "@kraph/model", widget=_search(SearchModelsQuery), describe=describe_model
327
+ )
292
328
  async def expand_model(id: str, kraph: Kraph) -> Model:
293
329
  """A trained model, by id: its weights and the pairs query run it learned from."""
294
330
  return await kraph.aget_model(id)
@@ -33,9 +33,13 @@ Example:
33
33
 
34
34
  import ssl
35
35
  from types import TracebackType
36
+ from typing import TypeVar
37
+
36
38
  from fakts import Alias
37
39
  from koil.composition import KoiledModel
38
40
 
41
+ _DataLayer = TypeVar("_DataLayer", bound="DataLayer")
42
+
39
43
 
40
44
  class DataLayer(KoiledModel):
41
45
  """Implements a S3 DataLayer
@@ -67,8 +71,11 @@ class DataLayer(KoiledModel):
67
71
  pinned, the public roots otherwise."""
68
72
  from arkitekt_spec.declare import tls
69
73
 
70
- return tls.pinned_context(self.certificates) if self.certificates else tls.default_context()
71
-
74
+ return (
75
+ tls.pinned_context(self.certificates)
76
+ if self.certificates
77
+ else tls.default_context()
78
+ )
72
79
 
73
80
  @classmethod
74
81
  def from_alias(cls, alias: "Alias") -> "DataLayer":
@@ -88,10 +95,10 @@ class DataLayer(KoiledModel):
88
95
  certificates=list(alias.certificates) if alias.is_pinned() else [],
89
96
  )
90
97
 
91
- async def get_endpoint_url(self):
98
+ async def get_endpoint_url(self) -> str:
92
99
  return self.endpoint_url
93
100
 
94
- async def __aenter__(self):
101
+ async def __aenter__(self: _DataLayer) -> _DataLayer:
95
102
  """Enter the DataLayer context.
96
103
 
97
104
  Entering does not make it "the current datalayer", and kraph never looks one up: downloads go
@@ -4,6 +4,7 @@ Both clients are the ones the object was fetched with (``client_of``): the kraph
4
4
  for the grant, and its datalayer, which says where the store is. Nothing is looked up.
5
5
  """
6
6
 
7
+ import asyncio
7
8
  from pathlib import Path
8
9
  from typing import TYPE_CHECKING, Any
9
10
 
@@ -24,8 +25,15 @@ def download_bigfile(store_id: str, file_name: str, kraph: "Kraph") -> str:
24
25
  """Stream the big file in ``store_id`` to ``file_name``. Returns the path written."""
25
26
  from kraph.api.schema import RequestBigFileAccessInput
26
27
 
27
- grant = kraph.request_bigfile_access(input=RequestBigFileAccessInput(store_id=store_id))
28
- store = create_s3_store(kraph.datalayer.endpoint_url, grant, proxy=kraph.datalayer.proxy, certificates=kraph.datalayer.certificates)
28
+ grant = kraph.request_bigfile_access(
29
+ input=RequestBigFileAccessInput(store_id=store_id)
30
+ )
31
+ store = create_s3_store(
32
+ kraph.datalayer.endpoint_url,
33
+ grant,
34
+ proxy=kraph.datalayer.proxy,
35
+ certificates=kraph.datalayer.certificates,
36
+ )
29
37
  response = obstore.get(store, grant.key)
30
38
  with open(_target(file_name), "wb") as file:
31
39
  for chunk in response.stream():
@@ -37,10 +45,19 @@ async def adownload_bigfile(store_id: str, file_name: str, kraph: "Kraph") -> st
37
45
  """Stream the big file in ``store_id`` to ``file_name``. Returns the path written."""
38
46
  from kraph.api.schema import RequestBigFileAccessInput
39
47
 
40
- grant = await kraph.arequest_bigfile_access(input=RequestBigFileAccessInput(store_id=store_id))
41
- store = create_s3_store(await kraph.datalayer.get_endpoint_url(), grant, proxy=kraph.datalayer.proxy, certificates=kraph.datalayer.certificates)
48
+ grant = await kraph.arequest_bigfile_access(
49
+ input=RequestBigFileAccessInput(store_id=store_id)
50
+ )
51
+ store = create_s3_store(
52
+ await kraph.datalayer.get_endpoint_url(),
53
+ grant,
54
+ proxy=kraph.datalayer.proxy,
55
+ certificates=kraph.datalayer.certificates,
56
+ )
42
57
  response = await obstore.get_async(store, grant.key)
43
- with open(_target(file_name), "wb") as file:
58
+ # Opened off the loop; the writes are of chunks already in memory.
59
+ file = await asyncio.to_thread(open, _target(file_name), "wb")
60
+ with file:
44
61
  async for chunk in response.stream():
45
62
  file.write(chunk)
46
63
  return file_name
@@ -48,4 +65,8 @@ async def adownload_bigfile(store_id: str, file_name: str, kraph: "Kraph") -> st
48
65
 
49
66
  def file_name_of(store: Any, file_name: str | None) -> str: # noqa: ANN401
50
67
  """Where a download lands: the name asked for, else the uploaded file's own name, else its key's last part."""
51
- return file_name or getattr(store, "original_file_name", None) or str(store.key).rsplit("/", 1)[-1]
68
+ return (
69
+ file_name
70
+ or getattr(store, "original_file_name", None)
71
+ or str(store.key).rsplit("/", 1)[-1]
72
+ )
@@ -40,7 +40,9 @@ class S3UploadGrantLike(Protocol):
40
40
  #: Called with the store id; returns a new grant for the *same* key. A context variable rather
41
41
  #: than a parameter because the store is built several calls down, in every writer the
42
42
  #: middleware drives, and the refresher is the middleware's to know about.
43
- upload_refresher: ContextVar["Callable[[str], S3UploadGrantLike] | None"] = ContextVar("upload_refresher", default=None)
43
+ upload_refresher: ContextVar["Callable[[str], S3UploadGrantLike] | None"] = ContextVar(
44
+ "upload_refresher", default=None
45
+ )
44
46
 
45
47
  #: How long before a grant runs out a fresh one is asked for. obstore asks its credential
46
48
  #: provider again shortly before the expiry it reported; refreshing a little earlier than that
@@ -60,7 +62,9 @@ class RefreshingUploadCredentials:
60
62
  refreshes would mint two sessions for nothing.
61
63
  """
62
64
 
63
- def __init__(self, grant: "S3UploadGrantLike", refresh: "Callable[[], S3UploadGrantLike]") -> None:
65
+ def __init__(
66
+ self, grant: "S3UploadGrantLike", refresh: "Callable[[], S3UploadGrantLike]"
67
+ ) -> None:
64
68
  """Wrap the grant an upload started with, and how to renew it."""
65
69
  self._refresh = refresh
66
70
  self._lock = threading.Lock()
@@ -69,13 +73,19 @@ class RefreshingUploadCredentials:
69
73
  def _install(self, grant: "S3UploadGrantLike") -> None:
70
74
  self._grant = grant
71
75
  expires_in = getattr(grant, "expires_in", None)
72
- self._expires_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=expires_in) if expires_in else None
76
+ self._expires_at = (
77
+ datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=expires_in)
78
+ if expires_in
79
+ else None
80
+ )
73
81
 
74
82
  def __call__(self) -> "S3Credential":
75
83
  """The credentials to sign the next request with."""
76
84
  with self._lock:
77
85
  if self._expires_at is not None:
78
- remaining = (self._expires_at - datetime.datetime.now(datetime.UTC)).total_seconds()
86
+ remaining = (
87
+ self._expires_at - datetime.datetime.now(datetime.UTC)
88
+ ).total_seconds()
79
89
  if remaining < UPLOAD_REFRESH_MARGIN_SECONDS:
80
90
  self._install(self._refresh())
81
91
  return {
@@ -120,7 +130,9 @@ def create_s3_store(
120
130
  if proxy:
121
131
  normalized_client_options["proxy_url"] = proxy
122
132
  if certificates:
123
- normalized_client_options["root_certificate"] = "\n".join(pem.strip() for pem in certificates)
133
+ normalized_client_options["root_certificate"] = "\n".join(
134
+ pem.strip() for pem in certificates
135
+ )
124
136
  normalized_client_options["disable_system_certificates"] = True
125
137
 
126
138
  store_kwargs: dict[str, object] = {
@@ -133,7 +145,9 @@ def create_s3_store(
133
145
  store_id = getattr(grant, "store", None)
134
146
  if refresh is not None and store_id:
135
147
  # Inside an upload: credentials that renew themselves against the same store.
136
- store_kwargs["credential_provider"] = RefreshingUploadCredentials(grant, lambda: refresh(store_id))
148
+ store_kwargs["credential_provider"] = RefreshingUploadCredentials(
149
+ grant, lambda: refresh(store_id)
150
+ )
137
151
  else:
138
152
  store_kwargs["access_key_id"] = grant.access_key
139
153
  store_kwargs["secret_access_key"] = grant.secret_key
@@ -21,24 +21,46 @@ if TYPE_CHECKING:
21
21
  logger = logging.getLogger(__name__)
22
22
 
23
23
 
24
- def upload_bigfile(file: BigFile, credentials: "BigFileUploadGrant", datalayer: "DataLayer") -> str:
24
+ def upload_bigfile(
25
+ file: BigFile, credentials: "BigFileUploadGrant", datalayer: "DataLayer"
26
+ ) -> str:
25
27
  """Write ``file`` to the object its grant names, synchronously. Returns the store id."""
26
- store = create_s3_store(datalayer.endpoint_url, credentials, proxy=datalayer.proxy, certificates=datalayer.certificates)
28
+ store = create_s3_store(
29
+ datalayer.endpoint_url,
30
+ credentials,
31
+ proxy=datalayer.proxy,
32
+ certificates=datalayer.certificates,
33
+ )
27
34
  try:
28
35
  obstore.put(store, credentials.key, file.value)
29
36
  except Exception as e:
30
- raise UploadError(f"Error while uploading to s3://{credentials.bucket}/{credentials.key} on {datalayer.endpoint_url}") from e
31
- logger.info("Uploaded %s to s3://%s/%s", file.file_name, credentials.bucket, credentials.key)
37
+ raise UploadError(
38
+ f"Error while uploading to s3://{credentials.bucket}/{credentials.key} on {datalayer.endpoint_url}"
39
+ ) from e
40
+ logger.info(
41
+ "Uploaded %s to s3://%s/%s", file.file_name, credentials.bucket, credentials.key
42
+ )
32
43
  return credentials.store
33
44
 
34
45
 
35
- async def aupload_bigfile(file: BigFile, credentials: "BigFileUploadGrant", datalayer: "DataLayer") -> str:
46
+ async def aupload_bigfile(
47
+ file: BigFile, credentials: "BigFileUploadGrant", datalayer: "DataLayer"
48
+ ) -> str:
36
49
  """Write ``file`` to the object its grant names. Returns the store id."""
37
50
  endpoint_url = await datalayer.get_endpoint_url()
38
- store = create_s3_store(endpoint_url, credentials, proxy=datalayer.proxy, certificates=datalayer.certificates)
51
+ store = create_s3_store(
52
+ endpoint_url,
53
+ credentials,
54
+ proxy=datalayer.proxy,
55
+ certificates=datalayer.certificates,
56
+ )
39
57
  try:
40
58
  await obstore.put_async(store, credentials.key, file.value)
41
59
  except Exception as e:
42
- raise UploadError(f"Error while uploading to s3://{credentials.bucket}/{credentials.key} on {endpoint_url}") from e
43
- logger.info("Uploaded %s to s3://%s/%s", file.file_name, credentials.bucket, credentials.key)
60
+ raise UploadError(
61
+ f"Error while uploading to s3://{credentials.bucket}/{credentials.key} on {endpoint_url}"
62
+ ) from e
63
+ logger.info(
64
+ "Uploaded %s to s3://%s/%s", file.file_name, credentials.bucket, credentials.key
65
+ )
44
66
  return credentials.store
@@ -21,7 +21,6 @@ from typing import Any
21
21
 
22
22
  from koil import unkoil, unkoil_gen
23
23
  from koil.composition import Composition
24
- from pydantic import Field
25
24
  from rath.origin import origin_context
26
25
  from rath.task import TASK_HEADER, TaskLike, current_task, token_of
27
26
  from rath.turms.funcs import TOperation
@@ -31,8 +30,6 @@ from kraph.datalayer import DataLayer
31
30
  from kraph.rath import KraphRath
32
31
 
33
32
 
34
-
35
-
36
33
  class Kraph(Composition, KraphApi):
37
34
  """The kraph client.
38
35
 
@@ -46,17 +43,24 @@ class Kraph(Composition, KraphApi):
46
43
  rath: KraphRath
47
44
  datalayer: DataLayer
48
45
 
49
-
50
46
  @staticmethod
51
- def _serialize(operation: type[TOperation], variables: dict[str, Any]) -> dict[str, Any]:
47
+ def _serialize(
48
+ operation: type[TOperation], variables: dict[str, Any]
49
+ ) -> dict[str, Any]:
52
50
  # exclude_none, not exclude_unset: see the module docstring.
53
- return operation.Arguments(**variables).model_dump(by_alias=True, exclude_none=True)
51
+ return operation.Arguments(**variables).model_dump(
52
+ by_alias=True, exclude_none=True
53
+ )
54
54
 
55
- async def _aprepare(self, operation: type[TOperation], variables: dict[str, Any]) -> dict[str, Any]:
55
+ async def _aprepare(
56
+ self, operation: type[TOperation], variables: dict[str, Any]
57
+ ) -> dict[str, Any]:
56
58
  """Serialize the variables, then run the rath's middlewares over them (uploads, in order)."""
57
59
  serialized = self._serialize(operation, variables)
58
60
  for middleware in self.rath.middlewares:
59
- serialized = await middleware.aprocess_variables(serialized, operation, self.rath)
61
+ serialized = await middleware.aprocess_variables(
62
+ serialized, operation, self.rath
63
+ )
60
64
  return serialized
61
65
 
62
66
  def _origin(self) -> dict[str, Any]:
@@ -21,7 +21,6 @@ The class is kept — rather than deleted — because ``KraphLinkComposition.upl
21
21
  field and ``tests/conftest.py`` imports the name. It passes operations through untouched.
22
22
  """
23
23
 
24
-
25
24
  from pydantic import ConfigDict, Field
26
25
  from rath.links.parsing import ParsingLink
27
26
  from rath.operation import Operation
@@ -12,7 +12,7 @@ Both sync and async variants are supported:
12
12
  from __future__ import annotations
13
13
 
14
14
  import abc
15
- from typing import Any, TYPE_CHECKING
15
+ from typing import TYPE_CHECKING, Any
16
16
 
17
17
  from pydantic import BaseModel
18
18
 
@@ -45,7 +45,7 @@ class OperationMiddleware(BaseModel, abc.ABC):
45
45
  self,
46
46
  variables: dict[str, Any],
47
47
  operation: type[TOperation],
48
- rath: "KraphRath",
48
+ rath: KraphRath,
49
49
  ) -> dict[str, Any]:
50
50
  """Process the serialized variables dict synchronously.
51
51
 
@@ -67,7 +67,7 @@ class OperationMiddleware(BaseModel, abc.ABC):
67
67
  self,
68
68
  variables: dict[str, Any],
69
69
  operation: type[TOperation],
70
- rath: "KraphRath",
70
+ rath: KraphRath,
71
71
  ) -> dict[str, Any]:
72
72
  """Process the serialized variables dict asynchronously.
73
73
 
@@ -48,7 +48,9 @@ async def _apply_async(func: Callable[[Any], Awaitable[Any]], obj: Any) -> Any:
48
48
  if isinstance(obj, list):
49
49
  return list(await asyncio.gather(*[_apply_async(func, value) for value in obj]))
50
50
  if isinstance(obj, tuple):
51
- return tuple(await asyncio.gather(*[_apply_async(func, value) for value in obj]))
51
+ return tuple(
52
+ await asyncio.gather(*[_apply_async(func, value) for value in obj])
53
+ )
52
54
  if isinstance(obj, BigFile):
53
55
  return await func(obj)
54
56
  return obj
@@ -102,11 +104,19 @@ class UploadMiddleware(OperationMiddleware):
102
104
 
103
105
  @staticmethod
104
106
  def _request(file: BigFile) -> dict[str, Any]:
105
- return _variables(RequestBigfileUploadMutation, RequestBigFileUploadInput(original_file_name=file.file_name, file_size=_byte_size(file.value)))
107
+ return _variables(
108
+ RequestBigfileUploadMutation,
109
+ RequestBigFileUploadInput(
110
+ original_file_name=file.file_name, file_size=_byte_size(file.value)
111
+ ),
112
+ )
106
113
 
107
114
  @staticmethod
108
115
  def _finish(store_id: str, valid: bool) -> dict[str, Any]:
109
- return _variables(FinishBigfileUploadMutation, FinishBigFileUploadInput(store_id=store_id, valid=valid))
116
+ return _variables(
117
+ FinishBigfileUploadMutation,
118
+ FinishBigFileUploadInput(store_id=store_id, valid=valid),
119
+ )
110
120
 
111
121
  def _refresher(self, rath: "KraphRath") -> Callable[[str], Any]:
112
122
  """How to renew the grant, callable from obstore's own worker threads.
@@ -118,52 +128,90 @@ class UploadMiddleware(OperationMiddleware):
118
128
  captured = contextvars.copy_context()
119
129
 
120
130
  def refresh(store_id: str) -> Any: # noqa: ANN401
121
- variables = _variables(RefreshBigfileUploadMutation, RefreshUploadInput(store_id=store_id))
122
- result = captured.copy().run(rath.query, RefreshBigfileUploadMutation.Meta.document, variables)
131
+ variables = _variables(
132
+ RefreshBigfileUploadMutation, RefreshUploadInput(store_id=store_id)
133
+ )
134
+ result = captured.copy().run(
135
+ rath.query, RefreshBigfileUploadMutation.Meta.document, variables
136
+ )
123
137
  return RefreshBigfileUploadMutation(**result.data).refresh_bigfile_upload
124
138
 
125
139
  return refresh
126
140
 
127
141
  def _upload(self, rath: "KraphRath", file: BigFile) -> str:
128
142
  """Grant, write with self-renewing credentials, finish; or report the failure and re-raise."""
129
- grant = RequestBigfileUploadMutation(**rath.query(RequestBigfileUploadMutation.Meta.document, self._request(file)).data).request_bigfile_upload
143
+ grant = RequestBigfileUploadMutation(
144
+ **rath.query(
145
+ RequestBigfileUploadMutation.Meta.document, self._request(file)
146
+ ).data
147
+ ).request_bigfile_upload
130
148
  token = upload_refresher.set(self._refresher(rath))
131
149
  try:
132
150
  store_id = upload_bigfile(file, grant, self.datalayer)
133
151
  except BaseException:
134
152
  try:
135
- rath.query(FinishBigfileUploadMutation.Meta.document, self._finish(grant.store, valid=False))
153
+ rath.query(
154
+ FinishBigfileUploadMutation.Meta.document,
155
+ self._finish(grant.store, valid=False),
156
+ )
136
157
  except Exception: # noqa: BLE001 - the write's own error is the one to raise
137
- logger.warning("Could not report the failed upload of store %s; it is collected once its deadline passes.", grant.store, exc_info=True)
158
+ logger.warning(
159
+ "Could not report the failed upload of store %s; it is collected once its deadline passes.",
160
+ grant.store,
161
+ exc_info=True,
162
+ )
138
163
  raise
139
164
  finally:
140
165
  upload_refresher.reset(token)
141
- rath.query(FinishBigfileUploadMutation.Meta.document, self._finish(store_id, valid=True))
166
+ rath.query(
167
+ FinishBigfileUploadMutation.Meta.document,
168
+ self._finish(store_id, valid=True),
169
+ )
142
170
  return store_id
143
171
 
144
172
  async def _aupload(self, rath: "KraphRath", file: BigFile) -> str:
145
173
  """Grant, write with self-renewing credentials, finish; or report the failure and re-raise."""
146
- grant = RequestBigfileUploadMutation(**(await rath.aquery(RequestBigfileUploadMutation.Meta.document, self._request(file))).data).request_bigfile_upload
174
+ grant = RequestBigfileUploadMutation(
175
+ **(
176
+ await rath.aquery(
177
+ RequestBigfileUploadMutation.Meta.document, self._request(file)
178
+ )
179
+ ).data
180
+ ).request_bigfile_upload
147
181
  token = upload_refresher.set(self._refresher(rath))
148
182
  try:
149
183
  store_id = await aupload_bigfile(file, grant, self.datalayer)
150
184
  except BaseException:
151
185
  try:
152
- await rath.aquery(FinishBigfileUploadMutation.Meta.document, self._finish(grant.store, valid=False))
186
+ await rath.aquery(
187
+ FinishBigfileUploadMutation.Meta.document,
188
+ self._finish(grant.store, valid=False),
189
+ )
153
190
  except Exception: # noqa: BLE001 - the write's own error is the one to raise
154
- logger.warning("Could not report the failed upload of store %s; it is collected once its deadline passes.", grant.store, exc_info=True)
191
+ logger.warning(
192
+ "Could not report the failed upload of store %s; it is collected once its deadline passes.",
193
+ grant.store,
194
+ exc_info=True,
195
+ )
155
196
  raise
156
197
  finally:
157
198
  upload_refresher.reset(token)
158
- await rath.aquery(FinishBigfileUploadMutation.Meta.document, self._finish(store_id, valid=True))
199
+ await rath.aquery(
200
+ FinishBigfileUploadMutation.Meta.document,
201
+ self._finish(store_id, valid=True),
202
+ )
159
203
  return store_id
160
204
 
161
205
  # --- the middleware ----------------------------------------------------------------
162
206
 
163
- def process_variables(self, variables: dict[str, Any], operation: type[TOperation], rath: "KraphRath") -> dict[str, Any]:
207
+ def process_variables(
208
+ self, variables: dict[str, Any], operation: type[TOperation], rath: "KraphRath"
209
+ ) -> dict[str, Any]:
164
210
  """Upload every ``BigFile`` in ``variables`` and put its store id in its place."""
165
211
  return _apply_sync(partial(self._upload, rath), variables)
166
212
 
167
- async def aprocess_variables(self, variables: dict[str, Any], operation: type[TOperation], rath: "KraphRath") -> dict[str, Any]:
213
+ async def aprocess_variables(
214
+ self, variables: dict[str, Any], operation: type[TOperation], rath: "KraphRath"
215
+ ) -> dict[str, Any]:
168
216
  """Upload every ``BigFile`` in ``variables`` and put its store id in its place."""
169
217
  return await _apply_async(partial(self._aupload, rath), variables)
@@ -43,20 +43,36 @@ def _end(descriptor: Any) -> tuple[list[str], list[Any]]: # noqa: ANN401
43
43
  """The identifiers and the pinned constraints of one end of a category."""
44
44
  if descriptor is None:
45
45
  return [], []
46
- return list(getattr(descriptor, "identifiers", None) or []), list(getattr(descriptor, "requires", None) or [])
46
+ return list(getattr(descriptor, "identifiers", None) or []), list(
47
+ getattr(descriptor, "requires", None) or []
48
+ )
47
49
 
48
50
 
49
- def _hold(name: str, end: tuple[str, str], descriptor: Any, check: Check | None) -> None: # noqa: ANN401
51
+ def _hold(
52
+ name: str,
53
+ end: tuple[str, str],
54
+ descriptor: Any, # noqa: ANN401
55
+ check: Check | None,
56
+ ) -> None:
50
57
  identifiers, requires = _end(descriptor)
51
58
  if identifiers and end[0] not in identifiers:
52
- raise PinRefused(f"The {name} is a {end[0]}, but this word pairs {', '.join(identifiers)} there")
59
+ raise PinRefused(
60
+ f"The {name} is a {end[0]}, but this word pairs {', '.join(identifiers)} there"
61
+ )
53
62
  if not requires:
54
63
  return
55
64
  if check is None:
56
- raise PinRefused(f"This word pins {len(requires)} descriptor(s) on its {name}, and only the datum's own service can say whether they hold: pass check=")
65
+ raise PinRefused(
66
+ f"This word pins {len(requires)} descriptor(s) on its {name}, and only the datum's own service can say whether they hold: pass check="
67
+ )
57
68
  if not check(end, requires):
58
- pinned = ", ".join(f"{c.key} {getattr(c.operator, 'value', c.operator)} {c.value!r}" for c in requires)
59
- raise PinRefused(f"The {name} {end[0]}:{end[1]} does not satisfy what this word pins there: {pinned}")
69
+ pinned = ", ".join(
70
+ f"{c.key} {getattr(c.operator, 'value', c.operator)} {c.value!r}"
71
+ for c in requires
72
+ )
73
+ raise PinRefused(
74
+ f"The {name} {end[0]}:{end[1]} does not satisfy what this word pins there: {pinned}"
75
+ )
60
76
 
61
77
 
62
78
  def _word(category: Any) -> str: # noqa: ANN401
@@ -92,7 +108,9 @@ def pair(
92
108
  _hold("target", target_end, getattr(category, "target_descriptor", None), check)
93
109
 
94
110
  structures = [
95
- client.assert_structure_exists(identifier=identifier, object=object_id).structure
111
+ client.assert_structure_exists(
112
+ identifier=identifier, object=object_id
113
+ ).structure
96
114
  for identifier, object_id in (source_end, target_end)
97
115
  ]
98
116
  return client.assert_structure_relation_exists(
@@ -1,16 +1,17 @@
1
1
  from types import TracebackType
2
+ from typing import TypeVar
3
+
2
4
  from pydantic import Field
3
- from kraph.links.upload import UploadLink
4
- from kraph.middleware.base import OperationMiddleware
5
5
  from rath import rath
6
-
7
6
  from rath.links.auth import AuthTokenLink
8
-
9
7
  from rath.links.compose import TypedComposedLink
10
8
  from rath.links.dictinglink import DictingLink
11
9
  from rath.links.shrink import ShrinkingLink
12
10
  from rath.links.split import SplitLink
13
11
 
12
+ from kraph.links.upload import UploadLink
13
+ from kraph.middleware.base import OperationMiddleware
14
+
14
15
 
15
16
  class KraphLinkComposition(TypedComposedLink):
16
17
  shrinking: ShrinkingLink = Field(default_factory=ShrinkingLink)
@@ -20,6 +21,9 @@ class KraphLinkComposition(TypedComposedLink):
20
21
  split: SplitLink
21
22
 
22
23
 
24
+ _KraphRath = TypeVar("_KraphRath", bound="KraphRath")
25
+
26
+
23
27
  class KraphRath(rath.Rath):
24
28
  """Kraph Rath
25
29
 
@@ -30,7 +34,7 @@ class KraphRath(rath.Rath):
30
34
 
31
35
  middlewares: list[OperationMiddleware] = Field(default_factory=list)
32
36
 
33
- async def __aenter__(self):
37
+ async def __aenter__(self: _KraphRath) -> _KraphRath:
34
38
  """Enter the client and its middlewares.
35
39
 
36
40
  Entering does not make it "the current client", and kraph never looks one up: calls go
@@ -112,7 +112,7 @@ def as_structure_ref(x: StructureRef) -> tuple[str, str]:
112
112
  raise TypeError(f"Cannot read a structure reference out of {type(x).__name__}")
113
113
 
114
114
 
115
- def as_term(x: Any) -> str:
115
+ def as_term(x: object) -> str:
116
116
  """The word a claim is stated in — a ``Term.key``, never a category id."""
117
117
  if isinstance(x, str):
118
118
  return x
@@ -76,7 +76,9 @@ class StructureIdentifier(str):
76
76
  return cls(identifier_for_cls(target))
77
77
 
78
78
  if isinstance(v, str):
79
- assert "@" in v, f"{v!r} is not a valid structure identifier (expected '@ns/name')"
79
+ assert "@" in v, (
80
+ f"{v!r} is not a valid structure identifier (expected '@ns/name')"
81
+ )
80
82
  return cls(v)
81
83
 
82
84
  raise TypeError(
@@ -106,7 +108,9 @@ class StructureObject(str):
106
108
  return cls(str(get_attributes_or_error(v, "id")))
107
109
  if isinstance(v, (str, int)):
108
110
  return cls(str(v))
109
- raise TypeError("A structure object must be a string, an int, or a model with an id")
111
+ raise TypeError(
112
+ "A structure object must be a string, an int, or a model with an id"
113
+ )
110
114
 
111
115
 
112
116
  class CypherLiteral(str):
@@ -153,7 +157,9 @@ class BigFile:
153
157
  handler: GetCoreSchemaHandler,
154
158
  ) -> CoreSchema:
155
159
  """Validate with :meth:`validate`; the instance travels to the middleware as itself."""
156
- return core_schema.no_info_after_validator_function(cls.validate, handler(object))
160
+ return core_schema.no_info_after_validator_function(
161
+ cls.validate, handler(object)
162
+ )
157
163
 
158
164
  @classmethod
159
165
  def validate(cls, v: "BigFileLikeCoercible | BigFile") -> "BigFile":
@@ -163,7 +169,9 @@ class BigFile:
163
169
  if isinstance(v, (str, os.PathLike)):
164
170
  return cls(open(v, "rb"), file_name=os.path.basename(os.fspath(v))) # noqa: SIM115 - read by the upload, closed with it
165
171
  if not isinstance(v, io.IOBase):
166
- raise ValueError(f"A big file is a path or an open binary file, not {type(v).__name__}")
172
+ raise ValueError(
173
+ f"A big file is a path or an open binary file, not {type(v).__name__}"
174
+ )
167
175
  return cls(v)
168
176
 
169
177
  def __repr__(self) -> str:
@@ -27,6 +27,7 @@ from typing import TYPE_CHECKING, Any
27
27
  from koil import unkoil
28
28
  from pydantic import BaseModel
29
29
  from rath.origin import ContextBound
30
+ from rath.scalars import WithId
30
31
  from rath.turms.utils import get_attributes_or_error
31
32
 
32
33
  from kraph.client import client_of
@@ -34,6 +35,7 @@ from kraph.client import client_of
34
35
  if TYPE_CHECKING:
35
36
  from arkitekt_spec.declare.structures.registry import StructureRegistry
36
37
 
38
+ from kraph.api.schema import GraphProjection
37
39
  from kraph.kraph import Kraph
38
40
 
39
41
 
@@ -56,9 +58,17 @@ class AssertedTrait(BaseModel):
56
58
  return get_attributes_or_error(self, "assertion").seq
57
59
 
58
60
  @property
59
- def claim(self) -> Any:
61
+ def claim(self) -> object:
60
62
  """The thing this write recorded, whichever field the payload carries it in."""
61
- for field in ("instance", "instances", "link", "links", "structure", "metric", "comment"):
63
+ for field in (
64
+ "instance",
65
+ "instances",
66
+ "link",
67
+ "links",
68
+ "structure",
69
+ "metric",
70
+ "comment",
71
+ ):
62
72
  value = getattr(self, field, None)
63
73
  if value is not None:
64
74
  return value
@@ -87,9 +97,11 @@ class HasDrawings(BaseModel):
87
97
  """
88
98
  return bool(get_attributes_or_error(self, "drawings"))
89
99
 
90
- def drawn_in(self, graph: Any) -> Any | None:
100
+ def drawn_in(self, graph: str | WithId) -> object | None:
91
101
  """This view's account of the claim, or ``None`` if this view does not draw it."""
92
- wanted = graph if isinstance(graph, str) else get_attributes_or_error(graph, "id")
102
+ wanted = (
103
+ graph if isinstance(graph, str) else get_attributes_or_error(graph, "id")
104
+ )
93
105
  for drawing in get_attributes_or_error(self, "drawings"):
94
106
  if str(drawing.graph.id) == str(wanted):
95
107
  return drawing
@@ -179,7 +191,7 @@ class StructureTrait(BaseModel):
179
191
  """The ``(identifier, object)`` pair that addresses this datum."""
180
192
  return get_attributes_or_error(self, "identifier", "object")
181
193
 
182
- def resolve(self, registry: "StructureRegistry") -> Any:
194
+ def resolve(self, registry: "StructureRegistry") -> object:
183
195
  """Expand this structure back into the concrete Python object it points at.
184
196
 
185
197
  Uses ``registry``, a structure registry bound to its clients (the one a running task
@@ -265,7 +277,7 @@ class GraphTrait(ContextBound):
265
277
  """
266
278
 
267
279
  @property
268
- def projection_state(self) -> Any:
280
+ def projection_state(self) -> "ProjectionTrait":
269
281
  return get_attributes_or_error(self, "projection")
270
282
 
271
283
  def wait_until_projected(
@@ -275,7 +287,7 @@ class GraphTrait(ContextBound):
275
287
  timeout: float = 30.0,
276
288
  poll: float = 0.5,
277
289
  kraph: "Kraph | None" = None,
278
- ) -> Any:
290
+ ) -> "GraphProjection":
279
291
  """Block until this view has drawn everything up to ``seq``.
280
292
 
281
293
  Never implicit: a backfill or a category edit redraws in-request and is unbounded in the
@@ -318,7 +330,9 @@ def structure_identifier(end: Any) -> str: # noqa: ANN401
318
330
  stamped = getattr(end, "__identifier__", None)
319
331
  if isinstance(stamped, str):
320
332
  return stamped
321
- raise TypeError(f"A pair's end is a structure identifier ('@mikro/arraylens') or a class stamped with one, not {end!r}")
333
+ raise TypeError(
334
+ f"A pair's end is a structure identifier ('@mikro/arraylens') or a class stamped with one, not {end!r}"
335
+ )
322
336
 
323
337
 
324
338
  def _typed_by_ends(cls: type, ends: Any, name: str) -> Any: # noqa: ANN401
@@ -338,8 +352,12 @@ def _typed_by_ends(cls: type, ends: Any, name: str) -> Any: # noqa: ANN401
338
352
  source, target = (structure_identifier(end) for end in ends)
339
353
  return Annotated[
340
354
  cls,
341
- Requires(key=SOURCE_IDENTIFIER, operator=DescriptorOperator.EQUALS, value=source),
342
- Requires(key=TARGET_IDENTIFIER, operator=DescriptorOperator.EQUALS, value=target),
355
+ Requires(
356
+ key=SOURCE_IDENTIFIER, operator=DescriptorOperator.EQUALS, value=source
357
+ ),
358
+ Requires(
359
+ key=TARGET_IDENTIFIER, operator=DescriptorOperator.EQUALS, value=target
360
+ ),
343
361
  ]
344
362
 
345
363
 
@@ -361,7 +379,13 @@ def _expanded(registry: "StructureRegistry", pairs: list[Any]) -> list[tuple[Any
361
379
  def expand(identifier: str, object_id: str) -> Any: # noqa: ANN401
362
380
  return unkoil(registry.get_fullfilled_structure(identifier).expand, object_id)
363
381
 
364
- return [(expand(pair.source_identifier, pair.source_object), expand(pair.target_identifier, pair.target_object)) for pair in pairs]
382
+ return [
383
+ (
384
+ expand(pair.source_identifier, pair.source_object),
385
+ expand(pair.target_identifier, pair.target_object),
386
+ )
387
+ for pair in pairs
388
+ ]
365
389
 
366
390
 
367
391
  class GraphPairsQueryTrait(ContextBound):
@@ -380,11 +404,22 @@ class GraphPairsQueryTrait(ContextBound):
380
404
  """Every pair the query answers now, from the view's drawing. Not a record: run it for one."""
381
405
  client = client_of(self, kraph)
382
406
  query_id = get_attributes_or_error(self, "id")
383
- return _read_pairs(lambda pagination: client.render_graph_pairs(id=query_id, pagination=pagination), page)
407
+ return _read_pairs(
408
+ lambda pagination: client.render_graph_pairs(
409
+ id=query_id, pagination=pagination
410
+ ),
411
+ page,
412
+ )
384
413
 
385
- def run(self, name: str, *, description: str | None = None, kraph: "Kraph | None" = None) -> Any: # noqa: ANN401
414
+ def run(
415
+ self, name: str, *, description: str | None = None, kraph: "Kraph | None" = None
416
+ ) -> Any: # noqa: ANN401
386
417
  """Run the query: its answer, stored with where the drawing stood. What a model cites."""
387
- return client_of(self, kraph).run_pairs_query(query=get_attributes_or_error(self, "id"), name=name, description=description)
418
+ return client_of(self, kraph).run_pairs_query(
419
+ query=get_attributes_or_error(self, "id"),
420
+ name=name,
421
+ description=description,
422
+ )
388
423
 
389
424
 
390
425
  class PairsQueryRunTrait(ContextBound):
@@ -399,13 +434,22 @@ class PairsQueryRunTrait(ContextBound):
399
434
  """``PairsQueryRun["@mikro/arraylens", "@mikro/arraylens"]``: runs of image pairs only."""
400
435
  return _typed_by_ends(cls, ends, "PairsQueryRun")
401
436
 
402
- def read_entries(self, *, kraph: "Kraph | None" = None, page: int = 1000) -> list[Any]:
437
+ def read_entries(
438
+ self, *, kraph: "Kraph | None" = None, page: int = 1000
439
+ ) -> list[Any]:
403
440
  """Every stored pair, in the run's order, as ``(identifier, object)`` addresses."""
404
441
  client = client_of(self, kraph)
405
442
  run_id = get_attributes_or_error(self, "id")
406
- return _read_pairs(lambda pagination: client.get_run_entries(id=run_id, pagination=pagination).page, page)
443
+ return _read_pairs(
444
+ lambda pagination: (
445
+ client.get_run_entries(id=run_id, pagination=pagination).page
446
+ ),
447
+ page,
448
+ )
407
449
 
408
- def pairs(self, registry: "StructureRegistry", *, kraph: "Kraph | None" = None) -> list[tuple[Any, Any]]:
450
+ def pairs(
451
+ self, registry: "StructureRegistry", *, kraph: "Kraph | None" = None
452
+ ) -> list[tuple[Any, Any]]:
409
453
  """Every pair as the objects themselves: ``(source, target)``, each expanded by its own service.
410
454
 
411
455
  ``registry`` is a structure registry bound to its clients (the one a running task
@@ -418,17 +462,29 @@ class PairsQueryRunTrait(ContextBound):
418
462
  class BigFileStoreTrait(ContextBound):
419
463
  """A big file in kraph's datalayer: read back through an access grant, never by its path."""
420
464
 
421
- def download(self, file_name: str | None = None, *, kraph: "Kraph | None" = None) -> str:
465
+ def download(
466
+ self, file_name: str | None = None, *, kraph: "Kraph | None" = None
467
+ ) -> str:
422
468
  """Stream the file to ``file_name`` (its uploaded name by default). Returns the path written."""
423
469
  from kraph.io.download import download_bigfile, file_name_of
424
470
 
425
- return download_bigfile(str(get_attributes_or_error(self, "id")), file_name_of(self, file_name), client_of(self, kraph))
471
+ return download_bigfile(
472
+ str(get_attributes_or_error(self, "id")),
473
+ file_name_of(self, file_name),
474
+ client_of(self, kraph),
475
+ )
426
476
 
427
- async def adownload(self, file_name: str | None = None, *, kraph: "Kraph | None" = None) -> str:
477
+ async def adownload(
478
+ self, file_name: str | None = None, *, kraph: "Kraph | None" = None
479
+ ) -> str:
428
480
  """Stream the file to ``file_name`` (its uploaded name by default). Returns the path written."""
429
481
  from kraph.io.download import adownload_bigfile, file_name_of
430
482
 
431
- return await adownload_bigfile(str(get_attributes_or_error(self, "id")), file_name_of(self, file_name), client_of(self, kraph))
483
+ return await adownload_bigfile(
484
+ str(get_attributes_or_error(self, "id")),
485
+ file_name_of(self, file_name),
486
+ client_of(self, kraph),
487
+ )
432
488
 
433
489
 
434
490
  class ModelTrait(ContextBound):
@@ -438,16 +494,28 @@ class ModelTrait(ContextBound):
438
494
  sends the file and passes the finished store on, as every service's files are uploaded.
439
495
  """
440
496
 
441
- def download(self, file_name: str | None = None, *, kraph: "Kraph | None" = None) -> str:
497
+ def download(
498
+ self, file_name: str | None = None, *, kraph: "Kraph | None" = None
499
+ ) -> str:
442
500
  """Stream the weights to ``file_name`` (their uploaded name by default). Returns the path written."""
443
501
  from kraph.io.download import download_bigfile, file_name_of
444
502
 
445
503
  store = get_attributes_or_error(self, "store")
446
- return download_bigfile(str(get_attributes_or_error(store, "id")), file_name_of(store, file_name), client_of(self, kraph))
504
+ return download_bigfile(
505
+ str(get_attributes_or_error(store, "id")),
506
+ file_name_of(store, file_name),
507
+ client_of(self, kraph),
508
+ )
447
509
 
448
- async def adownload(self, file_name: str | None = None, *, kraph: "Kraph | None" = None) -> str:
510
+ async def adownload(
511
+ self, file_name: str | None = None, *, kraph: "Kraph | None" = None
512
+ ) -> str:
449
513
  """Stream the weights to ``file_name`` (their uploaded name by default). Returns the path written."""
450
514
  from kraph.io.download import adownload_bigfile, file_name_of
451
515
 
452
516
  store = get_attributes_or_error(self, "store")
453
- return await adownload_bigfile(str(get_attributes_or_error(store, "id")), file_name_of(store, file_name), client_of(self, kraph))
517
+ return await adownload_bigfile(
518
+ str(get_attributes_or_error(store, "id")),
519
+ file_name_of(store, file_name),
520
+ client_of(self, kraph),
521
+ )
@@ -13,7 +13,7 @@ dependencies = [
13
13
  "rath>=4.1.1",
14
14
  "websockets>=15.0.1",
15
15
  # The service and structures are declared with arkitekt-spec (5.0: a service reads its scopes off its client).
16
- "arkitekt-spec>=5.0",
16
+ "arkitekt-spec>=12.9",
17
17
  # The service wiring (Alias, Require, FaktsAuthLink); it came through rekuest before.
18
18
  "fakts>=6.1",
19
19
  # The datalayer: big files (a model's weights) go to S3 through obstore, as in mikro and elektro.
@@ -33,57 +33,19 @@ dev-dependencies = [
33
33
  "aiohttp>=3.8.3,<4",
34
34
  "black>=23.1.0,<24",
35
35
  "pytest-aiohttp>=1.0.4,<2",
36
- "ruff>=0.0.254",
37
36
  "turms>=3.0",
38
37
  "dokker>=2.8",
39
- "basedpyright>=1.21",
40
38
  ]
41
39
 
42
- [tool.basedpyright]
43
- include = ["kraph"]
44
- exclude = ["**/__pycache__", "tests"]
45
- typeCheckingMode = "standard"
46
-
47
-
48
- [tool.ruff]
49
- extend-select = ["ANN", "D1", "UP"]
50
-
51
-
52
- # Exclude a variety of commonly ignored directories.
53
- exclude = [
54
- ".bzr",
55
- ".direnv",
56
- ".eggs",
57
- ".git",
58
- ".hg",
59
- ".mypy_cache",
60
- ".nox",
61
- ".pants.d",
62
- ".pytype",
63
- ".ruff_cache",
64
- ".svn",
65
- ".tox",
66
- ".venv",
67
- "__pypackages__",
68
- "_build",
69
- "buck-out",
70
- "build",
71
- "dist",
72
- "node_modules",
73
- "venv",
74
- ]
75
-
76
- # Same as Black.
77
- line-length = 100
78
- extend-ignore = ["UP037", "UP038", "UP042"]
79
-
80
- [tool.ruff.lint.per-file-ignores]
81
- "kraph/api/schema.py" = ["UP035"]
40
+ # `_tested.json` is written by the integration tests (the server version they ran against)
41
+ # and is not in git: named as an artifact, on both, it is shipped all the same.
82
42
  [tool.hatch.build.targets.sdist]
83
43
  include = ["kraph"]
44
+ artifacts = ["kraph/_tested.json"]
84
45
 
85
46
  [tool.hatch.build.targets.wheel]
86
47
  include = ["kraph"]
48
+ artifacts = ["kraph/_tested.json"]
87
49
 
88
50
 
89
51
  [build-system]
@@ -152,3 +114,9 @@ exclude_commit_patterns = [
152
114
  '^Merge ',
153
115
  ]
154
116
 
117
+
118
+ [dependency-groups]
119
+ dev = [
120
+ "ruff==0.17.6",
121
+ "basedpyright==1.40.2",
122
+ ]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes