Fix Summary Metrics That Ignore Active Filters
System DesignModel answerLast updated
Diagnose and fix an API endpoint where row results respect filters but the computed summary still reflects the full unfiltered dataset.
Fix Summary Metrics That Ignore Active Filters
A dashboard endpoint accepts filter parameters and returns two things: a list of matching rows and a summary block (totals, averages, counts). Users have noticed the rows respect whatever filters they apply, but the summary numbers always reflect the full dataset as if no filters were active.
A stripped-down version of the endpoint logic looks like this:
rows = repository.load_rows()
metrics = summarize(rows)
rows = apply_filters(rows, request.filters)
return {"rows": rows, "metrics": metrics}
Your job has three parts:
- Diagnose — Identify the exact defect and explain why it produces the observed symptom.
- Fix — Propose the smallest safe correction. Address the additional wrinkle that real endpoints typically apply pagination after filtering; the summary must cover all matched rows, not just the current page.
- Test — Design tests at both the unit level and the endpoint level that would catch this class of bug if it were reintroduced.
Context and constraints
summarizeproduces correct output for whatever rows it receives; the function itself is not broken.- Filters determine which rows should contribute to the summary. The summary is not intended to be a global/unfiltered figure.
- The shape of the API response must stay the same — callers expect both
rowsandmetricsin the same payload. - Authorization and tenant isolation may be enforced separately from user-facing filters; your fix must not accidentally bypass those controls.
- You are working in an unfamiliar Python web framework, and the frontend that surfaces the numbers is JavaScript. Describe how you would trace the bug end-to-end under those conditions.
Clarifying questions worth raising
- Are all summary values expected to reflect the filtered population, or do some fields intentionally show global figures?
- Is authorization/tenant scoping handled as a filter in
apply_filters, or is it enforced earlier in the stack beforeload_rowsis called? - Should the summary describe every row that matches the filters, or only the rows on the current page?
- Can filtering be pushed into the storage query rather than done in Python, and what consistency guarantees exist between the two result sets?
Hints
Hint 1
Start by tracing the data lineage of the wrong number backward from what the user sees: browser → network response → endpoint logic → data layer. Determine the earliest point where the filtered and unfiltered populations diverge.
Hint 2
Write a test fixture where the filtered and unfiltered summaries are necessarily different — e.g., two rows where one is excluded by the filter and contributes a non-zero amount to the aggregate. If your fix is correct the test will fail before and pass after.
Hint 3
Pagination is a separate concern from filtering. Make sure your fix computes the summary over all matched rows first, then slices the page, rather than computing the summary over only the page that happens to be returned.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Diagnosis
The defect is a data-lineage ordering error. summarize is called on the full result of load_rows() before apply_filters has had any chance to narrow the population. The filtered row list is computed afterward and returned correctly, but the metrics were already locked in against the wrong input. The summary and the rows are computed from different populations even though they travel together in one response.
This is easy to miss in review because both steps are present and individually correct — apply_filters does filter, summarize does summarize — the problem is purely sequencing.
Minimal Fix
Move summarize to run after apply_filters, and keep pagination (if any) after both:
rows = repository.load_rows()
rows = apply_filters(rows, request.filters)
metrics = summarize(rows) # now operates on the filtered population
page = paginate(rows, request.page)
return {"rows": page, "metrics": metrics}
Three ordering rules fall out of this:
- Authorization / tenant scoping — must happen first, either inside
load_rowsor as the very first transformation. Never let user-supplied filters run before security controls. - Semantic filters — run next, narrowing the authorized set to what the user actually asked for.
- Summary — computed over the full filtered+authorized population.
- Pagination — applied last, slicing the page for display only.
The response contract is unchanged: rows and metrics are still both present.
Tracing the Bug in an Unfamiliar Stack
When the frontend is JavaScript and the backend is a Python framework you haven't used before, work from outside in:
- Browser DevTools → Network tab. Capture the actual JSON response. Confirm whether
metricsin the payload is wrong or whether the frontend is displaying it incorrectly. This determines whether you own the fix at all. - Reproduce with a direct HTTP request.
curlor a tool like HTTPie lets you test the endpoint with and without filters and compare raw responses, eliminating any frontend transformation as a variable. - Find the route handler. Most Python frameworks (Flask, Django, FastAPI, etc.) have a URL routing table. Search the project for the path string (e.g.,
/api/metrics) to land on the handler quickly rather than reading the whole codebase. - Trace
metricsthrough the handler. Once you find wheremetricsis assembled, read backward: where does the input tosummarizecome from, and has filtering happened yet at that point? - Add a temporary log. Print
len(rows)before and afterapply_filters. If the counts differ and the metrics were computed before the drop, you have confirmed the bug without needing to understand the rest of the framework.
Tests
Unit test — ordering contract
def test_metrics_reflect_filtered_rows_not_full_set():
all_rows = [{"value": 10}, {"value": 90}] # total = 100
filters = FilterSpec(min_value=50)
# simulate the buggy order
metrics_buggy = summarize(all_rows)
filtered = apply_filters(all_rows, filters)
# simulate the correct order
metrics_correct = summarize(filtered)
assert metrics_correct["total"] == 90 # only the row that passed
assert metrics_buggy["total"] == 100 # proves the test is sensitive
The fixture is constructed so filtered and unfiltered results are necessarily different. If someone reintroduces the ordering bug, metrics_correct will equal 100 and the assertion will fail immediately.
Endpoint regression test
def test_endpoint_metrics_match_filtered_rows(client):
seed_rows([{"value": 10, "category": "A"},
{"value": 90, "category": "B"}])
response = client.get("/api/metrics?category=B")
data = response.json()
assert len(data["rows"]) == 1
assert data["metrics"]["total"] == 90 # not 100
This test covers the full request cycle so it catches bugs in filter wiring, not just in the pure functions.
Pagination-specific test
def test_metrics_cover_all_matched_rows_not_just_page(client):
seed_rows([{"value": v, "category": "A"} for v in range(1, 6)]) # 5 rows, total 15
response = client.get("/api/metrics?category=A&page=1&page_size=2")
data = response.json()
assert len(data["rows"]) == 2 # only one page returned
assert data["metrics"]["total"] == 15 # but metrics cover all 5
Common Mistakes to Avoid
- Moving
summarizebut forgetting to keep it beforepaginate. The fix isfilter → summarize → paginate, not just "move summarize somewhere after filter." - Treating authorization as a filter. If
apply_filtershandles both security scoping and user filters in one call, make sure your refactor doesn't expose a path where user filter parameters can be supplied before tenant isolation runs. - Assuming the frontend is the source. The raw HTTP response is the source of truth. Check it before reading any JavaScript.
- Duplicating filter logic. If the same filter is applied in two places (once in Python, once in a SQL query), a future change to one side will silently desync the rows and the metrics again. Prefer a single filter path, ideally pushed to storage.