Repository navigation
Expand file tree
/
Copy pathenvironment_resolution.py
More file actions
458 lines (402 loc) · 22.2 KB
/
Copy pathenvironment_resolution.py
File metadata and controls
458 lines (402 loc) · 22.2 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""Build immutable package/catalog selections for one compilation session."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Mapping
from .errors import CompileError
from . import packages, catalog, local_sources
from .resolved_environment import (
_freeze_package_selection,
PackageCallableExport,
ResolvedCatalog,
ResolvedCatalogFailure,
ResolvedCompileErrorFailure,
ResolvedEnvironment,
ResolvedOSErrorFailure,
ResolvedPackageNamespace,
)
def _resolved_failure_from_exception(exc: Exception) -> ResolvedCatalogFailure:
"""Detach one supported discovery/normalization failure for catalog replay."""
if isinstance(exc, CompileError):
return ResolvedCompileErrorFailure(tuple(exc.args))
if isinstance(exc, OSError):
return ResolvedOSErrorFailure(
exception_type=type(exc),
exception_args=tuple(exc.args),
errno=exc.errno,
strerror=exc.strerror,
filename=exc.filename,
filename2=exc.filename2,
winerror=getattr(exc, "winerror", None),
)
return ResolvedCompileErrorFailure((str(exc),))
def _resolve_environment_parts(*, capture_local: bool):
"""Resolve shared package/extension selections with optional eager Local capture."""
from .extensions.registry import (
ExtensionOwnerSession,
ExtensionRegistry,
capture_owner_code_snapshot,
library_owner_key,
system_owner_key,
)
manifests = tuple(packages.active_package_manifest_snapshot())
manifests_by_id = {manifest.package_id: manifest for manifest in manifests}
import_owners: dict[str, str] = {}
for manifest in manifests:
previous = import_owners.get(manifest.import_name)
if previous is not None and previous != manifest.package_id:
raise CompileError(
f"Package import name {manifest.import_name!r} is owned by both {previous} and {manifest.package_id}"
)
import_owners[manifest.import_name] = manifest.package_id
raw_system_records = tuple(packages.system_package_records_from_manifests(manifests))
raw_candidates: dict[str, tuple[object, ...]] = {}
examples_directories, examples_positions = [], []
discovery_failures: dict[str, Exception] = {}
deferred_package_discovery_failures: dict[tuple[str, str], Exception] = {}
for namespace in ("functions", "examples"):
collected: list[object] = []
if namespace == "examples":
try:
inventory = catalog.candidate_records_from_inputs(
namespace, package_roots=(), include_builtin_catalog=True,
)
collected.extend(inventory)
examples_directories.extend(("", path, origin) for path, origin in getattr(inventory, "directories", ()))
examples_positions.extend(("", path, name, origin) for path, name, origin in getattr(inventory, "source_positions", ()))
except (CompileError, OSError) as exc:
discovery_failures[namespace] = exc
for root in packages.library_roots_from_manifests(namespace, manifests):
try:
if namespace == "examples":
inventory = catalog.candidate_records_from_inputs(
namespace, package_roots=(root,), include_builtin_catalog=False,
)
collected.extend(inventory)
examples_directories.extend((root.package_id, path, origin) for path, origin in getattr(inventory, "directories", ()))
examples_positions.extend((root.package_id, path, name, origin) for path, name, origin in getattr(inventory, "source_positions", ()))
else:
collected.extend(catalog.candidate_records_from_inputs(
namespace, package_roots=(root,), include_builtin_catalog=False,
))
except (CompileError, OSError) as exc:
deferred_package_discovery_failures[(namespace, root.package_id)] = exc
raw_candidates[namespace] = tuple(collected)
local_catalog = _capture_local_catalog() if capture_local else None
system_sessions: dict[tuple[str, ...], ExtensionOwnerSession] = {}
system_snapshot_failures: dict[str, Exception] = {}
for record in raw_system_records:
try:
snapshot = capture_owner_code_snapshot(system_owner_key(record), record.root)
system_sessions[system_owner_key(record)] = ExtensionOwnerSession(snapshot)
except (CompileError, OSError) as exc:
system_snapshot_failures.setdefault(record.package_id, exc)
library_sessions: dict[tuple[str, ...], ExtensionOwnerSession] = {}
deferred_library_failures: dict[tuple[str, ...], Exception] = {}
for namespace in ("functions", "examples"):
for record in raw_candidates.get(namespace, ()):
if getattr(record, "interface_path", None) is None or getattr(record, "source_path", None) is not None:
continue
key = library_owner_key(record)
try:
snapshot = capture_owner_code_snapshot(key, record.interface_path.parent)
library_sessions[key] = ExtensionOwnerSession(snapshot)
except (CompileError, OSError) as exc:
deferred_library_failures[key] = exc
systems_by_package: dict[str, list[object]] = {package_id: [] for package_id in manifests_by_id}
for record in raw_system_records:
systems_by_package.setdefault(record.package_id, []).append(record)
functions_by_package: dict[str, list[object]] = {package_id: [] for package_id in manifests_by_id}
for record in raw_candidates.get("functions", ()):
functions_by_package.setdefault(record.package_id, []).append(record)
package_namespaces: dict[str, ResolvedPackageNamespace] = {}
admitted_packages: set[str] = set()
registry_sessions: list[ExtensionOwnerSession] = []
for package_id in sorted(manifests_by_id):
manifest = manifests_by_id[package_id]
try:
discovery_failure = deferred_package_discovery_failures.get(("functions", package_id))
if discovery_failure is not None:
raise discovery_failure
snapshot_failure = system_snapshot_failures.get(package_id)
if snapshot_failure is not None:
raise snapshot_failure
# Freeze every package source before discovering or validating any
# export; members and later semantic preparation use this revision.
from .compiler_identities import ModuleId
from .semantic.source_modules import parse_source_module
frozen_sources = {}
functions_root = manifest.root_for("functions")
for record in functions_by_package.get(package_id, ()):
source_path = getattr(record, "source_path", None)
if source_path is None:
continue
if getattr(record, "interface_path", None) is not None:
raise CompileError(f"Unsupported mixed source.nf and interface.py owner: {package_id}/{record.name}")
if source_path.suffix != ".nf":
raise CompileError(f"Unsupported legacy package source suffix: {source_path.name}")
if functions_root is None:
raise CompileError(f"Package {package_id} has no Functions source root")
physical = source_path.resolve()
try:
relative = physical.relative_to(functions_root.resolve())
except ValueError as exc:
raise CompileError(f"Package Functions source escapes its declared root: {physical}") from exc
module_id = ModuleId("PACKAGE", relative.as_posix(), package_id)
frozen_sources[record] = parse_source_module(
source_path.read_text(encoding="utf-8"), module_id
)
# Every export has one immutable canonical physical identity. Short
# aliases are derived only after all declarations are frozen.
canonical: dict[str, PackageCallableExport] = {}
package_sessions: list[ExtensionOwnerSession] = []
def publish(export: PackageCallableExport) -> None:
"""Reject the exact canonical target collision at publication."""
previous = canonical.get(export.qualified_name)
if previous is not None:
raise CompileError(
f"Duplicate package callable {export.qualified_name!r} inside {package_id}: "
f"{previous.record or previous.extension_callable_id} and "
f"{export.record or export.extension_callable_id}"
)
canonical[export.qualified_name] = export
for record in systems_by_package.get(package_id, ()):
session = system_sessions[system_owner_key(record)]
families, _refs = session.normalize_interface()
package_sessions.append(session)
for callable_id in families:
publish(PackageCallableExport(
package_id, callable_id.name, extension_callable_id=callable_id,
))
for record in functions_by_package.get(package_id, ()):
owner = ".".join(filter(None, (record.folder_path.replace("/", "."), record.name)))
source_snapshot = frozen_sources.get(record)
if source_snapshot is not None:
for name in source_snapshot.definitions:
publish(PackageCallableExport(
package_id, name, record=record,
definition=source_snapshot.definition_ref(name),
source_snapshot=source_snapshot,
qualified_name=f"{owner}.{name}",
))
continue
name = record.name
extension_callable_id = None
if getattr(record, "interface_path", None) is not None and getattr(record, "source_path", None) is None:
key = library_owner_key(record)
deferred = deferred_library_failures.get(key)
if deferred is not None:
raise deferred
session = library_sessions.get(key)
if session is None:
raise CompileError(f"Extension library owner {record.name!r} has no captured owner snapshot")
families, _refs = session.normalize_interface()
family_names = [callable_id.name for callable_id in families]
if family_names != [record.name]:
raise CompileError(
f"Native-only functions extension {record.name!r} must declare exactly one EXTENSIONS key with the same name"
)
extension_callable_id = next(iter(families))
package_sessions.append(session)
publish(PackageCallableExport(
package_id, name, record=record,
extension_callable_id=extension_callable_id, qualified_name=owner,
))
leaf_candidates: dict[str, list[PackageCallableExport]] = {}
for export in canonical.values():
leaf_candidates.setdefault(export.name, []).append(export)
exports: dict[str, PackageCallableExport] = {}
ambiguities: dict[str, tuple[str, ...]] = {}
for name, candidates in sorted(leaf_candidates.items()):
# An exact root callable has priority over module-qualified
# source exports. Otherwise one root .nf source wins, followed
# by the only candidate across the entire package.
direct = [e for e in candidates if e.qualified_name == name]
root_sources = [e for e in candidates if e.record is not None
and e.definition is not None and not e.record.folder_path]
options = direct or root_sources or candidates
if len(options) == 1:
exports[name] = options[0]
else:
ambiguities[name] = tuple(sorted(e.qualified_name for e in candidates))
namespace = ResolvedPackageNamespace(
package_id=package_id,
import_name=manifest.import_name,
package_name=manifest.name,
package_version=manifest.version,
exports=exports, qualified_exports=canonical, short_ambiguities=ambiguities,
)
except (CompileError, OSError, packages.PackageError) as exc:
# Preserve the manifest import reservation. Explicit access to this
# package surfaces the captured error instead of "unknown package".
package_namespaces[package_id] = ResolvedPackageNamespace(
package_id=package_id, import_name=manifest.import_name,
package_name=manifest.name, package_version=manifest.version,
exports={}, failure=_resolved_failure_from_exception(exc),
)
continue
package_namespaces[package_id] = namespace
admitted_packages.add(package_id)
registry_sessions.extend(package_sessions)
catalogs: dict[str, ResolvedCatalog] = {"functions": ResolvedCatalog("functions", {})}
namespace = "examples"
failure = discovery_failures.get(namespace)
candidates = []
if failure is None:
for package_id in sorted(admitted_packages):
deferred = deferred_package_discovery_failures.get((namespace, package_id))
if deferred is not None:
failure = deferred
break
if failure is None:
for record in raw_candidates.get(namespace, ()):
package_id = str(getattr(record, "package_id", ""))
if package_id and package_id not in admitted_packages:
continue
candidates.append(record)
if failure is not None:
catalogs[namespace] = ResolvedCatalog(
namespace, {}, _resolved_failure_from_exception(failure)
)
else:
try:
from .local_index import ExamplesSourceIndex
legacy_records = tuple(record for record in candidates
if not record.folder_path and record.kind != "runtime")
entries = catalog.unique_records_from_candidates(namespace, legacy_records)
admitted = {"", *admitted_packages}
discovered_dirs = tuple((path, origin) for pkg, path, origin in examples_directories if pkg in admitted)
discovered_positions = tuple((path, name, origin) for pkg, path, name, origin in examples_positions if pkg in admitted)
index = ExamplesSourceIndex.from_discovery(tuple(candidates), discovered_dirs, discovered_positions)
selected_sessions = []
for record in entries.values():
if getattr(record, "interface_path", None) is None or getattr(record, "source_path", None) is not None:
continue
key = library_owner_key(record)
deferred = deferred_library_failures.get(key)
if deferred is not None:
raise deferred
session = library_sessions.get(key)
if session is None:
raise CompileError(f"Extension library owner {record.name!r} has no captured owner snapshot")
families, _refs = session.normalize_interface()
if [callable_id.name for callable_id in families] != [record.name]:
raise CompileError(
f"Native-only {namespace} extension {record.name!r} must declare exactly one EXTENSIONS key with the same name"
)
selected_sessions.append(session)
except (CompileError, OSError) as exc:
catalogs[namespace] = ResolvedCatalog(
namespace, {}, _resolved_failure_from_exception(exc)
)
else:
catalogs[namespace] = ResolvedCatalog(namespace, entries, examples_index=index)
registry_sessions.extend(selected_sessions)
registry = ExtensionRegistry(tuple(registry_sessions))
return _ResolvedNonLocalParts(
functions_catalog=catalogs["functions"],
examples_catalog=catalogs["examples"],
package_namespaces=package_namespaces,
extension_registry=registry,
), local_catalog
def _capture_local_catalog() -> ResolvedCatalog:
"""Capture a complete immutable Local inventory or a replayable failure."""
from .local_index import LocalSourceIndex
try:
roots, files = local_sources._catalog_input_paths()
discovery = catalog.discover_local_sources(roots, files)
index = LocalSourceIndex.from_discovery(*discovery)
return ResolvedCatalog("local", {}, local_index=index)
except (CompileError, OSError) as exc:
return ResolvedCatalog("local", {}, _resolved_failure_from_exception(exc))
@dataclass(frozen=True)
class _ResolvedNonLocalParts:
"""Immutable package/extension selection shared by eager and compiler paths."""
functions_catalog: ResolvedCatalog
examples_catalog: ResolvedCatalog
package_namespaces: Mapping[str, ResolvedPackageNamespace]
extension_registry: object
def __post_init__(self) -> None:
"""Validate catalogs and freeze package ownership at the resolution boundary."""
if self.functions_catalog.namespace != "functions" or self.examples_catalog.namespace != "examples":
raise ValueError("Non-Local catalog selection requires functions and examples")
namespaces, import_index, registry = _freeze_package_selection(
self.package_namespaces, self.extension_registry
)
object.__setattr__(self, "package_namespaces", namespaces)
object.__setattr__(self, "_package_import_index", import_index)
object.__setattr__(self, "extension_registry", registry)
def package_by_import_name(self, import_name: str) -> ResolvedPackageNamespace | None:
"""Return the selected owner namespace without consulting package state."""
package_id = self._package_import_index.get(import_name)
return None if package_id is None else self.package_namespaces[package_id]
class _LocalCatalogSlot:
"""Capture Local once on semantic demand, including empty and failed results."""
def __init__(self) -> None:
"""Start an unrequested slot owned by one root compilation attempt."""
self._captured: ResolvedCatalog | None = None
def get(self) -> ResolvedCatalog:
"""Publish one immutable capture result and reuse its exact object."""
if self._captured is None:
self._captured = _capture_local_catalog()
return self._captured
class _LocalRuntimeRegistrySlot:
"""Accumulate explicitly selected trusted Local/Examples Python owners for one root attempt."""
def __init__(self, base_registry):
"""Start with the immutable admitted package registry and no Local execution."""
self.registry = base_registry
self._sessions = {}
self._base = base_registry
def admit(self, record):
"""Capture one selected owner without changing any prior frozen registry."""
from .local_runtime import capture_local_runtime_session, local_runtime_owner_key
from .extensions.contracts import ExtensionCallableId
owner = local_runtime_owner_key(record)
if owner not in self._sessions:
callable_id, session = capture_local_runtime_session(record)
candidate = self._base.with_owner_sessions((*self._sessions.values(), session))
if not candidate.contains(callable_id):
raise CompileError("Internal error: Local runtime callable is missing from overlay")
self._sessions[owner] = session
self.registry = candidate
return ExtensionCallableId(owner, record.name)
@dataclass(frozen=True)
class _CompilationEnvironment:
"""Root-scoped non-Local selection with one semantic-demand Local slot."""
_parts: _ResolvedNonLocalParts
_local_slot: _LocalCatalogSlot
_runtime_slot: _LocalRuntimeRegistrySlot
@property
def extension_registry(self):
"""Expose a sealed current registry including only selected Local runtime owners."""
return self._runtime_slot.registry
def admit_local_runtime(self, record):
"""Prepare one explicitly selected owner before semantic call lowering."""
return self._runtime_slot.admit(record)
def catalog(self, namespace: str) -> ResolvedCatalog:
"""Select a catalog, capturing Local only when that namespace is requested."""
if namespace == "local":
return self._local_slot.get()
if namespace == "functions":
return self._parts.functions_catalog
if namespace == "examples":
return self._parts.examples_catalog
raise CompileError(f"Unknown library catalog: {namespace}")
def package_by_import_name(self, import_name: str) -> ResolvedPackageNamespace | None:
"""Delegate canonical package lookup to the captured non-Local selection."""
return self._parts.package_by_import_name(import_name)
def _make_compilation_environment() -> _CompilationEnvironment:
"""Create fresh package selections and an unrequested Local slot for a root."""
parts, _local = _resolve_environment_parts(capture_local=False)
return _CompilationEnvironment(parts, _LocalCatalogSlot(), _LocalRuntimeRegistrySlot(parts.extension_registry))
def resolve_environment() -> ResolvedEnvironment:
"""Resolve a complete eager package/extension/Local environment snapshot."""
parts, local_catalog = _resolve_environment_parts(capture_local=True)
assert local_catalog is not None
return ResolvedEnvironment(
catalogs={"functions": parts.functions_catalog,
"examples": parts.examples_catalog,
"local": local_catalog},
package_namespaces=parts.package_namespaces,
extension_registry=parts.extension_registry,
)
__all__ = ["resolve_environment"]