emb 0.4.3 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4d58b231af28d6c73775973ffd3a8b458a525d6ec16e6bd857cdcd7eb7739fda
4
- data.tar.gz: f8e5a9fc0e5b6d868c5a1b687f9a76c3bfe15f21eafffeb1879bfe111d595b28
3
+ metadata.gz: 7b4c0996d433c97e3111b91add0af6fe329738e0f4b2f325a6111c86b6822bd3
4
+ data.tar.gz: ed039c262b7ada8fbfb7c7a4cf92c9bf5d918d6731f8d785fdca91eda3daed49
5
5
  SHA512:
6
- metadata.gz: f690bb5e12c38e2620b8ffcae077d9e80cabb6dd6bdc42168ec3e42ad2a81697219f6c69b643556c8663a83f72be0d165db55fbb99eee20bf77255e5f0e482d3
7
- data.tar.gz: a183ce499ae3078bfc187318257042f86d344c2692a9e481131fd516a2292851aeafefb4fbdc041a66915b309e9f19e3fa8c78af05d4c1250080c2e61e284070
6
+ metadata.gz: 25507d1c4460adf72dca1f75627d965314bcb4212e99359bec999a46f5fcbdf8177d07f9c51ba86c399e8712d62e76111a1b24f77fad7e5f6e324a4a1fffcbca
7
+ data.tar.gz: 2371cb697e80e7bfcfed7669ec71980c1c25588cad62021674e81929e205681377018f47af79f3cf85105f455b0164a977fab7eef9d172d2863abfa82ee31594
data/CHANGELOG.md CHANGED
@@ -3,7 +3,7 @@
3
3
  All notable changes to the `emb` gem are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
- ## [0.4.3.pre4] - unreleased
6
+ ## [0.5.0.pre1] - unreleased
7
7
 
8
8
  ### Changed
9
9
 
@@ -12,8 +12,56 @@ All notable changes to the `emb` gem are documented here. The format follows
12
12
  `EMB.MULTI`. A two-model scope runs concurrently even when it fits in a single
13
13
  `batch_size` chunk. `lazy: :multi` still coalesces into serial `EMB`/`EMB.MULTI`.
14
14
 
15
+ ### Fixed
16
+
17
+ - A deferred call and each `client.multi` entry copy their text (and image bytes) when
18
+ the call is made, so mutating or re-tagging the caller's String afterwards can no
19
+ longer change the sent `EMB`/`EMB.MULTI`/`EMB.IMGMULTI` payload.
20
+ - A failed share in a serial batch window no longer raises on a different client's
21
+ loader or drops that client's queued work: the window's other groups dispatch on
22
+ their own, and only the failed slice's items raise that share's `Emb::ServerError`.
23
+ A single-client window where nothing was delivered still fails closed (raise, then `[]`); with several clients, each failed share keeps its own error.
24
+ - Deferral telemetry is keyed by the pending item's identity instead of its content
25
+ hash, so a payload mutation can no longer strand an entry: its span closes and the
26
+ scope's registry drains.
27
+ - Image coercion returns a fresh binary String instead of re-tagging the caller's
28
+ String as `ASCII-8BIT` in place.
29
+ - A deferred single-image call decodes the one keyed map `EMB.IMG` replies with
30
+ instead of raising `ArgumentError`; the share's image count, not its call
31
+ count, selects the reply shape.
32
+ - `Emb.multi` blocks send the group's `OUTPUTS` on `EMB.IMGMULTI`, so `outputs:`
33
+ narrows the projection instead of being dropped.
34
+ - A deferred `image(io)` reads the stream against the scope's remaining
35
+ `max_image_batch_bytes` and raises `Emb::ImageBatchLimitError` while reading,
36
+ instead of materializing an oversized payload first.
37
+
15
38
  ### Added
16
39
 
