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,647 @@
1
+ # Run the pipelines on AWS
2
+
3
+ This guide runs the same three pipelines as the [local guide](run-locally.md). The backing services change. The dataset goes to S3. The chosen features go to SSM. The model is served from a SageMaker endpoint. Your app calls that endpoint.
4
+
5
+ Do the local guide first. This guide continues in the same `ltr-demo` project and reuses its `Gemfile`, `Rakefile`, `config/ltr/base.yml`, mapping files and `scripts/seed_ubi.rb`.
6
+
7
+ Every `Expect:` block in this guide is example output. It comes from an offline check with stubbed AWS responses, not from a real AWS account. The metric and hyperparameter numbers will differ from run to run.
8
+
9
+ ```mermaid
10
+ flowchart LR
11
+ A[OpenSearch with UBI data] --> B[ltr:aggregate]
12
+ B --> C[S3 dataset]
13
+ C --> D[ltr:optimize]
14
+ D --> E[SSM parameters]
15
+ E --> F[ltr:train]
16
+ F --> G[S3 model.tar.gz]
17
+ G --> H[SageMaker endpoint]
18
+ I[Your app] -->|InvokeEndpoint| H
19
+ ```
20
+
21
+ ## What it costs
22
+
23
+ The endpoint is billed every hour it exists, even with no traffic. The default instance is `ml.m5.large`. An OpenSearch domain is billed by the hour too, if you create one in the OpenSearch section. Check the current prices on the [SageMaker pricing page](https://aws.amazon.com/sagemaker/ai/pricing/) and the [OpenSearch Service pricing page](https://aws.amazon.com/opensearch-service/pricing/) before you start. Run the teardown step when you finish.
24
+
25
+ ## Before you start
26
+
27
+ - The local guide is done.
28
+ - AWS CLI v2 is installed and signed in. Check it with `aws sts get-caller-identity`.
29
+ - Your region is in `Ltr::Deploy::SagemakerEndpoint::IMAGE_REGISTRY_ACCOUNTS`, the regions where the deployer has a built-in `sagemaker-xgboost` image. In any other region, set `deploy.image_uri` in your config to a `sagemaker-xgboost` ECR image in that region.
30
+ - The endpoint can reach PyPI when it starts. The container runs `pip install` for `code/requirements.txt`, so an endpoint that cannot reach PyPI fails to start.
31
+ - You can create IAM roles and policies, S3 buckets, SSM parameters and SageMaker resources.
32
+ - The machine that runs the pipelines can reach your OpenSearch cluster.
33
+ - `tar` is installed.
34
+ - `jq` is installed.
35
+
36
+ ## Set your variables
37
+
38
+ Run this block once. Every later block uses only these variables. The block saves them to `.ltr.env`. In a new terminal, run `source .ltr.env`.
39
+
40
+ Change `AWS_REGION` if you want another supported region. If you use your own OpenSearch cluster, set `OPENSEARCH_USERNAME` before you run the block. You set `OPENSEARCH_URL` in [path A](#path-a-you-already-have-a-cluster-with-ubi-data).
41
+
42
+ ```bash
43
+ export AWS_REGION="${AWS_REGION:-us-east-1}"
44
+ AWS_ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)"
45
+ cat > .ltr.env <<EOF
46
+ export AWS_REGION=$AWS_REGION
47
+ export AWS_DEFAULT_REGION=$AWS_REGION
48
+ export AWS_ACCOUNT_ID=$AWS_ACCOUNT_ID
49
+ export LTR_MODEL_NAME=ltr-demo
50
+ export LTR_ENDPOINT=ltr-demo-endpoint
51
+ export LTR_BUCKET=ltr-demo-$AWS_ACCOUNT_ID-$AWS_REGION
52
+ export LTR_ROLE_NAME=ltr-demo-sagemaker-execution
53
+ export LTR_ROLE_ARN=arn:aws:iam::$AWS_ACCOUNT_ID:role/ltr-demo-sagemaker-execution
54
+ export LTR_INSTANCE_TYPE=ml.m5.large
55
+ export LTR_RUNNER_POLICY=ltr-demo-runner
56
+ export LTR_APP_POLICY=ltr-demo-app
57
+ export LTR_RUNNER_USER=${LTR_RUNNER_USER:-}
58
+ export LTR_RUNNER_ROLE=${LTR_RUNNER_ROLE:-}
59
+ export LTR_APP_ROLE=${LTR_APP_ROLE:-}
60
+ export LTR_OS_DOMAIN=ltr-demo
61
+ export OPENSEARCH_USERNAME=${OPENSEARCH_USERNAME:-ltr_admin}
62
+ export OPENSEARCH_PASSWORD_PARAM=/ltr-demo/opensearch-password
63
+ EOF
64
+ source .ltr.env
65
+ mkdir -p policies
66
+ echo "$LTR_BUCKET"
67
+ ```
68
+
69
+ `LTR_RUNNER_USER`, `LTR_RUNNER_ROLE` and `LTR_APP_ROLE` are optional. The permissions section attaches policies to them when they are set.
70
+
71
+ Expect:
72
+
73
+ ```text
74
+ ltr-demo-123456789012-us-east-1
75
+ ```
76
+
77
+ The gem reads its S3, SSM and SageMaker Runtime region from the AWS SDK default. The deployer reads its region from `training.s3_region`. Both come from `AWS_REGION` here, so they always match.
78
+
79
+ ## Create the S3 bucket
80
+
81
+ ```bash
82
+ if [ "$AWS_REGION" = us-east-1 ]; then
83
+ aws s3api create-bucket --bucket "$LTR_BUCKET"
84
+ else
85
+ aws s3api create-bucket --bucket "$LTR_BUCKET" --create-bucket-configuration "LocationConstraint=$AWS_REGION"
86
+ fi
87
+ aws s3api put-public-access-block --bucket "$LTR_BUCKET" \
88
+ --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
89
+ aws s3api put-bucket-encryption --bucket "$LTR_BUCKET" \
90
+ --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
91
+ aws s3api get-public-access-block --bucket "$LTR_BUCKET" --query 'PublicAccessBlockConfiguration.BlockPublicAcls'
92
+ ```
93
+
94
+ Expect:
95
+
96
+ ```text
97
+ true
98
+ ```
99
+
100
+ What the gem writes:
101
+
102
+ | Key | Written by |
103
+ |---|---|
104
+ | `ltr/data/ltr_dataset.csv.gz` | `ltr:aggregate` |
105
+ | `ltr/models/<model>-<unix time>/model.tar.gz` | `ltr:train`, one per deploy |
106
+
107
+ The feature store is not written to S3 by the pipelines. `ltr:train` packs it inside `model.tar.gz`.
108
+
109
+ ## Create the SageMaker execution role
110
+
111
+ The endpoint runs as this role. It reads the model from S3, pulls the inference image from the AWS ECR account that owns the image, and writes logs.
112
+
113
+ The policy below allows ECR pulls from the `sagemaker-xgboost` repository in the registry account of your region. Set `LTR_IMAGE_ACCOUNT` to the registry account first, because the account differs by region. The table shows what to set in each case.
114
+
115
+ | Case | What to do |
116
+ |---|---|
117
+ | Your region is in `IMAGE_REGISTRY_ACCOUNTS` | Run the lookup below. It saves `LTR_IMAGE_ACCOUNT` to `.ltr.env`. |
118
+ | Your region is not in `IMAGE_REGISTRY_ACCOUNTS` | The lookup fails and saves nothing. Set `LTR_IMAGE_ACCOUNT` to the 12-digit account at the start of your `deploy.image_uri` and add the `export` line to `.ltr.env` yourself. |
119
+ | `deploy.image_uri` is in another account or repository | Change the ECR `Resource` to match. |
120
+
121
+ ```bash
122
+ export LTR_IMAGE_ACCOUNT="$(bundle exec ruby -e 'require "ltr"; puts Ltr::Deploy::SagemakerEndpoint::IMAGE_REGISTRY_ACCOUNTS.fetch(ENV.fetch("AWS_REGION"))')"
123
+ test -n "$LTR_IMAGE_ACCOUNT" && echo "export LTR_IMAGE_ACCOUNT=$LTR_IMAGE_ACCOUNT" >> .ltr.env
124
+ echo "$LTR_IMAGE_ACCOUNT"
125
+ ```
126
+
127
+ Expect the account for your region. In `us-east-1` it is `683313688378`.
128
+
129
+ ```bash
130
+ cat > policies/sagemaker-trust.json <<EOF
131
+ {
132
+ "Version": "2012-10-17",
133
+ "Statement": [
134
+ { "Effect": "Allow", "Principal": { "Service": "sagemaker.amazonaws.com" }, "Action": "sts:AssumeRole" }
135
+ ]
136
+ }
137
+ EOF
138
+ cat > policies/sagemaker-execution.json <<EOF
139
+ {
140
+ "Version": "2012-10-17",
141
+ "Statement": [
142
+ { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::$LTR_BUCKET/ltr/models/*" },
143
+ { "Effect": "Allow", "Action": "ecr:GetAuthorizationToken", "Resource": "*" },
144
+ {
145
+ "Effect": "Allow",
146
+ "Action": ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"],
147
+ "Resource": "arn:aws:ecr:$AWS_REGION:$LTR_IMAGE_ACCOUNT:repository/sagemaker-xgboost"
148
+ },
149
+ {
150
+ "Effect": "Allow",
151
+ "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "logs:DescribeLogStreams"],
152
+ "Resource": "arn:aws:logs:$AWS_REGION:$AWS_ACCOUNT_ID:log-group:/aws/sagemaker/*"
153
+ },
154
+ { "Effect": "Allow", "Action": "cloudwatch:PutMetricData", "Resource": "*" }
155
+ ]
156
+ }
157
+ EOF
158
+ jq empty policies/sagemaker-trust.json policies/sagemaker-execution.json
159
+ aws iam create-role --role-name "$LTR_ROLE_NAME" --assume-role-policy-document file://policies/sagemaker-trust.json
160
+ aws iam put-role-policy --role-name "$LTR_ROLE_NAME" --policy-name ltr-demo-execution --policy-document file://policies/sagemaker-execution.json
161
+ aws iam get-role --role-name "$LTR_ROLE_NAME" --query Role.Arn --output text
162
+ ```
163
+
164
+ Expect:
165
+
166
+ ```text
167
+ arn:aws:iam::123456789012:role/ltr-demo-sagemaker-execution
168
+ ```
169
+
170
+ ## Give the runner its permissions
171
+
172
+ The runner is the user or role that runs the rake tasks. The app only calls the endpoint. Each gets its own policy.
173
+
174
+ ```bash
175
+ cat > policies/runner.json <<EOF
176
+ {
177
+ "Version": "2012-10-17",
178
+ "Statement": [
179
+ { "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], "Resource": "arn:aws:s3:::$LTR_BUCKET/ltr/*" },
180
+ { "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::$LTR_BUCKET" },
181
+ {
182
+ "Effect": "Allow",
183
+ "Action": ["ssm:GetParameter", "ssm:PutParameter", "ssm:GetParametersByPath"],
184
+ "Resource": [
185
+ "arn:aws:ssm:$AWS_REGION:$AWS_ACCOUNT_ID:parameter/ltr/$LTR_MODEL_NAME",
186
+ "arn:aws:ssm:$AWS_REGION:$AWS_ACCOUNT_ID:parameter/ltr/$LTR_MODEL_NAME/*",
187
+ "arn:aws:ssm:$AWS_REGION:$AWS_ACCOUNT_ID:parameter$OPENSEARCH_PASSWORD_PARAM"
188
+ ]
189
+ },
190
+ {
191
+ "Effect": "Allow",
192
+ "Action": [
193
+ "sagemaker:CreateModel", "sagemaker:DescribeModel", "sagemaker:DeleteModel",
194
+ "sagemaker:CreateEndpointConfig", "sagemaker:DescribeEndpointConfig", "sagemaker:DeleteEndpointConfig",
195
+ "sagemaker:CreateEndpoint", "sagemaker:UpdateEndpoint", "sagemaker:DescribeEndpoint", "sagemaker:DeleteEndpoint"
196
+ ],
197
+ "Resource": [
198
+ "arn:aws:sagemaker:$AWS_REGION:$AWS_ACCOUNT_ID:model/$LTR_MODEL_NAME*",
199
+ "arn:aws:sagemaker:$AWS_REGION:$AWS_ACCOUNT_ID:endpoint-config/$LTR_MODEL_NAME*",
200
+ "arn:aws:sagemaker:$AWS_REGION:$AWS_ACCOUNT_ID:endpoint/$LTR_MODEL_NAME*"
201
+ ]
202
+ },
203
+ { "Effect": "Allow", "Action": ["sagemaker:ListModels", "sagemaker:ListEndpointConfigs", "sagemaker:ListEndpoints"], "Resource": "*" },
204
+ {
205
+ "Effect": "Allow",
206
+ "Action": "iam:PassRole",
207
+ "Resource": "$LTR_ROLE_ARN",
208
+ "Condition": { "StringEquals": { "iam:PassedToService": "sagemaker.amazonaws.com" } }
209
+ },
210
+ { "Effect": "Allow", "Action": "cloudwatch:GetMetricStatistics", "Resource": "*" },
211
+ { "Effect": "Allow", "Action": ["logs:FilterLogEvents", "logs:GetLogEvents"], "Resource": "arn:aws:logs:$AWS_REGION:$AWS_ACCOUNT_ID:log-group:/aws/sagemaker/Endpoints/$LTR_ENDPOINT:*" }
212
+ ]
213
+ }
214
+ EOF
215
+ cat > policies/app.json <<EOF
216
+ {
217
+ "Version": "2012-10-17",
218
+ "Statement": [
219
+ { "Effect": "Allow", "Action": "sagemaker:InvokeEndpoint", "Resource": "arn:aws:sagemaker:$AWS_REGION:$AWS_ACCOUNT_ID:endpoint/$LTR_ENDPOINT" }
220
+ ]
221
+ }
222
+ EOF
223
+ jq empty policies/runner.json policies/app.json
224
+ RUNNER_POLICY_ARN="$(aws iam create-policy --policy-name "$LTR_RUNNER_POLICY" --policy-document file://policies/runner.json --query Policy.Arn --output text)"
225
+ APP_POLICY_ARN="$(aws iam create-policy --policy-name "$LTR_APP_POLICY" --policy-document file://policies/app.json --query Policy.Arn --output text)"
226
+ echo "export RUNNER_POLICY_ARN=$RUNNER_POLICY_ARN" >> .ltr.env
227
+ echo "export APP_POLICY_ARN=$APP_POLICY_ARN" >> .ltr.env
228
+ echo "$RUNNER_POLICY_ARN"
229
+ ```
230
+
231
+ Expect:
232
+
233
+ ```text
234
+ arn:aws:iam::123456789012:policy/ltr-demo-runner
235
+ ```
236
+
237
+ Attach the policies to whoever needs them. If you run the pipelines as the admin that made these resources, you can skip this block. For an SSO role, attach the policy through your permission set instead.
238
+
239
+ ```bash
240
+ if [ -n "$LTR_RUNNER_USER" ]; then aws iam attach-user-policy --user-name "$LTR_RUNNER_USER" --policy-arn "$RUNNER_POLICY_ARN"; fi
241
+ if [ -n "$LTR_RUNNER_ROLE" ]; then aws iam attach-role-policy --role-name "$LTR_RUNNER_ROLE" --policy-arn "$RUNNER_POLICY_ARN"; fi
242
+ if [ -n "$LTR_APP_ROLE" ]; then aws iam attach-role-policy --role-name "$LTR_APP_ROLE" --policy-arn "$APP_POLICY_ARN"; fi
243
+ ```
244
+
245
+ ## Connect to OpenSearch
246
+
247
+ The gem connects with a username and password, or with no auth. It does not sign requests with IAM (SigV4). So these do not work:
248
+
249
+ - A domain that allows only IAM access.
250
+ - OpenSearch Serverless.
251
+
252
+ Use fine-grained access control with an internal user.
253
+
254
+ ### Path A: you already have a cluster with UBI data
255
+
256
+ The cluster must accept basic auth and be reachable from the runner. Its `ubi_queries` and `ubi_events` indices must match [UBI documents](ubi-documents.md#required-field-types). Set the cluster URL and store the password in SSM, then check the data:
257
+
258
+ ```bash
259
+ export OPENSEARCH_URL=https://your-cluster.example.com:9200
260
+ echo "export OPENSEARCH_URL=$OPENSEARCH_URL" >> .ltr.env
261
+ read -r -s -p "OpenSearch password: " PW && echo
262
+ aws ssm put-parameter --name "$OPENSEARCH_PASSWORD_PARAM" --type SecureString --value "$PW" --overwrite
263
+ unset PW
264
+ OPENSEARCH_PASSWORD="$(aws ssm get-parameter --name "$OPENSEARCH_PASSWORD_PARAM" --with-decryption --query Parameter.Value --output text)"
265
+ export OPENSEARCH_PASSWORD
266
+ curl -s -u "$OPENSEARCH_USERNAME:$OPENSEARCH_PASSWORD" "$OPENSEARCH_URL/ubi_events/_count?filter_path=count"
267
+ ```
268
+
269
+ Then go to the next section.
270
+
271
+ ### Path B: create a small domain to try it out
272
+
273
+ This makes a one-node domain with HTTPS only, encryption at rest and node-to-node encryption. Its endpoint is public and protected by the master user's password and your IP address. Delete it when you finish.
274
+
275
+ ```bash
276
+ OPENSEARCH_PASSWORD="Aa1!$(openssl rand -hex 12)"
277
+ aws ssm put-parameter --name "$OPENSEARCH_PASSWORD_PARAM" --type SecureString --value "$OPENSEARCH_PASSWORD" --overwrite
278
+ MY_IP="$(curl -s https://checkip.amazonaws.com)"
279
+ cat > policies/opensearch-access.json <<EOF
280
+ {
281
+ "Version": "2012-10-17",
282
+ "Statement": [
283
+ {
284
+ "Effect": "Allow",
285
+ "Principal": { "AWS": "*" },
286
+ "Action": "es:ESHttp*",
287
+ "Resource": "arn:aws:es:$AWS_REGION:$AWS_ACCOUNT_ID:domain/$LTR_OS_DOMAIN/*",
288
+ "Condition": { "IpAddress": { "aws:SourceIp": "$MY_IP" } }
289
+ }
290
+ ]
291
+ }
292
+ EOF
293
+ jq empty policies/opensearch-access.json
294
+ aws opensearch create-domain --domain-name "$LTR_OS_DOMAIN" --engine-version OpenSearch_2.19 \
295
+ --cluster-config InstanceType=t3.small.search,InstanceCount=1 \
296
+ --ebs-options EBSEnabled=true,VolumeType=gp3,VolumeSize=10 \
297
+ --node-to-node-encryption-options Enabled=true \
298
+ --encryption-at-rest-options Enabled=true \
299
+ --domain-endpoint-options EnforceHTTPS=true,TLSSecurityPolicy=Policy-Min-TLS-1-2-2019-07 \
300
+ --advanced-security-options "Enabled=true,InternalUserDatabaseEnabled=true,MasterUserOptions={MasterUserName=$OPENSEARCH_USERNAME,MasterUserPassword=$OPENSEARCH_PASSWORD}" \
301
+ --access-policies file://policies/opensearch-access.json
302
+ until [ "$(aws opensearch describe-domain --domain-name "$LTR_OS_DOMAIN" --query DomainStatus.Processing --output text)" = False ]; do sleep 30; done
303
+ OPENSEARCH_URL="https://$(aws opensearch describe-domain --domain-name "$LTR_OS_DOMAIN" --query DomainStatus.Endpoint --output text)"
304
+ echo "export OPENSEARCH_URL=$OPENSEARCH_URL" >> .ltr.env
305
+ export OPENSEARCH_URL OPENSEARCH_PASSWORD
306
+ curl -s -u "$OPENSEARCH_USERNAME:$OPENSEARCH_PASSWORD" "$OPENSEARCH_URL/_cluster/health?filter_path=status"
307
+ ```
308
+
309
+ A new domain takes 15 to 30 minutes. Expect `{"status":"green"}`.
310
+
311
+ Create the indices and load the fake data with the files from the [local guide](run-locally.md):
312
+
313
+ ```bash
314
+ curl -s -u "$OPENSEARCH_USERNAME:$OPENSEARCH_PASSWORD" -X PUT "$OPENSEARCH_URL/ubi_queries" -H 'Content-Type: application/json' -d @config/ltr/ubi_queries.mapping.json
315
+ echo
316
+ curl -s -u "$OPENSEARCH_USERNAME:$OPENSEARCH_PASSWORD" -X PUT "$OPENSEARCH_URL/ubi_events" -H 'Content-Type: application/json' -d @config/ltr/ubi_events.mapping.json
317
+ echo
318
+ bundle exec ruby scripts/seed_ubi.rb
319
+ ```
320
+
321
+ The seed script reads `OPENSEARCH_URL`, `OPENSEARCH_USERNAME` and `OPENSEARCH_PASSWORD`. Expect `queries: 3000` and `events: 42614`.
322
+
323
+ ## Install the gem on the runner
324
+
325
+ Use the same `Gemfile`, `Rakefile` and `bundle install` as the local guide. First add `aws-sdk-s3`, `aws-sdk-ssm`, `aws-sdk-sagemaker` and `aws-sdk-sagemakerruntime` to the `Gemfile`, then run `bundle install` again. A laptop is fine for the first run. [Retrain on a schedule](#retrain-on-a-schedule) covers the rest.
326
+
327
+ ## Write the config
328
+
329
+ Use the same `config/ltr/base.yml` copy as the local guide. Then write `config/ltr/aws.yml`. Every account value comes from the variables. Every key is listed in the [Config reference](config.md). The file holds only the keys that differ from `base.yml`, plus the three sections that `ltr:optimize` rewrites.
330
+
331
+ ```bash
332
+ cat > config/ltr/aws.yml <<'EOF'
333
+ model:
334
+ name: <%= ENV.fetch("LTR_MODEL_NAME") %>
335
+ hyperparameters:
336
+ n_estimators: 100
337
+
338
+ training:
339
+ modelling_dataset_path: s3://<%= ENV.fetch("LTR_BUCKET") %>/ltr/data/ltr_dataset.csv
340
+ s3_region: <%= ENV.fetch("AWS_REGION") %>
341
+
342
+ search_time_features:
343
+ - relevancy
344
+ - bm25_name
345
+ - bm25_description
346
+
347
+ feature_store:
348
+ features:
349
+ - view_count
350
+ - add_to_cart_count
351
+ - purchase_count
352
+
353
+ ubi_data_loader:
354
+ n_events: 50000
355
+ opensearch:
356
+ url: <%= ENV.fetch("OPENSEARCH_URL") %>
357
+ username: <%= ENV.fetch("OPENSEARCH_USERNAME") %>
358
+ password: <%= ENV.fetch("OPENSEARCH_PASSWORD") %>
359
+
360
+ optimization:
361
+ iterations: 10
362
+ search_time_features:
363
+ - relevancy
364
+ - bm25_name
365
+ - bm25_description
366
+ feature_store_features:
367
+ - view_count
368
+ - add_to_cart_count
369
+ - purchase_count
370
+ - cart_conversion
371
+ - purchase_conversion
372
+
373
+ deploy:
374
+ enabled: true
375
+ sagemaker_bucket: <%= ENV.fetch("LTR_BUCKET") %>
376
+ execution_role: <%= ENV.fetch("LTR_ROLE_ARN") %>
377
+ instance_type: <%= ENV.fetch("LTR_INSTANCE_TYPE") %>
378
+ metric: ndcg@12
379
+
380
+ ssm:
381
+ enabled: true
382
+ all_features_param_path: /ltr/<%= ENV.fetch("LTR_MODEL_NAME") %>/all_features
383
+ feature_store_features_param_path: /ltr/<%= ENV.fetch("LTR_MODEL_NAME") %>/feature_store_features
384
+ hyperparameters_param_path: /ltr/<%= ENV.fetch("LTR_MODEL_NAME") %>/hyperparameters
385
+ EOF
386
+ ```
387
+
388
+ The copied `base.yml` reads the role and bucket from env vars. This override sets both, so always keep `execution_role` and `sagemaker_bucket` in it.
389
+
390
+ `AWS_REGION` must equal `training.s3_region`. The file reads both from the same variable.
391
+
392
+ The override holds `model.hyperparameters`, `search_time_features` and `feature_store.features` for the same reason as the local guide. `ltr:optimize` rewrites those sections. It also adds an `optimized_features` list at the end of the override file.
393
+
394
+ Load the OpenSearch password before every run:
395
+
396
+ ```bash
397
+ source .ltr.env
398
+ OPENSEARCH_PASSWORD="$(aws ssm get-parameter --name "$OPENSEARCH_PASSWORD_PARAM" --with-decryption --query Parameter.Value --output text)"
399
+ export OPENSEARCH_PASSWORD
400
+ ```
401
+
402
+ ## Run the pipelines
403
+
404
+ Run them in this order. Each step ends with a check.
405
+
406
+ First check that `OPENSEARCH_URL` points at your cluster. The check fails when it is empty or contains `localhost`.
407
+
408
+ ```bash
409
+ case "${OPENSEARCH_URL:-}" in ""|*localhost*) echo "OPENSEARCH_URL is empty or points at localhost: $OPENSEARCH_URL" >&2; false ;; esac
410
+ ```
411
+
412
+ It prints nothing when the URL is fine.
413
+
414
+ ### Aggregate
415
+
416
+ ```bash
417
+ bundle exec rake "ltr:aggregate[config/ltr/base.yml,config/ltr/aws.yml]" 2>&1 | grep "ltr:aggregate" | sed 's/.*INFO -- : //'
418
+ aws s3 ls "s3://$LTR_BUCKET/ltr/data/"
419
+ ```
420
+
421
+ Expect:
422
+
423
+ ```text
424
+ ltr:aggregate base config: config/ltr/base.yml, override config: config/ltr/aws.yml
425
+ ltr:aggregate wrote 1182 rows to s3://ltr-demo-123456789012-us-east-1/ltr/data/ltr_dataset.csv
426
+ 2026-11-16 10:19:12 66315 ltr_dataset.csv.gz
427
+ ```
428
+
429
+ ### Optimize
430
+
431
+ ```bash
432
+ bundle exec rake "ltr:optimize[config/ltr/base.yml,config/ltr/aws.yml]" 2>&1 | grep "ltr:optimize" | sed 's/.*INFO -- : //'
433
+ aws ssm get-parameters-by-path --path "/ltr/$LTR_MODEL_NAME/" --query 'Parameters[].Name' --output text
434
+ ```
435
+
436
+ Expect:
437
+
438
+ ```text
439
+ ltr:optimize base config: config/ltr/base.yml, override config: config/ltr/aws.yml
440
+ ltr:optimize search_time_features: ["relevancy", "relevancy_relative_score"]
441
+ ltr:optimize feature_store_features: ["view_count", "purchase_count"]
442
+ ltr:optimize hyperparameters: {:eval_metric=>"ndcg@12", ..., ...}
443
+ /ltr/ltr-demo/all_features /ltr/ltr-demo/feature_store_features /ltr/ltr-demo/hyperparameters
444
+ ```
445
+
446
+ `ltr:train` fails with `Aws::SSM::Errors::ParameterNotFound` until this step has written to SSM.
447
+
448
+ ### Train and deploy
449
+
450
+ ```bash
451
+ bundle exec rake "ltr:train[config/ltr/base.yml,config/ltr/aws.yml]" 2>&1 | grep "ltr:train" | sed 's/.*INFO -- : //'
452
+ ```
453
+
454
+ Expect:
455
+
456
+ ```text
457
+ ltr:train base config: config/ltr/base.yml, override config: config/ltr/aws.yml
458
+ ltr:train metrics: {"map@10"=>..., "mrr@10"=>..., "ndcg"=>..., "ndcg@5"=>..., "ndcg@12"=>..., "precision"=>..., "precision@5"=>..., "recall@5"=>...}
459
+ ltr:train sagemaker deploy: deployed=true, reason=threshold_met
460
+ ltr:train local deploy: deployed=false, reason=not_configured
461
+ ```
462
+
463
+ The task trains the model, then deploys it when the metric passes the gate. The deploy builds `model.tar.gz`, uploads it to S3, and creates a SageMaker model and endpoint config. Then it creates the endpoint `$LTR_ENDPOINT`, or updates it in place if it exists. The task waits until the endpoint is `InService`. It keeps polling on the `Creating`, `Updating`, `SystemUpdating` and `RollingBack` statuses. It stops at once on `Failed`. It also stops when the endpoint is `InService` but serves an older endpoint config than the one just deployed, which means the update rolled back and the old model is still serving. A new endpoint often takes 5 to 15 minutes. The wait stops after about an hour.
464
+
465
+ Check the endpoint:
466
+
467
+ ```bash
468
+ aws sagemaker describe-endpoint --endpoint-name "$LTR_ENDPOINT" --query EndpointStatus --output text
469
+ ```
470
+
471
+ Expect:
472
+
473
+ ```text
474
+ InService
475
+ ```
476
+
477
+ ### The deploy gate
478
+
479
+ The task deploys only when `deploy.metric` is at least `deploy.minimum_metric_value`. When it is not, the task still passes and prints:
480
+
481
+ ```text
482
+ ltr:train sagemaker deploy: deployed=false, reason=below_threshold, metric=ndcg@12, score=0.996, threshold=0.999
483
+ ```
484
+
485
+ Lower `minimum_metric_value` in `config/ltr/aws.yml` to deploy anyway. Read the metric names in the `ltr:train metrics` line.
486
+
487
+ With `deploy.local: true`, the local save uses the same minimum. Below it, the task writes no file.
488
+
489
+ ## Call the endpoint
490
+
491
+ Send the search-time features only. The endpoint adds the stored features from the feature store inside `model.tar.gz`.
492
+
493
+ ```bash
494
+ cat > payload.json <<'EOF'
495
+ {
496
+ "items": [
497
+ { "id": "p01-23", "fields": [{ "name": "relevancy", "value": 9.2 }, { "name": "bm25_name", "value": 8.1 }, { "name": "bm25_description", "value": 4.0 }] },
498
+ { "id": "p01-15", "fields": [{ "name": "relevancy", "value": 8.7 }, { "name": "bm25_name", "value": 7.9 }, { "name": "bm25_description", "value": 3.2 }] },
499
+ { "id": "p01-02", "fields": [{ "name": "relevancy", "value": 6.1 }, { "name": "bm25_name", "value": 5.0 }, { "name": "bm25_description", "value": 2.2 }] }
500
+ ]
501
+ }
502
+ EOF
503
+ aws sagemaker-runtime invoke-endpoint --endpoint-name "$LTR_ENDPOINT" --content-type application/json \
504
+ --cli-binary-format raw-in-base64-out --body file://payload.json out.json
505
+ cat out.json
506
+ ```
507
+
508
+ Expect:
509
+
510
+ ```text
511
+ {"items": [{"item": "p01-23", "score": 2.6748435497283936}, {"item": "p01-15", "score": 2.4464991092681885}, {"item": "p01-02", "score": -1.3254777193069458}], "took_seconds": 0.005}
512
+ ```
513
+
514
+ The same call from Ruby:
515
+
516
+ ```bash
517
+ bundle exec ruby -e 'require "ltr"; payload = JSON.parse(File.read("payload.json")); puts Ltr::Inference::SagemakerClient.call(payload, nil, ENV.fetch("LTR_ENDPOINT")).to_json'
518
+ ```
519
+
520
+ The response shape is in [Inference](inference.md#inference-response). A product id that is not in the feature store gets missing stored features. XGBoost treats them as missing.
521
+
522
+ ## Use it in your app
523
+
524
+ [Inference](inference.md) shows how to call the endpoint from your app, how to set the timeouts, and how to fall back to the original order when the call fails. See its [Failures](inference.md#failures) section.
525
+
526
+ ## Retrain on a schedule
527
+
528
+ Run `ltr:aggregate` then `ltr:train` often, for example every night. Run `ltr:optimize` less often, for example every week. These cadences are examples.
529
+
530
+ ```bash
531
+ mkdir -p bin
532
+ cat > bin/ltr-run <<'EOF'
533
+ #!/usr/bin/env bash
534
+ set -euo pipefail
535
+ cd "$(dirname "$0")/.."
536
+ source .ltr.env
537
+ OPENSEARCH_PASSWORD="$(aws ssm get-parameter --name "$OPENSEARCH_PASSWORD_PARAM" --with-decryption --query Parameter.Value --output text)"
538
+ export OPENSEARCH_PASSWORD
539
+ for task in "$@"; do
540
+ bundle exec rake "ltr:${task}[config/ltr/base.yml,config/ltr/aws.yml]"
541
+ done
542
+ EOF
543
+ chmod +x bin/ltr-run
544
+ ```
545
+
546
+ A cron example:
547
+
548
+ ```text
549
+ 0 3 * * * /srv/ltr-demo/bin/ltr-run aggregate train
550
+ 0 2 * * 0 /srv/ltr-demo/bin/ltr-run aggregate optimize train
551
+ ```
552
+
553
+ For a large pull, set `dataset_builder.aggregation_engine: sqlite` and `dataset_aggregation.staging_root` to a disk with room. The `ruby` engine holds every event in memory. The `sqlite` engine needs `gem "sqlite3", "~> 2.0"` in your `Gemfile`.
554
+
555
+ Each run updates the same endpoint in place.
556
+
557
+ ## Monitor and roll back
558
+
559
+ CloudWatch has `Invocations`, `ModelLatency` and `5XXError` under the `AWS/SageMaker` namespace. Read the endpoint logs with:
560
+
561
+ ```bash
562
+ aws logs tail "/aws/sagemaker/Endpoints/$LTR_ENDPOINT" --since 1h
563
+ ```
564
+
565
+ List the endpoint configs, newest first:
566
+
567
+ ```bash
568
+ aws sagemaker list-endpoint-configs --name-contains "$LTR_MODEL_NAME" --sort-by CreationTime --sort-order Descending \
569
+ --query 'EndpointConfigs[].EndpointConfigName' --output text
570
+ ```
571
+
572
+ Roll back to the previous config:
573
+
574
+ ```bash
575
+ PREVIOUS="$(aws sagemaker list-endpoint-configs --name-contains "$LTR_MODEL_NAME" --sort-by CreationTime --sort-order Descending \
576
+ --query 'EndpointConfigs[1].EndpointConfigName' --output text)"
577
+ aws sagemaker update-endpoint --endpoint-name "$LTR_ENDPOINT" --endpoint-config-name "$PREVIOUS"
578
+ ```
579
+
580
+ Every train run adds one model and one endpoint config. Delete the old ones. This keeps the newest three:
581
+
582
+ ```bash
583
+ for config in $(aws sagemaker list-endpoint-configs --name-contains "$LTR_MODEL_NAME" --sort-by CreationTime --sort-order Descending \
584
+ --query 'EndpointConfigs[3:].EndpointConfigName' --output text); do
585
+ aws sagemaker delete-endpoint-config --endpoint-config-name "$config"
586
+ aws sagemaker delete-model --model-name "${config%-config}"
587
+ done
588
+ ```
589
+
590
+ ## Tear it all down
591
+
592
+ Run this with the admin identity that created the resources. It deletes the endpoint first, then everything it used.
593
+
594
+ ```bash
595
+ aws sagemaker delete-endpoint --endpoint-name "$LTR_ENDPOINT"
596
+ for config in $(aws sagemaker list-endpoint-configs --name-contains "$LTR_MODEL_NAME" --query 'EndpointConfigs[].EndpointConfigName' --output text); do
597
+ aws sagemaker delete-endpoint-config --endpoint-config-name "$config"
598
+ done
599
+ for model in $(aws sagemaker list-models --name-contains "$LTR_MODEL_NAME" --query 'Models[].ModelName' --output text); do
600
+ aws sagemaker delete-model --model-name "$model"
601
+ done
602
+ aws s3 rm "s3://$LTR_BUCKET" --recursive
603
+ aws s3api delete-bucket --bucket "$LTR_BUCKET"
604
+ for name in $(aws ssm get-parameters-by-path --path "/ltr/$LTR_MODEL_NAME/" --query 'Parameters[].Name' --output text); do
605
+ aws ssm delete-parameter --name "$name"
606
+ done
607
+ aws ssm delete-parameter --name "$OPENSEARCH_PASSWORD_PARAM"
608
+ if [ -n "$LTR_RUNNER_USER" ]; then aws iam detach-user-policy --user-name "$LTR_RUNNER_USER" --policy-arn "$RUNNER_POLICY_ARN"; fi
609
+ if [ -n "$LTR_RUNNER_ROLE" ]; then aws iam detach-role-policy --role-name "$LTR_RUNNER_ROLE" --policy-arn "$RUNNER_POLICY_ARN"; fi
610
+ if [ -n "$LTR_APP_ROLE" ]; then aws iam detach-role-policy --role-name "$LTR_APP_ROLE" --policy-arn "$APP_POLICY_ARN"; fi
611
+ aws iam delete-policy --policy-arn "$RUNNER_POLICY_ARN"
612
+ aws iam delete-policy --policy-arn "$APP_POLICY_ARN"
613
+ aws iam delete-role-policy --role-name "$LTR_ROLE_NAME" --policy-name ltr-demo-execution
614
+ aws iam delete-role --role-name "$LTR_ROLE_NAME"
615
+ ```
616
+
617
+ If you made the domain in path B, delete it too:
618
+
619
+ ```bash
620
+ aws opensearch delete-domain --domain-name "$LTR_OS_DOMAIN"
621
+ ```
622
+
623
+ Check that nothing is left. Each command should print nothing or an empty list:
624
+
625
+ ```bash
626
+ aws sagemaker list-endpoints --name-contains "$LTR_MODEL_NAME" --query 'Endpoints[].EndpointName' --output text
627
+ aws sagemaker list-models --name-contains "$LTR_MODEL_NAME" --query 'Models[].ModelName' --output text
628
+ aws s3 ls | grep "$LTR_BUCKET" || echo "no bucket"
629
+ aws ssm get-parameters-by-path --path "/ltr/$LTR_MODEL_NAME/" --query 'Parameters[].Name' --output text
630
+ aws iam list-roles --query "Roles[?RoleName=='$LTR_ROLE_NAME'].RoleName" --output text
631
+ ```
632
+
633
+ ## Troubleshooting
634
+
635
+ | What you see | Cause | Fix |
636
+ |---|---|---|
637
+ | `Unsupported region: ...` | `training.s3_region` is not in `IMAGE_REGISTRY_ACCOUNTS`, and `deploy.image_uri` is not set. | Set `deploy.image_uri` to a `sagemaker-xgboost` ECR image in your region. Or set `AWS_REGION` to a region in `IMAGE_REGISTRY_ACCOUNTS`, then run `source .ltr.env` again. |
638
+ | `AccessDenied` for `iam:PassRole` | The runner may not pass the execution role to SageMaker. | Attach the runner policy from [Give the runner its permissions](#give-the-runner-its-permissions). It allows `iam:PassRole` on `$LTR_ROLE_ARN`. |
639
+ | `Aws::SSM::Errors::ParameterNotFound` | A required SSM parameter is missing at its configured path. During training these are `all_features` and `hyperparameters`. At deploy these include `feature_store_features` when the feature store is included. | Run `ltr:optimize`, then `ltr:train`. |
640
+ | `SSM is enabled but all_features not found in SSM` | The gem reads both parameters (`all_features`, `hyperparameters`), but `all_features` contains JSON `null`. | Run `ltr:optimize`, then `ltr:train`. |
641
+ | `SSM is enabled but hyperparameters not found in SSM` | The gem reads both parameters (`all_features`, `hyperparameters`). `all_features` holds a list, but `hyperparameters` contains JSON `null`. The gem checks `all_features` first, so a `null` there gives the row above. | Run `ltr:optimize`, then `ltr:train`. |
642
+ | `InstallModuleError` or a pip error in the endpoint log, then status `Failed` | The container runs `pip install` for `code/requirements.txt` when it starts, and the install fails. PyPI may be unreachable from the endpoint, or `xgboost==3.2.0` may not install over the image's pins. | Read the pip error with `aws logs tail "/aws/sagemaker/Endpoints/$LTR_ENDPOINT"`. Fix the cause, then run `ltr:train` again. SageMaker keeps the old endpoint config serving when an update fails. |
643
+ | The endpoint status is `Failed` | The role cannot read the model from S3 or pull the image from ECR. | Run `aws logs tail "/aws/sagemaker/Endpoints/$LTR_ENDPOINT"` and `aws sagemaker describe-endpoint --endpoint-name "$LTR_ENDPOINT" --query FailureReason`. Fix the execution role policy. |
644
+ | The SSO token expires during the endpoint wait | The wait can last up to about an hour. | Sign in again, then run `ltr:train` again. Each run makes a new model and config. |
645
+ | `Faraday::ConnectionFailed` after 5 tries, with 100 seconds of waits between attempts, plus the time each attempt takes | The runner cannot reach the URL in `ubi_data_loader.opensearch.url`. The error names the host and port but not the key. A VPC domain is one cause. | Check `ubi_data_loader.opensearch.url`. Run from a machine in the VPC, or use a public domain with an IP rule. The old dataset and model stay in place. |
646
+ | `ltr:aggregate` ends without a line saying it wrote the dataset | The command filters for `ltr:aggregate`, which hides warnings such as `OpenSearch request failed`. | Rerun the `ltr:aggregate` command without the `grep` and `sed` pipes to see the full output. |
647
+ | `Timeout waiting for endpoint` | The endpoint was not `InService` after about an hour. | Read `describe-endpoint` and the endpoint logs. The usual cause is a failed image pull. |