Repository navigation
Expand file tree
/
Copy pathpython_workflow_definition.py
More file actions
589 lines (500 loc) · 22.5 KB
/
Copy pathpython_workflow_definition.py
File metadata and controls
589 lines (500 loc) · 22.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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
"""
Bidirectional converter between flowrep and python-workflow-definition formats.
The ``python_workflow_definition`` (pwd) package is an **optional** dependency.
It represents workflows as flat, non-nested DAGs of atomic function calls with
explicit input/output nodes carrying JSON-serializable default values.
The two formats hold different axioms about how a function's return value maps
onto a node's output ports:
=========== ========================== ================================
whole return value component of return
=========== ========================== ================================
pwd ``sourcePort: null`` ``sourcePort: "<key>"`` →
``result["<key>"]``
flowrep exactly one output port N>1 ports unpack an N-tuple
=========== ========================== ================================
They overlap only on *exactly one output, meaning the whole return value*.
Anything outside that overlap raises :class:`OutputContractError` rather than
being mistranslated into a recipe that computes the wrong answer. As a
corollary, a flowrep node's sole output port name is not preserved across a
round-trip: it becomes pwd's unnamed ``sourcePort`` and returns as
:data:`_DEFAULT_OUTPUT_PORT`.
"""
from __future__ import annotations
from typing import Any
from pyiron_snippets import import_alarm, versions
from flowrep import base_models, edge_models
from flowrep.parsers import label_helpers
from flowrep.prospective import atomic_recipe, workflow_recipe
with import_alarm.ImportAlarm(
"This converter requires the 'python-workflow-definition' package. "
) as _import_alarm:
from python_workflow_definition import __version__ as pwd_version
from python_workflow_definition import models as pwd
# pwd encodes a single unnamed output as ``sourcePort: null``; its validator
# maps that to :data:`pwd.INTERNAL_DEFAULT_HANDLE` (``"__result__"``).
# We reuse the same string as a flowrep output-port name so that the
# representation round-trips without ambiguity.
_DEFAULT_OUTPUT_PORT: str = "__result__"
# Port names in pwd edges may not be valid Python identifiers (e.g. ``"0"``
# used by ``python_workflow_definition.shared.get_list``). Flowrep requires
# all port names to satisfy :func:`str.isidentifier`, not be keywords, and not
# be in :data:`base_models.RESERVED_NAMES`. We sanitize on the way in and
# reverse on the way out with a prefix that is itself a valid identifier start.
_PORT_SANITIZE_PREFIX: str = "flowrep_sanitized_"
class OutputContractError(ValueError):
"""
A node's output contract is not representable in the target format.
flowrep and pwd disagree about how a function's return value maps onto
output ports. pwd says ``sourcePort: null`` is the entire return value and
a named ``sourcePort`` is a key of a returned dict; flowrep says a single
output port is the entire return value and N>1 ports unpack an N-tuple.
The two overlap only on *exactly one output, meaning the whole return
value*. Converting a node outside that overlap would produce a recipe that
executes incorrectly, so we refuse rather than mistranslate.
Subclasses :class:`ValueError` so that callers already handling the
converter's other validation failures keep working.
"""
def _needs_sanitization(port: str) -> bool:
"""Return ``True`` if *port* is not a valid flowrep :class:`Label`."""
return not base_models.is_valid_label(port)
def _sanitize_port(port: str) -> str:
"""
Make a pwd port name safe for use as a flowrep :class:`Label`.
The transformation is reversible via :func:`_desanitize_port` as long as
no *user-created* port name starts with :data:`_PORT_SANITIZE_PREFIX` and
has a remainder that would itself need sanitisation.
"""
if _needs_sanitization(port):
return _PORT_SANITIZE_PREFIX + port
return port
def _desanitize_port(port: str) -> str:
"""
Reverse :func:`_sanitize_port` when converting back to pwd.
Only input (``targetPort``) names need this; output ports never round-trip
through pwd by name — see :func:`_build_pwd_edges`.
"""
if port.startswith(_PORT_SANITIZE_PREFIX):
candidate = port[len(_PORT_SANITIZE_PREFIX) :]
if candidate and _needs_sanitization(candidate):
return candidate
return port
@_import_alarm
def pwd2flowrep(
wf: pwd.PythonWorkflowDefinitionWorkflow,
) -> tuple[workflow_recipe.WorkflowRecipe, dict[str, pwd.AllowableDefaults]]:
"""
Convert a *python-workflow-definition* workflow to flowrep.
Args:
wf: A validated PWD workflow instance.
Returns:
A ``(WorkflowRecipe, defaults)`` pair where *defaults* maps each
workflow-input name to the default value carried by the corresponding
PWD input node.
Raises:
OutputContractError: If any function node is consumed via a named
``sourcePort``.
"""
input_nodes, output_nodes, function_nodes = _categorize_pwd_nodes(wf.nodes)
_validate_pwd_output_contracts(wf.edges, function_nodes)
label_map = _build_label_map(function_nodes)
node_inputs, node_outputs = _collect_function_node_ports(
wf.edges,
function_nodes,
)
nodes = _build_atomic_nodes(function_nodes, label_map, node_inputs, node_outputs)
wf_inputs = [input_nodes[nid].name for nid in sorted(input_nodes)]
wf_outputs = [output_nodes[nid].name for nid in sorted(output_nodes)]
defaults: dict[str, pwd.AllowableDefaults] = {
n.name: n.value for n in input_nodes.values()
}
fr_input_edges, fr_edges, fr_output_edges = _build_flowrep_edges(
wf.edges,
input_nodes,
output_nodes,
label_map,
)
result = workflow_recipe.WorkflowRecipe(
inputs=wf_inputs,
outputs=wf_outputs,
nodes=nodes,
input_edges=fr_input_edges,
edges=fr_edges,
output_edges=fr_output_edges,
)
return result, defaults
@_import_alarm
def flowrep2pwd(
wf: workflow_recipe.WorkflowRecipe,
**terminal_inputs: pwd.AllowableDefaults,
) -> pwd.PythonWorkflowDefinitionWorkflow:
"""
Convert a flowrep :class:`WorkflowRecipe` to *python-workflow-definition*.
Every child of *wf* must be an :class:`AtomicRecipe` (the pwd format does not
support nested sub-graphs). A default value must be supplied for **every**
workflow input via *terminal_inputs*.
Args:
wf: A flat flowrep workflow (atomic children only).
**terminal_inputs: One keyword argument per workflow input, providing
the JSON-serialisable default value for the corresponding PWD
input node.
Returns:
A validated :class:`PythonWorkflowDefinitionWorkflow`.
Raises:
ValueError: If any child is non-atomic, or if *terminal_inputs* does
not exactly cover the workflow's inputs.
OutputContractError: If any child has more than one output port.
"""
_validate_flat_workflow(wf)
_validate_flowrep_output_contract(wf)
_validate_terminal_inputs(wf, terminal_inputs)
id_counter = _IdCounter()
# --- input nodes ---
input_node_ids: dict[str, int] = {}
pwd_nodes: list[pwd.PythonWorkflowDefinitionNode] = []
for port in wf.inputs:
nid = id_counter.next()
input_node_ids[port] = nid
pwd_nodes.append(
pwd.PythonWorkflowDefinitionInputNode(
id=nid,
type="input",
name=port,
value=terminal_inputs[port],
)
)
# --- output nodes ---
output_node_ids: dict[str, int] = {}
for port in wf.outputs:
nid = id_counter.next()
output_node_ids[port] = nid
pwd_nodes.append(
pwd.PythonWorkflowDefinitionOutputNode(
id=nid,
type="output",
name=port,
)
)
# --- function nodes ---
func_node_ids: dict[str, int] = {}
for label, node in wf.nodes.items():
nid = id_counter.next()
func_node_ids[label] = nid
# Guaranteed by _validate_flat_workflow
assert isinstance(node, atomic_recipe.AtomicRecipe)
pwd_nodes.append(
pwd.PythonWorkflowDefinitionFunctionNode(
id=nid,
type="function",
value=node.fully_qualified_name,
)
)
# --- edges ---
pwd_edges = _build_pwd_edges(wf, input_node_ids, output_node_ids, func_node_ids)
return pwd.PythonWorkflowDefinitionWorkflow(
version=pwd_version,
nodes=pwd_nodes,
edges=pwd_edges,
)
def _categorize_pwd_nodes(
nodes: list[pwd.PythonWorkflowDefinitionNode],
) -> tuple[
dict[int, pwd.PythonWorkflowDefinitionInputNode],
dict[int, pwd.PythonWorkflowDefinitionOutputNode],
dict[int, pwd.PythonWorkflowDefinitionFunctionNode],
]:
"""Partition PWD nodes into input / output / function dicts keyed by id."""
input_nodes: dict[int, pwd.PythonWorkflowDefinitionInputNode] = {}
output_nodes: dict[int, pwd.PythonWorkflowDefinitionOutputNode] = {}
function_nodes: dict[int, pwd.PythonWorkflowDefinitionFunctionNode] = {}
for node in nodes:
if isinstance(node, pwd.PythonWorkflowDefinitionInputNode):
input_nodes[node.id] = node
elif isinstance(node, pwd.PythonWorkflowDefinitionOutputNode):
output_nodes[node.id] = node
elif isinstance(node, pwd.PythonWorkflowDefinitionFunctionNode):
function_nodes[node.id] = node
return input_nodes, output_nodes, function_nodes
def _validate_pwd_output_contracts(
edges: list[pwd.PythonWorkflowDefinitionEdge],
function_nodes: dict[int, pwd.PythonWorkflowDefinitionFunctionNode],
) -> None:
"""
Raise :class:`OutputContractError` for function nodes consumed by key.
A named ``sourcePort`` tells pwd to subscript the node's single return value
with that key. A flowrep atomic node cannot express that: its outputs are
either the whole return value (one port) or a tuple unpacking (many ports).
Inspects raw ``sourcePort`` values, before sanitisation, so the message
quotes the author's own port names.
"""
named: dict[int, list[str]] = {}
for edge in edges:
if edge.source not in function_nodes:
continue
port = edge.sourcePort
if port is None or port == pwd.INTERNAL_DEFAULT_HANDLE:
continue
ports = named.setdefault(edge.source, [])
if port not in ports:
ports.append(port)
if named:
offenders = [
f"node {nid} ({function_nodes[nid].value}) is consumed via "
f"sourcePort(s) {sorted(named[nid])}"
for nid in sorted(named)
]
raise OutputContractError(
"pwd2flowrep requires every function node to be consumed via a null "
"sourcePort. pwd reads a named sourcePort as a key of a single "
"returned dict, which a flowrep atomic node cannot express — its "
"outputs are either the whole return value (one port) or a tuple "
"unpacking (many). Offending nodes: " + "; ".join(offenders) + "."
)
def _build_label_map(
function_nodes: dict[int, pwd.PythonWorkflowDefinitionFunctionNode],
) -> dict[int, str]:
"""
Assign unique string labels to function nodes, deterministic by ID order.
Uses the last dot-segment of the node's ``value`` (the function name) as
the base, appended with an incrementing suffix — matching the convention
used by :func:`flowrep.models.parsers.label_helpers.unique_suffix`.
"""
counts: dict[str, int] = {}
label_map: dict[int, str] = {}
for node_id in sorted(function_nodes):
fn_node = function_nodes[node_id]
base = fn_node.value.rsplit(".", 1)[-1]
idx = counts.get(base, 0)
counts[base] = idx + 1
label_map[node_id] = label_helpers.index_label(base, idx)
return label_map
def _collect_function_node_ports(
edges: list[pwd.PythonWorkflowDefinitionEdge],
function_nodes: dict[int, pwd.PythonWorkflowDefinitionFunctionNode],
) -> tuple[dict[int, list[str]], dict[int, list[str]]]:
"""
Collect ordered, unique input/output port names for each function node.
Input port names that are not valid flowrep Labels are sanitized via
:func:`_sanitize_port`. Output ports are always the single
:data:`_DEFAULT_OUTPUT_PORT`.
"""
node_inputs: dict[int, list[str]] = {nid: [] for nid in function_nodes}
node_outputs: dict[int, list[str]] = {nid: [] for nid in function_nodes}
for edge in edges:
# Target ports (inputs of the function node)
if edge.target in function_nodes and edge.targetPort is not None:
port = _sanitize_port(edge.targetPort)
ports = node_inputs[edge.target]
if port not in ports:
ports.append(port)
# Outputs of the function node. Guaranteed null-sourced by
# _validate_pwd_output_contracts, so every such node has exactly the
# one default-named output port.
if edge.source in function_nodes:
ports = node_outputs[edge.source]
if _DEFAULT_OUTPUT_PORT not in ports:
ports.append(_DEFAULT_OUTPUT_PORT)
return node_inputs, node_outputs
def _build_atomic_nodes(
function_nodes: dict[int, pwd.PythonWorkflowDefinitionFunctionNode],
label_map: dict[int, str],
node_inputs: dict[int, list[str]],
node_outputs: dict[int, list[str]],
) -> dict[str, atomic_recipe.AtomicRecipe]:
"""Build flowrep :class:`AtomicRecipe` instances from PWD function nodes."""
nodes: dict[str, atomic_recipe.AtomicRecipe] = {}
for node_id in sorted(function_nodes):
fn_node = function_nodes[node_id]
label = label_map[node_id]
module, qualname = fn_node.value.rsplit(".", 1)
# This could, in principle, give the incorrect division into module and qualname
# For the purpose of a fully qualified name, it makes no difference
# But for someone trying to use just one component it might.
# Ultimately, we don't have much choice shy of trying to import and recover the
# underlying object, since PWD itself entangles the two sub-fields.
# This rsplit is at least consistent with the assumptions made in the PWD
# ecosystem:
# https://github.com/pythonworkflow/python-workflow-definition/blob/a372769e190176fe49e71740ad899937df0eeb94/src/python_workflow_definition/purepython.py#L80-L82
nodes[label] = atomic_recipe.AtomicRecipe(
reference=base_models.PythonReference(
info=versions.VersionInfo(
module=module,
qualname=qualname,
version=None, # PWD stores no information for this field
),
),
inputs=node_inputs[node_id],
outputs=node_outputs[node_id],
)
return nodes
def _build_flowrep_edges(
edges: list[pwd.PythonWorkflowDefinitionEdge],
input_nodes: dict[int, pwd.PythonWorkflowDefinitionInputNode],
output_nodes: dict[int, pwd.PythonWorkflowDefinitionOutputNode],
label_map: dict[int, str],
) -> tuple[edge_models.InputEdges, edge_models.Edges, edge_models.OutputEdges]:
"""Convert PWD edges into the three flowrep edge dictionaries."""
fr_input_edges: edge_models.InputEdges = {}
fr_edges: edge_models.Edges = {}
fr_output_edges: edge_models.OutputEdges = {}
for edge in edges:
source_is_input = edge.source in input_nodes
target_is_output = edge.target in output_nodes
if source_is_input and target_is_output:
# Pass-through: workflow input → workflow output
in_name = input_nodes[edge.source].name
out_name = output_nodes[edge.target].name
fr_output_edges[edge_models.OutputTarget(port=out_name)] = (
edge_models.InputSource(port=in_name)
)
elif source_is_input:
# Workflow input → function node
in_name = input_nodes[edge.source].name
target_label = label_map[edge.target]
target_port = _sanitize_port(edge.targetPort)
fr_input_edges[
edge_models.TargetHandle(node=target_label, port=target_port)
] = edge_models.InputSource(port=in_name)
elif target_is_output:
# Function node → workflow output
out_name = output_nodes[edge.target].name
source_label = label_map[edge.source]
source_port = _DEFAULT_OUTPUT_PORT
fr_output_edges[edge_models.OutputTarget(port=out_name)] = (
edge_models.SourceHandle(node=source_label, port=source_port)
)
else:
# Function node → function node (sibling edge)
source_label = label_map[edge.source]
target_label = label_map[edge.target]
source_port = _DEFAULT_OUTPUT_PORT
target_port = _sanitize_port(edge.targetPort)
fr_edges[edge_models.TargetHandle(node=target_label, port=target_port)] = (
edge_models.SourceHandle(node=source_label, port=source_port)
)
return fr_input_edges, fr_edges, fr_output_edges
class _IdCounter:
"""Simple incrementing integer-ID generator."""
def __init__(self, start: int = 0) -> None:
self._next = start
def next(self) -> int:
nid = self._next
self._next += 1
return nid
def _validate_flat_workflow(wf: workflow_recipe.WorkflowRecipe) -> None:
"""Raise :class:`ValueError` if any child is not an :class:`AtomicRecipe`."""
for label, node in wf.nodes.items():
if not isinstance(node, atomic_recipe.AtomicRecipe):
raise ValueError(
f"flowrep2pwd requires all children to be AtomicRecipe, but "
f"'{label}' is {type(node).__name__}."
)
def _validate_flowrep_output_contract(wf: workflow_recipe.WorkflowRecipe) -> None:
"""
Raise :class:`OutputContractError` if any child has more than one output.
Must be called *after* :func:`_validate_flat_workflow`, which guarantees
every child is an :class:`AtomicRecipe`.
"""
offenders: list[str] = []
for label, node in wf.nodes.items():
# Guaranteed by _validate_flat_workflow
assert isinstance(node, atomic_recipe.AtomicRecipe)
if len(node.outputs) > 1:
offenders.append(
f"'{label}' ({node.fully_qualified_name}) has "
f"{len(node.outputs)} outputs {node.outputs}"
)
if offenders:
raise OutputContractError(
"flowrep2pwd requires every child to have exactly one output. "
"flowrep reads multiple output ports as unpacking a tuple, whereas "
"pwd reads them as keys of a single returned dict, so the converted "
"workflow would not execute correctly. Offending nodes: "
+ "; ".join(offenders)
+ "."
)
def _validate_terminal_inputs(
wf: workflow_recipe.WorkflowRecipe,
terminal_inputs: dict[str, Any],
) -> None:
"""Raise :class:`ValueError` if *terminal_inputs* != workflow inputs."""
expected = set(wf.inputs)
provided = set(terminal_inputs)
missing = expected - provided
extra = provided - expected
if missing or extra:
parts: list[str] = []
if missing:
parts.append(f"missing: {sorted(missing)}")
if extra:
parts.append(f"extra: {sorted(extra)}")
raise ValueError(
f"terminal_inputs must exactly match workflow inputs. {'; '.join(parts)}"
)
def _build_pwd_edges(
wf: workflow_recipe.WorkflowRecipe,
input_node_ids: dict[str, int],
output_node_ids: dict[str, int],
func_node_ids: dict[str, int],
) -> list[pwd.PythonWorkflowDefinitionEdge]:
"""
Convert the three flowrep edge dicts into a flat PWD edge list.
Edges are emitted in a deterministic order that preserves the input-port
ordering of each child node — this is important for consumers that rely on
edge-list order (e.g. ``get_list``).
Every function-node source emits ``sourcePort=None``. A flowrep child has
exactly one output (enforced by :func:`_validate_flowrep_output_contract`) and that
output *is* the whole return value, which is precisely what pwd spells as a
null ``sourcePort``. The flowrep port's name is therefore not carried over.
"""
pwd_edges: list[pwd.PythonWorkflowDefinitionEdge] = []
# Emit edges targeting each child, one per input port in order.
# A given TargetHandle appears in exactly one of input_edges or edges.
source: edge_models.SourceHandle | edge_models.InputSource
for label, node in wf.nodes.items():
for port in node.inputs:
th = edge_models.TargetHandle(node=label, port=port)
target_port_pwd = _desanitize_port(port)
if th in wf.input_edges:
source = wf.input_edges[th]
pwd_edges.append(
pwd.PythonWorkflowDefinitionEdge(
source=input_node_ids[source.port],
sourcePort=None,
target=func_node_ids[label],
targetPort=target_port_pwd,
)
)
elif th in wf.edges:
source = wf.edges[th]
pwd_edges.append(
pwd.PythonWorkflowDefinitionEdge(
source=func_node_ids[source.node],
sourcePort=None,
target=func_node_ids[label],
targetPort=target_port_pwd,
)
)
# Emit output edges in workflow output order.
for port in wf.outputs:
ot = edge_models.OutputTarget(port=port)
if ot in wf.output_edges:
source = wf.output_edges[ot]
if isinstance(source, edge_models.InputSource):
pwd_edges.append(
pwd.PythonWorkflowDefinitionEdge(
source=input_node_ids[source.port],
sourcePort=None,
target=output_node_ids[port],
targetPort=None,
)
)
else:
pwd_edges.append(
pwd.PythonWorkflowDefinitionEdge(
source=func_node_ids[source.node],
sourcePort=None,
target=output_node_ids[port],
targetPort=None,
)
)
return pwd_edges