coolhand 0.10.0 → 0.11.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.
data/docs/log-search.md CHANGED
@@ -1,14 +1,15 @@
1
1
  # Reading Logs (Search + Get)
2
2
 
3
3
  `Coolhand::LogService` reads logs back out of Coolhand, with the per-log `cost` the dashboard shows.
4
- The write side, `Coolhand.logger_service`, is a different class. It wraps two read-only endpoints:
4
+ The write side, `Coolhand.logger_service`, is a different class. It wraps three read-only endpoints:
5
5
 
6
6
  | method | endpoint |
7
7
  |---|---|
8
8
  | `search_logs` | `GET /api/v2/llm_request_logs` |
9
9
  | `get_log` | `GET /api/v2/llm_request_logs/{id}` |
10
+ | `failure_summary` | `GET /api/v2/llm_request_logs/failure_summary` |
10
11
 
11
- Both require your **private** API key. The public key is write-only on this API and is rejected exactly
12
+ All three require your **private** API key. The public key is write-only on this API and is rejected exactly
12
13
  like an invalid one.
13
14
 
14
15
  ```ruby
@@ -38,6 +39,7 @@ keyword, and the `per_page` alias, since this gem only sends `per`.
38
39
  |---|---|---|
39
40
  | `template_id`, `workload_id` | String | Hashids. One that does not decode, or that belongs to another client, is a `422`. |
40
41
  | `system_prompt_contains`, `user_prompt_contains` | String | Case-insensitive substring. |
42
+ | `error_contains` | String | Case-insensitive substring of the failed request's error text. Pass a `failure_summary` `:error_pattern` to list the logs behind that pattern. |
41
43
  | `model`, `source_api`, `source_api_result`, `source_application` | String | Exact match. `source_api_result` is `success`, `failed`, `operational` or `unmatched`. |
42
44
  | `project_path` | String | Exact match against `metadata.project_path`. |
43
45
  | `unmatched_only` | Boolean | Only logs with no template. |
@@ -69,7 +71,7 @@ array, never wrapped. Rows are Symbol-keyed Hashes: `:id`, `:collector`, `:sourc
69
71
  `total_pages` are lower bounds the gem derives, not counts, and `has_next_page` is true when the page
70
72
  came back full. Pass `include_total: true` when you need real totals.
71
73
 
72
- ## `get_log(id, section: nil, max_chars: nil, search_query: nil, include_thinking: nil)`
74
+ ## `get_log(id, section: nil, max_chars: nil, search_query: nil, include_thinking: nil, include_turn_metrics: nil)`
73
75
 
74
76
  `id` is the log hashid. Returns the full log as a Symbol-keyed Hash: the list fields plus the prompts and
75
77
  `:output`, and:
@@ -81,9 +83,54 @@ came back full. Pass `include_total: true` when you need real totals.
81
83
  | `:cost_breakdown` | Hash or nil: `:total_cost`, `:input_cost`, `:output_cost`, `:cached_input_cost`, `:cache_creation_input_cost`, `:reasoning_output_cost` |
82
84
 
83
85
  `section` (`"full"`, `"beginning"`, `"end"`), `max_chars` and `search_query` bound or search the content;
