Repository navigation
Expand file tree
/
Copy pathfunction_instances.py
More file actions
388 lines (312 loc) · 14.5 KB
/
Copy pathfunction_instances.py
File metadata and controls
388 lines (312 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
"""Shared ownership and freshness helpers for reusable function groups.
This module contains the compiler-level protocol used by calls that
materialize editable reusable ``GeometryNodeTree`` datablocks. It deliberately
does not resolve imports or predict dependencies. Actual local/library
materializers report canonical ``IRFunctionMaterialization`` identity and the
realized child fingerprint while normal compilation runs.
"""
from __future__ import annotations
import hashlib
import json
import uuid
from contextlib import contextmanager
from dataclasses import dataclass, field
from .errors import CompileError
from .compiler_identities import (
CallSiteId,
ExtensionCallSiteId,
CORE_PACKAGE_ID,
)
from .semantic.ir import IRFunctionMaterialization, IRFunctionMaterializationMode
FUNCTION_INSTANCE_KEY_PROP = "nodeforge_function_instance_key"
FUNCTION_DEFINITION_OWNER_PROP = "nodeforge_function_definition_owner"
FUNCTION_INTERFACE_CONTRACT_PROP = "nodeforge_function_interface_contract"
FUNCTION_COMPILATION_FINGERPRINT_PROP = "nodeforge_function_compilation_fingerprint"
FUNCTION_ROOT_OWNER_ID_PROP = "nodeforge_function_root_owner_id"
COMPOSITION_ROOT_ID_PROP = "nodeforge_composition_root_id_v1"
FINGERPRINT_SCHEMA = 1
FUNCTION_COMPILER_VERSION: str | None = None
SHARED_INSTANCE_KEY = "SHARED"
def _canonical_json(value) -> str:
"""Serialize *value* deterministically for metadata and hashing."""
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def _digest_payload(value) -> str:
"""Return a SHA-256 digest for a canonical JSON payload."""
return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest()
def function_group_owner_scope(kind: str, *parts, instance_key: str | None = None) -> str:
"""Serialize the canonical owner scope for one physical reusable group."""
payload = {
"kind": str(kind),
"parts": list(parts),
"instance": instance_key or SHARED_INSTANCE_KEY,
}
return _canonical_json(payload)
def direct_library_owner_scope(namespace: str, package_id: str | None, name: str) -> str:
"""Return the established owner scope for standalone catalog materialization.
Local catalog entries intentionally predate package-qualified reusable ownership
and therefore keep an empty package slot. Other editable catalogs use the
canonical package identifier carried by ``FunctionId``.
"""
normalized_package_id = "" if namespace == "local" else str(package_id or CORE_PACKAGE_ID)
return function_group_owner_scope(
"LIBRARY",
str(namespace),
normalized_package_id,
str(name),
)
def direct_library_owner_scope_for_id(function_id, *, instance_key: str | None = None) -> str:
"""Use canonical Local origin and occurrence ownership; retain other catalog keys."""
if function_id.kind != "LIBRARY":
raise ValueError("Direct library owner requires a library FunctionId")
if function_id.namespace == "local":
if not function_id.source_origin:
raise ValueError("Local owner requires source origin")
return function_group_owner_scope(
"LIBRARY", "local", "", function_id.name, function_id.source_origin,
instance_key=instance_key,
)
return function_group_owner_scope(
"LIBRARY", function_id.namespace, function_id.package_id, function_id.name,
instance_key=instance_key,
)
def instance_key_for(call_site: CallSiteId) -> str:
"""Return the existing deterministic compact key for one canonical call site."""
return _digest_payload({
"schema": 1,
"owner_scope": call_site.owner_scope,
"callee_identity": call_site.callee.stable_key(),
"ordinal": call_site.ordinal,
})[:32]
def extension_instance_key_for(call_site: ExtensionCallSiteId) -> str:
"""Hash a physical extension occurrence using the established instance-key codec."""
if not isinstance(call_site, ExtensionCallSiteId):
raise TypeError("extension instance key requires ExtensionCallSiteId")
return _digest_payload({
"schema": 1,
"owner_scope": call_site.owner_scope,
"callee_identity": _canonical_json({
"owner": list(call_site.callee.owner), "name": call_site.callee.name,
}),
"ordinal": call_site.ordinal,
})[:32]
def instance_key_for_materialization(materialization: IRFunctionMaterialization) -> str:
"""Return the persisted instance key implied by reusable-call Semantic IR."""
if not isinstance(materialization, IRFunctionMaterialization):
raise TypeError("materialization must be an IRFunctionMaterialization")
if materialization.mode is IRFunctionMaterializationMode.SHARED:
return ""
if materialization.mode is IRFunctionMaterializationMode.INLINE:
raise ValueError("INLINE calls have no persisted physical instance key")
return instance_key_for(materialization.call_site)
def module_definition_owner_scope(function_id, *, instance_key: str = "") -> str:
"""Derive one MODULE_DEF physical scope from its exact stored instance key."""
if function_id.kind != "MODULE_DEF":
raise ValueError("Module owner requires a MODULE_DEF FunctionId")
return function_group_owner_scope(
"MODULE_DEF", function_id.module.stable_key(), function_id.name,
function_id.signature, instance_key=instance_key or None,
)
def function_materialization_owner_scope(
materialization: IRFunctionMaterialization,
) -> str:
"""Serialize reusable physical ownership from canonical materialization IR."""
if not isinstance(materialization, IRFunctionMaterialization):
raise TypeError("materialization must be an IRFunctionMaterialization")
callee = materialization.callee
instance_key = instance_key_for_materialization(materialization)
if callee.kind == "LOCAL_DEF":
return function_group_owner_scope(
"LOCAL_DEF",
callee.definition_owner,
callee.name,
callee.signature,
instance_key=instance_key,
)
if callee.kind == "MODULE_DEF":
return module_definition_owner_scope(callee, instance_key=instance_key)
if callee.kind == "LIBRARY":
if callee.namespace == "local":
return direct_library_owner_scope_for_id(callee, instance_key=instance_key or None)
return function_group_owner_scope(
"LIBRARY",
callee.namespace,
callee.package_id,
callee.name,
instance_key=instance_key or None,
)
raise ValueError(f"Unsupported reusable FunctionId kind: {callee.kind!r}")
def inline_semantic_fingerprint(prepared) -> str:
"""Fingerprint one realized inline region independently of its physical caller.
The body contains owner-scoped typed bindings and folded input defaults;
the interface retains physical order and exact type/default contracts. The
definition source and extension rows carry other effective dependencies.
"""
from .semantic.source_callables import PreparedSourceCallable
if not isinstance(prepared, PreparedSourceCallable):
raise TypeError("inline fingerprint requires PreparedSourceCallable")
group = prepared.group
return _digest_payload({
"schema": 1,
"function": prepared.contract.function_id.stable_key(),
"source": group.source,
"lowered_source": group.normalized_lowered_source,
"body": repr(group.body),
"interface": repr(group.interface),
"call_contract": repr(prepared.contract),
"extensions": group.extension_dependencies,
})
def new_root_owner_id() -> str:
"""Return a new lowercase UUID hex root owner id."""
return uuid.uuid4().hex
def validate_root_owner_id(value) -> str:
"""Return a validated persistent root UUID or raise a controlled error."""
if not isinstance(value, str) or not value:
raise CompileError("NodeForge root owner ID is invalid")
try:
parsed = uuid.UUID(hex=value)
except Exception as exc:
raise CompileError("NodeForge root owner ID is invalid") from exc
normalized = parsed.hex
if normalized != value.lower():
raise CompileError("NodeForge root owner ID is invalid")
return normalized
def interface_contract(group) -> str:
"""Serialize ordered public sockets of one compiled group."""
sockets = []
for item in getattr(group.interface, "items_tree", []):
if getattr(item, "item_type", None) != "SOCKET":
continue
sockets.append({
"name": getattr(item, "name", ""),
"in_out": getattr(item, "in_out", ""),
"socket_type": getattr(item, "socket_type", "") or getattr(item, "bl_socket_idname", ""),
})
return _canonical_json({"schema": 1, "sockets": sockets})
def stored_interface_contract(group) -> str:
"""Return the persisted interface contract, or an empty string."""
try:
return str(group.get(FUNCTION_INTERFACE_CONTRACT_PROP) or "")
except Exception:
return ""
def stored_fingerprint(group) -> str:
"""Return the persisted effective compilation fingerprint, or empty."""
try:
return str(group.get(FUNCTION_COMPILATION_FINGERPRINT_PROP) or "")
except Exception:
return ""
def stamp_function_metadata(group, *, instance_key: str | None, definition_owner: str | None, fingerprint: str | None = None) -> None:
"""Persist generic function-instance metadata on a reusable group."""
group[FUNCTION_INSTANCE_KEY_PROP] = str(instance_key or "")
if definition_owner is not None:
group[FUNCTION_DEFINITION_OWNER_PROP] = str(definition_owner)
if fingerprint:
group[FUNCTION_COMPILATION_FINGERPRINT_PROP] = str(fingerprint)
group[FUNCTION_INTERFACE_CONTRACT_PROP] = interface_contract(group)
@dataclass
class FunctionCompilationResult:
"""Finalized freshness result for one actual reusable-group compilation."""
fingerprint: str = ""
freshness_unproven: bool = False
@dataclass
class FunctionCompilationFrame:
"""Mutable trace frame populated by real child materialization paths."""
owner_identity: str
own_inputs: dict
child_rows: list = field(default_factory=list)
freshness_unproven: bool = False
result: FunctionCompilationResult | None = None
def record_dependency_identity(self, owner_identity: str, fingerprint: str | None) -> None:
"""Record one realized dependency by its canonical physical owner identity."""
if not isinstance(owner_identity, str) or not owner_identity:
raise ValueError("owner_identity must be a non-empty string")
if not fingerprint:
self.freshness_unproven = True
return
self.child_rows.append({"owner": owner_identity, "fingerprint": str(fingerprint)})
def record_dependency(
self,
materialization: IRFunctionMaterialization,
fingerprint: str | None,
) -> None:
"""Record one reusable access through the generic identity helper."""
if not isinstance(materialization, IRFunctionMaterialization):
raise TypeError("materialization must be an IRFunctionMaterialization")
self.record_dependency_identity(
function_materialization_owner_scope(materialization),
fingerprint,
)
def record_inline_dependency(
self, materialization: IRFunctionMaterialization, fingerprint: str,
) -> None:
"""Track one source expansion on the current physical parent's trace.
INLINE owns a semantic call occurrence, never a separate persisted
NodeTree. Its nested grouped children record in this same frame.
"""
from .compiler_identities import inline_expansion_owner_scope
if (not isinstance(materialization, IRFunctionMaterialization)
or materialization.mode is not IRFunctionMaterializationMode.INLINE):
raise ValueError("inline dependency requires INLINE materialization")
self.record_dependency_identity(
inline_expansion_owner_scope(materialization.call_site), fingerprint,
)
def finish(self, contract: str) -> FunctionCompilationResult:
"""Finalize this frame's effective fingerprint."""
if self.freshness_unproven:
self.result = FunctionCompilationResult("", True)
return self.result
payload = {
"schema": FINGERPRINT_SCHEMA,
"owner": self.owner_identity,
"own_inputs": self.own_inputs,
"children": sorted(self.child_rows, key=lambda row: _canonical_json(row)),
"interface": contract,
}
if FUNCTION_COMPILER_VERSION is not None:
payload["compiler"] = FUNCTION_COMPILER_VERSION
self.result = FunctionCompilationResult(_digest_payload(payload), False)
return self.result
class FunctionCompilationTrace:
"""Build-local actual-compilation trace for reusable function groups."""
def __init__(self):
self._stack: list[FunctionCompilationFrame] = []
@property
def current(self) -> FunctionCompilationFrame | None:
"""Return the current active frame, if any."""
return self._stack[-1] if self._stack else None
@contextmanager
def group(self, owner_identity: str, own_inputs: dict):
"""Open one actual compilation frame and guard against recursion."""
if owner_identity in {frame.owner_identity for frame in self._stack}:
chain = " -> ".join([frame.owner_identity for frame in self._stack] + [owner_identity])
raise CompileError(f"Cyclic function-group dependency: {chain}")
frame = FunctionCompilationFrame(owner_identity, dict(own_inputs or {}))
self._stack.append(frame)
try:
yield frame
finally:
if self._stack and self._stack[-1] is frame:
self._stack.pop()
__all__ = [
"inline_semantic_fingerprint",
"FUNCTION_INSTANCE_KEY_PROP",
"FUNCTION_DEFINITION_OWNER_PROP",
"FUNCTION_INTERFACE_CONTRACT_PROP",
"FUNCTION_COMPILATION_FINGERPRINT_PROP",
"FUNCTION_ROOT_OWNER_ID_PROP",
"COMPOSITION_ROOT_ID_PROP",
"FunctionCompilationTrace",
"function_group_owner_scope",
"direct_library_owner_scope",
"direct_library_owner_scope_for_id",
"function_materialization_owner_scope",
"module_definition_owner_scope",
"instance_key_for",
"extension_instance_key_for",
"instance_key_for_materialization",
"new_root_owner_id",
"validate_root_owner_id",
"interface_contract",
"stored_interface_contract",
"stored_fingerprint",
"stamp_function_metadata",
]