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.
Files changed (118) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +112 -0
  3. data/LICENSE +21 -0
  4. data/README.md +442 -0
  5. data/exe/ruby-on-dspy +7 -0
  6. data/lib/dspy_rb/cli.rb +83 -0
  7. data/lib/dspy_rb/clients/dummy_lm.rb +81 -0
  8. data/lib/dspy_rb/clients/lm.rb +44 -0
  9. data/lib/dspy_rb/datasets/data_loader.rb +74 -0
  10. data/lib/dspy_rb/datasets/dataset.rb +37 -0
  11. data/lib/dspy_rb/datasets/python_random.rb +38 -0
  12. data/lib/dspy_rb/errors.rb +135 -0
  13. data/lib/dspy_rb/evaluate/evaluate.rb +53 -0
  14. data/lib/dspy_rb/evaluate/metric.rb +61 -0
  15. data/lib/dspy_rb/execution/around.rb +63 -0
  16. data/lib/dspy_rb/execution/collector.rb +61 -0
  17. data/lib/dspy_rb/execution/context.rb +160 -0
  18. data/lib/dspy_rb/execution/evaluation.rb +90 -0
  19. data/lib/dspy_rb/execution/optimization.rb +71 -0
  20. data/lib/dspy_rb/execution/program.rb +126 -0
  21. data/lib/dspy_rb/execution/rows.rb +41 -0
  22. data/lib/dspy_rb/execution/scorer.rb +68 -0
  23. data/lib/dspy_rb/execution/step.rb +116 -0
  24. data/lib/dspy_rb/execution/toolbox.rb +28 -0
  25. data/lib/dspy_rb/predict/chain_of_thought.rb +22 -0
  26. data/lib/dspy_rb/predict/predict.rb +101 -0
  27. data/lib/dspy_rb/predict/react.rb +80 -0
  28. data/lib/dspy_rb/primitives/module.rb +105 -0
  29. data/lib/dspy_rb/primitives/parts.rb +121 -0
  30. data/lib/dspy_rb/runtime/channel/callback.rb +105 -0
  31. data/lib/dspy_rb/runtime/channel/ending.rb +35 -0
  32. data/lib/dspy_rb/runtime/channel/exchange.rb +176 -0
  33. data/lib/dspy_rb/runtime/channel/gate.rb +74 -0
  34. data/lib/dspy_rb/runtime/channel/listener.rb +125 -0
  35. data/lib/dspy_rb/runtime/channel/meter.rb +46 -0
  36. data/lib/dspy_rb/runtime/channel/reporter.rb +68 -0
  37. data/lib/dspy_rb/runtime/channel/settler.rb +69 -0
  38. data/lib/dspy_rb/runtime/channel/traffic.rb +121 -0
  39. data/lib/dspy_rb/runtime/channel/watchdog.rb +36 -0
  40. data/lib/dspy_rb/runtime/channel/writer.rb +77 -0
  41. data/lib/dspy_rb/runtime/channel.rb +145 -0
  42. data/lib/dspy_rb/runtime/child.rb +48 -0
  43. data/lib/dspy_rb/runtime/python.rb +43 -0
  44. data/lib/dspy_rb/runtime/registry.rb +48 -0
  45. data/lib/dspy_rb/runtime/startup.rb +53 -0
  46. data/lib/dspy_rb/secrets.rb +25 -0
  47. data/lib/dspy_rb/setup/environment.rb +120 -0
  48. data/lib/dspy_rb/setup/stale.rb +102 -0
  49. data/lib/dspy_rb/setup/uv.rb +122 -0
  50. data/lib/dspy_rb/signatures/signature.rb +100 -0
  51. data/lib/dspy_rb/signatures/types.rb +44 -0
  52. data/lib/dspy_rb/source.rb +64 -0
  53. data/lib/dspy_rb/teleprompt/bootstrap_few_shot.rb +9 -0
  54. data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_optuna.rb +9 -0
  55. data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_random_search.rb +9 -0
  56. data/lib/dspy_rb/teleprompt/gepa.rb +9 -0
  57. data/lib/dspy_rb/teleprompt/labeled_few_shot.rb +14 -0
  58. data/lib/dspy_rb/teleprompt/mipro_v2.rb +16 -0
  59. data/lib/dspy_rb/teleprompt/optimizer.rb +127 -0
  60. data/lib/dspy_rb/teleprompt/simba.rb +16 -0
  61. data/lib/dspy_rb/tool.rb +108 -0
  62. data/lib/dspy_rb/values/check.rb +14 -0
  63. data/lib/dspy_rb/values/context.rb +46 -0
  64. data/lib/dspy_rb/values/dataset.rb +55 -0
  65. data/lib/dspy_rb/values/dict.rb +17 -0
  66. data/lib/dspy_rb/values/env.rb +23 -0
  67. data/lib/dspy_rb/values/evaluation_result.rb +31 -0
  68. data/lib/dspy_rb/values/example.rb +134 -0
  69. data/lib/dspy_rb/values/fault.rb +15 -0
  70. data/lib/dspy_rb/values/history.rb +13 -0
  71. data/lib/dspy_rb/values/list.rb +16 -0
  72. data/lib/dspy_rb/values/literal.rb +27 -0
  73. data/lib/dspy_rb/values/loss.rb +12 -0
  74. data/lib/dspy_rb/values/optional.rb +16 -0
  75. data/lib/dspy_rb/values/prediction.rb +58 -0
  76. data/lib/dspy_rb/values/reasoning.rb +13 -0
  77. data/lib/dspy_rb/values/spend.rb +27 -0
  78. data/lib/dspy_rb/values/types.rb +164 -0
  79. data/lib/dspy_rb/version.rb +11 -0
  80. data/lib/dspy_rb/wire/departure.rb +100 -0
  81. data/lib/dspy_rb/wire/descriptions.rb +220 -0
  82. data/lib/dspy_rb/wire/facts.rb +79 -0
  83. data/lib/dspy_rb/wire/in_flight.rb +128 -0
  84. data/lib/dspy_rb/wire/json.rb +76 -0
  85. data/lib/dspy_rb/wire/optimizers.rb +240 -0
  86. data/lib/dspy_rb/wire/records.rb +44 -0
  87. data/lib/dspy_rb/wire/replies.rb +188 -0
  88. data/lib/dspy_rb/wire/requests.rb +214 -0
  89. data/lib/dspy_rb/wire/shape.rb +25 -0
  90. data/lib/dspy_rb/wire/types.rb +23 -0
  91. data/lib/dspy_rb/wire.rb +34 -0
  92. data/lib/dspy_rb.rb +191 -0
  93. data/lib/ruby-on-dspy.rb +4 -0
  94. data/python/dspy_rb/__init__.py +1 -0
  95. data/python/dspy_rb/__main__.py +76 -0
  96. data/python/dspy_rb/server/__init__.py +1 -0
  97. data/python/dspy_rb/server/build.py +281 -0
  98. data/python/dspy_rb/server/calls.py +215 -0
  99. data/python/dspy_rb/server/conversion.py +180 -0
  100. data/python/dspy_rb/server/data.py +169 -0
  101. data/python/dspy_rb/server/evaluation.py +107 -0
  102. data/python/dspy_rb/server/facts.py +357 -0
  103. data/python/dspy_rb/server/optimization.py +98 -0
  104. data/python/dspy_rb/server/pulse.py +68 -0
  105. data/python/dspy_rb/server/ruby.py +206 -0
  106. data/python/dspy_rb/server/serve.py +369 -0
  107. data/python/dspy_rb/server/standins.py +364 -0
  108. data/python/dspy_rb/server/state.py +104 -0
  109. data/python/dspy_rb/server/traffic.py +93 -0
  110. data/python/dspy_rb/values.py +51 -0
  111. data/python/dspy_rb/wire/__init__.py +1 -0
  112. data/python/dspy_rb/wire/channel.py +107 -0
  113. data/python/dspy_rb/wire/lines.py +269 -0
  114. data/python/dspy_rb/wire/shapes.py +1220 -0
  115. data/python/dspy_rb/wire/wire.json +4592 -0
  116. data/python/pyproject.toml +86 -0
  117. data/python/uv.lock +1576 -0
  118. metadata +230 -0
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # What a request's caller raises for any end but the reply asked for, with what the request spent.
7
+ module Ending
8
+ class << self
9
+ # `kept`, the first error that ended it from within, outranks `ended`, its reply or loss.
10
+ def error(kept, ended, spend, request)
11
+ case kept
12
+ when nil then of(ended, spend, request)
13
+ when Values::Fault then Malformed.new(kept.reason, spend, request)
14
+ else kept
15
+ end
16
+ end
17
+
18
+ private
19
+
20
+ def of(ended, spend, request)
21
+ case ended
22
+ when Values::Loss then Unavailable.new(ended.reason, spend, request)
23
+ when Values::Fault then Malformed.new(ended.reason, spend, request)
24
+ when Wire::Failed then DSPyError.for(ended.error, spend, request)
25
+ when Wire::Cancelled then Cancelled.new(spend, request)
26
+ when Wire::Refused then Refused.new(ended.reason, spend, request)
27
+ when Wire::Unfit then StateError.new(ended.reason, spend, request)
28
+ else Malformed.new("an unexpected #{ended.kind} reply", spend, request)
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+
5
+ module DSPyRb
6
+ module Runtime
7
+ class Channel
8
+ # One request and every line Python writes for it, its window, and what answers Python's callbacks for it.
9
+ class Exchange
10
+ extend Dry::Initializer
11
+ extend Forwardable
12
+
13
+ param :request, Wire::Types.Instance(Wire::Shape)
14
+
15
+ # How long Python may write nothing while it is open.
16
+ option :window, Wire::Types::Number
17
+
18
+ # Takes each of its model calls as it completes, and the request its outermost caller waits on.
19
+ option :report, Wire::Types.Interface(:call).optional, default: proc {}, reader: :private
20
+
21
+ # Answers a callback of its: takes the Callback and the callback's message, and gives Returned's keys.
22
+ option :serve, Wire::Types.Interface(:call).optional, default: proc {}
23
+
24
+ # Holds one of the slots of Python's pool until its reply.
25
+ option :pooled, Wire::Types::Strict::Bool, default: proc { false }
26
+
27
+ # The request whose callback it was made within, whose spend takes this one's as it replies.
28
+ option :parent, Wire::Types.Instance(Exchange).optional, default: proc {}, reader: :private
29
+
30
+ # What it spent, as Ruby learns it.
31
+ option :meter, default: proc { Meter.new }
32
+
33
+ # Gives its model calls to `report`, and those its gates let go that never went.
34
+ option :reporter, default: proc { Reporter.new(report, root) }
35
+
36
+ option :watchdog, default: proc { Watchdog.new(window) }, reader: :private
37
+ option :queue, default: proc { Thread::Queue.new }, reader: :private
38
+ option :lock, default: proc { Mutex.new }, reader: :private
39
+ option :written, default: proc { false }, reader: :private
40
+ option :cancelled, default: proc { false }, reader: :private
41
+ option :answer, default: proc {}, reader: :private
42
+ option :loss, default: proc {}, reader: :private
43
+ option :kept, default: proc {}, reader: :private
44
+
45
+ def_delegator :request, :id
46
+ def_delegator :queue, :push, :deliver
47
+
48
+ # Python wrote a line, so its window starts again.
49
+ def_delegator :watchdog, :touch
50
+
51
+ # Its whole line reached the pipe: a cancel now has a request to stop.
52
+ def written!
53
+ lock.synchronize { @written = true }
54
+ end
55
+
56
+ def written?
57
+ lock.synchronize { written }
58
+ end
59
+
60
+ # Its caller stopped waiting: none of its callbacks runs from now on.
61
+ def cancel!
62
+ lock.synchronize { @cancelled = true }
63
+ end
64
+
65
+ def answered?
66
+ lock.synchronize { !answer.nil? }
67
+ end
68
+
69
+ # Answered or cancelled: Ruby waits for nothing of it but its late lines.
70
+ def stopped?
71
+ lock.synchronize { cancelled || !answer.nil? }
72
+ end
73
+
74
+ # Its last line, a reply or the Fault a broken one read as.
75
+ def reply
76
+ lock.synchronize { answer }
77
+ end
78
+
79
+ # The request its outermost caller waits on, up every request whose callback it was made within.
80
+ def root
81
+ parent ? parent.root : self
82
+ end
83
+
84
+ # Keeps the first error ending it from within, for its caller to raise after the reply: whether it kept this.
85
+ def keep(error)
86
+ lock.synchronize { (kept.nil? && !cancelled && answer.nil?).tap { |keeping| @kept = error if keeping } }
87
+ end
88
+
89
+ # Its last line, giving each model call to `report` as it arrives; a silent window is the block's to answer.
90
+ def wait
91
+ loop do
92
+ item = take
93
+
94
+ return answered(yield) if item.nil?
95
+ next add(item.call) if item.is_a?(Wire::Progress)
96
+
97
+ return answered(item)
98
+ end
99
+ end
100
+
101
+ # The model calls still running at its reply, each given to `report` as it arrives, for at most `seconds`.
102
+ def trail(seconds)
103
+ ends = now + seconds
104
+
105
+ late.times do
106
+ item = take(ends)
107
+
108
+ # One never heard is counted as one unread: which call it was cannot be told.
109
+ break add(nil) unless item.is_a?(Wire::Progress)
110
+
111
+ add(item.call)
112
+ end
113
+ end
114
+
115
+ def late?
116
+ late.positive?
117
+ end
118
+
119
+ # What it spent as far as Ruby knows, with Python's counts once a reply carries them.
120
+ def spend
121
+ reply = self.reply
122
+ counts = reply.respond_to?(:running) ? [reply.unrecorded, reply.running] : [0, 0]
123
+
124
+ meter.spend(*counts)
125
+ end
126
+
127
+ # What its caller raises for any end but the reply asked for, with what it spent.
128
+ def error
129
+ kept, ended = lock.synchronize { [self.kept, loss || answer] }
130
+
131
+ Ending.error(kept, ended, spend, id)
132
+ end
133
+
134
+ private
135
+
136
+ # Its next line, waited for while Python writes; nil after a whole window of silence, or once `ends` has passed.
137
+ def take(ends = Float::INFINITY)
138
+ loop do
139
+ item = queue.pop(timeout: [watchdog.remaining, ends - now].min.clamp(0, nil))
140
+
141
+ return item if item
142
+ return unless watchdog.alive? && now < ends
143
+ end
144
+ end
145
+
146
+ def now
147
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
148
+ end
149
+
150
+ # A model call that ended; one Python or Ruby could not record has no call, and is counted until the end.
151
+ def add(call)
152
+ call ? meter.add(call) : meter.miss
153
+ reporter.arrived(call)
154
+ rescue StandardError
155
+ # A listener's raise once no one waits for the request has nothing left to stop, so the follow goes on.
156
+ raise unless stopped?
157
+ end
158
+
159
+ # Its end, a reply or the loss of its channel, holds its spend still: a late call reaches `report` alone.
160
+ def answered(item)
161
+ lock.synchronize { item.is_a?(Values::Loss) ? @loss = item : @answer = item }
162
+
163
+ meter.close
164
+ parent&.meter&.nest(spend)
165
+ item
166
+ end
167
+
168
+ def late
169
+ reply = self.reply
170
+
171
+ reply.respond_to?(:running) ? reply.running : 0
172
+ end
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "English"
4
+
5
+ module DSPyRb
6
+ module Runtime
7
+ class Channel
8
+ # A model call's gates, on a thread of their own and waited for at most BOUND; a call never sent is reported.
9
+ class Gate
10
+ extend Dry::Initializer
11
+
12
+ # Only a guard against a gate that hangs, since a gate answers at once from what the app already holds.
13
+ BOUND = 60
14
+
15
+ param :exchange, Wire::Types.Instance(Exchange), reader: :private
16
+ param :pending, Wire::Types.Instance(Wire::PendingCall), reader: :private
17
+ option :channel, Wire::Types.Instance(Channel), reader: :private
18
+ option :lock, default: proc { Mutex.new }, reader: :private
19
+ option :answered, default: proc { false }, reader: :private
20
+
21
+ # What the gates raised, of any kind, read as their thread ends: one outside StandardError refuses the call too.
22
+ option :raised, default: proc {}, reader: :private
23
+
24
+ # Given a value as the gates' thread ends, so it is waited for without what they raised being raised here.
25
+ option :ended, default: proc { Thread::Queue.new }, reader: :private
26
+
27
+ # Set once the bound passes with the gates still running: they report the call themselves when they return.
28
+ option :late, default: proc { false }, reader: :private
29
+
30
+ # What the block, run on a thread of its own, answers; whatever it raises, or no answer in time, stops the call.
31
+ def ask(&)
32
+ asking = Thread.new { asked(&) }
33
+
34
+ refuse(Error.new("a gate gave no answer within #{BOUND} s; the call was not sent")) unless in_time?
35
+ refuse(raised) if raised
36
+
37
+ asking.value.tap { exchange.reporter.admit(pending) if _1.is_a?(Wire::Returned) }
38
+ end
39
+
40
+ private
41
+
42
+ def asked
43
+ Thread.current.report_on_exception = false
44
+ yield
45
+ ensure
46
+ reported = lock.synchronize do
47
+ @raised = $ERROR_INFO
48
+ @answered = true
49
+ late
50
+ end
51
+
52
+ ended << true
53
+ exchange.reporter.unsent(pending) if reported
54
+ end
55
+
56
+ # Whether the gates answered within the bound, or just as it passed.
57
+ def in_time?
58
+ return true if ended.pop(timeout: BOUND)
59
+
60
+ lock.synchronize { @late = !answered }
61
+
62
+ !late
63
+ end
64
+
65
+ # Stops the outermost request at once, as a listener's raise does, and reports the call unless still asking.
66
+ def refuse(error)
67
+ channel.stop(exchange.root, error)
68
+ exchange.reporter.unsent(pending) unless late
69
+ raise error
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # Reads Python's lines on a thread of its own, never writing: each to its request, each callback to a thread.
7
+ class Listener
8
+ extend Dry::Initializer
9
+
10
+ param :reader, Wire::Types.Instance(IO), reader: :private
11
+ option :channel, Wire::Types.Instance(Channel), reader: :private
12
+
13
+ def read
14
+ channel.lose(take_lines)
15
+ rescue StandardError => e
16
+ channel.lose("the reply reader failed (#{e.class})")
17
+ ensure
18
+ # Whatever ended the reading, no caller waits for a line it will never deliver.
19
+ channel.lose("the reply reader stopped")
20
+ end
21
+
22
+ private
23
+
24
+ # A line of Python's as its message, or the Values::Fault a line that breaks the wire reads as.
25
+ def message(line)
26
+ data = JSON.parse(line, symbolize_names: true, allow_duplicate_key: false)
27
+ shape = data.is_a?(::Hash) && Wire::KINDS[data[:kind]]
28
+
29
+ shape ? built(shape, data) : Values::Fault.new(reason: "a line of no kind Python writes")
30
+ rescue JSON::ParserError
31
+ # The parser's own message quotes the line.
32
+ Values::Fault.new(reason: "a line that is not JSON with distinct keys")
33
+ end
34
+
35
+ def take_lines
36
+ while (line = reader.gets)
37
+ channel.heard
38
+ reason = take(message(line))
39
+
40
+ return reason if reason
41
+ end
42
+
43
+ "the Python process ended; its stderr says why"
44
+ end
45
+
46
+ # Why the reading ends, or nil when the line went where it belongs.
47
+ def take(message)
48
+ case message
49
+ when Wire::Alive then nil
50
+ when Values::Fault then fault(message)
51
+ when *Wire::CALLBACKS then call_back(message.id, request: message.request, message:)
52
+ when Wire::Refused then message.id ? deliver(message) : "Python could not read a request: #{message.reason}"
53
+ else deliver(message)
54
+ end
55
+ end
56
+
57
+ def deliver(message)
58
+ channel.deliver(message.id, message)
59
+ nil
60
+ end
61
+
62
+ # A broken line goes to the request it names, or ends the reading when it names none.
63
+ def fault(fault)
64
+ if Wire::CALLBACKS.include?(fault.shape) then broken_callback(fault)
65
+ elsif fault.shape == Wire::Progress then missed(fault)
66
+ else broken_reply(fault)
67
+ end
68
+ end
69
+
70
+ def broken_reply(fault)
71
+ return fault.reason unless fault.request
72
+
73
+ channel.deliver(fault.request, fault)
74
+ nil
75
+ end
76
+
77
+ # An unreadable model call reaches its request as one Python could not record, never failing it.
78
+ def missed(fault)
79
+ return fault.reason unless fault.request
80
+
81
+ channel.deliver(fault.request, Wire::Progress.new(id: fault.request))
82
+ nil
83
+ end
84
+
85
+ # Answered, fatally, so the Python thread waiting on it returns; its request raises the Fault after its reply.
86
+ def broken_callback(fault)
87
+ return fault.reason unless fault.callback
88
+
89
+ channel.exchange(fault.request)&.keep(fault) if fault.request
90
+ call_back(fault.callback, request: fault.request, refusal: fault.reason)
91
+ end
92
+
93
+ def built(shape, data)
94
+ shape.new(data)
95
+ rescue Dry::Struct::Error, Error
96
+ callback = Wire::CALLBACKS.include?(shape)
97
+ request = id(data, callback ? :request : :id)
98
+ reason = "#{named(shape, request)} breaks the wire at #{Wire::Departure.at(shape, data)}"
99
+
100
+ Values::Fault.new({ reason:, shape:, request:, callback: callback ? id(data, :id) : nil }.compact)
101
+ end
102
+
103
+ def named(shape, request)
104
+ return "a #{shape.kind} line" unless request
105
+ return "a callback for request #{request}" if Wire::CALLBACKS.include?(shape)
106
+ return "a model call of request #{request}" if shape == Wire::Progress
107
+
108
+ "the reply to request #{request}"
109
+ end
110
+
111
+ # A callback's own id is Python's, so it names the Ruby request it serves in `request`.
112
+ def id(data, key)
113
+ Wire::Types::Id.valid?(data[key]) ? data[key] : nil
114
+ end
115
+
116
+ def call_back(id, **)
117
+ Callback.new(id, channel:, **).start
118
+ nil
119
+ rescue ThreadError
120
+ "Ruby could not start a thread for a callback (ThreadError)"
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # One request's spend as Ruby learns it, held still from the request's end.
7
+ class Meter
8
+ extend Dry::Initializer
9
+
10
+ option :lock, default: proc { Mutex.new }, reader: :private
11
+ option :calls, default: proc { [] }, reader: :private
12
+ option :missed, default: proc { 0 }, reader: :private
13
+ option :nested, default: proc { [] }, reader: :private
14
+
15
+ # A model call that arrived before the end; a later one is only reported.
16
+ def add(call)
17
+ lock.synchronize { calls << call unless calls.frozen? }
18
+ end
19
+
20
+ # A model call Ruby could not read, counted beside those Python could not record; a later one is not.
21
+ def miss
22
+ lock.synchronize { @missed += 1 unless calls.frozen? }
23
+ end
24
+
25
+ # What a request made within one of the request's callbacks spent, kept until the end; summed only when asked.
26
+ def nest(spend)
27
+ lock.synchronize { nested << spend unless calls.frozen? }
28
+ end
29
+
30
+ def close
31
+ lock.synchronize { calls.freeze }
32
+ end
33
+
34
+ def spend(unrecorded, running)
35
+ lock.synchronize do
36
+ Values::Spend.new(
37
+ calls: calls + nested.flat_map(&:calls),
38
+ unrecorded: unrecorded + missed + nested.sum(&:unrecorded),
39
+ running: running + nested.sum(&:running)
40
+ )
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # Gives a request's model calls to its listeners as each arrives, and each its gates let go that never went.
7
+ class Reporter
8
+ extend Dry::Initializer
9
+
10
+ # Takes each call and the request its outermost caller waits on; none for a request with no listeners.
11
+ param :report, Wire::Types.Interface(:call).optional, reader: :private
12
+ param :root, Wire::Types.Interface(:keep), reader: :private
13
+
14
+ option :lock, default: proc { Mutex.new }, reader: :private
15
+ option :kept, default: proc { {} }, reader: :private
16
+ option :closed, default: proc { false }, reader: :private
17
+
18
+ # Set once a call arrives unread, so which of those kept it was cannot be told.
19
+ option :blurred, default: proc { false }, reader: :private
20
+
21
+ def arrived(call)
22
+ lock.synchronize { call ? kept.delete(call.id) : @blurred = true }
23
+
24
+ report&.call(call, root) if call
25
+ end
26
+
27
+ # Whether calls let go are kept, yet to arrive or be reported unsent.
28
+ def keeping?
29
+ lock.synchronize { kept.any? }
30
+ end
31
+
32
+ # Kept until it arrives, else reported at once, since a request that has ended sends nothing more.
33
+ def admit(pending)
34
+ held = lock.synchronize { kept[pending.id] = pending unless closed }
35
+
36
+ unsent(pending) unless held
37
+ end
38
+
39
+ # Its request has ended: each call kept never went, once every call sent was heard and none went unrecorded.
40
+ def close(reply)
41
+ left = lock.synchronize do
42
+ @closed = true
43
+ ended = kept.values
44
+
45
+ kept.clear
46
+ !blurred && counted?(reply) ? ended : []
47
+ end
48
+
49
+ left.each { unsent(_1) }
50
+ end
51
+
52
+ def unsent(pending)
53
+ report&.call(pending.unsent, root)
54
+ rescue StandardError
55
+ # Kept as a listener's raise at any call is; a call never sent was stopped already, or its request ended.
56
+ nil
57
+ end
58
+
59
+ private
60
+
61
+ # A reply that counts no call unrecorded, where a loss or an unreadable reply counts nothing at all.
62
+ def counted?(reply)
63
+ reply.is_a?(Wire::Shape) && (!reply.respond_to?(:unrecorded) || reply.unrecorded.zero?)
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # Sees each request through once its caller stops waiting, on a thread of its own while Python writes for it.
7
+ class Settler
8
+ extend Dry::Initializer
9
+
10
+ # The longest a late call is followed past its reply: one in a hung engine never ends.
11
+ FOLLOW = 3_600
12
+
13
+ param :traffic, Wire::Types.Instance(Traffic), reader: :private
14
+ option :channel, Wire::Types.Instance(Channel), reader: :private
15
+
16
+ # Its reply frees its slot; a request left without one is cancelled, its slot held until the reply.
17
+ def settle(exchange)
18
+ Thread.handle_interrupt(Object => :never) { settled(exchange) }
19
+ end
20
+
21
+ private
22
+
23
+ def settled(exchange)
24
+ if exchange.answered?
25
+ traffic.release(exchange)
26
+ ended(exchange)
27
+ elsif exchange.written? && !channel.lost?
28
+ cancel(exchange)
29
+ else
30
+ traffic.drop(exchange)
31
+ end
32
+ end
33
+
34
+ # Late calls, or calls let go yet to arrive, are reported on a thread of its own, out of the caller's reach.
35
+ def ended(exchange)
36
+ return follow(exchange) if exchange.late? || exchange.reporter.keeping?
37
+
38
+ traffic.drop(exchange)
39
+ exchange.reporter.close(exchange.reply)
40
+ end
41
+
42
+ # Written under settle's mask, so a second interrupt cannot drop it and leave Python spending for the request.
43
+ def cancel(exchange)
44
+ exchange.cancel!
45
+ follow(exchange)
46
+ channel.notify(Wire::Cancel.new(of: exchange.id))
47
+ end
48
+
49
+ def follow(exchange)
50
+ Thread.new(exchange) { followed(_1) }
51
+ rescue ThreadError
52
+ channel.lose("Ruby could not start a thread to follow a request (ThreadError)")
53
+ traffic.drop(exchange)
54
+ end
55
+
56
+ # Its reply and late model calls, taken on a thread of their own: a silent window still loses the channel.
57
+ def followed(exchange)
58
+ Thread.current.report_on_exception = false
59
+ exchange.wait { channel.lose(channel.silent(exchange)) } unless exchange.answered?
60
+ traffic.release(exchange)
61
+ exchange.trail(FOLLOW)
62
+ exchange.reporter.close(exchange.reply)
63
+ ensure
64
+ traffic.drop(exchange)
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end