emb 0.4.3.pre6 → 0.5.0.pre1

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.
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Emb
4
+ module Telemetry
5
+ # The per-thread deferral clock for `lazy` modes: keyed by the batch item
6
+ # (batch-loader's dedupe key) and never stored inside the tuple, where a
7
+ # per-call value would defeat coalescing and duplicate server inference.
8
+ #
9
+ # An entry is removed when its item resolves. Survivors are flushed as
10
+ # not-dispatched when the batch scope clears, which is the only evidence
11
+ # that a call waited and never reached a command.
12
+ module Deferred
13
+ KEY = :emb_telemetry_deferrals
14
+ private_constant :KEY
15
+
16
+ module_function
17
+
18
+ # `||=` keeps the earliest deferral for a coalesced tuple. Entries are
19
+ # keyed by the canonical item object itself (compared by identity): a
20
+ # content hash would follow a payload mutation and strand the entry.
21
+ def record(item, entry)
22
+ deferrals[canonical(item)] ||= entry.merge(at: Telemetry.mono, wall: Time.now)
23
+ end
24
+
25
+ # batch-loader keeps the first instance of a coalesced key, so a
26
+ # duplicate call has to record against the item the block will resolve.
27
+ # shortcut: one linear scan of the pending scope per deferral (bounded by
28
+ # batch_size); revisit if deferral throughput ever matters.
29
+ def canonical(item)
30
+ pending = BatchLoader::Executor.current&.items_by_block&.[](Emb::BATCH_PENDING_KEY)
31
+ pending&.find { |queued| queued == item } || item
32
+ end
33
+
34
+ # Stamps the dispatch point of a share's items: the queue ends here,
35
+ # before the command is written. The metric is emitted on resolution, so a
36
+ # slice an earlier failure never attempted contributes no queue.
37
+ def dispatched(slice)
38
+ now = Telemetry.mono
39
+ slice.each do |item|
40
+ entry = deferrals[item]
41
+ entry[:queue] ||= now - entry[:at] if entry
42
+ end
43
+ end
44
+
45
+ # Closes the deferred call's span. `dispatched: false` marks an item that
46
+ # resolved without ever being part of a sent command, so it is never read
47
+ # as a fast inference.
48
+ def resolve(item, dispatched: true, error: nil)
49
+ entry = deferrals.delete(item)
50
+ return unless entry
51
+
52
+ now = Telemetry.mono
53
+ queue = entry[:queue] || (now - entry[:at])
54
+ span = open_span(entry, dispatched: dispatched, queue: queue)
55
+ Telemetry.fail_span(span, error) if error
56
+ Telemetry.end_span(span)
57
+ Telemetry.histogram('emb.client.queue.duration', queue, attributes: { 'emb.mode' => entry[:mode] })
58
+ Telemetry.histogram('emb.client.embed.duration', now - entry[:at], attributes: metric_attributes(entry))
59
+ end
60
+
61
+ # Flushes deferrals that resolved without a command, then drops the scope's
62
+ # registry. Called when the batch scope ends and when a batch fails closed.
63
+ def flush
64
+ entries = Thread.current[KEY]
65
+ return if entries.nil? || entries.empty?
66
+
67
+ wall = Time.now
68
+ entries.each_value { |entry| emit(entry, wall) }
69
+ entries.clear
70
+ end
71
+
72
+ def span_attributes(entry, dispatched:)
73
+ attributes = {
74
+ 'emb.operation' => entry[:operation],
75
+ 'emb.model' => entry[:model],
76
+ 'emb.texts' => entry[:texts],
77
+ 'emb.mode' => entry[:mode],
78
+ 'emb.dispatched' => dispatched
79
+ }
80
+ attributes['emb.format'] = entry[:format].to_s if entry[:format]
81
+ attributes
82
+ end
83
+
84
+ def metric_attributes(entry)
85
+ attributes = { 'emb.model' => entry[:model], 'emb.mode' => entry[:mode] }
86
+ attributes['emb.format'] = entry[:format].to_s if entry[:format]
87
+ attributes
88
+ end
89
+
90
+ def deferrals
91
+ Thread.current[KEY] ||= {}.compare_by_identity
92
+ end
93
+
94
+ def open_span(entry, dispatched:, queue: nil)
95
+ attributes = span_attributes(entry, dispatched: dispatched)
96
+ attributes['emb.queue'] = queue if queue
97
+ Telemetry.start_span(Telemetry::SPAN_EMBED, attributes: attributes, kind: :client,
98
+ start_timestamp: entry[:wall])
99
+ end
100
+
101
+ def emit(entry, wall)
102
+ Telemetry.end_span(open_span(entry, dispatched: false), at: wall)
103
+ Telemetry.histogram('emb.client.embed.duration', Telemetry.mono - entry[:at],
104
+ attributes: metric_attributes(entry))
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,264 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Emb
4
+ # OpenTelemetry signals for the client itself.
5
+ #
6
+ # Optional: the gem does not depend on the OpenTelemetry gems. Install
7
+ # `opentelemetry-api` (and `opentelemetry-metrics-api` for metrics) and the
8
+ # client emits; without them every path below returns immediately. When they
9
+ # are installed but no SDK is configured, the API's default providers are
10
+ # no-ops. There is no gem-specific configuration; `OTEL_SDK_DISABLED=true` is
11
+ # the standard off, and nothing here may alter a command's arguments, result,
12
+ # or error.
13
+ #
14
+ # Spans carry no input text, image bytes, or vectors: model, operation, format,
15
+ # counts, and the instance that served a command only.
16
+ module Telemetry
17
+ SPAN_EMBED = 'emb.embed'
18
+ SPAN_BATCH = 'emb.batch'
19
+ SPAN_SHARE = 'emb.share'
20
+
21
+ # Declared as instrument advice, per unit. The SDK's default boundaries are
22
+ # millisecond-scale, so durations need their own and counts/ratios would
23
+ # collapse into one bucket under them.
24
+ BOUNDARIES = [0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0].freeze
25
+ COUNT_BOUNDARIES = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128].freeze
26
+ RATIO_BOUNDARIES = [1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 24.0, 32.0].freeze
27
+ UNIT_BOUNDARIES = { 's' => BOUNDARIES, '{share}' => COUNT_BOUNDARIES, '1' => RATIO_BOUNDARIES }.freeze
28
+
29
+ HISTOGRAMS = {
30
+ 'emb.client.embed.duration' => ['s', 'End-to-end latency of one embedding call, deferral included.'],
31
+ 'emb.client.queue.duration' => ['s', 'Time a deferred call waited before its command was dispatched.'],
32
+ 'emb.client.batch.duration' => ['s', 'Wall time of one forced batch.'],
33
+ 'emb.client.batch.shares' => ['{share}', 'Commands dispatched by one forced batch.'],
34
+ 'emb.client.batch.parallelism' => ['1', 'Share time divided by batch wall time; 1 is fully serial.'],
35
+ 'emb.client.share.duration' => ['s', 'Round trip of one command dispatched by a deferred mode.']
36
+ }.freeze
37
+
38
+ IN_FLIGHT = 'emb.client.shares.in_flight'
39
+ NAME = 'emb'
40
+
41
+ State = Struct.new(:provider, :tracer, :histograms, :in_flight)
42
+ private_constant :State
43
+
44
+ # Runs the block inside a span. Telemetry failures are contained: whatever
45
+ # the block returns or raises is what crosses this boundary.
46
+ # Loads the OpenTelemetry API on first use and remembers the answer, so an
47
+ # app that never installs it pays one branch per signal.
48
+ def self.available?
49
+ @available = load_api unless defined?(@available)
50
+ @available
51
+ end
52
+
53
+ # The metrics API does not define the global meter accessors on its own (it
54
+ # is still unstable), and it is a separate gem: traces can be present while
55
+ # metrics are not.
56
+ def self.load_api
57
+ require 'opentelemetry-api'
58
+ begin
59
+ require 'opentelemetry-metrics-api'
60
+ require 'opentelemetry/metrics/global'
61
+ rescue LoadError
62
+ nil
63
+ end
64
+ true
65
+ rescue LoadError
66
+ false
67
+ end
68
+
69
+ # The current span context, or nil when telemetry is unavailable. Callers
70
+ # pass it to a worker thread: a fresh Thread starts with an empty context.
71
+ def self.current_context
72
+ return nil unless available?
73
+
74
+ OpenTelemetry::Context.current
75
+ rescue StandardError
76
+ nil
77
+ end
78
+
79
+ # `current: true` makes the span the parent of spans created inside the
80
+ # block. Only a batch has children, and attaching a span costs a fiber-local
81
+ # write, so an ordinary call does not pay for it.
82
+ def self.in_span(name, attributes: nil, kind: :internal, current: false, &block)
83
+ span = start_span(name, attributes: attributes, kind: kind)
84
+ return block.call unless span
85
+ return around_span(span, &block) unless current
86
+
87
+ OpenTelemetry::Trace.with_span(span) { around_span(span, &block) }
88
+ end
89
+
90
+ def self.around_span(span, &block)
91
+ block.call
92
+ rescue StandardError => e
93
+ fail_span(span, e)
94
+ raise
95
+ ensure
96
+ safe { span.finish }
97
+ end
98
+
99
+ def self.start_span(name, attributes: nil, kind: :internal, start_timestamp: nil, parent: nil)
100
+ tracer = state&.tracer
101
+ return nil unless tracer
102
+
103
+ tracer.start_span(name, kind: kind, attributes: attributes, start_timestamp: start_timestamp,
104
+ with_parent: parent)
105
+ rescue StandardError
106
+ nil
107
+ end
108
+
109
+ # Ends a span that was started backdated (a deferred call's span starts at
110
+ # its deferral but is built when it resolves).
111
+ def self.end_span(span, at: Time.now)
112
+ safe { span&.finish(end_timestamp: at) }
113
+ end
114
+
115
+ def self.fail_span(span, error)
116
+ return unless span
117
+
118
+ safe { span.record_exception(error) }
119
+ safe { span.status = OpenTelemetry::Trace::Status.error(error.message) }
120
+ end
121
+
122
+ def self.histogram(name, value, attributes: {})
123
+ instrument = state&.histograms&.[](name)
124
+ instrument&.record(value, attributes: attributes)
125
+ rescue StandardError
126
+ nil
127
+ end
128
+
129
+ def self.in_flight(delta)
130
+ state&.in_flight&.add(delta)
131
+ rescue StandardError
132
+ nil
133
+ end
134
+
135
+ # One eager call: its span and its end-to-end duration, whichever way the
136
+ # command ends.
137
+ def self.embed_call(operation:, model:, texts:, format:, mode:, &)
138
+ entry = { at: mono, model: model.to_s, texts: texts, format: format, mode: mode.to_s }
139
+ attributes = { 'emb.operation' => operation, 'emb.model' => entry[:model], 'emb.texts' => texts }
140
+ attributes['emb.format'] = format.to_s if format
141
+ attributes['emb.mode'] = entry[:mode]
142
+ in_span(SPAN_EMBED, attributes: attributes, kind: :client, &)
143
+ ensure
144
+ histogram('emb.client.embed.duration', mono - entry[:at], attributes: metric_attributes(entry)) if entry
145
+ end
146
+
147
+ # One deferred batch: its span, its wall time, and its parallelism.
148
+ # `durations` is filled by the dispatcher with each share's duration, so a
149
+ # batch that raises still reports what actually ran.
150
+ def self.batch(mode:, shares:, texts:, workers:)
151
+ mode = mode.to_s
152
+ attributes = { 'emb.mode' => mode, 'emb.shares' => shares, 'emb.texts' => texts, 'emb.workers' => workers }
153
+ started = mono
154
+ durations = []
155
+ begin
156
+ in_span(SPAN_BATCH, attributes: attributes, current: true) { yield durations }
157
+ ensure
158
+ wall = mono - started
159
+ histogram('emb.client.batch.duration', wall, attributes: { 'emb.mode' => mode })
160
+ histogram('emb.client.batch.shares', shares, attributes: { 'emb.mode' => mode })
161
+ histogram('emb.client.batch.parallelism', wall.positive? ? durations.sum / wall : 0.0,
162
+ attributes: { 'emb.mode' => mode })
163
+ end
164
+ end
165
+
166
+ def self.mono = Process.clock_gettime(Process::CLOCK_MONOTONIC)
167
+
168
+ # A deferral entry: what a deferred call needs to emit its span when it
169
+ # resolves. Mode comes from the client so a per-call override is honored.
170
+ def self.entry_for(client, operation:, model:, texts:, format:)
171
+ { operation: operation, model: model.to_s, texts: texts, format: format,
172
+ mode: mode_for(client) }
173
+ end
174
+
175
+ # The batching mode label used on spans and metrics: eager|multi|batch.
176
+ def self.mode_for(client)
177
+ mode = client.respond_to?(:lazy_mode) ? client.lazy_mode : false
178
+ mode.nil? || mode == false ? 'eager' : mode.to_s
179
+ end
180
+
181
+ # Ends a share span and records its duration. The instance is passed in
182
+ # because it is only known after the command ran (a pre-send retry may
183
+ # have moved it to another instance).
184
+ # Attributes of one dispatched share. A mixed-model chunk carries no model
185
+ # attribute rather than a list: the model tag must stay low-cardinality.
186
+ def self.share_attributes(models, texts)
187
+ attributes = { 'emb.texts' => texts }
188
+ attributes['emb.model'] = models.first.to_s if models.size == 1
189
+ attributes
190
+ end
191
+
192
+ # The span keeps the text count; the histogram must not: it would create one
193
+ # series per count (up to batch_size), which is unbounded label cardinality.
194
+ def self.end_share(span, elapsed, attributes:, instance: nil)
195
+ attributes = attributes.merge('emb.instance' => instance) if instance
196
+ safe { span&.set_attribute('emb.instance', instance) } if instance
197
+ end_span(span)
198
+ histogram('emb.client.share.duration', elapsed, attributes: attributes.except('emb.texts'))
199
+ elapsed
200
+ end
201
+
202
+ # Built once per process. The API's proxy providers forward to an SDK
203
+ # configured later, and its provider reader takes a global mutex, so
204
+ # re-reading one on every call would buy a lock and nothing else.
205
+ def self.state
206
+ return nil unless available?
207
+
208
+ @state ||= build_state(OpenTelemetry.tracer_provider)
209
+ rescue StandardError
210
+ nil
211
+ end
212
+
213
+ def self.build_state(provider)
214
+ meter = meter_for
215
+ State.new(provider, provider.tracer(NAME, Emb::VERSION), histograms_for(meter), counter_for(meter))
216
+ rescue StandardError
217
+ nil
218
+ end
219
+
220
+ def self.meter_for
221
+ return nil unless defined?(OpenTelemetry) && OpenTelemetry.respond_to?(:meter_provider)
222
+
223
+ OpenTelemetry.meter_provider.meter(NAME, version: Emb::VERSION)
224
+ rescue StandardError
225
+ nil
226
+ end
227
+
228
+ def self.histograms_for(meter)
229
+ return nil unless meter
230
+
231
+ HISTOGRAMS.to_h do |name, (unit, description)|
232
+ [name, meter.create_histogram(name, unit: unit, description: description,
233
+ advisory: { explicit_bucket_boundaries: BOUNDARIES })]
234
+ end
235
+ rescue StandardError
236
+ nil
237
+ end
238
+
239
+ def self.counter_for(meter)
240
+ return nil unless meter
241
+
242
+ meter.create_up_down_counter(IN_FLIGHT, unit: '{share}', description: 'Commands currently dispatched.')
243
+ rescue StandardError
244
+ nil
245
+ end
246
+
247
+ def self.metric_attributes(entry)
248
+ attributes = { 'emb.model' => entry[:model], 'emb.mode' => entry[:mode] }
249
+ attributes['emb.format'] = entry[:format].to_s if entry[:format]
250
+ attributes
251
+ end
252
+
253
+ def self.safe
254
+ yield
255
+ rescue StandardError
256
+ nil
257
+ end
258
+
259
+ private_class_method :state, :build_state, :meter_for, :histograms_for,
260
+ :counter_for, :metric_attributes, :around_span, :safe
261
+ end
262
+ end
263
+
264
+ require_relative 'telemetry/deferred'
@@ -58,6 +58,7 @@ module Emb
58
58
  values = rows[offset, texts.size]
