Prompt,
but Verify

Code Coverage In AI era

Jan Nedbal

Principal Engineer at ShipMonk

  • x.com/janedbal
  • github.com/janedbal
  • Agents write code and tests
  • Tests verify the code
  • But what verifies the tests?
  • Coverage should!
OrderService.phpagent
function refund(Order $order): void
{
    if ($order->isPaid()) {
        $this->bank->refund($order);
    }
    $order->markRefunded();
}
OrderServiceTest.php✓ passedagent

Yet nobody uses
code coverage

…and I know why

Because coverage is slow

no coverage
PCOV
Xdebug

…and often gets squeezed into one number

a41f9c2guard empty order with exception80.11 %−0.01 %
b03d9c7add Order::cancel() with tests80.12 %
3fa8e62bump dependencies80.10 %
7c2a5f1extract PriceCalculator80.10 %
e19b0d4fix rounding in invoice total80.07 %
✓ useful as a trendnot as a CI gate

…though the report knows much more

OrderService.php
function refund(Order $order): void
{
    if ($order->isPaid()) {
        $this->bank->refund($order);
    }
    $order->markRefunded();
}
clover.xmlsimplified
<file name="src/Order/OrderService.php">
  <line num="1" type="method" name="refund" count="1"/>
  <line num="3" type="stmt" count="1"/>
  <line num="4" type="stmt" count="0"/>
  <line num="6" type="stmt" count="1"/>
  <metrics statements="3" coveredstatements="2"/>
</file>

Let me show you how to make it:

Fast

Almost plain PHP speed

tests
+ coverage

Useful

Fail CI on your rules

✗ OrderFacade::cancel()
  new method, no test

To make it fast

…we need to know how coverage works

How do we know which lines ran?

PHP runs opcodes, not lines — Xdebug & PCOV hook each one

require 'fee.php';
fee(3);
fee.php
function fee(int $weight): int
{
    if ($weight <= 0) {
        throw new LogicException();
    }
    $fee = $weight * 5;
    return $fee;
}
opcodes
3 | IS_SMALLER_OR_EQUAL | $weight, 0
3 | JMPZ | → MUL
4 | NEW | LogicException
4 | DO_FCALL |
4 | THROW |
6 | MUL | $weight, 5
6 | ASSIGN | $fee
7 | VERIFY_RETURN_TYPE | $fee
7 | RETURN | $fee
executedexecutable, not executedno opcodes

With executable lines, we can calculate coverage %

…and hooks slow everything down

plain PHP

run it
1×suite time

PCOV

hookfile wanted?
line new?
record line
run it
2×suite time

Xdebug

hookfilter check
branch info
mark line
+ own call stack
run it
13×suite time
• every opcode, every time, in all code, even vendor
• even on lines that are already covered

Idea: pay once per line

PCOVhook calls 0
function total(array $items): int
{
    $sum = 0;
    foreach ($items as $item) {
        $sum += $item->price;
    }
    return $sum;
}
plain PHP
one-shot probesprobe calls 0
function total(array $items): int
{
    $sum = 0;
    foreach ($items as $item) {
        $sum += $item->price;
    }
    return $sum;
}
plain PHP
✓ same report ✓ no probes in vendor ↻ probes re-armed for each test

shipmonk/turbocovnear-zero overhead

Introducing a new PHP extension

shipmonk/turbocov
no coverage
turbocov
PCOV
Xdebug

Driver overhead only · Carbon test suite · 6,349 tests · PHP 8.5

Why are probes so much faster?

fee(3)1st call2nd call
PCOVchecks 0
turbocovprobes fired 0
✓ fewer: first opcode of a line, only your files ✓ temporary: gone after the first run

A real CI run pays twice

no coverage
turbocov
PCOV
testscoverage driverPHPUnit processing

with turbocov, most of the cost is PHPUnit

Carbon test suite · 6,349 tests · PHP 8.5 · clover report

Luckily, only nightly runs need it all

Nightly — slow

whole codebase

1× per day, to track the metric

Every MR — fast

changed files only

no coverage
turbocov
PCOV

(whole run: driver + PHPUnit)

Carbon test suite · 2 changed files · clover report

No tool needs the full report in an MR

git diff --name-only --diff-filter=AMR origin/master...HEAD -- '*.php' > changed.txt
php -d turbocov.collect_paths=@changed.txt vendor/bin/phpunit
src/probe

PCOV can filter the report too, but not its hook

And turbocov wins the processing too

tests
turbocov
executed lines only
PHPUnit
2.6 s
tests
PCOV
always all executable lines
PHPUnitHOOK
7.6 s

Carbon test suite · full run

The more CPU, the bigger the gap

MR mode · ShipMonk core: CI, ~42k tests, 5 changed files · Carbon: 2 changed files

Ok, we are fast now!

…but how to make it useful?

See itfor those who still read the code
Enforce itfor everyone, even agents

See it

Coverage in the MR diff

src/Order/OrderService.phptests running…+8
public function cancel(Order $order): void
{
    if ($order->isShipped()) {
        throw new CannotCancelShippedOrder();
    }
    $order->markCancelled();
    $this->refunds->refund($order);
}

.gitlab-ci.yml artifact

coverage_report:
  coverage_format: cobertura
  path: cobertura.xml
✓GitLab ✗GitHub
⏳ nothing to see until the whole test pipeline finishes

See it

New file, no test?

never required → no opcodes → unknown count of executable lines PHPUnit reads its AST → 5 executable lines
MR coverage
–%

Enforce it

shipmonk/coverage-guard

rules, not numbers

Enforce it

Your rules

public function inspect(
    ClassMethodBlock $block,
    InspectionContext $context,
): ?CoverageError {
    if (
        $context->getClassReflection()?->isSubclassOf(Facade::class)
        && $block->getChangePercentage() === 100
        && $block->getCoveragePercentage() === 0
    ) {
        return CoverageError::create('New facade method without tests!');
    }
    return null;
}
src/Order/OrderFacade.php:42
New facade method without tests!
42public function cancel(int $id): void
43{
44 $this->orders->cancel($id);

Enforce it

Will unreachable code break my numbers?

public function ship(Order $order): void
{
    if (!$order->isPaid()) {
        throw new LogicException('Unreachable');
    }
    $this->carrier->send($order);
    $order->markShipped();
}
$config->addExecutableLineExcluder(
    new IgnoreThrowNewExceptionLineExcluder([LogicException::class]),
);
method coverage
75%

Enforce it

Will my legacy code fail everywhere?

vendor/bin/coverage-guard check clover.xml
errors
–

✓ --patch checks only the files & methods changed in the MR

Enforce it

Coverage Guard: More in the box

merge / convert

vendor/bin/coverage-guard merge *.xml
job 1
job 2
job 3
→
clover / cobertura

patch-coverage

coverage of changed lines only
✓Pipeline passed
Test coveragechanged lines0.0 %
✋ Changes requested

Try it

Fast

shipmonk/turbocov

QR code for github.com/shipmonk-rnd/turbocov

github.com/shipmonk-rnd/turbocov

Useful

shipmonk/coverage-guard

QR code for github.com/shipmonk-rnd/coverage-guard

github.com/shipmonk-rnd/coverage-guard

Thank you!

Questions?

↻ Turn your phone for a bigger view