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,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # One channel's open exchanges by id, the slots of Python's pool they hold, and the loss that ends them all.
7
+ class Traffic
8
+ extend Dry::Initializer
9
+
10
+ # The longest a request waits for a slot of Python's pool, whose calls may run as long as DSPy's do.
11
+ ADMISSION = 3_600
12
+
13
+ # At most this many requests that take a pool thread are in Python at once, so none waits there for a thread.
14
+ param :limit, Wire::Types::Strict::Integer.constrained(gteq: 1), reader: :private
15
+
16
+ option :lock, default: proc { Mutex.new }, reader: :private
17
+ option :changed, default: proc { ConditionVariable.new }, reader: :private
18
+ option :exchanges, default: proc { {} }, reader: :private
19
+ option :pool, default: proc { Set.new }, reader: :private
20
+
21
+ # The first loss wins: every later request is refused with it.
22
+ option :losses, default: proc { [] }, reader: :private
23
+
24
+ def [](id)
25
+ lock.synchronize { exchanges[id] }
26
+ end
27
+
28
+ def lost
29
+ lock.synchronize { losses.first }
30
+ end
31
+
32
+ # Registers it, its window starting now, after waiting at most ADMISSION for a pool slot when it takes one.
33
+ def admit(exchange)
34
+ lock.synchronize do
35
+ room(exchange) if exchange.pooled
36
+ standing(exchange)
37
+
38
+ pool << exchange.id if exchange.pooled
39
+ exchanges[exchange.id] = exchange
40
+ exchange.touch
41
+ end
42
+ end
43
+
44
+ # Python wrote a line: each open exchange's window starts again.
45
+ def touch
46
+ lock.synchronize { exchanges.each_value(&:touch) }
47
+ end
48
+
49
+ # Its reply frees its slot.
50
+ def release(exchange)
51
+ lock.synchronize do
52
+ pool.delete(exchange.id)
53
+ changed.broadcast
54
+ end
55
+ end
56
+
57
+ def drop(exchange)
58
+ lock.synchronize do
59
+ exchanges.delete(exchange.id)
60
+ pool.delete(exchange.id)
61
+ changed.broadcast
62
+ end
63
+ end
64
+
65
+ def drain(grace)
66
+ ends = now + grace
67
+
68
+ lock.synchronize do
69
+ changed.wait(lock, ends - now) until exchanges.empty? || losses.any? || now >= ends
70
+ end
71
+ end
72
+
73
+ # The first loss reaches every exchange: whether this one was it.
74
+ def lose(reason)
75
+ lock.synchronize do
76
+ next false if losses.any?
77
+
78
+ losses << Values::Loss.new(reason:)
79
+
80
+ exchanges.each_value { _1.deliver(losses.first) }
81
+
82
+ changed.broadcast
83
+ true
84
+ end
85
+ end
86
+
87
+ private
88
+
89
+ def room(exchange)
90
+ ends = now + ADMISSION
91
+
92
+ changed.wait(lock, ends - now) while full? && now < ends
93
+
94
+ return unless full?
95
+
96
+ reason = "Python's #{limit} pool threads stayed busy for #{ADMISSION} s"
97
+
98
+ raise unavailable(exchange, reason)
99
+ end
100
+
101
+ def standing(exchange)
102
+ raise unavailable(exchange, losses.first.reason) if losses.any?
103
+ end
104
+
105
+ # Raised before the request is sent, so it spent nothing.
106
+ def unavailable(exchange, reason)
107
+ Unavailable.new(reason, Values::Spend.new, exchange.id)
108
+ end
109
+
110
+ # A loss ends the wait for room.
111
+ def full?
112
+ pool.size >= limit && losses.empty?
113
+ end
114
+
115
+ def now
116
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
117
+ end
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # One request's window: each line of Python's starts it again.
7
+ class Watchdog
8
+ extend Dry::Initializer
9
+
10
+ # How long Python may write nothing while the request is open.
11
+ param :window, Wire::Types::Number, reader: :private
12
+
13
+ option :lock, default: proc { Mutex.new }, reader: :private
14
+ option :touched, default: proc { now }, reader: :private
15
+
16
+ def touch
17
+ lock.synchronize { @touched = now }
18
+ end
19
+
20
+ def remaining
21
+ lock.synchronize { [window - (now - touched), 0].max }
22
+ end
23
+
24
+ def alive?
25
+ lock.synchronize { now - touched < window }
26
+ end
27
+
28
+ private
29
+
30
+ def now
31
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ class Channel
6
+ # Writes Ruby's lines to Python whole, or loses the channel when Python takes none of a line for a stall bound.
7
+ class Writer
8
+ extend Dry::Initializer
9
+
10
+ # Python's reader drains the pipe while it lives, so a Python that takes no byte for this long is stuck.
11
+ STALL = 30
12
+
13
+ # The longest a write waits on a full pipe before it looks again, which bounds how long a close waits for it.
14
+ PAUSE = 0.5
15
+
16
+ param :io, Wire::Types.Instance(IO), reader: :private
17
+
18
+ # Takes why the channel is lost, and gives the loss that stands.
19
+ option :lose, Wire::Types.Interface(:call), reader: :private
20
+ option :writing, default: proc { Mutex.new }, reader: :private
21
+
22
+ # Nil once the line is whole, after the block, else the loss; an interrupt mid-line waits until it is whole.
23
+ def put(line)
24
+ writing.synchronize do
25
+ Thread.handle_interrupt(Object => :never) do
26
+ loss = whole("#{line}\n")
27
+
28
+ yield if loss.nil? && block_given?
29
+ loss
30
+ end
31
+ end
32
+ rescue IOError, SystemCallError => e
33
+ # A close from another thread reaches a write here, once its line is done with.
34
+ lose.call("the request pipe is closed (#{e.class})")
35
+ end
36
+
37
+ # A write waiting on the pipe ends with IOError within a pause, as the pipe closes.
38
+ def close
39
+ io.close unless io.closed?
40
+ end
41
+
42
+ private
43
+
44
+ def whole(data)
45
+ sent = 0
46
+ ends = now + STALL
47
+
48
+ while sent < data.bytesize
49
+ written = chunk(data.byteslice(sent..), ends)
50
+
51
+ return lose.call("Python read nothing for #{STALL} s") unless written
52
+
53
+ # Each byte Python takes starts the bound again: only a Python that has stopped reading loses the channel.
54
+ ends = now + STALL if written.positive?
55
+ sent += written
56
+ end
57
+ rescue IOError, SystemCallError => e
58
+ # Lost here, inside the mask, since a Timeout waiting at its end would take this error's place.
59
+ lose.call("the request pipe is closed (#{e.class})")
60
+ end
61
+
62
+ # What the pipe took; 0 after a pause on a full pipe; nil once the stall bound has passed with no room.
63
+ def chunk(rest, ends)
64
+ written = io.write_nonblock(rest, exception: false)
65
+
66
+ return written unless written == :wait_writable
67
+
68
+ 0 if io.wait_writable([ends - now, PAUSE].min.clamp(0..)) || now < ends
69
+ end
70
+
71
+ def now
72
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,145 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ # Requests from many threads over one Python's two pipes, each an exchange with every line Python writes for it.
6
+ class Channel
7
+ extend Dry::Initializer
8
+
9
+ FORGOTTEN = "this channel is the parent process's: a forked child forgets it"
10
+
11
+ # Python writes an alive line each interval while a request is open, so only a frozen or lost one is this silent.
12
+ WINDOW = 30 * Wire::ALIVE_INTERVAL
13
+
14
+ # Hello's own, since Python writes nothing until it has loaded DSPy and read the hello.
15
+ HELLO = 120
16
+
17
+ # The end Ruby reads Python's lines from, and the end it writes its own to.
18
+ option :replies, Wire::Types.Instance(IO), reader: :private
19
+ option :requests, Wire::Types.Instance(IO), reader: :private
20
+ option :limit, Wire::Types::Strict::Integer.constrained(gteq: 1), reader: :private
21
+
22
+ # How long Python may write nothing while a request is open.
23
+ option :window, Wire::Types::Number, default: proc { WINDOW }, reader: :private
24
+
25
+ option :on_loss, Wire::Types.Interface(:call).optional, default: proc {}, reader: :private
26
+ option :traffic, default: proc { Traffic.new(limit) }, reader: :private
27
+ option :writer, default: proc { Writer.new(requests, lose: method(:lose)) }, reader: :private
28
+ option :settler, default: proc { Settler.new(traffic, channel: self) }, reader: :private
29
+ option :numbering, default: proc { Mutex.new }, reader: :private
30
+ option :last_id, default: proc { 0 }, reader: :private
31
+
32
+ # Set in a forked child, whose copy touches neither its parent's ends nor its locks.
33
+ option :forgotten, default: proc { false }, reader: :private
34
+
35
+ # Declared last, so everything it reads exists.
36
+ option :listener, default: proc { listen }, reader: :private
37
+
38
+ def lost?
39
+ !traffic.lost.nil?
40
+ end
41
+
42
+ # A window with no line from Python loses the channel; `parent` is the exchange whose callback makes it.
43
+ def ask(shape, report: nil, serve: nil, parent: nil, **fields)
44
+ raise Unavailable.new(FORGOTTEN, Values::Spend.new) if forgotten
45
+
46
+ exchange = exchange_for(shape, fields, report: report && report_for(report), serve:, parent:)
47
+
48
+ traffic.admit(exchange)
49
+ post(exchange)
50
+
51
+ exchange.wait { lose(silent(exchange)) }
52
+
53
+ exchange
54
+ ensure
55
+ settler.settle(exchange) if exchange
56
+ end
57
+
58
+ def drain(grace)
59
+ traffic.drain(grace)
60
+ end
61
+
62
+ # Python reads the end of its input, and each request still waiting fails at once.
63
+ def close
64
+ traffic.lose("the channel is closed")
65
+ writer.close
66
+ end
67
+
68
+ # A forked child's copy closes without a lock or a write, since a parent's thread may hold either.
69
+ def forget
70
+ @forgotten = true
71
+
72
+ [replies, requests].each { _1.close unless _1.closed? }
73
+ end
74
+
75
+ # Python wrote a line, so it is alive: every open request's window starts again.
76
+ def heard
77
+ traffic.touch
78
+ end
79
+
80
+ # Why a request's silent window loses the channel.
81
+ def silent(exchange)
82
+ "Python wrote nothing for #{exchange.window} s"
83
+ end
84
+
85
+ # A line of Python's, for the request it belongs to.
86
+ def deliver(id, item)
87
+ traffic[id]&.deliver(item)
88
+ end
89
+
90
+ def exchange(id)
91
+ traffic[id]
92
+ end
93
+
94
+ # Writes a line Python answers nothing to, such as a callback's answer; once Python has gone, nothing is written.
95
+ def notify(message)
96
+ writer.put(Wire.write(message)) unless forgotten || lost?
97
+ end
98
+
99
+ def lose(reason)
100
+ on_loss&.call(self) if traffic.lose(reason)
101
+
102
+ traffic.lost
103
+ end
104
+
105
+ # Stops the outermost request at once, its error kept and its cancel written, unless it had stopped already.
106
+ def stop(root, error)
107
+ # Masked, as the settler's cancel is, so an interrupt cannot keep the error yet lose the cancel.
108
+ Thread.handle_interrupt(Object => :never) { notify(Wire::Cancel.new(of: root.id)) if root.keep(error) }
109
+ end
110
+
111
+ private
112
+
113
+ # Started in a fiber with no storage, so the reader holds no caller's context for good.
114
+ def listen
115
+ Fiber.new(storage: {}) { Thread.new { Listener.new(replies, channel: self).read } }.resume
116
+ end
117
+
118
+ # A plain counter under a lock: an Enumerator cannot be advanced from more than one thread.
119
+ def next_id
120
+ numbering.synchronize { @last_id += 1 }
121
+ end
122
+
123
+ def exchange_for(shape, fields, **)
124
+ request = shape.new(id: next_id, **fields)
125
+
126
+ Exchange.new(request, window: shape == Wire::Hello ? HELLO : window, pooled: pooled?(shape, fields), **)
127
+ end
128
+
129
+ # The block given with each call stops the outermost request at once: its error kept, its cancel written.
130
+ def report_for(report)
131
+ ->(call, root) { report.call(call) { |error| stop(root, error) } }
132
+ end
133
+
134
+ # A request made while serving a callback takes no pool thread: Python serves it on the thread that waits.
135
+ def pooled?(shape, fields)
136
+ !fields.key?(:within) && Wire::POOLED.include?(shape)
137
+ end
138
+
139
+ # A loss in the write reaches the exchange, admitted already, as its last line.
140
+ def post(exchange)
141
+ writer.put(Wire.write(exchange.request)) { exchange.written! }
142
+ end
143
+ end
144
+ end
145
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "io/nonblock"
4
+
5
+ module DSPyRb
6
+ module Runtime
7
+ # The spawned Python's operating-system process.
8
+ class Child
9
+ extend Dry::Initializer
10
+
11
+ STOP_WAIT = 5
12
+
13
+ param :pid, Wire::Types::Strict::Integer
14
+
15
+ # How long it is given to end on its own, then after TERM, before KILL.
16
+ option :stop_wait, Wire::Types::Number, default: proc { STOP_WAIT }, reader: :private
17
+
18
+ # Nothing else would reap it when it dies.
19
+ option :reaper, default: proc { ::Process.detach(pid) }, reader: :private
20
+
21
+ # A forked worker never stops its parent's Python.
22
+ option :owner, default: proc { ::Process.pid }, reader: :private
23
+
24
+ def self.spawn(env, requests, replies, threads:, logging:)
25
+ # IO.pipe's ends are non-blocking: the child would read an idle pipe as its end and cut a long reply.
26
+ requests.nonblock = false
27
+ replies.nonblock = false
28
+ flags = ["--threads", threads.to_s, logging ? "--logging" : "--no-logging"]
29
+
30
+ # Unbuffered, so a line DSPy prints reaches the app's stderr as it does, the wire's own pipes untouched.
31
+ command = [Setup::Environment.python, "-I", "-u", "-m", "dspy_rb", *flags]
32
+ ends = { Wire::REQUESTS_FD => requests, Wire::REPLIES_FD => replies, in: File::NULL, out: :err }
33
+
34
+ new(::Process.spawn(env.variables, *command, ends))
35
+ end
36
+
37
+ def stop
38
+ return unless owner == ::Process.pid
39
+
40
+ ::Process.kill("TERM", pid) unless reaper.join(stop_wait)
41
+ ::Process.kill("KILL", pid) unless reaper.join(stop_wait)
42
+ reaper.join
43
+ rescue Errno::ESRCH
44
+ nil
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ # A running Python.
6
+ class Python
7
+ extend Dry::Initializer
8
+
9
+ param :channel, Wire::Types.Instance(Channel), reader: :private
10
+ param :welcome, Wire::Types.Instance(Wire::Welcome)
11
+
12
+ # None for a Python whose process the gem did not start, which it never replaces.
13
+ option :child, Wire::Types.Instance(Child).optional, default: proc {}
14
+
15
+ # Python exits at the end of its input; signals follow only if it does not.
16
+ def self.finish(channel, child)
17
+ channel.close
18
+ child&.stop
19
+ end
20
+
21
+ def pid
22
+ child&.pid
23
+ end
24
+
25
+ def ask(shape, **)
26
+ channel.ask(shape, **)
27
+ end
28
+
29
+ def replaceable?
30
+ !child.nil? && channel.lost?
31
+ end
32
+
33
+ def stop(grace)
34
+ channel.drain(grace)
35
+ self.class.finish(channel, child)
36
+ end
37
+
38
+ def forget
39
+ channel.forget
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ # This Ruby process's one Python, started on first use and stopped at exit.
6
+ module Registry
7
+ @lock = Mutex.new
8
+
9
+ class << self
10
+ def current
11
+ @lock.synchronize do
12
+ @current = nil if @current&.replaceable?
13
+ @current ||= Startup.start(**DSPyRb.config.to_h.slice(:threads, :env, :logging))
14
+ end
15
+ end
16
+
17
+ def shutdown(grace = DSPyRb.config.grace)
18
+ python = @lock.synchronize { @current.tap { @current = nil } }
19
+
20
+ python&.stop(grace)
21
+ end
22
+
23
+ # A forked child forgets its parent's Python without writing to it.
24
+ def forget
25
+ @current&.forget
26
+ @current = nil
27
+
28
+ # A parent's thread may have held the lock at the fork, and no such thread exists here to release it.
29
+ @lock = Mutex.new
30
+ end
31
+ end
32
+
33
+ # Each forked worker starts its own Python.
34
+ module Fork
35
+ def _fork
36
+ pid = super
37
+
38
+ Registry.forget if pid.zero?
39
+ pid
40
+ end
41
+ end
42
+
43
+ ::Process.singleton_class.prepend(Fork)
44
+
45
+ at_exit { Registry.shutdown }
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Runtime
5
+ # Spawns a Python and checks its welcome.
6
+ module Startup
7
+ class << self
8
+ def start(threads:, env:, logging:)
9
+ requests, writer = IO.pipe(Encoding::UTF_8)
10
+ reader, replies = IO.pipe(Encoding::UTF_8)
11
+ child = Child.spawn(env, requests, replies, threads:, logging:)
12
+
13
+ # A lost child is ended in the background, so the caller learns of the loss at once.
14
+ on_loss = ->(lost) { Thread.new { Python.finish(lost, child) } }
15
+
16
+ greeted(Channel.new(replies: reader, requests: writer, limit: threads, on_loss:), child)
17
+ ensure
18
+ requests&.close
19
+ replies&.close
20
+ end
21
+
22
+ private
23
+
24
+ # Ended unless greeted, whatever stops the greeting: a Timeout raises no StandardError inside its block.
25
+ def greeted(channel, child)
26
+ greeting = channel.ask(Wire::Hello, protocol: Wire::PROTOCOL)
27
+
28
+ check(greeting)
29
+ python = Python.new(channel, greeting.reply, child:)
30
+ ensure
31
+ Python.finish(channel, child) unless python
32
+ end
33
+
34
+ def check(greeting)
35
+ welcome = greeting.reply
36
+
37
+ raise greeting.error unless welcome.is_a?(Wire::Welcome)
38
+
39
+ served = [welcome.protocol, welcome.package, welcome.dspy, welcome.python[/\A\d+\.\d+/]]
40
+ wanted = [Wire::PROTOCOL, VERSION, DSPY_VERSION, PYTHON_VERSION]
41
+
42
+ return if served == wanted
43
+
44
+ raise SetupError, "#{offered(*served)}, but this gem needs #{offered(*wanted)}: run `ruby-on-dspy setup`"
45
+ end
46
+
47
+ def offered(protocol, package, dspy, python)
48
+ "protocol #{protocol}, ruby-on-dspy #{package} and DSPy #{dspy} on Python #{python}"
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # What keeps keys out of everything the gem prints.
5
+ module Secrets
6
+ # Where Python's scrub cuts a message: a word a key follows, never one a provider's sign-in advice needs.
7
+ CUT_AT = /(?i)authori[sz]ation|x-(?:goog-)?api-key|api[-_ ]?key|bearer|secret|password|cookie/
8
+
9
+ # A name that may hold a key: CUT_AT's words, a credential, an access or private key, or a token.
10
+ NAME = Regexp.union(CUT_AT, /(?:access|private)[-_ ]?key|credential|(?:\A|[-_ ])token\z/i)
11
+
12
+ # Text that looks like a key, whatever holds it: a prefixed key, or a long token. Python's scrub reads it too.
13
+ KEY_LIKE = /(?i)\b(?:sk|key|aiza)[-_][A-Za-z0-9_\-*.]{4,}|[A-Za-z0-9_-]{24,}/
14
+ HIDDEN = "[hidden]"
15
+
16
+ def self.hidden(value)
17
+ case value
18
+ when ::Hash then value.to_h { |name, item| [name, NAME.match?(name.to_s) ? HIDDEN : hidden(item)] }
19
+ when ::Array then value.map { hidden(_1) }
20
+ when ::String then value.gsub(KEY_LIKE, HIDDEN)
21
+ else value
22
+ end
23
+ end
24
+ end
25
+ end