59
59
  offset += texts.size
60
60
  loader.call(item, values.size == 1 ? values.first : values)
61
+ Emb::Telemetry::Deferred.resolve(item)
61
62
  end
62
63
  end
63
64
 
@@ -70,6 +71,7 @@ module Emb
70
71
  values = entry_values(results, offset, texts)
71
72
  offset += texts.size
72
73
  loader.call(item, values.size == 1 ? values.first : values)
74
+ Emb::Telemetry::Deferred.resolve(item)
73
75
  end
74
76
  end
75
77
 
@@ -17,7 +17,11 @@ module Emb
17
17
  pairs = reply.is_a?(Hash) ? reply : reply.each_slice(2).to_h
18
18
  shape = pairs.fetch('shape')
19
19
  values = Array(pairs.fetch('values')).map { |v| float_value(v) }
20
- { dtype: pairs.fetch('dtype'), shape: shape, values: values }
20
+ envelope = { dtype: pairs.fetch('dtype'), shape: shape, values: values }
21
+ # A token output's envelope also carries its patch grid; text and pooled
22
+ # image envelopes do not, so the key appears only when the server sent it.
23
+ envelope[:grid] = pairs['grid'] if pairs.key?('grid')
24
+ envelope
21
25
  end
22
26
 
23
27
  # rows reshapes flat values into per-text rows using shape [m, dim].