40
+ - Image calls defer under the configured lazy mode. `Emb[:model].image(bytes)`
41
+ under `lazy: :multi`/`:batch` sends nothing until forced, then coalesces
42
+ compatible calls (same model, format, and `outputs:` projection) into
43
+ `EMB.IMG` shares — serial under `:multi`, concurrent under `:batch` — while
44
+ keeping the eager single-image Hash / multi-image Array shape. Deferred bytes
45
+ are captured at call time and bounded per scope by `batch_size` image payloads
46
+ and the new `max_image_batch_bytes` (32 MiB default, global and per client);
47
+ exceeding either raises `Emb::ImageBatchLimitError` before anything is queued.
48
+ - Image calls join the eager `Emb.multi` / `Client#multi` block exactly like
49
+ text: `m[:model].image(bytes, *more, format:, outputs:)` accepts the same
50
+ arguments as a single call and returns one output-name Hash per image in
51
+ submission order, `nil` for a failed or truncated pair. Compatible calls
52
+ (same format and `outputs:` projection) share one `EMB.IMGMULTI`; a block
53
+ mixing text and images sends `EMB.MULTI` and `EMB.IMGMULTI` and reassembles
54
+ results in submission order. `:values` decoding keeps the pair's `model` tag.
55
+ - Optional OpenTelemetry instrumentation. With `opentelemetry-api` (and
56
+ `opentelemetry-metrics-api` for metrics) installed, the client emits `emb.embed`,
57
+ `emb.batch`, and `emb.share` spans plus `emb.client.*` metrics: per-call latency,
58
+ deferral queue time, batch shape, share durations, observed parallelism, and
59
+ in-flight shares. There is **no new runtime dependency** — the gems are loaded on
60
+ first use, and without them every path returns immediately — and no emb-specific
61
+ configuration; `OTEL_SDK_DISABLED=true` is the off switch. See `TELEMETRY.md`,
62
+ including the view that applies the declared 1 ms–30 s histogram boundaries.
63
+ Measured cost: ~1.1 µs per call with the API loaded and no SDK (~0.1% of a
64
+ single-text round trip), and one branch without it.
17
65
  - `eval`/`evalsha` honor the configured `lazy` mode: deferred under `:multi` and
18
66
  `:batch` (each call is its own share, concurrent in `:batch`) and eager under
19
67
  `false`. `decode:` applies when the value resolves.
data/Gemfile CHANGED
@@ -9,6 +9,13 @@ gem 'redis-client'
9
9
  gem 'rake', require: false
10
10
  gem 'rspec', require: false
11
11
 
12
+ group :development, :test do
13
+ # The telemetry specs assert emitted spans and metrics through the SDK's
14
+ # in-memory exporters. Consumers bring their own SDK; versions live in the lock.
15
+ gem 'opentelemetry-metrics-sdk', require: false
16
+ gem 'opentelemetry-sdk', require: false
17
+ end
18
+
12
19
  # Development-only: the Railtie integration suite boots a real Rails app so the
13
20
  # real middleware-stack objects and boot order are exercised. Rails is never a
14
21
  # runtime dependency of the gem. Select a line with RAILS_VERSION.
