ruby-on-dspy 0.1.0
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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +112 -0
- data/LICENSE +21 -0
- data/README.md +442 -0
- data/exe/ruby-on-dspy +7 -0
- data/lib/dspy_rb/cli.rb +83 -0
- data/lib/dspy_rb/clients/dummy_lm.rb +81 -0
- data/lib/dspy_rb/clients/lm.rb +44 -0
- data/lib/dspy_rb/datasets/data_loader.rb +74 -0
- data/lib/dspy_rb/datasets/dataset.rb +37 -0
- data/lib/dspy_rb/datasets/python_random.rb +38 -0
- data/lib/dspy_rb/errors.rb +135 -0
- data/lib/dspy_rb/evaluate/evaluate.rb +53 -0
- data/lib/dspy_rb/evaluate/metric.rb +61 -0
- data/lib/dspy_rb/execution/around.rb +63 -0
- data/lib/dspy_rb/execution/collector.rb +61 -0
- data/lib/dspy_rb/execution/context.rb +160 -0
- data/lib/dspy_rb/execution/evaluation.rb +90 -0
- data/lib/dspy_rb/execution/optimization.rb +71 -0
- data/lib/dspy_rb/execution/program.rb +126 -0
- data/lib/dspy_rb/execution/rows.rb +41 -0
- data/lib/dspy_rb/execution/scorer.rb +68 -0
- data/lib/dspy_rb/execution/step.rb +116 -0
- data/lib/dspy_rb/execution/toolbox.rb +28 -0
- data/lib/dspy_rb/predict/chain_of_thought.rb +22 -0
- data/lib/dspy_rb/predict/predict.rb +101 -0
- data/lib/dspy_rb/predict/react.rb +80 -0
- data/lib/dspy_rb/primitives/module.rb +105 -0
- data/lib/dspy_rb/primitives/parts.rb +121 -0
- data/lib/dspy_rb/runtime/channel/callback.rb +105 -0
- data/lib/dspy_rb/runtime/channel/ending.rb +35 -0
- data/lib/dspy_rb/runtime/channel/exchange.rb +176 -0
- data/lib/dspy_rb/runtime/channel/gate.rb +74 -0
- data/lib/dspy_rb/runtime/channel/listener.rb +125 -0
- data/lib/dspy_rb/runtime/channel/meter.rb +46 -0
- data/lib/dspy_rb/runtime/channel/reporter.rb +68 -0
- data/lib/dspy_rb/runtime/channel/settler.rb +69 -0
- data/lib/dspy_rb/runtime/channel/traffic.rb +121 -0
- data/lib/dspy_rb/runtime/channel/watchdog.rb +36 -0
- data/lib/dspy_rb/runtime/channel/writer.rb +77 -0
- data/lib/dspy_rb/runtime/channel.rb +145 -0
- data/lib/dspy_rb/runtime/child.rb +48 -0
- data/lib/dspy_rb/runtime/python.rb +43 -0
- data/lib/dspy_rb/runtime/registry.rb +48 -0
- data/lib/dspy_rb/runtime/startup.rb +53 -0
- data/lib/dspy_rb/secrets.rb +25 -0
- data/lib/dspy_rb/setup/environment.rb +120 -0
- data/lib/dspy_rb/setup/stale.rb +102 -0
- data/lib/dspy_rb/setup/uv.rb +122 -0
- data/lib/dspy_rb/signatures/signature.rb +100 -0
- data/lib/dspy_rb/signatures/types.rb +44 -0
- data/lib/dspy_rb/source.rb +64 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_optuna.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_random_search.rb +9 -0
- data/lib/dspy_rb/teleprompt/gepa.rb +9 -0
- data/lib/dspy_rb/teleprompt/labeled_few_shot.rb +14 -0
- data/lib/dspy_rb/teleprompt/mipro_v2.rb +16 -0
- data/lib/dspy_rb/teleprompt/optimizer.rb +127 -0
- data/lib/dspy_rb/teleprompt/simba.rb +16 -0
- data/lib/dspy_rb/tool.rb +108 -0
- data/lib/dspy_rb/values/check.rb +14 -0
- data/lib/dspy_rb/values/context.rb +46 -0
- data/lib/dspy_rb/values/dataset.rb +55 -0
- data/lib/dspy_rb/values/dict.rb +17 -0
- data/lib/dspy_rb/values/env.rb +23 -0
- data/lib/dspy_rb/values/evaluation_result.rb +31 -0
- data/lib/dspy_rb/values/example.rb +134 -0
- data/lib/dspy_rb/values/fault.rb +15 -0
- data/lib/dspy_rb/values/history.rb +13 -0
- data/lib/dspy_rb/values/list.rb +16 -0
- data/lib/dspy_rb/values/literal.rb +27 -0
- data/lib/dspy_rb/values/loss.rb +12 -0
- data/lib/dspy_rb/values/optional.rb +16 -0
- data/lib/dspy_rb/values/prediction.rb +58 -0
- data/lib/dspy_rb/values/reasoning.rb +13 -0
- data/lib/dspy_rb/values/spend.rb +27 -0
- data/lib/dspy_rb/values/types.rb +164 -0
- data/lib/dspy_rb/version.rb +11 -0
- data/lib/dspy_rb/wire/departure.rb +100 -0
- data/lib/dspy_rb/wire/descriptions.rb +220 -0
- data/lib/dspy_rb/wire/facts.rb +79 -0
- data/lib/dspy_rb/wire/in_flight.rb +128 -0
- data/lib/dspy_rb/wire/json.rb +76 -0
- data/lib/dspy_rb/wire/optimizers.rb +240 -0
- data/lib/dspy_rb/wire/records.rb +44 -0
- data/lib/dspy_rb/wire/replies.rb +188 -0
- data/lib/dspy_rb/wire/requests.rb +214 -0
- data/lib/dspy_rb/wire/shape.rb +25 -0
- data/lib/dspy_rb/wire/types.rb +23 -0
- data/lib/dspy_rb/wire.rb +34 -0
- data/lib/dspy_rb.rb +191 -0
- data/lib/ruby-on-dspy.rb +4 -0
- data/python/dspy_rb/__init__.py +1 -0
- data/python/dspy_rb/__main__.py +76 -0
- data/python/dspy_rb/server/__init__.py +1 -0
- data/python/dspy_rb/server/build.py +281 -0
- data/python/dspy_rb/server/calls.py +215 -0
- data/python/dspy_rb/server/conversion.py +180 -0
- data/python/dspy_rb/server/data.py +169 -0
- data/python/dspy_rb/server/evaluation.py +107 -0
- data/python/dspy_rb/server/facts.py +357 -0
- data/python/dspy_rb/server/optimization.py +98 -0
- data/python/dspy_rb/server/pulse.py +68 -0
- data/python/dspy_rb/server/ruby.py +206 -0
- data/python/dspy_rb/server/serve.py +369 -0
- data/python/dspy_rb/server/standins.py +364 -0
- data/python/dspy_rb/server/state.py +104 -0
- data/python/dspy_rb/server/traffic.py +93 -0
- data/python/dspy_rb/values.py +51 -0
- data/python/dspy_rb/wire/__init__.py +1 -0
- data/python/dspy_rb/wire/channel.py +107 -0
- data/python/dspy_rb/wire/lines.py +269 -0
- data/python/dspy_rb/wire/shapes.py +1220 -0
- data/python/dspy_rb/wire/wire.json +4592 -0
- data/python/pyproject.toml +86 -0
- data/python/uv.lock +1576 -0
- metadata +230 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""DSPy's optimizers, run as DSPy runs them on a predictor or a Ruby program's stand-in, what they give read back."""
|
|
2
|
+
|
|
3
|
+
import dataclasses
|
|
4
|
+
from typing import Any, Final, cast
|
|
5
|
+
|
|
6
|
+
import dspy
|
|
7
|
+
from dspy.teleprompt import Teleprompter
|
|
8
|
+
|
|
9
|
+
from dspy_rb.server import build, conversion, evaluation, state
|
|
10
|
+
from dspy_rb.server.ruby import Ruby
|
|
11
|
+
from dspy_rb.wire import lines, shapes
|
|
12
|
+
from dspy_rb.wire.shapes import LM, Compile, Compiled, DummyLM, Example, Metric, Predictor, RubyMetric, RubyProgram
|
|
13
|
+
|
|
14
|
+
# DSPy's optimizers by Ruby's names.
|
|
15
|
+
OPTIMIZERS: Final[dict[str, type[Teleprompter]]] = {
|
|
16
|
+
"labeled_few_shot": dspy.LabeledFewShot,
|
|
17
|
+
"bootstrap_few_shot": dspy.BootstrapFewShot,
|
|
18
|
+
"gepa": dspy.GEPA,
|
|
19
|
+
"mipro_v2": dspy.MIPROv2,
|
|
20
|
+
"bootstrap_few_shot_with_optuna": dspy.BootstrapFewShotWithOptuna,
|
|
21
|
+
"bootstrap_few_shot_with_random_search": dspy.BootstrapFewShotWithRandomSearch,
|
|
22
|
+
"simba": dspy.SIMBA,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def compiled(request: Compile, ruby: Ruby) -> Compiled:
|
|
27
|
+
"""Compile the student with the optimizer made with its options and called with its compile's, as DSPy's docs do."""
|
|
28
|
+
student = build.program(request.student, ruby)
|
|
29
|
+
compiling = {} if request.compiling is None else options(request.compiling, ruby, request.id)
|
|
30
|
+
trainset = [conversion.example(each) for each in request.trainset]
|
|
31
|
+
|
|
32
|
+
optimizer = OPTIMIZERS[request.optimizer.name](**options(request.optimizer, ruby, request.id))
|
|
33
|
+
result = optimizer.compile(student, trainset=trainset, **compiling)
|
|
34
|
+
|
|
35
|
+
return Compiled(
|
|
36
|
+
id=request.id,
|
|
37
|
+
state=state.read(result, request.student, ruby, "compiled"),
|
|
38
|
+
results=_results(result),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def options(view: object, ruby: Ruby, request: int) -> dict[str, object]:
|
|
43
|
+
"""Give an optimizer's options or its compile's by DSPy's names, each as its kind; None for each `none` lists."""
|
|
44
|
+
given = cast("dict[str, object]", _taken(view, ruby, request))
|
|
45
|
+
none = cast("list[str]", given.pop("none", []))
|
|
46
|
+
|
|
47
|
+
# The optimizer's name tags its options and its compile's alike; DSPy takes neither.
|
|
48
|
+
del given["name"]
|
|
49
|
+
|
|
50
|
+
return given | dict.fromkeys(none)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# Each kind as DSPy takes it; a model built anew, since an optimizer may write into it (simba_utils.py:22-24).
|
|
54
|
+
def _taken(item: object, ruby: Ruby, request: int) -> object:
|
|
55
|
+
match item:
|
|
56
|
+
case LM():
|
|
57
|
+
return build.lm(item)
|
|
58
|
+
case DummyLM():
|
|
59
|
+
return build.dummy_lm(item, ruby, request)
|
|
60
|
+
case Metric() | RubyMetric():
|
|
61
|
+
return evaluation.metric(item, ruby)
|
|
62
|
+
case Predictor() | RubyProgram():
|
|
63
|
+
return build.program(item, ruby)
|
|
64
|
+
case Example():
|
|
65
|
+
return conversion.example(item)
|
|
66
|
+
case _:
|
|
67
|
+
return _held(item, ruby, request)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# What a struct or a list holds, each as its kind; anything else as the wire gives it.
|
|
71
|
+
def _held(item: object, ruby: Ruby, request: int) -> object:
|
|
72
|
+
if isinstance(item, list):
|
|
73
|
+
return [_taken(each, ruby, request) for each in cast("list[object]", item)]
|
|
74
|
+
|
|
75
|
+
if dataclasses.is_dataclass(item) and not isinstance(item, type):
|
|
76
|
+
present = ((each.name, getattr(item, each.name)) for each in dataclasses.fields(item))
|
|
77
|
+
|
|
78
|
+
return {name: _taken(value, ruby, request) for name, value in present if value is not None}
|
|
79
|
+
|
|
80
|
+
return lines.dump(item)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# GEPA's detailed results where track_stats asks (dspy/teleprompt/gepa/gepa.py:686-689): to_dict, each output's fields.
|
|
84
|
+
def _results(result: dspy.Module) -> shapes.Values | None:
|
|
85
|
+
detailed = getattr(result, "detailed_results", None)
|
|
86
|
+
|
|
87
|
+
if detailed is None:
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
given = cast("dict[str, Any]", detailed.to_dict())
|
|
91
|
+
best = cast("dict[int, list[tuple[int, dspy.Prediction]]] | None", given["best_outputs_valset"])
|
|
92
|
+
|
|
93
|
+
if best is not None:
|
|
94
|
+
given["best_outputs_valset"] = {
|
|
95
|
+
row: [(index, conversion.outputs(made)) for index, made in each] for row, each in best.items()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return cast("shapes.Values", conversion.value(given, "detailed_results"))
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Python's alive line, written while anything of Ruby's is open, so Ruby tells a long wait from a frozen process."""
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Final, Protocol, Self
|
|
6
|
+
|
|
7
|
+
from dspy_rb.server.traffic import Traffic
|
|
8
|
+
from dspy_rb.wire import lines
|
|
9
|
+
from dspy_rb.wire.channel import Channel
|
|
10
|
+
from dspy_rb.wire.shapes import ALIVE_INTERVAL, Alive
|
|
11
|
+
|
|
12
|
+
LINE: Final = lines.line_or_raise(Alive())
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Calls(Protocol):
|
|
16
|
+
"""A request's model calls, as its recorder counts those still running."""
|
|
17
|
+
|
|
18
|
+
def running(self) -> int:
|
|
19
|
+
"""Count the calls still running."""
|
|
20
|
+
...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Pulse:
|
|
25
|
+
"""Writes the alive line each interval while a request is open or a model call runs; nothing while idle."""
|
|
26
|
+
|
|
27
|
+
channel: Channel
|
|
28
|
+
traffic: Traffic
|
|
29
|
+
|
|
30
|
+
# Each request's calls by identity while one may run, a replied request's among them, whose progress Ruby waits for.
|
|
31
|
+
_watched: dict[int, Calls] = field(init=False, default_factory=dict[int, Calls])
|
|
32
|
+
_lock: threading.Lock = field(init=False, default_factory=threading.Lock)
|
|
33
|
+
_stopped: threading.Event = field(init=False, default_factory=threading.Event)
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def started(cls, channel: Channel, traffic: Traffic) -> Self:
|
|
37
|
+
"""Start writing on a daemon thread of its own, which never holds the interpreter's exit."""
|
|
38
|
+
pulse = cls(channel, traffic)
|
|
39
|
+
|
|
40
|
+
threading.Thread(target=pulse._beat, name="dspy_rb-pulse", daemon=True).start()
|
|
41
|
+
|
|
42
|
+
return pulse
|
|
43
|
+
|
|
44
|
+
def watch(self, calls: Calls) -> None:
|
|
45
|
+
"""Beat while any of `calls` runs."""
|
|
46
|
+
with self._lock:
|
|
47
|
+
self._watched[id(calls)] = calls
|
|
48
|
+
|
|
49
|
+
def stop(self) -> None:
|
|
50
|
+
"""Write no more, at the end of Ruby's input."""
|
|
51
|
+
self._stopped.set()
|
|
52
|
+
|
|
53
|
+
def _beat(self) -> None:
|
|
54
|
+
# Read at each wait, so a test can shorten the interval.
|
|
55
|
+
while not self._stopped.wait(ALIVE_INTERVAL):
|
|
56
|
+
if self._open():
|
|
57
|
+
self.channel.write(LINE)
|
|
58
|
+
|
|
59
|
+
def _open(self) -> bool:
|
|
60
|
+
# Counted under the lock, so calls a start adds to as they are counted out are watched again after.
|
|
61
|
+
with self._lock:
|
|
62
|
+
for key, calls in list(self._watched.items()):
|
|
63
|
+
if calls.running() == 0:
|
|
64
|
+
del self._watched[key]
|
|
65
|
+
|
|
66
|
+
running = bool(self._watched)
|
|
67
|
+
|
|
68
|
+
return running or self.traffic.busy()
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Ruby as DSPy's code calls back to it: each callback asked by an id of Python's, its thread waiting meanwhile."""
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
import queue
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Callable, Iterator
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Final, Self
|
|
9
|
+
|
|
10
|
+
import dspy
|
|
11
|
+
|
|
12
|
+
from dspy_rb.server import traffic
|
|
13
|
+
from dspy_rb.server.traffic import Exchange, Halted, Traffic
|
|
14
|
+
from dspy_rb.values import Broken, Gone, Wake
|
|
15
|
+
from dspy_rb.wire import lines
|
|
16
|
+
from dspy_rb.wire.channel import Channel
|
|
17
|
+
from dspy_rb.wire.shapes import Callback, Pooled, Raised, Refused, Returned, RubyFailure
|
|
18
|
+
|
|
19
|
+
type Make = Callable[[int, int], Callback]
|
|
20
|
+
|
|
21
|
+
# Serves a nested request on the waiting thread, giving the exception it raised, if any.
|
|
22
|
+
type Serve = Callable[[Pooled, Exchange], BaseException | None]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RubyError(Exception):
|
|
26
|
+
"""An exception a Ruby callback raised, which DSPy treats as it treats a Python callable's own."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class RubyAbort(BaseException):
|
|
30
|
+
"""A Ruby callback raised what ends its request (a signal, an exit), so it escapes DSPy's handlers."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Lost(BaseException):
|
|
34
|
+
"""Ruby's requests ended, so no callback will be answered."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
WAKE: Final = Wake()
|
|
38
|
+
GONE: Final = Gone()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class _Nested:
|
|
43
|
+
"""A request made within a callback, with the exchange opened for it as its line was read."""
|
|
44
|
+
|
|
45
|
+
request: Pooled
|
|
46
|
+
exchange: Exchange
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
type Inbound = Returned | Raised | _Nested | Wake | Gone | Broken
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class _Waiter:
|
|
54
|
+
"""The thread waiting on one callback: its exchange, what Ruby sends it, and its nested requests' exceptions."""
|
|
55
|
+
|
|
56
|
+
exchange: Exchange
|
|
57
|
+
|
|
58
|
+
# The program copy whose forward asked, whose own parts serve the calls made within it.
|
|
59
|
+
program: dspy.Module | None = None
|
|
60
|
+
inbox: queue.SimpleQueue[Inbound] = field(default_factory=queue.SimpleQueue[Inbound])
|
|
61
|
+
kept: dict[int, BaseException] = field(default_factory=dict[int, BaseException])
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class Ruby:
|
|
66
|
+
"""Asks Ruby on the thread whose DSPy code calls back, and delivers what Ruby sends to that thread."""
|
|
67
|
+
|
|
68
|
+
channel: Channel
|
|
69
|
+
traffic: Traffic
|
|
70
|
+
serve: Serve
|
|
71
|
+
_waiting: dict[int, _Waiter] = field(init=False, default_factory=dict[int, _Waiter])
|
|
72
|
+
_ids: Iterator[int] = field(init=False, default_factory=lambda: itertools.count(1))
|
|
73
|
+
_lock: threading.Lock = field(init=False, default_factory=threading.Lock)
|
|
74
|
+
_lost: bool = field(init=False, default=False)
|
|
75
|
+
|
|
76
|
+
def ask(self, make: Make, program: dspy.Module | None = None) -> Returned | BaseException:
|
|
77
|
+
"""Write the callback `make` builds from its id and request, and wait: the answer, or what to raise."""
|
|
78
|
+
exchange = traffic.current()
|
|
79
|
+
|
|
80
|
+
if exchange is None:
|
|
81
|
+
message = "a callback is asked only while a request is served"
|
|
82
|
+
|
|
83
|
+
raise RuntimeError(message)
|
|
84
|
+
|
|
85
|
+
# Once a request has answered or been cancelled, none of its leftover threads reaches Ruby.
|
|
86
|
+
if exchange.stopped():
|
|
87
|
+
return Halted()
|
|
88
|
+
|
|
89
|
+
with self._lock:
|
|
90
|
+
if self._lost:
|
|
91
|
+
return Lost()
|
|
92
|
+
|
|
93
|
+
callback = next(self._ids)
|
|
94
|
+
waiter = _Waiter(exchange, program)
|
|
95
|
+
|
|
96
|
+
self._waiting[callback] = waiter
|
|
97
|
+
|
|
98
|
+
try:
|
|
99
|
+
# Again once registered: a cancel read before then woke no waiter of this callback.
|
|
100
|
+
if exchange.stopped():
|
|
101
|
+
return Halted()
|
|
102
|
+
|
|
103
|
+
self.channel.write(lines.line_or_raise(make(callback, exchange.request)))
|
|
104
|
+
|
|
105
|
+
return self._wait(waiter)
|
|
106
|
+
finally:
|
|
107
|
+
self._leave(callback, waiter)
|
|
108
|
+
|
|
109
|
+
# Shared, as a function is: DSPy's optimizers deep-copy a program (primitives/base_module.py:111-155).
|
|
110
|
+
def __deepcopy__(self, memo: dict[int, object]) -> Self:
|
|
111
|
+
"""Give itself, so every copy of a program asks the one Ruby side."""
|
|
112
|
+
del memo
|
|
113
|
+
|
|
114
|
+
return self
|
|
115
|
+
|
|
116
|
+
def deliver(self, callback: int, message: Returned | Raised) -> bool:
|
|
117
|
+
"""Give Ruby's answer to the thread waiting on `callback`; whether one waits."""
|
|
118
|
+
return self._put(callback, lambda _: message)
|
|
119
|
+
|
|
120
|
+
def nest(self, callback: int, request: Pooled) -> bool:
|
|
121
|
+
"""Give a request made within `callback`, its exchange opened now, to the thread waiting; whether one waits."""
|
|
122
|
+
return self._put(
|
|
123
|
+
callback,
|
|
124
|
+
lambda waiter: _Nested(request, self.traffic.open(request, waiter.exchange, waiter.program)),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def fail(self, callback: int, reason: str) -> None:
|
|
128
|
+
"""End the wait on `callback`, whose answer could not be read."""
|
|
129
|
+
self._put(callback, lambda _: Broken(reason))
|
|
130
|
+
|
|
131
|
+
def wake(self) -> None:
|
|
132
|
+
"""Have every waiting thread look at its exchange again, after a cancel."""
|
|
133
|
+
self._each(WAKE)
|
|
134
|
+
|
|
135
|
+
def lose(self) -> None:
|
|
136
|
+
"""Wake every waiting thread with Lost, at the end of Ruby's input; no reply follows."""
|
|
137
|
+
with self._lock:
|
|
138
|
+
self._lost = True
|
|
139
|
+
|
|
140
|
+
self._each(GONE)
|
|
141
|
+
|
|
142
|
+
# Under the lock, which a waiter takes to leave, so nothing reaches an inbox no thread reads any more.
|
|
143
|
+
def _put(self, callback: int, message: Callable[[_Waiter], Inbound]) -> bool:
|
|
144
|
+
with self._lock:
|
|
145
|
+
waiter = self._waiting.get(callback)
|
|
146
|
+
|
|
147
|
+
if waiter is not None:
|
|
148
|
+
waiter.inbox.put(message(waiter))
|
|
149
|
+
|
|
150
|
+
return waiter is not None
|
|
151
|
+
|
|
152
|
+
def _each(self, message: Wake | Gone) -> None:
|
|
153
|
+
with self._lock:
|
|
154
|
+
for waiter in self._waiting.values():
|
|
155
|
+
waiter.inbox.put(message)
|
|
156
|
+
|
|
157
|
+
def _wait(self, waiter: _Waiter) -> Returned | BaseException:
|
|
158
|
+
while True:
|
|
159
|
+
message = waiter.inbox.get()
|
|
160
|
+
|
|
161
|
+
match message:
|
|
162
|
+
case Returned():
|
|
163
|
+
return message
|
|
164
|
+
case Raised(error=error):
|
|
165
|
+
return self._raised(waiter, error)
|
|
166
|
+
case Wake():
|
|
167
|
+
if waiter.exchange.stopped():
|
|
168
|
+
return Halted()
|
|
169
|
+
case Gone():
|
|
170
|
+
return Lost()
|
|
171
|
+
case Broken(reason=reason):
|
|
172
|
+
return RubyAbort(reason)
|
|
173
|
+
case _Nested(request=request, exchange=exchange):
|
|
174
|
+
# Served here, where DSPy's context and trace for this request already are.
|
|
175
|
+
raised = self.serve(request, exchange)
|
|
176
|
+
|
|
177
|
+
if raised is not None:
|
|
178
|
+
waiter.kept[request.id] = raised
|
|
179
|
+
|
|
180
|
+
def _raised(self, waiter: _Waiter, error: RubyFailure) -> BaseException:
|
|
181
|
+
if waiter.exchange.stopped():
|
|
182
|
+
return Halted()
|
|
183
|
+
|
|
184
|
+
# The very exception a nested request raised here, so DSPy's own handlers see their own class.
|
|
185
|
+
kept = None if error.of is None else waiter.kept.get(error.of)
|
|
186
|
+
|
|
187
|
+
if kept is not None:
|
|
188
|
+
return kept
|
|
189
|
+
|
|
190
|
+
described = f"{error.ruby_class}: {error.message}"
|
|
191
|
+
|
|
192
|
+
return RubyAbort(described) if error.fatal else RubyError(described)
|
|
193
|
+
|
|
194
|
+
def _leave(self, callback: int, waiter: _Waiter) -> None:
|
|
195
|
+
with self._lock:
|
|
196
|
+
del self._waiting[callback]
|
|
197
|
+
|
|
198
|
+
# A nested request that arrived as the wait ended gets a reply, so its Ruby caller never waits it out.
|
|
199
|
+
while not waiter.inbox.empty():
|
|
200
|
+
message = waiter.inbox.get()
|
|
201
|
+
|
|
202
|
+
if isinstance(message, _Nested):
|
|
203
|
+
reason = f"callback {callback} is no longer waiting"
|
|
204
|
+
|
|
205
|
+
self.traffic.finish(message.exchange)
|
|
206
|
+
self.channel.write(lines.line_or_raise(Refused(id=message.request.id, reason=reason)))
|