irimi-sdk 0.2.0.dev0__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.
Files changed (48) hide show
  1. irimi/__init__.py +4 -0
  2. irimi/_aiohttp_patch.py +371 -0
  3. irimi/_aiohttp_serving.py +216 -0
  4. irimi/_atomic_total.py +14 -0
  5. irimi/_bodies.py +64 -0
  6. irimi/_credential_headers.py +52 -0
  7. irimi/_decorators.py +236 -0
  8. irimi/_delivery.py +70 -0
  9. irimi/_divergence.py +60 -0
  10. irimi/_drops.py +24 -0
  11. irimi/_errors.py +14 -0
  12. irimi/_exporter.py +193 -0
  13. irimi/_function_answers.py +87 -0
  14. irimi/_git.py +37 -0
  15. irimi/_httpx_patch.py +236 -0
  16. irimi/_interception.py +174 -0
  17. irimi/_labeled_calls.py +116 -0
  18. irimi/_llm_providers.py +57 -0
  19. irimi/_object_fields.py +32 -0
  20. irimi/_outbound_calls.py +190 -0
  21. irimi/_patching.py +58 -0
  22. irimi/_rebuilding.py +97 -0
  23. irimi/_recorded_calls.py +231 -0
  24. irimi/_recording.py +122 -0
  25. irimi/_recording_loader.py +63 -0
  26. irimi/_replay_child.py +156 -0
  27. irimi/_replay_decisions.py +120 -0
  28. irimi/_replay_fields.py +16 -0
  29. irimi/_replay_proxy.py +328 -0
  30. irimi/_replay_refusals.py +5 -0
  31. irimi/_response_recording.py +74 -0
  32. irimi/_sdk.py +318 -0
  33. irimi/_serialisation.py +114 -0
  34. irimi/_status_reasons.py +10 -0
  35. irimi/_unpatched_clients.py +105 -0
  36. irimi/_url_credentials.py +11 -0
  37. irimi/_urllib3_patch.py +465 -0
  38. irimi/_urllib3_serving.py +81 -0
  39. irimi/_wire/__init__.py +56 -0
  40. irimi/_wire/call_roles.py +32 -0
  41. irimi/_wire/events.py +209 -0
  42. irimi/_wire/field_names.py +80 -0
  43. irimi/_wire/json_value.py +3 -0
  44. irimi/_wire/markers.py +49 -0
  45. irimi/py.typed +0 -0
  46. irimi_sdk-0.2.0.dev0.dist-info/METADATA +81 -0
  47. irimi_sdk-0.2.0.dev0.dist-info/RECORD +48 -0
  48. irimi_sdk-0.2.0.dev0.dist-info/WHEEL +4 -0