data/README.md CHANGED
@@ -187,8 +187,9 @@ Emb.setup(
187
187
  ```
188
188
 
189
189
  See the [redis-client documentation](https://github.com/redis-rb/redis-client) for
190
- all available options. Only `pool`, `lazy`, and `batch_size` are handled by the
191
- gem — everything else passes through to `RedisClient.new`.
190
+ all available options. Only `pool`, `lazy`, `batch_size`, and
191
+ `max_image_batch_bytes` are handled by the gem — everything else passes through
192
+ to `RedisClient.new`.
192
193
 
193
194
  ## Instance-based clients
194
195
 
@@ -395,6 +396,67 @@ client.multi do |m|
395
396
  end
396
397
  ```
397
398
 
399
+ ### Images
400
+
401
+ `Emb[:clip].image(bytes)` embeds one or more raw encoded images (JPEG, PNG, GIF,
402
+ WebP). The bytes go on the wire unchanged as a binary RESP bulk; an IO argument
403
+ is read fully, and URLs are never fetched.
404
+
405
+ ```ruby
406
+ Emb[:clip].image(File.binread("cat.jpg"))
407
+ # => {"embedding" => [0.0123, ...]}
408
+
409
+ Emb[:clip].image(io1, io2) # several images → Array of Hashes
410
+ Emb[:dino].image(bytes, outputs: ["patches"]) # narrow the projection
411
+ Emb[:clip].image(bytes, format: :values) # dtype/shape/values envelope
412
+ ```
413
+
414
+ Each reply is keyed by the model's configured output names; a failed or
415
+ truncated slot is `nil`.
416
+
417
+ Under `lazy: :multi` or `lazy: :batch` an image call defers like an embed:
418
+ creating it sends nothing, forcing it resolves it. Deferred calls coalesce only
419
+ when they share the model, reply format and `outputs:` projection; each
420
+ compatible group is sent as one `EMB.IMG`. Compatible groups are serial under
421
+ `:multi` and concurrent under `:batch`. Deferred mode captures the bytes at call
422
+ time (an IO is read immediately), so mutating the string or closing the IO
423
+ afterwards cannot change the request.
424
+
425
+ Two limits bound one deferred scope, both enforced before a call is queued:
426
+
427
+ - `batch_size` image payloads across the scope (default 512);
428
+ - `max_image_batch_bytes` encoded bytes across the scope (default 32 MiB, the
429
+ server's per-image cap), set globally with
430
+ `Emb.configure { |c| c.max_image_batch_bytes = 64 * 1024 * 1024 }` or per
431
+ client with `Emb.new(max_image_batch_bytes: ...)`.
432
+
433
+ A call that would exceed either raises `Emb::ImageBatchLimitError` naming the
434
+ limit; that image is neither queued nor sent. The bound is released with the
435
+ request/job batch scope, including when the scope raises.
436
+
437
+ ### Multi-model image batches
438
+
439
+ Image calls join the same eager `Emb.multi` block as text. The call is the same
440
+ `image` method, so single and multi sends accept identical options:
441
+
442
+ ```ruby
443
+ Emb.multi do |m|
444
+ m[:clip].image(File.binread("cat.jpg"))
445
+ m[:dino].image(File.binread("cat.jpg"))
446
+ end
447
+ # => [{"embedding" => [...]}, {"embedding" => [...], "patches" => [...]}]
448
+ ```
449
+
450
+ The block sends one `EMB.IMGMULTI` for image calls that share the format and
451
+ `outputs:` projection (separate commands otherwise), and the text `EMB.MULTI`
452
+ when the block also holds text pairs. Results come back in submission order, one
453
+ Hash per image, with `nil` for a failed or truncated pair. Bytes are binary-safe
454
+ and never URL-fetched. `format: :values` addresses each image's envelope and,
455
+ like the server, also carries that pair's `model` tag; `outputs:` is per call.
456
+ Server-side image count and byte caps still apply — a truncated pair comes back
457
+ as `nil`, not an error. Like the text block, `Emb.multi` is always eager, even on
458
+ a `lazy:` client.
459
+
398
460
  ### Script replies
399
461
 
400
462
  `Emb.eval` / `Emb.evalsha` run a Lua script against a model (KEYS = texts,
@@ -440,7 +502,9 @@ Shares fan out across the configured instances (one share per instance when the
440
502
  share count allows) or across the instance's pool connections when a single url is
441
503
  configured. Either mode fans out as soon as a scope resolves into more than one
442
504
  share — a two-model scope runs concurrently even when it fits in one `batch_size`
443
- chunk. Deferred work is powered by the
505
+ chunk. Deferred image calls join the same scope (see [Images](#images)): they
506
+ coalesce per model/format/projection and are bounded by `batch_size` and
507
+ `max_image_batch_bytes`. Deferred work is powered by the
444
508
  [batch-loader](https://github.com/exAspArk/batch-loader) gem:
445
509
 
446
510
  ```ruby
@@ -477,6 +541,13 @@ yields an `Array<Float>`, multiple texts yield `Array<Array<Float>>`. For explic
477
541
  composition that always sends immediately regardless of mode, use `Emb.multi { }`
478
542
  (see [Multi-model queries](#multi-model-queries)).
479
543
 
544
+ A deferred call — and each entry of an `Emb.multi` / `client.multi` block —
545
+ captures its arguments when it is made: the texts, the image bytes (copied to a
546
+ fresh `ASCII-8BIT` String; the caller's object is never re-tagged), the `format`,
547
+ and the `outputs:` projection. Mutating a String after the call therefore cannot
548
+ change what is sent. Identical deferred calls still coalesce into one wire
549
+ payload by design; every caller resolves from that single command.
550
+
480
551
  The batch executes in the current thread's scope; the Rack/ActiveJob middleware
481
552
  clears that scope after every request/job (`Emb::BatchScope`), so deferred work
482
553
  can never accumulate across requests (in eager mode there is nothing to clear).
@@ -497,22 +568,26 @@ prevents a slow server from turning one failed batch into endless duplicate work
497
568
  (retries re-running the whole batch) or growth of the pending set across retries.
498
569
  Pair-level failures the server reports as `null` (MGET semantics) are unaffected.
499
570
 
500
- Under `lazy: :multi` — and a `:batch` scope that resolves to a single share — a failed
501
- batch's items resolve to `[]` afterward. Under `lazy: :batch` with multiple shares a
502
- failure is **isolated per share**: the healthy shares resolve normally and the force does
503
- **not** raise for a sibling's failure, while every item of the failed share raises that
504
- share's `Emb::ServerError` (same message and `cause`) on each use, without re-sending. So a
505
- two-model scope that defers `siglip2` and `hyperclusters` no longer loses the healthy
506
- model's value, and the failed model's value raises instead of silently reading as `[]`.
571
+ A single-client window whose every share fails — the `lazy: :multi` case, and a
572
+ `:batch` scope that resolves to a single share — keeps the fail-closed contract above:
573
+ it raises and its items resolve to `[]` afterward. Every other window isolates failures
574
+ per share: healthy shares resolve normally and the force does **not** raise for a
575
+ sibling's failure, while every item of the failed share raises that share's
576
+ `Emb::ServerError` (same message and `cause`) on each use, without re-sending. That
577
+ holds across clients too: when two clients defer in one window and both commands fail,
578
+ forcing one returns that client's own error, never the other's, and a two-model
579
+ `:batch` scope that defers `siglip2` and `hyperclusters` no longer loses the healthy
580
+ model's value.
507
581
 
508
582
  > **Breaking change (gem ≥ next release):** a failed batch raises `Emb::ServerError`
509
583
  > instead of the raw `RedisClient::*` error. Rescue `Emb::ServerError` and read `cause`
510
584
  > for the original error. Eager `Emb.multi` and the `lazy: false` path are unchanged.
511
585
 
512
- > **Breaking change (gem ≥ next release):** under `lazy: :batch`, a share failure no
513
- > longer fails the force for its siblings and a failed share's items raise
514
- > `Emb::ServerError` on every use instead of resolving to `[]`. The serial (`:multi`,
515
- > single-share) path is unchanged.
586
+ > **Breaking change (gem ≥ next release):** under a deferred mode, a share failure no
587
+ > longer fails the force for its siblings: a failed share's items raise
588
+ > `Emb::ServerError` on every use instead of resolving to `[]`, and only a single-client
589
+ > window where nothing was delivered still raises fail-closed. Concurrent `:batch` share
590
+ > isolation is unchanged.
516
591
 
517
592
  ```ruby
518
593
  vec = Emb[:minilm]["hello"] # use -> Array of Float
@@ -641,6 +716,21 @@ chain when `Sidekiq::Testing` is loaded *before the app finishes booting* (e.g.
641
716
  after the app boots, so require it before your environment to get per-job clearing in
642
717
  fake/inline tests — e.g. `gem "sidekiq", require: ["sidekiq", "sidekiq/testing"]`.
643
718
 
719
+ ## Telemetry (OpenTelemetry)
720
+
721
+ Optional: the gem ships no OpenTelemetry dependency, and there is no emb setting.
722
+ Install the SDK and the client emits `emb.embed`, `emb.batch`, and `emb.share`
723
+ spans plus `emb.client.*` metrics — per-call latency, the `lazy` queue, batch
724
+ shape, and observed parallelism.
725
+
726
+ ```ruby
727
+ gem "opentelemetry-sdk"
728
+ gem "opentelemetry-exporter-otlp"
729
+ ```
730
+
731
+ [TELEMETRY.md](TELEMETRY.md) has the setup, the span and metric reference, and
732
+ Datadog queries. `OTEL_SDK_DISABLED=true` turns it off.
733
+
644
734
  ## Performance
645
735
 
646
736
  ### Eager-burst pipelining (no new API)
@@ -741,5 +831,27 @@ Start the emb server, then run the test suite:
741
831
  bundle exec rake
742
832
  ```
743
833
 
744
- Tests cover all commands: `EMB`, `EMB.MODELS`, `EMB.INFO`, `EMB.HELP`, `PING`,
745
- and `EMB.MULTI`, plus instance-based clients, URL configuration, and connection pooling.
834
+ The server contract (shipped as `lib/emb/commands.json`) has 22 commands:
835
+ `AUTH`, `CLIENT`, `CONFIG`, `EMB`, `EMB.CACHE.FLUSH`, `EMB.EVAL`, `EMB.EVSHA`,
836
+ `EMB.HELP`, `EMB.IMG`, `EMB.IMGMULTI`, `EMB.INFO`, `EMB.MODELS`, `EMB.MULTI`,
837
+ `EMB.READY`, `EMB.SAVE`, `EMB.SCRIPT`, `EMB.STATS`, `HELLO`, `INFO`, `MONITOR`,
838
+ `PING`, `SHUTDOWN`.
839
+
840
+ The suite covers the embedding path — `EMB`, `EMB.MULTI`, `EMB.MODELS`,
841
+ `EMB.INFO`, `EMB.HELP`, and `PING` — plus instance-based clients, URL
842
+ configuration, and connection pooling.
843
+
844
+ ### Command contract
845
+
846
+ The gem ships the server's command contract as `lib/emb/commands.json`. `spec/emb_commands_contract_spec.rb`
847
+ fails when a command name or a keyword the gem sends is missing from that contract, and when the shipped copy
848
+ differs from the repository's `commands.json`. After a server contract change, regenerate the
849
+ repository catalog, then refresh the copy:
850
+
851
+ ```bash
852
+ just commands-gen
853
+ bundle exec rake commands:sync
854
+ ```
855
+
856
+ Those specs stub the connection, so they also run where no server exists:
857
+ `EMB_NO_SERVER=1 bundle exec rspec spec/emb_commands_contract_spec.rb`.
data/TELEMETRY.md ADDED
@@ -0,0 +1,126 @@
1
+ # Telemetry
2
+
3
+ Optional OpenTelemetry spans and metrics for the `emb` client: what a call pays,
4
+ including the `lazy` coalescing queue, and whether a `:batch` scope's shares
5
+ actually ran in parallel.
6
+
7
+ The gem has no runtime dependency on OpenTelemetry and no telemetry setting of its
8
+ own. Install the gems and signals flow; `OTEL_SDK_DISABLED=true` stops them. All
9
+ other configuration is standard `OTEL_*`, owned by your application.
10
+
11
+ ## Enable
12
+
13
+ ```ruby
14
+ # Gemfile — spans
15
+ gem "opentelemetry-sdk" # brings opentelemetry-api
16
+ gem "opentelemetry-exporter-otlp"
17
+
18
+ # ...and metrics (brings opentelemetry-metrics-api)
19
+ gem "opentelemetry-metrics-sdk"
20
+ gem "opentelemetry-exporter-otlp-metrics"
21
+ ```
22
+
23
+ ```ruby
24
+ # config/initializers/emb_telemetry.rb — the app owns the SDK and the exporter.
25
+ require "opentelemetry/sdk"
26
+ require "opentelemetry-metrics-sdk"
27
+ require "opentelemetry/exporter/otlp"
28
+ require "opentelemetry/exporter/otlp_metrics"
29
+
30
+ OpenTelemetry::SDK.configure do |c|
31
+ c.service_name = "my-app"
32
+ c.add_span_processor(
33
+ OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor.new(
34
+ OpenTelemetry::Exporter::OTLP::Exporter.new
35
+ )
36
+ )
37
+ end
38
+
39
+ OpenTelemetry.meter_provider.add_metric_reader(
40
+ OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader.new(
41
+ exporter: OpenTelemetry::Exporter::OTLP::Metrics::MetricsExporter.new,
42
+ export_interval_millis: 15_000
43
+ )
44
+ )
45
+
46
+ # Boundaries per unit: embedding latency is seconds, the share count is a count,
47
+ # and parallelism is a ratio. The metrics SDK does not apply instrument advisories
48
+ # yet, so apply the gem's declared boundaries yourself, before the first call.
49
+ view = OpenTelemetry::SDK::Metrics::Aggregation::ExplicitBucketHistogram
50
+ OpenTelemetry.meter_provider.add_view("emb.client.*", type: :histogram, unit: "s",
51
+ aggregation: view.new(boundaries: Emb::Telemetry::BOUNDARIES))
52
+ OpenTelemetry.meter_provider.add_view("emb.client.*", type: :histogram, unit: "{share}",
53
+ aggregation: view.new(boundaries: Emb::Telemetry::COUNT_BOUNDARIES))
54
+ OpenTelemetry.meter_provider.add_view("emb.client.*", type: :histogram, unit: "1",
55
+ aggregation: view.new(boundaries: Emb::Telemetry::RATIO_BOUNDARIES))
56
+ ```
57
+
58
+ Spans land under the current trace, so a lookup inside a controller or job shows
59
+ the client's contribution to that request.
60
+
61
+ ## Spans
62
+
63
+ ```
64
+ rack.request
65
+ └── emb.batch mode=batch shares=4 texts=48 workers=3
66
+ ├── emb.share model=minilm instance=emb-0.internal:6379
67
+ ├── emb.share model=bge instance=emb-1.internal:6379
68
+ └── emb.share model=minilm instance=emb-0.internal:6379
69
+ ```
70
+
71
+ | Span | One per | Attributes |
72
+ |---|---|---|
73
+ | `emb.embed` | logical call — eager: the command; deferred: the deduped item, from deferral to resolution | `emb.operation`, `emb.model`, `emb.format`, `emb.texts`, `emb.mode`, `emb.dispatched`, `emb.queue` |
74
+ | `emb.batch` | forced batch per client | `emb.mode`, `emb.shares`, `emb.texts`, `emb.workers` |
75
+ | `emb.share` | command actually sent | `emb.model`, `emb.texts`, `emb.instance` |
76
+
77
+ `emb.share` spans are children of their batch and carry real start/end times, so a
78
+ flame graph shows the overlap: that *is* the parallelism. `emb.embed` spans under a
79
+ deferred mode start when the call was deferred, so their duration is what the
80
+ caller waited. An item that resolves without a command — a failed batch's unsent
81
+ remainder — is marked `emb.dispatched=false` rather than reported as a fast
82
+ inference.
83
+
84
+ ## Metrics
85
+
86
+ | Metric | Type | Attributes |
87
+ |---|---|---|
88
+ | `emb.client.embed.duration` | histogram (s) | model, mode, format |
89
+ | `emb.client.queue.duration` | histogram (s) | mode |
90
+ | `emb.client.batch.duration` | histogram (s) | mode |
91
+ | `emb.client.batch.shares` | histogram | mode |
92
+ | `emb.client.batch.parallelism` | histogram | mode |
93
+ | `emb.client.share.duration` | histogram (s) | model, instance |
94
+ | `emb.client.shares.in_flight` | up-down counter | — |
95
+
96
+ `emb.client.queue.duration` ends when the batch starts dispatching, so it measures
97
+ what coalescing held a call before any command was sent. Under `lazy: :multi`, a
98
+ call that then waits behind an earlier share shows that wait in its `emb.embed`
99
+ span, not in the queue metric.
100
+
101
+ `emb.client.batch.parallelism` is the sum of a batch's share durations divided by
102
+ its wall time: `1` means the shares ran one after another, `N` means `N` ran at
103
+ once. Under `lazy: :batch` it should track the number of models (capped by
104
+ `pool × url count`); if it sits near 1 while models are idle, the dispatch stopped
105
+ being concurrent.
106
+
107
+ ## Datadog
108
+
109
+ Point the exporter at the Datadog Agent's OTLP receiver
110
+ (`OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318`) or straight at Datadog's OTLP
111
+ intake.
112
+
113
+ ```
114
+ avg:emb.client.batch.parallelism{*} # parallelism over a batch workload
115
+ p95:emb.client.queue.duration{*} # what coalescing costs
116
+ p95:emb.client.embed.duration{*} by {emb.model} # latency your app pays
117
+ ```
118
+
119
+ ## Limits
120
+
121
+ The client measures the round trip, not the server's compute split. For
122
+ queueing-versus-compute use the server's own OTLP series (`emb.request.duration`,
123
+ `emb.inference.duration`, `emb.dispatch.wait`, `emb.sessions.busy`, joined on
124
+ `model`), and [MONITOR](../docs/commands.md) for per-request detail.
125
+ `emb.client.share.duration` includes network, serialization, and the server's own
126
+ queue.
data/lib/emb/batch.rb CHANGED
@@ -3,10 +3,13 @@
3
3
  require 'batch_loader'
4
4
  require 'redis_client'
5
5
  require_relative 'batch_dispatch'
6
+ require_relative 'image_batch'
7
+ require_relative 'item_shape'
6
8
  require_relative 'values_batch'
7
9
 
8
10
  module Emb
9
11
  extend BatchDispatch
12
+ extend ItemShape
10
13
 
11
14
  BATCH_KEY = :emb
12
15
 
@@ -21,44 +24,60 @@ module Emb
21
24
  # fail-closed rescue/wrap paths treat it as a client error, but stays
22
25
  # distinct so transient_error? does not count it as a transport retry: the
23
26
  # reply shape was wrong on the single send — nothing was re-sent.
24
- ShortReplyError = Class.new(RedisClient::ProtocolError)
27
+ class ShortReplyError < RedisClient::ProtocolError; end
25
28
 
26
29
  BATCH_BLOCK = lambda do |items, loader, _args|
27
- items.group_by(&:first).each do |client, client_items|
30
+ groups = items.group_by(&:first)
31
+ single_client = groups.size == 1
32
+ failures = []
33
+ groups.each do |client, client_items|
28
34
  chunk = client.respond_to?(:batch_size) && client.batch_size ? client.batch_size : Emb.configuration.batch_size
29
- # Script items never coalesce (each call is its own share); split them out
30
- # before packing embeds by model.
31
- embeds, scripts = client_items.partition { |item| !script_item?(item) }
32
-
33
- if client.respond_to?(:parallel_batch?) && client.parallel_batch?
34
- # :batch — one or more plain EMB shares per model plus one share per
35
- # script call, all dispatched concurrently. A lone share stays on the
36
- # forcing thread (no worker spawn).
37
- slices = batch_shares(embeds, scripts, chunk)
38
- if slices.size > 1
39
- dispatch_parallel(client, slices, loader)
40
- else
41
- dispatch_serial(client, slices, loader)
42
- end
43
- else
44
- # :multi — embeds coalesce across models into EMB/EMB.MULTI chunks,
45
- # then scripts are sent one after another.
46
- dispatch_serial(client, pack_slices(embeds, chunk) + scripts.map { |item| [item] }, loader)
47
- end
35
+ # Script items never coalesce (each call is its own share) and image
36
+ # items coalesce only with a compatible call; split both out before
37
+ # packing embeds by model.
38
+ embeds = client_items.select { |item| embed_item?(item) }
39
+ scripts = client_items.select { |item| script_item?(item) }
40
+ images = client_items.select { |item| image_item?(item) }
41
+ parallel = client.respond_to?(:parallel_batch?) && client.parallel_batch?
42
+
43
+ # :batch — one or more plain EMB shares per model, one or more EMB.IMG
44
+ # shares per compatible image group, plus one share per script call, all
45
+ # dispatched concurrently. :multi — embeds coalesce across models into
46
+ # EMB/EMB.MULTI chunks, then image groups and scripts are sent one after
47
+ # another.
48
+ slices = if parallel
49
+ batch_shares(embeds, scripts, images, chunk)
50
+ else
51
+ pack_slices(embeds, chunk) + ImageBatch.shares(images) +
52
+ scripts.map { |item| [item] }
53
+ end
54
+ # A lone share stays on the forcing thread (no worker spawn).
55
+ failures.concat(run_batch(client, slices, loader,
56
+ concurrent: parallel && slices.size > 1,
57
+ single_client: single_client) || [])
48
58
  end
59
+ # A failed share is isolated to its own slice: its items raise the share's
60
+ # error on use (like the parallel path), so no caller sees another share's.
61
+ failures.each { |error, slice, client| fail_share(loader, slice, error, client) }
49
62
  end
50
63
 
64
+ BATCH_PENDING_KEY = [BATCH_BLOCK.source_location, BATCH_KEY].freeze
65
+
51
66
  class << self
52
67
  # BatchDispatch mechanics (pack_slices, dispatch_parallel, resolve_slice,
53
68
  # ...) are internal to BATCH_BLOCK; nothing outside Emb calls them with an
54
69
  # explicit receiver.
55
70
  private(*BatchDispatch.instance_methods(false))
71
+ private(*ItemShape.instance_methods(false))
56
72
 
57
73
  def build_batch_loader(client, model, text, format: :binary)
58
74
  unless %i[binary values].include?(format)
59
75
  raise ArgumentError, "unknown format #{format.inspect} (expected :binary or :values)"
60
76
  end
61
77
 
78
+ # Copy at collection: the caller may mutate or re-tag its String after
79
+ # deferring, and the item is also batch-loader's dedupe key.
80
+ text = text.is_a?(Array) ? text.map(&:dup) : text.dup
62
81
  # default_value []: an item whose batch failed (serial path, or a local
63
82
  # error) resolves to an empty vector collection instead of nil, so
64
83
  # resolver methods like `loader.sum` do not blow up with
@@ -66,7 +85,24 @@ module Emb
66
85
  # instead (raises on use).
67
86
  # Items carry [client, model, text, format] so the dispatch knows how to
68
87
  # shape and parse the reply.
69
- BatchLoader.for([client, model, text, format]).batch(default_value: [], key: BATCH_KEY, &BATCH_BLOCK)
88
+ item = [client, model, text, format]
89
+ loader = BatchLoader.for(item).batch(default_value: [], key: BATCH_KEY, &BATCH_BLOCK)
90
+ # Telemetry keys its deferral clock by this item (the batch-loader dedupe
91
+ # key); it must never be stored inside the tuple, which would make every
92
+ # call unique and defeat coalescing. Recorded once the item is pending, so
93
+ # a coalesced duplicate records against the instance the block resolves.
94
+ Telemetry::Deferred.record(
95
+ item, Telemetry.entry_for(client, operation: 'embed', model: model, texts: Array(text).size, format: format)
96
+ )
97
+ loader
98
+ end
99
+
100
+ # Deferred image calls join the same batch scope as embeds and scripts, so
101
+ # forcing any of them resolves all. Bounds (batch_size images and
102
+ # max_image_batch_bytes encoded bytes across the pending scope) are
103
+ # enforced before the item is queued; see ImageBatch.
104
+ def build_image_loader(client, model, images, format: :binary, names: [])
105
+ ImageBatch.build(client, model, images, format: format, names: names)
70
106
  end
71
107
 
72
108
  # Scripts join the same batch scope as embeds (same BATCH_KEY) so forcing
@@ -74,17 +110,57 @@ module Emb
74
110
  # to nil. The item carries the prebuilt EMB.EVAL/EMB.EVSHA argv and the
75
111
  # normalized decode for resolve_slice.
76
112
  def build_script_loader(client, argv, decode)
77
- BatchLoader.for([client, SCRIPT_ITEM, argv, decode]).batch(default_value: nil, key: BATCH_KEY, &BATCH_BLOCK)
113
+ item = [client, SCRIPT_ITEM, argv, decode]
114
+ loader = BatchLoader.for(item).batch(default_value: nil, key: BATCH_KEY, &BATCH_BLOCK)
115
+ Telemetry::Deferred.record(
116
+ item, Telemetry.entry_for(client, operation: 'script', model: argv[1], texts: argv[3].to_i, format: nil)
117
+ )
118
+ loader
119
+ end
120
+
121
+ # Forced batch: one emitting wrapper around either dispatch path, so the
122
+ # batch's shape and wall time are recorded once, even when it raises.
123
+ # `single_client` marks a window with nothing else to deliver; the serial
124
+ # dispatcher raises an all-failed group from inside this span.
125
+ def run_batch(client, slices, loader, concurrent:, single_client: false)
126
+ # Queue ends when dispatch starts, on the forcing thread: the deferral
127
+ # registry is per-thread, so workers must never read or write it. A
128
+ # serial batch's later shares include their wait for earlier ones here.
129
+ slices.each { |slice| Telemetry::Deferred.dispatched(slice) }
130
+ texts = slices.sum { |slice| slice.sum { |item| item_text_count(item) } }
131
+ workers = concurrent ? [slices.size, worker_capacity(client)].min : 1
132
+ Telemetry.batch(mode: Telemetry.mode_for(client), shares: slices.size, texts: texts,
133
+ workers: workers) do |durations|
134
+ if concurrent
135
+ dispatch_parallel(client, slices, loader, durations)
136
+ else
137
+ dispatch_serial(client, slices, loader, durations, single_client: single_client)
138
+ end
139
+ end
140
+ end
141
+
142
+ # Nothing in a single-client window was delivered: keep the fail-closed
143
+ # contract.
144
+ def fail_closed(failures)
145
+ first = nil
146
+ failures.each do |error, slice, client|
147
+ wrapped = batch_error(error, slice: slice, budget: retry_budget(client))
148
+ first ||= wrapped
149
+ slice.each { |item| Telemetry::Deferred.resolve(item, error: wrapped) }
150
+ end
151
+ clear_batch_pending!
152
+ raise first
78
153
  end
79
154
 
80
155
  # Removes every pending item of the batch scope. batch-loader prunes
81
156
  # pending items only after a successful batch block, so failed batches
82
157
  # would otherwise stay queued: retries would re-run the whole batch and
83
158
  # stale items would be re-sent by later batches in the same scope. Guarded
84
- # for a nil executor (no batch scope).
159
+ # for a nil executor (no batch scope). Deferrals that never reached a
160
+ # command are flushed here so they are reported as not dispatched.
85
161
  def clear_batch_pending!
86
- key = [BATCH_BLOCK.source_location, BATCH_KEY]
87
- BatchLoader::Executor.current&.items_by_block&.delete(key)
162
+ BatchLoader::Executor.current&.items_by_block&.delete(BATCH_PENDING_KEY)
163
+ Telemetry::Deferred.flush
88
164
  end
89
165
 
90
166
  # Builds the Emb::ServerError for a failed share, carrying the models/texts/
@@ -144,6 +220,7 @@ module Emb
144
220
  (error.is_a?(RedisClient::ProtocolError) && !error.is_a?(ShortReplyError))
145
221
  end
146
222
 
147
- private :clear_batch_pending!, :batch_error, :with_cause, :retry_budget, :transient_error?
223
+ private :fail_closed, :clear_batch_pending!, :batch_error, :with_cause, :retry_budget,
224
+ :transient_error?
148
225
  end
149
226
  end