lex-llm-gemini 0.4.5 → 0.4.7

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.
@@ -1,1168 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'concurrent'
4
- require 'digest'
5
- require 'json'
6
- require 'uri'
7
- require 'faraday'
8
-
9
- begin
10
- require 'legion/extensions/actors/every'
11
- rescue LoadError
12
- nil
13
- end
14
-
15
- unless defined?(Legion::Extensions::Actors::Every)
16
- raise LoadError, 'LegionIO actor runtime is required for Gemini discovery'
17
- end
18
-
19
- require 'legion/extensions/llm/gemini/provider'
20
- require 'legion/extensions/llm/inventory/publisher'
21
- require 'legion/extensions/llm/inventory/scoped_refresher'
22
- require 'legion/extensions/llm/inventory/identity'
23
- require 'legion/extensions/llm/inventory/records'
24
- require 'legion/extensions/llm/inventory/evidence'
25
- require 'legion/extensions/llm/inventory/probe_coordinator'
26
- require 'legion/extensions/llm/inventory/weight_reconciler'
27
- require 'legion/extensions/llm/routing/provider_outcome'
28
- require 'legion/extensions/llm/taxonomies'
29
- require 'legion/extensions/llm/capabilities'
30
-
31
- module Legion
32
- module Extensions
33
- module Llm
34
- module Gemini
35
- module Actor
36
- # ── Evidence building helpers ────────────────────────────────────────
37
- module EvidenceBuilder
38
- private
39
-
40
- def extract_generation_methods(model_data:)
41
- Array(
42
- model_data[:supportedGenerationMethods] ||
43
- model_data[:supported_generation_methods] ||
44
- model_data['supportedGenerationMethods'] ||
45
- model_data['supported_generation_methods']
46
- )
47
- end
48
-
49
- def build_operation_evidence(generation_methods:)
50
- now = Time.now.freeze
51
- chat_status = resolve_operation_status(generation_methods: generation_methods,
52
- action: 'generateContent')
53
- stream_status = resolve_operation_status(generation_methods: generation_methods,
54
- action: 'streamGenerateContent')
55
- embed_status = resolve_operation_status(generation_methods: generation_methods, action: 'embedContent')
56
- {
57
- chat: op_evidence(operation: :chat, status: chat_status, observed_at: now),
58
- stream_chat: op_evidence(operation: :stream_chat, status: stream_status, observed_at: now),
59
- embed: op_evidence(operation: :embed, status: embed_status, observed_at: now),
60
- image: op_evidence(operation: :image, status: :unsupported, observed_at: now),
61
- transcribe: op_evidence(operation: :transcribe, status: :unsupported, observed_at: now),
62
- translate: op_evidence(operation: :translate, status: :unsupported, observed_at: now),
63
- speak: op_evidence(operation: :speak, status: :unsupported, observed_at: now),
64
- moderate: op_evidence(operation: :moderate, status: :unsupported, observed_at: now),
65
- count_tokens: op_evidence(operation: :count_tokens, status: :unknown, observed_at: now)
66
- }
67
- end
68
-
69
- def resolve_operation_status(generation_methods:, action:)
70
- return :unknown if generation_methods.empty?
71
-
72
- generation_methods.include?(action) ? :supported : :unsupported
73
- end
74
-
75
- def op_evidence(operation:, status:, observed_at:)
76
- source = status == :unknown ? :default_false : :provider_catalog
77
- Legion::Extensions::Llm::Inventory::OperationEvidence.new(
78
- operation: operation, status: status, source: source, observed_at: observed_at
79
- )
80
- end
81
-
82
- def build_capability_evidence(generation_methods:, **)
83
- {
84
- completion: cap_from_method(capability: :completion, methods: generation_methods,
85
- action: 'generateContent'),
86
- streaming: cap_from_method(capability: :streaming, methods: generation_methods,
87
- action: 'streamGenerateContent'),
88
- embedding: cap_from_method(capability: :embedding, methods: generation_methods,
89
- action: 'embedContent'),
90
- tools: cap_evidence(capability: :tools, status: :unknown, source: :default_false),
91
- thinking: cap_evidence(capability: :thinking, status: :unknown, source: :default_false),
92
- vision: cap_evidence(capability: :vision, status: :unknown, source: :default_false)
93
- }
94
- end
95
-
96
- def cap_from_method(capability:, methods:, action:)
97
- present = methods.include?(action)
98
- cap_evidence(
99
- capability: capability,
100
- status: present ? :supported : :unknown,
101
- source: present ? :provider_catalog : :default_false
102
- )
103
- end
104
-
105
- def cap_evidence(capability:, status:, source:)
106
- Legion::Extensions::Llm::Inventory::CapabilityEvidence.new(
107
- capability: capability, status: status, source: source, observed_at: Time.now.freeze
108
- )
109
- end
110
- end
111
-
112
- # ── Value evidence helpers ────────────────────────────────────────────
113
- module ValueEvidenceBuilder
114
- private
115
-
116
- def build_context_evidence(model_data:)
117
- ctx = model_data[:inputTokenLimit] || model_data['inputTokenLimit'] || model_data[:input_token_limit]
118
- if ctx.is_a?(Integer) && ctx.positive?
119
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :known, value: ctx,
120
- source: :provider_catalog)
121
- else
122
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :unknown, source: :absent)
123
- end
124
- end
125
-
126
- def build_max_output_evidence(model_data:)
127
- max_out = model_data[:outputTokenLimit] || model_data['outputTokenLimit'] ||
128
- model_data[:output_token_limit]
129
- if max_out.is_a?(Integer) && max_out.positive?
130
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :known, value: max_out,
131
- source: :provider_catalog)
132
- else
133
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :unknown, source: :absent)
134
- end
135
- end
136
-
137
- def build_embedding_dimensions_evidence(model_data:, generation_methods:)
138
- unless generation_methods.include?('embedContent')
139
- return Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :unknown, source: :absent)
140
- end
141
-
142
- dims = extract_valid_dimensions(model_data: model_data)
143
- if dims
144
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :known, value: dims,
145
- source: :provider_catalog)
146
- else
147
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :unknown, source: :absent)
148
- end
149
- end
150
-
151
- def extract_valid_dimensions(model_data:)
152
- dims = model_data[:embedding_dimensions] || model_data['embeddingDimensions']
153
- return nil unless dims.is_a?(Array) && !dims.empty?
154
- return nil unless dims.all? { |d| d.is_a?(Integer) && d.positive? }
155
-
156
- dims.uniq.sort
157
- end
158
-
159
- def build_model_revision_evidence(model_data:)
160
- revision = model_data[:version] || model_data['version']
161
- if revision.is_a?(String) && !revision.strip.empty?
162
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(
163
- status: :known, value: revision.strip, source: :provider_catalog
164
- )
165
- else
166
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :unknown, source: :absent)
167
- end
168
- end
169
-
170
- def build_tokenizer_evidence
171
- Legion::Extensions::Llm::Inventory::ValueEvidence.new(status: :unknown, source: :absent)
172
- end
173
- end
174
-
175
- # ── Model discovery helpers ──────────────────────────────────────────
176
- module ModelDiscovery
177
- private
178
-
179
- # Only transport and body-parse failures yield "no offerings".
180
- # Programming errors (NameError/NoMethodError/ArgumentError) must
181
- # propagate to the caller's loud log path — rescuing them here
182
- # would publish an activated instance with ZERO offerings
183
- # (invisible to the router) while looking healthy.
184
- def discover_offerings_for_instance(instance_cfg:, instance_key:)
185
- models = fetch_models(instance_cfg: instance_cfg)
186
- models.filter_map do |model_data|
187
- model_id = extract_model_id(model_data: model_data)
188
- next if model_id.empty?
189
-
190
- build_offering_draft(
191
- model_id: model_id, model_data: model_data,
192
- instance_cfg: instance_cfg, instance_key: instance_key
193
- )
194
- end
195
- rescue Faraday::Error, Legion::JSON::ParseError => e
196
- handle_exception(e, level: :warn, operation: 'gemini.actor.discover_offerings')
197
- []
198
- end
199
-
200
- def fetch_models(instance_cfg:)
201
- base_url = resolve_api_base(instance_cfg: instance_cfg)
202
- conn = build_api_connection(base_url: base_url, instance_cfg: instance_cfg)
203
- response = conn.get('models')
204
- body = Legion::JSON.load(response.body)
205
- Array(body[:models])
206
- end
207
-
208
- def extract_model_id(model_data:)
209
- name = model_data[:name] || model_data['name'] || ''
210
- name.to_s.delete_prefix('models/')
211
- end
212
-
213
- def build_offering_draft(model_id:, model_data:, instance_cfg:, instance_key:)
214
- tier = instance_cfg[:tier] || :frontier
215
- generation_methods = extract_generation_methods(model_data: model_data)
216
- weight_inputs = Legion::Extensions::Llm::Inventory::WeightSchema.weight_inputs(
217
- settings: Legion::Settings,
218
- instance_key: instance_key,
219
- provider_native_key: model_id,
220
- model: model_id,
221
- tier: tier
222
- )
223
-
224
- Legion::Extensions::Llm::Inventory::OfferingDraft.new(
225
- provider_native_key: model_id, model: model_id, tier: tier,
226
- weight_inputs: weight_inputs,
227
- base_weight: Legion::Extensions::Llm::Inventory::WeightSchema.base_weight(weight_inputs),
228
- operation_evidence: build_operation_evidence(generation_methods: generation_methods),
229
- capability_evidence: build_capability_evidence(generation_methods: generation_methods),
230
- context_evidence: build_context_evidence(model_data: model_data),
231
- max_output_evidence: build_max_output_evidence(model_data: model_data),
232
- embedding_dimensions_evidence: build_embedding_dimensions_evidence(
233
- model_data: model_data, generation_methods: generation_methods
234
- ),
235
- model_revision_evidence: build_model_revision_evidence(model_data: model_data),
236
- tokenizer_evidence: build_tokenizer_evidence,
237
- quota_domains: {},
238
- metadata: build_offering_metadata(model_data: model_data, instance_key: instance_key),
239
- publication_source: :provider_catalog
240
- )
241
- end
242
-
243
- def build_offering_metadata(model_data:, instance_key:)
244
- meta = { raw_model: extract_model_id(model_data: model_data) }
245
- meta[:display_name] = model_data[:displayName].to_s if model_data[:displayName]
246
- meta[:description] = model_data[:description].to_s[0, 200] if model_data[:description]
247
- meta[:instance_id] = instance_key.instance_id
248
- meta
249
- end
250
- end
251
-
252
- # ── Instance configuration helpers ───────────────────────────────────
253
- module ConfigResolver
254
- private
255
-
256
- def configured_instances
257
- instances = {}
258
- cfg_instances = settings[:instances]
259
- if cfg_instances.is_a?(Hash)
260
- cfg_instances.each do |name, config|
261
- normalized = claimable_instance_config(config: config)
262
- instances[name.to_sym] = normalized if normalized
263
- end
264
- end
265
- if instances.empty?
266
- auto_instance = build_auto_instance
267
- instances[:default_instance] = auto_instance if auto_instance
268
- end
269
- instances
270
- end
271
-
272
- # Returns the normalized config when the entry is claimable, else
273
- # nil: the always-present synthetic instances.default template is
274
- # loudly skipped while unmodified, and every other entry needs a
275
- # resolvable API key.
276
- def claimable_instance_config(config:)
277
- normalized = normalize_instance_config(config: config)
278
-
279
- return unless resolvable_api_key?(normalized[:gemini_api_key])
280
-
281
- normalized
282
- end
283
-
284
- # The synthetic instances.default section — ProviderSettings.build
285
- # always nests the extension's own instance defaults (endpoint,
286
- # discovery_interval, the env://GEMINI_API_KEY placeholder
287
- # credential, fleet/limits blocks) there. It is "configured" only
288
- # when the operator changed the entry: while it is still the
289
- # unmodified template (placeholder credential included) it is a
290
- # phantom the provider layer must never claim. A 'default' entry
291
- # the operator modified (a real API key, a different endpoint) is
292
- # a plain instance label — v2 accepted 'default' as an ordinary
293
- # name — and passes through to the claim path.
294
- def unconfigured_default?(name:, config:)
295
- name.to_s == 'default' && deep_symbolize(config) == synthetic_default_instance
296
- end
297
-
298
- # The nested template, straight from the extension's registered
299
- # defaults — compared by value against the live template, never
300
- # against a hardcoded literal.
301
- def synthetic_default_instance
302
- @synthetic_default_instance ||=
303
- Legion::Extensions::Llm::Gemini.default_settings.dig(:instances, :default)
304
- end
305
-
306
- # Settings entries arrive with string or symbol keys (YAML vs
307
- # JSON vs the nested template); canonicalize before comparing.
308
- def deep_symbolize(value)
309
- case value
310
- when Hash
311
- value.to_h { |key, inner| [key.respond_to?(:to_sym) ? key.to_sym : key, deep_symbolize(inner)] }
312
- when Array
313
- value.map { |inner| deep_symbolize(inner) }
314
- else
315
- value
316
- end
317
- end
318
-
319
- def build_auto_instance
320
- api_key = settings.dig(:credentials, :api_key)
321
- api_key = resolve_env_credential(api_key) if env_credential?(api_key)
322
- return nil unless resolvable_api_key?(api_key)
323
-
324
- {
325
- gemini_api_base: settings[:endpoint],
326
- gemini_api_key: api_key,
327
- tier: settings[:tier]
328
- }
329
- end
330
-
331
- def resolvable_api_key?(api_key)
332
- api_key.is_a?(String) && !api_key.strip.empty?
333
- end
334
-
335
- def env_credential?(value)
336
- value.is_a?(String) && value.start_with?('env://')
337
- end
338
-
339
- def resolve_env_credential(value)
340
- ENV.fetch(value.delete_prefix('env://'), nil)
341
- end
342
-
343
- def normalize_instance_config(config:)
344
- normalized = config.to_h.transform_keys(&:to_sym)
345
- resolve_instance_api_base(normalized: normalized)
346
- resolve_instance_credentials(normalized: normalized)
347
- normalized[:tier] ||= :frontier
348
- normalized
349
- end
350
-
351
- def resolve_instance_api_base(normalized:)
352
- normalized[:gemini_api_base] ||= normalized.delete(:base_url)
353
- normalized[:gemini_api_base] ||= normalized.delete(:api_base)
354
- normalized[:gemini_api_base] ||= normalized.delete(:endpoint)
355
- normalized[:gemini_api_base] ||= 'https://generativelanguage.googleapis.com/v1beta'
356
- end
357
-
358
- # Resolves env:// credential references in the instances.* path so an
359
- # env-only deployment claims the real key instead of the literal
360
- # 'env://GEMINI_API_KEY' placeholder (which would 4xx and pin the
361
- # instance in :initializing with a placeholder-fingerprinted id).
362
- def resolve_instance_credentials(normalized:)
363
- normalized[:gemini_api_key] ||= normalized.delete(:api_key)
364
- creds = normalized.delete(:credentials)
365
- if creds.is_a?(Hash)
366
- creds = creds.transform_keys(&:to_sym)
367
- normalized[:gemini_api_key] ||= creds[:api_key]
368
- end
369
- return unless env_credential?(normalized[:gemini_api_key])
370
-
371
- normalized[:gemini_api_key] = resolve_env_credential(normalized[:gemini_api_key])
372
- end
373
- end
374
-
375
- # ── HTTP connection helpers ──────────────────────────────────────────
376
- module HttpClient
377
- private
378
-
379
- def resolve_api_base(instance_cfg:)
380
- (instance_cfg[:gemini_api_base] || instance_cfg[:endpoint] ||
381
- 'https://generativelanguage.googleapis.com/v1beta').to_s
382
- end
383
-
384
- def build_api_connection(base_url:, instance_cfg:)
385
- Faraday.new(url: base_url) do |f|
386
- f.options.timeout = 15
387
- f.options.open_timeout = 5
388
- f.headers['Accept'] = 'application/json'
389
- apply_auth_header(faraday: f, instance_cfg: instance_cfg)
390
- f.adapter Faraday.default_adapter
391
- end
392
- end
393
-
394
- def apply_auth_header(faraday:, instance_cfg:)
395
- api_key = instance_cfg[:gemini_api_key] || instance_cfg[:api_key] ||
396
- instance_cfg.dig(:credentials, :api_key)
397
- return unless api_key.is_a?(String) && !api_key.strip.empty?
398
-
399
- faraday.headers['x-goog-api-key'] = api_key
400
- end
401
-
402
- # SECONDARY physical id (InstanceKey.physical_id): the derived
403
- # host:port/ak fingerprint, kept for dedup and diagnostics only.
404
- # Instance IDENTIFICATION is the operator's config name — see
405
- # claim_and_activate_instance. Never the identity itself.
406
- def derive_physical_id(instance_cfg:)
407
- base_url = instance_cfg[:gemini_api_base] || instance_cfg[:endpoint] ||
408
- 'https://generativelanguage.googleapis.com/v1beta'
409
- host_port = extract_host_port(url: base_url)
410
- api_key = instance_cfg[:gemini_api_key] || instance_cfg[:api_key] ||
411
- instance_cfg.dig(:credentials, :api_key)
412
-
413
- return host_port unless api_key.is_a?(String) && !api_key.strip.empty?
414
-
415
- fingerprint = ::Digest::SHA256.hexdigest(api_key)[0, 8]
416
- "#{host_port}/ak:#{fingerprint}"
417
- end
418
-
419
- def extract_host_port(url:)
420
- uri = URI.parse(url.to_s)
421
- host = uri.host || 'generativelanguage.googleapis.com'
422
- "#{host}:#{uri.port}"
423
- rescue URI::InvalidURIError => e
424
- handle_exception(e, level: :warn, operation: 'gemini.actor.extract_host_port', url: url.to_s)
425
- 'unknown:0'
426
- end
427
- end
428
-
429
- # ── Readiness probe helpers ──────────────────────────────────────────
430
- module ProbeRunner
431
- private
432
-
433
- def run_cadence_probe(instance_id:, state:)
434
- coordinator = state[:probe_coordinator]
435
- return unless coordinator.begin_probe
436
-
437
- run_instance_probe(instance_id: instance_id, state: state, coordinator: coordinator)
438
- sync_display_health(state: state)
439
- rescue StandardError => e
440
- finish_probe_on_error(coordinator: coordinator)
441
- handle_exception(e, level: :warn, operation: 'gemini.actor.cadence_probe', instance_id: instance_id)
442
- end
443
-
444
- def handle_reactive_probe(instance_id:, request:)
445
- state = tracked_instance_state(instance_id)
446
- return unless state
447
-
448
- coordinator = state[:probe_coordinator]
449
- return unless coordinator.begin_probe(request: request)
450
-
451
- run_instance_probe(instance_id: instance_id, state: state, coordinator: coordinator, request: request)
452
- sync_display_health(state: state)
453
- rescue StandardError => e
454
- finish_probe_on_error(coordinator: coordinator, request: request)
455
- handle_exception(e, level: :warn, operation: 'gemini.actor.reactive_probe', instance_id: instance_id)
456
- end
457
-
458
- # Shared probe body: starts the publisher probe, checks health,
459
- # finishes the coordinator probe (coalesced probes pass their
460
- # request token), and reports the outcome.
461
- def run_instance_probe(instance_id:, state:, coordinator:, request: nil)
462
- probe_token = publisher.readiness_probe_started(
463
- instance_id: instance_id, publisher_token: state[:publisher_token],
464
- physical_id: state[:instance_key].physical_id
465
- )
466
- readiness = check_health(instance_cfg: state[:instance_cfg])
467
- if request
468
- coordinator.finish_probe(request: request)
469
- else
470
- coordinator.finish_probe
471
- end
472
- report_probe_result(instance_id: instance_id, state: state,
473
- probe_token: probe_token, readiness: readiness)
474
- end
475
-
476
- # Best-effort probe release on the error path — a failure to
477
- # release is logged, never raised over the original error.
478
- def finish_probe_on_error(coordinator:, request: nil)
479
- if request
480
- coordinator&.finish_probe(request: request)
481
- else
482
- coordinator&.finish_probe
483
- end
484
- rescue StandardError => e
485
- handle_exception(e, level: :warn, operation: 'gemini.actor.probe.finish_probe')
486
- end
487
-
488
- def report_probe_result(instance_id:, state:, probe_token:, readiness:)
489
- if readiness.ready?
490
- publisher.readiness_succeeded(
491
- instance_id: instance_id, physical_id: state[:instance_key].physical_id, probe_token: probe_token
492
- )
493
- else
494
- publisher.readiness_failed(
495
- instance_id: instance_id, physical_id: state[:instance_key].physical_id,
496
- probe_token: probe_token, reason: readiness.reason
497
- )
498
- end
499
- end
500
-
501
- def build_probe_enqueue(instance_id:)
502
- proc do |request:|
503
- handle_reactive_probe(instance_id: instance_id, request: request)
504
- true
505
- rescue StandardError => e
506
- handle_exception(e, level: :warn, operation: 'gemini.actor.probe_enqueue', instance_id: instance_id)
507
- false
508
- end
509
- end
510
- end
511
-
512
- # ── Health check helpers ─────────────────────────────────────────────
513
- module HealthChecker
514
- private
515
-
516
- def check_health(instance_cfg:)
517
- base_url = resolve_api_base(instance_cfg: instance_cfg)
518
- conn = build_api_connection(base_url: base_url, instance_cfg: instance_cfg)
519
- response = conn.get('models', { pageSize: 1 })
520
- build_readiness_from_response(response: response, base_url: base_url)
521
- rescue Faraday::ConnectionFailed => e
522
- handle_exception(e, level: :warn, operation: 'gemini.actor.check_health.connection',
523
- base_url: base_url)
524
- readiness_failure(reason: "Gemini models API connection failed: #{e.message}", error: e)
525
- rescue StandardError => e
526
- handle_exception(e, level: :warn, operation: 'gemini.actor.check_health', base_url: base_url)
527
- readiness_failure(reason: "Gemini models API error: #{e.message}", error: e)
528
- end
529
-
530
- def build_readiness_from_response(response:, base_url:)
531
- Legion::Extensions::Llm::Inventory::ReadinessResult.new(
532
- ready: response.status == 200,
533
- reason: "Gemini models API returned #{response.status}",
534
- metadata: { status: response.status, base_url: base_url }
535
- )
536
- end
537
-
538
- def readiness_failure(reason:, error:)
539
- Legion::Extensions::Llm::Inventory::ReadinessResult.new(
540
- ready: false,
541
- reason: reason,
542
- metadata: { error_class: error.class.name }
543
- )
544
- end
545
- end
546
-
547
- # ── Instance lifecycle helpers ───────────────────────────────────────
548
- # ── Offering change comparison helpers ───────────────────────────────
549
- module OfferingComparison
550
- SCALAR_EVIDENCE_FIELDS = %i[
551
- context_evidence max_output_evidence embedding_dimensions_evidence
552
- model_revision_evidence tokenizer_evidence
553
- ].freeze
554
-
555
- private
556
-
557
- # Every catalog pass rebuilds evidence observation timestamps. The
558
- # timestamps are telemetry, but every other draft field remains
559
- # authoritative. Catalog order is not authoritative; multiplicity is.
560
- def offerings_changed?(previous:, current:)
561
- offering_comparison_multiset(current) != offering_comparison_multiset(previous)
562
- end
563
-
564
- def offering_comparison_multiset(offerings)
565
- Array(offerings).map { |draft| offering_comparison_state(draft) }.tally
566
- end
567
-
568
- def offering_comparison_state(draft)
569
- state = draft.to_h
570
- state[:operation_evidence] = comparison_evidence_map(draft.operation_evidence)
571
- state[:capability_evidence] = comparison_evidence_map(draft.capability_evidence)
572
- SCALAR_EVIDENCE_FIELDS.each do |field|
573
- state[field] = comparison_evidence(draft.public_send(field))
574
- end
575
- state
576
- end
577
-
578
- def comparison_evidence_map(evidence)
579
- evidence.transform_values { |entry| comparison_evidence(entry) }
580
- end
581
-
582
- def comparison_evidence(evidence)
583
- evidence.to_h.except(:observed_at)
584
- end
585
- end
586
-
587
- # ── Settings display health helpers (D14) ────────────────────────────
588
- module DisplayHealth
589
- private
590
-
591
- # Display-only health/capabilities for the status API, written after
592
- # each registry commit. The key is the CONFIG name
593
- # (settings[:instances] key), never the derived instance_id.
594
- # Routing authority stays the in-memory AvailabilityFact; this hash
595
- # is never read by the router.
596
- def sync_display_health(state:)
597
- entry = instance_settings_entry(name: state[:name])
598
- return unless entry.is_a?(Hash)
599
-
600
- entry.merge!(display_health_entry(state: state))
601
- rescue StandardError => e
602
- handle_exception(e, level: :warn, operation: 'gemini.actor.sync_display_health',
603
- instance_id: state[:instance_id])
604
- end
605
-
606
- def display_health_entry(state:)
607
- record = publisher.snapshot.instance(instance_key: state[:instance_key])
608
- status = publisher.snapshot.publication_status(instance_key: state[:instance_key])
609
- {
610
- health: display_health(availability: record&.availability, status: status),
611
- capabilities: instance_capabilities(state[:offerings])
612
- }
613
- end
614
-
615
- def clear_display_health(name:)
616
- entry = instance_settings_entry(name: name)
617
- return unless entry.is_a?(Hash)
618
-
619
- entry.delete(:health)
620
- entry.delete(:capabilities)
621
- rescue StandardError => e
622
- handle_exception(e, level: :warn, operation: 'gemini.actor.clear_display_health',
623
- instance_name: name.to_s)
624
- end
625
-
626
- def instance_settings_entry(name:)
627
- instances = settings[:instances]
628
- return nil unless instances.is_a?(Hash)
629
-
630
- instances[name] || instances[name.to_s]
631
- end
632
-
633
- def display_health(availability:, status:)
634
- available = availability&.state == :available
635
- {
636
- circuit_state: available ? :closed : :open,
637
- denied: false,
638
- available: available,
639
- adjustment: available ? 0 : -50,
640
- reason: health_reason(availability: availability, status: status),
641
- observed_at: health_observed_at(availability: availability, status: status),
642
- last_probe_outcome: status.last_probe_outcome,
643
- source: health_source(availability: availability)
644
- }
645
- end
646
-
647
- def health_reason(availability:, status:)
648
- availability&.reason || status.last_error
649
- end
650
-
651
- def health_observed_at(availability:, status:)
652
- availability&.observed_at || status.last_probe_completed_at
653
- end
654
-
655
- def health_source(availability:)
656
- availability&.source || :initial_readiness
657
- end
658
-
659
- def instance_capabilities(offerings)
660
- offerings.flat_map do |draft|
661
- draft.capability_evidence.filter_map do |capability, evidence|
662
- evidence.supported? ? capability : nil
663
- end
664
- end.uniq.sort
665
- end
666
- end
667
-
668
- # ── Instance component helpers ───────────────────────────────────────
669
- module InstanceComponents
670
- private
671
-
672
- def build_instance_key(instance_id:, physical_id: nil)
673
- Legion::Extensions::Llm::Inventory::Identity::InstanceKey.new(
674
- provider_family: :gemini, instance_id: instance_id, physical_id: physical_id
675
- )
676
- end
677
-
678
- def build_instance_components(instance_id:, instance_cfg:, instance_key:)
679
- callable = GeminiCallable.new(instance_cfg: instance_cfg, logger: log)
680
- probe_coordinator = Legion::Extensions::Llm::Inventory::ProbeCoordinator.new(
681
- instance_key: instance_key, enqueue: build_probe_enqueue(instance_id: instance_id)
682
- )
683
- publisher_token = publisher.claim_instance(
684
- instance_id: instance_id, callable: callable, probe_request_handle: probe_coordinator,
685
- physical_id: instance_key.physical_id
686
- )
687
- { callable: callable, probe_coordinator: probe_coordinator, publisher_token: publisher_token }
688
- end
689
-
690
- def claim_and_activate_instance(name:, instance_cfg:)
691
- # Identity is the operator's CONFIG NAME (the key the router
692
- # looks up in instances.<name>); the derived host:port/ak id is
693
- # the secondary physical id (dedup/diagnostics only).
694
- instance_id = name.to_s
695
- physical_id = derive_physical_id(instance_cfg: instance_cfg)
696
- instance_key = build_instance_key(instance_id: instance_id, physical_id: physical_id)
697
- offerings = discover_offerings_for_instance(instance_cfg: instance_cfg, instance_key: instance_key)
698
- components = build_instance_components(instance_id: instance_id, instance_cfg: instance_cfg,
699
- instance_key: instance_key)
700
- state = {
701
- name: name,
702
- instance_id: instance_id,
703
- instance_key: instance_key,
704
- instance_cfg: instance_cfg,
705
- callable: components[:callable],
706
- probe_coordinator: components[:probe_coordinator],
707
- publisher_token: components[:publisher_token],
708
- sequence: 0,
709
- offerings: offerings,
710
- published: false
711
- }
712
- Legion::Extensions::Llm::Inventory::WeightReconciler.track_initializing!(
713
- states: @instance_states, state_key: instance_id, state: state, mutex: @instance_state_mutex
714
- )
715
- settle_initial_readiness(instance_id: instance_id, state: state)
716
- sync_display_health(state: state) if tracked_instance_state(instance_id).equal?(state)
717
- end
718
-
719
- def drop_instance(instance_id:, state:)
720
- removed = @instance_state_mutex.synchronize do
721
- next false unless @instance_states[instance_id].equal?(state)
722
-
723
- publisher.remove_instance(
724
- instance_id: instance_id, publisher_token: state[:publisher_token],
725
- physical_id: state[:instance_key].physical_id
726
- )
727
- @instance_states.delete(instance_id)
728
- true
729
- end
730
- return false unless removed
731
-
732
- state[:callable]&.disconnect
733
- clear_display_health(name: state[:name])
734
- true
735
- rescue StandardError => e
736
- handle_exception(e, level: :warn, operation: 'gemini.actor.remove_instance',
737
- instance_id: instance_id)
738
- false
739
- end
740
- end
741
-
742
- # Shared weight-reconciliation bindings and synchronized state access.
743
- module WeightPublication
744
- private
745
-
746
- def commit_discovered_offerings(instance_id:, state:, offerings:)
747
- Legion::Extensions::Llm::Inventory::WeightReconciler.commit_if_changed!(
748
- settings: Legion::Settings,
749
- instance_id: instance_id,
750
- state: state,
751
- discovered_offerings: offerings,
752
- mutex: @instance_state_mutex,
753
- equivalent: lambda do |previous, current|
754
- !offerings_changed?(previous: previous, current: current)
755
- end,
756
- replace: method(:replace_weight_snapshot)
757
- )
758
- end
759
-
760
- def replace_weight_snapshot(instance_id:, state:, offerings:, sequence:)
761
- publisher.replace_instance_snapshot(
762
- instance_id: instance_id,
763
- publisher_token: state.fetch(:publisher_token),
764
- offerings: offerings,
765
- sequence: sequence,
766
- physical_id: state.fetch(:instance_key).physical_id
767
- )
768
- end
769
-
770
- def activate_weight_snapshot(instance_id:, state:, offerings:, sequence:, probe_token:)
771
- publisher.activate_instance_snapshot(
772
- instance_id: instance_id,
773
- publisher_token: state.fetch(:publisher_token),
774
- offerings: offerings,
775
- sequence: sequence,
776
- probe_token: probe_token,
777
- physical_id: state.fetch(:instance_key).physical_id
778
- )
779
- end
780
-
781
- def tracked_instance_state(instance_id)
782
- return unless @instance_states && @instance_state_mutex
783
-
784
- @instance_state_mutex.synchronize { @instance_states[instance_id] }
785
- end
786
-
787
- def instance_states_snapshot
788
- @instance_state_mutex.synchronize { @instance_states.each_pair.to_h }
789
- end
790
-
791
- def observe_dormant_weights
792
- Legion::Extensions::Llm::Inventory::WeightReconciler.observe_dormant!(
793
- settings: Legion::Settings,
794
- provider_family: :gemini,
795
- states: @instance_states,
796
- mutex: @instance_state_mutex,
797
- tracker: @dormant_weight_tracker,
798
- dormant_logger: lambda do |key|
799
- log.info do
800
- "[llm][gemini] action=dormant_weight weight_key=#{key.inspect} no_lane_published=true"
801
- end
802
- end
803
- )
804
- end
805
- end
806
-
807
- # Per-instance SSOT lifecycle: reconcile configured instances each
808
- # tick, run the readiness state machine (initial probe, recovery
809
- # while :initializing, cadence probes, snapshot replacement), and
810
- # retire instances on shutdown.
811
- module InstanceLifecycle
812
- private
813
-
814
- def initial_discovery
815
- @instance_states = Concurrent::Map.new
816
- @instance_state_mutex = Mutex.new
817
- @dormant_weight_tracker = Legion::Extensions::Llm::Inventory::DormantWeightTracker.new
818
- reconcile_and_refresh
819
- end
820
-
821
- def tick_refresh = reconcile_and_refresh
822
-
823
- # Re-scans configured instances every tick so instances configured
824
- # after boot appear without a restart and instances removed from
825
- # settings are retired from the registry. Instances claimed THIS
826
- # tick are not refreshed again in the same pass — their initial
827
- # probe just ran; refresh and cadence probes start next tick.
828
- def reconcile_and_refresh
829
- configured = configured_instances
830
- existing = instance_states_snapshot.keys
831
- add_newly_configured_instances(configured: configured)
832
- remove_unconfigured_instances(configured: configured)
833
- instance_states_snapshot.each do |instance_id, state|
834
- next unless existing.include?(instance_id)
835
-
836
- refresh_instance(instance_id: instance_id, state: state)
837
- rescue StandardError => e
838
- handle_exception(e, level: :warn, operation: 'gemini.actor.refresh_instance',
839
- instance_id: instance_id)
840
- end
841
- observe_dormant_weights
842
- end
843
-
844
- def add_newly_configured_instances(configured:)
845
- configured.each do |name, instance_cfg|
846
- # Dedup on the CONFIG NAME (the identity), not the physical
847
- # id: two config names pointing at the same endpoint are
848
- # distinct instances (the physical id never participates in
849
- # identity).
850
- next if tracked_instance_state(name.to_s)
851
-
852
- claim_and_activate_instance(name: name, instance_cfg: instance_cfg)
853
- rescue StandardError => e
854
- handle_exception(e, level: :warn, operation: 'gemini.actor.claim_instance', instance_name: name.to_s)
855
- end
856
- end
857
-
858
- def remove_unconfigured_instances(configured:)
859
- instance_states_snapshot.each_value do |state|
860
- next if configured.key?(state[:name])
861
-
862
- drop_instance(instance_id: state[:instance_id], state: state)
863
- end
864
- end
865
-
866
- # Starts the readiness probe and settles it: on success activates
867
- # the current offerings (sequence 0 — valid only while the scope
868
- # is still :initializing), on failure records it and the instance
869
- # stays :initializing for the next tick's retry.
870
- def settle_initial_readiness(instance_id:, state:)
871
- physical_id = state[:instance_key].physical_id
872
- probe_token = publisher.readiness_probe_started(
873
- instance_id: instance_id, publisher_token: state[:publisher_token], physical_id: physical_id
874
- )
875
- readiness = check_health(instance_cfg: state[:instance_cfg])
876
- if readiness.ready?
877
- Legion::Extensions::Llm::Inventory::WeightReconciler.activate_tracked!(
878
- settings: Legion::Settings,
879
- instance_id: instance_id,
880
- state_key: instance_id,
881
- state: state,
882
- states: @instance_states,
883
- mutex: @instance_state_mutex,
884
- probe_token: probe_token,
885
- activate: method(:activate_weight_snapshot),
886
- activation_sequence: ->(tracked) { tracked.fetch(:sequence) }
887
- )
888
- else
889
- publisher.readiness_failed(
890
- instance_id: instance_id, probe_token: probe_token, reason: readiness.reason,
891
- physical_id: physical_id
892
- )
893
- end
894
- end
895
-
896
- def refresh_instance(instance_id:, state:)
897
- if publication_state(instance_key: state[:instance_key]) == :initializing
898
- retry_initial_activation(instance_id: instance_id, state: state)
899
- else
900
- replace_offerings_if_changed(instance_id: instance_id, state: state)
901
- run_cadence_probe(instance_id: instance_id, state: state)
902
- end
903
- end
904
-
905
- def publication_state(instance_key:)
906
- publisher.snapshot.publication_status(instance_key: instance_key).state
907
- end
908
-
909
- # An instance that failed initial readiness stays :initializing —
910
- # readiness_succeeded and replace_instance_snapshot both refuse to
911
- # operate on an :initializing scope, so without this re-activation
912
- # path a transient outage at boot pins the instance for the process
913
- # lifetime. Re-probe each tick and activate once readiness passes.
914
- def retry_initial_activation(instance_id:, state:)
915
- offerings = discover_offerings_for_instance(
916
- instance_cfg: state[:instance_cfg], instance_key: state[:instance_key]
917
- )
918
- commit_discovered_offerings(instance_id: instance_id, state: state, offerings: offerings)
919
- settle_initial_readiness(instance_id: instance_id, state: state)
920
- sync_display_health(state: state) if tracked_instance_state(instance_id).equal?(state)
921
- end
922
-
923
- def replace_offerings_if_changed(instance_id:, state:)
924
- new_offerings = discover_offerings_for_instance(
925
- instance_cfg: state[:instance_cfg], instance_key: state[:instance_key]
926
- )
927
- changed = commit_discovered_offerings(
928
- instance_id: instance_id, state: state, offerings: new_offerings
929
- )
930
- sync_display_health(state: state) if changed
931
- end
932
-
933
- def remove_all_instances
934
- return unless @instance_states
935
-
936
- instance_states_snapshot.each_value do |state|
937
- drop_instance(instance_id: state[:instance_id], state: state)
938
- end
939
- @instance_state_mutex.synchronize do
940
- @instance_states.clear
941
- @dormant_weight_tracker.clear!
942
- end
943
- end
944
- end
945
-
946
- # SSOT v3 periodic discovery actor for Gemini provider instances.
947
- # Claims configured instances, discovers models via the Gemini models
948
- # API, probes health via model listing, and publishes complete
949
- # OfferingDraft snapshots through the Inventory::Publisher. Recovers
950
- # instances that fail initial readiness and supports coalesced
951
- # reactive probes after dispatch-triggered instance_unavailable
952
- # transitions.
953
- class DiscoveryRefresh < Legion::Extensions::Actors::Every
954
- include Legion::Extensions::Helpers::Lex
955
- include Legion::Logging::Helper
956
- include EvidenceBuilder
957
- include ValueEvidenceBuilder
958
- include ModelDiscovery
959
- include ConfigResolver
960
- include HttpClient
961
- include ProbeRunner
962
- include HealthChecker
963
- include OfferingComparison
964
- include DisplayHealth
965
- include InstanceComponents
966
- include WeightPublication
967
- include InstanceLifecycle
968
-
969
- def runner_class = self.class
970
- def runner_function = 'manual'
971
- def run_now? = true
972
- def use_runner? = false
973
- def check_subtask? = false
974
- def generate_task? = false
975
-
976
- # The registered discovery interval lives under instances.default
977
- # (provider_settings nests it there). Never return nil — a nil
978
- # execution_interval makes the TimerTask fire exactly once and then
979
- # stop, killing all refresh, probes, and recovery.
980
- def time
981
- interval = settings.dig(:instances, :default, :discovery_interval)
982
- return interval if interval.is_a?(::Integer) && interval.positive?
983
-
984
- Legion::Extensions::Llm::Gemini.default_settings.dig(:instances, :default, :discovery_interval)
985
- end
986
-
987
- def manual
988
- if @initialized
989
- tick_refresh
990
- else
991
- initial_discovery
992
- @initialized = true
993
- end
994
- rescue StandardError => e
995
- handle_exception(e, level: :warn, operation: 'gemini.actor.discovery_refresh')
996
- end
997
-
998
- def shutdown
999
- remove_all_instances
1000
- rescue StandardError => e
1001
- handle_exception(e, level: :warn, operation: 'gemini.actor.discovery_refresh.shutdown')
1002
- end
1003
-
1004
- private
1005
-
1006
- def publisher
1007
- @publisher ||= Legion::Extensions::Llm::Inventory::Publisher.new(
1008
- provider_family: :gemini,
1009
- compatibility_adapter: Legion::Extensions::Llm::Inventory::ScopedRefresher::LegacyCoordinatorAdapter.new(
1010
- provider_family: :gemini
1011
- )
1012
- )
1013
- end
1014
- end
1015
-
1016
- # Callable wrapper for a Gemini provider instance. Implements the
1017
- # fleet dispatch ops (chat/stream_chat/embed/count_tokens) by
1018
- # delegating to a per-instance Gemini::Provider, plus the
1019
- # disconnect and normalize_dispatch_error contracts required by
1020
- # Inventory::CallableHandle and Routing::ProviderOutcome. Dispatch
1021
- # errors propagate untouched so normalize_dispatch_error can
1022
- # classify them.
1023
- class GeminiCallable
1024
- def initialize(instance_cfg:, logger:, provider: nil)
1025
- @instance_cfg = instance_cfg
1026
- @logger = logger
1027
- @provider = provider
1028
- @disconnected = false
1029
- end
1030
-
1031
- def disconnected? = @disconnected
1032
-
1033
- def disconnect
1034
- @disconnected = true
1035
- @provider&.disconnect
1036
- @logger.debug { '[gemini][callable] disconnected' }
1037
- end
1038
-
1039
- # Fleet and SelectionDispatch pass model as a RAW STRING (the
1040
- # offering's model id). Gemini's render path calls model.id
1041
- # (MessageFormatter#render_payload), so a raw string must be
1042
- # wrapped before delegation; Model::Info instances pass through.
1043
- def chat(messages:, model:, **rest)
1044
- provider.chat(messages: messages, model: llm_model(model), **rest)
1045
- end
1046
-
1047
- def stream_chat(messages:, model:, **rest, &)
1048
- provider.stream_chat(messages: messages, model: llm_model(model), **rest, &)
1049
- end
1050
-
1051
- def embed(text:, model:, **rest)
1052
- provider.embed(text: text, model: llm_model(model), **rest)
1053
- end
1054
-
1055
- def count_tokens(messages:, model:, **rest)
1056
- provider.count_tokens(messages: messages, model: llm_model(model), **rest)
1057
- end
1058
-
1059
- def normalize_dispatch_error(error:)
1060
- reason = error.message.to_s[0, 512]
1061
- Legion::Extensions::Llm::Routing::ProviderOutcome.new(
1062
- kind: classify_dispatch_error(error: error), reason: reason.empty? ? 'unknown dispatch error' : reason
1063
- )
1064
- end
1065
-
1066
- private
1067
-
1068
- def llm_model(model)
1069
- return model if model.respond_to?(:id)
1070
-
1071
- Legion::Extensions::Llm::Model::Info.new(id: model.to_s, provider: :gemini)
1072
- end
1073
-
1074
- def provider = @provider ||= build_provider
1075
-
1076
- def build_provider
1077
- Legion::Extensions::Llm::Gemini::Provider.new(
1078
- {
1079
- gemini_api_key: @instance_cfg[:gemini_api_key] || @instance_cfg[:api_key] ||
1080
- @instance_cfg.dig(:credentials, :api_key),
1081
- gemini_api_base: @instance_cfg[:gemini_api_base] || @instance_cfg[:endpoint]
1082
- }.compact
1083
- )
1084
- end
1085
-
1086
- def classify_dispatch_error(error:)
1087
- return :connection_failure if error.is_a?(Faraday::ConnectionFailed)
1088
- return :timeout if error.is_a?(Faraday::TimeoutError)
1089
- return :overloaded if error.is_a?(Legion::Extensions::Llm::OverloadedError)
1090
- return classify_by_status(error: error) if http_status_error?(error)
1091
-
1092
- :provider_error
1093
- end
1094
-
1095
- def http_status_error?(error)
1096
- error.is_a?(Faraday::ClientError) || error.is_a?(Faraday::ServerError) ||
1097
- error.is_a?(Legion::Extensions::Llm::Error)
1098
- end
1099
-
1100
- # §8 health firewall: only the explicit Gemini UNAVAILABLE body
1101
- # signal maps to :instance_unavailable. Status code alone (503/529)
1102
- # never does — those are request-local overload conditions.
1103
- def classify_by_status(error:)
1104
- return :instance_unavailable if explicit_service_unavailable?(error: error)
1105
-
1106
- status = dispatch_status(error)
1107
- return :model_not_ready if status.is_a?(::Integer) && status >= 500 &&
1108
- model_not_ready_signal?(error: error)
1109
-
1110
- status_kind(status)
1111
- end
1112
-
1113
- def status_kind(status)
1114
- case status
1115
- when 401 then :authentication
1116
- when 403 then :authorization
1117
- when 404 then :model_missing
1118
- when 429 then :rate_limited
1119
- when 503, 529 then :overloaded
1120
- when 400...500 then :invalid_request
1121
- else :provider_error
1122
- end
1123
- end
1124
-
1125
- # Returns true only when the Gemini API response body explicitly
1126
- # carries "status":"UNAVAILABLE" — the flat service-level
1127
- # unavailability signal distinct from throttling
1128
- # (RESOURCE_EXHAUSTED) or model loading.
1129
- def explicit_service_unavailable?(error:)
1130
- body = response_body_string(error)
1131
- return false if body.nil?
1132
-
1133
- (body.include?('"status":"UNAVAILABLE"') || body.include?('"status": "UNAVAILABLE"')) &&
1134
- !body.include?('RESOURCE_EXHAUSTED')
1135
- end
1136
-
1137
- def model_not_ready_signal?(error:)
1138
- body = response_body_string(error)&.downcase
1139
- body.to_s.include?('model not ready') || body.to_s.include?('model is still loading')
1140
- end
1141
-
1142
- # Reads the body from every real Faraday error shape: Faraday::Env
1143
- # (Faraday 2.x — a Struct, NOT a Hash, which is why an
1144
- # is_a?(Hash) gate here is dead in production), Faraday::Response
1145
- # (lex-llm ErrorMiddleware), or the plain response Hash (Faraday
1146
- # RaiseError middleware / Faraday 1.x).
1147
- def response_body_string(error)
1148
- response = error.respond_to?(:response) ? error.response : nil
1149
- return nil unless response
1150
-
1151
- body = response.respond_to?(:body) ? response.body : (response[:body] if response.respond_to?(:[]))
1152
- return body if body.is_a?(String)
1153
-
1154
- body && ::JSON.generate(body)
1155
- end
1156
-
1157
- def dispatch_status(error)
1158
- return error.response_status if error.respond_to?(:response_status) && error.response_status
1159
-
1160
- response = error.respond_to?(:response) ? error.response : nil
1161
- response.respond_to?(:status) ? response.status : nil
1162
- end
1163
- end
1164
- end
1165
- end
1166
- end
1167
- end
1168
- end