lex-apollo 0.4.44 → 0.4.49
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 +54 -0
- data/README.md +76 -14
- data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -41
- data/lib/legion/extensions/apollo/actors/corroboration_checker.rb +1 -1
- data/lib/legion/extensions/apollo/actors/decay.rb +1 -1
- data/lib/legion/extensions/apollo/actors/entity_watchdog.rb +2 -135
- data/lib/legion/extensions/apollo/actors/expertise_aggregator.rb +1 -1
- data/lib/legion/extensions/apollo/actors/gas_subscriber.rb +16 -16
- data/lib/legion/extensions/apollo/actors/ingest.rb +7 -7
- data/lib/legion/extensions/apollo/actors/query_responder.rb +25 -6
- data/lib/legion/extensions/apollo/actors/writeback_store.rb +10 -4
- data/lib/legion/extensions/apollo/actors/writeback_vectorize.rb +9 -35
- data/lib/legion/extensions/apollo/api.rb +96 -41
- data/lib/legion/extensions/apollo/client.rb +20 -9
- data/lib/legion/extensions/apollo/gaia_integration.rb +14 -12
- data/lib/legion/extensions/apollo/helpers/capability.rb +10 -51
- data/lib/legion/extensions/apollo/helpers/confidence.rb +8 -52
- data/lib/legion/extensions/apollo/helpers/data_models.rb +22 -38
- data/lib/legion/extensions/apollo/helpers/embedding.rb +118 -0
- data/lib/legion/extensions/apollo/helpers/graph_query.rb +99 -43
- data/lib/legion/extensions/apollo/helpers/similarity.rb +35 -26
- data/lib/legion/extensions/apollo/helpers/storage.rb +75 -0
- data/lib/legion/extensions/apollo/helpers/tag_normalizer.rb +4 -4
- data/lib/legion/extensions/apollo/helpers/writeback.rb +64 -102
- data/lib/legion/extensions/apollo/runners/contradictions.rb +126 -0
- data/lib/legion/extensions/apollo/runners/embedding.rb +60 -0
- data/lib/legion/extensions/apollo/runners/entity_extractor.rb +18 -10
- data/lib/legion/extensions/apollo/runners/entity_watchdog.rb +146 -0
- data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
- data/lib/legion/extensions/apollo/runners/gas.rb +120 -142
- data/lib/legion/extensions/apollo/runners/knowledge.rb +276 -346
- data/lib/legion/extensions/apollo/runners/maintenance.rb +154 -65
- data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
- data/lib/legion/extensions/apollo/runners/request.rb +51 -46
- data/lib/legion/extensions/apollo/runners/search.rb +88 -0
- data/lib/legion/extensions/apollo/runners/writeback.rb +57 -0
- data/lib/legion/extensions/apollo/transport/messages/ingest.rb +13 -9
- data/lib/legion/extensions/apollo/transport/messages/query.rb +4 -14
- data/lib/legion/extensions/apollo/transport/messages/writeback.rb +36 -14
- data/lib/legion/extensions/apollo/transport/subscription_delivery.rb +40 -0
- data/lib/legion/extensions/apollo/transport.rb +8 -5
- data/lib/legion/extensions/apollo/version.rb +1 -1
- data/lib/legion/extensions/apollo.rb +28 -24
- data/spec/legion/extensions/apollo/actors/gas_subscriber_spec.rb +9 -24
- data/spec/legion/extensions/apollo/actors/ingest_spec.rb +18 -21
- data/spec/legion/extensions/apollo/actors/query_responder_spec.rb +59 -0
- data/spec/legion/extensions/apollo/api_spec.rb +240 -8
- data/spec/legion/extensions/apollo/contradiction_spec.rb +28 -50
- data/spec/legion/extensions/apollo/gaia_integration_spec.rb +16 -21
- data/spec/legion/extensions/apollo/helpers/capability_spec.rb +24 -27
- data/spec/legion/extensions/apollo/helpers/confidence_spec.rb +16 -101
- data/spec/legion/extensions/apollo/helpers/embedding_spec.rb +33 -0
- data/spec/legion/extensions/apollo/helpers/graph_query_spec.rb +108 -0
- data/spec/legion/extensions/apollo/helpers/similarity_spec.rb +29 -12
- data/spec/legion/extensions/apollo/helpers/storage_spec.rb +59 -0
- data/spec/legion/extensions/apollo/helpers/tag_normalizer_spec.rb +20 -18
- data/spec/legion/extensions/apollo/helpers/writeback_spec.rb +73 -74
- data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +35 -6
- data/spec/legion/extensions/apollo/runners/decay_cycle_spec.rb +17 -10
- data/spec/legion/extensions/apollo/runners/embedding_spec.rb +99 -0
- data/spec/legion/extensions/apollo/runners/entity_extractor_spec.rb +32 -99
- data/spec/legion/extensions/apollo/runners/entity_watchdog_spec.rb +205 -0
- data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
- data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +14 -91
- data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +28 -11
- data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
- data/spec/legion/extensions/apollo/runners/gas_spec.rb +87 -77
- data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +14 -89
- data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +141 -9
- data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
- data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +314 -655
- data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +14 -5
- data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +48 -64
- data/spec/legion/extensions/apollo/runners/query_response_spec.rb +161 -0
- data/spec/legion/extensions/apollo/runners/reembedding_integration_spec.rb +227 -0
- data/spec/legion/extensions/apollo/runners/request_spec.rb +120 -98
- data/spec/legion/extensions/apollo/runners/search_spec.rb +155 -0
- data/spec/legion/extensions/apollo/runners/writeback_spec.rb +93 -0
- data/spec/legion/extensions/apollo/transport/messages/ingest_spec.rb +26 -51
- data/spec/legion/extensions/apollo/transport/messages/query_spec.rb +20 -61
- data/spec/legion/extensions/apollo/transport/messages/writeback_spec.rb +126 -47
- data/spec/legion/extensions/apollo/transport/subscription_delivery_spec.rb +41 -0
- data/spec/legion/extensions/apollo/transport_spec.rb +33 -0
- data/spec/spec_helper.rb +42 -13
- metadata +41 -13
- data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
- data/spec/legion/extensions/apollo/actors/contradiction_scanner_spec.rb +0 -38
- data/spec/legion/extensions/apollo/actors/decay_spec.rb +0 -45
- data/spec/legion/extensions/apollo/actors/entity_watchdog_spec.rb +0 -134
- data/spec/legion/extensions/apollo/actors/expertise_aggregator_spec.rb +0 -41
- data/spec/legion/extensions/apollo/actors/writeback_store_spec.rb +0 -42
- data/spec/legion/extensions/apollo/actors/writeback_vectorize_spec.rb +0 -102
- data/spec/legion/extensions/apollo/helpers/entity_watchdog_spec.rb +0 -64
|
@@ -1,39 +1,55 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require 'legion/json'
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
require 'legion/logging/helper'
|
|
5
|
+
require 'legion/settings/helper'
|
|
6
|
+
require 'legion/extensions/apollo/helpers/confidence'
|
|
7
|
+
require 'legion/extensions/apollo/helpers/data_models'
|
|
8
|
+
require 'legion/extensions/apollo/helpers/similarity'
|
|
9
|
+
require 'legion/extensions/apollo/helpers/graph_query'
|
|
10
|
+
require 'legion/extensions/apollo/helpers/embedding'
|
|
11
|
+
require 'legion/extensions/apollo/helpers/storage'
|
|
12
|
+
require 'legion/extensions/apollo/runners/embedding'
|
|
8
13
|
|
|
9
14
|
module Legion
|
|
10
15
|
module Extensions
|
|
11
16
|
module Apollo
|
|
12
17
|
module Runners
|
|
13
18
|
module Maintenance
|
|
19
|
+
include Legion::Logging::Helper
|
|
20
|
+
include Legion::JSON::Helper
|
|
21
|
+
include Legion::Settings::Helper
|
|
22
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
23
|
+
extend Legion::Extensions::Apollo::Helpers::Confidence
|
|
24
|
+
extend Legion::Extensions::Apollo::Helpers::Storage
|
|
25
|
+
extend Legion::Extensions::Apollo::Helpers::Embedding
|
|
26
|
+
extend Legion::Extensions::Apollo::Helpers::Similarity
|
|
27
|
+
extend Legion::Extensions::Apollo::Helpers::GraphQuery
|
|
28
|
+
extend self
|
|
29
|
+
|
|
14
30
|
def force_decay(factor: Legion::Extensions::Apollo.settings[:maintenance][:force_decay_factor], **)
|
|
15
|
-
return { action: :force_decay, factor: factor }
|
|
31
|
+
return { action: :force_decay, factor: factor } if data_model_entry.nil?
|
|
16
32
|
return { success: false, error: 'invalid_factor' } unless factor.is_a?(Numeric) && factor.real? && factor.finite? && factor.between?(0.0, 1.0)
|
|
17
33
|
|
|
18
|
-
decayed =
|
|
19
|
-
|
|
20
|
-
|
|
34
|
+
decayed = data_model_entry
|
|
35
|
+
.exclude(status: 'archived')
|
|
36
|
+
.update(confidence: Sequel[:confidence] * factor)
|
|
21
37
|
{ success: true, decayed: decayed, factor: factor }
|
|
22
38
|
rescue Sequel::Error => e
|
|
23
39
|
handle_exception(e, level: :error, operation: 'apollo.maintenance.force_decay')
|
|
24
40
|
{ success: false, decayed: 0, error: e.message }
|
|
25
41
|
end
|
|
26
42
|
|
|
27
|
-
def archive_stale(days:
|
|
28
|
-
return { action: :archive_stale, days: days }
|
|
43
|
+
def archive_stale(days: Legion::Extensions::Apollo.settings[:stale_days], **)
|
|
44
|
+
return { action: :archive_stale, days: days } if data_model_entry.nil?
|
|
29
45
|
return { success: false, error: 'invalid_days' } unless days.is_a?(Numeric) && days.real? && days.finite? && days >= 0
|
|
30
46
|
|
|
31
47
|
now = Time.now
|
|
32
48
|
cutoff = now - (days * 86_400)
|
|
33
|
-
archived =
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
49
|
+
archived = data_model_entry
|
|
50
|
+
.exclude(status: 'archived')
|
|
51
|
+
.where(Sequel.function(:coalesce, :updated_at, :created_at) < cutoff)
|
|
52
|
+
.update(status: 'archived', updated_at: now)
|
|
37
53
|
{ success: true, archived: archived, days: days }
|
|
38
54
|
rescue Sequel::Error => e
|
|
39
55
|
handle_exception(e, level: :error, operation: 'apollo.maintenance.archive_stale')
|
|
@@ -41,9 +57,7 @@ module Legion
|
|
|
41
57
|
end
|
|
42
58
|
|
|
43
59
|
def resolve_dispute(entry_id:, resolution:, **)
|
|
44
|
-
|
|
45
|
-
return { action: :resolve_dispute, entry_id: entry_id, resolution: resolution }
|
|
46
|
-
end
|
|
60
|
+
return { action: :resolve_dispute, entry_id: entry_id, resolution: resolution } if data_model_entry.nil?
|
|
47
61
|
|
|
48
62
|
target_status = case resolution.to_s
|
|
49
63
|
when 'accept', 'keep' then 'confirmed'
|
|
@@ -51,7 +65,7 @@ module Legion
|
|
|
51
65
|
end
|
|
52
66
|
return { success: false, error: 'invalid_resolution', entry_id: entry_id } unless target_status
|
|
53
67
|
|
|
54
|
-
entry_model =
|
|
68
|
+
entry_model = data_model_entry
|
|
55
69
|
entry_model.db.transaction do
|
|
56
70
|
entry = entry_model.for_update.with_pk(entry_id)
|
|
57
71
|
next({ success: false, error: 'entry_not_found', entry_id: entry_id }) unless entry
|
|
@@ -76,24 +90,30 @@ module Legion
|
|
|
76
90
|
end
|
|
77
91
|
|
|
78
92
|
def run_decay_cycle(alpha: nil, min_confidence: nil, **)
|
|
79
|
-
alpha ||=
|
|
80
|
-
min_confidence ||=
|
|
81
|
-
min_age_hours =
|
|
93
|
+
alpha ||= Legion::Extensions::Apollo.settings[:power_law_alpha]
|
|
94
|
+
min_confidence ||= Legion::Extensions::Apollo.settings[:decay_threshold]
|
|
95
|
+
min_age_hours = Legion::Extensions::Apollo.settings[:decay_min_age_hours]
|
|
96
|
+
cycle_alpha = alpha * (Legion::Extensions::Apollo.settings[:actors][:decay_interval].to_f / 86_400.0)
|
|
82
97
|
|
|
83
98
|
log.debug("Apollo Maintenance.run_decay_cycle alpha=#{alpha} min_confidence=#{min_confidence} min_age_hours=#{min_age_hours}")
|
|
84
|
-
unless
|
|
99
|
+
unless Legion::Data.connection
|
|
85
100
|
log.warn('Apollo Maintenance.run_decay_cycle skipped: apollo_data_not_available')
|
|
86
|
-
return { decayed: 0, archived: 0 }
|
|
101
|
+
return { success: false, decayed: 0, archived: 0, error: 'apollo_data_not_available' }
|
|
87
102
|
end
|
|
88
103
|
|
|
89
104
|
conn = Legion::Data.connection
|
|
105
|
+
if conn.database_type == :sqlite
|
|
106
|
+
return maintenance_decay_sqlite_entries(db: conn, alpha: alpha, cycle_alpha: cycle_alpha,
|
|
107
|
+
min_confidence: min_confidence,
|
|
108
|
+
min_age_hours: min_age_hours)
|
|
109
|
+
end
|
|
90
110
|
|
|
91
111
|
age_days_expr = Sequel.lit(
|
|
92
112
|
'GREATEST(EXTRACT(EPOCH FROM (NOW() - COALESCE(updated_at, created_at))) / 86400.0, 1.0)'
|
|
93
113
|
)
|
|
94
114
|
decay_factor = Sequel.lit(
|
|
95
115
|
'POWER(CAST(? AS double precision) / (CAST(? AS double precision) + 1.0), ?)',
|
|
96
|
-
age_days_expr, age_days_expr,
|
|
116
|
+
age_days_expr, age_days_expr, cycle_alpha
|
|
97
117
|
)
|
|
98
118
|
|
|
99
119
|
min_age_filter = Sequel.lit(
|
|
@@ -112,50 +132,53 @@ module Legion
|
|
|
112
132
|
.exclude(status: 'archived')
|
|
113
133
|
.update(status: 'archived')
|
|
114
134
|
|
|
115
|
-
{ decayed: decayed, archived: archived, alpha: alpha, threshold: min_confidence,
|
|
135
|
+
{ success: true, decayed: decayed, archived: archived, alpha: alpha, threshold: min_confidence,
|
|
116
136
|
min_age_hours: min_age_hours }
|
|
117
137
|
.tap { |result| log.info("Apollo Maintenance.run_decay_cycle decayed=#{result[:decayed]} archived=#{result[:archived]} alpha=#{alpha} threshold=#{min_confidence}") } # rubocop:disable Layout/LineLength
|
|
118
138
|
rescue Sequel::Error => e
|
|
119
139
|
handle_exception(e, level: :error, operation: 'apollo.maintenance.run_decay_cycle')
|
|
120
|
-
{ decayed: 0, archived: 0, error: e.message }
|
|
140
|
+
{ success: false, decayed: 0, archived: 0, error: e.message }
|
|
121
141
|
end
|
|
122
142
|
|
|
123
143
|
def check_corroboration(**)
|
|
124
|
-
|
|
144
|
+
entry_model = data_model_entry
|
|
145
|
+
relation_model = data_model_relation
|
|
146
|
+
unless entry_model && relation_model
|
|
125
147
|
missing = []
|
|
126
|
-
missing << 'entry' unless
|
|
127
|
-
missing << 'relation' unless
|
|
148
|
+
missing << 'entry' unless entry_model
|
|
149
|
+
missing << 'relation' unless relation_model
|
|
128
150
|
log.warn("Apollo Maintenance.check_corroboration skipped: apollo_data_not_available missing=#{missing.join(',')}")
|
|
129
151
|
return { success: false, error: 'apollo_data_not_available' }
|
|
130
152
|
end
|
|
131
153
|
|
|
132
|
-
|
|
133
|
-
candidates = entry_model.where(status: 'candidate').exclude(embedding: nil).order(:id).limit(100).all
|
|
154
|
+
candidates = entry_model.where(status: 'candidate').exclude(embedding: nil).exclude(embedding_space_id: nil).order(:id).limit(100).all
|
|
134
155
|
confirmed_ids = entry_model.where(status: 'confirmed').select_map(:id)
|
|
135
156
|
log.debug("Apollo Maintenance.check_corroboration candidates=#{candidates.size} confirmed=#{confirmed_ids.size}")
|
|
136
157
|
|
|
137
158
|
promoted = 0
|
|
138
159
|
candidates.each_with_index do |candidate, index|
|
|
139
|
-
match =
|
|
140
|
-
|
|
160
|
+
match = maintenance_corroboration_match_for(candidate: candidate, evidence_ids: confirmed_ids) ||
|
|
161
|
+
maintenance_bootstrap_match_for(candidate: candidate, candidates: candidates, candidate_index: index)
|
|
141
162
|
next unless match
|
|
142
163
|
|
|
143
164
|
bootstrap = !confirmed_ids.include?(match.id)
|
|
144
165
|
updates = {
|
|
145
166
|
status: 'confirmed',
|
|
146
167
|
confirmed_at: Time.now,
|
|
147
|
-
confidence:
|
|
168
|
+
confidence: confidence_apply_corroboration_boost(confidence: candidate.confidence),
|
|
148
169
|
updated_at: Time.now
|
|
149
170
|
}
|
|
150
|
-
updates[:source_context] =
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
171
|
+
updates[:source_context] = maintenance_bootstrap_confirmation_context(entry: candidate) if bootstrap
|
|
172
|
+
entry_model.db.transaction do
|
|
173
|
+
candidate.update(updates)
|
|
174
|
+
relation_model.create(
|
|
175
|
+
from_entry_id: candidate.id,
|
|
176
|
+
to_entry_id: match.id,
|
|
177
|
+
relation_type: 'similar_to',
|
|
178
|
+
source_agent: 'system:corroboration',
|
|
179
|
+
weight: Legion::Extensions::Apollo.settings[:corroboration][:relation_weight]
|
|
180
|
+
)
|
|
181
|
+
end
|
|
159
182
|
promoted += 1
|
|
160
183
|
end
|
|
161
184
|
|
|
@@ -166,46 +189,117 @@ module Legion
|
|
|
166
189
|
{ success: false, error: e.message }
|
|
167
190
|
end
|
|
168
191
|
|
|
192
|
+
def reembed_entries(limit: 100, after_id: nil, from_space_id: nil, legacy_only: true, **routing)
|
|
193
|
+
return { success: false, error: 'apollo_data_not_available' } if data_model_entry.nil?
|
|
194
|
+
return { success: false, error: 'invalid_limit' } unless limit.is_a?(Integer) && limit.between?(1, 1000)
|
|
195
|
+
return { success: false, error: 'invalid_legacy_only' } unless [true, false].include?(legacy_only)
|
|
196
|
+
|
|
197
|
+
entry_model = data_model_entry
|
|
198
|
+
entries = entry_model.exclude(status: 'archived')
|
|
199
|
+
entries = entries.where(embedding_space_id: nil) if legacy_only
|
|
200
|
+
entries = entries.where(embedding_space_id: from_space_id) if from_space_id
|
|
201
|
+
entries = entries.where(Sequel[:id] > after_id) unless after_id.nil?
|
|
202
|
+
batch = entries.order(:id).limit(limit).all
|
|
203
|
+
routing = routing.slice(:provider, :model, :instance, :dimensions)
|
|
204
|
+
updated = 0
|
|
205
|
+
skipped = 0
|
|
206
|
+
failures = []
|
|
207
|
+
batch.each do |entry|
|
|
208
|
+
document = Legion::Extensions::Apollo::Runners::Embedding.generate(
|
|
209
|
+
text: entry.content, task: :document, **routing
|
|
210
|
+
)
|
|
211
|
+
changed = entry_model.where(id: entry.id, content: entry.content).exclude(status: 'archived').update(
|
|
212
|
+
embedding: storage_serialize_embedding(db: entry_model.db, vector: document[:vector]),
|
|
213
|
+
embedding_provenance: storage_serialize_provenance(db: entry_model.db, provenance: document[:provenance]),
|
|
214
|
+
embedding_space_id: document[:provenance][:space_id], embedding_dimensions: document[:vector].length
|
|
215
|
+
)
|
|
216
|
+
changed.positive? ? updated += 1 : skipped += 1
|
|
217
|
+
rescue Sequel::Error, Legion::LLM::LLMError, Legion::Extensions::Apollo::Helpers::Embedding::Error => e
|
|
218
|
+
handle_exception(e, level: :error, operation: 'apollo.maintenance.reembed_entries', entry_id: entry.id)
|
|
219
|
+
failures << { entry_id: entry.id, error: e.message }
|
|
220
|
+
end
|
|
221
|
+
{ success: failures.empty?, scanned: batch.size, updated: updated, skipped: skipped,
|
|
222
|
+
failures: failures, next_after_id: batch.size == limit ? batch.last.id : nil }
|
|
223
|
+
rescue Sequel::Error => e
|
|
224
|
+
handle_exception(e, level: :error, operation: 'apollo.maintenance.reembed_entries')
|
|
225
|
+
{ success: false, error: e.message }
|
|
226
|
+
end
|
|
227
|
+
|
|
169
228
|
private
|
|
170
229
|
|
|
171
|
-
def
|
|
230
|
+
def maintenance_decay_sqlite_entries(db:, alpha:, cycle_alpha:, min_confidence:, min_age_hours:, **)
|
|
231
|
+
now = Time.now
|
|
232
|
+
cutoff = now - (min_age_hours * 3600)
|
|
233
|
+
entries = db[:apollo_entries].exclude(status: 'archived')
|
|
234
|
+
.where(Sequel.function(:coalesce, :updated_at, :created_at) < cutoff)
|
|
235
|
+
decayed = 0
|
|
236
|
+
archived = 0
|
|
237
|
+
db.transaction do
|
|
238
|
+
entries.order(:id).paged_each(rows_per_fetch: 500, strategy: :filter) do |entry|
|
|
239
|
+
timestamp = entry[:updated_at] || entry[:created_at]
|
|
240
|
+
age_days = [(now - timestamp.to_time) / 86_400.0, 1.0].max
|
|
241
|
+
confidence = entry[:confidence].to_f * ((age_days / (age_days + 1.0))**cycle_alpha)
|
|
242
|
+
updates = { confidence: confidence }
|
|
243
|
+
if confidence < min_confidence
|
|
244
|
+
updates[:status] = 'archived'
|
|
245
|
+
archived += 1
|
|
246
|
+
end
|
|
247
|
+
db[:apollo_entries].where(id: entry[:id]).update(updates)
|
|
248
|
+
decayed += 1
|
|
249
|
+
end
|
|
250
|
+
end
|
|
251
|
+
{ success: true, decayed: decayed, archived: archived, alpha: alpha, threshold: min_confidence, min_age_hours: min_age_hours }
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
def maintenance_corroboration_match_for(candidate:, evidence_ids:, **)
|
|
172
255
|
return nil if evidence_ids.empty?
|
|
173
256
|
|
|
174
257
|
scope = candidate.access_scope || 'global'
|
|
175
258
|
return nil if scope != 'global' && candidate.identity_principal_id.nil?
|
|
176
259
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
260
|
+
provenance = embedding_parse_provenance(value: candidate[:embedding_provenance])
|
|
261
|
+
vector = similarity_parse_vector(vector: candidate.embedding)
|
|
262
|
+
return nil unless embedding_valid?(vector: vector, provenance: provenance, task: :document)
|
|
263
|
+
|
|
264
|
+
evidence = data_model_entry
|
|
265
|
+
.where(id: evidence_ids, content_type: candidate.content_type,
|
|
266
|
+
knowledge_domain: candidate.knowledge_domain, access_scope: scope,
|
|
267
|
+
embedding_space_id: provenance[:space_id], embedding_dimensions: provenance[:dimensions])
|
|
268
|
+
.exclude(embedding: nil)
|
|
181
269
|
if scope != 'global'
|
|
182
270
|
evidence = evidence.where(
|
|
183
|
-
Sequel.lit(
|
|
271
|
+
Sequel.lit(graph_access_scope_sql,
|
|
184
272
|
requesting_principal_id: candidate.identity_principal_id)
|
|
185
273
|
)
|
|
186
274
|
end
|
|
187
275
|
|
|
188
|
-
evidence.limit(500).find { |entry|
|
|
276
|
+
evidence.limit(500).find { |entry| maintenance_corroborates?(candidate: candidate, entry: entry) }
|
|
189
277
|
end
|
|
190
278
|
|
|
191
|
-
def
|
|
279
|
+
def maintenance_bootstrap_match_for(candidate:, candidates:, candidate_index:)
|
|
192
280
|
evidence_ids = candidates.drop(candidate_index + 1).map(&:id)
|
|
193
|
-
|
|
281
|
+
maintenance_corroboration_match_for(candidate: candidate, evidence_ids: evidence_ids)
|
|
194
282
|
end
|
|
195
283
|
|
|
196
|
-
def
|
|
284
|
+
def maintenance_corroborates?(candidate:, entry:, **)
|
|
197
285
|
return false if candidate.id == entry.id
|
|
198
|
-
return false if
|
|
286
|
+
return false if maintenance_bootstrap_confirmation?(entry: entry)
|
|
199
287
|
|
|
200
|
-
both_known =
|
|
288
|
+
both_known = maintenance_known_provider?(candidate.source_provider) && maintenance_known_provider?(entry.source_provider)
|
|
201
289
|
return false if both_known && candidate.source_provider == entry.source_provider
|
|
202
290
|
return false if candidate.source_channel && candidate.source_channel == entry.source_channel
|
|
203
291
|
|
|
204
|
-
|
|
205
|
-
|
|
292
|
+
provenance = embedding_parse_provenance(value: candidate[:embedding_provenance])
|
|
293
|
+
evidence_provenance = embedding_parse_provenance(value: entry[:embedding_provenance])
|
|
294
|
+
vector = similarity_parse_vector(vector: entry.embedding)
|
|
295
|
+
return false unless embedding_valid?(vector: vector, provenance: evidence_provenance, task: :document)
|
|
296
|
+
return false unless embedding_compatible?(left: provenance, right: evidence_provenance)
|
|
297
|
+
|
|
298
|
+
similarity = similarity_cosine(vec_a: candidate.embedding, vec_b: entry.embedding)
|
|
299
|
+
similarity_above_corroboration_threshold?(similarity: similarity)
|
|
206
300
|
end
|
|
207
301
|
|
|
208
|
-
def
|
|
302
|
+
def maintenance_bootstrap_confirmation_context(entry:, **)
|
|
209
303
|
context = entry[:source_context]
|
|
210
304
|
context = Legion::JSON.load(context) if context.is_a?(String)
|
|
211
305
|
context ||= {}
|
|
@@ -214,22 +308,17 @@ module Legion
|
|
|
214
308
|
Legion::JSON.dump(context.transform_keys(&:to_sym).merge(corroboration_mode: 'bootstrap'))
|
|
215
309
|
end
|
|
216
310
|
|
|
217
|
-
def
|
|
311
|
+
def maintenance_bootstrap_confirmation?(entry:, **)
|
|
218
312
|
return false unless entry.status == 'confirmed'
|
|
219
313
|
|
|
220
314
|
context = entry[:source_context]
|
|
221
315
|
context = Legion::JSON.load(context) if context.is_a?(String)
|
|
222
316
|
context.respond_to?(:[]) && (context[:corroboration_mode] || context['corroboration_mode']) == 'bootstrap'
|
|
223
|
-
rescue Legion::JSON::ParseError => e
|
|
224
|
-
handle_exception(e, level: :warn, operation: 'apollo.maintenance.bootstrap_confirmation')
|
|
225
|
-
true
|
|
226
317
|
end
|
|
227
318
|
|
|
228
|
-
def
|
|
319
|
+
def maintenance_known_provider?(provider)
|
|
229
320
|
!provider.nil? && !provider.to_s.empty? && provider.to_s != 'unknown'
|
|
230
321
|
end
|
|
231
|
-
|
|
232
|
-
include Legion::Extensions::Helpers::Lex if defined?(Legion::Extensions::Helpers::Lex)
|
|
233
322
|
end
|
|
234
323
|
end
|
|
235
324
|
end
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'legion/json'
|
|
4
|
+
require 'securerandom'
|
|
5
|
+
require 'timeout'
|
|
6
|
+
require 'legion/transport/helper'
|
|
7
|
+
require 'legion/extensions/apollo/runners/knowledge'
|
|
8
|
+
|
|
9
|
+
module Legion
|
|
10
|
+
module Extensions
|
|
11
|
+
module Apollo
|
|
12
|
+
module Runners
|
|
13
|
+
module QueryResponse
|
|
14
|
+
include Legion::Logging::Helper
|
|
15
|
+
include Legion::Transport::Helper
|
|
16
|
+
extend self
|
|
17
|
+
|
|
18
|
+
ACTIONS = { 'query' => :handle_query, 'retrieve' => :retrieve_relevant, 'traverse' => :handle_traverse }.freeze
|
|
19
|
+
|
|
20
|
+
def handle_request(action: 'query', reply_to: nil, correlation_id: nil, **request)
|
|
21
|
+
function = ACTIONS[action.to_s]
|
|
22
|
+
error = query_response_input_error(action: action, request: request) if function
|
|
23
|
+
result = if function.nil?
|
|
24
|
+
{ success: false, error: :invalid_action }
|
|
25
|
+
elsif error
|
|
26
|
+
{ success: false, error: :invalid_request, message: error }
|
|
27
|
+
else
|
|
28
|
+
request[:requesting_principal_id] ||= 0
|
|
29
|
+
Legion::Extensions::Apollo::Runners::Knowledge.public_send(function, **request)
|
|
30
|
+
end
|
|
31
|
+
query_response_publish(result: result, reply_to: reply_to, correlation_id: correlation_id) unless reply_to.nil?
|
|
32
|
+
result
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
private
|
|
36
|
+
|
|
37
|
+
def query_response_input_error(action:, request:, **)
|
|
38
|
+
input_error = if action.to_s == 'traverse'
|
|
39
|
+
query_response_traversal_error(request: request)
|
|
40
|
+
else
|
|
41
|
+
query_response_search_error(request: request)
|
|
42
|
+
end
|
|
43
|
+
return input_error if input_error
|
|
44
|
+
|
|
45
|
+
return 'tag_match must be any or all' if request.key?(:tag_match) && !%w[any all].include?(request[:tag_match].to_s)
|
|
46
|
+
return 'exclude_source_agents must be an array' if !request[:exclude_source_agents].nil? && !request[:exclude_source_agents].is_a?(Array)
|
|
47
|
+
|
|
48
|
+
principal = request[:requesting_principal_id]
|
|
49
|
+
return 'requesting_principal_id must be a nonnegative integer' if !principal.nil? && (!principal.is_a?(Integer) || principal.negative?)
|
|
50
|
+
|
|
51
|
+
nil
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def query_response_traversal_error(request:, **)
|
|
55
|
+
entry_id = request[:entry_id]
|
|
56
|
+
valid_id = (entry_id.is_a?(String) && !entry_id.empty?) || (entry_id.is_a?(Integer) && entry_id.positive?)
|
|
57
|
+
return 'entry_id must be a nonempty string or positive integer' unless valid_id
|
|
58
|
+
return 'depth must be a nonnegative integer' if request.key?(:depth) && (!request[:depth].is_a?(Integer) || request[:depth].negative?)
|
|
59
|
+
return 'relation_types must be an array' if !request[:relation_types].nil? && !request[:relation_types].is_a?(Array)
|
|
60
|
+
|
|
61
|
+
nil
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def query_response_search_error(request:, **)
|
|
65
|
+
return 'query must be a string' unless request[:query].is_a?(String)
|
|
66
|
+
return 'limit must be a positive integer' if request.key?(:limit) && (!request[:limit].is_a?(Integer) || !request[:limit].positive?)
|
|
67
|
+
|
|
68
|
+
if request.key?(:min_confidence)
|
|
69
|
+
confidence = request[:min_confidence]
|
|
70
|
+
return 'min_confidence must be between zero and one' unless confidence.is_a?(Numeric) && confidence.finite? && confidence.between?(0, 1)
|
|
71
|
+
end
|
|
72
|
+
nil
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def query_response_publish(result:, reply_to:, correlation_id:, **)
|
|
76
|
+
raise ArgumentError, 'reply_to must be a nonempty string' unless reply_to.is_a?(String) && !reply_to.empty?
|
|
77
|
+
|
|
78
|
+
channel = transport_channel
|
|
79
|
+
exchange = channel.default_exchange
|
|
80
|
+
message_id = SecureRandom.uuid
|
|
81
|
+
returned = false
|
|
82
|
+
exchange.on_return do |_delivery, properties, _payload|
|
|
83
|
+
returned = true if properties.message_id == message_id
|
|
84
|
+
end
|
|
85
|
+
confirmed = Timeout.timeout(5) do
|
|
86
|
+
channel.confirm_select unless channel.using_publisher_confirmations?
|
|
87
|
+
exchange.publish(Legion::JSON.dump(result), routing_key: reply_to, correlation_id: correlation_id,
|
|
88
|
+
message_id: message_id, content_type: 'application/json', content_encoding: 'identity', mandatory: true)
|
|
89
|
+
channel.wait_for_confirms
|
|
90
|
+
end
|
|
91
|
+
raise IOError, 'Apollo reply publication failed' unless confirmed == true && !returned
|
|
92
|
+
rescue Timeout::Error => e
|
|
93
|
+
handle_exception(e, level: :warn, operation: 'apollo.query_response.publish')
|
|
94
|
+
begin
|
|
95
|
+
Timeout.timeout(1) { channel.close if channel&.open? }
|
|
96
|
+
rescue StandardError => close_error
|
|
97
|
+
handle_exception(close_error, level: :warn, operation: 'apollo.query_response.close_channel')
|
|
98
|
+
end
|
|
99
|
+
raise
|
|
100
|
+
rescue StandardError => e
|
|
101
|
+
handle_exception(e, level: :warn, operation: 'apollo.query_response.publish')
|
|
102
|
+
raise
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
end
|
|
@@ -1,65 +1,69 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
require 'legion/transport'
|
|
4
|
+
require 'legion/extensions/apollo/transport/messages/query'
|
|
5
|
+
require 'legion/extensions/apollo/transport/messages/ingest'
|
|
6
|
+
require 'legion/extensions/apollo/helpers/data_models'
|
|
7
|
+
require 'legion/extensions/apollo/runners/knowledge'
|
|
5
8
|
module Legion
|
|
6
9
|
module Extensions
|
|
7
10
|
module Apollo
|
|
8
11
|
module Runners
|
|
9
12
|
module Request
|
|
13
|
+
include Legion::Settings::Helper
|
|
10
14
|
include Legion::Logging::Helper
|
|
11
|
-
include Legion::Transport::Helper
|
|
12
|
-
extend Legion::
|
|
15
|
+
include Legion::Transport::Helper
|
|
16
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
13
17
|
extend self
|
|
14
18
|
|
|
15
19
|
def self.data_required?
|
|
16
20
|
false
|
|
17
21
|
end
|
|
18
22
|
|
|
19
|
-
def query(text:, limit:
|
|
23
|
+
def query(text:, limit: settings[:query][:default_limit], min_confidence: settings[:query][:default_min_confidence], tags: nil,
|
|
20
24
|
domain: nil, agent_id: 'unknown', **)
|
|
21
|
-
if
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
elsif
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
if data_model_entry
|
|
26
|
+
Legion::Extensions::Apollo::Runners::Knowledge.handle_query(query: text, limit: limit, min_confidence: min_confidence,
|
|
27
|
+
tags: tags, domain: domain, agent_id: agent_id, **)
|
|
28
|
+
elsif transport_session_open?
|
|
29
|
+
request_publish_query(action: :query, query: text, limit: limit, min_confidence: min_confidence,
|
|
30
|
+
tags: tags, domain: domain, agent_id: agent_id, **)
|
|
27
31
|
else
|
|
28
32
|
{ success: false, error: :no_path_available }
|
|
29
33
|
end
|
|
30
34
|
end
|
|
31
35
|
|
|
32
|
-
def retrieve(text:, limit: 5, min_confidence:
|
|
33
|
-
if
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
elsif
|
|
37
|
-
|
|
38
|
-
|
|
36
|
+
def retrieve(text:, limit: 5, min_confidence: settings[:query][:default_min_confidence], tags: nil, domain: nil, **)
|
|
37
|
+
if data_model_entry
|
|
38
|
+
Legion::Extensions::Apollo::Runners::Knowledge.retrieve_relevant(query: text, limit: limit, min_confidence: min_confidence,
|
|
39
|
+
tags: tags, domain: domain, **)
|
|
40
|
+
elsif transport_session_open?
|
|
41
|
+
request_publish_query(action: :retrieve, query: text, limit: limit, min_confidence: min_confidence,
|
|
42
|
+
tags: tags, domain: domain, **)
|
|
39
43
|
else
|
|
40
44
|
{ success: false, error: :no_path_available }
|
|
41
45
|
end
|
|
42
46
|
end
|
|
43
47
|
|
|
44
|
-
def ingest(content:, content_type:, tags: [], source_agent: 'unknown', **)
|
|
45
|
-
if
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
elsif
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
def ingest(content:, content_type:, tags: [], source_agent: 'unknown', **options)
|
|
49
|
+
if data_model_entry
|
|
50
|
+
Legion::Extensions::Apollo::Runners::Knowledge.handle_ingest(content: content, content_type: content_type,
|
|
51
|
+
tags: tags, source_agent: source_agent, **options)
|
|
52
|
+
elsif transport_session_open?
|
|
53
|
+
request_publish_ingest(**request_process_identity(options: options), content: content, content_type: content_type,
|
|
54
|
+
tags: tags, source_agent: source_agent, **options)
|
|
51
55
|
else
|
|
52
56
|
{ success: false, error: :no_path_available }
|
|
53
57
|
end
|
|
54
58
|
end
|
|
55
59
|
|
|
56
|
-
def traverse(entry_id:, depth:
|
|
57
|
-
if
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
elsif
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
def traverse(entry_id:, depth: settings[:graph][:default_depth], relation_types: nil, agent_id: 'unknown', **)
|
|
61
|
+
if data_model_entry
|
|
62
|
+
Legion::Extensions::Apollo::Runners::Knowledge.handle_traverse(entry_id: entry_id, depth: depth,
|
|
63
|
+
relation_types: relation_types, agent_id: agent_id, **)
|
|
64
|
+
elsif transport_session_open?
|
|
65
|
+
request_publish_query(action: :traverse, entry_id: entry_id, depth: depth,
|
|
66
|
+
relation_types: relation_types, agent_id: agent_id, **)
|
|
63
67
|
else
|
|
64
68
|
{ success: false, error: :no_path_available }
|
|
65
69
|
end
|
|
@@ -67,29 +71,30 @@ module Legion
|
|
|
67
71
|
|
|
68
72
|
private
|
|
69
73
|
|
|
70
|
-
def
|
|
71
|
-
|
|
72
|
-
|
|
74
|
+
def request_process_identity(options:, **)
|
|
75
|
+
return {} if options.key?(:identity_principal_id)
|
|
76
|
+
return {} unless defined?(Legion::Identity::Process)
|
|
73
77
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
78
|
+
identity = {}
|
|
79
|
+
identity[:identity_principal_id] = Legion::Identity::Process.db_principal_id unless options.key?(:identity_principal_id)
|
|
80
|
+
identity[:identity_id] = Legion::Identity::Process.db_identity_id unless options.key?(:identity_id)
|
|
81
|
+
identity[:identity_canonical_name] = Legion::Identity::Process.canonical_name unless options.key?(:identity_canonical_name)
|
|
82
|
+
identity.compact
|
|
83
|
+
rescue StandardError => e
|
|
84
|
+
handle_exception(e, level: :warn, operation: 'apollo.request.process_identity')
|
|
85
|
+
raise
|
|
81
86
|
end
|
|
82
87
|
|
|
83
|
-
def
|
|
84
|
-
Transport::Messages::Query.new(**payload).publish
|
|
88
|
+
def request_publish_query(**payload)
|
|
89
|
+
Legion::Extensions::Apollo::Transport::Messages::Query.new(**payload).publish!
|
|
85
90
|
{ success: true, dispatched: :transport, payload: payload }
|
|
86
91
|
rescue StandardError => e
|
|
87
92
|
handle_exception(e, level: :warn, operation: 'apollo.request.publish_query')
|
|
88
93
|
{ success: false, error: e.message }
|
|
89
94
|
end
|
|
90
95
|
|
|
91
|
-
def
|
|
92
|
-
Transport::Messages::Ingest.new(**payload).publish
|
|
96
|
+
def request_publish_ingest(**payload)
|
|
97
|
+
Legion::Extensions::Apollo::Transport::Messages::Ingest.new(**payload).publish!
|
|
93
98
|
{ success: true, dispatched: :transport, payload: payload }
|
|
94
99
|
rescue StandardError => e
|
|
95
100
|
handle_exception(e, level: :warn, operation: 'apollo.request.publish_ingest')
|