84
- `include_thinking` adds `:thinking_response`. Truncation and search are reported back as `:truncated`,
85
- `:total_chars`, `:search_query` and `:matches`. Only directly-collected logs are fetchable; internally
86
- generated records are a `404`.
86
+ `include_thinking` adds `:thinking_response`, and `include_turn_metrics: true` adds `:turn_metrics`.
87
+ Truncation and search are reported back as `:truncated`, `:total_chars`, `:search_query` and `:matches`.
88
+ Only directly-collected logs are fetchable; internally generated records are a `404`.
89
+
90
+ `:turn_metrics` is the per-turn breakdown of a captured agent session: an Array with one Hash per user
91
+ message, `{ index, human, started_at, ended_at, assistant_requests, tool_calls, input_tokens,
92
+ output_tokens, cache_read_tokens, cache_creation_tokens }`. The timestamps and the four token counts
93
+ are nil when unknown. It is `nil` for a log that is not a captured session, and the key is absent
94
+ unless you ask for it. It holds no content, so it is still returned after the content scrub.
95
+
96
+ ## `failure_summary(days_back: nil)`
97
+
98
+ ```ruby
99
+ summary = Coolhand.log_service.failure_summary(days_back: 30)
100
+ summary[:error_breakdown].each { |p| puts "#{p[:category]} #{p[:count]} #{p[:error_pattern]}" }
101
+
102
+ # The logs behind the most frequent pattern
103
+ top = summary[:error_breakdown].first
104
+ Coolhand.log_service.search_logs(error_contains: top[:error_pattern]).logs if top
105
+ ```
106
+
107
+ Rolls this client's recent failed requests up by error pattern (error text and `source_api`) and by
108
+ template, and sorts each pattern into whose problem it is. Failures inside a confirmed provider outage
109
+ are left out and counted in `:provider_outage_excluded_count`. Only directly-collected logs whose content
110
+ has not been removed by retention are counted.
111
+
112
+ `days_back` is the lookback in days (server default 7, max 36500). It is sent only when given and not
113
+ checked here, so `0` or a negative number is a `422` from the server.
114
+
115
+ Returns the response as one Symbol-keyed Hash, not paginated:
116
+
117
+ | key | type |
118
+ |---|---|
119
+ | `:client_id`, `:client_name` | String |
120
+ | `:days_analyzed`, `:total_failed_count`, `:provider_outage_excluded_count` | Integer |
121
+ | `:error_breakdown` | Array of the 50 most frequent patterns (below) |
122
+ | `:by_template` | Array of `:template_id` (String or nil), `:template_name`, `:failed_count`, `:error_patterns`, `:example_log_ids`, `:example_log_urls` |
123
+ | `:actionable_summary` | Hash: `:client_fixable_count`, `:server_side_count` |
124
+
125
+ Each `:error_breakdown` item has `:error_pattern`, `:source_api` (String or nil), `:count`,
126
+ `:first_seen_at`, `:last_seen_at` (ISO8601 Strings), `:category`, `:example_error_details`,
127
+ `:example_log_ids` (up to 3) and `:example_log_urls`. `:category` is `"client_error"` (a 4xx the caller
128
+ can fix), `"rate_limit"` (429), `"server_error"` (5xx), `"provider_error"` (no HTTP status) or
129
+ `"relayed_upstream"` (an upstream vendor's account or key error surfaced through a relay).
130
+
131
+ The totals and `:actionable_summary` count every pattern, not just the 50 listed. The API definition
132
+ types each `:by_template` `:error_patterns` item only as an open object; today it is `:category`,
133
+ `:count`, `:error` and `:source_api`, and any other key is optional.
87
134
 
88
135
  ## Errors
89
136
 
@@ -95,7 +142,7 @@ The read methods raise where the write methods log and return `nil`. `Coolhand::
95
142
  | `401` | No API key, an invalid key, or the public key. |
96
143
  | `404` | `get_log` only: unknown id, another client's log, or an internally generated record. |
97
144
  | `422` | Bad `template_id`, `workload_id`, `days_back`, `since`, `until`, `min_cost`, `order` or `max_chars`. |
98
- | `504` | The search exceeded the statement timeout. Narrow the window and retry. |
145
+ | `504` | The search or summary exceeded the statement timeout. Narrow the window (for `failure_summary`, a smaller `days_back`) and retry. |
99
146
 
100
147
  `Coolhand::Error` covers no API key configured, a transport failure, a body that is not valid JSON, a
101
148
  non-array list body, and a blank `id` passed to `get_log`. An unsupported `since`/`until` type raises
data/docs/openai.md CHANGED
@@ -12,7 +12,7 @@ Requires Rails — `Coolhand::WebhookInterceptor` and `Coolhand::OpenAi::BatchRe
12
12
  - Include the interceptor in your controller: `include Coolhand::WebhookInterceptor`
13
13
  - Add the `before_action` to validate and populate the `@validator` payload: `before_action :intercept_batch_request, only: :openai`
14
14
  - Ensure you skip CSRF for the webhook endpoint: `skip_before_action :verify_authenticity_token`
15
- - Override the `webhook_secret` method to return your OpenAI webhook secret
15
+ - Override the `webhook_secret` method to return your OpenAI webhook secret. Define it under `private` so it can't be routed as an action
16
16
 
17
17
  `intercept_batch_request` already validates the webhook and, for `batch.completed`/`batch.failed`/`batch.expired`/`batch.cancelled` events, calls `Coolhand::OpenAi::BatchResultProcessor` — that part requires no code in your controller action. The batch's status is checked inline in the `before_action`, but for a completed batch the two JSONL file downloads and the one-request-log-per-item sends run on Coolhand's [background log thread](configuration.md#asynchronous-logging), so a large batch doesn't hold up your webhook response. (With `config.async_logging = false` this all runs inline, and a large batch can trip your webhook endpoint's timeout and OpenAI's retry behavior.) The example below shows a controller action doing additional, app-specific work on top of that (e.g. updating your own `BatchApiRequest` record and enqueuing your own background job), which is optional.
18
18
 
@@ -53,19 +53,68 @@ rescue StandardError => e
53
53
  head :internal_server_error
54
54
  end
55
55
 
56
+ private # keep helpers like this below your public actions
57
+
56
58
  def webhook_secret
57
59
  Rails.application.credentials.openai_webhook_secret
58
60
  end
59
61
  # ...existing code...
60
62
  ```
61
63
 
64
+ `intercept_batch_request`, `webhook_secret` and `process_event` are private in `Coolhand::WebhookInterceptor`, so Rails doesn't treat them as controller actions, and `before_action :intercept_batch_request` works with a private method. Code outside the controller can no longer call them directly (it gets `NoMethodError`); `super` from your own override still works.
65
+
66
+ If your controller re-defines `webhook_secret` or `process_event` as public, they are public methods again, but `Coolhand::WebhookInterceptor` still removes all three names from the controller's `action_methods`, so they stay unroutable. That also means these names are reserved: a controller action with one of those names would not be routable. Defining your overrides under `private` is still the recommended form.
67
+
68
+ ## What gets logged for a completed batch
69
+
70
+ Each batch item is logged with `source_api: "openai"` and the `model` from the item's request body (falling back to the response body). Batch input files use relative URLs such as `/v1/chat/completions`; these are logged as `https://api.openai.com/v1/chat/completions` (the host is not configurable, so Azure OpenAI or proxy batches are logged with that host too). The batch's `in_progress_at` and `completed_at` timestamps become each log's start and completion times; if OpenAI reports either as missing, the whole batch is skipped with an error in `Rails.logger` rather than logged with bogus times. If `completed_at` is earlier than `in_progress_at`, a warning is logged and `duration_ms` is clamped to 0.
71
+
72
+ Each item's request body and response body are capped separately by [`max_captured_body_bytes`](configuration.md#body-capture-limits): one over the limit is logged as a `{"_coolhand_capture_skipped" => "body_too_large", ...}` placeholder (the item itself is still logged, and `model` is still taken from the full request body). See [Body Capture Limits](configuration.md#body-capture-limits) for the other placeholders. When the OpenAI client returns a result file as a String or IO, it is read and parsed one JSONL line at a time; a client that returns the file already parsed (`ruby-openai` does) has loaded it in full before Coolhand sees it. A malformed line is skipped and counted in an error log, and the other lines are still processed.
73
+
74
+ The batch ID from the webhook payload and the batch's input/output file IDs are used in calls to the OpenAI API with your `OPENAI_API_KEY`, so they are format-checked first (`batch_...` and `file-...`/`file_...`, letters, digits, `_` and `-` only). An event or batch whose IDs don't match is ignored with an error in `Rails.logger`.
75
+
62
76
  ## Signature header and secret rotation
63
77
 
64
78
  The `webhook-signature` header may carry several space-separated signatures (`v1,sigA v1,sigB`), as senders produce while a webhook secret is being rotated. `Coolhand::OpenAi::WebhookValidator` accepts the request if any `v1,` entry matches your secret, comparing each in constant time and ignoring entries with any other version prefix. The timestamp and replay checks below still run, and only after a signature matches.
65
79
 
80
+ ## Local development and testing
81
+
82
+ Signature headers (`webhook-signature`, `webhook-timestamp`, `webhook-id`) are required whenever a webhook secret is configured, in every `Rails.env`, including `development` and `test`. A request missing any of them is rejected, so your controller responds with 401. Earlier versions let unsigned requests through in development and test, which meant an app running with `RAILS_ENV=development` on a reachable host accepted forged webhooks.
83
+
84
+ The same applies to a missing (`nil`) request body: with a secret configured it is rejected in every `Rails.env`, since there is nothing to verify the signature against. An empty-string body is not treated as missing; it goes through the normal signature check and passes only if it was actually signed.
85
+
86
+ Signature verification (and the missing-body check) is skipped, with a logged warning, only when no secret is configured at all, and only in `development` and `test`. Every other environment rejects the request.
87
+
88
+ If you post unsigned test payloads to a local app that has a secret set, pick one of these:
89
+
90
+ - **Sign the test payload** with the same secret:
91
+
92
+ ```ruby
93
+ require "openssl"
94
+ require "base64"
95
+ require "json"
96
+ require "securerandom"
97
+
98
+ # Same key handling as the validator: a `whsec_` secret is base64-decoded, anything else is used as-is.
99
+ secret = ENV.fetch("OPENAI_WEBHOOK_SECRET")
100
+ secret_bytes = secret.start_with?("whsec_") ? Base64.strict_decode64(secret.delete_prefix("whsec_")) : secret
101
+ id = "wh_local_#{SecureRandom.hex(4)}"
102
+ timestamp = Time.now.to_i.to_s
103
+ body = { type: "batch.completed", data: { id: "batch_123" } }.to_json
104
+ signature = Base64.strict_encode64(OpenSSL::HMAC.digest("sha256", secret_bytes, "#{id}.#{timestamp}.#{body}"))
105
+
106
+ # Send `body` with these headers:
107
+ # webhook-id: <id>
108
+ # webhook-timestamp: <timestamp>
109
+ # webhook-signature: v1,<signature>
110
+ ```
111
+
112
+ - **Leave the secret unset in development**, for example have `webhook_secret` return `nil` unless `Rails.env.production?`.
113
+ - **Replay a real delivery** to your local app through a tunnel.
114
+
66
115
  ## Replay protection
67
116
 
68
- `Coolhand::OpenAi::WebhookValidator` rejects requests whose `webhook-timestamp` is more than **300 seconds** away from the current time, and rejects a `webhook-id` it has already seen within that window — this prevents a captured request (from a log aggregator, APM trace, or proxy log) from being replayed to re-trigger `Coolhand::OpenAi::BatchResultProcessor`.
117
+ `Coolhand::OpenAi::WebhookValidator` rejects requests whose `webhook-timestamp` is more than **300 seconds** away from the current time, and rejects a `webhook-id` it has already seen within twice that window (a request dated at the edge of the tolerance stays fresh for up to two tolerances, so the id is remembered at least as long) — this prevents a captured request (from a log aggregator, APM trace, or proxy log) from being replayed to re-trigger `Coolhand::OpenAi::BatchResultProcessor`.
69
118
 
70
119
  Both are configurable:
71
120
 
@@ -76,7 +125,7 @@ Coolhand.configure do |config|
76
125
  end
77
126
  ```
78
127
 
79
- The default `webhook-id` dedup store is in-memory and per-process, so it only protects a single process — replays across multiple app processes/dynos within the tolerance window aren't caught by default. If you run more than one process, supply your own store via `config.webhook_id_store`; any object responding to `claim!(id, ttl_seconds)` works, e.g. one backed by `Rails.cache`. `claim!` must atomically check-and-record the id in one operation (not a separate read then write) — otherwise two requests racing on the same id can both "win" — so lean on your cache backend's compare-and-set primitive (`unless_exist:` below maps to Redis `SET NX` when using `RedisCacheStore`):
128
+ The default `webhook-id` dedup store is in-memory and per-process, so it only protects a single process — replays across multiple app processes/dynos within the replay-protection window aren't caught by default. If you run more than one process, supply your own store via `config.webhook_id_store`; any object responding to `claim!(id, ttl_seconds)` works (`ttl_seconds` is twice `webhook_replay_tolerance_seconds`), e.g. one backed by `Rails.cache`. `claim!` must atomically check-and-record the id in one operation (not a separate read then write) — otherwise two requests racing on the same id can both "win" — so lean on your cache backend's compare-and-set primitive (`unless_exist:` below maps to Redis `SET NX` when using `RedisCacheStore`):
80
129
 
81
130
  ```ruby
82
131
  class RailsCacheWebhookIdStore
@@ -92,4 +141,14 @@ Coolhand.configure do |config|
92
141
  end
93
142
  ```
94
143
 
95
- Note: the `webhook-id` is claimed as soon as the signature and timestamp are confirmed valid — before your controller's `process_event` runs. If something downstream fails before the batch is actually handled (e.g. an unexpectedly-shaped payload), a same-id retry within the tolerance window will be rejected as a replay rather than reprocessed.
144
+ Note: the `webhook-id` is claimed as soon as the signature and timestamp are confirmed valid — before your controller's `process_event` runs. If something downstream raises (e.g. an error in your own `process_event` override, or an unexpectedly-shaped payload), the interceptor releases the claim before responding, so OpenAI's retry of the same `webhook-id` is processed rather than rejected as a replay. (`Coolhand::OpenAi::BatchResultProcessor` rescues and logs its own errors, and does its heavy work in the background, so this mainly matters for exceptions raised in your own code.)
145
+
146
+ Releasing is optional for custom stores: if your store also responds to `release!(id)`, it is called to forget the claim; a store that only implements `claim!` behaves as before and keeps the id claimed for its TTL even after a failure. To opt in, add `release!` to the store above:
147
+
148
+ ```ruby
149
+ class RailsCacheWebhookIdStore
150
+ def release!(id)
151
+ Rails.cache.delete("coolhand:openai_webhook:#{id}")
152
+ end
153
+ end
154
+ ```
@@ -0,0 +1,85 @@
1
+ # Reading Step Templates (List + Get)
2
+
3
+ `Coolhand::StepTemplateService` reads the step templates Coolhand detects in captured agent sessions.
4
+ A `prompt_step` matches a user prompt such as a slash command; a `tool_step` matches tool usage. It
5
+ wraps two read-only endpoints; there are no write endpoints:
6
+
7
+ | method | endpoint |
8
+ |---|---|
9
+ | `list_step_templates` | `GET /api/v2/step_templates` |
10
+ | `get_step_template` | `GET /api/v2/step_templates/{id}` |
11
+
12
+ Both require your **private** API key; the public key returns `401`. The client is derived from the
13
+ key, so there is no `client_id` keyword.
14
+
15
+ ```ruby
16
+ require "coolhand"
17
+
18
+ Coolhand.configure do |config|
19
+ config.api_key = ENV.fetch("COOLHAND_PRIVATE_API_KEY")
20
+ end
21
+
22
+ steps = Coolhand.step_template_service
23
+
24
+ result = steps.list_step_templates(step_type: "prompt_step", include_metrics: true, page: 1)
25
+ result.step_templates.each { |step| puts "#{step[:name]} (#{step[:sessions_count]} sessions)" }
26
+
27
+ lean = steps.get_step_template(result.step_templates.first[:id], include_metrics: false)
28
+ ```
29
+
30
+ ## `list_step_templates(search: nil, step_type: nil, include_metrics: nil, page: nil, per: nil)`
31
+
32
+ | keyword | type | notes |
33
+ |---|---|---|
34
+ | `search` | String | Case-insensitive substring match on the name. |
35
+ | `step_type` | String | `"prompt_step"` or `"tool_step"`. Anything else is a `422` from the server. |
36
+ | `include_metrics` | Boolean | Adds a `:metrics` Hash per row. Off by default; when set the server caps `per` at 25, and `pagination.per_page` reports the size applied. |
37
+ | `page` | Integer | 1-based. |
38
+ | `per` | Integer | Default 25, max 100, both enforced server-side. |
39
+
40
+ Returns a `Coolhand::StepTemplateSearchResult` (`#step_templates`, `#pagination`), newest first. The
41
+ endpoint renders a bare array; `pagination` is a `Coolhand::Pagination` read from the `X-Page`,
42
+ `X-Per-Page`, `X-Total-Count` and `X-Total-Pages` response headers, the same as `search_templates`
43
+ and `search_logs`.
44
+
45
+ ## `get_step_template(id, include_metrics: nil)`
46
+
47
+ `id` is the Integer `:id` from the list (not a hashid). Anything that is not a positive Integer raises
48
+ `Coolhand::Error` before any request. Unlike the list, `:metrics` is included by default; pass
49
+ `include_metrics: false` to skip the metrics queries.
50
+
51
+ ## Fields
52
+
53
+ Rows are plain Symbol-keyed Hashes, handed back as the API rendered them. Every row has `:id`,
54
+ `:name`, `:step_type`, `:status`, `:user_turn_pattern` (nil-able), `:created_at`, `:updated_at`,
55
+ `:sessions_count` (distinct sessions it appeared in), `:occurrences_count` and `:last_seen_at`
56
+ (nil-able). `:metrics` is present only when requested, or by default on `get_step_template`:
57
+
58
+ | `:metrics` field | Meaning |
59
+ |---|---|
60
+ | `:total_runs` | Runs counted; excludes scrubbed prompt-step sessions. |
61
+ | `:tool_stats` | Array of `{ name:, pct_of_runs:, avg_per_run: }`, or nil when there is nothing to show. |
62
+ | `:turn_stats` | `{ avg:, median:, high:, single_turn_pct: }` (`single_turn_pct` nil-able), or nil. |
63
+ | `:efficiency` | `{ interactive:, automated:, all:, unavailable_runs: }`, or nil for tool steps and step templates with no runs. Each cohort is nil when it has no runs. |
64
+ | `:notes` | Array of plain-sentence explanations of each data gap that applies. |
65
+
66
+ A cohort is `{ runs:, avg_turns_after:, avg_tool_calls:, avg_requests:, token_runs:, tokens_available:,
67
+ median_tokens:, p90_tokens:, tokens_per_tool_call: }`. The last three are nil, and `tokens_available`
68
+ is `false`, when no run in the cohort has token data (expected today).
69
+
70
+ ## Errors
71
+
72
+ Both methods raise on failure, like the other read methods. A non-2xx response is a
73
+ `Coolhand::HttpError` whose `#status` holds the HTTP status:
74
+
75
+ | status | when |
76
+ |---|---|
77
+ | `401` | Missing, invalid or public API key. |
78
+ | `404` | `get_step_template` only: unknown id, a draft or failed step template, or another client's. |
79
+ | `422` | `list_step_templates` only: a `step_type` other than `prompt_step` / `tool_step`. |
80
+ | `504` | A query exceeded the statement timeout. Retryable: narrow with `search` or a smaller `per`. |
81
+
82
+ ## Turn metrics on a log
83
+
84
+ `Coolhand.log_service.get_log(id, include_turn_metrics: true)` adds `:turn_metrics` to the log; see
85
+ [Reading Logs](log-search.md).
data/docs/vertex.md CHANGED
@@ -19,6 +19,7 @@ require "coolhand/vertex/batch_result_processor"
19
19
  - Optionally pass `model:` to populate the logged `model` field. It falls back to a `"model"` key in `batch_info` if present, and is omitted from the payload entirely when neither is available. If the value (from either source) looks like a Vertex model resource path (`publishers/<publisher>/models/<id>` or `projects/<project>/locations/<location>/models/<id>`), it's normalized down to just the trailing id/version before being logged; any other string is sent as-is.
20
20
  - `batch_info["name"]` must be the exact Vertex job resource name (`projects/<project>/locations/<location>/batchPredictionJobs/<job-id>`), and `batch_info["startTime"]`/`["endTime"]` must be valid ISO 8601 timestamps — a batch with a missing or malformed resource name or timestamps is skipped entirely (logged as an error) rather than sent with a broken URL.
21
21
  - If `endTime` precedes `startTime` (e.g. clock skew), the batch is still logged — `duration_ms` is clamped to `0` and a warning is logged — rather than dropping the results.
22
+ - Each item's `"request"` and `"response"` are capped separately by [`max_captured_body_bytes`](configuration.md#body-capture-limits): one over the limit is logged as a `{"_coolhand_capture_skipped" => "body_too_large", ...}` placeholder. (See [Body Capture Limits](configuration.md#body-capture-limits) for the other placeholders.) The results array is supplied by your code, so it is already in memory; only what is sent to Coolhand is capped.
22
23
  - Each element of the `batch_results` array passed to `.call` must be a `Hash` with a `"request"` and/or `"response"` key (the request/response body to log for that item — either key alone is accepted). Any other shape is treated as malformed and skipped, with the skip counted in a `Rails.logger.warn` summary rather than raised.
23
24
 
24
25
  ## Minimal example
@@ -87,9 +87,10 @@ module Coolhand
87
87
  # Bound worst-case latency: with async_logging off this call happens inline in
88
88
  # the intercepted request's path (otherwise it ties up the background log
89
89
  # worker), so a slow/unreachable Coolhand backend must not hang for Ruby's
90
- # ~60s Net::HTTP defaults.
90
+ # ~60s Net::HTTP defaults (a stalled upload hits write_timeout).
91
91
  http.open_timeout = 5
92
92
  http.read_timeout = 5
93
+ http.write_timeout = 5
93
94
 
94
95
  request = Net::HTTP::Post.new(uri.request_uri)
95
96
  apply_headers(request, create_request_options(payload))
@@ -13,6 +13,28 @@ module Coolhand
13
13
  # paths (interceptor + webhook forwarding) stay consistent.
14
14
  SENSITIVE_HEADER_PATTERN = /key|token|secret|signature|auth|passw|credential|bearer|jwt|session|cookie/i
15
15
 
16
+ # Rate-limit telemetry headers (OpenAI `x-ratelimit-remaining-tokens`, Anthropic
17
+ # `anthropic-ratelimit-input-tokens-reset`, ...) contain the word "token" but carry counts and
18
+ # reset times, not credentials, so redacting them only loses useful data. The vocabulary after
19
+ # `ratelimit` is closed (a lookalike such as `x-ratelimit-api-key` stays redacted), and the
20
+ # optional vendor prefix captured in group 1 must itself be free of sensitive words (see
21
+ # `safe_header?`), so `secret-ratelimit-remaining` stays redacted too. Checked against the
22
+ # downcased header name.
23
+ SAFE_HEADER_PATTERN =
24
+ /\A((?:[a-z0-9]+-){0,2})rate-?limit(?:-(?:limit|remaining|reset|requests|tokens|input|output))+\z/
25
+
26
+ # True when a header name should be redacted. Shared with LoggerService so both logging paths
27
+ # make the same call.
28
+ def sensitive_header?(name)
29
+ down = name.to_s.downcase
30
+ down.match?(SENSITIVE_HEADER_PATTERN) && !safe_header?(down)
31
+ end
32
+
33
+ def safe_header?(down_name)
34
+ match = SAFE_HEADER_PATTERN.match(down_name)
35
+ !match.nil? && !match[1].match?(SENSITIVE_HEADER_PATTERN)
36
+ end
37
+
16
38
  def sanitize_headers(headers)
17
39
  return {} if headers.nil?
18
40
 
@@ -37,7 +59,7 @@ module Coolhand
37
59
  headers.each { |k, v| h[k.to_s] = normalize_header_value(v) }
38
60
  h
39
61
  else
40
- { "raw" => headers.to_s }
62
+ {} # fail closed: an unrecognised shape can't be checked header-by-header
41
63
  end
42
64
 
43
65
  raw ||= {} # in case to_hash raised and nothing was built
@@ -55,7 +77,7 @@ module Coolhand
55
77
  else
56
78
  "[REDACTED]"
57
79
  end
58
- elsif key_down.match?(SENSITIVE_HEADER_PATTERN)
80
+ elsif sensitive_header?(key_down)
59
81
  sanitized[k] = "[REDACTED]"
60
82
  end
61
83
  end
@@ -78,7 +100,39 @@ module Coolhand
78
100
  # credential params used by AWS (X-Amz-Signature, X-Amz-Credential,
79
101
  # X-Amz-Security-Token) and Google Cloud (X-Goog-Signature,
80
102
  # X-Goog-Credential) storage APIs.
81
- SENSITIVE_QUERY_PARAM_PATTERN = /key|token|secret|sig|credential|password|auth/i
103
+ SENSITIVE_QUERY_PARAM_PATTERN = Regexp.new(
104
+ %w[key token secret sig credential password auth jwt bearer session cookie passphrase ticket assertion].join("|"),
105
+ Regexp::IGNORECASE
106
+ )
107
+
108
+ # Param names that are sensitive but too short or generic to match as a substring without
109
+ # over-matching (`code` would hit `encoding`, `country_code`). Matched by whole name,
110
+ # case-insensitively: `code` (Azure Functions keys, OAuth authorization codes), `sas` (Azure
111
+ # SAS tokens), and `pwd`/`passwd`, which the `password` substring above does not cover.
112
+ SENSITIVE_QUERY_PARAM_EXACT_NAMES = %w[code sas pwd passwd pass sid otp].freeze
113
+
114
+ # Percent-encoded "[REDACTED]", the form the placeholder takes once inside a URL.
115
+ REDACTED_URL_VALUE = "%5BREDACTED%5D"
116
+
117
+ # A `;name=value` matrix parameter. In a path the value stops at the next path delimiter; in a
118
+ # query value "/" is legal inside a secret (base64), so the value runs to the next ";" or "&".
119
+ PATH_MATRIX_PARAM_PATTERN = %r{;([^/;?#=&]+)=([^/;?#&]*)}
120
+ QUERY_MATRIX_PARAM_PATTERN = /;([^;=&#]+)=([^;&#]*)/
121
+
122
+ def sensitive_query_param?(name)
123
+ decoded = begin
124
+ # scrub: a percent-escaped invalid byte (`%FF`) must not make the match below raise.
125
+ URI.decode_www_form_component(name).scrub
126
+ rescue ArgumentError
127
+ name.scrub
128
+ end
129
+ decoded.match?(SENSITIVE_QUERY_PARAM_PATTERN) || exact_sensitive_query_name?(decoded)
130
+ end
131
+
132
+ # Exact-name check that also sees through Rails/PHP bracket syntax: `code[]`, `auth[code]`.
133
+ def exact_sensitive_query_name?(decoded_name)
134
+ decoded_name.downcase.split(/[\[\]]+/).any? { |part| SENSITIVE_QUERY_PARAM_EXACT_NAMES.include?(part) }
135
+ end
82
136
 
83
137
  def sanitize_url(url)
84
138
  uri = URI.parse(url)
@@ -91,28 +145,57 @@ module Coolhand
91
145
  modified = true
92
146
  end
93
147
 
94
- if uri.query
95
- params = URI.decode_www_form(uri.query)
96
- redacted_query = false
97
- params.map! do |n, v|
98
- if n.match?(SENSITIVE_QUERY_PARAM_PATTERN)
99
- redacted_query = true
100
- [n, "[REDACTED]"]
101
- else
102
- [n, v]
103
- end
104
- end
105
- if redacted_query
106
- uri.query = URI.encode_www_form(params)
107
- modified = true
108
- end
148
+ path = uri.path && redact_matrix_params(uri.path, PATH_MATRIX_PARAM_PATTERN)
149
+ if path != uri.path
150
+ uri.path = path
151
+ modified = true
152
+ end
153
+
154
+ query = uri.query && redact_query(uri.query)
155
+ if query != uri.query
156
+ uri.query = query
157
+ modified = true
158
+ end
159
+
160
+ # A fragment never reaches a server, but a caller-supplied URL can carry one (OAuth
161
+ # implicit flow puts `access_token=...` there), so drop it as the fallback below does.
162
+ if uri.fragment
163
+ uri.fragment = nil
164
+ modified = true
109
165
  end
110
166
 
111
167
  modified ? uri.to_s : url
112
168
  rescue URI::InvalidURIError
113
169
  # Fail closed: an unparseable URL can't be checked param-by-param, so drop everything
114
170
  # that could carry a credential (userinfo, query, fragment) rather than pass it through.
115
- url.to_s.sub(%r{//[^/?#]*@}, "//REDACTED@").split(/[?#]/, 2).first
171
+ stripped = url.to_s.sub(%r{//[^/?#]*@}, "//REDACTED@").split(/[?#]/, 2).first
172
+ redact_matrix_params(stripped, PATH_MATRIX_PARAM_PATTERN)
173
+ end
174
+
175
+ def redact_matrix_params(text, pattern)
176
+ text.gsub(pattern) do |match|
177
+ sensitive_query_param?(Regexp.last_match(1)) ? ";#{Regexp.last_match(1)}=#{REDACTED_URL_VALUE}" : match
178
+ end
179
+ end
180
+
181
+ # Works on the raw query rather than decode_www_form so a bare segment (`?sk-abc123`) is not
182
+ # mistaken for an empty-valued param, and untouched segments pass through byte-for-byte.
183
+ def redact_query(query)
184
+ query.split("&", -1).map { |segment| redact_query_segment(segment) }.join("&")
185
+ end
186
+
187
+ def redact_query_segment(segment)
188
+ return segment if segment.empty?
189
+
190
+ # Matrix redaction first: in `x;code=S` the first "=" makes the "name" `x;code`, which would
191
+ # dodge the exact-name rule.
192
+ segment = redact_matrix_params(segment, QUERY_MATRIX_PARAM_PATTERN)
193
+ name, separator, = segment.partition("=")
194
+ # No "=": nothing says what this is, so a stray token could be a credential. Fail closed.
195
+ return REDACTED_URL_VALUE if separator.empty?
196
+ return "#{name}=#{REDACTED_URL_VALUE}" if sensitive_query_param?(name)
197
+
198
+ segment
116
199
  end
117
200
 
118
201
  # Key names inside an Azure OpenAI "On Your Data" data_sources/dataSources entry that carry
@@ -122,35 +205,49 @@ module Coolhand
122
205
  # (Elasticsearch) are caught — not just exact or snake_case-only names.
123
206
  SENSITIVE_BODY_KEY_PATTERN = /key|token|secret|passw|pwd|credential|bearer|jwt|connectionstring|signature/i
124
207
 
208
+ REDACTED = "[REDACTED]"
209
+
210
+ # Subtrees nested deeper than this are replaced wholesale rather than walked, so a pathological
211
+ # body can neither overflow the stack (SystemStackError is not a StandardError, so
212
+ # send_complete_request_log's rescue would not catch it) nor smuggle a credential past the walk.
213
+ MAX_BODY_DEPTH = 100
214
+
125
215
  def sanitize_body(body)
126
- return body unless body.is_a?(Hash)
216
+ BodyRedactor.redact(body)
217
+ end
127
218
 
128
- sanitized = body.dup
129
- sanitized.each_key do |key|
130
- next unless key.to_s.delete("_-").casecmp?("datasources")
219
+ def redact_sensitive_body_values(node, depth = 0)
220
+ return REDACTED if depth > MAX_BODY_DEPTH
131
221
 
132
- sanitized[key] = redact_sensitive_body_values(sanitized[key])
222
+ case node
223
+ when Hash then redact_sensitive_body_hash(node, depth)
224
+ when Array then node.map { |v| redact_sensitive_body_values(v, depth + 1) }
225
+ when String then redact_embedded_url_credentials(node)
226
+ else node
133
227
  end
134
- sanitized
135
228
  end
136
229
 
137
- def redact_sensitive_body_values(node)
138
- case node
139
- when Hash
140
- node.each_with_object({}) do |(k, v), acc|
141
- normalized = k.to_s.gsub(/[_\-\s]/, "").downcase
142
- acc[k] = normalized.match?(SENSITIVE_BODY_KEY_PATTERN) ? "[REDACTED]" : redact_sensitive_body_values(v)
143
- end
144
- when Array
145
- node.map { |v| redact_sensitive_body_values(v) }
146
- else
147
- node
230
+ def redact_sensitive_body_hash(hash, depth)
231
+ hash.each_with_object({}) do |(k, v), acc|
232
+ normalized = k.to_s.gsub(/[_\-\s]/, "").downcase
233
+ acc[k] = normalized.match?(SENSITIVE_BODY_KEY_PATTERN) ? REDACTED : redact_sensitive_body_values(v, depth + 1)
148
234
  end
149
235
  end
150
236
 
237
+ # A single whitespace-free absolute URL, e.g. an Azure `endpoint` of `https://u:PASS@h/?sas=...`.
238
+ # Only applied to data_sources config and to the exact URL-valued body keys in BodyRedactor
239
+ # (never free text), where a URL value can carry userinfo or a SAS/key query param itself.
240
+ EMBEDDED_URL_PATTERN = %r{\A[a-z][a-z0-9+.-]*://\S+\z}i
241
+
242
+ def redact_embedded_url_credentials(value)
243
+ # JSON.parse accepts invalid UTF-8, which would make the regexp raise and drop the whole log.
244
+ value = value.scrub unless value.valid_encoding?
245
+ value.match?(EMBEDDED_URL_PATTERN) ? sanitize_url(value) : value
246
+ end
247
+
151
248
  def send_complete_request_log(request_id:, method:, url:, request_headers:, request_body:, response_headers:,
152
249
  response_body:, status_code:, start_time:, end_time:, duration_ms:, is_streaming:, source_api: nil, model: nil,
153
- declared: nil)
250
+ declared: nil, stream_incomplete: false)
154
251
  raw_request = {
155
252
  id: request_id,
156
253
  timestamp: start_time.iso8601,
@@ -159,7 +256,7 @@ module Coolhand
159
256
  headers: sanitize_headers(request_headers),
160
257
  request_body: sanitize_body(request_body),
161
258
  response_headers: sanitize_headers(response_headers),
162
- response_body: response_body,
259
+ response_body: sanitize_body(response_body),
163
260
  status_code: status_code,
164
261
  duration_ms: duration_ms,
165
262
  completed_at: end_time.iso8601,
@@ -167,6 +264,7 @@ module Coolhand
167
264
  }
168
265
  raw_request[:source_api] = source_api if Coolhand.required_field?(source_api)
169
266
  raw_request[:model] = model if Coolhand.required_field?(model)
267
+ raw_request[:stream_incomplete] = true if stream_incomplete
170
268
 
171
269
  request_data = { raw_request: raw_request }
172
270
  request_data[:declared] = declared if declared && !declared.empty?
@@ -181,6 +279,9 @@ module Coolhand
181
279
 
182
280
  def parse_json(string)
183
281
  JSON.parse(string)
282
+ rescue JSON::NestingError
283
+ # Too deep to walk for redaction; logging the raw string would skip BodyRedactor entirely.
284
+ { "_coolhand_capture_skipped" => "nesting_too_deep" }
184
285
  rescue JSON::ParserError, TypeError
185
286
  string
186
287
  end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coolhand
4
+ # Applies max_captured_body_bytes to the request/response bodies of batch items, the same way
5
+ # NetHttpInterceptor does for live requests: an oversized body is replaced by the body_too_large
6
+ # marker so the log entry (and the queued job holding it) stays small.
7
+ module BatchBodyCap
8
+ module_function
9
+
10
+ # Re-serializing a parsed number can write more bytes than the source had (depending on the json
11
+ # version, "1e9" becomes "1000000000.0" and "7e22" becomes "7.0000000000000004e+22"). Counting
12
+ # the separators around them, a body grows by well under this factor.
13
+ SERIALIZED_GROWTH = 6
14
+
15
+ # Returns the body, or the marker when its JSON size is over the cap. `source_size` is the byte
16
+ # size of the JSON the body was parsed from, when the caller has it (e.g. a JSONL line): a body
17
+ # that small even after SERIALIZED_GROWTH is within the cap without serializing it to measure.
18
+ def cap(body, source_size: nil)
19
+ return body if body.nil? || helpers.capture_limit.nil?
20
+ return body if source_size && !helpers.over_capture_limit?(source_size * SERIALIZED_GROWTH)
21
+
22
+ size = JSON.generate(body).bytesize
23
+ helpers.over_capture_limit?(size) ? helpers.body_too_large_marker(nil, size) : body
24
+ rescue JSON::NestingError
25
+ helpers.skipped_capture_marker(nil, "nesting_too_deep")
26
+ rescue JSON::JSONError
27
+ # NaN/Infinity or invalid UTF-8: it can't be logged either, and must not fail the other
28
+ # items of the batch.
29
+ helpers.skipped_capture_marker(nil, "unserializable_body")
30
+ end
31
+
32
+ def helpers
33
+ NetHttpInterceptor::Helpers
34
+ end
35
+ end
36
+ end