跳到正文
DEV Community· Anton Korzunov·· 1 小時前AI 評分60

CI 未必是瓶頸?Variance 探討如何降低測試驗證成本

What if CI is not a bottleneck?

AI 導讀

Variance 保留測試與其執行程式碼之間的關係,按程式碼變更找出有證據需要執行的測試,藉此降低 CI 的驗證工作量。在 TanStack Query 連續 60 次提交的重播測試中,某次 Query.fetch 變更由 Nx 選出 168 個測試檔,Variance 選出 9 個。

正文

You are shipping more code than ever. Your engineers have AI assistants, your AI assistants have agents, and your agents generate code, write tests, open pull requests and occasionally fix their own mistakes.

There is just one problem.

Someone has to verify all that AI slop.

Your CI is struggling, your PR queue is growing, and your engineering team is discussing how to optimise GitHub Actions again, reduce the number of tests, or get rid of them altogether. Meanwhile, you are waiting for some magical CLI from Vercel to finally solve all your problems without going to extremes.

Somewhere along the way, we dramatically reduced the cost of producing code without doing much about the cost of verifying it.

And now we have to deal with the consequences.

Coverage is good. Coverage is bad.

We love code coverage. 80% is good, 90% is better, and 100% deserves a badge in your README.

  • 0% coverage means your codebase is very flexible. You can do whatever you want with it, including breaking it.
  • 40% coverage means that, hopefully, some important elements of your application are not going to randomly change their behaviour.
  • 80% coverage doesn't necessarily tell you much more.

Because coverage tells you what was executed, not what was verified. And even less about whether your tests would actually detect a regression.

Consider three perfectly reasonable end-to-end tests in an e-commerce application.

Test Login Product page Checkout
User can log in ●
Discount is displayed correctly ○ ●
User can complete a purchase ○ ○ ●

● Behaviour under test · ○ Behaviour executed along the way

From a code coverage perspective, we have covered login three times. From a verification perspective, we have explicitly tested it once.

Now change the pricing logic and rerun your tests. Not only are we running a login test that has nothing to do with our change, but we are also going through the login process twice more to verify the functionality we actually care about.

We are executing login not because we want to, but because it's in our way. We cannot access anything else without going through it.

Can we do better? Of course. We can start our test after login, with an already authenticated user. We can take it further and render the product page in isolation, or go straight to the function responsible for calculating the price.

The ability to work with a smaller slice of a bigger product is what allows us to move from end-to-end testing towards integration testing, and from integration testing towards unit testing.

Rings a bell?

The economics of the testing pyramid

The testing pyramid: progressively smaller slices of application execution

We didn't invent the testing pyramid because there is something fundamentally wrong with end-to-end tests. We invented it because verification has a cost.

The smaller the slice of the application we need to execute, the cheaper it generally is to verify a particular behaviour. Of course, the smaller that slice is, the less we know about how it works together with everything else. But we also can better understand small things, while coverage for large things means almost nothing.

This is a trade-off we have been managing for years. We argue about what to mock, what to isolate, what deserves an integration test and whether a particular user journey is important enough to justify another Playwright scenario.

The testing pyramid is as much an economic model as it is a technical one.

And now AI can generate another thousand tests before lunch. Writing tests has become significantly cheaper. Running them still costs the same.

Something in that economic model needs to change.

Making CI faster

There are a few established approaches to dealing with the growing cost of CI:

  • Parallelisation — do the same work simultaneously.
  • Caching — don't repeat work if the inputs haven't changed.
  • Affected detection — don't run tasks unrelated to a change.
  • Faster tooling — reduce the cost of individual operations.

Nx and Turborepo have done a great job bringing these ideas into everyday development. If you have a sufficiently large monorepo, you are probably already using something along these lines.

But imagine you changed a single function in your shared utilities package. Hundreds of components depend on that package, dozens of test suites import it, and suddenly a substantial portion of your repository needs to be verified again.

