Module: Legion::Apollo::Local

Extended by:
Logging::Helper
Defined in:
lib/legion/apollo/local.rb,
lib/legion/apollo/local/graph.rb

Overview

Node-local knowledge store backed by SQLite + FTS5. Mirrors Legion::Apollo's public API but stores locally.

Defined Under Namespace

Modules: Graph

Constant Summary collapse

MIGRATION_PATH =

rubocop:disable Metrics/ModuleLength

File.expand_path('local/migrations', __dir__).freeze
LIFECYCLE_MUTEX =
Mutex.new
WRITE_MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.graphObject



138
139
140
# File 'lib/legion/apollo/local.rb', line 138

def graph
  Legion::Apollo::Local::Graph
end

.ingest(content:, tags: [], access_scope: 'global', **opts) ⇒ Object

rubocop:disable Metrics/MethodLength



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/legion/apollo/local.rb', line 45

def ingest(content:, tags: [], access_scope: 'global', **opts) # rubocop:disable Metrics/MethodLength
  return not_started_error unless started?

  tags = normalize_tags_input(tags)
  WRITE_MUTEX.synchronize do
    ingest_without_lock(content: content, tags: tags,
                        **inject_identity_context(opts).merge(access_scope: access_scope))
  end
rescue StandardError => e
  handle_exception(
    e,
    level:          :error,
    operation:      'apollo.local.ingest',
    tags:           Array(tags).size,
    source_channel: opts[:source_channel]
  )
  { success: false, error: e.message }
end

.promote_to_global(tags:, min_confidence: 0.6) ⇒ Object

rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/legion/apollo/local.rb', line 168

def promote_to_global(tags:, min_confidence: 0.6) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
  return { success: false, error: :not_started } unless local_db_usable?(local_db_connection)

  tags = normalize_tags_input(tags)
  entries = query_by_tags(tags: tags)
  return entries unless entries[:success]

  unless entries[:results]&.any?
    log.info { "Apollo::Local promote_to_global skipped tag_count=#{tags.size} reason=no_entries" }
    return { success: true, promoted: 0 }
  end

  promoted = 0
  entries[:results].each do |entry|
    next if entry[:confidence].to_f < min_confidence

     = parse_tags(entry[:tags])
    hostname = begin
      ::Socket.gethostname
    rescue StandardError => e
      handle_exception(e, level: :debug, operation: 'apollo.local.resolve_hostname')
      'unknown'
    end
    result = Legion::Apollo.ingest(
      content:        entry[:content],
      raw_content:    entry[:raw_content] || entry[:content],
      valid_from:     entry[:valid_from],
      valid_to:       entry[:valid_to],
      tags:            + ['promoted_from_local'],
      source_channel: 'local_promotion',
      submitted_by:   "node:#{hostname}",
      confidence:     entry[:confidence],
      scope:          :global
    )
    promoted += 1 if result[:success]
  end

  log.info { "Apollo::Local promote_to_global completed promoted=#{promoted} tag_count=#{tags.size}" }
  { success: true, promoted: promoted }
rescue StandardError => e
  handle_exception(
    e,
    level:          :error,
    operation:      'apollo.local.promote_to_global',
    tag_count:      tags.size,
    min_confidence: min_confidence
  )
  { success: false, error: e.message }
end

.query(text:, limit: nil, min_confidence: nil, tags: nil, requesting_principal_id: nil, **opts) ⇒ Object

rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/ParameterLists



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/legion/apollo/local.rb', line 92

def query(text:, limit: nil, min_confidence: nil, tags: nil, requesting_principal_id: nil, **opts) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/ParameterLists
  return not_started_error unless started?

  text = normalize_text_input(text)
  tags = normalize_tags_input(tags)
  limit ||= local_setting(:default_limit, 5)
  min_confidence ||= local_setting(:min_confidence, 0.3)
  multiplier = local_setting(:fts_candidate_multiplier, 3)
  as_of = normalize_temporal_value(opts[:as_of])
  log.info do
    "Apollo::Local query executing text_length=#{text.to_s.length} " \
      "limit=#{limit} min_confidence=#{min_confidence} tag_count=#{Array(tags).size}"
  end
  log.debug { "Apollo::Local query limit=#{limit} min_confidence=#{min_confidence} tags=#{Array(tags).size}" }

  candidates = fts_search(text, limit: limit * multiplier, as_of: as_of)
  include_inferences = opts.fetch(:include_inferences, true)
  include_history = opts.fetch(:include_history, false)
  candidates = filter_candidates(candidates, min_confidence: min_confidence, tags: tags,
                                             options: { include_inferences: include_inferences,
                                                        include_history: include_history, as_of: as_of,
                                                        requesting_principal_id: requesting_principal_id })
  candidates = cosine_rerank(text, candidates) if can_rerank?
  results = candidates.first(limit)

  tier = opts[:tier]
  results = results.map { |r| project_tier(r, tier) } if tier

  log.info { "Apollo::Local query completed count=#{results.size}" }
  { success: true, results: results, count: results.size, mode: :local, tier: tier }
