emb 0.4.3.pre3 → 0.4.3.pre5
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 +4 -4
- data/CHANGELOG.md +30 -0
- data/README.md +47 -10
- data/lib/emb/batch.rb +62 -36
- data/lib/emb/batch_dispatch.rb +111 -21
- data/lib/emb/commands.rb +16 -30
- data/lib/emb/script_reply_decode.rb +35 -5
- metadata +3 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 4c87e29ea90a5297b17e9e6b725cb6b3a5a1239d13c2bdbf580193ef7de09bc0
|
|
4
|
+
data.tar.gz: ab58a3838ca79ff057b475993c77255aabde8e6f262ac9499b43eeeeea134dc7
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: e6d4ee4f26779118fc8e722006aa7620e753a9d20b5e912c780a82c2d8efd90392fbfccdf94a99bd6b5a228736b8dde97abc2572ead4bdb4835589c5b660c4af
|
|
7
|
+
data.tar.gz: c73c2c1e63a2986133b104ff937186bb24f7a1af5c95b1c2d71be75059c9a8cacee7c5189fe596c662c8909cfdd5b1d78eba133ae6b8afa3f18bf3678c9d81b4
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to the `emb` gem are documented here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
5
|
+
|
|
6
|
+
## [0.4.3.pre4] - unreleased
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
|
|
10
|
+
- `lazy: :batch` now splits a resolving scope into one plain `EMB <model> <text>...`
|
|
11
|
+
share per model and dispatches every share concurrently; it never sends
|
|
12
|
+
`EMB.MULTI`. A two-model scope runs concurrently even when it fits in a single
|
|
13
|
+
`batch_size` chunk. `lazy: :multi` still coalesces into serial `EMB`/`EMB.MULTI`.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- `eval`/`evalsha` honor the configured `lazy` mode: deferred under `:multi` and
|
|
18
|
+
`:batch` (each call is its own share, concurrent in `:batch`) and eager under
|
|
19
|
+
`false`. `decode:` applies when the value resolves.
|
|
20
|
+
|
|
21
|
+
### Breaking
|
|
22
|
+
|
|
23
|
+
- Under `lazy: :batch`, a share that fails terminally no longer fails the force for
|
|
24
|
+
its sibling shares, and its items raise that share's `Emb::ServerError` on every
|
|
25
|
+
use instead of resolving to `[]`. Healthy shares in the same scope resolve
|
|
26
|
+
normally. The serial (`:multi`, single-share) path is unchanged.
|
|
27
|
+
- Under a deferred mode (`lazy: :multi` or `:batch`), `eval`/`evalsha` return a
|
|
28
|
+
lazy value instead of sending immediately. Force the value (or use an eager
|
|
29
|
+
client) to get the parsed reply. The explicit `Emb.multi { }` block API is
|
|
30
|
+
unaffected.
|
data/README.md
CHANGED
|
@@ -427,10 +427,20 @@ actually a float vector / hash at the decodable position, raises
|
|
|
427
427
|
|
|
428
428
|
### Lazy batching
|
|
429
429
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
430
|
+
`lazy` has three modes. `false` (the default) is eager: one `EMB` per call. `:multi`
|
|
431
|
+
defers, coalesces a scope into one `EMB` (single-model) or one `EMB.MULTI`
|
|
432
|
+
(mixed-model), and sends those chunks **serially**. `:batch` also defers but never
|
|
433
|
+
sends `EMB.MULTI`: a resolving scope is split into one plain `EMB <model> <text>...`
|
|
434
|
+
share per model (chunked by `batch_size`), and every share — including **each
|
|
435
|
+
deferred `eval`/`evalsha` call** — is dispatched concurrently, so a batch whose
|
|
436
|
+
pieces take 60ms and 10ms completes in roughly the slowest share (~60ms) instead of
|
|
437
|
+
the sum (~70ms).
|
|
438
|
+
|
|
439
|
+
Shares fan out across the configured instances (one share per instance when the
|
|
440
|
+
share count allows) or across the instance's pool connections when a single url is
|
|
441
|
+
configured. Either mode fans out as soon as a scope resolves into more than one
|
|
442
|
+
share — a two-model scope runs concurrently even when it fits in one `batch_size`
|
|
443
|
+
chunk. Deferred work is powered by the
|
|
434
444
|
[batch-loader](https://github.com/exAspArk/batch-loader) gem:
|
|
435
445
|
|
|
436
446
|
```ruby
|
|
@@ -443,13 +453,25 @@ l1 = Emb[:minilm]["hello"]
|
|
|
443
453
|
l2 = Emb[:minilm]["world"]
|
|
444
454
|
l3 = Emb[:bge]["bonjour"]
|
|
445
455
|
|
|
446
|
-
# ...then consume them.
|
|
447
|
-
#
|
|
456
|
+
# ...then consume them. :multi sends ONE EMB (single-model scope) or ONE
|
|
457
|
+
# EMB.MULTI (mixed-model scope) serially; :batch sends TWO concurrent plain EMB
|
|
458
|
+
# commands (one per model) instead.
|
|
448
459
|
l1.sum # => 12.345
|
|
449
460
|
l2.sum # => -0.678
|
|
450
461
|
l3.sum # => 3.141
|
|
451
462
|
```
|
|
452
463
|
|
|
464
|
+
`eval` and `evalsha` honor the same mode: eager under `false`, deferred under
|
|
465
|
+
`:multi` (sent one after another after the coalesced embeds) and `:batch` (each
|
|
466
|
+
call is its own share, dispatched alongside the `EMB` shares). `decode:` applies
|
|
467
|
+
when the value resolves, with the same results and errors as the eager path.
|
|
468
|
+
|
|
469
|
+
> **Breaking change (gem ≥ next release):** under a deferred mode `eval`/`evalsha`
|
|
470
|
+
> return a lazy value instead of sending immediately, so callers that set
|
|
471
|
+
> `lazy: :multi`/`:batch` and expect a plain Hash/Array/String back at call time
|
|
472
|
+
> must force that value (or use an eager client). The explicit `Emb.multi { }`
|
|
473
|
+
> block API is unaffected.
|
|
474
|
+
|
|
453
475
|
Each lazy value materializes to the same shape as the eager API: a single text
|
|
454
476
|
yields an `Array<Float>`, multiple texts yield `Array<Array<Float>>`. For explicit
|
|
455
477
|
composition that always sends immediately regardless of mode, use `Emb.multi { }`
|
|
@@ -463,7 +485,7 @@ can never accumulate across requests (in eager mode there is nothing to clear).
|
|
|
463
485
|
`:batch` mode a share failure after pre-send retries are exhausted — the batch raises
|
|
464
486
|
**`Emb::ServerError`** to the code that first used it, and every deferred item of that
|
|
465
487
|
batch is removed from the scope — retrying (or using other items of the failed batch)
|
|
466
|
-
**does not re-send the batch
|
|
488
|
+
**does not re-send the batch**. The error's `cause` is the
|
|
467
489
|
underlying redis error (`RedisClient::ReadTimeoutError`, `RedisClient::CommandError`, ...)
|
|
468
490
|
and its message includes the model(s), text count, and attempt count. Transient failures
|
|
469
491
|
(timeout, connection error, protocol error) re-send up to `reconnect_attempts` extra
|
|
@@ -475,10 +497,23 @@ prevents a slow server from turning one failed batch into endless duplicate work
|
|
|
475
497
|
(retries re-running the whole batch) or growth of the pending set across retries.
|
|
476
498
|
Pair-level failures the server reports as `null` (MGET semantics) are unaffected.
|
|
477
499
|
|
|
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 `[]`.
|
|
507
|
+
|
|
478
508
|
> **Breaking change (gem ≥ next release):** a failed batch raises `Emb::ServerError`
|
|
479
509
|
> instead of the raw `RedisClient::*` error. Rescue `Emb::ServerError` and read `cause`
|
|
480
510
|
> for the original error. Eager `Emb.multi` and the `lazy: false` path are unchanged.
|
|
481
511
|
|
|
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.
|
|
516
|
+
|
|
482
517
|
```ruby
|
|
483
518
|
vec = Emb[:minilm]["hello"] # use -> Array of Float
|
|
484
519
|
vecs = Emb[:minilm]["hello", "world"] # use -> Array of Array of Float
|
|
@@ -517,9 +552,11 @@ Emb.new(url: "redis://localhost:6379", lazy: :batch)
|
|
|
517
552
|
```
|
|
518
553
|
|
|
519
554
|
Under `lazy: :multi`, `Emb[:minilm]["hello"]` returns a lazy embedding that sends
|
|
520
|
-
`EMB` on first use (serial chunks; `EMB.MULTI` only for mixed-model scopes).
|
|
521
|
-
|
|
522
|
-
|
|
555
|
+
`EMB` on first use (serial chunks; `EMB.MULTI` only for mixed-model scopes).
|
|
556
|
+
Under `lazy: :batch`, a resolving scope is split into one plain `EMB` per model plus
|
|
557
|
+
one share per deferred script call, and every share executes concurrently —
|
|
558
|
+
`EMB.MULTI` is never sent; with multiple `url`s the shares fan out across instances.
|
|
559
|
+
The default is eager (`lazy: false`). `Emb.multi` remains the explicit, eager,
|
|
523
560
|
deterministic composition API in every mode.
|
|
524
561
|
|
|
525
562
|
### Clearing the cache per request
|
data/lib/emb/batch.rb
CHANGED
|
@@ -10,6 +10,12 @@ module Emb
|
|
|
10
10
|
|
|
11
11
|
BATCH_KEY = :emb
|
|
12
12
|
|
|
13
|
+
# Identity sentinel in slot 1 of a script batch item
|
|
14
|
+
# ([client, SCRIPT_ITEM, argv, decode]); embed items are
|
|
15
|
+
# [client, model, text, format]. A unique object matched with #equal? cannot
|
|
16
|
+
# collide with a model name.
|
|
17
|
+
SCRIPT_ITEM = Object.new
|
|
18
|
+
|
|
13
19
|
# Raised by resolve_slice when the server reply carries fewer entries than
|
|
14
20
|
# the slice's texts. Subclasses RedisClient::ProtocolError so the existing
|
|
15
21
|
# fail-closed rescue/wrap paths treat it as a client error, but stays
|
|
@@ -20,22 +26,24 @@ module Emb
|
|
|
20
26
|
BATCH_BLOCK = lambda do |items, loader, _args|
|
|
21
27
|
items.group_by(&:first).each do |client, client_items|
|
|
22
28
|
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) }
|
|
23
32
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
rescue RedisClient::Error => e
|
|
34
|
-
fail_batch!(e, slice: slice, budget: retry_budget(client))
|
|
35
|
-
rescue StandardError
|
|
36
|
-
clear_batch_pending!
|
|
37
|
-
raise
|
|
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)
|
|
38
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)
|
|
39
47
|
end
|
|
40
48
|
end
|
|
41
49
|
end
|
|
@@ -51,14 +59,24 @@ module Emb
|
|
|
51
59
|
raise ArgumentError, "unknown format #{format.inspect} (expected :binary or :values)"
|
|
52
60
|
end
|
|
53
61
|
|
|
54
|
-
# default_value []: an item whose batch failed (
|
|
55
|
-
# an empty vector collection instead of nil, so
|
|
56
|
-
# `loader.sum` do not blow up with
|
|
62
|
+
# default_value []: an item whose batch failed (serial path, or a local
|
|
63
|
+
# error) resolves to an empty vector collection instead of nil, so
|
|
64
|
+
# resolver methods like `loader.sum` do not blow up with
|
|
65
|
+
# NoMethodError-on-nil. Parallel redis failures get a FailedShare poison
|
|
66
|
+
# instead (raises on use).
|
|
57
67
|
# Items carry [client, model, text, format] so the dispatch knows how to
|
|
58
68
|
# shape and parse the reply.
|
|
59
69
|
BatchLoader.for([client, model, text, format]).batch(default_value: [], key: BATCH_KEY, &BATCH_BLOCK)
|
|
60
70
|
end
|
|
61
71
|
|
|
72
|
+
# Scripts join the same batch scope as embeds (same BATCH_KEY) so forcing
|
|
73
|
+
# either resolves both. default_value nil (not []): a failed script resolves
|
|
74
|
+
# to nil. The item carries the prebuilt EMB.EVAL/EMB.EVSHA argv and the
|
|
75
|
+
# normalized decode for resolve_slice.
|
|
76
|
+
def build_script_loader(client, argv, decode)
|
|
77
|
+
BatchLoader.for([client, SCRIPT_ITEM, argv, decode]).batch(default_value: nil, key: BATCH_KEY, &BATCH_BLOCK)
|
|
78
|
+
end
|
|
79
|
+
|
|
62
80
|
# Removes every pending item of the batch scope. batch-loader prunes
|
|
63
81
|
# pending items only after a successful batch block, so failed batches
|
|
64
82
|
# would otherwise stay queued: retries would re-run the whole batch and
|
|
@@ -69,28 +87,36 @@ module Emb
|
|
|
69
87
|
BatchLoader::Executor.current&.items_by_block&.delete(key)
|
|
70
88
|
end
|
|
71
89
|
|
|
72
|
-
#
|
|
73
|
-
#
|
|
74
|
-
#
|
|
75
|
-
#
|
|
76
|
-
#
|
|
77
|
-
#
|
|
78
|
-
#
|
|
79
|
-
#
|
|
80
|
-
#
|
|
81
|
-
#
|
|
82
|
-
|
|
83
|
-
def fail_batch!(error, slice:, budget:)
|
|
84
|
-
clear_batch_pending!
|
|
90
|
+
# Builds the Emb::ServerError for a failed share, carrying the models/texts/
|
|
91
|
+
# attempts context and the original redis error as `cause`. Does not clear
|
|
92
|
+
# the pending set or raise: the serial path re-raises it immediately, while
|
|
93
|
+
# the parallel path hands it to a FailedShare so every item of the failed
|
|
94
|
+
# share raises it on use. `attempts` counts the error's retry class:
|
|
95
|
+
# connection/protocol errors (the ones redis-client actually re-sends)
|
|
96
|
+
# report `budget + 1`; operation errors and read timeouts (never re-sent — a
|
|
97
|
+
# timeout may already have executed server work) report 1. A pre-send
|
|
98
|
+
# connection refusal is retried across instances by the connection router
|
|
99
|
+
# before it can reach here as a terminal error.
|
|
100
|
+
def batch_error(error, slice:, budget:)
|
|
85
101
|
attempts = transient_error?(error) ? budget + 1 : 1
|
|
86
|
-
models = slice.map { |
|
|
87
|
-
texts = slice.sum { |
|
|
102
|
+
models = slice.map { |item| item_model(item) }.uniq.join(', ')
|
|
103
|
+
texts = slice.sum { |item| item_text_count(item) }
|
|
88
104
|
message = "batch failed after #{attempts} attempt(s) " \
|
|
89
105
|
"(models: #{models}, #{texts} text(s)) #{error.class}: #{error.message}"
|
|
106
|
+
with_cause(error, ServerError.new(message, attempts: attempts))
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Attaches `error` as the cause of `wrapped` from a non-rescue context (the
|
|
110
|
+
# parallel path resolves on the forcing thread after a worker captured the
|
|
111
|
+
# error): raise the original, build the wrapper inside that rescue so Ruby
|
|
112
|
+
# records it as cause, then rescue the wrapper to return it.
|
|
113
|
+
def with_cause(error, wrapped)
|
|
114
|
+
raise error
|
|
115
|
+
rescue StandardError
|
|
90
116
|
begin
|
|
91
|
-
raise
|
|
92
|
-
rescue
|
|
93
|
-
|
|
117
|
+
raise wrapped
|
|
118
|
+
rescue ServerError => e
|
|
119
|
+
e
|
|
94
120
|
end
|
|
95
121
|
end
|
|
96
122
|
|
|
@@ -118,6 +144,6 @@ module Emb
|
|
|
118
144
|
(error.is_a?(RedisClient::ProtocolError) && !error.is_a?(ShortReplyError))
|
|
119
145
|
end
|
|
120
146
|
|
|
121
|
-
private :clear_batch_pending!, :
|
|
147
|
+
private :clear_batch_pending!, :batch_error, :with_cause, :retry_budget, :transient_error?
|
|
122
148
|
end
|
|
123
149
|
end
|
data/lib/emb/batch_dispatch.rb
CHANGED
|
@@ -1,16 +1,80 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require_relative 'script_reply_decode'
|
|
4
|
+
|
|
3
5
|
module Emb
|
|
6
|
+
# Poison value for an item whose share failed terminally under parallel
|
|
7
|
+
# dispatch: any use raises the share's Emb::ServerError. BasicObject so only
|
|
8
|
+
# method_missing is reachable — batch-loader's __replace_with! calls
|
|
9
|
+
# `value.methods` on first use, and Array()/respond_to? raise too.
|
|
10
|
+
#
|
|
11
|
+
# No respond_to_missing?: BasicObject has no respond_to?, so it would never
|
|
12
|
+
# be called (dead code).
|
|
13
|
+
# rubocop:disable Style/MissingRespondToMissing
|
|
14
|
+
class FailedShare < BasicObject
|
|
15
|
+
def initialize(error)
|
|
16
|
+
@error = error
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def method_missing(*)
|
|
20
|
+
::Kernel.raise(@error)
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
# rubocop:enable Style/MissingRespondToMissing
|
|
24
|
+
|
|
4
25
|
# Share-dispatch mechanics for the deferred batch path: EMB/MULTI wire
|
|
5
26
|
# shaping, per-slice result mapping, and the bounded concurrent fan-out used
|
|
6
27
|
# by `lazy: :batch`. Extended into Emb by batch.rb.
|
|
7
28
|
module BatchDispatch
|
|
29
|
+
# Script batch items are [client, SCRIPT_ITEM, argv, decode]; embed items are
|
|
30
|
+
# [client, model, text, format]. argv is the fully built EMB.EVAL/EMB.EVSHA
|
|
31
|
+
# command and argv[3] its text count.
|
|
32
|
+
def script_item?(item)
|
|
33
|
+
item[1].equal?(SCRIPT_ITEM)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def item_model(item)
|
|
37
|
+
script_item?(item) ? item[2][1] : item[1]
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def item_text_count(item)
|
|
41
|
+
script_item?(item) ? item[2][3].to_i : Array(item[2]).size
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# :batch shares: per-model chunked EMB shares plus one share per script
|
|
45
|
+
# call. group_by preserves first-deferral order of the models.
|
|
46
|
+
def batch_shares(embeds, scripts, chunk)
|
|
47
|
+
slices = []
|
|
48
|
+
embeds.group_by { |item| item[1] }.each_value { |group| slices.concat(pack_slices(group, chunk)) }
|
|
49
|
+
scripts.each { |item| slices << [item] }
|
|
50
|
+
slices
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Serial dispatch: one share in flight at a time. Redis errors fail closed
|
|
54
|
+
# with context; anything else is a local bug and is re-raised unchanged
|
|
55
|
+
# after the pending set is dropped.
|
|
56
|
+
def dispatch_serial(client, slices, loader)
|
|
57
|
+
slices.each do |slice|
|
|
58
|
+
resolve_slice(loader, slice, dispatch_slice(client, slice))
|
|
59
|
+
rescue RedisClient::Error => e
|
|
60
|
+
clear_batch_pending!
|
|
61
|
+
raise batch_error(e, slice: slice, budget: retry_budget(client))
|
|
62
|
+
rescue StandardError
|
|
63
|
+
clear_batch_pending!
|
|
64
|
+
raise
|
|
65
|
+
end
|
|
66
|
+
end
|
|
67
|
+
|
|
8
68
|
# Sends one chunk share and returns the raw reply entries. Single-model
|
|
9
69
|
# shares use plain `EMB <model> <text>...` (one inference, model once);
|
|
10
70
|
# mixed-model shares keep EMB.MULTI per-pair nil semantics. Errors after
|
|
11
71
|
# the command may have been sent are terminal and propagate so the forcing
|
|
12
72
|
# thread can fail closed.
|
|
13
73
|
def dispatch_slice(client, slice)
|
|
74
|
+
# Scripts keep their prebuilt argv and their raw reply (a Hash reply must
|
|
75
|
+
# not be Array()-wrapped into pairs).
|
|
76
|
+
return client.send_command(*slice.first[2]) if script_item?(slice.first)
|
|
77
|
+
|
|
14
78
|
models = slice.map { |_, model, _, _| model }.uniq
|
|
15
79
|
args = models.size == 1 ? same_model_args(slice, models.first) : mixed_model_args(slice)
|
|
16
80
|
Array(client.send_command(*args))
|
|
@@ -51,6 +115,8 @@ module Emb
|
|
|
51
115
|
# from a client-raised ProtocolError so it is not counted as a transport
|
|
52
116
|
# retry).
|
|
53
117
|
def resolve_slice(loader, slice, results)
|
|
118
|
+
return resolve_script_slice(loader, slice.first, results) if script_item?(slice.first)
|
|
119
|
+
|
|
54
120
|
if slice_format(slice) == :values
|
|
55
121
|
return ValuesBatch.resolve(loader, slice, results)
|
|
56
122
|
end
|
|
@@ -77,6 +143,13 @@ module Emb
|
|
|
77
143
|
values.size == 1 ? values.first : values
|
|
78
144
|
end
|
|
79
145
|
|
|
146
|
+
# A script call is always a singleton slice; its reply is parsed on the
|
|
147
|
+
# forcing thread. multi: comes from the argv text count (argv[3]).
|
|
148
|
+
def resolve_script_slice(loader, item, results)
|
|
149
|
+
multi = item[2][3].to_i > 1
|
|
150
|
+
loader.call(item, ScriptReplyDecode.parse_script_reply(results, multi: multi, decode: item[3]))
|
|
151
|
+
end
|
|
152
|
+
|
|
80
153
|
# The worker captures failures as outcomes; only the forcing thread
|
|
81
154
|
# resolves loaders (see resolve_slice).
|
|
82
155
|
def dispatch_share(client, slice)
|
|
@@ -86,7 +159,8 @@ module Emb
|
|
|
86
159
|
end
|
|
87
160
|
|
|
88
161
|
# Dispatches all shares concurrently over at most the client's connection
|
|
89
|
-
# capacity workers, then
|
|
162
|
+
# capacity workers, then resolves the outcomes (isolating a failed share's
|
|
163
|
+
# error to its own items).
|
|
90
164
|
def dispatch_parallel(client, slices, loader)
|
|
91
165
|
workers = slices.size.clamp(1, worker_capacity(client))
|
|
92
166
|
queue = share_queue(slices, workers)
|
|
@@ -119,32 +193,48 @@ module Emb
|
|
|
119
193
|
end.each(&:join)
|
|
120
194
|
end
|
|
121
195
|
|
|
122
|
-
# Redis errors
|
|
123
|
-
#
|
|
196
|
+
# Redis errors are isolated to their own share: every item of the failed
|
|
197
|
+
# share resolves to a FailedShare that re-raises that share's
|
|
198
|
+
# Emb::ServerError on use (no re-send), while healthy shares resolve
|
|
199
|
+
# normally and the force never raises for a sibling. batch-loader then
|
|
200
|
+
# prunes the pending items itself once the block returns. Non-redis errors
|
|
201
|
+
# are local bugs: resolve the other shares, then clear the pending set and
|
|
202
|
+
# re-raise the first one.
|
|
124
203
|
def resolve_outcomes(client, outcomes, loader)
|
|
125
|
-
first_error, failed_slice = collect_outcomes(outcomes, loader)
|
|
126
|
-
return unless first_error
|
|
127
|
-
|
|
128
|
-
raise first_error unless first_error.is_a?(RedisClient::Error)
|
|
129
|
-
|
|
130
|
-
fail_batch!(first_error, slice: failed_slice, budget: retry_budget(client))
|
|
131
|
-
rescue StandardError
|
|
132
|
-
clear_batch_pending!
|
|
133
|
-
raise
|
|
134
|
-
end
|
|
135
|
-
|
|
136
|
-
def collect_outcomes(outcomes, loader)
|
|
137
204
|
first_error = nil
|
|
138
|
-
failed_slice = nil
|
|
139
205
|
outcomes.each do |status, slice, result|
|
|
140
|
-
|
|
141
|
-
|
|
206
|
+
error = outcome_error(loader, status, slice, result)
|
|
207
|
+
next unless error
|
|
208
|
+
|
|
209
|
+
if error.is_a?(RedisClient::Error)
|
|
210
|
+
fail_share(loader, slice, error, client)
|
|
142
211
|
else
|
|
143
|
-
first_error ||=
|
|
144
|
-
failed_slice ||= slice
|
|
212
|
+
first_error ||= error
|
|
145
213
|
end
|
|
146
214
|
end
|
|
147
|
-
|
|
215
|
+
return unless first_error
|
|
216
|
+
|
|
217
|
+
clear_batch_pending!
|
|
218
|
+
raise first_error
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# The error an outcome carries: the worker's captured error, or a
|
|
222
|
+
# resolve_slice failure (e.g. ShortReplyError) against an :ok reply.
|
|
223
|
+
def outcome_error(loader, status, slice, result)
|
|
224
|
+
return result unless status == :ok
|
|
225
|
+
|
|
226
|
+
resolve_slice(loader, slice, result)
|
|
227
|
+
nil
|
|
228
|
+
rescue StandardError => e
|
|
229
|
+
e
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# Resolves every item of a failed share to a poison value that raises the
|
|
233
|
+
# share's Emb::ServerError on use. Building the error once keeps its
|
|
234
|
+
# message/context and cause identical for all of the share's items.
|
|
235
|
+
def fail_share(loader, slice, error, client)
|
|
236
|
+
poison = batch_error(error, slice: slice, budget: retry_budget(client))
|
|
237
|
+
slice.each { |item| loader.call(item, FailedShare.new(poison)) }
|
|
148
238
|
end
|
|
149
239
|
|
|
150
240
|
# Packs items into shares by accumulated text count so one command stays
|
data/lib/emb/commands.rb
CHANGED
|
@@ -28,19 +28,18 @@ module Emb
|
|
|
28
28
|
# replies (flat field/value pair arrays under RESP2) become Ruby Hashes,
|
|
29
29
|
# nested values recurse. decode: opt-in float decoding — see
|
|
30
30
|
# parse_script_reply (decode: :f32 or decode: {field => :f32}).
|
|
31
|
+
#
|
|
32
|
+
# Honors the client's lazy mode: eager under false, deferred under :multi
|
|
33
|
+
# and :batch (see Emb::Commands#run_script_command).
|
|
31
34
|
def eval(model, script, texts, args = [], decode: nil)
|
|
32
35
|
texts = Array(texts)
|
|
33
|
-
|
|
34
|
-
reply = send_command('EMB.EVAL', model.to_s, script, texts.size, *texts.map(&:to_s), *args.map(&:to_s))
|
|
35
|
-
parse_script_reply(reply, multi: texts.size > 1, decode: schema)
|
|
36
|
+
run_script_command(script_argv('EMB.EVAL', model, script, texts, args), decode)
|
|
36
37
|
end
|
|
37
38
|
|
|
38
39
|
# Evaluate a previously loaded script by SHA1 (EMB.EVSHA). See #eval.
|
|
39
40
|
def evalsha(model, sha, texts, args = [], decode: nil)
|
|
40
41
|
texts = Array(texts)
|
|
41
|
-
|
|
42
|
-
reply = send_command('EMB.EVSHA', model.to_s, sha, texts.size, *texts.map(&:to_s), *args.map(&:to_s))
|
|
43
|
-
parse_script_reply(reply, multi: texts.size > 1, decode: schema)
|
|
42
|
+
run_script_command(script_argv('EMB.EVSHA', model, sha, texts, args), decode)
|
|
44
43
|
end
|
|
45
44
|
|
|
46
45
|
# EMB.SCRIPT subcommands: a small command object so the surface reads
|
|
@@ -89,33 +88,20 @@ module Emb
|
|
|
89
88
|
|
|
90
89
|
private
|
|
91
90
|
|
|
92
|
-
#
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
# indistinguishable from two-field hashes on the RESP2 wire, so scripts
|
|
96
|
-
# that must return them should nest them (wrap the list in a table).
|
|
97
|
-
#
|
|
98
|
-
# decode is the normalized (see normalize_decode) opt-in float decoding:
|
|
99
|
-
# nil → no decoding, parsing exactly as before
|
|
100
|
-
# :f32 → each value position is unpack('e*')'d when
|
|
101
|
-
# it is a packed float bulk; numeric arrays
|
|
102
|
-
# pass through unchanged (element types kept)
|
|
103
|
-
# {field => :f32, ...} → after hash parsing, the named field(s) of
|
|
104
|
-
# each hash reply decode as :f32 (fields
|
|
105
|
-
# absent from a reply are left untouched)
|
|
106
|
-
def parse_script_reply(reply, multi:, decode: nil)
|
|
107
|
-
parsed = (multi ? reply : [reply]).map { |v| script_hash(v) }
|
|
108
|
-
decoded = apply_decode(parsed, decode)
|
|
109
|
-
multi ? decoded : decoded.first
|
|
91
|
+
# EMB.EVAL/EMB.EVSHA argv: command, model, script|SHA, numtexts, KEYS, ARGV.
|
|
92
|
+
def script_argv(cmd, model, target, texts, args)
|
|
93
|
+
[cmd, model.to_s, target, texts.size, *texts.map(&:to_s), *args.map(&:to_s)]
|
|
110
94
|
end
|
|
111
95
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
96
|
+
# Sends the built argv (eager) or defers it into the thread's batch scope
|
|
97
|
+
# (Emb.build_script_loader). decode: is normalized here so an invalid mode
|
|
98
|
+
# raises before anything is sent; the reply is parsed only on resolution
|
|
99
|
+
# (ScriptReplyDecode#parse_script_reply), with multi: from the argv count.
|
|
100
|
+
def run_script_command(argv, decode)
|
|
101
|
+
schema = normalize_decode(decode)
|
|
102
|
+
return Emb.build_script_loader(self, argv, schema) if lazy?
|
|
117
103
|
|
|
118
|
-
|
|
104
|
+
parse_script_reply(send_command(*argv), multi: argv[3].to_i > 1, decode: schema)
|
|
119
105
|
end
|
|
120
106
|
|
|
121
107
|
# Parse Redis INFO section text into a nested Hash:
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module Emb
|
|
4
|
-
#
|
|
5
|
-
# Emb::Commands#eval / #evalsha. Kept out of the Commands module so the
|
|
6
|
-
# command surface
|
|
7
|
-
#
|
|
4
|
+
# Script-reply parsing and opt-in float decoding — the decode: keyword on
|
|
5
|
+
# Emb::Commands#eval / #evalsha. Kept out of the Commands module so both the
|
|
6
|
+
# command surface and the deferred batch resolver can share it. module_function
|
|
7
|
+
# makes every method callable as Emb::ScriptReplyDecode.foo(...) and, when
|
|
8
|
+
# included, a private instance method (how Commands uses it).
|
|
8
9
|
module ScriptReplyDecode
|
|
9
|
-
|
|
10
|
+
module_function
|
|
10
11
|
|
|
11
12
|
# Validates an (un-normalized) decode option and canonicalizes it. Raises
|
|
12
13
|
# ArgumentError for unknown modes so callers fail before any command is
|
|
@@ -29,6 +30,35 @@ module Emb
|
|
|
29
30
|
end
|
|
30
31
|
end
|
|
31
32
|
|
|
33
|
+
# Converts a scripted reply (single value, or an array of per-text values
|
|
34
|
+
# for multi-text calls) through the hash grammar: a flat field/value pair
|
|
35
|
+
# array becomes a Hash, recursively. Pure even-length string lists are
|
|
36
|
+
# indistinguishable from two-field hashes on the RESP2 wire, so scripts
|
|
37
|
+
# that must return them should nest them (wrap the list in a table).
|
|
38
|
+
#
|
|
39
|
+
# decode is the normalized (see normalize_decode) opt-in float decoding:
|
|
40
|
+
# nil → no decoding, parsing exactly as before
|
|
41
|
+
# :f32 → each value position is unpack('e*')'d when
|
|
42
|
+
# it is a packed float bulk; numeric arrays
|
|
43
|
+
# pass through unchanged (element types kept)
|
|
44
|
+
# {field => :f32, ...} → after hash parsing, the named field(s) of
|
|
45
|
+
# each hash reply decode as :f32 (fields
|
|
46
|
+
# absent from a reply are left untouched)
|
|
47
|
+
def parse_script_reply(reply, multi:, decode: nil)
|
|
48
|
+
parsed = (multi ? reply : [reply]).map { |v| script_hash(v) }
|
|
49
|
+
decoded = apply_decode(parsed, decode)
|
|
50
|
+
multi ? decoded : decoded.first
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def script_hash(value)
|
|
54
|
+
return value unless value.is_a?(Array) && value.size.even?
|
|
55
|
+
|
|
56
|
+
pairs = value.each_slice(2).to_a
|
|
57
|
+
return value unless pairs.all? { |field, _| field.is_a?(String) }
|
|
58
|
+
|
|
59
|
+
pairs.to_h { |field, val| [field, script_hash(val)] }
|
|
60
|
+
end
|
|
61
|
+
|
|
32
62
|
# Applies a normalized decode to the parsed (script_hash'ed) reply array.
|
|
33
63
|
def apply_decode(parsed, decode)
|
|
34
64
|
return parsed if decode.nil?
|
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.
|
|
4
|
+
version: 0.4.3.pre5
|
|
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-
|
|
11
|
+
date: 2026-10-14 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: batch-loader
|
|
@@ -45,6 +45,7 @@ executables: []
|
|
|
45
45
|
extensions: []
|
|
46
46
|
extra_rdoc_files: []
|
|
47
47
|
files:
|
|
48
|
+
- CHANGELOG.md
|
|
48
49
|
- Gemfile
|
|
49
50
|
- LICENSE
|
|
50
51
|
- README.md
|