ltr 0.1.0

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.
Files changed (169) hide show
  1. checksums.yaml +7 -0
  2. data/ARCHITECTURE.md +92 -0
  3. data/CHANGELOG.md +5 -0
  4. data/LICENSE +21 -0
  5. data/README.md +186 -0
  6. data/docs/AGENTS.md +67 -0
  7. data/docs/aggregation-engines.md +80 -0
  8. data/docs/config.md +516 -0
  9. data/docs/data-contracts.md +94 -0
  10. data/docs/data-splits.md +34 -0
  11. data/docs/dataset-builder-steps.md +13 -0
  12. data/docs/dataset-csv.md +73 -0
  13. data/docs/dataset-enrichers.md +62 -0
  14. data/docs/errors.md +33 -0
  15. data/docs/feature-selection.md +108 -0
  16. data/docs/features.md +202 -0
  17. data/docs/glossary.md +56 -0
  18. data/docs/host-integration.md +128 -0
  19. data/docs/host-run-pipelines.md +48 -0
  20. data/docs/index.md +50 -0
  21. data/docs/inference.md +164 -0
  22. data/docs/label-transformers.md +242 -0
  23. data/docs/labels-from-behavior.md +94 -0
  24. data/docs/learning-to-rank.md +119 -0
  25. data/docs/metrics.md +166 -0
  26. data/docs/model-files.md +73 -0
  27. data/docs/optimization.md +72 -0
  28. data/docs/public-api.md +67 -0
  29. data/docs/rake-tasks.md +82 -0
  30. data/docs/relevance-grades.md +80 -0
  31. data/docs/run-locally.md +584 -0
  32. data/docs/run-on-aws.md +647 -0
  33. data/docs/training-objective.md +110 -0
  34. data/docs/ubi-documents.md +75 -0
  35. data/docs/ubi-logging.md +125 -0
  36. data/lib/ltr/README.md +28 -0
  37. data/lib/ltr/configuration/README.md +12 -0
  38. data/lib/ltr/configuration/config_loader.rb +326 -0
  39. data/lib/ltr/configuration/config_validator.rb +476 -0
  40. data/lib/ltr/configuration/configuration.rb +84 -0
  41. data/lib/ltr/configuration/example_config.yml +182 -0
  42. data/lib/ltr/data/README.md +20 -0
  43. data/lib/ltr/data/csv/README.md +9 -0
  44. data/lib/ltr/data/csv/typed_columns.rb +101 -0
  45. data/lib/ltr/data/csv.rb +126 -0
  46. data/lib/ltr/data/dataframe.rb +80 -0
  47. data/lib/ltr/data/dataset_loader.rb +29 -0
  48. data/lib/ltr/data/row_store.rb +188 -0
  49. data/lib/ltr/data/split_cache.rb +30 -0
  50. data/lib/ltr/data/splits.rb +86 -0
  51. data/lib/ltr/dataset_aggregation/README.md +32 -0
  52. data/lib/ltr/dataset_aggregation/aggregated_sqlite_loader.rb +64 -0
  53. data/lib/ltr/dataset_aggregation/cascade_actions.rb +58 -0
  54. data/lib/ltr/dataset_aggregation/column_name.rb +47 -0
  55. data/lib/ltr/dataset_aggregation/dataset_builder/README.md +15 -0
  56. data/lib/ltr/dataset_aggregation/dataset_builder/context.rb +159 -0
  57. data/lib/ltr/dataset_aggregation/dataset_builder/steps/README.md +16 -0
  58. data/lib/ltr/dataset_aggregation/dataset_builder/steps/behavioural_feature_builder.rb +77 -0
  59. data/lib/ltr/dataset_aggregation/dataset_builder/steps/dataset_filters.rb +29 -0
  60. data/lib/ltr/dataset_aggregation/dataset_builder/steps/label_creator.rb +125 -0
  61. data/lib/ltr/dataset_aggregation/dataset_builder/steps/negative_downsampler.rb +52 -0
  62. data/lib/ltr/dataset_aggregation/dataset_builder/steps/query_aggregator.rb +163 -0
  63. data/lib/ltr/dataset_aggregation/dataset_builder/steps/split_assigner.rb +76 -0
  64. data/lib/ltr/dataset_aggregation/dataset_builder/steps/ubi_joiner.rb +137 -0
  65. data/lib/ltr/dataset_aggregation/dataset_builder/steps/user_query_aggregator.rb +68 -0
  66. data/lib/ltr/dataset_aggregation/dataset_builder.rb +82 -0
  67. data/lib/ltr/dataset_aggregation/dataset_enricher.rb +168 -0
  68. data/lib/ltr/dataset_aggregation/dataset_finalizer.rb +116 -0
  69. data/lib/ltr/dataset_aggregation/dataset_pipeline.rb +113 -0
  70. data/lib/ltr/dataset_aggregation/dataset_saver.rb +79 -0
  71. data/lib/ltr/dataset_aggregation/derived_features.rb +45 -0
  72. data/lib/ltr/dataset_aggregation/display_positions.rb +25 -0
  73. data/lib/ltr/dataset_aggregation/dropped_events.rb +29 -0
  74. data/lib/ltr/dataset_aggregation/labels/README.md +18 -0
  75. data/lib/ltr/dataset_aggregation/labels/identity_label_transformer.rb +11 -0
  76. data/lib/ltr/dataset_aggregation/labels/label_transformer.rb +61 -0
  77. data/lib/ltr/dataset_aggregation/labels/log_plus_one_label_transformer.rb +18 -0
  78. data/lib/ltr/dataset_aggregation/labels/per_query_k_means_label_transformer.rb +141 -0
  79. data/lib/ltr/dataset_aggregation/labels/per_query_label_transformer.rb +52 -0
  80. data/lib/ltr/dataset_aggregation/labels/per_query_min_max_label_transformer.rb +27 -0
  81. data/lib/ltr/dataset_aggregation/labels/quantile_label_transformer.rb +73 -0
  82. data/lib/ltr/dataset_aggregation/labels/sqrt_label_transformer.rb +18 -0
  83. data/lib/ltr/dataset_aggregation/missing_hit_ids.rb +20 -0
  84. data/lib/ltr/dataset_aggregation/negative_rank.rb +15 -0
  85. data/lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb +209 -0
  86. data/lib/ltr/dataset_aggregation/sqlite_aggregator.rb +167 -0
  87. data/lib/ltr/dataset_aggregation/sqlite_event_stager.rb +79 -0
  88. data/lib/ltr/dataset_aggregation/sqlite_query_stager.rb +148 -0
  89. data/lib/ltr/dataset_aggregation/sqlite_staging.rb +180 -0
  90. data/lib/ltr/dataset_aggregation/sqlite_ubi_data_loader.rb +91 -0
  91. data/lib/ltr/dataset_aggregation/ubi_data_loader.rb +138 -0
  92. data/lib/ltr/dataset_aggregation/ubi_data_loader_base.rb +147 -0
  93. data/lib/ltr/dataset_aggregation/ubi_query_fields.rb +54 -0
  94. data/lib/ltr/deploy/README.md +21 -0
  95. data/lib/ltr/deploy/artifacts/code/inference.py +371 -0
  96. data/lib/ltr/deploy/artifacts/code/requirements.txt +1 -0
  97. data/lib/ltr/deploy/feature_extractor.rb +94 -0
  98. data/lib/ltr/deploy/feature_store_deployer.rb +88 -0
  99. data/lib/ltr/deploy/local_deployer.rb +61 -0
  100. data/lib/ltr/deploy/model_packager.rb +90 -0
  101. data/lib/ltr/deploy/sagemaker_deployer.rb +85 -0
  102. data/lib/ltr/deploy/sagemaker_endpoint.rb +199 -0
  103. data/lib/ltr/deploy/ssm_feature_source.rb +35 -0
  104. data/lib/ltr/errors/README.md +16 -0
  105. data/lib/ltr/errors/configuration_error.rb +5 -0
  106. data/lib/ltr/errors/deploy_error.rb +5 -0
  107. data/lib/ltr/errors/error.rb +5 -0
  108. data/lib/ltr/errors/invalid_dataset_error.rb +5 -0
  109. data/lib/ltr/errors/missing_dependency_error.rb +5 -0
  110. data/lib/ltr/errors/sqlite_error.rb +14 -0
  111. data/lib/ltr/features/README.md +19 -0
  112. data/lib/ltr/features/encoders/README.md +10 -0
  113. data/lib/ltr/features/encoders/enriched_column_encoder.rb +77 -0
  114. data/lib/ltr/features/encoders/feature_encoder.rb +61 -0
  115. data/lib/ltr/features/feature_engineering.rb +194 -0
  116. data/lib/ltr/features/feature_transformer.rb +92 -0
  117. data/lib/ltr/features/float32_range.rb +20 -0
  118. data/lib/ltr/features/transform_steps.rb +34 -0
  119. data/lib/ltr/features/transform_store.rb +123 -0
  120. data/lib/ltr/inference/README.md +11 -0
  121. data/lib/ltr/inference/base.rb +52 -0
  122. data/lib/ltr/inference/local_reranker.rb +147 -0
  123. data/lib/ltr/inference/sagemaker_client.rb +62 -0
  124. data/lib/ltr/metrics/README.md +12 -0
  125. data/lib/ltr/metrics/metric_scores.rb +67 -0
  126. data/lib/ltr/metrics/metrics.rb +139 -0
  127. data/lib/ltr/optimize/README.md +25 -0
  128. data/lib/ltr/optimize/bayesian_optimizer.rb +212 -0
  129. data/lib/ltr/optimize/candidate_selector.rb +97 -0
  130. data/lib/ltr/optimize/cholesky_decomposition.rb +81 -0
  131. data/lib/ltr/optimize/expected_improvement.rb +33 -0
  132. data/lib/ltr/optimize/feature_selection/README.md +15 -0
  133. data/lib/ltr/optimize/feature_selection/greedy_backward.rb +38 -0
  134. data/lib/ltr/optimize/feature_selection/importance_ranked.rb +23 -0
  135. data/lib/ltr/optimize/feature_selection/rfe.rb +22 -0
  136. data/lib/ltr/optimize/feature_selection/strategy.rb +112 -0
  137. data/lib/ltr/optimize/feature_selection/trial.rb +39 -0
  138. data/lib/ltr/optimize/gaussian_process.rb +125 -0
  139. data/lib/ltr/optimize/optimization_dataset.rb +16 -0
  140. data/lib/ltr/optimize/optimize_features.rb +129 -0
  141. data/lib/ltr/optimize/optimize_hyperparameters.rb +165 -0
  142. data/lib/ltr/optimize/optimize_pipeline.rb +105 -0
  143. data/lib/ltr/optimize/search_space.rb +165 -0
  144. data/lib/ltr/optimize/update_config.rb +196 -0
  145. data/lib/ltr/ssm/README.md +11 -0
  146. data/lib/ltr/ssm/loader.rb +61 -0
  147. data/lib/ltr/ssm/parameter_paths.rb +19 -0
  148. data/lib/ltr/ssm/saver.rb +76 -0
  149. data/lib/ltr/support/README.md +13 -0
  150. data/lib/ltr/support/callable.rb +10 -0
  151. data/lib/ltr/support/optional_dependency.rb +31 -0
  152. data/lib/ltr/support/pipeline_result.rb +22 -0
  153. data/lib/ltr/support/pipeline_task.rb +81 -0
  154. data/lib/ltr/support/version.rb +7 -0
  155. data/lib/ltr/tasks/ltr.rake +24 -0
  156. data/lib/ltr/train/README.md +19 -0
  157. data/lib/ltr/train/deploy_gate.rb +77 -0
  158. data/lib/ltr/train/deploy_metric.rb +63 -0
  159. data/lib/ltr/train/eval_logger.rb +16 -0
  160. data/lib/ltr/train/evaluation_cache.rb +101 -0
  161. data/lib/ltr/train/modelling_pipeline.rb +82 -0
  162. data/lib/ltr/train/optimization_split_report.rb +54 -0
  163. data/lib/ltr/train/utils.rb +35 -0
  164. data/lib/ltr/train/xgb_evaluator.rb +96 -0
  165. data/lib/ltr/train/xgb_trainer.rb +154 -0
  166. data/lib/ltr/ubi.rb +86 -0
  167. data/lib/ltr.rb +61 -0
  168. data/scripts/seed_ubi.rb +75 -0
  169. metadata +346 -0