How many of those tests actually use the function you changed?

Your dependency graph can tell you which tests could be affected. Execution coverage can tell you which tests have actually used that function.

We already collect this information. We just tend to aggregate it into a percentage and put it on a dashboard. Throw it away.

What if coverage was not a report?

This is where Variance Authority comes in.

Instead of aggregating execution information from individual tests into a single number, Variance preserves the relationship between tests and the code they execute. Essentially, we are reversing the question.

    What code did these tests execute?

              ↓

    Which tests executed this code?

Same information. A completely different application.

Change a function, and Variance can identify the tests that previously executed it, supplementing historical evidence with dependency analysis to account for changes that previous executions cannot explain.

There is an important distinction here. Variance is not trying to guess which tests you should run. It is looking for evidence that allows you to skip them.

A new test? Run it.
A previously failed test? Run it.
No recording available? Run everything.
A reason to skip a test? Skip it!

Running a test is the default. Skipping it requires evidence.

It doesn't particularly matter where those tests sit in our testing pyramid. A function might be covered by a unit test, a component test and an end-to-end scenario. All three provide different kinds of evidence about the behaviour of our application, and all three might be worth running when that function changes.

Having a thousand end-to-end tests becomes considerably less of a problem if you don't have to run a thousand end-to-end tests every time someone changes a line of code.

78% fewer tests. On top of Nx.

We use Variance to develop Variance itself, running on average just 1.4% of our own tests. But our repository is hardly an independent example, so let's look at somebody else's.

TanStack Query already uses Nx. Over a replay of 60 consecutive commits, we compared the number of test-file executions selected by three different approaches.

TanStack Query benchmark: 11,280 full-suite executions, 3,464 with Nx, 775 with Variance

For one particular change inside Query.fetch, Nx selected 168 test files. Variance selected nine.

Not because the other tests were bad, redundant or poorly written. They just had nothing relevant to verify for that particular change.

You can find more about the experiment in my previous article.

But surely collecting all that information is expensive?

On Material UI, recording execution evidence for test selection added just over two seconds to a 92-second test run. Collecting conventional V8 coverage added over 19 seconds.

Material UI benchmark Execution time Overhead
Uninstrumented 91.56s —
Variance recording 93.69s 2.3%
V8 coverage 110.86s 21.1%

We don't need to know how many times a function was executed to decide whether a test reached it. Once is enough.

Looking at different projects, I would consider a 70% reduction in testing time a reasonable target to investigate. Your mileage will vary, particularly depending on how much of your CI time is actually spent running tests.

And we haven't made a single test faster yet.


But how small is your unit test, really?

Remember why we invented the testing pyramid? We wanted to execute smaller slices of our application. We even have a special name for the smallest slice — a unit test.

Consider a perfectly innocent one:

import { calculatePrice } from '@/utils';

it('calculates the discounted price', () => {
  expect(calculatePrice(100, 0.2)).toBe(80);
});

The actual test takes virtually no time to execute. However, your utils barrel file also exports authentication helpers, date formatters, analytics integrations and a few other things somebody decided were utilities three years ago.

Depending on your module structure and test runner, you might end up loading and evaluating a substantial part of your application just to multiply two numbers.

You have written a unit test. Whether you are executing a unit is another question.

Unlike our login example, some of this code is not even a prerequisite for the functionality under test. It's being executed simply because that's how our module system works.

This is not a new problem. We have been dealing with it in application development for years.

React Native addresses it with inline requires. SWC has a similar mechanism in the form of lazy imports.

Why initialise something now if you might never use it?

We care about this when optimising application startup because our users are waiting. Somehow, when it comes to testing, we are considerably more tolerant of the same inefficiency.

Same tests. Cheaper execution.

There are some interesting examples of what happens when we stop tolerating it.

