Test AI-generated averages with unequal batch sizes
Test AI-generated aggregation code by checking both a known weighted result and whether regrouping the same requests changes that result. The acceptance rule is simple: every request contributes equally, so mean latency must equal total duration divided by total request count.
For example, imagine an AI-assisted change that replaces raw latency samples with batch summaries:
| Batch | Requests | Batch mean | Total duration |
|---|---|---|---|
| A | One request at 100 ms | 100 ms | 100 ms |
| B | Nine requests at 10 ms | 10 ms | 90 ms |
The required pooled mean is (100 + 90) / (1 + 9) = 19 ms. Averaging the two batch means produces (100 + 10) / 2 = 55 ms.
Both implementations can look reasonable in a code review. Only one satisfies the requirement.
Batch boundaries must not change a request-weighted mean.
Decide what the summary must preserve
The reader decision is whether to accept a change that discards individual observations in favor of summaries. For this requirement, I would accept a summary that preserves request count and total duration, subject to explicit numeric and input policies. I would reject a summary containing only the mean.
A mean without a count loses the batch's weight. Once that information is gone, downstream code cannot reliably reconstruct the pooled mean.
For batches indexed by i, retain:
count_i: the number of requests in the batch.total_duration_ms_i: the sum of their durations in milliseconds.
Merge summaries by adding corresponding fields, then divide once:
count = sum(batch.count)
total_duration_ms = sum(batch.total_duration_ms)
mean_latency_ms = total_duration_ms / count
A mean paired with its count can also support weighted aggregation. Count and total duration make the merge rule explicit and avoid reconstructing totals from already-rounded means.
This is also where the requirement's scope matters. Those two fields support a pooled mean; they do not preserve enough information to recover arbitrary percentiles.
The abstract of “Why Finite Intelligence Works in an Infinite World: A Mathematical Theory” describes conditions under which finite representations preserve decision value across permitted tasks. That is a useful prompt to ask which future questions a summary must support. The abstract does not evaluate this software contract or coding-agent verification.
Put the requirement into a checkable contract
Use this small contract as the review artifact. The input and precision choices below are example policies, not universal defaults.
| Contract item | Declared behavior |
|---|---|
| Requirement | Every included request has equal weight in mean latency, regardless of batch boundaries. |
| Valid observations | Finite, nonnegative request durations expressed in milliseconds. |
| Retained state | Integer request count and total duration in milliseconds. |
| Merge rule | Add counts and totals; do not average batch means without weights. |
| Empty input | Empty batches contribute nothing. If no requests remain, return None. |
| Numeric comparison | For the small fixtures below, accept absolute error no greater than 1e-9 ms. |
| Regrouping rule | Repartitioning the same observations leaves the result unchanged within tolerance. |
Returning zero for an empty report would conflate “no observations” with “observed zero latency.” An API error or an explicit no-data object could also work, but choose one behavior before asking an agent to implement it.
Choose a numeric tolerance deliberately, too. The example tolerance is suitable for these small fixtures, not a justified production error budget for every duration range or accumulation strategy.
Equal-sized batches conceal an unweighted-average bug.
Test the real aggregation path
An incorrect implementation might contain this logic:
batch_means = [sum(batch) / len(batch) for batch in batches if batch]
return sum(batch_means) / len(batch_means)
Tests using only equally sized batches will not distinguish that calculation from the required weighted mean. The unequal fixture above will.
The following acceptance-test function assumes report(batches) returns a mean in milliseconds, or None when there are no observations. Connect report to the actual changed code. If production accepts summaries rather than raw batches, the adapter should use the production summarization and aggregation path, not implement a second calculator.
from math import isclose
def check_aggregation_contract(report):
def expect(batches, expected):
actual = report(batches)
assert actual is not None
assert isclose(
actual, expected, rel_tol=0.0, abs_tol=1e-9
), (batches, actual, expected)
# Same requests, different batch boundaries.
samples = [100.0] + [10.0] * 9
partitions = [
[samples],
[[100.0], [10.0] * 9],
[[value] for value in samples],
[samples[:4], samples[4:]],
]
for batches in partitions:
expect(batches, 19.0)
# Independent values prevent a constant 19 from passing.
expect([[2.0, 4.0], [12.0]], 6.0)
expect([[0.0]], 0.0)
# Explicit no-data and empty-batch behavior.
assert report([]) is None
assert report([[], []]) is None
expect([[], [100.0], [], [10.0] * 9], 19.0)
This is a test outline to adapt, not a reported test run.
The known result anchors the calculation to the requirement. The alternative partitions check that packaging does not change the answer. Both matter: partition invariance alone would also accept a function that always returned zero.
Make the contract part of the agent's change
Give the coding agent the requirement, contract table, and counterexample before implementation. Ask it to identify which fields survive aggregation and where rounding occurs.
Then use a short verification loop:
- Inspect the diff. Confirm counts and totals survive every intermediate aggregation stage.
- Run the acceptance checks. Exercise the actual changed path, including unequal batch sizes and empty inputs.
- Review the evidence. Keep the test output and reviewed diff associated with the contract version and code revision.
- Repeat after relevant changes. Rerun when summarization, merging, units, or reporting behavior changes.
A passing result attached to an older revision says nothing about the latest diff. Keeping the requirement beside its executable checks also makes specification drift easier to spot: an agent changing the expected value to 55 ms has changed the intended behavior, not fixed the implementation.
Passing these checks is evidence about a bounded contract, not mathematical proof.
Know what a passing result leaves open
These fixtures test pooled arithmetic and selected regroupings. They do not establish that the report selected the correct time window, removed duplicates, or included the right requests. A perfectly weighted mean over the wrong observations is still the wrong report.
They also leave invalid-input handling, overflow, large-scale floating-point accumulation, and other numerical edge cases untested. Percentile reporting needs a separate contract and an appropriate retained representation.
In five minutes, add the 19 ms fixture and one regrouping of those same requests to your real test suite. That can expose the average-of-averages error; it cannot validate the entire reporting pipeline. To put that bounded check into an intent-verification workflow, start with Gate your first AI change.