lex-apollo 0.4.30 → 0.4.45
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 +125 -0
- data/README.md +113 -18
- data/lib/legion/extensions/apollo/actors/contradiction_scanner.rb +2 -38
- 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 +5 -19
- 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 +116 -51
- 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 -63
- data/lib/legion/extensions/apollo/helpers/confidence.rb +9 -53
- 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 +107 -67
- 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 +67 -109
- 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 +110 -0
- data/lib/legion/extensions/apollo/runners/expertise.rb +58 -29
- data/lib/legion/extensions/apollo/runners/gas.rb +165 -144
- data/lib/legion/extensions/apollo/runners/knowledge.rb +349 -371
- data/lib/legion/extensions/apollo/runners/maintenance.rb +242 -56
- data/lib/legion/extensions/apollo/runners/query_response.rb +108 -0
- data/lib/legion/extensions/apollo/runners/request.rb +51 -47
- 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 +20 -0
- data/lib/legion/extensions/apollo/version.rb +1 -1
- data/lib/legion/extensions/apollo.rb +26 -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 +250 -28
- data/spec/legion/extensions/apollo/contradiction_spec.rb +23 -54
- data/spec/legion/extensions/apollo/gaia_integration_spec.rb +10 -21
- data/spec/legion/extensions/apollo/helpers/capability_spec.rb +26 -29
- 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 +88 -80
- 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 +98 -71
- data/spec/legion/extensions/apollo/runners/corroboration_integration_spec.rb +220 -0
- 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 +124 -0
- data/spec/legion/extensions/apollo/runners/expertise_spec.rb +75 -79
- data/spec/legion/extensions/apollo/runners/gas_anticipate_spec.rb +15 -85
- data/spec/legion/extensions/apollo/runners/gas_deposit_integration_spec.rb +108 -0
- data/spec/legion/extensions/apollo/runners/gas_relate_spec.rb +45 -87
- data/spec/legion/extensions/apollo/runners/gas_spec.rb +51 -83
- data/spec/legion/extensions/apollo/runners/gas_synthesize_spec.rb +17 -84
- data/spec/legion/extensions/apollo/runners/ingest_transaction_integration_spec.rb +246 -0
- data/spec/legion/extensions/apollo/runners/knowledge_scope_integration_spec.rb +130 -0
- data/spec/legion/extensions/apollo/runners/knowledge_spec.rb +332 -683
- data/spec/legion/extensions/apollo/runners/lifecycle_integration_spec.rb +174 -0
- data/spec/legion/extensions/apollo/runners/maintenance_spec.rb +42 -160
- 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 +146 -107
- 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/spec_helper.rb +13 -15
- metadata +71 -13
- data/lib/legion/extensions/apollo/helpers/entity_watchdog.rb +0 -91
- 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/gas_subscriber_spec.rb +0 -49
- 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,38 +1,110 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
require 'legion/json'
|
|
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'
|
|
6
13
|
|
|
7
14
|
module Legion
|
|
8
15
|
module Extensions
|
|
9
16
|
module Apollo
|
|
10
17
|
module Runners
|
|
11
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
|
+
|
|
12
30
|
def force_decay(factor: Legion::Extensions::Apollo.settings[:maintenance][:force_decay_factor], **)
|
|
13
|
-
{ action: :force_decay, factor: factor }
|
|
31
|
+
return { action: :force_decay, factor: factor } if data_model_entry.nil?
|
|
32
|
+
return { success: false, error: 'invalid_factor' } unless factor.is_a?(Numeric) && factor.real? && factor.finite? && factor.between?(0.0, 1.0)
|
|
33
|
+
|
|
34
|
+
decayed = data_model_entry
|
|
35
|
+
.exclude(status: 'archived')
|
|
36
|
+
.update(confidence: Sequel[:confidence] * factor)
|
|
37
|
+
{ success: true, decayed: decayed, factor: factor }
|
|
38
|
+
rescue Sequel::Error => e
|
|
39
|
+
handle_exception(e, level: :error, operation: 'apollo.maintenance.force_decay')
|
|
40
|
+
{ success: false, decayed: 0, error: e.message }
|
|
14
41
|
end
|
|
15
42
|
|
|
16
|
-
def archive_stale(days:
|
|
17
|
-
{ 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?
|
|
45
|
+
return { success: false, error: 'invalid_days' } unless days.is_a?(Numeric) && days.real? && days.finite? && days >= 0
|
|
46
|
+
|
|
47
|
+
now = Time.now
|
|
48
|
+
cutoff = now - (days * 86_400)
|
|
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)
|
|
53
|
+
{ success: true, archived: archived, days: days }
|
|
54
|
+
rescue Sequel::Error => e
|
|
55
|
+
handle_exception(e, level: :error, operation: 'apollo.maintenance.archive_stale')
|
|
56
|
+
{ success: false, archived: 0, error: e.message }
|
|
18
57
|
end
|
|
19
58
|
|
|
20
59
|
def resolve_dispute(entry_id:, resolution:, **)
|
|
21
|
-
{ action: :resolve_dispute, entry_id: entry_id, resolution: resolution }
|
|
60
|
+
return { action: :resolve_dispute, entry_id: entry_id, resolution: resolution } if data_model_entry.nil?
|
|
61
|
+
|
|
62
|
+
target_status = case resolution.to_s
|
|
63
|
+
when 'accept', 'keep' then 'confirmed'
|
|
64
|
+
when 'reject' then 'archived'
|
|
65
|
+
end
|
|
66
|
+
return { success: false, error: 'invalid_resolution', entry_id: entry_id } unless target_status
|
|
67
|
+
|
|
68
|
+
entry_model = data_model_entry
|
|
69
|
+
entry_model.db.transaction do
|
|
70
|
+
entry = entry_model.for_update.with_pk(entry_id)
|
|
71
|
+
next({ success: false, error: 'entry_not_found', entry_id: entry_id }) unless entry
|
|
72
|
+
next({ success: false, error: 'entry_not_disputed', entry_id: entry.id, status: entry.status }) unless entry.status == 'disputed'
|
|
73
|
+
|
|
74
|
+
context = entry[:source_context]
|
|
75
|
+
context = Legion::JSON.load(context) if context.is_a?(String)
|
|
76
|
+
context ||= {}
|
|
77
|
+
raise Sequel::Error, 'invalid_source_context' unless context.respond_to?(:transform_keys)
|
|
78
|
+
|
|
79
|
+
context = context.transform_keys(&:to_sym)
|
|
80
|
+
now = Time.now
|
|
81
|
+
updates = { status: target_status, updated_at: now,
|
|
82
|
+
source_context: Legion::JSON.dump(context.merge(dispute_resolution: resolution.to_s)) }
|
|
83
|
+
updates[:confirmed_at] = now if target_status == 'confirmed'
|
|
84
|
+
entry.update(updates)
|
|
85
|
+
{ success: true, entry_id: entry.id, status: target_status, resolution: resolution }
|
|
86
|
+
end
|
|
87
|
+
rescue Sequel::Error, Legion::JSON::ParseError => e
|
|
88
|
+
handle_exception(e, level: :error, operation: 'apollo.maintenance.resolve_dispute')
|
|
89
|
+
{ success: false, error: e.message, entry_id: entry_id }
|
|
22
90
|
end
|
|
23
91
|
|
|
24
92
|
def run_decay_cycle(alpha: nil, min_confidence: nil, **)
|
|
25
|
-
alpha ||=
|
|
26
|
-
min_confidence ||=
|
|
27
|
-
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]
|
|
28
96
|
|
|
29
97
|
log.debug("Apollo Maintenance.run_decay_cycle alpha=#{alpha} min_confidence=#{min_confidence} min_age_hours=#{min_age_hours}")
|
|
30
|
-
unless
|
|
98
|
+
unless Legion::Data.connection
|
|
31
99
|
log.warn('Apollo Maintenance.run_decay_cycle skipped: apollo_data_not_available')
|
|
32
|
-
return { decayed: 0, archived: 0 }
|
|
100
|
+
return { success: false, decayed: 0, archived: 0, error: 'apollo_data_not_available' }
|
|
33
101
|
end
|
|
34
102
|
|
|
35
103
|
conn = Legion::Data.connection
|
|
104
|
+
if conn.database_type == :sqlite
|
|
105
|
+
return maintenance_decay_sqlite_entries(db: conn, alpha: alpha, min_confidence: min_confidence,
|
|
106
|
+
min_age_hours: min_age_hours)
|
|
107
|
+
end
|
|
36
108
|
|
|
37
109
|
age_days_expr = Sequel.lit(
|
|
38
110
|
'GREATEST(EXTRACT(EPOCH FROM (NOW() - COALESCE(updated_at, created_at))) / 86400.0, 1.0)'
|
|
@@ -58,79 +130,193 @@ module Legion
|
|
|
58
130
|
.exclude(status: 'archived')
|
|
59
131
|
.update(status: 'archived')
|
|
60
132
|
|
|
61
|
-
{ decayed: decayed, archived: archived, alpha: alpha, threshold: min_confidence,
|
|
133
|
+
{ success: true, decayed: decayed, archived: archived, alpha: alpha, threshold: min_confidence,
|
|
62
134
|
min_age_hours: min_age_hours }
|
|
63
135
|
.tap { |result| log.info("Apollo Maintenance.run_decay_cycle decayed=#{result[:decayed]} archived=#{result[:archived]} alpha=#{alpha} threshold=#{min_confidence}") } # rubocop:disable Layout/LineLength
|
|
64
136
|
rescue Sequel::Error => e
|
|
65
137
|
handle_exception(e, level: :error, operation: 'apollo.maintenance.run_decay_cycle')
|
|
66
|
-
{ decayed: 0, archived: 0, error: e.message }
|
|
138
|
+
{ success: false, decayed: 0, archived: 0, error: e.message }
|
|
67
139
|
end
|
|
68
140
|
|
|
69
|
-
def check_corroboration(**)
|
|
70
|
-
|
|
71
|
-
|
|
141
|
+
def check_corroboration(**)
|
|
142
|
+
entry_model = data_model_entry
|
|
143
|
+
relation_model = data_model_relation
|
|
144
|
+
unless entry_model && relation_model
|
|
145
|
+
missing = []
|
|
146
|
+
missing << 'entry' unless entry_model
|
|
147
|
+
missing << 'relation' unless relation_model
|
|
148
|
+
log.warn("Apollo Maintenance.check_corroboration skipped: apollo_data_not_available missing=#{missing.join(',')}")
|
|
72
149
|
return { success: false, error: 'apollo_data_not_available' }
|
|
73
150
|
end
|
|
74
151
|
|
|
75
|
-
candidates =
|
|
76
|
-
|
|
77
|
-
log.debug("Apollo Maintenance.check_corroboration candidates=#{candidates.size} confirmed=#{
|
|
152
|
+
candidates = entry_model.where(status: 'candidate').exclude(embedding: nil).exclude(embedding_space_id: nil).order(:id).limit(100).all
|
|
153
|
+
confirmed_ids = entry_model.where(status: 'confirmed').select_map(:id)
|
|
154
|
+
log.debug("Apollo Maintenance.check_corroboration candidates=#{candidates.size} confirmed=#{confirmed_ids.size}")
|
|
78
155
|
|
|
79
156
|
promoted = 0
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
next unless conf.content_type == candidate.content_type
|
|
84
|
-
|
|
85
|
-
sim = Helpers::Similarity.cosine_similarity(
|
|
86
|
-
vec_a: candidate.embedding, vec_b: conf.embedding
|
|
87
|
-
)
|
|
88
|
-
Helpers::Similarity.above_corroboration_threshold?(similarity: sim)
|
|
89
|
-
end
|
|
90
|
-
|
|
157
|
+
candidates.each_with_index do |candidate, index|
|
|
158
|
+
match = maintenance_corroboration_match_for(candidate: candidate, evidence_ids: confirmed_ids) ||
|
|
159
|
+
maintenance_bootstrap_match_for(candidate: candidate, candidates: candidates, candidate_index: index)
|
|
91
160
|
next unless match
|
|
92
161
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
both_known = known_provider?(candidate_provider) && known_provider?(match_provider)
|
|
96
|
-
next if both_known && candidate_provider == match_provider
|
|
97
|
-
|
|
98
|
-
candidate_channel = candidate.respond_to?(:source_channel) ? candidate.source_channel : nil
|
|
99
|
-
match_channel = match.respond_to?(:source_channel) ? match.source_channel : nil
|
|
100
|
-
next if candidate_channel && match_channel && candidate_channel == match_channel
|
|
101
|
-
|
|
102
|
-
candidate.update(
|
|
162
|
+
bootstrap = !confirmed_ids.include?(match.id)
|
|
163
|
+
updates = {
|
|
103
164
|
status: 'confirmed',
|
|
104
165
|
confirmed_at: Time.now,
|
|
105
|
-
confidence:
|
|
166
|
+
confidence: confidence_apply_corroboration_boost(confidence: candidate.confidence),
|
|
106
167
|
updated_at: Time.now
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
168
|
+
}
|
|
169
|
+
updates[:source_context] = maintenance_bootstrap_confirmation_context(entry: candidate) if bootstrap
|
|
170
|
+
entry_model.db.transaction do
|
|
171
|
+
candidate.update(updates)
|
|
172
|
+
relation_model.create(
|
|
173
|
+
from_entry_id: candidate.id,
|
|
174
|
+
to_entry_id: match.id,
|
|
175
|
+
relation_type: 'similar_to',
|
|
176
|
+
source_agent: 'system:corroboration',
|
|
177
|
+
weight: Legion::Extensions::Apollo.settings[:corroboration][:relation_weight]
|
|
178
|
+
)
|
|
179
|
+
end
|
|
117
180
|
promoted += 1
|
|
118
181
|
end
|
|
119
182
|
|
|
120
183
|
{ success: true, promoted: promoted, scanned: candidates.size }
|
|
121
184
|
.tap { |result| log.info("Apollo Maintenance.check_corroboration scanned=#{result[:scanned]} promoted=#{result[:promoted]}") }
|
|
122
|
-
rescue Sequel::Error => e
|
|
185
|
+
rescue Sequel::Error, Legion::JSON::ParseError => e
|
|
123
186
|
handle_exception(e, level: :error, operation: 'apollo.maintenance.check_corroboration')
|
|
124
187
|
{ success: false, error: e.message }
|
|
125
188
|
end
|
|
126
189
|
|
|
190
|
+
def reembed_entries(limit: 100, after_id: nil, from_space_id: nil, legacy_only: true, **routing)
|
|
191
|
+
return { success: false, error: 'apollo_data_not_available' } if data_model_entry.nil?
|
|
192
|
+
return { success: false, error: 'invalid_limit' } unless limit.is_a?(Integer) && limit.between?(1, 1000)
|
|
193
|
+
return { success: false, error: 'invalid_legacy_only' } unless [true, false].include?(legacy_only)
|
|
194
|
+
|
|
195
|
+
entry_model = data_model_entry
|
|
196
|
+
entries = entry_model.exclude(status: 'archived')
|
|
197
|
+
entries = entries.where(embedding_space_id: nil) if legacy_only
|
|
198
|
+
entries = entries.where(embedding_space_id: from_space_id) if from_space_id
|
|
199
|
+
entries = entries.where(Sequel[:id] > after_id) unless after_id.nil?
|
|
200
|
+
batch = entries.order(:id).limit(limit).all
|
|
201
|
+
routing = routing.slice(:provider, :model, :instance, :dimensions)
|
|
202
|
+
updated = 0
|
|
203
|
+
skipped = 0
|
|
204
|
+
failures = []
|
|
205
|
+
batch.each do |entry|
|
|
206
|
+
document = Legion::Extensions::Apollo::Runners::Embedding.generate(
|
|
207
|
+
text: entry.content, task: :document, **routing
|
|
208
|
+
)
|
|
209
|
+
changed = entry_model.where(id: entry.id, content: entry.content).exclude(status: 'archived').update(
|
|
210
|
+
embedding: storage_serialize_embedding(db: entry_model.db, vector: document[:vector]),
|
|
211
|
+
embedding_provenance: storage_serialize_provenance(db: entry_model.db, provenance: document[:provenance]),
|
|
212
|
+
embedding_space_id: document[:provenance][:space_id], embedding_dimensions: document[:vector].length
|
|
213
|
+
)
|
|
214
|
+
changed.positive? ? updated += 1 : skipped += 1
|
|
215
|
+
rescue Sequel::Error, Legion::LLM::LLMError, Legion::Extensions::Apollo::Helpers::Embedding::Error => e
|
|
216
|
+
handle_exception(e, level: :error, operation: 'apollo.maintenance.reembed_entries', entry_id: entry.id)
|
|
217
|
+
failures << { entry_id: entry.id, error: e.message }
|
|
218
|
+
end
|
|
219
|
+
{ success: failures.empty?, scanned: batch.size, updated: updated, skipped: skipped,
|
|
220
|
+
failures: failures, next_after_id: batch.size == limit ? batch.last.id : nil }
|
|
221
|
+
rescue Sequel::Error => e
|
|
222
|
+
handle_exception(e, level: :error, operation: 'apollo.maintenance.reembed_entries')
|
|
223
|
+
{ success: false, error: e.message }
|
|
224
|
+
end
|
|
225
|
+
|
|
127
226
|
private
|
|
128
227
|
|
|
129
|
-
def
|
|
130
|
-
|
|
228
|
+
def maintenance_decay_sqlite_entries(db:, alpha:, min_confidence:, min_age_hours:, **)
|
|
229
|
+
now = Time.now
|
|
230
|
+
cutoff = now - (min_age_hours * 3600)
|
|
231
|
+
entries = db[:apollo_entries].exclude(status: 'archived')
|
|
232
|
+
.where(Sequel.function(:coalesce, :updated_at, :created_at) < cutoff)
|
|
233
|
+
decayed = 0
|
|
234
|
+
archived = 0
|
|
235
|
+
db.transaction do
|
|
236
|
+
entries.order(:id).paged_each(rows_per_fetch: 500, strategy: :filter) do |entry|
|
|
237
|
+
timestamp = entry[:updated_at] || entry[:created_at]
|
|
238
|
+
age_days = [(now - timestamp.to_time) / 86_400.0, 1.0].max
|
|
239
|
+
confidence = entry[:confidence].to_f * ((age_days / (age_days + 1.0))**alpha)
|
|
240
|
+
updates = { confidence: confidence }
|
|
241
|
+
if confidence < min_confidence
|
|
242
|
+
updates[:status] = 'archived'
|
|
243
|
+
archived += 1
|
|
244
|
+
end
|
|
245
|
+
db[:apollo_entries].where(id: entry[:id]).update(updates)
|
|
246
|
+
decayed += 1
|
|
247
|
+
end
|
|
248
|
+
end
|
|
249
|
+
{ success: true, decayed: decayed, archived: archived, alpha: alpha, threshold: min_confidence, min_age_hours: min_age_hours }
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
def maintenance_corroboration_match_for(candidate:, evidence_ids:, **)
|
|
253
|
+
return nil if evidence_ids.empty?
|
|
254
|
+
|
|
255
|
+
scope = candidate.access_scope || 'global'
|
|
256
|
+
return nil if scope != 'global' && candidate.identity_principal_id.nil?
|
|
257
|
+
|
|
258
|
+
provenance = embedding_parse_provenance(value: candidate[:embedding_provenance])
|
|
259
|
+
vector = similarity_parse_vector(vector: candidate.embedding)
|
|
260
|
+
return nil unless embedding_valid?(vector: vector, provenance: provenance, task: :document)
|
|
261
|
+
|
|
262
|
+
evidence = data_model_entry
|
|
263
|
+
.where(id: evidence_ids, content_type: candidate.content_type,
|
|
264
|
+
knowledge_domain: candidate.knowledge_domain, access_scope: scope,
|
|
265
|
+
embedding_space_id: provenance[:space_id], embedding_dimensions: provenance[:dimensions])
|
|
266
|
+
.exclude(embedding: nil)
|
|
267
|
+
if scope != 'global'
|
|
268
|
+
evidence = evidence.where(
|
|
269
|
+
Sequel.lit(graph_access_scope_sql,
|
|
270
|
+
requesting_principal_id: candidate.identity_principal_id)
|
|
271
|
+
)
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
evidence.limit(500).find { |entry| maintenance_corroborates?(candidate: candidate, entry: entry) }
|
|
131
275
|
end
|
|
132
276
|
|
|
133
|
-
|
|
277
|
+
def maintenance_bootstrap_match_for(candidate:, candidates:, candidate_index:)
|
|
278
|
+
evidence_ids = candidates.drop(candidate_index + 1).map(&:id)
|
|
279
|
+
maintenance_corroboration_match_for(candidate: candidate, evidence_ids: evidence_ids)
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
def maintenance_corroborates?(candidate:, entry:, **)
|
|
283
|
+
return false if candidate.id == entry.id
|
|
284
|
+
return false if maintenance_bootstrap_confirmation?(entry: entry)
|
|
285
|
+
|
|
286
|
+
both_known = maintenance_known_provider?(candidate.source_provider) && maintenance_known_provider?(entry.source_provider)
|
|
287
|
+
return false if both_known && candidate.source_provider == entry.source_provider
|
|
288
|
+
return false if candidate.source_channel && candidate.source_channel == entry.source_channel
|
|
289
|
+
|
|
290
|
+
provenance = embedding_parse_provenance(value: candidate[:embedding_provenance])
|
|
291
|
+
evidence_provenance = embedding_parse_provenance(value: entry[:embedding_provenance])
|
|
292
|
+
vector = similarity_parse_vector(vector: entry.embedding)
|
|
293
|
+
return false unless embedding_valid?(vector: vector, provenance: evidence_provenance, task: :document)
|
|
294
|
+
return false unless embedding_compatible?(left: provenance, right: evidence_provenance)
|
|
295
|
+
|
|
296
|
+
similarity = similarity_cosine(vec_a: candidate.embedding, vec_b: entry.embedding)
|
|
297
|
+
similarity_above_corroboration_threshold?(similarity: similarity)
|
|
298
|
+
end
|
|
299
|
+
|
|
300
|
+
def maintenance_bootstrap_confirmation_context(entry:, **)
|
|
301
|
+
context = entry[:source_context]
|
|
302
|
+
context = Legion::JSON.load(context) if context.is_a?(String)
|
|
303
|
+
context ||= {}
|
|
304
|
+
raise Sequel::Error, 'invalid_source_context' unless context.respond_to?(:transform_keys)
|
|
305
|
+
|
|
306
|
+
Legion::JSON.dump(context.transform_keys(&:to_sym).merge(corroboration_mode: 'bootstrap'))
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
def maintenance_bootstrap_confirmation?(entry:, **)
|
|
310
|
+
return false unless entry.status == 'confirmed'
|
|
311
|
+
|
|
312
|
+
context = entry[:source_context]
|
|
313
|
+
context = Legion::JSON.load(context) if context.is_a?(String)
|
|
314
|
+
context.respond_to?(:[]) && (context[:corroboration_mode] || context['corroboration_mode']) == 'bootstrap'
|
|
315
|
+
end
|
|
316
|
+
|
|
317
|
+
def maintenance_known_provider?(provider)
|
|
318
|
+
!provider.nil? && !provider.to_s.empty? && provider.to_s != 'unknown'
|
|
319
|
+
end
|
|
134
320
|
end
|
|
135
321
|
end
|
|
136
322
|
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,64 +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
|
-
|
|
15
|
+
include Legion::Transport::Helper
|
|
16
|
+
extend Legion::Extensions::Apollo::Helpers::DataModels
|
|
12
17
|
extend self
|
|
13
18
|
|
|
14
19
|
def self.data_required?
|
|
15
20
|
false
|
|
16
21
|
end
|
|
17
22
|
|
|
18
|
-
def query(text:, limit:
|
|
23
|
+
def query(text:, limit: settings[:query][:default_limit], min_confidence: settings[:query][:default_min_confidence], tags: nil,
|
|
19
24
|
domain: nil, agent_id: 'unknown', **)
|
|
20
|
-
if
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
elsif
|
|
24
|
-
|
|
25
|
-
|
|
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, **)
|
|
26
31
|
else
|
|
27
32
|
{ success: false, error: :no_path_available }
|
|
28
33
|
end
|
|
29
34
|
end
|
|
30
35
|
|
|
31
|
-
def retrieve(text:, limit: 5, min_confidence:
|
|
32
|
-
if
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
elsif
|
|
36
|
-
|
|
37
|
-
|
|
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, **)
|
|
38
43
|
else
|
|
39
44
|
{ success: false, error: :no_path_available }
|
|
40
45
|
end
|
|
41
46
|
end
|
|
42
47
|
|
|
43
|
-
def ingest(content:, content_type:, tags: [], source_agent: 'unknown', **)
|
|
44
|
-
if
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
elsif
|
|
48
|
-
|
|
49
|
-
|
|
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)
|
|
50
55
|
else
|
|
51
56
|
{ success: false, error: :no_path_available }
|
|
52
57
|
end
|
|
53
58
|
end
|
|
54
59
|
|
|
55
|
-
def traverse(entry_id:, depth:
|
|
56
|
-
if
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
elsif
|
|
60
|
-
|
|
61
|
-
|
|
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, **)
|
|
62
67
|
else
|
|
63
68
|
{ success: false, error: :no_path_available }
|
|
64
69
|
end
|
|
@@ -66,31 +71,30 @@ module Legion
|
|
|
66
71
|
|
|
67
72
|
private
|
|
68
73
|
|
|
69
|
-
def
|
|
70
|
-
|
|
71
|
-
|
|
74
|
+
def request_process_identity(options:, **)
|
|
75
|
+
return {} if options.key?(:identity_principal_id)
|
|
76
|
+
return {} unless defined?(Legion::Identity::Process)
|
|
72
77
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
Legion::Transport.connected?
|
|
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
|
|
82
86
|
end
|
|
83
87
|
|
|
84
|
-
def
|
|
85
|
-
Transport::Messages::Query.new(payload).publish
|
|
88
|
+
def request_publish_query(**payload)
|
|
89
|
+
Legion::Extensions::Apollo::Transport::Messages::Query.new(**payload).publish!
|
|
86
90
|
{ success: true, dispatched: :transport, payload: payload }
|
|
87
91
|
rescue StandardError => e
|
|
88
92
|
handle_exception(e, level: :warn, operation: 'apollo.request.publish_query')
|
|
89
93
|
{ success: false, error: e.message }
|
|
90
94
|
end
|
|
91
95
|
|
|
92
|
-
def
|
|
93
|
-
Transport::Messages::Ingest.new(payload).publish
|
|
96
|
+
def request_publish_ingest(**payload)
|
|
97
|
+
Legion::Extensions::Apollo::Transport::Messages::Ingest.new(**payload).publish!
|
|
94
98
|
{ success: true, dispatched: :transport, payload: payload }
|
|
95
99
|
rescue StandardError => e
|
|
96
100
|
handle_exception(e, level: :warn, operation: 'apollo.request.publish_ingest')
|