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.
- checksums.yaml +7 -0
- data/ARCHITECTURE.md +92 -0
- data/CHANGELOG.md +5 -0
- data/LICENSE +21 -0
- data/README.md +186 -0
- data/docs/AGENTS.md +67 -0
- data/docs/aggregation-engines.md +80 -0
- data/docs/config.md +516 -0
- data/docs/data-contracts.md +94 -0
- data/docs/data-splits.md +34 -0
- data/docs/dataset-builder-steps.md +13 -0
- data/docs/dataset-csv.md +73 -0
- data/docs/dataset-enrichers.md +62 -0
- data/docs/errors.md +33 -0
- data/docs/feature-selection.md +108 -0
- data/docs/features.md +202 -0
- data/docs/glossary.md +56 -0
- data/docs/host-integration.md +128 -0
- data/docs/host-run-pipelines.md +48 -0
- data/docs/index.md +50 -0
- data/docs/inference.md +164 -0
- data/docs/label-transformers.md +242 -0
- data/docs/labels-from-behavior.md +94 -0
- data/docs/learning-to-rank.md +119 -0
- data/docs/metrics.md +166 -0
- data/docs/model-files.md +73 -0
- data/docs/optimization.md +72 -0
- data/docs/public-api.md +67 -0
- data/docs/rake-tasks.md +82 -0
- data/docs/relevance-grades.md +80 -0
- data/docs/run-locally.md +584 -0
- data/docs/run-on-aws.md +647 -0
- data/docs/training-objective.md +110 -0
- data/docs/ubi-documents.md +75 -0
- data/docs/ubi-logging.md +125 -0
- data/lib/ltr/README.md +28 -0
- data/lib/ltr/configuration/README.md +12 -0
- data/lib/ltr/configuration/config_loader.rb +326 -0
- data/lib/ltr/configuration/config_validator.rb +476 -0
- data/lib/ltr/configuration/configuration.rb +84 -0
- data/lib/ltr/configuration/example_config.yml +182 -0
- data/lib/ltr/data/README.md +20 -0
- data/lib/ltr/data/csv/README.md +9 -0
- data/lib/ltr/data/csv/typed_columns.rb +101 -0
- data/lib/ltr/data/csv.rb +126 -0
- data/lib/ltr/data/dataframe.rb +80 -0
- data/lib/ltr/data/dataset_loader.rb +29 -0
- data/lib/ltr/data/row_store.rb +188 -0
- data/lib/ltr/data/split_cache.rb +30 -0
- data/lib/ltr/data/splits.rb +86 -0
- data/lib/ltr/dataset_aggregation/README.md +32 -0
- data/lib/ltr/dataset_aggregation/aggregated_sqlite_loader.rb +64 -0
- data/lib/ltr/dataset_aggregation/cascade_actions.rb +58 -0
- data/lib/ltr/dataset_aggregation/column_name.rb +47 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/README.md +15 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/context.rb +159 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/README.md +16 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/behavioural_feature_builder.rb +77 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/dataset_filters.rb +29 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/label_creator.rb +125 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/negative_downsampler.rb +52 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/query_aggregator.rb +163 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/split_assigner.rb +76 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/ubi_joiner.rb +137 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/user_query_aggregator.rb +68 -0
- data/lib/ltr/dataset_aggregation/dataset_builder.rb +82 -0
- data/lib/ltr/dataset_aggregation/dataset_enricher.rb +168 -0
- data/lib/ltr/dataset_aggregation/dataset_finalizer.rb +116 -0
- data/lib/ltr/dataset_aggregation/dataset_pipeline.rb +113 -0
- data/lib/ltr/dataset_aggregation/dataset_saver.rb +79 -0
- data/lib/ltr/dataset_aggregation/derived_features.rb +45 -0
- data/lib/ltr/dataset_aggregation/display_positions.rb +25 -0
- data/lib/ltr/dataset_aggregation/dropped_events.rb +29 -0
- data/lib/ltr/dataset_aggregation/labels/README.md +18 -0
- data/lib/ltr/dataset_aggregation/labels/identity_label_transformer.rb +11 -0
- data/lib/ltr/dataset_aggregation/labels/label_transformer.rb +61 -0
- data/lib/ltr/dataset_aggregation/labels/log_plus_one_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_k_means_label_transformer.rb +141 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_label_transformer.rb +52 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_min_max_label_transformer.rb +27 -0
- data/lib/ltr/dataset_aggregation/labels/quantile_label_transformer.rb +73 -0
- data/lib/ltr/dataset_aggregation/labels/sqrt_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/missing_hit_ids.rb +20 -0
- data/lib/ltr/dataset_aggregation/negative_rank.rb +15 -0
- data/lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb +209 -0
- data/lib/ltr/dataset_aggregation/sqlite_aggregator.rb +167 -0
- data/lib/ltr/dataset_aggregation/sqlite_event_stager.rb +79 -0
- data/lib/ltr/dataset_aggregation/sqlite_query_stager.rb +148 -0
- data/lib/ltr/dataset_aggregation/sqlite_staging.rb +180 -0
- data/lib/ltr/dataset_aggregation/sqlite_ubi_data_loader.rb +91 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader.rb +138 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader_base.rb +147 -0
- data/lib/ltr/dataset_aggregation/ubi_query_fields.rb +54 -0
- data/lib/ltr/deploy/README.md +21 -0
- data/lib/ltr/deploy/artifacts/code/inference.py +371 -0
- data/lib/ltr/deploy/artifacts/code/requirements.txt +1 -0
- data/lib/ltr/deploy/feature_extractor.rb +94 -0
- data/lib/ltr/deploy/feature_store_deployer.rb +88 -0
- data/lib/ltr/deploy/local_deployer.rb +61 -0
- data/lib/ltr/deploy/model_packager.rb +90 -0
- data/lib/ltr/deploy/sagemaker_deployer.rb +85 -0
- data/lib/ltr/deploy/sagemaker_endpoint.rb +199 -0
- data/lib/ltr/deploy/ssm_feature_source.rb +35 -0
- data/lib/ltr/errors/README.md +16 -0
- data/lib/ltr/errors/configuration_error.rb +5 -0
- data/lib/ltr/errors/deploy_error.rb +5 -0
- data/lib/ltr/errors/error.rb +5 -0
- data/lib/ltr/errors/invalid_dataset_error.rb +5 -0
- data/lib/ltr/errors/missing_dependency_error.rb +5 -0
- data/lib/ltr/errors/sqlite_error.rb +14 -0
- data/lib/ltr/features/README.md +19 -0
- data/lib/ltr/features/encoders/README.md +10 -0
- data/lib/ltr/features/encoders/enriched_column_encoder.rb +77 -0
- data/lib/ltr/features/encoders/feature_encoder.rb +61 -0
- data/lib/ltr/features/feature_engineering.rb +194 -0
- data/lib/ltr/features/feature_transformer.rb +92 -0
- data/lib/ltr/features/float32_range.rb +20 -0
- data/lib/ltr/features/transform_steps.rb +34 -0
- data/lib/ltr/features/transform_store.rb +123 -0
- data/lib/ltr/inference/README.md +11 -0
- data/lib/ltr/inference/base.rb +52 -0
- data/lib/ltr/inference/local_reranker.rb +147 -0
- data/lib/ltr/inference/sagemaker_client.rb +62 -0
- data/lib/ltr/metrics/README.md +12 -0
- data/lib/ltr/metrics/metric_scores.rb +67 -0
- data/lib/ltr/metrics/metrics.rb +139 -0
- data/lib/ltr/optimize/README.md +25 -0
- data/lib/ltr/optimize/bayesian_optimizer.rb +212 -0
- data/lib/ltr/optimize/candidate_selector.rb +97 -0
- data/lib/ltr/optimize/cholesky_decomposition.rb +81 -0
- data/lib/ltr/optimize/expected_improvement.rb +33 -0
- data/lib/ltr/optimize/feature_selection/README.md +15 -0
- data/lib/ltr/optimize/feature_selection/greedy_backward.rb +38 -0
- data/lib/ltr/optimize/feature_selection/importance_ranked.rb +23 -0
- data/lib/ltr/optimize/feature_selection/rfe.rb +22 -0
- data/lib/ltr/optimize/feature_selection/strategy.rb +112 -0
- data/lib/ltr/optimize/feature_selection/trial.rb +39 -0
- data/lib/ltr/optimize/gaussian_process.rb +125 -0
- data/lib/ltr/optimize/optimization_dataset.rb +16 -0
- data/lib/ltr/optimize/optimize_features.rb +129 -0
- data/lib/ltr/optimize/optimize_hyperparameters.rb +165 -0
- data/lib/ltr/optimize/optimize_pipeline.rb +105 -0
- data/lib/ltr/optimize/search_space.rb +165 -0
- data/lib/ltr/optimize/update_config.rb +196 -0
- data/lib/ltr/ssm/README.md +11 -0
- data/lib/ltr/ssm/loader.rb +61 -0
- data/lib/ltr/ssm/parameter_paths.rb +19 -0
- data/lib/ltr/ssm/saver.rb +76 -0
- data/lib/ltr/support/README.md +13 -0
- data/lib/ltr/support/callable.rb +10 -0
- data/lib/ltr/support/optional_dependency.rb +31 -0
- data/lib/ltr/support/pipeline_result.rb +22 -0
- data/lib/ltr/support/pipeline_task.rb +81 -0
- data/lib/ltr/support/version.rb +7 -0
- data/lib/ltr/tasks/ltr.rake +24 -0
- data/lib/ltr/train/README.md +19 -0
- data/lib/ltr/train/deploy_gate.rb +77 -0
- data/lib/ltr/train/deploy_metric.rb +63 -0
- data/lib/ltr/train/eval_logger.rb +16 -0
- data/lib/ltr/train/evaluation_cache.rb +101 -0
- data/lib/ltr/train/modelling_pipeline.rb +82 -0
- data/lib/ltr/train/optimization_split_report.rb +54 -0
- data/lib/ltr/train/utils.rb +35 -0
- data/lib/ltr/train/xgb_evaluator.rb +96 -0
- data/lib/ltr/train/xgb_trainer.rb +154 -0
- data/lib/ltr/ubi.rb +86 -0
- data/lib/ltr.rb +61 -0
- data/scripts/seed_ubi.rb +75 -0
- metadata +346 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
-- Cascade examination and per-(qid, doc) aggregation, out-of-core. Rendered from the
|
|
2
|
+
-- config and executed statement by statement by SqliteAggregator. How to configure
|
|
3
|
+
-- and debug the engine is in docs/aggregation-engines.md.
|
|
4
|
+
|
|
5
|
+
-- STATEMENT: index_staged_queries
|
|
6
|
+
CREATE INDEX idx_staged_queries_qid_doc ON staged_queries(query_id, doc_id);
|
|
7
|
+
|
|
8
|
+
-- STATEMENT: index_staged_events
|
|
9
|
+
CREATE INDEX idx_staged_events_qid_doc ON staged_events(query_id, doc_id, action_name);
|
|
10
|
+
|
|
11
|
+
-- STATEMENT: analyze_staged
|
|
12
|
+
ANALYZE;
|
|
13
|
+
|
|
14
|
+
-- STATEMENT: agg_actions
|
|
15
|
+
CREATE TABLE agg_actions AS
|
|
16
|
+
SELECT
|
|
17
|
+
e.query_id AS query_id,
|
|
18
|
+
e.doc_id AS doc_id
|
|
19
|
+
<% action_columns.each do |(action, column)| -%>
|
|
20
|
+
, max(CASE WHEN e.action_name = <%= quote.call(action) %> THEN 1 ELSE 0 END) AS <%= column %>
|
|
21
|
+
<% end -%>
|
|
22
|
+
FROM staged_events e
|
|
23
|
+
WHERE e.action_name IN (<%= action_literals %>)
|
|
24
|
+
AND EXISTS (
|
|
25
|
+
SELECT 1 FROM staged_queries q WHERE q.query_id = e.query_id AND q.doc_id = e.doc_id
|
|
26
|
+
)
|
|
27
|
+
GROUP BY e.query_id, e.doc_id;
|
|
28
|
+
|
|
29
|
+
-- STATEMENT: index_agg_actions
|
|
30
|
+
CREATE UNIQUE INDEX idx_agg_actions ON agg_actions(query_id, doc_id);
|
|
31
|
+
|
|
32
|
+
-- STATEMENT: agg_cutoff
|
|
33
|
+
-- The cutoff is the lowest-ranked document with an action. Documents ranked below it were not examined.
|
|
34
|
+
CREATE TABLE agg_cutoff AS
|
|
35
|
+
SELECT q.query_id AS query_id, max(q.original_position) AS cutoff_position
|
|
36
|
+
FROM staged_queries q
|
|
37
|
+
JOIN agg_actions a ON a.query_id = q.query_id AND a.doc_id = q.doc_id
|
|
38
|
+
GROUP BY q.query_id;
|
|
39
|
+
|
|
40
|
+
-- STATEMENT: index_agg_cutoff
|
|
41
|
+
CREATE UNIQUE INDEX idx_agg_cutoff ON agg_cutoff(query_id);
|
|
42
|
+
|
|
43
|
+
-- STATEMENT: agg_examined
|
|
44
|
+
CREATE TABLE agg_examined AS
|
|
45
|
+
SELECT
|
|
46
|
+
q.rowid AS source_position,
|
|
47
|
+
q.user_query AS user_query,
|
|
48
|
+
<% qid_field_columns.each do |column| -%>
|
|
49
|
+
q.<%= column %> AS <%= column %>,
|
|
50
|
+
<% end -%>
|
|
51
|
+
q.doc_id AS doc_id,
|
|
52
|
+
q.timestamp AS timestamp,
|
|
53
|
+
q.original_position AS original_position,
|
|
54
|
+
q.scores_json AS scores_json,
|
|
55
|
+
<% if cascade_cutoff -%>
|
|
56
|
+
1 AS impression_count
|
|
57
|
+
<% else -%>
|
|
58
|
+
CASE WHEN q.original_position <= c.cutoff_position THEN 1 ELSE 0 END AS impression_count
|
|
59
|
+
<% end -%>
|
|
60
|
+
<% action_columns.each do |(_action, column)| -%>
|
|
61
|
+
, coalesce(a.<%= column %>, 0) AS <%= column %>
|
|
62
|
+
<% end -%>
|
|
63
|
+
FROM staged_queries q
|
|
64
|
+
JOIN agg_cutoff c ON c.query_id = q.query_id
|
|
65
|
+
LEFT JOIN agg_actions a ON a.query_id = q.query_id AND a.doc_id = q.doc_id
|
|
66
|
+
<% if cascade_cutoff -%>
|
|
67
|
+
WHERE q.original_position <= c.cutoff_position;
|
|
68
|
+
<% else -%>
|
|
69
|
+
;
|
|
70
|
+
<% end -%>
|
|
71
|
+
|
|
72
|
+
-- STATEMENT: index_agg_examined
|
|
73
|
+
CREATE INDEX idx_agg_examined ON agg_examined(<%= qid_key_list %>, doc_id);
|
|
74
|
+
|
|
75
|
+
-- STATEMENT: collect_shadowed_scores
|
|
76
|
+
-- Keeps the reserved feature names that any examined session logged, because agg_latest keeps one session's scores only.
|
|
77
|
+
CREATE TABLE agg_shadowed_scores AS
|
|
78
|
+
SELECT DISTINCT j.key AS name
|
|
79
|
+
FROM agg_examined e,
|
|
80
|
+
json_each(CASE WHEN json_valid(e.scores_json) AND json_type(e.scores_json) = 'object' THEN e.scores_json ELSE '{}' END) j
|
|
81
|
+
WHERE j.key IN (<%= reserved_feature_literals %>);
|
|
82
|
+
|
|
83
|
+
-- STATEMENT: drop_staged_queries
|
|
84
|
+
DROP TABLE staged_queries;
|
|
85
|
+
|
|
86
|
+
-- STATEMENT: drop_staged_events
|
|
87
|
+
DROP TABLE staged_events;
|
|
88
|
+
|
|
89
|
+
-- STATEMENT: drop_staged_query_ids
|
|
90
|
+
DROP TABLE staged_query_ids;
|
|
91
|
+
|
|
92
|
+
-- STATEMENT: drop_agg_actions
|
|
93
|
+
DROP TABLE agg_actions;
|
|
94
|
+
|
|
95
|
+
-- STATEMENT: agg_qids
|
|
96
|
+
CREATE TABLE agg_qids AS
|
|
97
|
+
SELECT
|
|
98
|
+
<% qid_key_columns.each do |column| -%>
|
|
99
|
+
<%= column %>,
|
|
100
|
+
<% end -%>
|
|
101
|
+
row_number() OVER (ORDER BY first_source_position) AS qid
|
|
102
|
+
FROM (
|
|
103
|
+
SELECT
|
|
104
|
+
<% qid_key_columns.each do |column| -%>
|
|
105
|
+
<%= column %>,
|
|
106
|
+
<% end -%>
|
|
107
|
+
min(CASE WHEN impression_count > 0 THEN source_position END) AS first_source_position
|
|
108
|
+
FROM agg_examined
|
|
109
|
+
GROUP BY <%= qid_key_list %>
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
-- STATEMENT: index_agg_qids
|
|
113
|
+
CREATE UNIQUE INDEX idx_agg_qids ON agg_qids(<%= qid_key_list %>);
|
|
114
|
+
|
|
115
|
+
-- STATEMENT: agg_latest
|
|
116
|
+
-- Keeps one row per query and document: examined first, then newest timestamp, with a missing timestamp last.
|
|
117
|
+
CREATE TABLE agg_latest AS
|
|
118
|
+
SELECT
|
|
119
|
+
<% qid_key_columns.each do |column| -%>
|
|
120
|
+
<%= column %>,
|
|
121
|
+
<% end -%>
|
|
122
|
+
doc_id,
|
|
123
|
+
original_position,
|
|
124
|
+
scores_json
|
|
125
|
+
FROM (
|
|
126
|
+
SELECT
|
|
127
|
+
<% qid_key_columns.each do |column| -%>
|
|
128
|
+
<%= column %>,
|
|
129
|
+
<% end -%>
|
|
130
|
+
doc_id,
|
|
131
|
+
original_position,
|
|
132
|
+
scores_json,
|
|
133
|
+
row_number() OVER (
|
|
134
|
+
PARTITION BY <%= qid_key_list %>, doc_id
|
|
135
|
+
ORDER BY impression_count DESC, (timestamp IS NULL) ASC, timestamp DESC, source_position ASC
|
|
136
|
+
) AS rn
|
|
137
|
+
FROM agg_examined
|
|
138
|
+
)
|
|
139
|
+
WHERE rn = 1;
|
|
140
|
+
|
|
141
|
+
-- STATEMENT: index_agg_latest
|
|
142
|
+
CREATE UNIQUE INDEX idx_agg_latest ON agg_latest(<%= qid_key_list %>, doc_id);
|
|
143
|
+
|
|
144
|
+
-- STATEMENT: agg_summed
|
|
145
|
+
CREATE TABLE agg_summed AS
|
|
146
|
+
SELECT
|
|
147
|
+
<% qid_key_columns.each do |column| -%>
|
|
148
|
+
<%= column %>,
|
|
149
|
+
<% end -%>
|
|
150
|
+
doc_id,
|
|
151
|
+
min(source_position) AS first_source_position,
|
|
152
|
+
CAST(sum(impression_count) AS INTEGER) AS impression_count
|
|
153
|
+
<% action_columns.each do |(_action, column)| -%>
|
|
154
|
+
, CAST(sum(<%= column %>) AS INTEGER) AS <%= column %>
|
|
155
|
+
<% end -%>
|
|
156
|
+
FROM agg_examined
|
|
157
|
+
GROUP BY <%= qid_key_list %>, doc_id;
|
|
158
|
+
|
|
159
|
+
<% if negative_downsample_ratio -%>
|
|
160
|
+
-- STATEMENT: downsample_negatives
|
|
161
|
+
-- rn is 1-based, so rn - 1 is the count of negatives already kept.
|
|
162
|
+
DELETE FROM agg_summed
|
|
163
|
+
WHERE rowid IN (
|
|
164
|
+
SELECT ranked.rowid
|
|
165
|
+
FROM (
|
|
166
|
+
SELECT
|
|
167
|
+
rowid,
|
|
168
|
+
doc_id,
|
|
169
|
+
<% qid_key_columns.each do |column| -%>
|
|
170
|
+
<%= column %>,
|
|
171
|
+
<% end -%>
|
|
172
|
+
row_number() OVER (PARTITION BY <%= qid_key_list %> ORDER BY ltr_negative_rank(<%= qid_key_list %>, doc_id), doc_id) AS rn
|
|
173
|
+
FROM agg_summed
|
|
174
|
+
WHERE impression_count = 0
|
|
175
|
+
) ranked
|
|
176
|
+
LEFT JOIN (
|
|
177
|
+
SELECT <%= qid_key_list %>, count(*) AS positives
|
|
178
|
+
FROM agg_summed
|
|
179
|
+
WHERE impression_count > 0
|
|
180
|
+
GROUP BY <%= qid_key_list %>
|
|
181
|
+
) p ON <%= join_condition.call("p", "ranked", false) %>
|
|
182
|
+
WHERE ranked.rn - 1 >= coalesce(p.positives, 0) * <%= negative_downsample_ratio %>
|
|
183
|
+
);
|
|
184
|
+
|
|
185
|
+
<% end -%>
|
|
186
|
+
-- STATEMENT: drop_agg_examined
|
|
187
|
+
DROP TABLE agg_examined;
|
|
188
|
+
|
|
189
|
+
-- STATEMENT: analyze_aggregate
|
|
190
|
+
ANALYZE;
|
|
191
|
+
|
|
192
|
+
-- STATEMENT: aggregate_select
|
|
193
|
+
SELECT
|
|
194
|
+
qids.qid AS qid,
|
|
195
|
+
s.user_query AS user_query,
|
|
196
|
+
<% qid_field_columns.each do |column| -%>
|
|
197
|
+
s.<%= column %> AS <%= column %>,
|
|
198
|
+
<% end -%>
|
|
199
|
+
s.doc_id AS doc_id,
|
|
200
|
+
l.original_position AS original_position,
|
|
201
|
+
l.scores_json AS scores_json,
|
|
202
|
+
s.impression_count AS impression_count
|
|
203
|
+
<% action_columns.each do |(_action, column)| -%>
|
|
204
|
+
, s.<%= column %> AS <%= column %>
|
|
205
|
+
<% end -%>
|
|
206
|
+
FROM agg_summed s
|
|
207
|
+
JOIN agg_latest l ON <%= join_condition.call("l", "s", true) %>
|
|
208
|
+
JOIN agg_qids qids ON <%= join_condition.call("qids", "s", false) %>
|
|
209
|
+
ORDER BY s.first_source_position;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Runs the SQL statements that aggregate the staged queries and events in SQLite.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::SqliteAggregator
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
SQL_TEMPLATE_PATH = File.expand_path("sql/aggregate.sqlite.sql.erb", __dir__)
|
|
9
|
+
AGGREGATE_SELECT = "aggregate_select"
|
|
10
|
+
# Splits the rendered template into named statements at each "-- STATEMENT: <name>" line.
|
|
11
|
+
STATEMENT_PATTERN = /^-- STATEMENT: (\S+)[^\n]*\n(.*?)(?=^-- STATEMENT: |\z)/m
|
|
12
|
+
|
|
13
|
+
def initialize(config, staging, context)
|
|
14
|
+
@config = config
|
|
15
|
+
@staging = staging
|
|
16
|
+
@context = context
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Runs the statements of the SQL template in order, except `aggregate_select`.
|
|
20
|
+
# Raises `ArgumentError` if no events or no queries are staged.
|
|
21
|
+
# Raises `Ltr::SqliteError` if a statement fails.
|
|
22
|
+
# Returns the `aggregate_select` statement as a string.
|
|
23
|
+
def call
|
|
24
|
+
assert_staged_data!
|
|
25
|
+
warn_absent_cascade_actions!
|
|
26
|
+
log_staged_counts
|
|
27
|
+
report_orphan_events
|
|
28
|
+
|
|
29
|
+
statements = render_statements
|
|
30
|
+
read_sql = statements.delete(AGGREGATE_SELECT)
|
|
31
|
+
|
|
32
|
+
define_negative_rank! if context.negative_downsample_ratio
|
|
33
|
+
statements.each { |name, sql| execute!(name, sql) }
|
|
34
|
+
warn_shadowed_scores!
|
|
35
|
+
|
|
36
|
+
rows = db.get_first_value("SELECT count(*) FROM agg_summed")
|
|
37
|
+
logger.info("Sqlite aggregation produced #{rows} aggregated rows (#{staging.staged_bytes} bytes staged)")
|
|
38
|
+
|
|
39
|
+
read_sql
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
attr_reader :config, :staging, :context
|
|
45
|
+
|
|
46
|
+
def db
|
|
47
|
+
staging.db
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def assert_staged_data!
|
|
51
|
+
if count_of("staged_events").zero?
|
|
52
|
+
raise ArgumentError, "UBI events cannot be empty (no cascade-action events staged)"
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
if count_of("staged_queries").zero?
|
|
56
|
+
raise ArgumentError, "UBI queries cannot be empty (no query documents staged)"
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def warn_absent_cascade_actions!
|
|
61
|
+
present_actions = staged_action_counts.select { |_action, count| count > 0 }.keys
|
|
62
|
+
Ltr::DatasetAggregation::CascadeActions.absent_column_warnings(context.conversion_rate_targets, present_actions)
|
|
63
|
+
.each { |message| logger.warn(message) }
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def warn_shadowed_scores!
|
|
67
|
+
names = db.execute("SELECT name FROM agg_shadowed_scores").map { |row| row["name"] }
|
|
68
|
+
logger.warn(Ltr::DatasetAggregation::CascadeActions.shadowed_scores_warning(names)) if names.any?
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def staged_action_counts
|
|
72
|
+
db.execute("SELECT action_name, count(*) AS count FROM staged_events GROUP BY action_name")
|
|
73
|
+
.to_h { |row| [row["action_name"], row["count"]] }
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def log_staged_counts
|
|
77
|
+
logger.info("Aggregating #{count_of("staged_queries")} query-document rows and " \
|
|
78
|
+
"#{count_of("staged_events")} event rows from #{count_of("staged_query_ids")} query records")
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def report_orphan_events
|
|
82
|
+
orphans = db.get_first_value(
|
|
83
|
+
"SELECT count(*) FROM staged_events e WHERE NOT EXISTS (SELECT 1 FROM staged_query_ids q WHERE q.query_id = e.query_id AND q.has_hit_ids = 1)"
|
|
84
|
+
).to_i
|
|
85
|
+
Ltr::DatasetAggregation::DroppedEvents.report_orphan_events(logger, orphans)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def count_of(table)
|
|
89
|
+
db.get_first_value("SELECT count(*) FROM #{table}").to_i
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def render_statements
|
|
93
|
+
rendered = ERB.new(File.read(SQL_TEMPLATE_PATH), trim_mode: "-").result(template_binding)
|
|
94
|
+
rendered.scan(STATEMENT_PATTERN).to_h { |name, sql| [name, sql.strip] }
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# The locals below are the names that aggregate.sqlite.sql.erb reads.
|
|
98
|
+
def template_binding
|
|
99
|
+
action_columns = self.action_columns
|
|
100
|
+
action_literals = self.action_literals
|
|
101
|
+
qid_field_columns = self.qid_field_columns
|
|
102
|
+
qid_key_columns = self.qid_key_columns
|
|
103
|
+
qid_key_list = qid_key_columns.join(", ")
|
|
104
|
+
join_condition = method(:join_condition).to_proc
|
|
105
|
+
quote = Ltr::DatasetAggregation::ColumnName.method(:quote_literal)
|
|
106
|
+
reserved_feature_literals = context.reserved_feature_names.map { |name| Ltr::DatasetAggregation::ColumnName.quote_literal(name.to_s) }.join(", ")
|
|
107
|
+
cascade_cutoff = context.cascade_cutoff
|
|
108
|
+
negative_downsample_ratio = context.negative_downsample_ratio&.then { |ratio| Float(ratio) }
|
|
109
|
+
|
|
110
|
+
binding
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def join_condition(left, right, with_doc_id)
|
|
114
|
+
columns = qid_key_columns
|
|
115
|
+
columns += ["doc_id"] if with_doc_id
|
|
116
|
+
columns.map { |column| "#{left}.#{column} IS #{right}.#{column}" }.join(" AND ")
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
def qid_key_columns
|
|
120
|
+
[quote_column("user_query")] + qid_field_columns
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def qid_field_columns
|
|
124
|
+
staging.qid_field_names.map { |field| quote_column(field) }
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
def action_columns
|
|
128
|
+
@action_columns ||= context.cascade_actions.map { |action| [action.to_s, quote_column("#{action}_count")] }
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# Every config-derived column in the SQL template is double-quoted, so a SQL keyword such as `order` is a usable name.
|
|
132
|
+
def quote_column(name)
|
|
133
|
+
Ltr::DatasetAggregation::ColumnName.quote_column(name)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def action_literals
|
|
137
|
+
action_columns.map { |action, _column| Ltr::DatasetAggregation::ColumnName.quote_literal(action) }
|
|
138
|
+
.join(", ")
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def define_negative_rank!
|
|
142
|
+
seed = Integer(context.random_seed)
|
|
143
|
+
db.define_function("ltr_negative_rank") do |*args|
|
|
144
|
+
*key_parts, doc_id = args
|
|
145
|
+
rank = Ltr::DatasetAggregation::NegativeRank.for(seed, key_parts, doc_id)
|
|
146
|
+
# SQLite turns a large Integer into a float. Fixed-width hex of the shifted rank sorts as text in the same order.
|
|
147
|
+
format("%016x", rank + 2**63)
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def execute!(name, sql)
|
|
152
|
+
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
153
|
+
db.execute_batch(sql)
|
|
154
|
+
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
|
|
155
|
+
logger.info("Sqlite aggregation stage #{name}: #{elapsed.round(2)}s")
|
|
156
|
+
rescue SQLite3::Exception => error
|
|
157
|
+
raise Ltr::SqliteError.new(
|
|
158
|
+
"Sqlite aggregation failed at stage #{name}: #{error.message} (sqlite code #{error.code})",
|
|
159
|
+
statement: sql,
|
|
160
|
+
error_code: error.code
|
|
161
|
+
)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def logger
|
|
165
|
+
Ltr.config.logger
|
|
166
|
+
end
|
|
167
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Fetches UBI events in batches and stages them in the SQLite database.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::SqliteEventStager
|
|
6
|
+
def initialize(staging:, context:, batch_size:, n_events:, logger:, fetch:)
|
|
7
|
+
@staging = staging
|
|
8
|
+
@context = context
|
|
9
|
+
@batch_size = batch_size
|
|
10
|
+
@n_events = n_events
|
|
11
|
+
@logger = logger
|
|
12
|
+
@fetch = fetch
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Fetches events in batches until it has fetched `n_events` of them or there are no more.
|
|
16
|
+
# Stages the events that have a query ID and a document ID.
|
|
17
|
+
# Returns `[staged_row_count, query_ids]`, where `query_ids` is a set of the query IDs of the staged events.
|
|
18
|
+
def stage_events
|
|
19
|
+
query_ids = Set.new
|
|
20
|
+
total_rows = 0
|
|
21
|
+
total_hits = 0
|
|
22
|
+
without_doc_id = 0
|
|
23
|
+
search_after = nil
|
|
24
|
+
remaining = n_events
|
|
25
|
+
batch_number = 0
|
|
26
|
+
insert = db.prepare("INSERT INTO staged_events (query_id, doc_id, action_name) VALUES (?, ?, ?)")
|
|
27
|
+
|
|
28
|
+
while remaining > 0
|
|
29
|
+
batch_number += 1
|
|
30
|
+
current_batch_size = [remaining, batch_size].min
|
|
31
|
+
logger.info("Events batch #{batch_number}: requesting #{current_batch_size}, #{remaining} remaining")
|
|
32
|
+
|
|
33
|
+
hits, search_after = fetch.call(current_batch_size, search_after)
|
|
34
|
+
break if hits.empty?
|
|
35
|
+
|
|
36
|
+
staged_rows, batch_without_doc_id = stage_batch(hits, query_ids, insert)
|
|
37
|
+
total_rows += staged_rows
|
|
38
|
+
total_hits += hits.length
|
|
39
|
+
without_doc_id += batch_without_doc_id
|
|
40
|
+
logger.info("Events batch #{batch_number}: #{hits.length} hits -> #{staged_rows} staged rows")
|
|
41
|
+
|
|
42
|
+
remaining -= hits.length
|
|
43
|
+
break unless search_after
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
Ltr::DatasetAggregation::DroppedEvents.report_missing_doc_id(total_hits, without_doc_id, context.doc_id_field)
|
|
47
|
+
[total_rows, query_ids]
|
|
48
|
+
ensure
|
|
49
|
+
insert&.close
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
private
|
|
53
|
+
|
|
54
|
+
attr_reader :staging, :context, :batch_size, :n_events, :logger, :fetch
|
|
55
|
+
|
|
56
|
+
def db
|
|
57
|
+
staging.db
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def stage_batch(hits, query_ids, insert)
|
|
61
|
+
rows, without_doc_id = event_rows_for(hits, query_ids)
|
|
62
|
+
db.transaction { rows.each { |row| insert.execute(row) } }
|
|
63
|
+
[rows.length, without_doc_id]
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def event_rows_for(hits, query_ids)
|
|
67
|
+
without_doc_id = 0
|
|
68
|
+
rows = hits.filter_map do |event|
|
|
69
|
+
query_id = event[context.query_id_field]
|
|
70
|
+
doc_id = Ltr::DatasetAggregation::DroppedEvents.doc_id(event, context.doc_id_field)
|
|
71
|
+
without_doc_id += 1 if doc_id.nil?
|
|
72
|
+
next if query_id.blank? || doc_id.nil?
|
|
73
|
+
|
|
74
|
+
query_ids << query_id
|
|
75
|
+
[query_id.to_s, doc_id.to_s, event["action_name"].to_s]
|
|
76
|
+
end
|
|
77
|
+
[rows, without_doc_id]
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Fetches UBI queries in batches and stages them in the SQLite database.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::SqliteQueryStager
|
|
6
|
+
def initialize(staging:, context:, batch_size:, logger:, fetch:)
|
|
7
|
+
@staging = staging
|
|
8
|
+
@context = context
|
|
9
|
+
@batch_size = batch_size
|
|
10
|
+
@logger = logger
|
|
11
|
+
@fetch = fetch
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Fetches the queries for the given query IDs in slices and stages one row per document that has scores and a hit ID.
|
|
15
|
+
# Skips queries with a blank `user_query`, a blank query ID, no `scores` hash or no hit IDs.
|
|
16
|
+
# Logs one warning with the count and the first query IDs of the queries with no hit IDs.
|
|
17
|
+
# Only the first record of a query ID is staged. Later ones count as duplicates, even when the first has no hit IDs and is skipped.
|
|
18
|
+
# Raises `ArgumentError` if nothing is staged and some queries were skipped for having no hit IDs, which means `hit_ids_field` is wrong.
|
|
19
|
+
# Raises `Ltr::InvalidDatasetError` for a query with a `query_id` and a `user_query` where `query_attributes` or its `scores` is present and not a hash.
|
|
20
|
+
# Logs the counts of the staged records and document rows when done.
|
|
21
|
+
def stage_queries(query_ids)
|
|
22
|
+
@counts = Hash.new(0)
|
|
23
|
+
@missing_hit_ids_sample = []
|
|
24
|
+
stage_slices(query_ids) unless query_ids.empty?
|
|
25
|
+
|
|
26
|
+
warn_duplicates(@counts[:duplicates])
|
|
27
|
+
report_missing_hit_ids
|
|
28
|
+
logger.info("Staged #{@counts[:rows]} query-document rows from #{@counts[:records]} query records")
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
private
|
|
32
|
+
|
|
33
|
+
attr_reader :staging, :context, :batch_size, :logger, :fetch
|
|
34
|
+
|
|
35
|
+
def db
|
|
36
|
+
staging.db
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def insert_queries_sql
|
|
40
|
+
columns = %w[query_id user_query timestamp doc_id original_position scores_json] + staging.qid_field_names
|
|
41
|
+
placeholders = Array.new(columns.length, "?").join(", ")
|
|
42
|
+
quoted = columns.map { |column| Ltr::DatasetAggregation::ColumnName.quote_column(column) }
|
|
43
|
+
"INSERT INTO staged_queries (#{quoted.join(", ")}) VALUES (#{placeholders})"
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def stage_slices(query_ids)
|
|
47
|
+
claim = db.prepare("INSERT OR IGNORE INTO staged_query_ids (query_id, has_hit_ids) VALUES (?, ?)")
|
|
48
|
+
insert = db.prepare(insert_queries_sql)
|
|
49
|
+
|
|
50
|
+
query_ids.each_slice(batch_size).with_index(1) do |slice_query_ids, slice_number|
|
|
51
|
+
logger.info("Queries slice #{slice_number}: requesting #{slice_query_ids.length} query IDs")
|
|
52
|
+
stage_slice(slice_query_ids, claim, insert)
|
|
53
|
+
logger.info("Queries slice #{slice_number}: #{@counts[:records]} records staged so far")
|
|
54
|
+
end
|
|
55
|
+
ensure
|
|
56
|
+
claim&.close
|
|
57
|
+
insert&.close
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def stage_slice(slice_query_ids, claim, insert)
|
|
61
|
+
search_after = nil
|
|
62
|
+
|
|
63
|
+
loop do
|
|
64
|
+
hits, search_after = fetch.call(slice_query_ids, search_after)
|
|
65
|
+
break if hits.empty?
|
|
66
|
+
|
|
67
|
+
db.transaction { hits.each { |query| stage_query_record(query, claim, insert) } }
|
|
68
|
+
break unless search_after
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def stage_query_record(query, claim, insert)
|
|
73
|
+
user_query = normalize_user_query(query["user_query"])
|
|
74
|
+
return unless user_query
|
|
75
|
+
|
|
76
|
+
query_id = query[context.query_id_field]
|
|
77
|
+
return if query_id.blank?
|
|
78
|
+
|
|
79
|
+
scores_by_doc = Ltr::DatasetAggregation::UbiQueryFields.scores_by_doc(query, query_id_field: context.query_id_field)
|
|
80
|
+
return if scores_by_doc.nil?
|
|
81
|
+
|
|
82
|
+
has_hit_ids = Ltr::DatasetAggregation::UbiQueryFields.hit_ids?(query, hit_ids_field: context.hit_ids_field)
|
|
83
|
+
unless claim_query_id(query_id.to_s, has_hit_ids, claim)
|
|
84
|
+
@counts[:duplicates] += 1
|
|
85
|
+
return
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
unless has_hit_ids
|
|
89
|
+
@counts[:missing_hit_ids] += 1
|
|
90
|
+
@missing_hit_ids_sample << query_id if @missing_hit_ids_sample.length < Ltr::DatasetAggregation::MissingHitIds::SAMPLE_SIZE
|
|
91
|
+
return
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
@counts[:records] += 1
|
|
95
|
+
@counts[:rows] += insert_doc_rows(query, query_id.to_s, user_query, scores_by_doc, insert)
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
def normalize_user_query(user_query)
|
|
99
|
+
return nil if user_query.nil?
|
|
100
|
+
|
|
101
|
+
normalized = user_query.strip.downcase
|
|
102
|
+
normalized.empty? ? nil : normalized
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
# The first record seen for a query_id wins. Later ones are duplicates.
|
|
106
|
+
def claim_query_id(query_id, has_hit_ids, claim)
|
|
107
|
+
claim.execute(query_id, has_hit_ids ? 1 : 0)
|
|
108
|
+
!db.changes.zero?
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def insert_doc_rows(query, query_id, user_query, scores_by_doc, insert)
|
|
112
|
+
timestamp = query["timestamp"]&.to_s
|
|
113
|
+
qid_field_values = context.additional_qid_fields.map do |field|
|
|
114
|
+
Ltr::DatasetAggregation::UbiQueryFields.qid_field_value(query, field, query_id_field: context.query_id_field)
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
display_positions = Ltr::DatasetAggregation::DisplayPositions.for(
|
|
118
|
+
query, hit_ids_field: context.hit_ids_field, query_id_field: context.query_id_field
|
|
119
|
+
)
|
|
120
|
+
display_positions.each do |doc_id, position|
|
|
121
|
+
insert.execute([
|
|
122
|
+
query_id,
|
|
123
|
+
user_query,
|
|
124
|
+
timestamp,
|
|
125
|
+
doc_id.to_s,
|
|
126
|
+
position,
|
|
127
|
+
JSON.generate(scores_by_doc[doc_id]),
|
|
128
|
+
*qid_field_values,
|
|
129
|
+
])
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
display_positions.size
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def report_missing_hit_ids
|
|
136
|
+
Ltr::DatasetAggregation::MissingHitIds.report(
|
|
137
|
+
logger, @counts[:missing_hit_ids], @missing_hit_ids_sample,
|
|
138
|
+
kept: @counts[:records].positive?, hit_ids_field: context.hit_ids_field
|
|
139
|
+
)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def warn_duplicates(duplicates)
|
|
143
|
+
return if duplicates.zero?
|
|
144
|
+
|
|
145
|
+
logger.warn("Skipped #{duplicates} ubi_queries record(s) repeating an already-staged query_id; " \
|
|
146
|
+
"kept the most recent record for each")
|
|
147
|
+
end
|
|
148
|
+
end
|