@@ -0,0 +1,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Creates and manages the temporary SQLite database that holds the staged data.
4
+
5
+ class Ltr::DatasetAggregation::SqliteStaging
6
+ DATABASE_FILENAME = "ubi.sqlite3"
7
+ RUN_PREFIX = "ltr-aggregation-"
8
+
9
+ DEFAULT_CACHE_SIZE_MB = 256
10
+ DEFAULT_PAGE_SIZE = 8192
11
+
12
+ TABLES = %w[
13
+ staged_queries staged_events staged_query_ids
14
+ agg_actions agg_cutoff agg_examined agg_shadowed_scores agg_qids agg_latest agg_summed
15
+ ].freeze
16
+
17
+ # The directory that holds the staging directory of each run.
18
+ attr_reader :root
19
+
20
+ # The directory of this run, created under `root`. `cleanup!` deletes it.
21
+ attr_reader :path
22
+
23
+ # Returns `staging_root` from the config, or the system temp directory if that is blank.
24
+ # A relative `staging_root` is resolved against `Ltr.config.root`.
25
+ def self.resolve_root(config)
26
+ configured = config.dataset_aggregation.dig("staging_root")
27
+ return Pathname.new(Dir.tmpdir) if configured.blank?
28
+
29
+ pathname = Pathname.new(configured)
30
+ pathname.absolute? ? pathname : Ltr.config.root.join(configured)
31
+ end
32
+
33
+ def initialize(context)
34
+ @context = context
35
+ @config = context.config
36
+ @root = self.class.resolve_root(@config)
37
+ FileUtils.mkdir_p(@root)
38
+ @path = Pathname.new(Dir.mktmpdir(RUN_PREFIX, @root.to_s))
39
+ logger.info("Sqlite staging database: #{db_path}")
40
+ end
41
+
42
+ # Returns the path of the SQLite file.
43
+ def db_path
44
+ path.join(DATABASE_FILENAME)
45
+ end
46
+
47
+ # Returns the open database connection.
48
+ # It is opened on first use, with journaling and syncing off.
49
+ def db
50
+ @db ||= open_database
51
+ end
52
+
53
+ # Creates the tables that hold the staged queries, events and query IDs.
54
+ # Raises if the tables already exist.
55
+ def create_schema!
56
+ db.execute_batch(<<~SQL)
57
+ CREATE TABLE staged_queries (
58
+ query_id TEXT NOT NULL,
59
+ user_query TEXT NOT NULL,
60
+ timestamp TEXT,
61
+ doc_id TEXT NOT NULL,
62
+ original_position INTEGER NOT NULL,
63
+ scores_json TEXT NOT NULL#{qid_field_columns}
64
+ );
65
+
66
+ CREATE TABLE staged_events (
67
+ query_id TEXT NOT NULL,
68
+ doc_id TEXT NOT NULL,
69
+ action_name TEXT NOT NULL
70
+ );
71
+
72
+ CREATE TABLE staged_query_ids (query_id TEXT PRIMARY KEY, has_hit_ids INTEGER NOT NULL) WITHOUT ROWID;
73
+ SQL
74
+ end
75
+
76
+ def qid_field_names
77
+ context.additional_qid_fields
78
+ end
79
+
80
+ # Returns the size of the database file in bytes, or 0 if it does not exist.
81
+ def staged_bytes
82
+ db_path.exist? ? File.size(db_path) : 0
83
+ end
84
+
85
+ # Closes the database and deletes the staging directory.
86
+ def cleanup!
87
+ close_database
88
+ FileUtils.remove_entry(path) if path.exist?
89
+ end
90
+
91
+ # Logs one error line with the phase, the error, the table counts and the database size.
92
+ # For a `Ltr::SqliteError` it adds the failing statement.
93
+ # If any of this raises a `StandardError`, it logs a shorter line instead of raising.
94
+ def log_failure_diagnostics(phase, error)
95
+ details = ["phase=#{phase}", "error=#{error.class}: #{error.message}"]
96
+ details << "counts: #{table_counts}"
97
+ details << "database: #{format_bytes(staged_bytes)}"
98
+ details << "deleted: #{path}"
99
+ details << "failing statement:\n#{error.statement}" if error.is_a?(Ltr::SqliteError) && error.statement
100
+
101
+ logger.error("Sqlite aggregation failed -- #{details.join("; ")}")
102
+ rescue => diagnostics_error
103
+ logger.error("Sqlite aggregation failed during #{phase}; diagnostics unavailable (#{diagnostics_error.class})")
104
+ end
105
+
106
+ private
107
+
108
+ attr_reader :context, :config
109
+
110
+ def open_database
111
+ Ltr::OptionalDependency.require!("sqlite3", feature: "the sqlite aggregation engine")
112
+ database = SQLite3::Database.new(db_path.to_s, results_as_hash: true)
113
+ database.execute_batch(pragmas)
114
+ database
115
+ end
116
+
117
+ # The database is thrown away after each run, so crash safety is traded for write speed.
118
+ # A negative cache_size is in KiB, a positive one is in pages.
119
+ def pragmas
120
+ <<~SQL
121
+ PRAGMA page_size = #{page_size};
122
+ PRAGMA journal_mode = OFF;
123
+ PRAGMA synchronous = OFF;
124
+ PRAGMA temp_store = FILE;
125
+ PRAGMA cache_size = -#{cache_size_mb * 1024};
126
+ PRAGMA temp_store_directory = #{Ltr::DatasetAggregation::ColumnName.quote_literal(path)};
127
+ SQL
128
+ end
129
+
130
+ def page_size
131
+ Integer(sqlite_settings["page_size"] || DEFAULT_PAGE_SIZE)
132
+ end
133
+
134
+ def cache_size_mb
135
+ Integer(sqlite_settings["cache_size_mb"] || DEFAULT_CACHE_SIZE_MB)
136
+ end
137
+
138
+ def sqlite_settings
139
+ config.dataset_aggregation["sqlite"] || {}
140
+ end
141
+
142
+ def qid_field_columns
143
+ qid_field_names.map { |field| ",\n #{Ltr::DatasetAggregation::ColumnName.quote_column(field)} TEXT" }.join
144
+ end
145
+
146
+ def close_database
147
+ @db&.close unless @db&.closed?
148
+ @db = nil
149
+ rescue SQLite3::Exception
150
+ @db = nil
151
+ end
152
+
153
+ def table_counts
154
+ TABLES.filter_map do |table|
155
+ count = begin
156
+ db.get_first_value("SELECT count(*) FROM #{table}")
157
+ rescue SQLite3::Exception
158
+ nil
159
+ end
160
+ "#{table}=#{count}" if count
161
+ end.join(", ").presence || "none"
162
+ end
163
+
164
+ def format_bytes(bytes)
165
+ return "unknown" unless bytes
166
+
167
+ units = ["B", "KB", "MB", "GB", "TB"]
168
+ index = 0
169
+ value = bytes.to_f
170
+ while value >= 1024 && index < units.length - 1
171
+ value /= 1024
172
+ index += 1
173
+ end
174
+ "#{value.round(1)} #{units[index]}"
175
+ end
176
+
177
+ def logger
178
+ Ltr.config.logger
179
+ end
180
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loads UBI events and queries from OpenSearch into the SQLite staging database.
4
+
5
+ class Ltr::DatasetAggregation::SqliteUbiDataLoader < Ltr::DatasetAggregation::UbiDataLoaderBase
6
+ DEFAULT_BATCH_SIZE = 10_000
7
+
8
+ def initialize(config, staging, context, start_date: nil, end_date: nil, n_events: nil,
9
+ custom_queries_filters: nil, custom_events_filters: nil)
10
+ super(config, start_date: start_date, end_date: end_date, n_events: n_events,
11
+ custom_queries_filters: custom_queries_filters,
12
+ custom_events_filters: custom_events_filters)
13
+ @staging = staging
14
+ @context = context
15
+ end
16
+
17
+ # Stages the events with a cascade action, then the queries of those events, in the SQLite database.
18
+ # Raises `Ltr::ConfigurationError` if `conversion_rate_targets` is empty, a `conversion_features` action is not a cascade action, a cascade action's `<action>_count` column is not a usable name, or `additional_qid_fields` is not an array of strings, holds a bad, reserved or repeated name, or names an `<action>_count` column. Raises `ArgumentError` if the dates, the event count or the custom filters are invalid.
19
+ def call
20
+ validate_inputs!
21
+ staging.create_schema!
22
+
23
+ event_rows, query_ids = event_stager.stage_events
24
+ logger.info("Staged #{event_rows} cascade-action event rows, #{query_ids.length} unique query IDs")
25
+
26
+ query_stager.stage_queries(query_ids)
27
+ end
28
+
29
+ private
30
+
31
+ attr_reader :staging, :context
32
+
33
+ def default_batch_size
34
+ DEFAULT_BATCH_SIZE
35
+ end
36
+
37
+ def event_stager
38
+ Ltr::DatasetAggregation::SqliteEventStager.new(
39
+ staging: staging, context: context, batch_size: batch_size, n_events: n_events, logger: logger,
40
+ fetch: lambda { |size, search_after|
41
+ result = fetch_events(size, search_after)
42
+ [extract_hits(result), extract_search_after(result)]
43
+ }
44
+ )
45
+ end
46
+
47
+ def fetch_events(size, search_after)
48
+ body = {
49
+ query: events_query,
50
+ size: size,
51
+ sort: SEARCH_SORT,
52
+ _source: events_source_fields,
53
+ }
54
+ body[:search_after] = search_after if search_after
55
+
56
+ retry_opensearch { |client| client.search(index: events_index, body: body) }
57
+ end
58
+
59
+ def events_query
60
+ filters = [date_range_filter, cascade_actions_filter]
61
+ filters.concat(custom_events_filters)
62
+ { bool: { filter: filters.compact } }
63
+ end
64
+
65
+ def query_stager
66
+ Ltr::DatasetAggregation::SqliteQueryStager.new(
67
+ staging: staging, context: context, batch_size: batch_size, logger: logger,
68
+ fetch: lambda { |slice_query_ids, search_after|
69
+ result = fetch_queries(slice_query_ids, search_after)
70
+ [extract_hits(result), extract_search_after(result)]
71
+ }
72
+ )
73
+ end
74
+
75
+ def fetch_queries(slice_query_ids, search_after)
76
+ body = {
77
+ query: queries_query(slice_query_ids),
78
+ size: batch_size,
79
+ sort: SEARCH_SORT,
80
+ _source: queries_source_fields,
81
+ }
82
+ body[:search_after] = search_after if search_after
83
+
84
+ retry_opensearch { |client| client.search(index: queries_index, body: body) }
85
+ end
86
+
87
+ def queries_query(slice_query_ids)
88
+ filters = custom_queries_filters + [{ terms: { context.query_id_field => slice_query_ids } }]
89
+ { bool: { filter: filters.compact } }
90
+ end
91
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loads UBI events and queries from OpenSearch into memory.
4
+
5
+ class Ltr::DatasetAggregation::UbiDataLoader < Ltr::DatasetAggregation::UbiDataLoaderBase
6
+ DEFAULT_BATCH_SIZE = 100
7
+
8
+ # Loads up to `n_events` cascade-action events from OpenSearch, then the queries for the query IDs of those events.
9
+ # Raises `Ltr::ConfigurationError` if `conversion_rate_targets` is empty, a `conversion_features` action is not a cascade action, a cascade action's `<action>_count` column is not a usable name, or `additional_qid_fields` is not an array of strings, holds a bad, reserved or repeated name, or names an `<action>_count` column. Raises `ArgumentError` if the dates, the event count or the custom filters are invalid.
10
+ # Returns a hash with `:queries` and `:events`.
11
+ def call
12
+ validate_inputs!
13
+ result = load_events_and_queries
14
+ logger.info("UBI data loading completed. Queries: #{result[:queries]&.length || 0}, Events: #{result[:events]&.length || 0}")
15
+ result
16
+ end
17
+
18
+ private
19
+
20
+ def default_batch_size
21
+ DEFAULT_BATCH_SIZE
22
+ end
23
+
24
+ def load_events_and_queries
25
+ events = load_events_data
26
+ logger.info("Events loaded: #{events.length} total events")
27
+
28
+ query_ids = extract_query_ids_from_events(events)
29
+ logger.info("Found #{query_ids.length} unique query IDs")
30
+
31
+ queries = fetch_queries_by_ids(query_ids)
32
+ logger.info("Queries fetched: #{queries.length} total queries")
33
+
34
+ { queries: queries, events: events }
35
+ end
36
+
37
+ def load_events_data
38
+ events = []
39
+ search_after = nil
40
+ remaining = n_events
41
+ batch_count = 0
42
+
43
+ while remaining > 0
44
+ current_batch_size = [remaining, batch_size].min
45
+ batch_count += 1
46
+ logger.info("Processing batch #{batch_count}, requesting #{current_batch_size} events, #{remaining} remaining")
47
+
48
+ result = search_events(current_batch_size, search_after)
49
+
50
+ hits = extract_hits(result)
51
+ logger.info("Batch #{batch_count} returned #{hits.length} events")
52
+ break if hits.empty?
53
+
54
+ events.concat(hits)
55
+ remaining -= hits.length
56
+ search_after = extract_search_after(result)
57
+ break unless search_after
58
+ end
59
+
60
+ events
61
+ end
62
+
63
+ def search_events(size, search_after)
64
+ query = build_query_for_events(custom_events_filters)
65
+ search_body = build_search_body(events_index, query, events_source_fields, size, search_after: search_after)
66
+ retry_opensearch { |client| client.search(search_body) }
67
+ end
68
+
69
+ def build_query_for_events(additional_filters)
70
+ filters = [date_range_filter, cascade_actions_filter]
71
+ filters.concat(additional_filters)
72
+ { bool: { filter: filters.compact } }
73
+ end
74
+
75
+ def build_search_body(index, query, source_fields, size, search_after: nil)
76
+ search_body = {
77
+ query: query,
78
+ size: size,
79
+ sort: SEARCH_SORT,
80
+ _source: source_fields,
81
+ }
82
+ search_body[:search_after] = search_after if search_after
83
+
84
+ {
85
+ index: index,
86
+ body: search_body,
87
+ }
88
+ end
89
+
90
+ def extract_query_ids_from_events(events)
91
+ events.filter_map { |event| event[config.query_id_field] }.uniq
92
+ end
93
+
94
+ def fetch_queries_by_ids(query_ids)
95
+ return [] if query_ids.empty?
96
+
97
+ queries = []
98
+ batch_count = 0
99
+
100
+ query_ids.each_slice(batch_size) do |batch_query_ids|
101
+ batch_count += 1
102
+ logger.info("Processing query batch #{batch_count}, size: #{batch_query_ids.length}")
103
+
104
+ hits = fetch_query_pages(batch_query_ids)
105
+ logger.info("Query batch #{batch_count} returned #{hits.length} queries")
106
+ queries.concat(hits)
107
+ end
108
+
109
+ queries
110
+ end
111
+
112
+ def fetch_query_pages(batch_query_ids)
113
+ hits = []
114
+ search_after = nil
115
+
116
+ loop do
117
+ result = search_queries(batch_query_ids, search_after)
118
+ page = extract_hits(result)
119
+ hits.concat(page)
120
+ search_after = extract_search_after(result)
121
+ break if page.length < batch_size || !search_after
122
+ end
123
+
124
+ hits
125
+ end
126
+
127
+ def search_queries(batch_query_ids, search_after)
128
+ query = build_query_for_query_ids(batch_query_ids)
129
+ search_body = build_search_body(queries_index, query, queries_source_fields, batch_size, search_after: search_after)
130
+ retry_opensearch { |client| client.search(search_body) }
131
+ end
132
+
133
+ def build_query_for_query_ids(query_ids)
134
+ query_id_filter = { terms: { config.query_id_field.to_sym => query_ids } }
135
+ filters = custom_queries_filters + [query_id_filter]
136
+ { bool: { filter: filters.compact } }
137
+ end
138
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Base class for the UBI data loaders.
4
+ # Handles the date range (whole UTC days), filters, batch size and OpenSearch retries.
5
+ # Both loaders fetch only events whose action is a cascade action, so `n_events` counts the same events in both.
6
+
7
+ class Ltr::DatasetAggregation::UbiDataLoaderBase
8
+ extend Ltr::Callable
9
+
10
+ MAX_RETRIES = 5
11
+ # The 4xx statuses that mean "try again later" (request timeout, too many requests).
12
+ RETRYABLE_CLIENT_STATUSES = [408, 429].freeze
13
+ RETRY_BACKOFF_SECONDS = 10
14
+ SEARCH_SORT = [{ timestamp: { order: :desc } }, { _doc: { order: :asc } }].freeze
15
+ QUERY_SOURCE_FIELDS = %w[user_query query_attributes timestamp].freeze
16
+ EVENT_SOURCE_FIELDS = %w[action_name event_attributes].freeze
17
+
18
+ def initialize(config, start_date: nil, end_date: nil, n_events: nil, custom_queries_filters: nil, custom_events_filters: nil)
19
+ @config = config
20
+ # Read the clock once. Two reads can straddle UTC midnight and move the window by a day.
21
+ today = Time.now.utc.to_date
22
+ @start_date = start_date || today - config.ubi_data_loader.dig("max_days_ago")
23
+ @end_date = end_date || today
24
+ @n_events = n_events || default_n_events
25
+ @custom_queries_filters = custom_queries_filters || config_custom_filters("queries")
26
+ @custom_events_filters = custom_events_filters || config_custom_filters("events")
27
+ @batch_size = config.ubi_data_loader["batch_size"] || default_batch_size
28
+ end
29
+
30
+ private
31
+
32
+ attr_reader :config, :start_date, :end_date, :n_events, :custom_queries_filters, :custom_events_filters, :batch_size
33
+
34
+ def default_n_events
35
+ config.ubi_data_loader.dig("n_events")
36
+ end
37
+
38
+ def config_custom_filters(query_type)
39
+ return [] unless config.respond_to?(:custom_filters)
40
+
41
+ custom_filters_path = config.custom_filters
42
+ return [] if custom_filters_path.blank?
43
+
44
+ @custom_filters_yaml ||= YAML.load_file(custom_filters_path)
45
+ @custom_filters_yaml[query_type] || []
46
+ end
47
+
48
+ def validate_inputs!
49
+ raise ArgumentError, "Start and end dates must be Date objects (UTC dates)" unless [start_date, end_date].all? { |date| date.instance_of?(Date) }
50
+ raise ArgumentError, "Start date cannot be after end date" if start_date > end_date
51
+ raise ArgumentError, "Number of events must be positive" if n_events <= 0
52
+ raise ArgumentError, "Custom queries filters must be an array" if !custom_queries_filters.is_a?(Array)
53
+ raise ArgumentError, "Custom events filters must be an array" if !custom_events_filters.is_a?(Array)
54
+ Ltr::ConfigValidator.new(config.config).validate_aggregation!
55
+ end
56
+
57
+ def cascade_actions
58
+ @cascade_actions ||= Ltr::DatasetAggregation::CascadeActions.for(config.dataset_builder["conversion_rate_targets"] || [])
59
+ end
60
+
61
+ def queries_source_fields
62
+ additional_qid_fields = config.dataset_builder["additional_qid_fields"] || []
63
+ [config.query_id_field, *QUERY_SOURCE_FIELDS, config.hit_ids_field, *additional_qid_fields.map(&:to_s)].uniq
64
+ end
65
+
66
+ def events_source_fields
67
+ [config.query_id_field, *EVENT_SOURCE_FIELDS]
68
+ end
69
+
70
+ def cascade_actions_filter
71
+ { terms: { action_name: cascade_actions } }
72
+ end
73
+
74
+ def date_range_filter
75
+ {
76
+ range: {
77
+ timestamp: {
78
+ gte: "#{start_date.iso8601}T00:00:00Z",
79
+ lte: "#{end_date.iso8601}T23:59:59Z",
80
+ },
81
+ },
82
+ }
83
+ end
84
+
85
+ def extract_hits(search_result)
86
+ search_result.dig("hits", "hits")&.pluck("_source") || []
87
+ end
88
+
89
+ def extract_search_after(result)
90
+ result.dig("hits", "hits", -1, "sort")
91
+ end
92
+
93
+ def queries_index
94
+ config.ubi_data_loader.dig("index", "queries")
95
+ end
96
+
97
+ def events_index
98
+ config.ubi_data_loader.dig("index", "events")
99
+ end
100
+
101
+ def opensearch_client
102
+ @opensearch_client ||= build_opensearch_client
103
+ end
104
+
105
+ def build_opensearch_client
106
+ url = config.ubi_data_loader.dig("opensearch", "url")
107
+ username = config.ubi_data_loader.dig("opensearch", "username")
108
+ password = config.ubi_data_loader.dig("opensearch", "password")
109
+
110
+ raise ArgumentError, "OpenSearch URL is required" if url.blank?
111
+
112
+ Ltr::OptionalDependency.require!("opensearch-ruby", feature: "loading UBI data from OpenSearch")
113
+ ::OpenSearch::Client.new(Ltr.config.opensearch_connect_options(url, username, password))
114
+ end
115
+
116
+ def retry_opensearch
117
+ retries = 0
118
+ client = opensearch_client
119
+ begin
120
+ yield client
121
+ rescue Faraday::ConnectionFailed, Faraday::TimeoutError, OpenSearch::Transport::Transport::ServerError => e
122
+ raise e unless retryable?(e)
123
+
124
+ logger.warn("OpenSearch request failed (attempt #{retries + 1}/#{MAX_RETRIES}): #{e.message}")
125
+ raise e if (retries += 1) >= MAX_RETRIES
126
+ sleep(RETRY_BACKOFF_SECONDS * retries)
127
+ retry
128
+ end
129
+ end
130
+
131
+ # The gem makes every HTTP status error a `ServerError`, so a 4xx has to be told apart by its status.
132
+ def retryable?(error)
133
+ return true unless error.is_a?(OpenSearch::Transport::Transport::ServerError)
134
+
135
+ status = http_status(error)
136
+ !status.nil? && (status >= 500 || RETRYABLE_CLIENT_STATUSES.include?(status))
137
+ end
138
+
139
+ # The gem starts the message of every HTTP error with the status, like `[404] ...`, whether it maps a class or not.
140
+ def http_status(error)
141
+ error.message[/\A\[(\d{3})\]/, 1]&.to_i
142
+ end
143
+
144
+ def logger
145
+ Ltr.config.logger
146
+ end
147
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Reads a field from a UBI query record or from its document scores.
4
+
5
+ module Ltr::DatasetAggregation::UbiQueryFields
6
+ module_function
7
+
8
+ # Returns the `scores` hash of a query record, or nil when `query_attributes` is missing or has no `scores`.
9
+ # Raises `Ltr::InvalidDatasetError` naming the query when `query_attributes` or its `scores` is present and not a hash.
10
+ def scores_by_doc(query, query_id_field:)
11
+ query_attributes = query["query_attributes"]
12
+ return nil if query_attributes.nil?
13
+
14
+ ensure_hash!(query_attributes, "query_attributes", query, query_id_field)
15
+ scores = query_attributes["scores"]
16
+ ensure_hash!(scores, "query_attributes.scores", query, query_id_field) unless scores.nil?
17
+ scores
18
+ end
19
+
20
+ # Returns true if the query has a non-empty array of hit IDs.
21
+ def hit_ids?(query, hit_ids_field:)
22
+ hit_ids = query[hit_ids_field]
23
+ hit_ids.is_a?(Array) && hit_ids.any?
24
+ end
25
+
26
+ def ensure_hash!(value, name, query, query_id_field)
27
+ return if value.is_a?(Hash)
28
+
29
+ raise Ltr::InvalidDatasetError,
30
+ "ubi_queries record for query #{query[query_id_field].to_s.inspect}: #{name} must be a hash, got #{value.class}"
31
+ end
32
+ private_class_method :ensure_hash!
33
+
34
+ # Returns the value of an additional qid field as text, or nil when the query has none.
35
+ # Both engines group queries on this text, so the values 1 and "1" are one group.
36
+ def qid_field_value(query, field, query_id_field:)
37
+ extract_field_value(query, field, query_id_field: query_id_field)&.to_s
38
+ end
39
+
40
+ # Returns `query[field]` if the query has that key, even when the value is nil.
41
+ # Otherwise returns the field from the scores of its first document, or nil if that has no such key.
42
+ def extract_field_value(query, field, query_id_field:)
43
+ return query[field] if query.key?(field)
44
+
45
+ # A field may sit in the document scores instead of on the query. The first document is used.
46
+ scores = scores_by_doc(query, query_id_field: query_id_field)
47
+ if scores&.any?
48
+ first_doc_scores = scores.values.first
49
+ return first_doc_scores[field] if first_doc_scores.is_a?(Hash) && first_doc_scores.key?(field)
50
+ end
51
+
52
+ nil
53
+ end
54
+ end
@@ -0,0 +1,21 @@
1
+ # `lib/ltr/deploy`
2
+
3
+ Deployment of trained models within the `Ltr::Deploy` namespace: packaging the XGBoost booster with Python inference artifacts, pushing to a SageMaker endpoint, building the feature store for the model archive, and persisting a model locally. This is the bridge between the training pipeline's output and query-time inference. Both model deployers read the [`.serving.json` file](../../../docs/model-files.md#dataset-serving-file) next to the dataset before saving the model.
4
+
5
+ ## Subfolders
6
+
7
+ | Folder | Purpose |
8
+ |---|---|
9
+ | `artifacts/` | Python inference artifacts (`code/inference.py`, `code/requirements.txt`) packaged into the SageMaker model tarball; ignored by the Zeitwerk autoloader since it contains no Ruby. `inference.py` runs in the SageMaker XGBoost container. Its `transform_fn` answers bad input with HTTP 400 for a `BadRequestError`. It clamps an infinite or too large number to the float32 range instead; see [inference](../../../docs/inference.md). |
10
+
11
+ ## Files
12
+
13
+ | File | Purpose |
14
+ |---|---|
15
+ | `feature_extractor.rb` | Extracts the configured per-document feature values from the modelling dataset CSV, taking the first occurrence of each document. |
16
+ | `feature_store_deployer.rb` | Builds the feature store map from the modelling dataset. It also fills missing values from `fallback_feature_totals` in the serving file. It is for `SagemakerDeployer` and `LocalDeployer` to bundle with the model. Reports failures through `Ltr.config.report_error` and re-raises. |
17
+ | `local_deployer.rb` | Persists a trained booster to the configured `deploy.local_path` when local deployment is enabled and the deploy metric meets the minimum, with the feature transform steps, the one-hot column names and the feature store stored in the model file. |
18
+ | `sagemaker_deployer.rb` | Runs the deploy in order: builds `ModelPackager` with a feature list lambda that `ModelPackager` resolves after it saves the model, then builds `SagemakerEndpoint`. |
19
+ | `model_packager.rb` | Packages the booster with the Python inference code into a `model.tar.gz` built in a temp folder, and uploads the tarball to S3. |
20
+ | `sagemaker_endpoint.rb` | Creates/updates the SageMaker model, endpoint config, and endpoint, and waits for it to be `InService` on the new endpoint config. |
21
+ | `ssm_feature_source.rb` | Reads an optimized feature list from SSM for `SagemakerDeployer` and `FeatureStoreDeployer`. |