coolhand 0.13.0 → 0.14.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 +4 -4
- data/CHANGELOG.md +22 -0
- data/README.md +21 -1
- data/docs/declared_workloads.md +29 -1
- data/docs/experiments.md +150 -0
- data/lib/coolhand/base_interceptor.rb +6 -3
- data/lib/coolhand/body_redactor.rb +2 -0
- data/lib/coolhand/declared_context.rb +46 -2
- data/lib/coolhand/experiment_event_service.rb +323 -0
- data/lib/coolhand/experiment_service.rb +147 -0
- data/lib/coolhand/experiment_status_cache.rb +90 -0
- data/lib/coolhand/log_queue.rb +42 -12
- data/lib/coolhand/logger_service.rb +19 -6
- data/lib/coolhand/post_delivery.rb +3 -2
- data/lib/coolhand/read_requests.rb +13 -9
- data/lib/coolhand/version.rb +1 -1
- data/lib/coolhand.rb +22 -8
- metadata +6 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 8d5d90cd4c06e135710fee6a42c174af7dd90c34a01699b73974326c08da70ec
|
|
4
|
+
data.tar.gz: 75680baf460a561512fe95d45f2df9a1e91ea1482921f2d7b0a52bed7362fde2
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 17f3c86f56ba18929d41ec35eb383b239b04fed4d74df512b98c8f88c64572602055c58d3e83db03575517e781df17b64ad602499a0f4d7100ee86d2499e6543
|
|
7
|
+
data.tar.gz: 7ec9201d04a6347c44ac4e1f73512efb36338a8c7bae8aac2f858d9e960c0d4b73b450396ebe420c67f56213a84573a339d119b3f062cb175f68a5d3e2d2e67f
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.14.0] - 2026-12-03
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
- `Coolhand.experiment_service` for experiments (A/B tests) ([#246](https://github.com/Coolhand-Labs/coolhand-ruby/pull/246)). Four parts, documented in the new `docs/experiments.md`:
|
|
14
|
+
- **Private-key endpoints:** `list_experiments` (filters by `status`, `origin`, `kind` and `workload_id`, with pagination read from the `X-*` headers), `get_experiment`, `get_experiment_by_key`, `register_experiment` and `update_experiment`. They raise `Coolhand::HttpError` (with `status`) or `Coolhand::Error` like the other read services. A by-key key with an empty, `.` or `..` segment is refused before the request.
|
|
15
|
+
- **Experiment events:** `register`, `expose` and `ended` take Squishling's payloads unchanged, check `type` against the method, and never raise. Events are queued, sent in batches (at most 500 events, 50 of them registrations and endings, and under 10MB) to `POST /api/v2/experiment_events` with the ingest key, retried once on a network error, 429 or 5xx, and covered by `Coolhand.flush` and the exit flush. At most 10,000 events are held, and an event over the server's 128KB limit is dropped with a warning.
|
|
16
|
+
- **`experiment_status(key)`:** whether an experiment, and each fingerprint, should still run. It returns `nil` on any failure, never raises, waits at most 5 seconds per phase, and caches answers for 60 seconds (`nil` answers for 5).
|
|
17
|
+
- **Experiment tags:** `Coolhand.with_context` takes `experiment_key:`, `arm:` and an optional `fingerprint:`, and sends `declared.experiment` on the captured logs. An invalid tag is dropped with one warning per process, never raised. See `docs/declared_workloads.md`.
|
|
18
|
+
- **Requires a Coolhand server that has the experiment events API** (Coolhand-Labs/coolhand#2515). Against an older server, events are dropped with a 404 and `experiment_status` returns `nil` with the ingest key.
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
- Internal: `LogQueue.submit` gained `on_abandon:` and `requeue:` options and a `before_flush` hook, `LogQueue.register_at_exit` is now public, and `ReadRequests` accepts a shorter per-call timeout ([#246](https://github.com/Coolhand-Labs/coolhand-ruby/pull/246)). No change for existing callers.
|
|
22
|
+
|
|
23
|
+
### Fixed
|
|
24
|
+
- Redaction hardening from the release red-team (no PR). Request and response bodies now also redact `auth_token`, `api_token`, `oauth_token`, `api_secret`, `webhook_secret`, `signing_key`, `subscription_key`, `passphrase`, `pwd`, `credentials`, `sas_token`, `connection_string`, `jwt`, `cookie` and `X-Goog-Api-Key` string values. Headers named `*sig*`, `*pwd*`, `*sas*` or `dpop` are redacted. A credential after a `;` inside a URL-valued header (`Location: https://h/cb?state=1;access_token=...`) is scrubbed. Webhooks sent through `forward_webhook` now scrub URL-valued headers and `metadata` the way the interceptor does.
|
|
25
|
+
- A request header whose value is not valid UTF-8 no longer makes header sanitizing raise, which could replace the host's own LLM response with the error. The value is scrubbed of invalid bytes first.
|
|
26
|
+
- A 2xx response from Coolhand whose body is JSON but not an object (an array, say) now counts as delivered instead of raising `TypeError` into the caller.
|
|
27
|
+
|
|
28
|
+
### Dependencies
|
|
29
|
+
- `ruby/setup-ruby` bumped to 1.345.0 in CI and the publish workflow ([#241](https://github.com/Coolhand-Labs/coolhand-ruby/pull/241)).
|
|
30
|
+
- `rubygems/release-gem` bumped to 1.5.0 in the publish workflow ([#242](https://github.com/Coolhand-Labs/coolhand-ruby/pull/242)).
|
|
31
|
+
|
|
10
32
|
## [0.13.0] - 2026-11-25
|
|
11
33
|
|
|
12
34
|
### Added
|
data/README.md
CHANGED
|
@@ -199,6 +199,25 @@ end
|
|
|
199
199
|
|
|
200
200
|
For nesting rules, class-level declarations, Rails jobs and controllers, upserts, and public-key limits, see [Declared Workloads →](docs/declared_workloads.md).
|
|
201
201
|
|
|
202
|
+
## Experiments (A/B Tests)
|
|
203
|
+
|
|
204
|
+
Register, read and end A/B tests with your private API key, and tag captured calls with the arm they ran under:
|
|
205
|
+
|
|
206
|
+
```ruby
|
|
207
|
+
experiments = Coolhand.experiment_service
|
|
208
|
+
experiment = experiments.register_experiment(
|
|
209
|
+
key: 'checkout-copy', name: 'Shorter checkout copy', evaluate_at: Time.utc(2026, 12, 21),
|
|
210
|
+
arms: [{ key: 'control', role: 'champion' }, { key: 'short', role: 'challenger' }]
|
|
211
|
+
)
|
|
212
|
+
experiments.update_experiment(experiment[:id], status: 'concluded')
|
|
213
|
+
|
|
214
|
+
Coolhand.with_context(experiment_key: 'checkout-copy', arm: 'short') do
|
|
215
|
+
client.chat(...) # captured with the experiment tag
|
|
216
|
+
end
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
The same service carries [Squishling](https://github.com/Coolhand-Labs/squishling)'s experiment reports (`register`, `expose`, `ended`) and `experiment_status`, which work with the public key and never raise. See [Experiments →](docs/experiments.md).
|
|
220
|
+
|
|
202
221
|
## Rails Integration
|
|
203
222
|
|
|
204
223
|
### Configuration
|
|
@@ -533,7 +552,7 @@ The monitor handles errors gracefully:
|
|
|
533
552
|
- Failed API logging attempts are logged to console but don't interrupt your application
|
|
534
553
|
- Invalid API keys will be reported but won't crash your app
|
|
535
554
|
- Network issues are handled with appropriate error messages
|
|
536
|
-
- The read methods (`search_templates`, `get_template`, `list_step_templates`, `get_step_template`, `search_workloads`, `get_realized_savings`, `search_logs`, `get_log`, `failure_summary`, `search_help_articles`, `get_help_article`, `list_help_categories`), the feedback-link methods and the `upsert` methods are the exception — they raise `Coolhand::Error` (`Coolhand::HttpError` for non-2xx responses); see [Reading Templates →](docs/template-search.md), [Reading Step Templates →](docs/step-templates.md), [Reading Workloads →](docs/workload-search.md), [Reading Realized Savings →](docs/savings.md), [Reading Logs →](docs/log-search.md), [Linking Feedback →](docs/feedback-links.md)
|
|
555
|
+
- The read methods (`search_templates`, `get_template`, `list_step_templates`, `get_step_template`, `search_workloads`, `get_realized_savings`, `search_logs`, `get_log`, `failure_summary`, `search_help_articles`, `get_help_article`, `list_help_categories`, `list_experiments`, `get_experiment`, `get_experiment_by_key`), the feedback-link methods, `register_experiment`, `update_experiment` and the `upsert` methods are the exception — they raise `Coolhand::Error` (`Coolhand::HttpError` for non-2xx responses); see [Reading Templates →](docs/template-search.md), [Reading Step Templates →](docs/step-templates.md), [Reading Workloads →](docs/workload-search.md), [Reading Realized Savings →](docs/savings.md), [Reading Logs →](docs/log-search.md), [Linking Feedback →](docs/feedback-links.md), [Declared Workloads →](docs/declared_workloads.md) and [Experiments →](docs/experiments.md)
|
|
537
556
|
|
|
538
557
|
## Documentation
|
|
539
558
|
|
|
@@ -547,6 +566,7 @@ The monitor handles errors gracefully:
|
|
|
547
566
|
- **[Reading the Help Center](docs/help-center.md)** — Search and read Coolhand's help center articles and list its sections, with no API key required
|
|
548
567
|
- **[Linking Feedback](docs/feedback-links.md)** — Link feedback to an optimization as evidence, singly or in bulk, using the private API key
|
|
549
568
|
- **[Declared Workloads](docs/declared_workloads.md)** — Declare the workload and template of captured LLM calls with `Coolhand.with_context`, and create or rename them with `upsert`
|
|
569
|
+
- **[Experiments](docs/experiments.md)** — Register, read and end A/B tests, report Squishling's experiments, check whether one should still run, and tag captured calls with their arm
|
|
550
570
|
- **[Anthropic Integration](docs/anthropic.md)** — Official and community Anthropic Ruby gems, streaming, using both gems, and troubleshooting
|
|
551
571
|
- **[ElevenLabs Integration](docs/elevenlabs.md)** — Webhook capture, feedback submission, and Rails integration
|
|
552
572
|
- **[OpenAI Batch Webhook Handler](docs/openai.md)** — Handle OpenAI batch job completion events via webhook interception
|
data/docs/declared_workloads.md
CHANGED
|
@@ -25,6 +25,7 @@ end
|
|
|
25
25
|
| `workload` | Hash: `id`, `key`, `name`, `description` | Needs an `id` or a `key`. Other keys are ignored. |
|
|
26
26
|
| `template` | Hash: `id`, `key`, `name` | Needs an `id` or a `key`. Other keys are ignored. |
|
|
27
27
|
| `client_unique_id` | String | Your own id for the request, so feedback can find it. See [Linking feedback to a request](#linking-feedback-to-a-request). |
|
|
28
|
+
| `experiment_key`, `arm`, `fingerprint` | Strings | The experiment arm the calls ran under. See [Experiment tags](#experiment-tags). |
|
|
28
29
|
|
|
29
30
|
- `id` refers to an existing record. `key` is a stable string of your choosing; Coolhand finds or creates the record with that key. On a template, `id` wins over `key`.
|
|
30
31
|
- `name`, `description` and `reporter` are used only when a record is **first created**. Declaring never renames or re-attributes an existing record; use `upsert` for that. A display name that is already taken gets a numeric suffix, and names such as "Unmatched" are reserved.
|
|
@@ -36,7 +37,7 @@ end
|
|
|
36
37
|
|
|
37
38
|
### Nesting
|
|
38
39
|
|
|
39
|
-
Blocks nest. Each field (`reporter`, `workload`, `template`, `client_unique_id
|
|
40
|
+
Blocks nest. Each field (`reporter`, `workload`, `template`, `client_unique_id`, and the experiment tag, see [Experiment tags](#experiment-tags)) is taken from the innermost block that sets it, and fields an inner block leaves out are inherited (with the one exception below):
|
|
40
41
|
|
|
41
42
|
```ruby
|
|
42
43
|
Coolhand.with_context(reporter: "my-app", workload: { key: "Parser#call" }) do
|
|
@@ -72,6 +73,33 @@ Coolhand.feedback_service.create_feedback(
|
|
|
72
73
|
- It travels as `llm_request_log.client_unique_id`, not inside `declared`, and it works without a `workload` or `template`.
|
|
73
74
|
- Matching happens on the Coolhand server, so whether the id is honoured depends on the server version. What happens when two logs share an id is also decided by the server.
|
|
74
75
|
|
|
76
|
+
### Experiment tags
|
|
77
|
+
|
|
78
|
+
`experiment_key:` and `arm:`, with an optional `fingerprint:`, tag every log captured in the block with
|
|
79
|
+
the experiment arm it ran under. Coolhand uses the tag to score the experiment and to keep a challenger's
|
|
80
|
+
traffic apart from its template's dashboard. See [Experiments](experiments.md).
|
|
81
|
+
|
|
82
|
+
```ruby
|
|
83
|
+
Coolhand.with_context(experiment_key: "TicketTriage#call/haiku_is_enough", arm: "challenger",
|
|
84
|
+
fingerprint: "3f9a1c2b4d5e") do
|
|
85
|
+
client.chat(...) # logged with declared.experiment = { key:, arm:, fingerprint: }
|
|
86
|
+
end
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
- The three are one unit. `experiment_key` and `arm` go together and `fingerprint` is optional (`nil`
|
|
90
|
+
counts as not given). Squishling passes `"champion"` or `"challenger"` as the arm; an experiment you
|
|
91
|
+
registered through the API names its own arms.
|
|
92
|
+
- `experiment_key` is at most 255 characters and `arm` at most 100. Each starts with a letter or digit and
|
|
93
|
+
is made of ASCII letters, digits and `_.:#/?!-`. `fingerprint` is 1-64 lowercase hex characters.
|
|
94
|
+
- A missing or invalid tag drops all three and is **never raised**: your block still runs and its calls
|
|
95
|
+
are logged without the tag. The first invalid tag in a process is logged; later ones are dropped
|
|
96
|
+
without a warning, since apps wrap every call.
|
|
97
|
+
- An inner block that sets a tag replaces the outer one as a whole. One that sets none of the three
|
|
98
|
+
inherits the outer tag, even when it declares a new workload or template. An inner block with an
|
|
99
|
+
**invalid** tag clears the outer one, so its calls never count toward the outer arm.
|
|
100
|
+
- The tag travels as `llm_request_log.declared.experiment` and is sent even when no workload or template
|
|
101
|
+
is declared. Older Coolhand servers ignore it.
|
|
102
|
+
|
|
75
103
|
### Threads and background logging
|
|
76
104
|
|
|
77
105
|
The context is thread-local, like `Coolhand.with_capture`. It is also fiber-local, so it does not carry into threads, fibers, `Enumerator#next` blocks or async tasks you start inside the block; calls made there are captured without a declaration. The identity is read on the thread that made the LLM call, before the log is queued, so it survives `async_logging` (the default).
|
data/docs/experiments.md
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# Experiments (A/B Tests)
|
|
2
|
+
|
|
3
|
+
Coolhand tracks A/B tests ("experiments"): ones it detects in your traffic, ones you register over
|
|
4
|
+
the API, and ones [Squishling](https://github.com/Coolhand-Labs/squishling) runs on live calls. Coolhand
|
|
5
|
+
scores each one nightly against its `primary_metric` and records a verdict. The gem covers three parts,
|
|
6
|
+
all on `Coolhand.experiment_service`:
|
|
7
|
+
|
|
8
|
+
- **Register, read and end** experiments with your **private** API key.
|
|
9
|
+
- **The experiment service**: sends Squishling's registrations, exposures and endings in batches with
|
|
10
|
+
the ingest (public) key, and checks whether an experiment should still run (`experiment_status`).
|
|
11
|
+
- **Experiment tags** on captured logs, so an arm can be scored on the calls you tag with it.
|
|
12
|
+
|
|
13
|
+
These need a Coolhand server with the experiment events API. Against an older one, the events are
|
|
14
|
+
dropped (`404`) and `experiment_status` returns `nil` with the ingest key.
|
|
15
|
+
|
|
16
|
+
## Register, read and end (private API key)
|
|
17
|
+
|
|
18
|
+
```ruby
|
|
19
|
+
experiments = Coolhand.experiment_service
|
|
20
|
+
|
|
21
|
+
experiment = experiments.register_experiment(
|
|
22
|
+
key: "checkout-copy",
|
|
23
|
+
name: "Shorter checkout copy",
|
|
24
|
+
hypothesis: "Shorter copy gets better feedback",
|
|
25
|
+
primary_metric: "feedback",
|
|
26
|
+
evaluate_at: Time.utc(2026, 12, 21),
|
|
27
|
+
arms: [
|
|
28
|
+
{ key: "control", role: "champion", template_id: "tmpl_hashid" },
|
|
29
|
+
{ key: "short", role: "challenger" } # scored on the logs you tag with it
|
|
30
|
+
]
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
result = experiments.list_experiments(status: "running", per: 50)
|
|
34
|
+
result.experiments # => [{ id:, key:, name:, status:, arms: [...], ... }]
|
|
35
|
+
result.pagination # => #<struct Coolhand::Pagination current_page=1, ...>
|
|
36
|
+
|
|
37
|
+
experiments.get_experiment(experiment[:id]) # by hashid
|
|
38
|
+
experiments.get_experiment_by_key("checkout-copy") # by your key
|
|
39
|
+
experiments.update_experiment(experiment[:id], status: "concluded")
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
| Method | Endpoint | Notes |
|
|
43
|
+
|---|---|---|
|
|
44
|
+
| `list_experiments(status:, origin:, kind:, workload_id:, page:, per:)` | `GET /api/v2/experiments` | All filters optional. `status`: `running`, `concluded`, `cancelled`. `origin`: `detected`, `bakeoff`, `api`, `admin`, `squishling`. `kind`: `model`, `temperature`, `provider`, `mixed`, `prompt`, `bakeoff`, `custom`. `workload_id` is a hashid. `per` is at most 100 (default 25). Returns an `ExperimentListResult` (`experiments`, `pagination`); pagination is read from the `X-Page`, `X-Per-Page`, `X-Total-Count` and `X-Total-Pages` headers. |
|
|
45
|
+
| `get_experiment(id)` | `GET /api/v2/experiments/{id}` | Adds `result` (the last evaluation: `window`, `metrics`) and `revisions` to the list fields. |
|
|
46
|
+
| `get_experiment_by_key(key)` | `GET /api/v2/experiments/by_key/{key}` | Each `/`-separated part of the key is escaped on its own (`TicketTriage#call/x?` becomes `TicketTriage%23call/x%3F`). A key with an empty, `.` or `..` part (`a/`, `a//b`, `a/../b`) can't be put in that path, so it raises `Coolhand::Error` before any request; read it by id instead. With the public (ingest) key it answers only for experiments Squishling reported, with the status fields alone (see [Should it still run?](#should-it-still-run)), and `404` for any other key. |
|
|
47
|
+
| `register_experiment(key:, name:, evaluate_at:, arms:, hypothesis:, kind:, primary_metric:, started_at:, workload_id:)` | `POST /api/v2/experiments` | 2-10 `arms`, exactly one with `role: "champion"`. Each arm is a Hash: `key` and `role` (`champion`/`challenger`), and optionally `name`, `template_id`, `template_external_key`. Returns the experiment (`201`). |
|
|
48
|
+
| `update_experiment(id, name:, hypothesis:, primary_metric:, evaluate_at:, status:)` | `PATCH /api/v2/experiments/{id}` | Sends only the fields you give. `status: "concluded"` or `"cancelled"` ends a running test; an ended test can't be reopened (`422`). Returns the experiment. |
|
|
49
|
+
|
|
50
|
+
`evaluate_at` and `started_at` take a `Time`, `DateTime`, `Date` or an ISO 8601 String; times are sent in
|
|
51
|
+
UTC. Anything else raises `ArgumentError` before the request.
|
|
52
|
+
|
|
53
|
+
Rows and bodies are plain Symbol-keyed Hashes with the API's field names: `id`, `key`, `name`,
|
|
54
|
+
`hypothesis`, `kind`, `origin`, `status`, `primary_metric`, `workload_id`, `started_at`, `evaluate_at`,
|
|
55
|
+
`ended_at`, `evaluated_at`, `verdict` (`winner`, `equivalent`, `inconclusive` or `nil`),
|
|
56
|
+
`recommended_arm_key` and `arms`. Each arm has `key`, `name`, `role`, `arm_type` (`template`,
|
|
57
|
+
`metadata_tag`, `bakeoff_champion`, `bakeoff_challenger`), `template_id` and `declared`. Timestamps are
|
|
58
|
+
ISO 8601 UTC strings.
|
|
59
|
+
|
|
60
|
+
Like the gem's other read methods, these raise: `Coolhand::HttpError` (with `status` and the raw `body`)
|
|
61
|
+
for a non-2xx response, and `Coolhand::Error` for a network failure, a missing API key or a body that
|
|
62
|
+
isn't JSON.
|
|
63
|
+
|
|
64
|
+
| Status | When |
|
|
65
|
+
|---|---|
|
|
66
|
+
| `401` | Missing or invalid key, or the public key (except `get_experiment_by_key`, below) |
|
|
67
|
+
| `404` | Unknown id or key, or another client's |
|
|
68
|
+
| `422` | An unknown filter value, an invalid body (`{ "errors": { "field": ["message"] } }`), or reopening an ended test |
|
|
69
|
+
|
|
70
|
+
An arm registered without a template is scored on tagged logs: tag its calls with the arm's
|
|
71
|
+
`declared.experiment` value (on the arm in the response), as described under
|
|
72
|
+
[Experiment tags](#experiment-tags-on-captured-logs).
|
|
73
|
+
|
|
74
|
+
## The experiment service (ingest key)
|
|
75
|
+
|
|
76
|
+
`register`, `expose` and `ended` take Squishling's experiment payloads and send them, unchanged, to
|
|
77
|
+
`POST /api/v2/experiment_events` with the key the gem is configured with. The ingest key is enough.
|
|
78
|
+
Squishling calls these itself once it finds `Coolhand.experiment_service`; you only need them to report
|
|
79
|
+
experiments of your own in the same format.
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
service = Coolhand.experiment_service
|
|
83
|
+
service.register(type: "experiment.registered", experiment_key: key, fingerprint: fingerprint, ...)
|
|
84
|
+
service.expose(type: "experiment.exposure", experiment_key: key, fingerprint: fingerprint, arm: "challenger", ...)
|
|
85
|
+
service.ended(type: "experiment.ended", experiment_key: key, fingerprint: fingerprint, ended_at: ended_at)
|
|
86
|
+
|
|
87
|
+
Coolhand.flush # optional: pending events are also sent at process exit
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- Each method serializes the event, queues it and returns `nil`; **nothing ever raises**. The
|
|
91
|
+
event's `type` must match the method (`experiment.registered`, `experiment.exposure`,
|
|
92
|
+
`experiment.ended`), or it is dropped with a warning. An event that can't be serialized as JSON, or
|
|
93
|
+
is larger than the server's 128KB per-event limit, is dropped with a warning too. Because events are
|
|
94
|
+
serialized when queued, changing your Hash afterwards doesn't change what is sent.
|
|
95
|
+
- Events go out from the same background worker as captured logs, taking turns with them one request
|
|
96
|
+
at a time, so they are covered by `Coolhand.flush` and sent at process exit. With
|
|
97
|
+
`config.async_logging = false` a call sends the events queued so far before it returns; a call made
|
|
98
|
+
while another thread is already sending leaves its event for the next call, `Coolhand.flush` or the
|
|
99
|
+
exit flush.
|
|
100
|
+
- Events queued while a request is in flight are sent together: up to 500 per request, at most 50 of
|
|
101
|
+
them registrations and endings (the rest wait for the next request, in order), and under the
|
|
102
|
+
server's 10MB body limit.
|
|
103
|
+
- A queued send that fails with a network error, `429` or `5xx` is retried once, after a second; inline
|
|
104
|
+
sends are not retried, as with captured logs. The server dedupes exposures and endings and upserts
|
|
105
|
+
registrations, so a resent batch is safe. Any other failure drops the batch and is logged, and (with
|
|
106
|
+
async logging on) the next `Coolhand.flush` returns `false`.
|
|
107
|
+
- The server answers with one result per event. Each `rejected` one is logged by its type, experiment
|
|
108
|
+
key and `call_id` (exposures) or `fingerprint` (registrations and endings), with the server's errors;
|
|
109
|
+
the rest of the batch is unaffected.
|
|
110
|
+
- At most 10,000 events are held. Past that, new events are dropped, with one warning until the queue
|
|
111
|
+
has drained.
|
|
112
|
+
- With `config.debug_mode`, batches are printed instead of sent.
|
|
113
|
+
|
|
114
|
+
Messages go through the gem's usual logging, so `config.silent = true` hides them. The event fields are
|
|
115
|
+
in the API reference (`Report Experiment Events`).
|
|
116
|
+
|
|
117
|
+
### Should it still run?
|
|
118
|
+
|
|
119
|
+
```ruby
|
|
120
|
+
status = Coolhand.experiment_service.experiment_status("TicketTriage#call/haiku_is_enough")
|
|
121
|
+
use_champion = status.nil? || status[:status] != "running"
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`experiment_status(experiment_key)` reads `GET /api/v2/experiments/by_key/{key}` and returns
|
|
125
|
+
|
|
126
|
+
```ruby
|
|
127
|
+
{ key:, status:, started_at:, evaluate_at:, ended_at:,
|
|
128
|
+
revisions: [{ fingerprint:, status:, traffic_percent:, registered_at:, ended_at: }] }
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
where `status` is `running`, `concluded` or `cancelled`, for the experiment and for each fingerprint.
|
|
132
|
+
It works with either key: with the ingest key the server answers only for experiments Squishling
|
|
133
|
+
reported, and with the private key the detail view is narrowed to the same fields. It returns `nil` for
|
|
134
|
+
an unknown key, any error or a timeout, and **never raises**. It waits at most 5 seconds each to connect, for
|
|
135
|
+
the TLS handshake and for the answer. Each answer is cached per key for 60 seconds (the server's `Cache-Control: max-age`);
|
|
136
|
+
`nil` for 5 seconds. Concurrent calls for one key share one request.
|
|
137
|
+
|
|
138
|
+
## Experiment tags on captured logs
|
|
139
|
+
|
|
140
|
+
Declare the arm a call ran under with `Coolhand.with_context`; every log captured inside is sent with
|
|
141
|
+
`declared.experiment = { key, arm, fingerprint }`, even with no workload or template declared.
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
Coolhand.with_context(experiment_key: "TicketTriage#call/haiku_is_enough", arm: "challenger",
|
|
145
|
+
fingerprint: "3f9a1c2b4d5e") do
|
|
146
|
+
client.messages.create(...)
|
|
147
|
+
end
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
See [Declared Workloads → Experiment tags](declared_workloads.md#experiment-tags) for the rules.
|
|
@@ -11,7 +11,8 @@ module Coolhand
|
|
|
11
11
|
# (cookie, set-cookie), and future/unknown providers using a
|
|
12
12
|
# similarly-named header. Shared with LoggerService so the two logging
|
|
13
13
|
# paths (interceptor + webhook forwarding) stay consistent.
|
|
14
|
-
SENSITIVE_HEADER_PATTERN =
|
|
14
|
+
SENSITIVE_HEADER_PATTERN =
|
|
15
|
+
/key|token|secret|signature|auth|passw|pwd|credential|bearer|jwt|session|cookie|sas|dpop|sig/i
|
|
15
16
|
|
|
16
17
|
# Rate-limit telemetry headers (OpenAI `x-ratelimit-remaining-tokens`, Anthropic
|
|
17
18
|
# `anthropic-ratelimit-input-tokens-reset`, ...) contain the word "token" but carry counts and
|
|
@@ -75,6 +76,8 @@ module Coolhand
|
|
|
75
76
|
|
|
76
77
|
# The value to log for one header: redacted by name, or with credentials scrubbed out of a URL it holds.
|
|
77
78
|
def sanitize_header_value(key_down, value)
|
|
79
|
+
# Net::HTTP sends a header value of any bytes; the regex checks below raise on an invalid one.
|
|
80
|
+
value = value.scrub unless value.valid_encoding?
|
|
78
81
|
if key_down == "authorization"
|
|
79
82
|
# Keep only the scheme: nothing after "Bearer " survives, whatever the value contains.
|
|
80
83
|
value.to_s.match?(/\ABearer\s+/i) ? "Bearer [REDACTED]" : "[REDACTED]"
|
|
@@ -99,8 +102,8 @@ module Coolhand
|
|
|
99
102
|
end
|
|
100
103
|
|
|
101
104
|
# An absolute URL inside a header value (stops at whitespace and the delimiters that separate
|
|
102
|
-
# URLs in Link and similar headers).
|
|
103
|
-
HEADER_URL_PATTERN = %r{[a-z][a-z0-9+.-]*://[^\s<>"
|
|
105
|
+
# URLs in Link and similar headers). A `;` does not end it: it can separate query parameters.
|
|
106
|
+
HEADER_URL_PATTERN = %r{[a-z][a-z0-9+.-]*://[^\s<>",]+}i
|
|
104
107
|
|
|
105
108
|
# Matches query param *names* that signal sensitive content, the same way
|
|
106
109
|
# SENSITIVE_HEADER_PATTERN does for headers — covers exact params this
|
|
@@ -18,6 +18,8 @@ module Coolhand
|
|
|
18
18
|
authorization authorizationtoken accesstoken refreshtoken idtoken
|
|
19
19
|
apikey clientsecret privatekey secretkey password
|
|
20
20
|
xapikey secret secretaccesskey awssecretaccesskey sessiontoken bearertoken
|
|
21
|
+
authtoken apitoken oauthtoken apisecret webhooksecret signingkey signingsecret subscriptionkey
|
|
22
|
+
passphrase pwd passwd credentials credential sastoken connectionstring jwt cookie xgoogapikey
|
|
21
23
|
].freeze
|
|
22
24
|
|
|
23
25
|
# Body keys whose *string* value is a URL that can carry credentials (MCP `server_url`, a
|
|
@@ -28,16 +28,22 @@ module Coolhand
|
|
|
28
28
|
# key by key: `{ id: x }` merged with `{ key: y }` would declare both, and the server prefers `id`.
|
|
29
29
|
# A template belongs to a workload, so a block that declares a workload without a template does
|
|
30
30
|
# not inherit the outer one; it would pair the new workload with a template from another.
|
|
31
|
-
|
|
31
|
+
# The experiment tag is replaced as a whole too, and an invalid one clears the outer tag rather than
|
|
32
|
+
# letting the block's calls count toward the outer arm.
|
|
33
|
+
def with(reporter: nil, workload: nil, template: nil, client_unique_id: nil, experiment_key: nil, arm: nil,
|
|
34
|
+
fingerprint: nil)
|
|
32
35
|
previous = current
|
|
36
|
+
experiment = experiment_tag(experiment_key, arm, fingerprint)
|
|
33
37
|
declared = {
|
|
34
38
|
reporter: normalize_reporter(reporter),
|
|
35
39
|
workload: normalize_part(:workload, workload, WORKLOAD_FIELDS),
|
|
36
40
|
template: normalize_part(:template, template, TEMPLATE_FIELDS),
|
|
37
|
-
client_unique_id: normalize_client_unique_id(client_unique_id)
|
|
41
|
+
client_unique_id: normalize_client_unique_id(client_unique_id),
|
|
42
|
+
experiment: (experiment unless experiment == INHERIT)
|
|
38
43
|
}.compact
|
|
39
44
|
inherited = previous || {}
|
|
40
45
|
inherited = inherited.except(:template) if declared.key?(:workload) && !declared.key?(:template)
|
|
46
|
+
inherited = inherited.except(:experiment) unless experiment == INHERIT
|
|
41
47
|
merged = inherited.merge(declared)
|
|
42
48
|
ensure_template_has_workload!(merged)
|
|
43
49
|
Thread.current[THREAD_KEY] = merged.empty? ? nil : merged.freeze
|
|
@@ -52,6 +58,44 @@ module Coolhand
|
|
|
52
58
|
reporter.to_s
|
|
53
59
|
end
|
|
54
60
|
|
|
61
|
+
# Mirrors the server's `DeclaredExperimentTag`, which drops a tag it can't take with a warning.
|
|
62
|
+
MAX_EXPERIMENT_KEY_LENGTH = 255
|
|
63
|
+
MAX_ARM_LENGTH = 100
|
|
64
|
+
EXPERIMENT_TAG_FORMAT = %r{\A[A-Za-z0-9][A-Za-z0-9_.:#/?!-]*\z}
|
|
65
|
+
MAX_FINGERPRINT_LENGTH = 64
|
|
66
|
+
FINGERPRINT_FORMAT = /\A[0-9a-f]{1,#{MAX_FINGERPRINT_LENGTH}}\z/
|
|
67
|
+
INHERIT = :inherit
|
|
68
|
+
@experiment_warning_mutex = Mutex.new
|
|
69
|
+
@warned_invalid_experiment = false
|
|
70
|
+
|
|
71
|
+
# `{ key:, arm:, fingerprint: }` (fingerprint only when given), INHERIT when none of the three is
|
|
72
|
+
# given, or nil for an invalid tag. A bad tag never raises: it must not break the caller's LLM
|
|
73
|
+
# call, and the warning is written once per process because apps wrap every call.
|
|
74
|
+
def experiment_tag(key, arm, fingerprint)
|
|
75
|
+
return INHERIT if key.nil? && arm.nil? && fingerprint.nil?
|
|
76
|
+
|
|
77
|
+
if valid_string?(key, MAX_EXPERIMENT_KEY_LENGTH, EXPERIMENT_TAG_FORMAT) &&
|
|
78
|
+
valid_string?(arm, MAX_ARM_LENGTH, EXPERIMENT_TAG_FORMAT) &&
|
|
79
|
+
(fingerprint.nil? || valid_string?(fingerprint, MAX_FINGERPRINT_LENGTH, FINGERPRINT_FORMAT))
|
|
80
|
+
return { key: key, arm: arm, fingerprint: fingerprint }.compact.transform_values { |v| v.dup.freeze }.freeze
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
warn_invalid_experiment
|
|
84
|
+
nil
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def warn_invalid_experiment
|
|
88
|
+
first = @experiment_warning_mutex.synchronize do
|
|
89
|
+
!@warned_invalid_experiment && (@warned_invalid_experiment = true)
|
|
90
|
+
end
|
|
91
|
+
return unless first
|
|
92
|
+
|
|
93
|
+
Coolhand.log "Ignoring experiment tag: it needs an experiment_key (at most #{MAX_EXPERIMENT_KEY_LENGTH} " \
|
|
94
|
+
"characters) and an arm (at most #{MAX_ARM_LENGTH}) made of letters, digits and _.:#/?!-, and " \
|
|
95
|
+
"an optional fingerprint of 1-#{MAX_FINGERPRINT_LENGTH} lowercase hex characters. Later invalid " \
|
|
96
|
+
"tags are dropped without a warning."
|
|
97
|
+
end
|
|
98
|
+
|
|
55
99
|
# The caller's own id for the next logged request(s), so feedback can find them by
|
|
56
100
|
# `create_feedback(client_unique_id:)`. Unlike a workload key, a bad value is dropped rather than
|
|
57
101
|
# raised: a correlation id must never break the caller's LLM call, and a value the server may
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
require_relative "api_service"
|
|
7
|
+
require_relative "log_queue"
|
|
8
|
+
|
|
9
|
+
module Coolhand
|
|
10
|
+
# Delivers the experiment service's events to `POST /api/v2/experiment_events`, with whatever key the
|
|
11
|
+
# gem is configured with (the ingest key is enough). Reached through {ExperimentService#register},
|
|
12
|
+
# {ExperimentService#expose} and {ExperimentService#ended}; see docs/experiments.md.
|
|
13
|
+
#
|
|
14
|
+
# Events are serialized on the caller's thread into a process-wide buffer, and one {LogQueue} job at a
|
|
15
|
+
# time drains it, a batch per job, so they are sent off the caller's thread and covered by
|
|
16
|
+
# `Coolhand.flush` and the exit flush. The buffer is separate from the LogQueue's because one job carries
|
|
17
|
+
# a whole batch.
|
|
18
|
+
class ExperimentEventService < ApiService
|
|
19
|
+
MAX_EVENTS_PER_BATCH = 500
|
|
20
|
+
# The endpoint rejects registrations and endings past this many in one request.
|
|
21
|
+
MAX_REGISTRATIONS_AND_ENDINGS_PER_BATCH = 50
|
|
22
|
+
MAX_QUEUED_EVENTS = 10_000
|
|
23
|
+
# The server rejects any single event larger than this.
|
|
24
|
+
MAX_EVENT_BYTES = 128 * 1024
|
|
25
|
+
# The server refuses an ingest-key body over 10MB with a 413; stay a little under it.
|
|
26
|
+
MAX_BATCH_BYTES = (10 * 1024 * 1024) - 1024
|
|
27
|
+
BATCH_ENVELOPE_BYTES = '{"events":[]}'.bytesize
|
|
28
|
+
RETRY_DELAY = 1
|
|
29
|
+
# Log delivery's retryable errors, widened by the ambiguous ones (a read timeout, a reset connection)
|
|
30
|
+
# it won't retry: the server dedupes exposures and endings and upserts registrations, so a resent
|
|
31
|
+
# batch is safe.
|
|
32
|
+
NETWORK_ERRORS = [
|
|
33
|
+
*PostDelivery::RETRYABLE_ERRORS, Net::ReadTimeout, Net::WriteTimeout, Errno::ECONNRESET, Errno::EPIPE,
|
|
34
|
+
Errno::ETIMEDOUT, Errno::EHOSTUNREACH, Errno::ENETUNREACH, EOFError, OpenSSL::SSL::SSLError
|
|
35
|
+
].freeze
|
|
36
|
+
REGISTERED = "experiment.registered"
|
|
37
|
+
EXPOSURE = "experiment.exposure"
|
|
38
|
+
ENDED = "experiment.ended"
|
|
39
|
+
|
|
40
|
+
# `label` names the event in a rejection warning, since the server reports only its index.
|
|
41
|
+
Event = Struct.new(:json, :bytes, :capped, :label)
|
|
42
|
+
|
|
43
|
+
# One request's events, in queue order. Registrations and endings past the per-request cap are held
|
|
44
|
+
# for the next request rather than sent to be rejected.
|
|
45
|
+
class Batch
|
|
46
|
+
attr_reader :events, :held
|
|
47
|
+
|
|
48
|
+
def initialize
|
|
49
|
+
@events = []
|
|
50
|
+
@held = []
|
|
51
|
+
@bytes = BATCH_ENVELOPE_BYTES
|
|
52
|
+
@capped = 0
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Takes the event into the batch or the held list; false, taking nothing, once the batch is full.
|
|
56
|
+
def offer(event)
|
|
57
|
+
return false if @events.size >= MAX_EVENTS_PER_BATCH
|
|
58
|
+
return hold(event) if event.capped && @capped >= MAX_REGISTRATIONS_AND_ENDINGS_PER_BATCH
|
|
59
|
+
return false if !@events.empty? && @bytes + event.bytes + 1 > MAX_BATCH_BYTES
|
|
60
|
+
|
|
61
|
+
@bytes += event.bytes + (@events.empty? ? 0 : 1)
|
|
62
|
+
@capped += 1 if event.capped
|
|
63
|
+
@events << event
|
|
64
|
+
true
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
private
|
|
68
|
+
|
|
69
|
+
def hold(event)
|
|
70
|
+
@held << event
|
|
71
|
+
true
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
@mutex = Mutex.new
|
|
76
|
+
@queue = []
|
|
77
|
+
@draining = false
|
|
78
|
+
@warned_full = false
|
|
79
|
+
@pid = Process.pid
|
|
80
|
+
|
|
81
|
+
class << self
|
|
82
|
+
# Queues the event (a Hash whose `type` must be `type`) and returns nil. Never raises.
|
|
83
|
+
def enqueue(type, payload)
|
|
84
|
+
event = build_event(type, payload)
|
|
85
|
+
submit_drain if event && schedule(event)
|
|
86
|
+
nil
|
|
87
|
+
rescue StandardError => e
|
|
88
|
+
Coolhand.log "⚠️ Dropped an #{type} event: #{e.class}: #{e.message}"
|
|
89
|
+
nil
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Testing-only: discard queued events.
|
|
93
|
+
def reset!
|
|
94
|
+
@mutex.synchronize { forget_queue }
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
private
|
|
98
|
+
|
|
99
|
+
def build_event(type, payload)
|
|
100
|
+
actual = payload.is_a?(Hash) ? payload[:type] || payload["type"] : nil
|
|
101
|
+
unless actual == type
|
|
102
|
+
Coolhand.log "⚠️ Dropped an experiment event: expected type #{type.inspect}, got #{actual.inspect}"
|
|
103
|
+
return nil
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Serialized now, so a later change to the caller's Hash isn't sent and an event that can't be
|
|
107
|
+
# serialized doesn't sink the batch it would have joined.
|
|
108
|
+
json = JSON.generate(payload)
|
|
109
|
+
if json.bytesize > MAX_EVENT_BYTES
|
|
110
|
+
Coolhand.log "⚠️ Dropped an #{type} event: it is larger than the server's 128KB event limit"
|
|
111
|
+
return nil
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
Event.new(json, json.bytesize, type != EXPOSURE, label(type, payload))
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def label(type, payload)
|
|
118
|
+
field = type == EXPOSURE ? :call_id : :fingerprint
|
|
119
|
+
key, id = [:experiment_key, field].map { |name| payload.key?(name) ? payload[name] : payload[name.to_s] }
|
|
120
|
+
"#{type} for #{key.to_s.inspect} (#{field} #{id})"
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# True when a drain job must be submitted for the event.
|
|
124
|
+
def schedule(event)
|
|
125
|
+
LogQueue.register_at_exit
|
|
126
|
+
@mutex.synchronize do
|
|
127
|
+
forget_inherited_queue
|
|
128
|
+
if @queue.size >= MAX_QUEUED_EVENTS
|
|
129
|
+
warn_full
|
|
130
|
+
next false
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
@queue << event
|
|
134
|
+
claim_drain
|
|
135
|
+
end
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# Run before every flush, so events a discarded or failed drain left behind are still sent.
|
|
139
|
+
def resume_drain
|
|
140
|
+
start = @mutex.synchronize do
|
|
141
|
+
forget_inherited_queue
|
|
142
|
+
claim_drain
|
|
143
|
+
end
|
|
144
|
+
submit_drain if start
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# The caller holds the mutex. True when the caller must submit the drain job.
|
|
148
|
+
def claim_drain
|
|
149
|
+
return false if @draining || @queue.empty?
|
|
150
|
+
|
|
151
|
+
@draining = true
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def warn_full
|
|
155
|
+
LogQueue.record_failure
|
|
156
|
+
return if @warned_full
|
|
157
|
+
|
|
158
|
+
@warned_full = true
|
|
159
|
+
Coolhand.log "⚠️ Experiment event queue is full (#{MAX_QUEUED_EVENTS}); dropping new events until it drains"
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def submit_drain(requeue: false)
|
|
163
|
+
LogQueue.submit(requeue: requeue, on_abandon: method(:drain_abandoned)) { drain }
|
|
164
|
+
rescue StandardError => e
|
|
165
|
+
drain_abandoned
|
|
166
|
+
Coolhand.log "⚠️ Couldn't schedule sending experiment events: #{e.class}: #{e.message}; they stay queued"
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# On a queue worker, sends one batch and, if events remain, requeues itself behind the log sends
|
|
170
|
+
# submitted meanwhile, so a long drain can't hold up the lane they share. One drain is queued or
|
|
171
|
+
# running at a time; whatever stops one early (an error, a discarded job) leaves the rest for the
|
|
172
|
+
# next event's drain or the next flush.
|
|
173
|
+
def drain
|
|
174
|
+
settled = false
|
|
175
|
+
if LogQueue.worker_thread?
|
|
176
|
+
batch = take_batch
|
|
177
|
+
new.deliver_batch(batch) if batch
|
|
178
|
+
else
|
|
179
|
+
drain_inline
|
|
180
|
+
end
|
|
181
|
+
settled = true
|
|
182
|
+
submit_drain(requeue: true) if batch && events_left?
|
|
183
|
+
ensure
|
|
184
|
+
drain_abandoned unless settled
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
# Run on the caller's thread (the queue is off), sends only as many events as were queued when it
|
|
188
|
+
# started, so other threads that keep queuing meanwhile can't hold the caller's thread indefinitely.
|
|
189
|
+
def drain_inline
|
|
190
|
+
budget = @mutex.synchronize { @queue.size }
|
|
191
|
+
while (batch = take_batch(more: budget.positive?))
|
|
192
|
+
new.deliver_batch(batch)
|
|
193
|
+
budget -= batch.size
|
|
194
|
+
end
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def drain_abandoned
|
|
198
|
+
@mutex.synchronize { @draining = false }
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
# True while events remain, keeping the drain claimed; otherwise ends it.
|
|
202
|
+
def events_left?
|
|
203
|
+
@mutex.synchronize do
|
|
204
|
+
next true unless @queue.empty?
|
|
205
|
+
|
|
206
|
+
@draining = false
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# In queue order, holding back registrations and endings past the per-request cap for the next
|
|
211
|
+
# request. Nil, and the drain over, once the buffer is empty or the caller wants no `more`.
|
|
212
|
+
def take_batch(more: true)
|
|
213
|
+
@mutex.synchronize do
|
|
214
|
+
if !more || @queue.empty?
|
|
215
|
+
@draining = false
|
|
216
|
+
next nil
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
batch, held, rest = split_batch
|
|
220
|
+
@queue = held + rest
|
|
221
|
+
@warned_full = false if @queue.empty?
|
|
222
|
+
batch
|
|
223
|
+
end
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def split_batch
|
|
227
|
+
batch = Batch.new
|
|
228
|
+
taken = @queue.index { |event| !batch.offer(event) } || @queue.size
|
|
229
|
+
[batch.events, batch.held, @queue.drop(taken)]
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# A forked child inherits the parent's events but not the worker that drains them.
|
|
233
|
+
def forget_inherited_queue
|
|
234
|
+
forget_queue if @pid != Process.pid
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
def forget_queue
|
|
238
|
+
@pid = Process.pid
|
|
239
|
+
@queue = []
|
|
240
|
+
@draining = false
|
|
241
|
+
@warned_full = false
|
|
242
|
+
end
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
LogQueue.before_flush { resume_drain }
|
|
246
|
+
|
|
247
|
+
def initialize
|
|
248
|
+
super("v2/experiment_events")
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
# @api private
|
|
252
|
+
# Sends one batch, retrying a queued send once on a network error, 429 or 5xx, and logs each
|
|
253
|
+
# rejected event. Never raises.
|
|
254
|
+
def deliver_batch(batch)
|
|
255
|
+
body = "{\"events\":[#{batch.map(&:json).join(',')}]}"
|
|
256
|
+
return log_debug_batch(body) if debug_mode?
|
|
257
|
+
return drop(batch, "an API key is required") unless Coolhand.required_field?(api_key)
|
|
258
|
+
|
|
259
|
+
result = post_with_retry(body)
|
|
260
|
+
rescue StandardError => e
|
|
261
|
+
drop(batch, e.is_a?(HttpError) ? "#{e.status} - #{format_error_body(e.body)}" : "#{e.class}: #{e.message}")
|
|
262
|
+
else
|
|
263
|
+
log_rejected(result, batch)
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
private
|
|
267
|
+
|
|
268
|
+
def post_with_retry(body)
|
|
269
|
+
retried = false
|
|
270
|
+
begin
|
|
271
|
+
post_once(*events_request(body))
|
|
272
|
+
rescue StandardError => e
|
|
273
|
+
raise if retried || !LogQueue.worker_thread? || !retryable?(e)
|
|
274
|
+
|
|
275
|
+
retried = true
|
|
276
|
+
log "⚠️ Experiment events request failed (#{e.message}); retrying in #{RETRY_DELAY}s"
|
|
277
|
+
sleep(RETRY_DELAY)
|
|
278
|
+
retry
|
|
279
|
+
end
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
def retryable?(error)
|
|
283
|
+
return error.status == 429 || error.status >= 500 if error.is_a?(HttpError)
|
|
284
|
+
|
|
285
|
+
NETWORK_ERRORS.any? { |klass| error.is_a?(klass) }
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
def events_request(body)
|
|
289
|
+
uri = URI.parse(api_endpoint)
|
|
290
|
+
request = Net::HTTP::Post.new(uri.request_uri)
|
|
291
|
+
apply_headers(request, create_request_options(nil))
|
|
292
|
+
request.body = body
|
|
293
|
+
[uri, request]
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
def drop(batch, reason)
|
|
297
|
+
LogQueue.record_failure if LogQueue.worker_thread?
|
|
298
|
+
log "❌ Dropped #{batch.size} experiment event(s): #{strip_control_characters(reason)}"
|
|
299
|
+
end
|
|
300
|
+
|
|
301
|
+
def log_debug_batch(body)
|
|
302
|
+
log "🛠️ Debug Mode - Experiment events prepared but not sent to API:"
|
|
303
|
+
log body
|
|
304
|
+
end
|
|
305
|
+
|
|
306
|
+
def log_rejected(result, batch)
|
|
307
|
+
rejected(result).each do |entry|
|
|
308
|
+
log "⚠️ #{sanitize_warning(event_name(entry[:index], batch))} was rejected: " \
|
|
309
|
+
"#{sanitize_warning(JSON.generate(entry[:errors]))}"
|
|
310
|
+
end
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
def rejected(result)
|
|
314
|
+
results = result.is_a?(Hash) ? result[:results] : nil
|
|
315
|
+
Array(results).select { |entry| entry.is_a?(Hash) && entry[:status] == "rejected" }
|
|
316
|
+
end
|
|
317
|
+
|
|
318
|
+
def event_name(index, batch)
|
|
319
|
+
event = batch[index] if index.is_a?(Integer) && index >= 0
|
|
320
|
+
event ? event.label : "experiment event #{index}"
|
|
321
|
+
end
|
|
322
|
+
end
|
|
323
|
+
end
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "api_service"
|
|
4
|
+
require_relative "pagination"
|
|
5
|
+
require_relative "read_query"
|
|
6
|
+
require_relative "write_requests"
|
|
7
|
+
require_relative "experiment_event_service"
|
|
8
|
+
require_relative "experiment_status_cache"
|
|
9
|
+
|
|
10
|
+
module Coolhand
|
|
11
|
+
# Rows stay plain Symbol-keyed Hashes so a field the server adds later is not dropped in transit.
|
|
12
|
+
ExperimentListResult = Struct.new(:experiments, :pagination, keyword_init: true)
|
|
13
|
+
|
|
14
|
+
# Coolhand's experiments (A/B tests). Squishling detects `Coolhand.experiment_service` and calls
|
|
15
|
+
# {#register}, {#expose}, {#ended} and {#experiment_status}, which work with the ingest key and never
|
|
16
|
+
# raise. {#list_experiments}, {#get_experiment}, {#get_experiment_by_key}, {#register_experiment} and
|
|
17
|
+
# {#update_experiment} need the client's **private** key and raise like the other read services. See
|
|
18
|
+
# docs/experiments.md.
|
|
19
|
+
class ExperimentService < ApiService
|
|
20
|
+
include ReadQuery
|
|
21
|
+
include WriteRequests
|
|
22
|
+
|
|
23
|
+
ERROR_NOUN = "Experiment"
|
|
24
|
+
BLANK_ID_MESSAGE = "id must be a non-empty experiment hashid"
|
|
25
|
+
# Callers wait on the status read before assigning a challenger, so a hung API must cost them
|
|
26
|
+
# seconds, not the 60-second read timeout; on nil they fall back to the champion.
|
|
27
|
+
STATUS_TIMEOUT = 5
|
|
28
|
+
STATUSES = %w[running concluded cancelled].freeze
|
|
29
|
+
REVISION_TIMES = %i[registered_at ended_at].freeze
|
|
30
|
+
|
|
31
|
+
def initialize
|
|
32
|
+
super("v2/experiments")
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# Filters, pagination and errors: docs/experiments.md.
|
|
36
|
+
def list_experiments(status: nil, origin: nil, kind: nil, workload_id: nil, page: nil, per: nil)
|
|
37
|
+
query = { status: status, origin: origin, kind: kind, workload_id: workload_id, page: page, per: per }.compact
|
|
38
|
+
fetch_list(query, ExperimentListResult, :experiments, page: page, per: per)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# By hashid. Adds `result` (the last evaluation) and `revisions` to the list fields.
|
|
42
|
+
def get_experiment(id)
|
|
43
|
+
get_json(resource_url(id, "get_experiment: #{BLANK_ID_MESSAGE}"), ERROR_NOUN)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# By the key it was registered with; the same body as {#get_experiment}. A key with an empty, `.` or
|
|
47
|
+
# `..` segment can't be put in the path and raises {Coolhand::Error} before any request.
|
|
48
|
+
def get_experiment_by_key(key)
|
|
49
|
+
get_json(by_key_url("get_experiment_by_key", key), ERROR_NOUN)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Registers an A/B test for Coolhand to score. `arms` is an Array of Hashes (`key`, `role`, and
|
|
53
|
+
# optionally `name`, `template_id`, `template_external_key`). Times may be Time, DateTime, Date or
|
|
54
|
+
# ISO 8601 Strings. Returns the experiment (detail view).
|
|
55
|
+
def register_experiment(key:, name:, evaluate_at:, arms:, hypothesis: nil, kind: nil, primary_metric: nil,
|
|
56
|
+
started_at: nil, workload_id: nil)
|
|
57
|
+
experiment = {
|
|
58
|
+
key: key, name: name, hypothesis: hypothesis, kind: kind, primary_metric: primary_metric,
|
|
59
|
+
started_at: time_param(:started_at, started_at), evaluate_at: time_param(:evaluate_at, evaluate_at),
|
|
60
|
+
workload_id: workload_id, arms: arms
|
|
61
|
+
}.compact
|
|
62
|
+
request_json(:post, api_endpoint, ERROR_NOUN, body: { experiment: experiment })
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Sends only the fields given. `status:` ends a running test (`"concluded"` or `"cancelled"`); an
|
|
66
|
+
# ended one can't be reopened (422). Returns the experiment (detail view).
|
|
67
|
+
def update_experiment(id, name: nil, hypothesis: nil, primary_metric: nil, evaluate_at: nil, status: nil)
|
|
68
|
+
url = resource_url(id, "update_experiment: #{BLANK_ID_MESSAGE}")
|
|
69
|
+
experiment = { name: name, hypothesis: hypothesis, primary_metric: primary_metric,
|
|
70
|
+
evaluate_at: time_param(:evaluate_at, evaluate_at), status: status }.compact
|
|
71
|
+
request_json(:patch, url, ERROR_NOUN, body: { experiment: experiment })
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Queues Squishling's `experiment.registered` payload and returns nil. Never raises. See
|
|
75
|
+
# docs/experiments.md for when it is sent.
|
|
76
|
+
def register(payload)
|
|
77
|
+
ExperimentEventService.enqueue(ExperimentEventService::REGISTERED, payload)
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Queues Squishling's `experiment.exposure` payload and returns nil. Never raises. See
|
|
81
|
+
# docs/experiments.md for when it is sent.
|
|
82
|
+
def expose(payload)
|
|
83
|
+
ExperimentEventService.enqueue(ExperimentEventService::EXPOSURE, payload)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Queues Squishling's `experiment.ended` payload and returns nil. Never raises. See
|
|
87
|
+
# docs/experiments.md for when it is sent.
|
|
88
|
+
def ended(payload)
|
|
89
|
+
ExperimentEventService.enqueue(ExperimentEventService::ENDED, payload)
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Whether the experiment, and each fingerprint, should still run: `{ key:, status:, started_at:,
|
|
93
|
+
# evaluate_at:, ended_at:, revisions: [{ fingerprint:, status:, traffic_percent:, registered_at:,
|
|
94
|
+
# ended_at: }] }`, or nil for an unknown key, any error or a timeout. Never raises. Works with the
|
|
95
|
+
# ingest key (which reads only experiments Squishling reported) or the private key. Cached per key.
|
|
96
|
+
def experiment_status(experiment_key)
|
|
97
|
+
cache_key = [base_url, api_key, experiment_key]
|
|
98
|
+
# The first caller's read takes at most a connect, a TLS handshake (Net::HTTP applies
|
|
99
|
+
# open_timeout to both) and a read, with no automatic retry (see ReadRequests#build_http), so
|
|
100
|
+
# the callers waiting on it give up a second after it would have.
|
|
101
|
+
ExperimentStatusCache.fetch(cache_key, wait: (STATUS_TIMEOUT * 3) + 1) { fetch_status(experiment_key) }
|
|
102
|
+
rescue StandardError
|
|
103
|
+
nil
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
private
|
|
107
|
+
|
|
108
|
+
def fetch_status(experiment_key)
|
|
109
|
+
body = get_json(by_key_url("experiment_status", experiment_key), ERROR_NOUN, timeout: STATUS_TIMEOUT)
|
|
110
|
+
status = status_info(body)
|
|
111
|
+
log "⚠️ experiment_status(#{experiment_key.inspect}): unexpected response shape" unless status
|
|
112
|
+
status
|
|
113
|
+
rescue HttpError => e
|
|
114
|
+
# A 404 is the normal answer for an experiment the server doesn't know (yet).
|
|
115
|
+
log "⚠️ experiment_status(#{experiment_key.inspect}) failed: #{e.message}" unless e.status == 404
|
|
116
|
+
nil
|
|
117
|
+
rescue StandardError => e
|
|
118
|
+
log "⚠️ experiment_status(#{experiment_key.inspect}) failed: #{e.message}"
|
|
119
|
+
nil
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Projects the ingest key's status body, or the private key's detail body, onto the status fields,
|
|
123
|
+
# so callers see one shape whichever key the gem holds. Nil if it is neither.
|
|
124
|
+
def status_info(raw)
|
|
125
|
+
return nil unless raw.is_a?(Hash) && raw[:key].is_a?(String) && STATUSES.include?(raw[:status])
|
|
126
|
+
return nil unless raw[:started_at].is_a?(String) && raw[:evaluate_at].is_a?(String)
|
|
127
|
+
|
|
128
|
+
revisions = Array(raw[:revisions]).map { |entry| revision_info(entry) }
|
|
129
|
+
return nil if revisions.include?(nil)
|
|
130
|
+
|
|
131
|
+
{ key: raw[:key], status: raw[:status], started_at: raw[:started_at], evaluate_at: raw[:evaluate_at],
|
|
132
|
+
ended_at: optional_string(raw[:ended_at]), revisions: revisions.freeze }.freeze
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def revision_info(raw)
|
|
136
|
+
return nil unless raw.is_a?(Hash) && raw[:fingerprint].is_a?(String) && STATUSES.include?(raw[:status])
|
|
137
|
+
|
|
138
|
+
traffic = raw[:traffic_percent]
|
|
139
|
+
{ fingerprint: raw[:fingerprint], status: raw[:status], traffic_percent: traffic.is_a?(Numeric) ? traffic : nil,
|
|
140
|
+
**REVISION_TIMES.to_h { |field| [field, optional_string(raw[field])] } }.freeze
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def optional_string(value)
|
|
144
|
+
value.is_a?(String) ? value : nil
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
end
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Coolhand
|
|
4
|
+
# The process-wide cache behind {ExperimentService#experiment_status}: an answer is kept for 60 seconds
|
|
5
|
+
# (the server's `Cache-Control: max-age=60`), a nil one (404, error, timeout) for 5, and concurrent
|
|
6
|
+
# callers for one key wait on the first caller's request instead of sending their own.
|
|
7
|
+
module ExperimentStatusCache
|
|
8
|
+
SUCCESS_TTL = 60
|
|
9
|
+
# Long enough to spare the API a request per caller, short enough that a blip, or an experiment this
|
|
10
|
+
# process has just registered, isn't reported unknown for a minute.
|
|
11
|
+
FAILURE_TTL = 5
|
|
12
|
+
|
|
13
|
+
Entry = Struct.new(:value, :expires_at, :done)
|
|
14
|
+
|
|
15
|
+
@mutex = Mutex.new
|
|
16
|
+
@settled = ConditionVariable.new
|
|
17
|
+
@entries = {}
|
|
18
|
+
@pid = Process.pid
|
|
19
|
+
|
|
20
|
+
class << self
|
|
21
|
+
# The cached value for `key`, or the block's (which must not raise), cached. A caller waiting on
|
|
22
|
+
# another's request gets nil once `wait` seconds pass.
|
|
23
|
+
def fetch(key, wait:)
|
|
24
|
+
entry, owner = claim(key)
|
|
25
|
+
return entry.value if entry.done
|
|
26
|
+
return await(entry, wait) unless owner
|
|
27
|
+
|
|
28
|
+
value = nil
|
|
29
|
+
begin
|
|
30
|
+
value = yield
|
|
31
|
+
ensure
|
|
32
|
+
settle(entry, value)
|
|
33
|
+
end
|
|
34
|
+
value
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Testing-only: forget every answer.
|
|
38
|
+
def reset!
|
|
39
|
+
@mutex.synchronize { @entries.clear }
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
def claim(key)
|
|
45
|
+
@mutex.synchronize do
|
|
46
|
+
forget_inherited_entries
|
|
47
|
+
now = monotonic_now
|
|
48
|
+
entry = @entries[key]
|
|
49
|
+
next [entry, false] if entry && (!entry.done || entry.expires_at > now)
|
|
50
|
+
|
|
51
|
+
@entries.delete_if { |_, cached| cached.done && cached.expires_at <= now }
|
|
52
|
+
entry = Entry.new(nil, nil, false)
|
|
53
|
+
@entries[key] = entry
|
|
54
|
+
[entry, true]
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def settle(entry, value)
|
|
59
|
+
@mutex.synchronize do
|
|
60
|
+
entry.value = value
|
|
61
|
+
entry.expires_at = monotonic_now + (value.nil? ? FAILURE_TTL : SUCCESS_TTL)
|
|
62
|
+
entry.done = true
|
|
63
|
+
@settled.broadcast
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def await(entry, wait)
|
|
68
|
+
deadline = monotonic_now + wait
|
|
69
|
+
@mutex.synchronize do
|
|
70
|
+
loop do
|
|
71
|
+
return entry.value if entry.done
|
|
72
|
+
return nil unless LogQueue.wait_for(@settled, @mutex, deadline)
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# A forked child inherits entries whose request is still in flight in the parent.
|
|
78
|
+
def forget_inherited_entries
|
|
79
|
+
return if @pid == Process.pid
|
|
80
|
+
|
|
81
|
+
@pid = Process.pid
|
|
82
|
+
@entries.clear
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def monotonic_now
|
|
86
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
data/lib/coolhand/log_queue.rb
CHANGED
|
@@ -79,6 +79,22 @@ module Coolhand
|
|
|
79
79
|
end
|
|
80
80
|
end
|
|
81
81
|
|
|
82
|
+
# A job whose submitter must learn that it was discarded before it ran (queue full, reset).
|
|
83
|
+
class AbandonableJob
|
|
84
|
+
def initialize(job, on_abandon)
|
|
85
|
+
@job = job
|
|
86
|
+
@on_abandon = on_abandon
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def call
|
|
90
|
+
@job.call
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def abandon
|
|
94
|
+
@on_abandon.call
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
|
|
82
98
|
# The pending deliveries, keyed by client_unique_id (several logs may share an id), plus the
|
|
83
99
|
# most recent ids whose last send failed, so feedback arriving after the fact still sees it.
|
|
84
100
|
class Deliveries
|
|
@@ -275,16 +291,21 @@ module Coolhand
|
|
|
275
291
|
@failure_mutex = Mutex.new
|
|
276
292
|
@failures = 0
|
|
277
293
|
@failures_pid = Process.pid
|
|
294
|
+
@before_flush = []
|
|
278
295
|
|
|
279
296
|
class << self
|
|
280
297
|
# Queues the job on a background lane, or runs it inline (see the module comment). With a
|
|
281
298
|
# `client_unique_id`, the job's outcome is tracked for {await_delivery}: it counts as delivered
|
|
282
|
-
# when the block returns a non-nil value, and as failed when it returns nil or raises.
|
|
283
|
-
|
|
284
|
-
|
|
299
|
+
# when the block returns a non-nil value, and as failed when it returns nil or raises. `on_abandon`
|
|
300
|
+
# is called if the queued job is discarded before it runs. `requeue: true` lets a job running on a
|
|
301
|
+
# worker queue its continuation at the back of the lane, behind the jobs submitted meanwhile, instead
|
|
302
|
+
# of running it inline.
|
|
303
|
+
def submit(lane: :default, client_unique_id: nil, on_abandon: nil, requeue: false, &job)
|
|
304
|
+
return yield unless async? || (requeue && worker_thread?)
|
|
285
305
|
|
|
286
306
|
register_at_exit
|
|
287
307
|
job = DELIVERIES.track(client_unique_id, job) if client_unique_id
|
|
308
|
+
job = AbandonableJob.new(job, on_abandon) if on_abandon
|
|
288
309
|
enqueue_or_abandon(LANES.fetch(lane), job)
|
|
289
310
|
nil
|
|
290
311
|
end
|
|
@@ -309,10 +330,17 @@ module Coolhand
|
|
|
309
330
|
# flush; false means a timeout or a lost log. A job that finished is not a job that delivered.
|
|
310
331
|
def flush(timeout = DEFAULT_FLUSH_TIMEOUT)
|
|
311
332
|
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
|
|
333
|
+
@before_flush.each(&:call)
|
|
312
334
|
drained = LANES.values.map { |lane| lane.flush(deadline) }.all?
|
|
313
335
|
drained && take_failures.zero?
|
|
314
336
|
end
|
|
315
337
|
|
|
338
|
+
# Runs the hook at the start of every flush, the exit flush included, so work buffered outside the
|
|
339
|
+
# lanes can be queued before the wait. The hook must not raise.
|
|
340
|
+
def before_flush(&hook)
|
|
341
|
+
@before_flush << hook
|
|
342
|
+
end
|
|
343
|
+
|
|
316
344
|
# Called by a worker's send that gave up, so `flush` can report it.
|
|
317
345
|
def record_failure
|
|
318
346
|
@failure_mutex.synchronize do
|
|
@@ -336,6 +364,17 @@ module Coolhand
|
|
|
336
364
|
true
|
|
337
365
|
end
|
|
338
366
|
|
|
367
|
+
# Registers the exit flush, once per process. Also called by buffers outside the lanes, whose
|
|
368
|
+
# events an inline drain can leave for a later flush.
|
|
369
|
+
def register_at_exit
|
|
370
|
+
@at_exit_mutex.synchronize do
|
|
371
|
+
return if @at_exit_registered
|
|
372
|
+
|
|
373
|
+
@at_exit_registered = true
|
|
374
|
+
at_exit { flush }
|
|
375
|
+
end
|
|
376
|
+
end
|
|
377
|
+
|
|
339
378
|
# Testing-only: discard queued work and stop the workers.
|
|
340
379
|
def reset!
|
|
341
380
|
LANES.each_value(&:reset!)
|
|
@@ -371,15 +410,6 @@ module Coolhand
|
|
|
371
410
|
def async?
|
|
372
411
|
Coolhand.configuration.async_logging && !Coolhand.configuration.debug_mode && !worker_thread?
|
|
373
412
|
end
|
|
374
|
-
|
|
375
|
-
def register_at_exit
|
|
376
|
-
@at_exit_mutex.synchronize do
|
|
377
|
-
return if @at_exit_registered
|
|
378
|
-
|
|
379
|
-
@at_exit_registered = true
|
|
380
|
-
at_exit { flush }
|
|
381
|
-
end
|
|
382
|
-
end
|
|
383
413
|
end
|
|
384
414
|
end
|
|
385
415
|
end
|
|
@@ -50,9 +50,9 @@ module Coolhand
|
|
|
50
50
|
response_headers: options[:response_headers] && sanitize_headers(options[:response_headers]),
|
|
51
51
|
status_code: options[:status_code] || 200,
|
|
52
52
|
source: "#{source}_webhook"
|
|
53
|
-
}.merge(options
|
|
53
|
+
}.merge(passthrough_fields(options))
|
|
54
54
|
|
|
55
|
-
#
|
|
55
|
+
# Sent inline, on the caller's thread (it is not queued).
|
|
56
56
|
log_to_api(webhook_data)
|
|
57
57
|
end
|
|
58
58
|
|
|
@@ -66,6 +66,13 @@ module Coolhand
|
|
|
66
66
|
false
|
|
67
67
|
end
|
|
68
68
|
|
|
69
|
+
# The caller's own fields, sent along as given except that `metadata` is redacted like the bodies.
|
|
70
|
+
def passthrough_fields(options)
|
|
71
|
+
fields = options.slice(:metadata, :conversation_id, :agent_id)
|
|
72
|
+
fields[:metadata] = BodyRedactor.redact(fields[:metadata]) if fields.key?(:metadata)
|
|
73
|
+
fields
|
|
74
|
+
end
|
|
75
|
+
|
|
69
76
|
def build_webhook_url(source, event_type)
|
|
70
77
|
base = "webhook://#{source}"
|
|
71
78
|
event_type ? "#{base}/#{event_type}" : base
|
|
@@ -87,14 +94,20 @@ module Coolhand
|
|
|
87
94
|
# Convert Rails HTTP_ prefix headers
|
|
88
95
|
clean_key = key.to_s.gsub(/^HTTP_/, "").tr("_", "-").downcase
|
|
89
96
|
|
|
90
|
-
|
|
91
|
-
# paths treat the same header names as sensitive)
|
|
92
|
-
clean_value = BaseInterceptor.sensitive_header?(clean_key) ? "[REDACTED]" : value.to_s
|
|
93
|
-
clean_headers[clean_key] = clean_value
|
|
97
|
+
clean_headers[clean_key] = clean_header_value(clean_key, value)
|
|
94
98
|
end
|
|
95
99
|
clean_headers
|
|
96
100
|
end
|
|
97
101
|
|
|
102
|
+
# Redacts sensitive headers (shared with BaseInterceptor so both logging paths treat the same header
|
|
103
|
+
# names as sensitive). A URL-valued header (Referer, Origin, Location) can carry credentials in its
|
|
104
|
+
# query or userinfo, so the rest are scrubbed of those.
|
|
105
|
+
def clean_header_value(clean_key, value)
|
|
106
|
+
return "[REDACTED]" if BaseInterceptor.sensitive_header?(clean_key)
|
|
107
|
+
|
|
108
|
+
BaseInterceptor.sanitize_header_value(clean_key, value.to_s)
|
|
109
|
+
end
|
|
110
|
+
|
|
98
111
|
# Rails' request.headers#each yields the whole Rack env, not just headers. Drop the
|
|
99
112
|
# non-header entries (rack.session, action_dispatch.*, REQUEST_METHOD, QUERY_STRING, ...)
|
|
100
113
|
# so session/params data is never forwarded. Ordinary header names (including normalized
|
|
@@ -106,10 +106,11 @@ module Coolhand
|
|
|
106
106
|
parse_success_body(response.body)
|
|
107
107
|
end
|
|
108
108
|
|
|
109
|
-
# The server already accepted the request, so a blank, non-JSON
|
|
109
|
+
# The server already accepted the request, so a blank, non-JSON, `null` or non-object 2xx body (a 204, say) is
|
|
110
110
|
# still a delivery: reporting it as a failure would make a retrying caller store it twice.
|
|
111
111
|
def parse_success_body(body)
|
|
112
|
-
JSON.parse(body.to_s, symbolize_names: true)
|
|
112
|
+
parsed = JSON.parse(body.to_s, symbolize_names: true)
|
|
113
|
+
parsed.is_a?(Hash) ? parsed : {}
|
|
113
114
|
rescue JSON::ParserError
|
|
114
115
|
{}
|
|
115
116
|
end
|
|
@@ -24,18 +24,19 @@ module Coolhand
|
|
|
24
24
|
|
|
25
25
|
protected
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
# `timeout` bounds the connect and the wait for the answer, each.
|
|
28
|
+
def get_json(url, noun, timeout: READ_TIMEOUT)
|
|
29
|
+
body, = get_json_with_headers(url, noun, timeout: timeout)
|
|
29
30
|
body
|
|
30
31
|
end
|
|
31
32
|
|
|
32
33
|
# Also returns the response, for endpoints that carry pagination in headers rather than the body.
|
|
33
|
-
def get_json_with_headers(url, noun)
|
|
34
|
+
def get_json_with_headers(url, noun, timeout: READ_TIMEOUT)
|
|
34
35
|
if api_key_required? && !Coolhand.required_field?(api_key)
|
|
35
36
|
raise Error, "#{noun} request failed: an API key is required"
|
|
36
37
|
end
|
|
37
38
|
|
|
38
|
-
response = perform_get(url, noun)
|
|
39
|
+
response = perform_get(url, noun, timeout)
|
|
39
40
|
|
|
40
41
|
raise_http_error(response, noun) unless response.is_a?(Net::HTTPSuccess)
|
|
41
42
|
|
|
@@ -55,9 +56,9 @@ module Coolhand
|
|
|
55
56
|
|
|
56
57
|
private
|
|
57
58
|
|
|
58
|
-
def perform_get(url, noun)
|
|
59
|
+
def perform_get(url, noun, timeout)
|
|
59
60
|
uri = url.is_a?(URI::Generic) ? url : URI.parse(url.to_s)
|
|
60
|
-
http = build_http(uri)
|
|
61
|
+
http = build_http(uri, timeout)
|
|
61
62
|
|
|
62
63
|
request = Net::HTTP::Get.new(uri.request_uri)
|
|
63
64
|
headers = { "Accept" => "application/json" }
|
|
@@ -71,12 +72,15 @@ module Coolhand
|
|
|
71
72
|
raise Error, "#{noun} request failed: #{e.message}"
|
|
72
73
|
end
|
|
73
74
|
|
|
74
|
-
def build_http(uri)
|
|
75
|
+
def build_http(uri, timeout = READ_TIMEOUT)
|
|
75
76
|
http = Net::HTTP.new(uri.host, uri.port)
|
|
76
77
|
http.use_ssl = (uri.scheme == "https")
|
|
77
|
-
http.open_timeout = READ_OPEN_TIMEOUT
|
|
78
|
-
http.read_timeout =
|
|
78
|
+
http.open_timeout = [READ_OPEN_TIMEOUT, timeout].min
|
|
79
|
+
http.read_timeout = timeout
|
|
79
80
|
http.write_timeout = READ_WRITE_TIMEOUT
|
|
81
|
+
# A shortened timeout is a latency bound, which Net::HTTP's automatic retry of a GET after a read
|
|
82
|
+
# timeout would double.
|
|
83
|
+
http.max_retries = 0 if timeout < READ_TIMEOUT
|
|
80
84
|
http
|
|
81
85
|
end
|
|
82
86
|
|
data/lib/coolhand/version.rb
CHANGED
data/lib/coolhand.rb
CHANGED
|
@@ -29,6 +29,7 @@ require_relative "coolhand/workload_service"
|
|
|
29
29
|
require_relative "coolhand/savings_service"
|
|
30
30
|
require_relative "coolhand/help_center_service"
|
|
31
31
|
require_relative "coolhand/log_service"
|
|
32
|
+
require_relative "coolhand/experiment_service"
|
|
32
33
|
require_relative "coolhand/webhook_interceptor"
|
|
33
34
|
# Only when Rails is already loaded; the gem has no Rails dependency.
|
|
34
35
|
require_relative "coolhand/railtie" if defined?(Rails::Railtie)
|
|
@@ -100,22 +101,26 @@ module Coolhand
|
|
|
100
101
|
# `name:` (and `description:` on a workload). `client_unique_id:` is your own id (a non-blank String
|
|
101
102
|
# of at most 255 characters, no control or invisible characters) stamped on the logs captured in the block, so
|
|
102
103
|
# `FeedbackService#create_feedback(client_unique_id:)` can find them; an invalid one is ignored.
|
|
103
|
-
#
|
|
104
|
+
# `experiment_key:` and `arm:` (with an optional `fingerprint:`) tag the logs with the experiment arm
|
|
105
|
+
# they ran under; an invalid tag is dropped with a warning, never raised. Squishling detects these
|
|
106
|
+
# three by parameter name, so keep them. See docs/declared_workloads.md.
|
|
104
107
|
#
|
|
105
108
|
# Example:
|
|
106
109
|
# Coolhand.with_context(reporter: "squishling", workload: { key: "Parser#call" }) { client.chat(...) }
|
|
107
|
-
def with_context(reporter: nil, workload: nil, template: nil, client_unique_id: nil,
|
|
110
|
+
def with_context(reporter: nil, workload: nil, template: nil, client_unique_id: nil, experiment_key: nil,
|
|
111
|
+
arm: nil, fingerprint: nil, &block)
|
|
108
112
|
raise ArgumentError, "Coolhand.with_context requires a block" unless block
|
|
109
113
|
|
|
110
114
|
DeclaredContext.with(reporter: reporter, workload: workload, template: template,
|
|
111
|
-
client_unique_id: client_unique_id,
|
|
115
|
+
client_unique_id: client_unique_id, experiment_key: experiment_key, arm: arm, fingerprint: fingerprint,
|
|
116
|
+
&block)
|
|
112
117
|
end
|
|
113
118
|
|
|
114
|
-
# Blocks until log requests queued by async logging have been sent, or the
|
|
115
|
-
# seconds) elapses. Returns true if everything was sent, false on a timeout or if a log
|
|
116
|
-
# not delivered (a send that failed after retrying transient errors, a job
|
|
117
|
-
#
|
|
118
|
-
# Pending logs are also flushed automatically at process exit.
|
|
119
|
+
# Blocks until log requests and experiment events queued by async logging have been sent, or the
|
|
120
|
+
# timeout (in seconds) elapses. Returns true if everything was sent, false on a timeout or if a log
|
|
121
|
+
# or experiment event was not delivered (a send that failed after retrying transient errors, a job
|
|
122
|
+
# that raised, or one dropped from a full queue) since the previous flush that drained.
|
|
123
|
+
# Pending logs and events are also flushed automatically at process exit.
|
|
119
124
|
def flush(timeout: LogQueue::DEFAULT_FLUSH_TIMEOUT)
|
|
120
125
|
LogQueue.flush(timeout)
|
|
121
126
|
end
|
|
@@ -171,6 +176,15 @@ module Coolhand
|
|
|
171
176
|
LogService.new
|
|
172
177
|
end
|
|
173
178
|
|
|
179
|
+
# Creates a new ExperimentService, for experiments (A/B tests). `register`, `expose`, `ended` and
|
|
180
|
+
# `experiment_status` work with the ingest key and never raise; `list_experiments`, `get_experiment`,
|
|
181
|
+
# `get_experiment_by_key`, `register_experiment` and `update_experiment` need the private API key.
|
|
182
|
+
# Squishling detects this method, so it exists only because the server's experiment events endpoint
|
|
183
|
+
# does (see docs/experiments.md).
|
|
184
|
+
def experiment_service
|
|
185
|
+
ExperimentService.new
|
|
186
|
+
end
|
|
187
|
+
|
|
174
188
|
# Creates a new HelpCenterService, for reading the Coolhand help center. Needs no API key; a
|
|
175
189
|
# configured one is sent and lifts the anonymous rate limit.
|
|
176
190
|
def help_center_service
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: coolhand
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.14.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Michael Carroll
|
|
@@ -9,7 +9,7 @@ authors:
|
|
|
9
9
|
autorequire:
|
|
10
10
|
bindir: exe
|
|
11
11
|
cert_chain: []
|
|
12
|
-
date: 2026-
|
|
12
|
+
date: 2026-12-03 00:00:00.000000000 Z
|
|
13
13
|
dependencies:
|
|
14
14
|
- !ruby/object:Gem::Dependency
|
|
15
15
|
name: base64
|
|
@@ -49,6 +49,7 @@ files:
|
|
|
49
49
|
- docs/configuration.md
|
|
50
50
|
- docs/declared_workloads.md
|
|
51
51
|
- docs/elevenlabs.md
|
|
52
|
+
- docs/experiments.md
|
|
52
53
|
- docs/feedback-links.md
|
|
53
54
|
- docs/feedback.md
|
|
54
55
|
- docs/help-center.md
|
|
@@ -73,6 +74,9 @@ files:
|
|
|
73
74
|
- lib/coolhand/default_intercept_addresses.yml
|
|
74
75
|
- lib/coolhand/default_intercept_path_patterns.yml
|
|
75
76
|
- lib/coolhand/errors.rb
|
|
77
|
+
- lib/coolhand/experiment_event_service.rb
|
|
78
|
+
- lib/coolhand/experiment_service.rb
|
|
79
|
+
- lib/coolhand/experiment_status_cache.rb
|
|
76
80
|
- lib/coolhand/feedback_service.rb
|
|
77
81
|
- lib/coolhand/help_center_service.rb
|
|
78
82
|
- lib/coolhand/log_queue.rb
|