Compute the prompt cache hit rate per model while ignoring unknown rows

EasySQL

Why it matters Cache hit rate is one of the first cost metrics for any LLM gateway, and logs with missing flags are common.

Prompt caching cuts LLM cost, so teams track the share of requests that hit the cache. Some old log rows did not record the flag at all, and those should not count as misses.

Write query() returning a SQLite SQL string. Table requests(id INTEGER, model TEXT, cache_hit INTEGER) where cache_hit is 1, 0 or NULL (unknown).

Return one row per model: (model, n_known, hit_rate) where n_known is the number of rows with a non-NULL cache_hit and hit_rate = ROUND(100.0 * hits / n_known, 1). If a model has no known rows, n_known is 0 and hit_rate is NULL. Order by model ascending.

Signaturedef query()

Example

model 'a' with 1, 0, NULL, 1 and model 'b' with NULL give [('a', 3, 66.7), ('b', 0, None)].

Understand the idea

Aggregate functions in SQL quietly skip NULL. SUM, AVG, MIN, MAX and COUNT(col) all ignore NULL values; only COUNT(*) counts every row. This is useful when NULL means 'not recorded'.

Worked example for model a with flags 1, 0, NULL, 1: COUNT(*) = 4, COUNT(cache_hit) = 3, SUM(cache_hit) = 2. Hit rate = 100 * 2 / 3 = 66.7 percent. Dividing by 4 would give 50 percent, which wrongly counts the unknown row as a miss.

Rule: rate = 100.0 * SUM(flag) / NULLIF(COUNT(flag), 0). Write 100.0, not 100, so SQLite does real division instead of integer division.

LLM gateways report cache hit rate, tool call success rate and refusal rate this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: example_run1(query())
  • Sample 2: unknown rows in the middle_run2(query())
  • Test 3: all misses_run3(query())