Linear reduced its total API-shard runner time from 32.8 to 22 minutes per run by allowing suitable test files to share loaded modules under strict isolation rules. That's roughly a third of the runner time gone. Their CI optimisation article is well worth reading.

Rstest achieved a 37.8% reduction in execution time in one benchmark by prebundling jsdom. See the Rstest 0.12 announcement.

Neither optimisation required removing tests or assertions.

And going back to TanStack Query, we found that 47% of the source lines counted across module loads belonged to modules whose functions no test in the corresponding test file ever entered.

Almost half of what was loaded.

And this was a well-maintained library, not some legacy enterprise application nobody wants to touch.

Variance distinguishes between module initialisation and subsequent execution. This gives us the evidence necessary to identify candidates for more focused imports, smaller fixtures, deliberate mocks and other execution optimisations.

Not everything that was loaded can be removed. Some modules perform necessary work during initialisation. But now we have something considerably better than a guess about where to start, and a way to verify the result afterwards.

Importing something, using something and testing something are three very different activities.

Perhaps before asking how to make our tests faster, we should figure out how much time our tests spend actually testing.

Run fewer tests. Execute less code.

Think about your test suite as a matrix, where every row is a test and every column represents a piece of application code.

Two dimensions of test optimisation: vertical test selection and horizontal reduction of unnecessary execution

Coverage-based selection allows us to optimise vertically, reducing the number of tests we need to execute.

Distilling tests and avoiding unnecessary module initialisation allows us to optimise horizontally, reducing the work inside each remaining test.

These are complementary optimisations. Neither requires us to remove tests because they are too expensive to run, and neither particularly cares how many tests AI generated this morning.

But there is another interesting property of this matrix: we don't have to throw it away when our tests finish.

Normally, when your test suite finishes, you get a green tick and very little else of lasting value. Perhaps a coverage report that somebody will look at once a month.

With Variance, you also get a persistent map of your application's execution. You can use it to select tests for your next change, find the tests associated with a particular function, investigate expensive module loading or understand which parts of your application are exercised by different kinds of tests.

Your tests have finished working. Let their results do some work as well.


From testing afterwards to testing as you go

AI agents handing verified changes to a smarter CI pipeline

Perhaps the more interesting consequence of making verification cheaper is not a shorter CI pipeline, but what happens outside of it.

If running the relevant tests takes seconds rather than minutes, why wait until you push your changes? Why not verify your code while you are writing it?

And why not let your AI agents do exactly the same thing?

Instead of generating a whole pull request and hoping CI turns green, an agent could verify its changes as it makes them, using the same tests, the same execution evidence and the same selection mechanism as your CI.

CI can become the place where we confirm that the work has been done correctly, rather than the place where we start figuring that out.

That's a different development loop altogether, and something we'll get into in the next article — Testing as you go.

Go try it yourself

Before you start wondering how much effort it would take to introduce another tool into your monorepo — relax, it's not Bazel.

Variance is not another test runner or build system. Keep your existing tests, your favourite test harness, your Nx or Turborepo setup and your GitHub Actions workflows.

There are integrations for Vitest, Jest, Playwright, Storybook and Rstest.

You don't need to adopt everything at once:

  1. Add Variance to your existing test harness and record your suite.
  2. Change something and see how many tests you actually need to run.
  3. Inspect what those tests execute and what they unnecessarily load.
  4. Use intelligent sharding to distribute the work that remains.

Or just give your coding agent variance-authority.dev and ask it to integrate Variance. There are agent skills to guide it through the process.

You already have the tests. You already have the infrastructure. You might even have a perfectly reasonable testing strategy.

What you probably don't have is a good understanding of how much of that work needs to happen every time you change something. The answer is - "not that much".

Go try it yourself.

Supports jest, vitest, retest and playwright out of the box.

You might discover that CI was never the bottleneck. It was simply doing everything you asked it to do. But it's time to ask it to be smarter.

來源:DEV Community · dev.to