@@ -26,10 +30,10 @@ module Emb
26
30
  values.each_slice(dim).to_a
27
31
  end
28
32
 
29
- def float_value(v)
30
- Float(v)
33
+ def float_value(value)
34
+ Float(value)
31
35
  rescue ArgumentError, TypeError
32
- raise ArgumentError, "EMB VALUES: unparsable decimal value #{v.inspect} (expected a numeric bulk string)"
36
+ raise ArgumentError, "EMB VALUES: unparsable decimal value #{value.inspect} (expected a numeric bulk string)"
33
37
  end
34
38
  end
35
- end
39
+ end
data/lib/emb.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative 'emb/version'
4
+ require_relative 'emb/telemetry'
4
5
  require_relative 'emb/configuration'
5
6
  require_relative 'emb/errors'
6
7
  require_relative 'emb/commands'
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: emb
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.3.pre6
4
+ version: 0.5.0.pre1
5
5
  platform: ruby
6
6
  authors:
7
7
  - elcuervo
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-15 00:00:00.000000000 Z
11
+ date: 2026-12-01 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: batch-loader
@@ -30,14 +30,14 @@ dependencies:
30
30
  requirements:
31
31
  - - "~>"
32
32
  - !ruby/object:Gem::Version
33
- version: '0.24'
33
+ version: '0.27'
34
34
  type: :runtime
