Module: Legion::Extensions::Llm::Ledger::Writers::OfficialRecordWriter
- Extended by:
- Logging::Helper
- Defined in:
- lib/legion/extensions/llm/ledger/writers/official_record_writer.rb
Constant Summary collapse
- ALLOWED_CLASSIFICATION_LEVELS =
%w[public internal confidential restricted].freeze
Class Method Summary collapse
- .billing(body) ⇒ Object
- .caller_identity(body) ⇒ Object
- .caller_identity_refs(db, body) ⇒ Object
- .caller_principal(body) ⇒ Object
- .caller_type(body) ⇒ Object
- .classification_level(body) ⇒ Object
- .compute_content_hash(content) ⇒ Object
- .contains_phi?(body) ⇒ Boolean
- .contains_pii?(body) ⇒ Boolean
- .correlation_id(body) ⇒ Object
- .cost_usd(body) ⇒ Object
- .crypt_available? ⇒ Boolean
- .deep_symbolize(value) ⇒ Object
- .deterministic_uuid(value) ⇒ Object
- .enrich_request!(db, existing, body, latest_message = nil) ⇒ Object
- .enrich_response!(db, existing, response_message, body) ⇒ Object
- .extract_inline_thinking(text) ⇒ Object
- .find_or_create_conversation(db, body) ⇒ Object
- .find_or_create_identity(db, principal, provider, descriptor) ⇒ Object
- .find_or_create_identity_principal(db, descriptor) ⇒ Object
- .find_or_create_identity_provider(db, provider_name) ⇒ Object
- .find_or_create_metric(db, request, response, body) ⇒ Object
- .find_or_create_request(db, conversation, latest_message, body) ⇒ Object
- .find_or_create_response(db, request, response_message, body) ⇒ Object
- .find_or_create_response_message(db, conversation, request, body) ⇒ Object
- .find_or_create_user_message(db, conversation, body) ⇒ Object
- .finish_reason(body) ⇒ Object
- .identity_canonical_name(body) ⇒ Object
- .identity_tables_available?(db) ⇒ Boolean
- .insert_row(db, table, attributes, operation:) ⇒ Object
- .insert_with_savepoint(db, table, attributes, operation:) ⇒ Object
- .integer(value, default: 0) ⇒ Object
- .integer_or_nil(value) ⇒ Object
- .json_dump(value) ⇒ Object
- .link_response_message!(db, response_message, response) ⇒ Object
- .model_id(body) ⇒ Object
- .next_message_seq(db, conversation) ⇒ Object
- .normalize_caller_type(value) ⇒ Object
- .normalize_provider_name(value) ⇒ Object
- .operation(body) ⇒ Object
- .parse_identity_descriptor(raw_identity, raw_type, provider_name) ⇒ Object
- .parsed_identity_descriptor(body) ⇒ Object
- .phi_protect(json_string, is_phi) ⇒ Object
- .present?(value) ⇒ Boolean
- .provider(body) ⇒ Object
- .provider_instance(body) ⇒ Object
- .recorded_at(body) ⇒ Object
- .reference(body, *keys) ⇒ Object
- .request_content(body) ⇒ Object
- .request_payload(body) ⇒ Object
- .request_ref(body) ⇒ Object
- .resolve_context_tokens(body) ⇒ Object
- .resolve_identity(db, body) ⇒ Object
- .resolve_parent_request_id(db, body) ⇒ Object
-
.resolve_request_content_hash(body) ⇒ Object
Prefer precomputed hash from emitter (A4: hash ships instead of raw content).
-
.resolve_response_content_hash(body) ⇒ Object
Prefer precomputed hash from emitter (A4: hash ships instead of raw content).
- .response_content(body) ⇒ Object
- .runtime_caller_class(body) ⇒ Object
- .runtime_caller_client(body) ⇒ Object
- .stable_uuid(value) ⇒ Object
- .stringify_content(content) ⇒ Object
- .thinking_response(body) ⇒ Object
- .tier(body) ⇒ Object
- .tokens(body) ⇒ Object
- .update_if_missing(updates, existing, key, value) ⇒ Object
- .update_if_placeholder(updates, existing, key, value) ⇒ Object
-
.upsert_guard?(value) ⇒ Boolean
Core guard: never upsert a value that is nil, empty string, or empty JSON object.
- .visible_response(body) ⇒ Object
- .write_metering(payload) ⇒ Object
- .write_prompt(payload) ⇒ Object
Class Method Details
.billing(body) ⇒ Object
674 675 676 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 674 def billing(body) body[:billing] || body[:cost] || {} end |
.caller_identity(body) ⇒ Object
413 414 415 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 413 def caller_identity(body) caller_identity_refs(::Legion::Data.connection, body)[:identity_id] end |
.caller_identity_refs(db, body) ⇒ Object
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 441 def caller_identity_refs(db, body) body[:__ledger_caller_identity_refs] ||= begin explicit_identity_id = integer_or_nil(body[:caller_identity_id] || body.dig(:caller, :requested_by, :id)) explicit_principal_id = integer_or_nil(body[:caller_principal_id] || body.dig(:caller, :requested_by, :principal_id)) explicit_identity_id ||= integer_or_nil(body[:__header_identity_id]) explicit_principal_id ||= integer_or_nil(body[:__header_principal_id]) refs = { principal_id: explicit_principal_id, identity_id: explicit_identity_id }.compact unless refs[:principal_id] && refs[:identity_id] if explicit_identity_id && !explicit_principal_id && identity_tables_available?(db) row = db[:identities].where(id: explicit_identity_id).first refs[:principal_id] = row[:principal_id] if row end resolved = resolve_identity(db, body) refs[:principal_id] ||= resolved[:principal_id] refs[:identity_id] ||= resolved[:identity_id] end refs.compact end end |
.caller_principal(body) ⇒ Object
417 418 419 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 417 def caller_principal(body) caller_identity_refs(::Legion::Data.connection, body)[:principal_id] end |
.caller_type(body) ⇒ Object
421 422 423 424 425 426 427 428 429 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 421 def caller_type(body) raw_type = body[:caller_type] || body.dig(:identity, :type) || body.dig(:caller, :requested_by, :type) || body.dig(:caller, :source) return normalize_caller_type(raw_type) if present?(raw_type) parsed_identity_descriptor(body)[:kind] end |
.classification_level(body) ⇒ Object
748 749 750 751 752 753 754 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 748 def classification_level(body) raw = body[:classification_level] || body.dig(:classification, :level) return 'internal' if raw.nil? || raw.to_s.empty? normalized = raw.to_s.downcase ALLOWED_CLASSIFICATION_LEVELS.include?(normalized) ? normalized : 'internal' end |
.compute_content_hash(content) ⇒ Object
838 839 840 841 842 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 838 def compute_content_hash(content) return nil if content.nil? || content.to_s.empty? Digest::SHA256.hexdigest(json_dump(content))[0..31] end |
.contains_phi?(body) ⇒ Boolean
756 757 758 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 756 def contains_phi?(body) body[:contains_phi] || body.dig(:classification, :contains_phi) || false end |
.contains_pii?(body) ⇒ Boolean
760 761 762 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 760 def contains_pii?(body) body[:contains_pii] || body.dig(:classification, :contains_pii) || false end |
.correlation_id(body) ⇒ Object
639 640 641 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 639 def correlation_id(body) reference(body, :correlation_id, :correlation_ref) || body.dig(:tracing, :correlation_id) end |
.cost_usd(body) ⇒ Object
678 679 680 681 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 678 def cost_usd(body) raw = body[:cost_usd] || body.dig(:cost, :estimated_usd) || body.dig(:cost, :usd) raw.to_f end |
.crypt_available? ⇒ Boolean
811 812 813 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 811 def crypt_available? defined?(Legion::Crypt) && Legion::Crypt.respond_to?(:encrypt) end |
.deep_symbolize(value) ⇒ Object
819 820 821 822 823 824 825 826 827 828 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 819 def deep_symbolize(value) case value when Hash value.each_with_object({}) { |(key, item), memo| memo[key.to_sym] = deep_symbolize(item) } when Array value.map { |item| deep_symbolize(item) } else value end end |
.deterministic_uuid(value) ⇒ Object
780 781 782 783 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 780 def deterministic_uuid(value) hex = Digest::SHA256.hexdigest(value.to_s)[0, 32] "#{hex[0, 8]}-#{hex[8, 4]}-#{hex[12, 4]}-#{hex[16, 4]}-#{hex[20, 12]}" end |
.enrich_request!(db, existing, body, latest_message = nil) ⇒ Object
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 384 def enrich_request!(db, existing, body, = nil) updates = {} update_if_missing(updates, existing, :latest_message_id, &.dig(:id)) caller_refs = caller_identity_refs(db, body) update_if_missing(updates, existing, :caller_identity_id, caller_refs[:identity_id]) update_if_missing(updates, existing, :caller_principal_id, caller_refs[:principal_id]) update_if_missing(updates, existing, :runtime_caller_type, caller_type(body)) update_if_missing(updates, existing, :runtime_caller_class, runtime_caller_class(body)) update_if_missing(updates, existing, :runtime_caller_client, runtime_caller_client(body)) update_if_missing(updates, existing, :identity_canonical_name, identity_canonical_name(body)) update_if_missing(updates, existing, :request_content_hash, resolve_request_content_hash(body)) request_json = request_payload(body) ? json_dump(request_payload(body)) : nil if request_json update_if_placeholder(updates, existing, :request_json, request_json) elsif existing[:request_json].nil? # Nothing to add end msg_count = Array(body.dig(:request, :messages) || body[:messages]).size updates[:context_message_count] = msg_count if existing[:context_message_count].to_i.zero? && msg_count.positive? return existing if updates.empty? db[:llm_message_inference_requests].where(id: existing[:id]).update(updates) log.info("[ledger] enriched request id=#{existing[:id]} fields=#{updates.keys.join(',')}") existing.merge(updates) end |
.enrich_response!(db, existing, response_message, body) ⇒ Object
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 268 def enrich_response!(db, existing, , body) updates = {} update_if_missing(updates, existing, :response_message_id, &.dig(:id)) update_if_missing(updates, existing, :tier, tier(body)) update_if_missing(updates, existing, :provider_instance, provider_instance(body)) update_if_missing(updates, existing, :finish_reason, finish_reason(body)) update_if_missing(updates, existing, :dispatch_path, body[:dispatch_path] || body[:tier]) update_if_missing(updates, existing, :identity_canonical_name, identity_canonical_name(body)) update_if_missing(updates, existing, :response_content_hash, resolve_response_content_hash(body)) vis = visible_response(body) if vis response_json = json_dump(vis) update_if_placeholder(updates, existing, :response_json, response_json) elsif existing[:response_json].nil? # Nothing to add, but also don't overwrite existing data with nil end think = thinking_response(body) if think thinking_json = json_dump(think) update_if_placeholder(updates, existing, :response_thinking_json, thinking_json) elsif existing[:response_thinking_json].nil? # Nothing to add end return if updates.empty? db[:llm_message_inference_responses].where(id: existing[:id]).update(updates) log.info("[ledger] enriched response id=#{existing[:id]} fields=#{updates.keys.join(',')}") end |
.extract_inline_thinking(text) ⇒ Object
723 724 725 726 727 728 729 730 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 723 def extract_inline_thinking(text) if defined?(::Legion::Extensions::Llm::Responses::ThinkingExtractor) extraction = ::Legion::Extensions::Llm::Responses::ThinkingExtractor.extract(text) [extraction.content, extraction.thinking] else [text, nil] end end |
.find_or_create_conversation(db, body) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 58 def find_or_create_conversation(db, body) uuid = stable_uuid(reference(body, :conversation_id, :conversation_ref) || 'default-conversation') existing = db[:llm_conversations].where(uuid: uuid).first return existing if existing id = insert_with_savepoint(db, :llm_conversations, { uuid: uuid, title: body[:title] || body[:conversation_title], classification_level: classification_level(body), contains_phi: contains_phi?(body), contains_pii: contains_pii?(body), pii_types_json: json_dump(Array(body.dig(:classification, :pii_types))), jurisdictions_json: json_dump(Array(body.dig(:classification, :jurisdictions) || body[:jurisdictions])), retention_policy: body[:retention_policy] || 'default', expires_at: body[:expires_at], identity_canonical_name: identity_canonical_name(body), recorded_at: recorded_at(body), inserted_at: Time.now.utc, created_at: Time.now.utc, updated_at: Time.now.utc }, operation: 'official_record_writer.conversation') db[:llm_conversations][id: id] rescue Sequel::UniqueConstraintViolation => e log.debug("[ledger] conversation collision resolved uuid=#{uuid} error=#{e.class}") existing = db[:llm_conversations].where(uuid: uuid).first return existing if existing raise end |
.find_or_create_identity(db, principal, provider, descriptor) ⇒ Object
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 568 def find_or_create_identity(db, principal, provider, descriptor) table = db[:identities] existing = table.where( principal_id: principal[:id], provider_id: provider[:id], provider_identity_key: descriptor[:provider_identity_key] ).first return existing if existing uuid_key = "identity:#{principal[:id]}:#{provider[:id]}:#{descriptor[:provider_identity_key]}" id = insert_with_savepoint(db, :identities, { uuid: deterministic_uuid(uuid_key), principal_id: principal[:id], provider_id: provider[:id], provider_identity_key: descriptor[:provider_identity_key], last_authenticated_at: Time.now.utc, account_type: 'primary', is_default: true, created_at: Time.now.utc, updated_at: Time.now.utc }, operation: 'official_record_writer.identity') table[id: id] rescue Sequel::UniqueConstraintViolation => e handle_exception(e, level: :debug, handled: true, operation: 'official_record_writer.identity_race') existing = table.where(principal_id: principal[:id], provider_id: provider[:id], provider_identity_key: descriptor[:provider_identity_key]).first return existing if existing raise end |
.find_or_create_identity_principal(db, descriptor) ⇒ Object
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 545 def find_or_create_identity_principal(db, descriptor) table = db[:identity_principals] existing = table.where(canonical_name: descriptor[:canonical_name], kind: descriptor[:kind]).first return existing if existing id = insert_with_savepoint(db, :identity_principals, { uuid: deterministic_uuid("identity_principal:#{descriptor[:kind]}:#{descriptor[:canonical_name]}"), canonical_name: descriptor[:canonical_name], kind: descriptor[:kind], display_name: descriptor[:canonical_name], last_seen_at: Time.now.utc, created_at: Time.now.utc, updated_at: Time.now.utc }, operation: 'official_record_writer.identity_principal') table[id: id] rescue Sequel::UniqueConstraintViolation => e handle_exception(e, level: :debug, handled: true, operation: 'official_record_writer.identity_principal_race') existing = table.where(canonical_name: descriptor[:canonical_name], kind: descriptor[:kind]).first return existing if existing raise end |
.find_or_create_identity_provider(db, provider_name) ⇒ Object
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 522 def find_or_create_identity_provider(db, provider_name) table = db[:identity_providers] existing = table.where(name: provider_name).first return existing if existing id = insert_with_savepoint(db, :identity_providers, { uuid: deterministic_uuid("identity_provider:#{provider_name}"), name: provider_name, provider_type: provider_name == 'local' ? 'local' : 'external', facing: 'internal', source: 'ledger', created_at: Time.now.utc, updated_at: Time.now.utc }, operation: 'official_record_writer.identity_provider') table[id: id] rescue Sequel::UniqueConstraintViolation => e handle_exception(e, level: :debug, handled: true, operation: 'official_record_writer.identity_provider_race') existing = table.where(name: provider_name).first return existing if existing raise end |
.find_or_create_metric(db, request, response, body) ⇒ Object
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 323 def find_or_create_metric(db, request, response, body) metric_uuid = stable_uuid(reference(body, :metric_id, :metric_ref) || "metric:#{request_ref(body)}") existing = db[:llm_message_inference_metrics].where(uuid: metric_uuid).first return existing if existing token_values = tokens(body) id = insert_with_savepoint(db, :llm_message_inference_metrics, { uuid: metric_uuid, message_inference_request_id: request[:id], message_inference_response_id: response[:id], provider: provider(body), model_key: model_id(body), tier: tier(body), input_tokens: token_values[:input_tokens], output_tokens: token_values[:output_tokens], thinking_tokens: token_values[:thinking_tokens], total_tokens: token_values[:total_tokens], latency_ms: integer(body[:latency_ms]), wall_clock_ms: integer(body[:wall_clock_ms]), cost_usd: cost_usd(body), currency: body[:currency] || 'USD', cost_center: billing(body)[:cost_center], budget_key: billing(body)[:budget_id] || billing(body)[:budget_key], identity_principal_id: caller_identity_refs(db, body)[:principal_id], identity_id: caller_identity_refs(db, body)[:identity_id], identity_canonical_name: identity_canonical_name(body), recorded_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.inference_metric') db[:llm_message_inference_metrics][id: id] rescue Sequel::UniqueConstraintViolation => e log.debug("[ledger] metric collision resolved uuid=#{metric_uuid} error=#{e.class}") existing = db[:llm_message_inference_metrics].where(uuid: metric_uuid).first return existing if existing raise end |
.find_or_create_request(db, conversation, latest_message, body) ⇒ Object
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 118 def find_or_create_request(db, conversation, , body) request_id = request_ref(body) existing = db[:llm_message_inference_requests].where(request_ref: request_id).first return enrich_request!(db, existing, body, ) if existing operation = operation(body) caller_refs = caller_identity_refs(db, body) id = insert_with_savepoint(db, :llm_message_inference_requests, { uuid: stable_uuid(request_id), conversation_id: conversation[:id], latest_message_id: &.dig(:id), parent_request_id: resolve_parent_request_id(db, body), caller_principal_id: caller_refs[:principal_id], caller_identity_id: caller_refs[:identity_id], identity_canonical_name: identity_canonical_name(body), runtime_caller_type: caller_type(body), runtime_caller_class: runtime_caller_class(body), runtime_caller_client: runtime_caller_client(body), request_ref: request_id, correlation_ref: correlation_id(body), correlation_id: correlation_id(body), exchange_ref: body[:exchange_id], request_type: operation, operation: operation, idempotency_key: body[:idempotency_key] || request_id, status: 'responded', context_message_count: Array(body.dig(:request, :messages) || body[:messages]).size, request_capture_mode: 'full', request_json: if request_payload(body) phi_protect(json_dump(request_payload(body)), contains_phi?(body)) end, classification_level: classification_level(body), cost_center: billing(body)[:cost_center], budget_key: billing(body)[:budget_id] || billing(body)[:budget_key], injected_tool_count: Array(body.dig(:audit, :injected_tools) || body[:injected_tools]).size, context_tokens: resolve_context_tokens(body), request_content_hash: resolve_request_content_hash(body), curation_strategy: body[:curation_strategy] || body.dig(:audit, :curation_strategy), tool_policy: body[:tool_policy] || body.dig(:audit, :tool_policy), requested_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.inference_request') db[:llm_message_inference_requests][id: id] rescue Sequel::UniqueConstraintViolation => e log.debug("[ledger] request collision resolved request_ref=#{request_id} error=#{e.class}") existing = db[:llm_message_inference_requests].where(request_ref: request_id).first return enrich_request!(db, existing, body, ) if existing raise end |
.find_or_create_response(db, request, response_message, body) ⇒ Object
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 203 def find_or_create_response(db, request, , body) response_uuid = stable_uuid(reference(body, :provider_response_ref) || "response:#{request_ref(body)}:#{body[:provider] || 'unknown'}") existing = db[:llm_message_inference_responses].where(uuid: response_uuid).first # Fallback: if we couldn't find a response by UUID, check if a response # already exists for this request (e.g., metering arrived first and created # a response with a different UUID). Enrich it instead of creating a duplicate. unless existing existing = db[:llm_message_inference_responses] .where(message_inference_request_id: request[:id]) .first log.debug("[ledger] response fallback: found existing response id=#{existing[:id]} for request_id=#{request[:id]}") if existing end if existing enrich_response!(db, existing, , body) return existing end vis_resp = visible_response(body) think_resp = thinking_response(body) phi = contains_phi?(body) id = insert_with_savepoint(db, :llm_message_inference_responses, { uuid: response_uuid, message_inference_request_id: request[:id], response_message_id: &.dig(:id), provider: provider(body), provider_instance: provider_instance(body), model_key: model_id(body), tier: tier(body), runner_ref: body[:worker_id] || body[:runner_ref], provider_response_ref: body[:provider_response_ref], status: body[:error] ? 'error' : 'success', finish_reason: finish_reason(body), latency_ms: integer(body[:latency_ms]), wall_clock_ms: integer(body[:wall_clock_ms]), response_capture_mode: 'full', response_json: vis_resp ? phi_protect(json_dump(vis_resp), phi) : nil, response_thinking_json: think_resp ? phi_protect(json_dump(think_resp), phi) : nil, dispatch_path: body[:dispatch_path] || body[:tier], error_category: body[:error_category] || body.dig(:error, :category), error_code: body[:error_code] || body.dig(:error, :code), error_message: body[:error_message] || body.dig(:error, :message), response_content_hash: resolve_response_content_hash(body), route_attempts: (body[:route_attempts] || body.dig(:audit, :route_attempts)).to_i, escalation_chain_ref: body[:escalation_chain_ref], identity_principal_id: caller_identity_refs(db, body)[:principal_id], identity_id: caller_identity_refs(db, body)[:identity_id], identity_canonical_name: identity_canonical_name(body), responded_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.inference_response') db[:llm_message_inference_responses][id: id] rescue Sequel::UniqueConstraintViolation => e log.debug("[ledger] response collision resolved uuid=#{response_uuid} error=#{e.class}") existing = db[:llm_message_inference_responses].where(uuid: response_uuid).first if existing enrich_response!(db, existing, , body) return existing end raise end |
.find_or_create_response_message(db, conversation, request, body) ⇒ Object
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 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 170 def (db, conversation, request, body) uuid = stable_uuid(reference(body, :response_message_id) || "response-message:#{request_ref(body)}") existing = db[:llm_messages].where(uuid: uuid).first return existing if existing latest = db[:llm_messages][id: request[:latest_message_id]] seq = (latest&.dig(:seq) || 1) + 1 begin id = insert_with_savepoint(db, :llm_messages, { uuid: uuid, conversation_id: conversation[:id], parent_message_id: latest&.dig(:id), message_inference_request_id: request[:id], seq: seq, role: 'assistant', content_type: 'text', content: response_content(body), input_tokens: 0, output_tokens: tokens(body)[:output_tokens], identity_principal_id: caller_identity_refs(db, body)[:principal_id], identity_id: caller_identity_refs(db, body)[:identity_id], identity_canonical_name: identity_canonical_name(body), created_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.response_message') db[:llm_messages][id: id] rescue Sequel::UniqueConstraintViolation => e log.debug("[ledger] seq collision resolved uuid=#{uuid} conversation_id=#{conversation[:id]} error=#{e.class}") db[:llm_messages].where(uuid: uuid).first || db[:llm_messages].where(conversation_id: conversation[:id], seq: seq).first end end |
.find_or_create_user_message(db, conversation, body) ⇒ Object
88 89 90 91 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 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 88 def (db, conversation, body) uuid = stable_uuid(reference(body, :message_id, :message_id_ctx) || "request-message:#{request_ref(body)}") existing = db[:llm_messages].where(uuid: uuid).first return existing if existing seq = body[:message_seq] ? integer(body[:message_seq]) : (db, conversation) begin id = insert_with_savepoint(db, :llm_messages, { uuid: uuid, conversation_id: conversation[:id], seq: seq, role: 'user', content_type: 'text', content: request_content(body), input_tokens: tokens(body)[:input_tokens], output_tokens: 0, identity_principal_id: caller_identity_refs(db, body)[:principal_id], identity_id: caller_identity_refs(db, body)[:identity_id], identity_canonical_name: identity_canonical_name(body), created_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.user_message') db[:llm_messages][id: id] rescue Sequel::UniqueConstraintViolation => e log.debug("[ledger] seq collision resolved uuid=#{uuid} conversation_id=#{conversation[:id]} error=#{e.class}") db[:llm_messages].where(uuid: uuid).first || db[:llm_messages].where(conversation_id: conversation[:id], seq: seq).first end end |
.finish_reason(body) ⇒ Object
739 740 741 742 743 744 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 739 def finish_reason(body) return body[:finish_reason] if body[:finish_reason] return nil unless body[:response].is_a?(Hash) body.dig(:response, :finish_reason) || body.dig(:response, :stop, :reason) end |
.identity_canonical_name(body) ⇒ Object
830 831 832 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 830 def identity_canonical_name(body) parsed_identity_descriptor(body)[:canonical_name] end |
.identity_tables_available?(db) ⇒ Boolean
599 600 601 602 603 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 599 def identity_tables_available?(db) db.table_exists?(:identity_providers) && db.table_exists?(:identity_principals) && db.table_exists?(:identities) end |
.insert_row(db, table, attributes, operation:) ⇒ Object
361 362 363 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 361 def insert_row(db, table, attributes, operation:) Helpers::PersistenceLogging.insert_row(db, table, attributes, operation: operation, warn_on_unique: false) end |
.insert_with_savepoint(db, table, attributes, operation:) ⇒ Object
365 366 367 368 369 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 365 def insert_with_savepoint(db, table, attributes, operation:) db.transaction(savepoint: true) do insert_row(db, table, attributes, operation: operation) end end |
.integer(value, default: 0) ⇒ Object
789 790 791 792 793 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 789 def integer(value, default: 0) return default if value.nil? value.to_i end |
.integer_or_nil(value) ⇒ Object
619 620 621 622 623 624 625 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 619 def integer_or_nil(value) return nil if value.nil? return value if value.is_a?(Integer) int = value.to_s.to_i int.positive? ? int : nil end |
.json_dump(value) ⇒ Object
815 816 817 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 815 def json_dump(value) Helpers::Json.dump(value) end |
.link_response_message!(db, response_message, response) ⇒ Object
377 378 379 380 381 382 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 377 def (db, , response) return unless && response return if [:message_inference_response_id] == response[:id] db[:llm_messages].where(id: [:id]).update(message_inference_response_id: response[:id]) end |
.model_id(body) ⇒ Object
656 657 658 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 656 def model_id(body) body[:model_id] || body[:model_key] || body.dig(:routing, :model) end |
.next_message_seq(db, conversation) ⇒ Object
785 786 787 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 785 def (db, conversation) db[:llm_messages].where(conversation_id: conversation[:id]).max(:seq).to_i + 1 end |
.normalize_caller_type(value) ⇒ Object
605 606 607 608 609 610 611 612 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 605 def normalize_caller_type(value) return nil unless present?(value) normalized = value.to_s.downcase.gsub(/[^a-z0-9_:-]+/, '_').split(':', 2).first return 'human' if normalized == 'user' normalized end |
.normalize_provider_name(value) ⇒ Object
614 615 616 617 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 614 def normalize_provider_name(value) raw = present?(value) ? value.to_s : 'local' raw.downcase.gsub(/[^a-z0-9_.:-]+/, '-').gsub(/\A-+|-+\z/, '') end |
.operation(body) ⇒ Object
643 644 645 646 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 643 def operation(body) (body[:operation] || body[:request_type] || body.dig(:routing, :operation) || body.dig(:headers, :'x-legion-llm-request-type') || 'chat').to_s end |
.parse_identity_descriptor(raw_identity, raw_type, provider_name) ⇒ Object
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 500 def parse_identity_descriptor(raw_identity, raw_type, provider_name) text = raw_identity.to_s kind = normalize_caller_type(raw_type) canonical = text if text.include?(':') && !text.include?('@') prefix, remainder = text.split(':', 2) prefix_kind = normalize_caller_type(prefix) if prefix_kind && present?(remainder) kind ||= prefix_kind canonical = remainder end end { canonical_name: canonical, kind: kind || 'unknown', provider_identity_key: text, provider_name: normalize_provider_name(provider_name) } end |
.parsed_identity_descriptor(body) ⇒ Object
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 481 def parsed_identity_descriptor(body) raw_identity = body[:caller_identity] || body.dig(:identity, :identity) || body.dig(:identity, :canonical_name) || body.dig(:caller, :requested_by, :identity) || body.dig(:caller, :requested_by, :canonical_name) || body.dig(:caller, :requested_by, :id) return {} unless present?(raw_identity) raw_type = body[:caller_type] || body.dig(:identity, :type) || body.dig(:caller, :requested_by, :type) || body.dig(:caller, :source) provider_name = body.dig(:identity, :credential) || body.dig(:caller, :requested_by, :credential) || 'local' parse_identity_descriptor(raw_identity, raw_type, provider_name) end |
.phi_protect(json_string, is_phi) ⇒ Object
802 803 804 805 806 807 808 809 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 802 def phi_protect(json_string, is_phi) return json_string unless is_phi && crypt_available? Legion::Crypt.encrypt(json_string) rescue StandardError => e handle_exception(e, level: :warn, handled: true, operation: 'official_record_writer.phi_encrypt') json_string end |
.present?(value) ⇒ Boolean
834 835 836 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 834 def present?(value) !value.nil? && !(value.respond_to?(:empty?) && value.empty?) end |
.provider(body) ⇒ Object
648 649 650 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 648 def provider(body) (body[:provider] || body.dig(:routing, :provider)).to_s end |
.provider_instance(body) ⇒ Object
652 653 654 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 652 def provider_instance(body) body[:provider_instance] || body.dig(:routing, :provider_instance) || body.dig(:routing, :instance) end |
.recorded_at(body) ⇒ Object
764 765 766 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 764 def recorded_at(body) body[:recorded_at] || body[:timestamp] || body.dig(:timestamps, :returned) || body.dig(:timestamps, :provider_end) || Time.now.utc end |
.reference(body, *keys) ⇒ Object
768 769 770 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 768 def reference(body, *keys) keys.lazy.map { |key| body[key] }.find { |value| present?(value) }&.to_s end |
.request_content(body) ⇒ Object
687 688 689 690 691 692 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 687 def request_content(body) = body.dig(:request, :messages) || body[:messages] = Array().reverse.find { |item| item[:role].to_s == 'user' } || Array().last content = &.dig(:content) || body[:prompt] || body[:text] stringify_content(content) end |
.request_payload(body) ⇒ Object
683 684 685 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 683 def request_payload(body) body[:request] || body[:messages] end |
.request_ref(body) ⇒ Object
371 372 373 374 375 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 371 def request_ref(body) body[:__ledger_request_ref] ||= reference(body, :request_id, :request_ref) || correlation_id(body) || stable_uuid(SecureRandom.uuid) end |
.resolve_context_tokens(body) ⇒ Object
860 861 862 863 864 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 860 def resolve_context_tokens(body) raw = body[:tokens] || body[:audit] || body val = raw[:input_tokens] || raw[:input] || raw[:context_tokens] || raw[:prompt_tokens] present?(val) ? val.to_i : 0 end |
.resolve_identity(db, body) ⇒ Object
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 465 def resolve_identity(db, body) return {} unless identity_tables_available?(db) descriptor = parsed_identity_descriptor(body) return {} unless present?(descriptor[:canonical_name]) provider = find_or_create_identity_provider(db, descriptor[:provider_name]) principal = find_or_create_identity_principal(db, descriptor) identity = find_or_create_identity(db, principal, provider, descriptor) { principal_id: principal[:id], identity_id: identity[:id] } rescue StandardError => e handle_exception(e, level: :warn, handled: true, operation: 'official_record_writer.identity_resolution') {} end |
.resolve_parent_request_id(db, body) ⇒ Object
627 628 629 630 631 632 633 634 635 636 637 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 627 def resolve_parent_request_id(db, body) parent_ref = body[:parent_request_id] || body.dig(:context, :parent_request_id) || body.dig(:caller, :parent_request_ref) return nil unless present?(parent_ref) if parent_ref.is_a?(Integer) parent_ref else parent = db[:llm_message_inference_requests].where(request_ref: parent_ref.to_s).first parent&.dig(:id) end end |
.resolve_request_content_hash(body) ⇒ Object
Prefer precomputed hash from emitter (A4: hash ships instead of raw content). Falls back to computing from raw content for backward compatibility.
846 847 848 849 850 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 846 def resolve_request_content_hash(body) return body[:request_content_hash] if present?(body[:request_content_hash]) compute_content_hash(body.dig(:request, :content) || body.dig(:audit, :request_content)) end |
.resolve_response_content_hash(body) ⇒ Object
Prefer precomputed hash from emitter (A4: hash ships instead of raw content). Falls back to computing from raw content for backward compatibility.
854 855 856 857 858 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 854 def resolve_response_content_hash(body) return body[:response_content_hash] if present?(body[:response_content_hash]) compute_content_hash(body[:response_content] || body.dig(:audit, :response_content)) end |
.response_content(body) ⇒ Object
732 733 734 735 736 737 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 732 def response_content(body) vis = visible_response(body) return nil unless vis stringify_content(vis[:content] || vis.dig(:message, :content)) end |
.runtime_caller_class(body) ⇒ Object
431 432 433 434 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 431 def runtime_caller_class(body) body.dig(:caller, :class) || body.dig(:caller, :caller_class) || body.dig(:caller, :source_class) || body[:runtime_caller_class] end |
.runtime_caller_client(body) ⇒ Object
436 437 438 439 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 436 def runtime_caller_client(body) body.dig(:caller, :client) || body.dig(:caller, :user_agent) || body[:runtime_caller_client] end |
.stable_uuid(value) ⇒ Object
772 773 774 775 776 777 778 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 772 def stable_uuid(value) raw = value.to_s return raw if raw.length <= 36 hex = Digest::SHA256.hexdigest(raw)[0, 32] "#{hex[0, 8]}-#{hex[8, 4]}-#{hex[12, 4]}-#{hex[16, 4]}-#{hex[20, 12]}" end |
.stringify_content(content) ⇒ Object
795 796 797 798 799 800 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 795 def stringify_content(content) return nil if content.nil? return content if content.is_a?(String) json_dump(content) end |
.thinking_response(body) ⇒ Object
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 707 def thinking_response(body) thinking = body[:response_thinking] || body[:thinking] thinking ||= body.dig(:response, :thinking) if body[:response].is_a?(Hash) if thinking return { content: thinking } if thinking.is_a?(String) return thinking end content_str = body[:response_content] || body[:response] || body[:content] return nil unless content_str.is_a?(String) _clean, extracted = extract_inline_thinking(content_str) extracted ? { content: extracted } : nil end |
.tier(body) ⇒ Object
660 661 662 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 660 def tier(body) body[:tier] || body.dig(:routing, :tier) end |
.tokens(body) ⇒ Object
664 665 666 667 668 669 670 671 672 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 664 def tokens(body) raw = body[:tokens] || body input = integer(raw[:input_tokens] || raw[:input]) output = integer(raw[:output_tokens] || raw[:output]) thinking = integer(raw[:thinking_tokens] || raw[:thinking]) total = integer(raw[:total_tokens] || raw[:total], default: input + output + thinking) { input_tokens: input, output_tokens: output, thinking_tokens: thinking, total_tokens: total } end |
.update_if_missing(updates, existing, key, value) ⇒ Object
311 312 313 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 311 def update_if_missing(updates, existing, key, value) updates[key] = value if existing[key].nil? && upsert_guard?(value) end |
.update_if_placeholder(updates, existing, key, value) ⇒ Object
315 316 317 318 319 320 321 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 315 def update_if_placeholder(updates, existing, key, value) return unless upsert_guard?(value) existing_val = existing[key] is_placeholder = ['{}', 'null'].include?(existing_val.to_s) updates[key] = value if is_placeholder end |
.upsert_guard?(value) ⇒ Boolean
Core guard: never upsert a value that is nil, empty string, or empty JSON object. This prevents a leaner message (e.g., metering) from overwriting valid data written by a richer message (e.g., prompt audit).
303 304 305 306 307 308 309 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 303 def upsert_guard?(value) return false if value.nil? return false if value.is_a?(String) && value.strip.empty? return false if value.to_s == '{}' true end |
.visible_response(body) ⇒ Object
694 695 696 697 698 699 700 701 702 703 704 705 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 694 def visible_response(body) response = body[:response] || body[:response_content] || body[:content] return nil if response.nil? || (response.is_a?(Hash) && response.empty?) if response.is_a?(String) clean, _thinking = extract_inline_thinking(response) return { content: clean } end return { content: response[:content] } if response.is_a?(Hash) && response.key?(:content) response.is_a?(Hash) ? response.except(:thinking) : { content: response.to_s } end |
.write_metering(payload) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 41 def write_metering(payload) body = deep_symbolize(payload) db = ::Legion::Data.connection result = nil db.transaction do conversation = find_or_create_conversation(db, body) request = find_or_create_request(db, conversation, nil, body) response = find_or_create_response(db, request, nil, body) metric = find_or_create_metric(db, request, response, body) OfficialRouteAttemptWriter.write_route_attempts(db, request, response, body) result = { result: :ok, request_id: request[:id], response_id: response[:id], metric_id: metric[:id] } end result end |
.write_prompt(payload) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 21 def write_prompt(payload) body = deep_symbolize(payload) db = ::Legion::Data.connection result = nil db.transaction do conversation = find_or_create_conversation(db, body) = (db, conversation, body) request = find_or_create_request(db, conversation, , body) = (db, conversation, request, body) response = find_or_create_response(db, request, , body) (db, , response) metric = find_or_create_metric(db, request, response, body) OfficialRouteAttemptWriter.write_route_attempts(db, request, response, body) result = { result: :ok, request_id: request[:id], response_id: response[:id], metric_id: metric[:id] } end result end |