rescue StandardError => e
  handle_exception(
    e,
    level:          :error,
    operation:      'apollo.local.query',
    limit:          limit,
    min_confidence: min_confidence,
    tag_count:      Array(tags).size
  )
  { success: false, error: e.message }
end

.query_by_tags(tags:, limit: 50) ⇒ Object

rubocop:disable Metrics/MethodLength



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/legion/apollo/local.rb', line 148

def query_by_tags(tags:, limit: 50) # rubocop:disable Metrics/MethodLength
  connection = local_db_connection
  tags = normalize_tags_input(tags)
  return { success: false, error: :not_started } unless local_db_usable?(connection)

  results = query_by_tags_via_sql(connection, tags: tags, limit: limit)

  log.info { "Apollo::Local query_by_tags completed tag_count=#{tags.size} count=#{results.size}" }
  { success: true, results: results, count: results.size }
rescue StandardError => e
  handle_exception(
    e,
    level:     :error,
    operation: 'apollo.local.query_by_tags',
    tag_count: tags.size,
    limit:     limit
  )
  { success: false, error: e.message }
end

.reset!Object



142
143
144
145
146
# File 'lib/legion/apollo/local.rb', line 142

def reset!
  LIFECYCLE_MUTEX.synchronize do
    @started = false
  end
end

.retrieve(text:, limit: 5) ⇒ Object



134
135
136
# File 'lib/legion/apollo/local.rb', line 134

def retrieve(text:, limit: 5, **)
  query(text: text, limit: limit, **)
end

.shutdownObject



31
32
33
34
35
36
37
38
39
# File 'lib/legion/apollo/local.rb', line 31

def shutdown
  LIFECYCLE_MUTEX.synchronize do
    @started = false
    log.info 'Legion::Apollo::Local shutdown'
  end
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'apollo.local.shutdown')
  @started = false
end


243
244
245
246
247
248
249
250
251
# File 'lib/legion/apollo/local.rb', line 243

def source_links_for(entry_id:)
  return not_started_error unless started?

  links = db[:local_source_links].where(entry_id: entry_id).all
  { success: true, links: links, count: links.size }
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'apollo.local.source_links_for', entry_id: entry_id)
  { success: false, error: e.message }
end

.startObject



24
25
26
27
28
29
# File 'lib/legion/apollo/local.rb', line 24

def start
  LIFECYCLE_MUTEX.synchronize { start_without_lock }
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'apollo.local.start')
  @started = false
end

.started?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/legion/apollo/local.rb', line 41

def started?
  @started == true
end

.upsert(content:, tags: [], access_scope: 'global', **opts) ⇒ Object

rubocop:disable Metrics/MethodLength,Metrics/AbcSize



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/legion/apollo/local.rb', line 64

def upsert(content:, tags: [], access_scope: 'global', **opts) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize
  return not_started_error unless started?

  sorted_tags = normalize_tags_input(tags).sort
  tag_json = Legion::JSON.dump(sorted_tags)
  merged_opts = inject_identity_context(opts).merge(access_scope: access_scope)
  WRITE_MUTEX.synchronize do
    existing = db[:local_knowledge].where(tags: tag_json).first

    if existing
      update_upsert_entry(existing, content, tag_json, merged_opts)
    else
      result = ingest_without_lock(content: content, tags: sorted_tags, **merged_opts)
      result[:mode] = :inserted if result[:success] && result[:mode] != :deduplicated
      result
    end
  end
rescue StandardError => e
  handle_exception(
    e,
    level:          :warn,
    operation:      'apollo.local.upsert',
    tags:           Array(tags).size,
    source_channel: opts[:source_channel]
  )
  { success: false, error: e.message }
end

.version_chain(entry_id:, max_depth: 50) ⇒ Object

rubocop:disable Metrics/MethodLength



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/legion/apollo/local.rb', line 218

def version_chain(entry_id:, max_depth: 50) # rubocop:disable Metrics/MethodLength
  return not_started_error unless started?

  chain = []
  current_id = entry_id
  seen = Set.new

  max_depth.times do
    break unless current_id
    break if seen.include?(current_id)

    seen.add(current_id)
    row = db[:local_knowledge].where(id: current_id).first
    break unless row

    chain << row
    current_id = row[:parent_knowledge_id]
  end

  { success: true, chain: chain, count: chain.size }
rescue StandardError => e
  handle_exception(e, level: :error, operation: 'apollo.local.version_chain', entry_id: entry_id)
  { success: false, error: e.message }
end