function-sequence 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- function_sequence/__init__.py +26 -0
- function_sequence/__main__.py +3 -0
- function_sequence/_budget.py +66 -0
- function_sequence/_validation.py +125 -0
- function_sequence/application.py +33 -0
- function_sequence/cli.py +146 -0
- function_sequence/control.py +31 -0
- function_sequence/definitions.py +191 -0
- function_sequence/errors.py +58 -0
- function_sequence/expressions.py +114 -0
- function_sequence/operations.py +191 -0
- function_sequence/pipeline.py +279 -0
- function_sequence/py.typed +0 -0
- function_sequence/runtime.py +302 -0
- function_sequence/storage.py +164 -0
- function_sequence/terminal.py +193 -0
- function_sequence/values.py +77 -0
- function_sequence/workflow.py +135 -0
- function_sequence/workflow_cli.py +108 -0
- function_sequence-0.2.0.dist-info/METADATA +101 -0
- function_sequence-0.2.0.dist-info/RECORD +24 -0
- function_sequence-0.2.0.dist-info/WHEEL +4 -0
- function_sequence-0.2.0.dist-info/entry_points.txt +3 -0
- function_sequence-0.2.0.dist-info/licenses/LICENSE.md +22 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Cooperative function sequences with explicit, serializable boundaries."""
|
|
2
|
+
|
|
3
|
+
from .definitions import Ref, Script
|
|
4
|
+
from .control import Control, pause
|
|
5
|
+
from .errors import (
|
|
6
|
+
BusyError, CheckpointError, DefinitionError, DefinitionMismatchError, ExecutionLimitError,
|
|
7
|
+
InvalidValueError, RecoveryRequiredError,
|
|
8
|
+
ResolutionError, ScriptError, StepFailedError, PipelineError, StepError,
|
|
9
|
+
)
|
|
10
|
+
from .runtime import Event, RunResult, Status
|
|
11
|
+
from .storage import CheckpointStore
|
|
12
|
+
from .operations import NativeResolver, Operation, Resolver, validate_json_value
|
|
13
|
+
from .expressions import Input
|
|
14
|
+
from .pipeline import BoundPipeline, Pipeline, Result, Step, compile_script
|
|
15
|
+
from ._budget import execution_scope
|
|
16
|
+
from .workflow import DocumentError, Workflow, load, loads
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"BusyError", "CheckpointError", "CheckpointStore", "Control", "DefinitionError",
|
|
20
|
+
"ExecutionLimitError", "DefinitionMismatchError", "Event", "InvalidValueError",
|
|
21
|
+
"RecoveryRequiredError", "Ref", "ResolutionError", "RunResult", "Script",
|
|
22
|
+
"DocumentError", "Workflow", "load", "loads",
|
|
23
|
+
"compile_script", "execution_scope", "Input", "Step", "Pipeline", "BoundPipeline", "Result", "PipelineError", "StepError",
|
|
24
|
+
"NativeResolver", "Operation", "Resolver", "validate_json_value",
|
|
25
|
+
"ScriptError", "Status", "StepFailedError", "pause",
|
|
26
|
+
]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Invocation-local limits shared across explicitly nested compositions."""
|
|
2
|
+
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from contextvars import ContextVar
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from threading import Lock
|
|
7
|
+
|
|
8
|
+
from .errors import DefinitionError, ExecutionLimitError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class _Budget:
|
|
13
|
+
maximum: int
|
|
14
|
+
max_depth: int
|
|
15
|
+
parent: object = None
|
|
16
|
+
used_steps: int = 0
|
|
17
|
+
lock: Lock = field(default_factory=Lock)
|
|
18
|
+
|
|
19
|
+
def consume(self):
|
|
20
|
+
with self.lock:
|
|
21
|
+
if self.used_steps >= self.maximum:
|
|
22
|
+
raise ExecutionLimitError("Composition operation budget exhausted")
|
|
23
|
+
if self.parent is not None:
|
|
24
|
+
self.parent.consume()
|
|
25
|
+
self.used_steps += 1
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_current = ContextVar("function_sequence_execution_budget", default=None)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@contextmanager
|
|
32
|
+
def execution_scope(*, max_steps=None, max_depth=None):
|
|
33
|
+
"""Bound resolved operation calls across nested executions in this context.
|
|
34
|
+
|
|
35
|
+
An application can select tighter limits at any boundary; descendant calls
|
|
36
|
+
consume both the local budget and every enclosing budget. Native Script functions
|
|
37
|
+
remain bounded by their explicit definition; each resolved operation costs
|
|
38
|
+
one step, including a composite and each of its descendant operations.
|
|
39
|
+
"""
|
|
40
|
+
for value, maximum in ((max_steps, 1_000_000), (max_depth, 64)):
|
|
41
|
+
if value is not None and (type(value) is not int or not 1 <= value <= maximum):
|
|
42
|
+
raise DefinitionError("Use finite positive execution limits")
|
|
43
|
+
parent = _current.get()
|
|
44
|
+
if parent is None:
|
|
45
|
+
budget, depth = _Budget(max_steps or 256, max_depth or 16), 0
|
|
46
|
+
else:
|
|
47
|
+
inherited, depth = parent
|
|
48
|
+
if max_steps is None and max_depth is None:
|
|
49
|
+
budget = inherited
|
|
50
|
+
else:
|
|
51
|
+
budget = _Budget(max_steps or inherited.maximum,
|
|
52
|
+
min(max_depth or inherited.max_depth, inherited.max_depth),
|
|
53
|
+
parent=inherited)
|
|
54
|
+
if depth >= budget.max_depth:
|
|
55
|
+
raise ExecutionLimitError("Composition nesting limit exceeded")
|
|
56
|
+
token = _current.set((budget, depth + 1))
|
|
57
|
+
try:
|
|
58
|
+
yield budget
|
|
59
|
+
finally:
|
|
60
|
+
_current.reset(token)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def consume_operation():
|
|
64
|
+
active = _current.get()
|
|
65
|
+
if active is not None:
|
|
66
|
+
active[0].consume()
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Validation for the documented schema subset, with unsupported keywords rejected."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .errors import DefinitionError
|
|
10
|
+
|
|
11
|
+
_KEYWORDS = frozenset({
|
|
12
|
+
"$schema", "title", "description", "default", "examples", "type", "enum",
|
|
13
|
+
"anyOf", "properties", "required", "additionalProperties", "items",
|
|
14
|
+
})
|
|
15
|
+
_TYPES = frozenset({"null", "boolean", "integer", "number", "string", "array", "object"})
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ValueValidationError(ValueError):
|
|
19
|
+
"""A finite JSON value does not match the declared subset."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def check_schema(schema: Mapping[str, Any]) -> None:
|
|
23
|
+
if not isinstance(schema, Mapping):
|
|
24
|
+
raise DefinitionError("Schema nodes must be objects.")
|
|
25
|
+
unknown = set(schema) - _KEYWORDS
|
|
26
|
+
if unknown:
|
|
27
|
+
raise DefinitionError(f"Unsupported schema keywords: {', '.join(sorted(unknown))}.")
|
|
28
|
+
if "type" in schema:
|
|
29
|
+
types = schema["type"]
|
|
30
|
+
if isinstance(types, str):
|
|
31
|
+
types = (types,)
|
|
32
|
+
if not isinstance(types, (list, tuple)) or not types or any(
|
|
33
|
+
not isinstance(item, str) or item not in _TYPES for item in types
|
|
34
|
+
):
|
|
35
|
+
raise DefinitionError("Schema type must be a supported JSON type or nonempty type list.")
|
|
36
|
+
for annotation in ("$schema", "title", "description"):
|
|
37
|
+
if annotation in schema and not isinstance(schema[annotation], str):
|
|
38
|
+
raise DefinitionError(f"Schema {annotation} must be a string.")
|
|
39
|
+
if "examples" in schema and not isinstance(schema["examples"], (list, tuple)):
|
|
40
|
+
raise DefinitionError("Schema examples must be an array.")
|
|
41
|
+
if "type" in schema and len(types) != len(set(types)):
|
|
42
|
+
raise DefinitionError("Schema type names must be unique.")
|
|
43
|
+
if "enum" in schema and (not isinstance(schema["enum"], (list, tuple)) or not schema["enum"]):
|
|
44
|
+
raise DefinitionError("Schema enum must be a nonempty array.")
|
|
45
|
+
if "anyOf" in schema:
|
|
46
|
+
branches = schema["anyOf"]
|
|
47
|
+
if not isinstance(branches, (list, tuple)) or not branches:
|
|
48
|
+
raise DefinitionError("Schema anyOf must be a nonempty array.")
|
|
49
|
+
for branch in branches:
|
|
50
|
+
check_schema(branch)
|
|
51
|
+
properties = schema.get("properties", {})
|
|
52
|
+
if not isinstance(properties, Mapping):
|
|
53
|
+
raise DefinitionError("Schema properties must be an object.")
|
|
54
|
+
for child in properties.values():
|
|
55
|
+
check_schema(child)
|
|
56
|
+
if "required" in schema:
|
|
57
|
+
required = schema["required"]
|
|
58
|
+
if not isinstance(required, (list, tuple)) or any(not isinstance(item, str) for item in required):
|
|
59
|
+
raise DefinitionError("Schema required must be an array of property names.")
|
|
60
|
+
if len(required) != len(set(required)):
|
|
61
|
+
raise DefinitionError("Schema required names must be unique.")
|
|
62
|
+
additional = schema.get("additionalProperties", True)
|
|
63
|
+
if not isinstance(additional, bool):
|
|
64
|
+
check_schema(additional)
|
|
65
|
+
if additional is False and any(name not in properties for name in schema.get("required", ())):
|
|
66
|
+
raise DefinitionError("A closed schema requires a property it does not declare.")
|
|
67
|
+
if "items" in schema:
|
|
68
|
+
check_schema(schema["items"])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _matches(value: Any, kind: str) -> bool:
|
|
72
|
+
if kind == "null":
|
|
73
|
+
return value is None
|
|
74
|
+
if kind == "boolean":
|
|
75
|
+
return isinstance(value, bool)
|
|
76
|
+
if kind == "integer":
|
|
77
|
+
return type(value) is int or (type(value) is float and math.isfinite(value) and value.is_integer())
|
|
78
|
+
if kind == "number":
|
|
79
|
+
return type(value) is int or (type(value) is float and math.isfinite(value))
|
|
80
|
+
return isinstance(value, {"string": str, "array": list, "object": dict}[kind])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _equal(first: Any, second: Any) -> bool:
|
|
84
|
+
if isinstance(first, bool) != isinstance(second, bool):
|
|
85
|
+
return False
|
|
86
|
+
if isinstance(first, Mapping) and isinstance(second, Mapping):
|
|
87
|
+
return first.keys() == second.keys() and all(_equal(first[key], second[key]) for key in first)
|
|
88
|
+
if isinstance(first, (tuple, list)) and isinstance(second, (tuple, list)):
|
|
89
|
+
return len(first) == len(second) and all(_equal(a, b) for a, b in zip(first, second))
|
|
90
|
+
return first == second
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def validate_value(schema: Mapping[str, Any], value: Any, path: str = "$arguments") -> None:
|
|
94
|
+
if "type" in schema:
|
|
95
|
+
types = schema["type"]
|
|
96
|
+
types = (types,) if isinstance(types, str) else types
|
|
97
|
+
if not any(_matches(value, kind) for kind in types):
|
|
98
|
+
raise ValueValidationError(f"{path}: expected {' or '.join(types)}.")
|
|
99
|
+
if "enum" in schema and not any(_equal(value, item) for item in schema["enum"]):
|
|
100
|
+
raise ValueValidationError(f"{path}: value is outside the declared enum.")
|
|
101
|
+
if "anyOf" in schema:
|
|
102
|
+
for branch in schema["anyOf"]:
|
|
103
|
+
try:
|
|
104
|
+
validate_value(branch, value, path)
|
|
105
|
+
break
|
|
106
|
+
except ValueValidationError:
|
|
107
|
+
pass
|
|
108
|
+
else:
|
|
109
|
+
raise ValueValidationError(f"{path}: value does not match any declared type.")
|
|
110
|
+
if isinstance(value, dict):
|
|
111
|
+
properties = schema.get("properties", {})
|
|
112
|
+
for name in schema.get("required", ()):
|
|
113
|
+
if name not in value:
|
|
114
|
+
raise ValueValidationError(f"{path}.{name}: required argument is missing.")
|
|
115
|
+
additional = schema.get("additionalProperties", True)
|
|
116
|
+
for name, item in value.items():
|
|
117
|
+
if name in properties:
|
|
118
|
+
validate_value(properties[name], item, f"{path}.{name}")
|
|
119
|
+
elif additional is False:
|
|
120
|
+
raise ValueValidationError(f"{path}.{name}: unexpected argument.")
|
|
121
|
+
elif isinstance(additional, Mapping):
|
|
122
|
+
validate_value(additional, item, f"{path}.{name}")
|
|
123
|
+
if isinstance(value, list) and "items" in schema:
|
|
124
|
+
for index, item in enumerate(value):
|
|
125
|
+
validate_value(schema["items"], item, f"{path}[{index}]")
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Application outcomes shared by command-line and optional interactive hosts."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
async def execute(workflow, resolver, *, resolver_version, inputs, checkpoint=None,
|
|
7
|
+
resume=False, pace="auto", retry=False, restart=False, control=None, observer=None):
|
|
8
|
+
"""Run selected code without installing input/signal/terminal policy.
|
|
9
|
+
|
|
10
|
+
An explicit checkpoint selects Function Sequence. New execution requires a new path;
|
|
11
|
+
resume requires existing progress. Recovery choices retain Function Sequence semantics.
|
|
12
|
+
"""
|
|
13
|
+
bound = workflow.bind(resolver, resolver_version=resolver_version)
|
|
14
|
+
if checkpoint is None:
|
|
15
|
+
if resume or retry or restart or pace != "auto" or control is not None or observer is not None:
|
|
16
|
+
raise ValueError("Lifecycle options require an explicit checkpoint")
|
|
17
|
+
result = await bound.arun(inputs)
|
|
18
|
+
return {"schema": 1, "status": "completed", "fingerprint": bound.fingerprint,
|
|
19
|
+
"completed": [step.id for step in bound.definition.steps], "results": result.results,
|
|
20
|
+
"outputs": result.outputs, "run_id": None}
|
|
21
|
+
if bool(resume) != Path(checkpoint).exists():
|
|
22
|
+
raise ValueError("Resume requires existing progress; run requires a new checkpoint path")
|
|
23
|
+
if (retry or restart) and not resume:
|
|
24
|
+
raise ValueError("Recovery requires explicit resume")
|
|
25
|
+
from .pipeline import compile_script
|
|
26
|
+
|
|
27
|
+
script = compile_script(bound, inputs, asynchronous=True)
|
|
28
|
+
progress = await script.arun(checkpoint=checkpoint, pace=pace, retry=retry, restart=restart,
|
|
29
|
+
control=control, observer=observer)
|
|
30
|
+
outputs = bound.finish(inputs, progress.results).outputs if progress.status == "completed" else None
|
|
31
|
+
return {"schema": 1, "status": str(progress.status), "fingerprint": bound.fingerprint,
|
|
32
|
+
"completed": list(progress.completed), "results": progress.results,
|
|
33
|
+
"outputs": outputs, "run_id": progress.run_id}
|
function_sequence/cli.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Explicit trusted-code invocation and passive checkpoint management."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from importlib import import_module
|
|
7
|
+
from importlib.metadata import version
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import re
|
|
11
|
+
import signal
|
|
12
|
+
import sys
|
|
13
|
+
from threading import current_thread, main_thread
|
|
14
|
+
|
|
15
|
+
from .control import Control
|
|
16
|
+
from .definitions import Script
|
|
17
|
+
from .errors import DefinitionError, ScriptError
|
|
18
|
+
from .runtime import Status
|
|
19
|
+
from .storage import CheckpointStore
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _parser():
|
|
23
|
+
parser = argparse.ArgumentParser(prog="function-sequence", description="Run trusted Python steps with JSON progress.")
|
|
24
|
+
parser.add_argument("--version", action="version", version=version("function-sequence"))
|
|
25
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
26
|
+
run = commands.add_parser("run", help="import an explicitly selected module:script")
|
|
27
|
+
run.add_argument("target", help="trusted module:attribute containing a Script")
|
|
28
|
+
run.add_argument("--checkpoint", required=True, help="progress file in an existing local directory")
|
|
29
|
+
run.add_argument("--pace", choices=("auto", "function", "pause"), default="auto")
|
|
30
|
+
run.add_argument("--async", dest="asynchronous", action="store_true", help="await asynchronous steps")
|
|
31
|
+
run.add_argument("--interactive", action="store_true", help="prompt after each function; Return continues")
|
|
32
|
+
run.add_argument("--console-log", action="store_true", help="print structural events without values")
|
|
33
|
+
recovery = run.add_mutually_exclusive_group()
|
|
34
|
+
recovery.add_argument("--restart", action="store_true", help="discard progress and repeat the entire script")
|
|
35
|
+
recovery.add_argument("--retry", action="store_true", help="permit repetition of the uncertain current step")
|
|
36
|
+
status = commands.add_parser("status", help="inspect progress without importing script code")
|
|
37
|
+
status.add_argument("checkpoint")
|
|
38
|
+
delete = commands.add_parser("delete", help="explicitly remove only the selected progress file")
|
|
39
|
+
delete.add_argument("checkpoint")
|
|
40
|
+
commands.add_parser("workflow", help="inspect/run passive workflows with the optional cli profile", add_help=False)
|
|
41
|
+
return parser
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _load_target(target):
|
|
45
|
+
module, separator, attribute = target.partition(":")
|
|
46
|
+
if not separator or not re.fullmatch(r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*", module) or not attribute.isidentifier():
|
|
47
|
+
raise DefinitionError("Target must be a trusted module:attribute")
|
|
48
|
+
try:
|
|
49
|
+
script = getattr(import_module(module), attribute)
|
|
50
|
+
except Exception as error:
|
|
51
|
+
raise DefinitionError(f"Trusted script module could not be loaded ({type(error).__name__})") from error
|
|
52
|
+
if not isinstance(script, Script):
|
|
53
|
+
raise DefinitionError("Selected attribute must be a Script")
|
|
54
|
+
return script
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@contextmanager
|
|
58
|
+
def _module_path():
|
|
59
|
+
# Console entry points otherwise omit the current directory from sys.path.
|
|
60
|
+
directory = str(Path.cwd())
|
|
61
|
+
sys.path.insert(0, directory)
|
|
62
|
+
try:
|
|
63
|
+
yield
|
|
64
|
+
finally:
|
|
65
|
+
sys.path.remove(directory)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@contextmanager
|
|
69
|
+
def _cooperative_sigint(control):
|
|
70
|
+
installed = current_thread() is main_thread()
|
|
71
|
+
if installed:
|
|
72
|
+
previous = signal.getsignal(signal.SIGINT)
|
|
73
|
+
signal.signal(signal.SIGINT, lambda _number, _frame: control.request_pause())
|
|
74
|
+
try:
|
|
75
|
+
yield
|
|
76
|
+
finally:
|
|
77
|
+
if installed:
|
|
78
|
+
signal.signal(signal.SIGINT, previous)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _summary(data):
|
|
82
|
+
if data is None:
|
|
83
|
+
return {"status": "missing"}
|
|
84
|
+
return {"status": data["status"], "next_step": data["cursor"],
|
|
85
|
+
"completed_count": len(data["results"]), "active_step": data["active_step"],
|
|
86
|
+
"error_type": data["error_type"], "run_id": data["run_id"]}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _run(args):
|
|
90
|
+
script = _load_target(args.target)
|
|
91
|
+
control = Control()
|
|
92
|
+
first = True
|
|
93
|
+
while True:
|
|
94
|
+
options = dict(checkpoint=args.checkpoint, pace="function" if args.interactive else args.pace,
|
|
95
|
+
control=control, console_log=args.console_log,
|
|
96
|
+
restart=args.restart and first, retry=args.retry and first)
|
|
97
|
+
with _cooperative_sigint(control):
|
|
98
|
+
result = asyncio.run(script.arun(**options)) if args.asynchronous else script.run(**options)
|
|
99
|
+
first = False
|
|
100
|
+
print(json.dumps({"status": str(result.status), "next_step": result.next_step,
|
|
101
|
+
"completed_count": len(result.completed), "run_id": result.run_id}))
|
|
102
|
+
if result.status == Status.COMPLETED or not args.interactive or control.pause_requested:
|
|
103
|
+
return 0
|
|
104
|
+
try:
|
|
105
|
+
reply = input("Return to continue; any text stops: ")
|
|
106
|
+
except EOFError:
|
|
107
|
+
return 0
|
|
108
|
+
except KeyboardInterrupt:
|
|
109
|
+
print("\nProgress paused.")
|
|
110
|
+
return 130
|
|
111
|
+
if reply.strip():
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def main(argv=None) -> int:
|
|
116
|
+
arguments = list(sys.argv[1:] if argv is None else argv)
|
|
117
|
+
if arguments and arguments[0] == "workflow":
|
|
118
|
+
try:
|
|
119
|
+
from .workflow_cli import main as workflow_main
|
|
120
|
+
except ModuleNotFoundError as error:
|
|
121
|
+
if error.name == "expose_interface":
|
|
122
|
+
print("Install function-sequence[cli] for workflow commands.", file=sys.stderr)
|
|
123
|
+
return 2
|
|
124
|
+
raise
|
|
125
|
+
result = workflow_main(arguments[1:])
|
|
126
|
+
return 0 if result is None else result
|
|
127
|
+
parser = _parser()
|
|
128
|
+
args = parser.parse_args(arguments)
|
|
129
|
+
try:
|
|
130
|
+
if args.command == "status":
|
|
131
|
+
print(json.dumps(_summary(CheckpointStore(args.checkpoint).read())))
|
|
132
|
+
return 0
|
|
133
|
+
if args.command == "delete":
|
|
134
|
+
removed = CheckpointStore(args.checkpoint).delete()
|
|
135
|
+
print("Progress deleted." if removed else "No progress file.")
|
|
136
|
+
return 0
|
|
137
|
+
if args.interactive and args.pace != "auto":
|
|
138
|
+
parser.error("--interactive supplies function pacing; omit --pace")
|
|
139
|
+
with _module_path():
|
|
140
|
+
return _run(args)
|
|
141
|
+
except KeyboardInterrupt:
|
|
142
|
+
print("Interrupted; inspect progress before continuing.", file=sys.stderr)
|
|
143
|
+
return 130
|
|
144
|
+
except (ScriptError, ValueError, TypeError, OSError) as error:
|
|
145
|
+
print(f"function-sequence: {error}", file=sys.stderr)
|
|
146
|
+
return 2
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Opt-in cooperative controls; importing installs no input or signal hooks."""
|
|
2
|
+
|
|
3
|
+
from contextvars import ContextVar
|
|
4
|
+
from threading import Event
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Control:
|
|
8
|
+
"""A pause request that input adapters may set from another thread."""
|
|
9
|
+
|
|
10
|
+
def __init__(self) -> None:
|
|
11
|
+
self._pause = Event()
|
|
12
|
+
|
|
13
|
+
@property
|
|
14
|
+
def pause_requested(self) -> bool:
|
|
15
|
+
return self._pause.is_set()
|
|
16
|
+
|
|
17
|
+
def request_pause(self) -> None:
|
|
18
|
+
self._pause.set()
|
|
19
|
+
|
|
20
|
+
def reset(self) -> None:
|
|
21
|
+
self._pause.clear()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_current: ContextVar[tuple[Control, str] | None] = ContextVar("function_sequence_control", default=None)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def pause() -> None:
|
|
28
|
+
"""Request a pause after this function, only while running with pace='pause'."""
|
|
29
|
+
current = _current.get()
|
|
30
|
+
if current is not None and current[1] == "pause":
|
|
31
|
+
current[0].request_pause()
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Named function queues and explicit references to preceding results."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import hashlib
|
|
5
|
+
import inspect
|
|
6
|
+
import re
|
|
7
|
+
from threading import Lock
|
|
8
|
+
from typing import Any, Callable
|
|
9
|
+
|
|
10
|
+
from .errors import BusyError, DefinitionError, InvalidValueError, ResolutionError
|
|
11
|
+
from .values import MAX_DEPTH, copy_json, encode_json
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _identifier(value: str) -> str:
|
|
15
|
+
if type(value) is not str or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}", value):
|
|
16
|
+
raise DefinitionError("Names must be 1–128 ASCII letters, digits, dots, hyphens or underscores")
|
|
17
|
+
return value
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _is_async_callable(function):
|
|
21
|
+
return inspect.iscoroutinefunction(function) or inspect.iscoroutinefunction(getattr(type(function), "__call__", None))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Ref:
|
|
26
|
+
"""A completed step's JSON result, optionally selected by key/index."""
|
|
27
|
+
|
|
28
|
+
step_id: str
|
|
29
|
+
path: tuple[str | int, ...] = ()
|
|
30
|
+
|
|
31
|
+
def __post_init__(self):
|
|
32
|
+
_identifier(self.step_id)
|
|
33
|
+
if type(self.path) is not tuple or len(self.path) > MAX_DEPTH:
|
|
34
|
+
raise DefinitionError("Reference path must be a bounded tuple")
|
|
35
|
+
if any(type(part) not in (str, int) or (type(part) is int and part < 0)
|
|
36
|
+
for part in self.path):
|
|
37
|
+
raise DefinitionError("Reference paths use string keys or nonnegative indexes")
|
|
38
|
+
encode_json(list(self.path))
|
|
39
|
+
|
|
40
|
+
def __getitem__(self, key: str | int) -> "Ref":
|
|
41
|
+
return Ref(self.step_id, (*self.path, key))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _copy_argument(value: Any, previous: set[str], depth: int = 0) -> Any:
|
|
45
|
+
if depth > MAX_DEPTH:
|
|
46
|
+
raise DefinitionError("Argument nesting exceeds the supported limit")
|
|
47
|
+
if isinstance(value, Ref):
|
|
48
|
+
if value.step_id not in previous:
|
|
49
|
+
raise DefinitionError("References must point to earlier function steps")
|
|
50
|
+
return value
|
|
51
|
+
if type(value) is list:
|
|
52
|
+
return [_copy_argument(item, previous, depth + 1) for item in value]
|
|
53
|
+
if type(value) is dict:
|
|
54
|
+
if any(type(key) is not str for key in value):
|
|
55
|
+
raise InvalidValueError("Argument object keys must be strings")
|
|
56
|
+
return {key: _copy_argument(item, previous, depth + 1) for key, item in value.items()}
|
|
57
|
+
return copy_json(value, depth)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _describe(value: Any) -> dict:
|
|
61
|
+
if isinstance(value, Ref):
|
|
62
|
+
return {"ref": {"step": value.step_id, "path": list(value.path)}}
|
|
63
|
+
if type(value) is list:
|
|
64
|
+
return {"list": [_describe(item) for item in value]}
|
|
65
|
+
if type(value) is dict:
|
|
66
|
+
return {"dict": {key: _describe(item) for key, item in value.items()}}
|
|
67
|
+
return {"value": value}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def resolve(value: Any, results: dict) -> Any:
|
|
71
|
+
if isinstance(value, Ref):
|
|
72
|
+
try:
|
|
73
|
+
selected = results[value.step_id]
|
|
74
|
+
for part in value.path:
|
|
75
|
+
if type(part) is str and type(selected) is dict:
|
|
76
|
+
selected = selected[part]
|
|
77
|
+
elif type(part) is int and type(selected) is list:
|
|
78
|
+
selected = selected[part]
|
|
79
|
+
else:
|
|
80
|
+
raise KeyError
|
|
81
|
+
return copy_json(selected)
|
|
82
|
+
except (KeyError, IndexError):
|
|
83
|
+
raise ResolutionError("Result reference cannot be resolved") from None
|
|
84
|
+
if type(value) is list:
|
|
85
|
+
return [resolve(item, results) for item in value]
|
|
86
|
+
if type(value) is dict:
|
|
87
|
+
return {key: resolve(item, results) for key, item in value.items()}
|
|
88
|
+
return value
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class _Step:
|
|
93
|
+
step_id: str
|
|
94
|
+
function: Callable | None
|
|
95
|
+
action: str
|
|
96
|
+
args: tuple
|
|
97
|
+
kwargs: dict
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Script:
|
|
101
|
+
"""Build a sequential script. Bump version when callable behavior changes."""
|
|
102
|
+
|
|
103
|
+
def __init__(self, name: str, *, version: str = "1") -> None:
|
|
104
|
+
self._name = _identifier(name)
|
|
105
|
+
self._version = _identifier(version)
|
|
106
|
+
self._steps: list[_Step] = []
|
|
107
|
+
self._lock = Lock()
|
|
108
|
+
self._state = None
|
|
109
|
+
self._checkpoint_path = None
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def name(self) -> str:
|
|
113
|
+
return self._name
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def version(self) -> str:
|
|
117
|
+
return self._version
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def step_ids(self) -> tuple[str, ...]:
|
|
121
|
+
return tuple(step.step_id for step in self._steps)
|
|
122
|
+
|
|
123
|
+
def add_function(self, function: Callable, /, *args,
|
|
124
|
+
step_id: str | None = None, **kwargs) -> Ref:
|
|
125
|
+
if not callable(function):
|
|
126
|
+
raise DefinitionError("Expected a callable")
|
|
127
|
+
selected = step_id if step_id is not None else getattr(function, "__name__", None)
|
|
128
|
+
selected = _identifier(selected)
|
|
129
|
+
try:
|
|
130
|
+
inspect.signature(function).bind(*args, **kwargs)
|
|
131
|
+
except (TypeError, ValueError):
|
|
132
|
+
raise DefinitionError("Function arguments do not match an inspectable signature") from None
|
|
133
|
+
action = f"{getattr(function, '__module__', type(function).__module__)}:{getattr(function, '__qualname__', type(function).__qualname__)}"
|
|
134
|
+
self._append(selected, function, action, args, kwargs)
|
|
135
|
+
return Ref(selected)
|
|
136
|
+
|
|
137
|
+
def add_pause(self, *, step_id: str) -> None:
|
|
138
|
+
self._append(_identifier(step_id), None, "pause", (), {})
|
|
139
|
+
|
|
140
|
+
def _append(self, step_id, function, action, args, kwargs):
|
|
141
|
+
if not self._lock.acquire(blocking=False):
|
|
142
|
+
raise BusyError("Script is executing")
|
|
143
|
+
try:
|
|
144
|
+
if self._state is not None:
|
|
145
|
+
raise DefinitionError("A script with progress cannot be changed; build a new definition")
|
|
146
|
+
if step_id in self.step_ids:
|
|
147
|
+
raise DefinitionError("Step IDs must be unique")
|
|
148
|
+
previous = {step.step_id for step in self._steps if step.function is not None}
|
|
149
|
+
copied_args = tuple(_copy_argument(value, previous) for value in args)
|
|
150
|
+
copied_kwargs = {key: _copy_argument(value, previous) for key, value in kwargs.items()}
|
|
151
|
+
candidate = _Step(step_id, function, action, copied_args, copied_kwargs)
|
|
152
|
+
self._steps.append(candidate)
|
|
153
|
+
try:
|
|
154
|
+
encode_json(self.manifest)
|
|
155
|
+
except BaseException:
|
|
156
|
+
self._steps.pop()
|
|
157
|
+
raise
|
|
158
|
+
finally:
|
|
159
|
+
self._lock.release()
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def manifest(self) -> dict:
|
|
163
|
+
"""Return fresh passive metadata. No callables are reconstructed from it."""
|
|
164
|
+
return {"schema": 1, "name": self.name, "version": self.version, "steps": [
|
|
165
|
+
{"id": step.step_id, "action": step.action,
|
|
166
|
+
"kind": "pause" if step.function is None else "function",
|
|
167
|
+
"args": [_describe(value) for value in step.args],
|
|
168
|
+
"kwargs": {key: _describe(value) for key, value in step.kwargs.items()}}
|
|
169
|
+
for step in self._steps]}
|
|
170
|
+
|
|
171
|
+
@property
|
|
172
|
+
def fingerprint(self) -> str:
|
|
173
|
+
return hashlib.sha256(encode_json(self.manifest)).hexdigest()
|
|
174
|
+
|
|
175
|
+
def run(self, **options):
|
|
176
|
+
"""Run synchronously; repeated calls continue from completed steps."""
|
|
177
|
+
from .runtime import run
|
|
178
|
+
|
|
179
|
+
return run(self, **options)
|
|
180
|
+
|
|
181
|
+
def delete_progress(self, *, checkpoint=None) -> bool:
|
|
182
|
+
"""Discard selected progress without executing the script."""
|
|
183
|
+
from .runtime import delete_progress
|
|
184
|
+
|
|
185
|
+
return delete_progress(self, checkpoint)
|
|
186
|
+
|
|
187
|
+
async def arun(self, **options):
|
|
188
|
+
"""Await the queue using the same progress and pacing rules as run()."""
|
|
189
|
+
from .runtime import arun
|
|
190
|
+
|
|
191
|
+
return await arun(self, **options)
|