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
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: b03210e9f90c97427a7b30e370d5dd0ebe6408a390f1734af190e7c4f0391c3a
|
|
4
|
+
data.tar.gz: 4df90065d8fbf073e8a20cd0036e665da22a9e74705674e054ae974dee14526d
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 2ca9dee7f14d06e66d311fe75e149bcb8aba2ab8eb7275300c21d9003169928eb75c4a833d7e6277b4fad9a9b1266aff120cb3bcec21ee46731de1d5e115f3f0
|
|
7
|
+
data.tar.gz: ff322129af79719f2e26c7ab329a92ecf3eed636a06b5cbb6fd6b59dc466f88acdee8e3bc7aef502775cc0ea7144e01154931f03d79bce1c145c468f4c291d5f
|
data/ARCHITECTURE.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
How the `ltr` gem is put together internally. For usage and configuration reference, see `README.md` and `docs/index.md`; for contributor conventions and commands, see `AGENTS.md`.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
`ltr` is a library, not an application — it exposes three independent pipelines plus an inference entry point, all sharing one configuration object. There is no long-running process or scheduler in the gem; a host app drives the pipelines, typically from cron through the `ltr:aggregate` / `ltr:optimize` / `ltr:train` rake tasks the gem ships (`lib/ltr/tasks/ltr.rake`, which the host loads with `load "ltr/tasks/ltr.rake"`).
|
|
8
|
+
|
|
9
|
+
```mermaid
|
|
10
|
+
flowchart LR
|
|
11
|
+
subgraph aggregation [Dataset aggregation]
|
|
12
|
+
UbiDataLoader -->|queries and events| DatasetBuilder
|
|
13
|
+
DatasetBuilder -->|labelled dataset| DatasetEnricher
|
|
14
|
+
DatasetEnricher -->|text columns| EnrichedColumnEncoder
|
|
15
|
+
EnrichedColumnEncoder --> DatasetSaver
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
subgraph optimize [Optimization]
|
|
19
|
+
OptimizeFeatures --> OptimizeHyperparameters
|
|
20
|
+
OptimizeHyperparameters --> SsmSaver[Ssm::Saver / UpdateConfig]
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
subgraph train [Training]
|
|
24
|
+
XgbTrainer --> XgbEvaluator
|
|
25
|
+
XgbEvaluator --> SagemakerDeployer
|
|
26
|
+
SagemakerDeployer --> FeatureStoreDeployer
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
subgraph inference [Inference]
|
|
30
|
+
InferenceBase[Inference::Base] --> LocalReranker
|
|
31
|
+
InferenceBase --> SagemakerClient
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
DatasetSaver -->|"CSV (local or S3)"| OptimizeFeatures
|
|
35
|
+
DatasetSaver -->|"CSV (local or S3)"| XgbTrainer
|
|
36
|
+
SsmSaver -->|SSM parameters| XgbTrainer
|
|
37
|
+
SagemakerDeployer -->|endpoint| SagemakerClient
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The pipelines are decoupled: each reads its inputs from disk/S3/SSM rather than from the previous pipeline's return value, so they can be run, re-run, and scheduled independently.
|
|
41
|
+
|
|
42
|
+
## Building blocks
|
|
43
|
+
|
|
44
|
+
**`Ltr::Callable`** (`lib/ltr/support/callable.rb`) — the pervasive pattern. A class `extend`s it to get a class-level `.call(*args, **kwargs, &block)` that instantiates and calls the instance. Almost every unit of work (pipelines, builder steps, deployers, transformers) is a `Callable` service with an `initialize` + `call`. New units of work should follow this shape.
|
|
45
|
+
|
|
46
|
+
**`Ltr::PipelineResult`** (`lib/ltr/support/pipeline_result.rb`) — the immutable value object each pipeline returns. Read an output with `result[:key]`. `result.to_h` returns a mutable copy of the output hash. A failed pipeline raises.
|
|
47
|
+
|
|
48
|
+
**`Ltr::Configuration`** (`lib/ltr/configuration/configuration.rb`) — the global host-integration shim held at `Ltr.config`. Separate from pipeline config. It provides `logger`, `s3_client`, `root`, `error_reporter`, and `opensearch_connect_options`, each defaulting to standalone values (`Rails.logger` when Rails is loaded for `logger`). A host sets `s3_client_builder` and `opensearch_connect_options_builder` explicitly. `Ltr.configure { |c| ... }` overrides them; `Ltr.reset_config!` resets (used per-example in specs). It holds no pipeline loader. `Ltr::Ubi.query` and `Ltr::Ubi.event` take the model's `Ltr::ConfigLoader` as `config:` on each call.
|
|
49
|
+
|
|
50
|
+
**`Ltr::ConfigLoader`** (`lib/ltr/configuration/config_loader.rb`) — the pipeline config. Loads a base YAML (example `lib/ltr/configuration/example_config.yml`), deep-merges an optional override file on top, ERB-evaluates both (so values read ENV), validates via `ConfigValidator`, and exposes typed section accessors (`model_name`, `deploy`, `ssm`, `search_time_features`, ...). It is mutable — `OptimizePipeline` writes optimized features/hyperparameters back and `save!` persists to the override (or base) file.
|
|
51
|
+
|
|
52
|
+
**Zeitwerk autoloading** (`lib/ltr.rb`) — no manual requires within `lib/ltr/`. Several directories are `collapse`d so their files sit directly under a parent namespace (e.g. `dataset_aggregation/labels/*` → `Ltr::DatasetAggregation::*`). `deploy/artifacts` is ignored (Python inference code shipped to SageMaker, not Ruby).
|
|
53
|
+
|
|
54
|
+
## The three pipelines
|
|
55
|
+
|
|
56
|
+
### DatasetAggregation::DatasetPipeline
|
|
57
|
+
Load → build → enrich → save.
|
|
58
|
+
1. `UbiDataLoader` pulls UBI `queries`/`events` from OpenSearch in batches.
|
|
59
|
+
2. `DatasetBuilder` turns them into a labelled dataset (see below).
|
|
60
|
+
3. An optional host-supplied `DatasetEnricher` subclass (resolved by class name from config) joins in product features. `EnrichedColumnEncoder` then one-hot encodes the text columns it added into `<column>_<value>` flags. The flag names are saved with the one-hot column names in the `.serving.json` file.
|
|
61
|
+
4. `DatasetSaver` writes a gzipped CSV locally or to S3.
|
|
62
|
+
|
|
63
|
+
Steps 1–2 are the `ruby` aggregation engine, the default. `dataset_builder.aggregation_engine: sqlite` swaps them for the out-of-core engine below; steps 3–4 are unchanged either way.
|
|
64
|
+
|
|
65
|
+
### Optimize::OptimizePipeline
|
|
66
|
+
Load dataset → `OptimizeFeatures` (feature selection, greedy backward by default) → `OptimizeHyperparameters` (Bayesian optimization, implemented in-repo via `GaussianProcess` + `CholeskyDecomposition` + `SearchSpace`) → write results back into the config (`UpdateConfig`) and, when `ssm.enabled`, to SSM (`Ssm::Saver`). Pre-loads existing hyperparameters from SSM when enabled. [Optimization](docs/optimization.md) explains the trial loop.
|
|
67
|
+
|
|
68
|
+
### Train::ModellingPipeline
|
|
69
|
+
Load dataset → `XgbTrainer` (XGBoost ranker) → `XgbEvaluator` (configured metrics) → conditional deploy. Deployment is gated twice: `SagemakerDeployer` runs only when `deploy.enabled` and the chosen metric meets `deploy.minimum_metric_value`; `LocalDeployer` runs when `deploy.local` and the same metric meets the same minimum, whatever `deploy.enabled` is. `Train::DeployMetric` reads the metric name, the threshold and the score for both. `Train::DeployGate` (`call` and its private `validate_inputs!`) holds the SageMaker gate, and `ModellingPipeline` holds the local one.
|
|
70
|
+
|
|
71
|
+
## DatasetBuilder step chain
|
|
72
|
+
|
|
73
|
+
`DatasetBuilder` threads a shared `Context` through an ordered chain of step objects. The chain, the cascade examination model and the label target are in [Dataset builder steps](docs/dataset-builder-steps.md) and [Labels from behavior](docs/labels-from-behavior.md).
|
|
74
|
+
|
|
75
|
+
## The `sqlite` aggregation engine
|
|
76
|
+
|
|
77
|
+
The `sqlite` engine is an opt-in, out-of-core replacement for `UbiDataLoader` and the first three builder steps, for pulls that no longer fit in RAM. `DatasetPipeline#build_with_sqlite_engine` threads one `SqliteStaging` through `SqliteUbiDataLoader` → `SqliteAggregator` → `AggregatedSqliteLoader` → `DatasetFinalizer`. A failure discards the database and re-raises. How to choose an engine and what both engines give are in [Aggregation engines](docs/aggregation-engines.md#what-both-engines-give).
|
|
78
|
+
|
|
79
|
+
## Inference
|
|
80
|
+
|
|
81
|
+
`Inference::Base` (`lib/ltr/inference/base.rb`) is the dispatcher: it picks the `local` backend when `deploy.local` is set, otherwise `sagemaker`, and delegates to `LocalReranker` or `SagemakerClient`. Callers can force a backend or pass a custom model path/endpoint. `SagemakerClient.call` is a stable public API consumed by host apps.
|
|
82
|
+
|
|
83
|
+
## Data representation
|
|
84
|
+
|
|
85
|
+
Tabular data flows as `Rover::DataFrame` (a Ruby dataframe) plus `Ltr::Data` helpers (`Csv`, `DatasetLoader`, `RowStore`). `DatasetLoader.load` reads the modelling CSV from a local path or `s3://` URI. Numerics lean on `numo-narray`/`matrix`.
|
|
86
|
+
|
|
87
|
+
## External systems
|
|
88
|
+
|
|
89
|
+
- **OpenSearch** — source of UBI training data (read).
|
|
90
|
+
- **S3** — datasets, model tarballs, feature-store JSON (via `Ltr.config.s3_client`).
|
|
91
|
+
- **SSM Parameter Store** — persisted optimized features/hyperparameters.
|
|
92
|
+
- **SageMaker** — model/endpoint deployment (`deploy/`) and runtime invocation (`inference/`). The Python scoring code lives in `lib/ltr/deploy/artifacts/code/`.
|
data/CHANGELOG.md
ADDED
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fullscript
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# LTR
|
|
2
|
+
|
|
3
|
+
[](https://rubygems.org/gems/ltr)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](ltr.gemspec)
|
|
6
|
+
|
|
7
|
+
Learning-to-rank (LTR) pipelines for search result reranking. Use it when your search engine (e.g. an OpenSearch index) finds the right results but puts them in a suboptimal order. The gem learns a better order from your users' queries and clicks. It covers the whole model lifecycle: building a training dataset from users' search data, picking optimal features and hyperparameters, training an XGBoost ranking model, deploying it, and reranking results.
|
|
8
|
+
|
|
9
|
+
## Prerequisites
|
|
10
|
+
|
|
11
|
+
- OpenSearch with UBI data. The gem reads the `ubi_queries` and `ubi_events` indices. `ubi_data_loader.index` sets the names. See [UBI documents](docs/ubi-documents.md#required-field-types).
|
|
12
|
+
- AWS (S3, SSM and SageMaker) to run in the cloud. You can skip AWS and run everything on your machine.
|
|
13
|
+
|
|
14
|
+
Dataset aggregation reads User Behavior Insights (UBI) data from OpenSearch. Training and inference work with results from any search engine.
|
|
15
|
+
|
|
16
|
+
## Installation
|
|
17
|
+
|
|
18
|
+
Add to your Gemfile:
|
|
19
|
+
|
|
20
|
+
```ruby
|
|
21
|
+
gem "ltr"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
GCC 15 and newer need a flag to build `numo-narray` 0.9.2.1, a dependency of `ltr`.
|
|
25
|
+
For `gem install`, run `gem install numo-narray -v 0.9.2.1 -- --with-cflags="-std=gnu17"` first.
|
|
26
|
+
For Bundler, run `bundle config set --local build.numo-narray --with-cflags=-std=gnu17` in your project before `bundle install`.
|
|
27
|
+
GCC 14 and macOS need no flag.
|
|
28
|
+
|
|
29
|
+
XGBoost needs the OpenMP library at runtime. On macOS, run `brew install libomp`. On Debian and Ubuntu, install `libgomp1` if Ruby fails with a `libgomp` load error.
|
|
30
|
+
|
|
31
|
+
Some gems are optional. Add the ones your features need to your Gemfile. If one is missing or outside its version range, the call that needs it raises `Ltr::MissingDependencyError`. The message gives the Gemfile line to add.
|
|
32
|
+
|
|
33
|
+
| Gemfile line | Needed for |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `gem "opensearch-ruby", ">= 4.0.0.pre.beta.5", "< 5.a"` | Building a dataset from UBI data. The loader reads the UBI events and queries from OpenSearch. |
|
|
36
|
+
| `gem "sqlite3", "~> 2.0"` | The `sqlite` aggregation engine. A host that sets `dataset_builder.aggregation_engine` to `sqlite` must add it. |
|
|
37
|
+
| `gem "aws-sdk-s3", "~> 1"` | Reading or writing datasets on S3, uploading SageMaker model archives, and the default S3 client |
|
|
38
|
+
| `gem "aws-sdk-ssm", "~> 1"` | SSM parameters (`ssm.enabled`) |
|
|
39
|
+
| `gem "aws-sdk-sagemaker", "~> 1"` | Deploying a model to a SageMaker endpoint |
|
|
40
|
+
| `gem "aws-sdk-sagemakerruntime", "~> 1"` | Reranking through a SageMaker endpoint |
|
|
41
|
+
|
|
42
|
+
## Supported versions
|
|
43
|
+
|
|
44
|
+
| Dependency | Version |
|
|
45
|
+
|---|---|
|
|
46
|
+
| Ruby | `>= 3.3` |
|
|
47
|
+
| ActiveSupport | `>= 7.0, < 9` |
|
|
48
|
+
| `xgb` | `>= 0.11, < 0.12.2` |
|
|
49
|
+
| OpenSearch | Tested with `2.19`. Other versions are untested. See [Run the pipelines locally](docs/run-locally.md). |
|
|
50
|
+
|
|
51
|
+
## Run it
|
|
52
|
+
|
|
53
|
+
Start with the path that needs no AWS account.
|
|
54
|
+
|
|
55
|
+
- [Run the pipelines locally](docs/run-locally.md): train and use a model on a laptop with Docker.
|
|
56
|
+
- [Run the pipelines on AWS](docs/run-on-aws.md): use S3, SSM and a SageMaker endpoint.
|
|
57
|
+
|
|
58
|
+
## How it works
|
|
59
|
+
|
|
60
|
+
Four steps run in order. Each one reads what the step before it wrote.
|
|
61
|
+
|
|
62
|
+
```text
|
|
63
|
+
UBI queries and events (OpenSearch)
|
|
64
|
+
-> aggregate : writes a labelled dataset (CSV, local or S3) and its .serving.json file
|
|
65
|
+
-> optimize : reads the dataset, writes the optimized features and hyperparameters to the config file, and to SSM when `ssm.enabled`
|
|
66
|
+
-> train : reads the dataset and the config, writes a model (local file or SageMaker endpoint)
|
|
67
|
+
-> infer : reads the model and a payload, returns the items with a score
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Run `ltr:optimize` before `ltr:train`. `ltr:train` does not run it. If you train first, it trains on the features and hyperparameters that the config lists now, which are the starting values and not the chosen ones. See [Rake tasks](docs/rake-tasks.md#run-the-tasks-in-order) for the SSM case and the earlier `optimized_features` case.
|
|
71
|
+
|
|
72
|
+
Both local and SageMaker deploys need the [`.serving.json` file](docs/model-files.md#dataset-serving-file) next to the dataset.
|
|
73
|
+
|
|
74
|
+
The first three steps are entry points that share one `Ltr::ConfigLoader` configuration:
|
|
75
|
+
|
|
76
|
+
| Pipeline | Entry point | What it does |
|
|
77
|
+
|---|---|---|
|
|
78
|
+
| Dataset aggregation | `Ltr::DatasetAggregation::DatasetPipeline.call(config)` | Loads UBI queries/events from OpenSearch, builds a labelled dataset, optionally enriches it with host-app features, saves the gzipped CSV and its `.serving.json` file locally or to S3 |
|
|
79
|
+
| Optimization | `Ltr::Optimize::OptimizePipeline.call(config)` | Feature selection (greedy backward by default) plus Bayesian hyperparameter tuning; writes the optimized features and hyperparameters to the config file, and to SSM when `ssm.enabled`. See [Optimization](docs/optimization.md) |
|
|
80
|
+
| Training | `Ltr::Train::ModellingPipeline.call(config)` | Trains the XGBoost ranker, evaluates it, saves it to a local file when `deploy.local` is true, and deploys to SageMaker when enabled. Each deploy needs the metric threshold to be met |
|
|
81
|
+
|
|
82
|
+
## Quick start
|
|
83
|
+
|
|
84
|
+
Copy the gem's `example_config.yml` to `config/ltr/base.yml`:
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
mkdir -p config/ltr
|
|
88
|
+
cp "$(bundle exec gem contents ltr | grep example_config.yml)" config/ltr/base.yml
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Then write a small override file, `config/ltr/local.yml`:
|
|
92
|
+
|
|
93
|
+
```yaml
|
|
94
|
+
model:
|
|
95
|
+
name: my-model
|
|
96
|
+
hyperparameters:
|
|
97
|
+
objective: rank:ndcg
|
|
98
|
+
search_time_features:
|
|
99
|
+
- relevancy
|
|
100
|
+
- bm25_name
|
|
101
|
+
feature_store:
|
|
102
|
+
features:
|
|
103
|
+
- view_count
|
|
104
|
+
ubi_data_loader:
|
|
105
|
+
opensearch:
|
|
106
|
+
url: <%= ENV.fetch("OPENSEARCH_URL", "http://localhost:9200") %>
|
|
107
|
+
deploy:
|
|
108
|
+
enabled: false
|
|
109
|
+
local: true
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
The override is merged over the base file. `deploy.metric` and `deploy.minimum_metric_value` come from `base.yml`. `deploy.local: true` needs both. [Config](docs/config.md) lists every key.
|
|
113
|
+
|
|
114
|
+
The override holds `model.hyperparameters`, `search_time_features` and `feature_store.features` on purpose. `Optimize::UpdateConfig` rewrites those three sections in this file. It adds a section that is missing, and `optimized_features` too.
|
|
115
|
+
|
|
116
|
+
Set the gem up once, for example in `config/initializers/ltr.rb`:
|
|
117
|
+
|
|
118
|
+
```ruby
|
|
119
|
+
Ltr.configure do |config|
|
|
120
|
+
config.root = Rails.root.to_s
|
|
121
|
+
end
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`config.root` is the base for relative config paths. It defaults to `Dir.pwd`. A relative value is expanded to an absolute path when you set it. [Host integration](docs/host-integration.md) lists every setting.
|
|
125
|
+
|
|
126
|
+
`Ltr::Ubi.query` and `Ltr::Ubi.event` take the model's loader on each call, as `config:`.
|
|
127
|
+
|
|
128
|
+
Before `Ltr::DatasetAggregation::DatasetPipeline.call(config)`, the two UBI indices (`ubi_queries` and `ubi_events` in the example config) must exist with their mappings. [Create the UBI indices](docs/run-locally.md#create-the-ubi-indices) has the commands. [UBI documents](docs/ubi-documents.md) describes the fields.
|
|
129
|
+
|
|
130
|
+
Run the pipelines:
|
|
131
|
+
|
|
132
|
+
```ruby
|
|
133
|
+
require "ltr"
|
|
134
|
+
|
|
135
|
+
config = Ltr::ConfigLoader.new(base_config_path: "config/ltr/base.yml", override_config_path: "config/ltr/local.yml")
|
|
136
|
+
|
|
137
|
+
Ltr::DatasetAggregation::DatasetPipeline.call(config)
|
|
138
|
+
Ltr::Optimize::OptimizePipeline.call(config)
|
|
139
|
+
Ltr::Train::ModellingPipeline.call(config)
|
|
140
|
+
|
|
141
|
+
payload = [
|
|
142
|
+
{id: "doc1", fields: [{name: "bm25_name", value: 0.9}, {name: "relevancy", value: 12.1}]},
|
|
143
|
+
{id: "doc2", fields: [{name: "bm25_name", value: 0.7}, {name: "relevancy", value: 8.4}]}
|
|
144
|
+
]
|
|
145
|
+
Ltr::Inference::Base.call(payload, config)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
With `deploy.local: true`, `Inference::Base` uses the local model. The SageMaker payload and the item fields are in [Data contracts](docs/inference.md#inference-request).
|
|
149
|
+
|
|
150
|
+
The config file is evaluated as ERB, so it can run code. Only load config files you trust.
|
|
151
|
+
|
|
152
|
+
## Documentation
|
|
153
|
+
|
|
154
|
+
- [Config](docs/config.md): every key in the pipeline config.
|
|
155
|
+
- [Host integration](docs/host-integration.md): set up `Ltr.configure`, build the loader for `Ltr::Ubi`, and set the environment variables.
|
|
156
|
+
- [Run the pipelines from a host app](docs/host-run-pipelines.md): AWS resources, pipeline calls from Ruby and deployment results.
|
|
157
|
+
- [Public API](docs/public-api.md): the entry points that stay stable between releases.
|
|
158
|
+
- [Rake tasks](docs/rake-tasks.md): run the pipelines on a schedule.
|
|
159
|
+
- [Label transformers](docs/label-transformers.md): customize how the pipeline labels an `Ltr::Data::RowStore`.
|
|
160
|
+
- [Dataset enrichers](docs/dataset-enrichers.md) and [Logging UBI documents](docs/ubi-logging.md): add host features and log search activity.
|
|
161
|
+
- [Architecture](ARCHITECTURE.md): how the gem is built inside.
|
|
162
|
+
|
|
163
|
+
The full list is in [docs/index.md](docs/index.md).
|
|
164
|
+
|
|
165
|
+
## Versioning
|
|
166
|
+
|
|
167
|
+
The gem follows [semantic versioning](https://semver.org/). The [changelog](CHANGELOG.md) marks a breaking change with a `**Breaking:**` prefix. While the version is `0.x`, a minor release can break the API.
|
|
168
|
+
|
|
169
|
+
## Development
|
|
170
|
+
|
|
171
|
+
XGBoost needs OpenMP. See [Installation](#installation).
|
|
172
|
+
|
|
173
|
+
The specs stub AWS and OpenSearch. They need no Docker and no running OpenSearch.
|
|
174
|
+
|
|
175
|
+
```bash
|
|
176
|
+
bundle install
|
|
177
|
+
bundle exec rspec # run the test suite
|
|
178
|
+
bundle exec rubocop # style checks (standard rules plus .rubocop.yml)
|
|
179
|
+
bundle exec rake yard # build the API docs into doc/
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
`bundle exec rake` runs the specs and rubocop. See [CONTRIBUTING.md](CONTRIBUTING.md) to propose a change.
|
|
183
|
+
|
|
184
|
+
## License
|
|
185
|
+
|
|
186
|
+
Released under the [MIT License](LICENSE).
|
data/docs/AGENTS.md
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Writing the docs
|
|
2
|
+
|
|
3
|
+
This page lists the rules for how a page under `docs/` is laid out and worded, so that every page reads the same way. The root `AGENTS.md` and `CONTRIBUTING.md` hold the rules for code, specs and the changelog.
|
|
4
|
+
|
|
5
|
+
## Layout
|
|
6
|
+
|
|
7
|
+
- The opening paragraph says what the page covers. It flows as prose and is not a list of definitions.
|
|
8
|
+
- A page that uses 3 or more terms a new reader would not know has a `## Glossary` table right after the opening paragraph. It has the columns `Term` and `Meaning`, its rows are in alphabetical order, and it holds no links.
|
|
9
|
+
- Each glossary row copies the wording of [docs/glossary.md](glossary.md) word for word. If a term is missing there, add it to the master list first. If the MR that adds the term is still open, the page names that MR.
|
|
10
|
+
- A rule or a process with steps, cases or numbers gets its own section title and a table or a Mermaid diagram, not a paragraph of conditions. One sentence before the table says what it shows.
|
|
11
|
+
- Name a section for what it does or shows, such as "Calculating the smoothed rate of a document". Do not name it for a question or a single case it answers.
|
|
12
|
+
- Spell out every name in a table's column headers and row labels. Do not use an acronym or an internal short name there. In the text, name the case a row shows, such as "a query with one bought document". Do not write "the first case" or "the last row shows".
|
|
13
|
+
- A new or edited Mermaid flowchart starts with the frontmatter block `---`, `config:`, ` flowchart:`, ` wrappingWidth: 480`, `---`, so the node boxes are wide. Other chart types, such as `xychart-beta`, have their own settings. In a flowchart, keep node text short, and keep longer detail out of edge labels, because edge labels wrap narrowly.
|
|
14
|
+
- Pages inside and outside `docs/` may link to a heading anchor. Before you rename a heading, run `rg -n -F 'page.md#' .` from the repo root, with `page.md` replaced by the real filename, and fix every link it finds.
|
|
15
|
+
|
|
16
|
+
## Wording
|
|
17
|
+
|
|
18
|
+
- Use plain words that a 12-year-old can follow, in the active voice. Keep sentences short, but join two closely related facts into one sentence rather than chopping the prose into five-word sentences. Do not repeat a relative pronoun in a parallel clause. Write "which the gem works out from the dataset and has no config key", not "which the gem works out from the dataset and which has no config key".
|
|
19
|
+
- Define a term, an action or a step in or before the sentence that first uses it. Give the long form of an acronym where you introduce it, such as "Discounted Cumulative Gain adds up each document's gain times a discount for its rank. Ideal Discounted Cumulative Gain is that sum for the best possible order of the documents".
|
|
20
|
+
- Describe only what the code does. Do not use "now", "no longer", "instead of" or other words that point back at an older design.
|
|
21
|
+
- Do not use figurative wording for a mechanism. Say what is saved, where, and when it is read.
|
|
22
|
+
- Say each fact once on a page. Do not add a sentence that explains an obvious step. Drop a sentence that does not help the reader.
|
|
23
|
+
- Leave out detail the reader does not need, such as a column's type when only its meaning matters, or a list of helpers that no example on the page uses.
|
|
24
|
+
- When a paragraph states a bound or a result, say why it is true in a few short sentences: the premise, the step and the conclusion. For a range or a bound, also give the formula, or the table, that shows how the bound is reached, next to that reasoning.
|
|
25
|
+
- When a sentence names a set, list its members in brackets, such as "one split at a time (train, test, val)".
|
|
26
|
+
- Tell the reader what to set in the config and what each value does, such as "set `model.hyperparameters.ndcg_exp_gain: false` for linear gain". Do not explain the internal value the gem stores or reads back.
|
|
27
|
+
- Start an edge case with its result, such as "A query with no relevant document counts as 0.0". Cut the detail that the reader does not need to act on it.
|
|
28
|
+
- Use "relative to" to compare sizes, not "next to".
|
|
29
|
+
- Link a named external tool or method to its documentation. Pin the link to a version when the page depends on that version.
|
|
30
|
+
- Put every identifier in backticks, spelled as in the code. Metric names and config keys are lowercase, as written in the config.
|
|
31
|
+
- Give a config key as `section.key`, with its default and its rule in the same sentence or the same table row.
|
|
32
|
+
- Write a hyperparameter key as `model.hyperparameters.<key>`. A table of hyperparameters has a column for the shipped value.
|
|
33
|
+
- When two backends or languages differ, name which one does what, such as Ruby and Python, or the SageMaker endpoint and the local reranker.
|
|
34
|
+
|
|
35
|
+
## Formulas and numbers
|
|
36
|
+
|
|
37
|
+
- Write a formula in a `math` block, or inline as `` $`...`$ ``. Define each symbol in a list right under the block, and add one plain sentence that says what the formula means.
|
|
38
|
+
- Give each formula its own subsection. Say the full name of its metric in words before its symbol, such as "The precision at $`i`$, $`P(i)`$".
|
|
39
|
+
- Before a formula, say where each input comes from: a config key with its default and its rule, or a value the gem computes, and from which data.
|
|
40
|
+
- Bad, from `docs/config.md`, a formula written as code: "When `true` it is `2^label - 1`."
|
|
41
|
+
- Keep formulas out of Mermaid labels, because they do not render there.
|
|
42
|
+
- Give every size and default with its unit, such as 4 decimals or 10 sessions.
|
|
43
|
+
- Say "pairs" when you count pairs and "documents" when you count documents. Good, from `docs/glossary.md`: "A group holds the candidate documents for one `user_query` [...] XGBoost builds pairs only inside a group."
|
|
44
|
+
- When you split a total into groups, show every group, and make the groups add up to the total, such as in a table with a total row. Say where every number comes from, unless the reader can see it computed on the page.
|
|
45
|
+
|
|
46
|
+
## Examples
|
|
47
|
+
|
|
48
|
+
- Take every number in an example from the real code, run in a scratch script. Do not state a measured claim, such as a typical range or a rate, without a run on real or toy data that you can point to.
|
|
49
|
+
- Start an example with a sentence that says it is an example and what it holds, such as "In the example below, the search result has six documents. The session is made up." A made-up example says it is made up, such as "The table applies both methods to made-up `bm25_name` scores for the query magnesium."
|
|
50
|
+
|
|
51
|
+
## Updating a page
|
|
52
|
+
|
|
53
|
+
- Do not insert a phrase or a sentence into a paragraph. Rewrite the whole paragraph so it reads as one piece. A longer rewrite is better than a patched sentence.
|
|
54
|
+
- When a new topic needs explaining, add a table or a diagram, not more sentences in a paragraph.
|
|
55
|
+
- When a page grows too long, split it into two pages that each have one job. Search the whole repo for the old filename with `rg -n -F 'page.md' .`, then update `docs/index.md`, every link it finds and the anchors that pointed into the moved text.
|
|
56
|
+
- Describe the code on `main` after the merged MRs. If a docs MR describes behaviour from an open code MR, its description names that MR and says which one merges first.
|
|
57
|
+
- When a change makes a sentence untrue, search every page with `rg` for the phrase, the key name and the feature name, and fix every page. Change `docs/glossary.md` first, then every page that repeats the row.
|
|
58
|
+
- When a code change renames a config key, a setting or a metric name, use the new name on every page in the same MR, or name the MR that owns the rename.
|
|
59
|
+
- When you rewrite a paragraph, remove any fact that another paragraph on the page already states.
|
|
60
|
+
- Check every number, table and diagram in a rewritten paragraph against the real code, because the rewrite can make them wrong.
|
|
61
|
+
- Update the MR description and `CHANGELOG.md` when the page changes in a way a reader would notice. Describe the page as it is, not as it was.
|
|
62
|
+
- When a reviewer gives a writing note that this page does not cover, add it here as a rule in the same MR as the page change, or in a follow-up MR if that MR has merged.
|
|
63
|
+
|
|
64
|
+
## Before you push
|
|
65
|
+
|
|
66
|
+
- `bundle exec rake yard` exits 0. The YARD site shows math as code, which is expected.
|
|
67
|
+
- Every link resolves, and no heading was renamed by accident.
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Aggregation engines
|
|
2
|
+
|
|
3
|
+
This page explains when to pick the `sqlite` aggregation engine over the default `ruby` one, which config keys set it up, and what both engines give. It also covers what a failed `sqlite` run logs, and how much memory and disk each engine needs.
|
|
4
|
+
|
|
5
|
+
Aggregation joins the [UBI](https://docs.opensearch.org/latest/search-plugins/ubi/index/) (User Behavior Insights) queries and events from [OpenSearch](https://docs.opensearch.org/latest/) into one row per query group and document. A query group is the set of searches that share a `user_query` and the `dataset_builder.additional_qid_fields` values. Each group gets one `qid`. Both engines number the groups from 1 with no gaps, in the order of each group's first row. Later, `DatasetFilters` drops the groups below `min_documents_per_query` and numbers the kept groups from 1 again, with no gaps, in the same order. A cascade action is an action that `dataset_builder.conversion_rate_targets` names as a numerator or a denominator, such as `add_to_cart`. Both engines hand their rows to `DatasetFinalizer`, so labelling, feature encoding and the data split run the same code. [Labels from behavior](labels-from-behavior.md) explains the aggregation steps.
|
|
6
|
+
|
|
7
|
+
## Choose an engine
|
|
8
|
+
|
|
9
|
+
| | `ruby` (default) | `sqlite` |
|
|
10
|
+
|---|---|---|
|
|
11
|
+
| Held in memory | Every fetched event and search record | One OpenSearch page, then the aggregated rows |
|
|
12
|
+
| Disk | None | The downloaded rows and working tables, under `dataset_aggregation.staging_root` |
|
|
13
|
+
| Extra gem | None | `gem "sqlite3", "~> 2.0"` |
|
|
14
|
+
| `ubi_data_loader.batch_size` default | `100` | `10000` |
|
|
15
|
+
|
|
16
|
+
Use `ruby` while the pull fits in the pipeline host's RAM. Switch to `sqlite` when it no longer fits.
|
|
17
|
+
|
|
18
|
+
## Set the engine
|
|
19
|
+
|
|
20
|
+
Set `dataset_builder.aggregation_engine`, which defaults to `ruby`, to `sqlite`, and add `gem "sqlite3", "~> 2.0"` to the host app's Gemfile. Any other value raises `Ltr::ConfigurationError` at config load. A missing gem raises `Ltr::MissingDependencyError` when the run starts. [Config](config.md#dataset_aggregation) has the defaults for the keys below.
|
|
21
|
+
|
|
22
|
+
| Key | Effect on the `sqlite` engine |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `dataset_aggregation.staging_root` | The folder where each run makes its `ltr-aggregation-*` scratch folder for the database. Blank uses the system temp folder. Point it at a volume with room for the download. |
|
|
25
|
+
| `dataset_aggregation.sqlite.cache_size_mb`, `dataset_aggregation.sqlite.page_size` | SQLite's cache, `256` MB, and page size, `8192` bytes. The cache adds to the engine's memory. |
|
|
26
|
+
| `ubi_data_loader.batch_size` | The OpenSearch page size, the rows per insert transaction, and the query ids per queries request. |
|
|
27
|
+
|
|
28
|
+
Both engines request the same `_source` fields, and no config key changes them. Queries: the query id field, `user_query`, `query_attributes`, `timestamp`, the hit ids field and each `additional_qid_fields` name. Events: the query id field, `action_name` and `event_attributes`.
|
|
29
|
+
|
|
30
|
+
When `ubi_queries` holds two records with one `query_id`, both engines keep only the first one the search returns, which is the newest. That record wins even when it is then skipped for having no hit ids. The older record is not used, and it counts as a repeat. The `sqlite` engine logs `Skipped <n> ubi_queries record(s) repeating an already-staged query_id`. The `ruby` engine logs `Skipped <n> ubi_queries record(s) repeating an already-seen query_id`.
|
|
31
|
+
|
|
32
|
+
Both engines skip a query record whose hit ids are missing or empty. Both log one line, `Skipped <n> ubi_queries record(s) with no <hit_ids_field> (first: <query_id>, ...)`, that names the first 10 query ids. When every record lacks hit ids, both raise `ArgumentError`.
|
|
33
|
+
|
|
34
|
+
The doc id check counts only the cascade-action events each engine loaded. When none of them has `event_attributes.<doc_id_field>`, both engines raise `ArgumentError` with the field name.
|
|
35
|
+
|
|
36
|
+
## Checking the column names from config
|
|
37
|
+
|
|
38
|
+
Each `additional_qid_fields` name and each cascade action's `<action>_count` column becomes a column name. The check runs before the download. The table lists each rule and an example name that breaks it.
|
|
39
|
+
|
|
40
|
+
| Rule | Names it applies to | Example that raises |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| Matches `[a-z_][a-z0-9_]*` | Each `additional_qid_fields` name and each `<action>_count` column | `Market`, `add-to-cart_count` |
|
|
43
|
+
| Is not a reserved name (the error lists them) | Each `additional_qid_fields` name and each `<action>_count` column | `qid`, `doc_id`, `rn`, `events` |
|
|
44
|
+
| Is a string | Each `additional_qid_fields` name | `7`, `:market` |
|
|
45
|
+
| Is not listed twice | Each `additional_qid_fields` name | `market`, listed two times |
|
|
46
|
+
| Does not equal an `<action>_count` column | Each `additional_qid_fields` name | `view_count`, when `view` is a cascade action |
|
|
47
|
+
|
|
48
|
+
A name that breaks a rule raises `Ltr::ConfigurationError` that names the setting. The bare action name is not checked, so an action named `qid` is fine. The SQL double-quotes each config-derived column, so an SQL keyword such as `order` is a usable name.
|
|
49
|
+
|
|
50
|
+
Both engines compare values as text. A query id matches an event's query id when their text is the same, so an Integer `7` in one index joins the String `"7"` in the other. The `additional_qid_fields` values `1` and `"1"` are one value, so those queries share a `qid`.
|
|
51
|
+
|
|
52
|
+
A document score is kept when it is a number, text or a boolean. A `true` score becomes 1 and a `false` score becomes 0, the same numbers a host sends to serving. So a `true` `bm25_*` score counts in `bm25_fields_matched` and a `false` one does not. A `nil`, hash or array score is left out, so it makes no column and does not count in `bm25_fields_matched`. Text scores stay as features, which one-hot encoding turns into columns.
|
|
53
|
+
|
|
54
|
+
## What both engines give
|
|
55
|
+
|
|
56
|
+
With the same config and data, both engines produce the same rows, the same `qid` numbers and the same labels. They also keep the same negatives under `dataset_builder.negative_downsample_ratio`. Both engines give string doc ids, even when the event attribute holds a number.
|
|
57
|
+
|
|
58
|
+
With `dataset_builder.negative_downsample_ratio` set, both engines rank each negative with `Ltr::DatasetAggregation::NegativeRank`. The `ruby` engine calls it in Ruby. The `sqlite` engine registers the same function as `ltr_negative_rank`. Each group keeps the negatives with the lowest rank.
|
|
59
|
+
|
|
60
|
+
## When a `sqlite` run fails
|
|
61
|
+
|
|
62
|
+
A failure at any point deletes the run's folder and its database, then raises the original error. Ctrl-C deletes them too. The engine has no retry or resume, and keeps nothing for inspection. Fix the cause and rerun the pipeline.
|
|
63
|
+
|
|
64
|
+
Before deleting the folder, the engine logs one error line that starts `Sqlite aggregation failed --`. It then lists the `phase`, the `error`, the row `counts` per table, the `database` size and the `deleted` path. `phase` is `download`, `aggregation`, `aggregate_load` or `finalize`. When an SQL statement failed, the line ends with that statement.
|
|
65
|
+
|
|
66
|
+
| Error | What to do |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `Ltr::MissingDependencyError` | Add `gem "sqlite3", "~> 2.0"` to the Gemfile. |
|
|
69
|
+
| `Ltr::ConfigurationError: dataset_builder.conversion_rate_targets must be a non-empty array` | Add a rate target that names an action. |
|
|
70
|
+
| `ArgumentError: UBI events cannot be empty` or `UBI queries cannot be empty` | Check the rate targets' action names against the events index, then the date range. |
|
|
71
|
+
| `ArgumentError: No ubi_queries record has <field>. Check dataset_builder.hit_ids_field.` | Set `dataset_builder.hit_ids_field` to the field with the page's ordered hit ids. |
|
|
72
|
+
| `ArgumentError: None of the <n> events has event_attributes.<field>.` | Set `dataset_builder.doc_id_field` to the event attribute that holds the doc id. |
|
|
73
|
+
| `SQLite3::FullException`, or `Ltr::SqliteError` with `database or disk is full` | Point `staging_root` at a larger volume, or shorten the date range. |
|
|
74
|
+
| `Ltr::SqliteError: Sqlite aggregation failed at stage <name>` | Read SQLite's message and the failing statement in the log line. The stage is the `-- STATEMENT: <name>` block in `lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb`. |
|
|
75
|
+
|
|
76
|
+
## Memory and disk
|
|
77
|
+
|
|
78
|
+
- **Memory.** While downloading, the `sqlite` engine holds one OpenSearch page and the set of query ids it has seen. The aggregated rows then load into memory for `DatasetFinalizer`, as on the `ruby` engine. So `sqlite` keeps the raw events and per-search rows out of RAM, but not the final dataset.
|
|
79
|
+
- **Disk.** The database holds every downloaded cascade-action event, and one row per scored document that each search showed. It also holds the working tables. Large sorts write temporary files to the same folder.
|
|
80
|
+
- **Time.** The log has one line for each SQL statement except the last one, `aggregate_select`, `Sqlite aggregation stage <name>: <seconds>s`.
|