35
35
  prerelease: false
36
36
  version_requirements: !ruby/object:Gem::Requirement
37
37
  requirements:
38
38
  - - "~>"
39
39
  - !ruby/object:Gem::Version
40
- version: '0.24'
40
+ version: '0.27'
41
41
  description:
42
42
  email:
43
43
  - elcuervo@elcuervo.net
@@ -49,15 +49,20 @@ files:
49
49
  - Gemfile
50
50
  - LICENSE
51
51
  - README.md
52
+ - TELEMETRY.md
52
53
  - lib/emb.rb
53
54
  - lib/emb/batch.rb
54
55
  - lib/emb/batch_dispatch.rb
55
56
  - lib/emb/batch_scope.rb
56
57
  - lib/emb/client.rb
58
+ - lib/emb/commands.json
57
59
  - lib/emb/commands.rb
58
60
  - lib/emb/configuration.rb
59
61
  - lib/emb/connection_router.rb
60
62
  - lib/emb/errors.rb
63
+ - lib/emb/image_batch.rb
64
+ - lib/emb/image_command.rb
65
+ - lib/emb/item_shape.rb
61
66
  - lib/emb/job_middleware.rb
62
67
  - lib/emb/middleware.rb
63
68
  - lib/emb/multi.rb
@@ -66,6 +71,8 @@ files:
66
71
  - lib/emb/round_robin_pool.rb
67
72
  - lib/emb/runtime_config.rb
68
73
  - lib/emb/script_reply_decode.rb
74
+ - lib/emb/telemetry.rb
75
+ - lib/emb/telemetry/deferred.rb
69
76
  - lib/emb/values_batch.rb
70
77
  - lib/emb/values_reply.rb
71
78
  - lib/emb/version.rb