irimi/_recording.py ADDED
@@ -0,0 +1,122 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import secrets
5
+ from collections.abc import Callable, Iterator, Mapping
6
+ from contextlib import contextmanager
7
+ from contextvars import ContextVar
8
+ from dataclasses import dataclass
9
+
10
+ from irimi._wire import EndEvent, Event, JsonValue, StartEvent, field_names
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Payload:
15
+ fields: Mapping[str, JsonValue]
16
+ approximate_size: int
17
+
18
+
19
+ class Run:
20
+ def __init__(self, trace_id: str, is_workflow: bool) -> None:
21
+ self.trace_id = trace_id
22
+ self.is_workflow = is_workflow
23
+ self._calls_started = itertools.count()
24
+ self._events_produced = itertools.count(1)
25
+
26
+ def count_start(self) -> int:
27
+ next(self._events_produced)
28
+ return next(self._calls_started)
29
+
30
+ def count_end(self) -> int:
31
+ return next(self._events_produced)
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class ActiveCall:
36
+ run: Run
37
+ span_id: str
38
+ parent: ActiveCall | None
39
+
40
+
41
+ class Recorder:
42
+ def __init__(
43
+ self, enqueue: Callable[[Event, int], None], read_clock: Callable[[], int]
44
+ ) -> None:
45
+ self._enqueue = enqueue
46
+ self._read_clock = read_clock
47
+ self._current_call: ContextVar[ActiveCall | None] = ContextVar(
48
+ "irimi_current_call", default=None
49
+ )
50
+
51
+ def find_current_call(self) -> ActiveCall | None:
52
+ return self._current_call.get()
53
+
54
+ @contextmanager
55
+ def make_current(self, call: ActiveCall | None) -> Iterator[None]:
56
+ token = self._current_call.set(call)
57
+ try:
58
+ yield
59
+ finally:
60
+ self._current_call.reset(token)
61
+
62
+ def begin_call(self, kind: str, name: str, payload: Payload) -> ActiveCall:
63
+ call = self.begin_detached_call(kind, name, payload)
64
+ self._current_call.set(call)
65
+ return call
66
+
67
+ def end_call(self, call: ActiveCall, payload: Payload) -> None:
68
+ self._current_call.set(call.parent)
69
+ self._write_end(call, payload, is_run_end=call.parent is None and call.run.is_workflow)
70
+
71
+ def begin_detached_call(self, kind: str, name: str, payload: Payload) -> ActiveCall:
72
+ parent = self._current_call.get()
73
+ run = parent.run if parent else Run(_new_trace_id(), is_workflow=kind == "workflow")
74
+ call = ActiveCall(run=run, span_id=_new_span_id(), parent=parent)
75
+ self._enqueue(
76
+ StartEvent(
77
+ id=_new_event_id(),
78
+ type="start",
79
+ trace_id=run.trace_id,
80
+ span_id=call.span_id,
81
+ time_unix_nano=self._read_clock(),
82
+ parent_span_id=parent.span_id if parent else None,
83
+ kind=kind,
84
+ name=name,
85
+ seq=run.count_start(),
86
+ fields=payload.fields,
87
+ ),
88
+ payload.approximate_size,
89
+ )
90
+ return call
91
+
92
+ def end_detached_call(self, call: ActiveCall, payload: Payload) -> None:
93
+ self._write_end(call, payload, is_run_end=False)
94
+
95
+ def _write_end(self, call: ActiveCall, payload: Payload, is_run_end: bool) -> None:
96
+ events_produced = call.run.count_end()
97
+ fields = payload.fields
98
+ if is_run_end:
99
+ fields = {**fields, field_names.EVENTS_PRODUCED: events_produced}
100
+ self._enqueue(
101
+ EndEvent(
102
+ id=_new_event_id(),
103
+ type="end",
104
+ trace_id=call.run.trace_id,
105
+ span_id=call.span_id,
106
+ time_unix_nano=self._read_clock(),
107
+ fields=fields,
108
+ ),
109
+ payload.approximate_size,
110
+ )
111
+
112
+
113
+ def _new_trace_id() -> str:
114
+ return secrets.token_hex(16)
115
+
116
+
117
+ def _new_span_id() -> str:
118
+ return secrets.token_hex(8)
119
+
120
+
121
+ def _new_event_id() -> str:
122
+ return secrets.token_hex(16)
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+
3
+ from irimi._delivery import REQUEST_TIMEOUT_SECONDS, Destination
4
+ from irimi._replay_refusals import ReplayRefusal
5
+ from irimi._wire import RUN_EVENTS_PATH, Event, JsonValue, ParsedBatch, field_names, parse_batch
6
+
7
+
8
+ def load_recorded_events(destination: Destination, trace_id: str) -> tuple[Event, ...]:
9
+ events: list[Event] = []
10
+ cursor: str | None = None
11
+ while True:
12
+ page = _read_page(destination, trace_id, cursor)
13
+ events.extend(page.batch.events)
14
+ cursor = _read_next_cursor(
15
+ page.batch.fields.get(field_names.NEXT_CURSOR), destination, trace_id
16
+ )
17
+ if cursor is None:
18
+ return tuple(events)
19
+
20
+
21
+ def _read_page(destination: Destination, trace_id: str, cursor: str | None) -> ParsedBatch:
22
+ import http.client
23
+ import json
24
+ import urllib.error
25
+ import urllib.parse
26
+ import urllib.request
27
+
28
+ url = destination.server_url.rstrip("/") + RUN_EVENTS_PATH.format(
29
+ trace_id=urllib.parse.quote(trace_id, safe="")
30
+ )
31
+ if cursor is not None:
32
+ url += "?" + urllib.parse.urlencode({"cursor": cursor})
33
+ headers = {"Authorization": f"Bearer {destination.api_key}"} if destination.api_key else {}
34
+ request = urllib.request.Request(url, headers=headers)
35
+ try:
36
+ with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as answer:
37
+ return parse_batch(json.loads(answer.read()))
38
+ except urllib.error.HTTPError as error:
39
+ raise ReplayRefusal(_explain_answer(error.code, destination, trace_id)) from error
40
+ except (ValueError, RecursionError) as error:
41
+ raise ReplayRefusal(_explain_unreadable(destination, trace_id)) from error
42
+ except (OSError, http.client.HTTPException) as error:
43
+ raise ReplayRefusal(
44
+ f"the server at {destination.server_url} could not be reached to read run {trace_id}"
45
+ ) from error
46
+
47
+
48
+ def _read_next_cursor(value: JsonValue, destination: Destination, trace_id: str) -> str | None:
49
+ if value is None or isinstance(value, str):
50
+ return value
51
+ raise ReplayRefusal(_explain_unreadable(destination, trace_id))
52
+
53
+
54
+ def _explain_answer(status: int, destination: Destination, trace_id: str) -> str:
55
+ if status == 404:
56
+ return f"the server at {destination.server_url} holds no run with id {trace_id}"
57
+ return f"the server at {destination.server_url} answered {status} when asked for run {trace_id}"
58
+
59
+
60
+ def _explain_unreadable(destination: Destination, trace_id: str) -> str:
61
+ return (
62
+ f"the server at {destination.server_url} did not answer with the events of run {trace_id}"
63
+ )
irimi/_replay_child.py ADDED
@@ -0,0 +1,156 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import importlib
5
+ import inspect
6
+ import os
7
+ import sys
8
+ from collections.abc import Callable, Mapping
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from irimi._rebuilding import RebuildError, rebuild
13
+ from irimi._replay_proxy import LiveCalls, catch_escaping_calls
14
+ from irimi._replay_refusals import ReplayRefusal
15
+ from irimi._sdk import REPLAY_RESULT_VARIABLE, SDK, SERVER_URL_VARIABLE, flush
16
+ from irimi._unpatched_clients import (
17
+ forget_libraries_only_irimi_loaded,
18
+ refuse_unallowed_clients,
19
+ )
20
+ from irimi._wire import JsonValue, StartEvent, field_names
21
+
22
+ SCRIPT_MODULE = "__main__"
23
+ IRIMI_FAILED = (
24
+ "the replay ran, but irimi hit a failure, so a call may have been faked "
25
+ "or part of the recording lost; irimi's warnings above say what"
26
+ )
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class WorkflowCall:
31
+ import_path: str
32
+ workflow: Callable[..., object]
33
+ arguments: list[object]
34
+ keyword_arguments: dict[str, object]
35
+
36
+
37
+ def main(environment_variables: Mapping[str, str], working_directory: Path) -> int:
38
+ try:
39
+ live_calls = LiveCalls()
40
+ modules_loaded_before_patching = frozenset(sys.modules)
41
+ recorded_run, replay = SDK.start_replay(
42
+ environment_variables, working_directory, live_calls
43
+ )
44
+ forget_libraries_only_irimi_loaded(replay, modules_loaded_before_patching)
45
+ catch_escaping_calls(live_calls, replay, environment_variables[SERVER_URL_VARIABLE])
46
+ workflow_call = _prepare_workflow_call(recorded_run.root)
47
+ refuse_unallowed_clients(replay, environment_variables, list(sys.modules))
48
+ except ReplayRefusal as refusal:
49
+ return _fail(str(refusal))
50
+ runs_started_before_the_call = len(replay.started_runs)
51
+ try:
52
+ _call_workflow(workflow_call)
53
+ except ReplayRefusal as refusal:
54
+ if not flush():
55
+ print(IRIMI_FAILED, file=sys.stderr)
56
+ return _fail(str(refusal))
57
+ except BaseException:
58
+ if not flush():
59
+ return _fail(IRIMI_FAILED)
60
+ raise
61
+ if not flush():
62
+ return _fail(IRIMI_FAILED)
63
+ runs_started_by_the_call = replay.started_runs[runs_started_before_the_call:]
64
+ if not runs_started_by_the_call:
65
+ return _fail(
66
+ f"{workflow_call.import_path} is no longer an irimi workflow, "
67
+ "so the replay recorded no run"
68
+ )
69
+ new_run = runs_started_by_the_call[0]
70
+ result_path = environment_variables.get(REPLAY_RESULT_VARIABLE)
71
+ if result_path:
72
+ try:
73
+ Path(result_path).write_text(new_run)
74
+ except OSError as error:
75
+ return _fail(f"the replay ran as {new_run}, but its id could not be written: {error}")
76
+ print(f"replayed {recorded_run.trace_id} as {new_run}")
77
+ print(f"irimi runs {new_run} shows it")
78
+ return 0
79
+
80
+
81
+ def _prepare_workflow_call(root: StartEvent) -> WorkflowCall:
82
+ import_path = _read_import_path(root.fields.get(field_names.STARTED_BY))
83
+ workflow = _find_workflow(import_path)
84
+ if not SDK.is_registered_workflow(import_path):
85
+ raise ReplayRefusal(
86
+ f"{import_path} is no longer an irimi workflow; "
87
+ "mark it with @irimi.workflow to replay it"
88
+ )
89
+ arguments, keyword_arguments = _rebuild_input(root.fields.get(field_names.INPUT))
90
+ return WorkflowCall(import_path, workflow, arguments, keyword_arguments)
91
+
92
+
93
+ def _read_import_path(started_by: JsonValue) -> str:
94
+ import_path = started_by.get(field_names.IMPORT_PATH) if isinstance(started_by, dict) else None
95
+ if not isinstance(import_path, str):
96
+ raise ReplayRefusal("the recording does not say which function started the run")
97
+ return import_path
98
+
99
+
100
+ def _find_workflow(import_path: str) -> Callable[..., object]:
101
+ module_name, _, qualified_name = import_path.partition(":")
102
+ if module_name == SCRIPT_MODULE:
103
+ raise ReplayRefusal(
104
+ "the workflow was recorded in a script run directly; "
105
+ "move it into a module that can be imported"
106
+ )
107
+ try:
108
+ found: object = importlib.import_module(module_name)
109
+ except Exception as error:
110
+ raise ReplayRefusal(
111
+ f"the workflow's module {module_name} could not be imported: {error}"
112
+ ) from error
113
+ for name in qualified_name.split("."):
114
+ try:
115
+ found = getattr(found, name)
116
+ except AttributeError:
117
+ raise ReplayRefusal(f"the workflow {import_path} was not found") from None
118
+ if not callable(found):
119
+ raise ReplayRefusal(f"{import_path} is not a function, so it cannot be called")
120
+ return found
121
+
122
+
123
+ def _rebuild_input(recorded_input: JsonValue) -> tuple[list[object], dict[str, object]]:
124
+ try:
125
+ rebuilt = rebuild(recorded_input)
126
+ except RebuildError as error:
127
+ raise ReplayRefusal(f"the run's input cannot be rebuilt: {error}") from error
128
+ arguments = rebuilt.get(field_names.ARGS) if isinstance(rebuilt, dict) else None
129
+ keyword_arguments = rebuilt.get(field_names.KWARGS) if isinstance(rebuilt, dict) else None
130
+ if not isinstance(arguments, list) or not isinstance(keyword_arguments, dict):
131
+ raise ReplayRefusal("the recording does not hold the run's input")
132
+ return arguments, keyword_arguments
133
+
134
+
135
+ def _call_workflow(workflow_call: WorkflowCall) -> None:
136
+ workflow = workflow_call.workflow
137
+ arguments = workflow_call.arguments
138
+ keyword_arguments = workflow_call.keyword_arguments
139
+ try:
140
+ if inspect.iscoroutinefunction(workflow):
141
+ asyncio.run(workflow(*arguments, **keyword_arguments))
142
+ else:
143
+ workflow(*arguments, **keyword_arguments)
144
+ except ReplayRefusal:
145
+ raise
146
+ except Exception as error:
147
+ print(f"the workflow raised {type(error).__name__}: {error}", file=sys.stderr)
148
+
149
+
150
+ def _fail(sentence: str) -> int:
151
+ print(sentence, file=sys.stderr)
152
+ return 1
153
+
154
+
155
+ if __name__ == "__main__":
156
+ sys.exit(main(os.environ, Path.cwd()))
@@ -0,0 +1,120 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator
4
+ from dataclasses import dataclass
5
+ from threading import Lock
6
+ from typing import Literal, Protocol
7
+
8
+ from irimi._recorded_calls import RecordedCall
9
+ from irimi._wire import Flag, JsonValue, field_names
10
+ from irimi._wire.call_roles import CallRole, is_write_role
11
+
12
+ MatchRule = Literal["same request", "same name, same position", "same kind and name"]
13
+ Answer = Literal["live", "recorded", "faked"]
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class CandidateCall:
18
+ role: CallRole
19
+ name: str
20
+ match_key: JsonValue
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Decision:
25
+ role: CallRole
26
+ answer: Answer
27
+ matched: RecordedCall | None
28
+ rule: MatchRule | None
29
+ is_changed: bool
30
+ flags: tuple[Flag, ...]
31
+
32
+
33
+ class Decides(Protocol):
34
+ def decide(self, call: CandidateCall) -> Decision: ...
35
+ def decide_undescribed_call(self, role: CallRole) -> Decision: ...
36
+
37
+
38
+ def choose_undescribed_decision(role: CallRole) -> Decision:
39
+ answer: Answer = "faked" if is_write_role(role) else "live"
40
+ return Decision(role, answer, None, None, False, (field_names.UNDESCRIBED_CALL,))
41
+
42
+
43
+ FAKED_UNDESCRIBED_CALL = choose_undescribed_decision("http_write")
44
+
45
+
46
+ class ReplayDecider:
47
+ def __init__(self, calls: tuple[RecordedCall, ...]) -> None:
48
+ self._calls = calls
49
+ self._claimed: set[str] = set()
50
+ self._lock = Lock()
51
+
52
+ def decide(self, call: CandidateCall) -> Decision:
53
+ with self._lock:
54
+ decision = self._choose(call)
55
+ if decision.matched is not None:
56
+ self._claimed.add(decision.matched.span_id)
57
+ if decision.matched is not None and decision.answer == "recorded":
58
+ self._claimed.update(decision.matched.descendant_span_ids)
59
+ return decision
60
+
61
+ def decide_undescribed_call(self, role: CallRole) -> Decision:
62
+ return choose_undescribed_decision(role)
63
+
64
+ def _choose(self, call: CandidateCall) -> Decision:
65
+ if call.role == "plain":
66
+ return self._choose_live_by_name(call)
67
+ exact = self._find_exact(call)
68
+ if exact is not None:
69
+ return _serve_exact(call, exact)
70
+ if is_write_role(call.role):
71
+ return self._choose_for_new_write(call)
72
+ if call.role == "llm":
73
+ return self._choose_live_by_name(call)
74
+ return Decision(call.role, "live", None, None, False, (field_names.UNMATCHED_READ,))
75
+
76
+ def _choose_live_by_name(self, call: CandidateCall) -> Decision:
77
+ following = self._find_next(call)
78
+ if following is None:
79
+ return Decision(call.role, "live", None, None, False, ())
80
+ return Decision(call.role, "live", following, "same kind and name", False, ())
81
+
82
+ def _choose_for_new_write(self, call: CandidateCall) -> Decision:
83
+ following = self._find_next(call)
84
+ if following is None:
85
+ return Decision(call.role, "faked", None, None, False, (field_names.NEW_WRITE,))
86
+ if following.result is None:
87
+ flags: tuple[Flag, ...] = (field_names.RECORDED_VALUE_UNSERVABLE,)
88
+ return Decision(call.role, "faked", following, "same name, same position", True, flags)
89
+ return Decision(call.role, "recorded", following, "same name, same position", True, ())
90
+
91
+ def _find_exact(self, call: CandidateCall) -> RecordedCall | None:
92
+ return next(
93
+ (
94
+ recorded
95
+ for recorded in self._unclaimed_named(call)
96
+ if recorded.match_key == call.match_key
97
+ ),
98
+ None,
99
+ )
100
+
101
+ def _find_next(self, call: CandidateCall) -> RecordedCall | None:
102
+ return next(self._unclaimed_named(call), None)
103
+
104
+ def _unclaimed_named(self, call: CandidateCall) -> Iterator[RecordedCall]:
105
+ return (
106
+ recorded
107
+ for recorded in self._calls
108
+ if recorded.span_id not in self._claimed
109
+ and recorded.role == call.role
110
+ and recorded.name == call.name
111
+ )
112
+
113
+
114
+ def _serve_exact(call: CandidateCall, exact: RecordedCall) -> Decision:
115
+ if exact.result is not None:
116
+ return Decision(call.role, "recorded", exact, "same request", False, ())
117
+ answer: Answer = "faked" if is_write_role(call.role) else "live"
118
+ return Decision(
119
+ call.role, answer, exact, "same request", False, (field_names.RECORDED_VALUE_UNSERVABLE,)
120
+ )
@@ -0,0 +1,16 @@
1
+ from __future__ import annotations
2
+
3
+ from irimi._replay_decisions import Decision
4
+ from irimi._wire import JsonValue, field_names
5
+
6
+
7
+ def describe_decision(decision: Decision) -> dict[str, JsonValue]:
8
+ fields: dict[str, JsonValue] = {field_names.ANSWERED: decision.answer}
9
+ if decision.matched is not None:
10
+ fields[field_names.MATCHED] = {
11
+ field_names.SPAN_ID: decision.matched.span_id,
12
+ field_names.RULE: decision.rule,
13
+ }
14
+ if decision.is_changed:
15
+ fields[field_names.CHANGED] = True
16
+ return fields