Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/concurrent-coordinator-conformance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@systemfsoftware/agent-testing": minor
---

`durableCoordinatorConformance` is now a function of `{ withStorage, concurrency }` and runs its sweep cells concurrently, each over storage that `withStorage` supplies for that cell alone. Pass a `withStorage` that checks out a separate database per cell.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
title: Concurrent conformance cells need their own storage, failpoint control and runtime
date: 2026-11-25
category: test-failures
module: agent-testing coordinator conformance
problem_type: slow_test
component: testing
severity: medium
applies_when:
- A sequential fault-injection sweep is slow but mostly waits on I/O
- Sweep cells share a database, a failpoint handler or a runtime
- Tuning test concurrency on a CI runner with few vCPUs
tags: [concurrency, integresql, failpoints, conformance, ci]
---

# Concurrent conformance cells need their own storage, failpoint control and runtime

## Context

The PostgreSQL coordinator certification ran as one sequential sweep: 90.8s on CI, 84.8s locally
on 20.4s of CPU. That makes it I/O- and wait-bound, which is the case concurrency helps.

## What it took

- **Isolate every cell.** Recovery passes scan every Thread in storage, and the failpoint control
holds a single handler, so concurrent cells on one database or one control fire and recover each
other's work. Each cell builds its own runtime, failpoint control and config, and checks out its
own IntegreSQL database through the caller's `withStorage`.
- **Keep the sweep's closure.** Recovery in one cell can reach a failpoint that clean discovery
never did (four of six scenarios swept more cells than discovery reached). A fixed list from
discovery drops those cells. Run waves until no scenario has a reached but undriven location.
- **Keep IntegreSQL's pool above the concurrency.** IntegreSQL v1.1.0 recreates the oldest
checked-out database, even one still in use, once its pool reaches the maximum size with fewer
than the initial size ready or recreating (`pkg/pool/pool.go`, `autoCleanDirty`). With 16 cells
on a pool of 16, a cell's database was dropped under it (`database "integresql_test_empty_009"
does not exist`). The pool maximum is derived from the most databases a test holds plus room for
the initial size, so the two cannot drift apart.
- **Size the pools together.** At 16 cells, Postgres refused connections until each cell's client
was capped at four connections, keeping 64 connections under `max_connections` 200.

## Measure where it runs

On a 4-vCPU runner shared with every other suite, 16 cells made the test slower (153.2s). In its
own CI lane it took 53.2s at 16 and 57.9s at 4. Concurrency that wins alone can lose under
contention, so measure it in the layout it will run in, and land it after the lane split.
216 changes: 128 additions & 88 deletions packages/testing/src/DurableCoordinatorConformance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -816,112 +816,152 @@ const runSweepCell = Effect.fnUntraced(function*(

const caseName = 'coordinator recovery converges after injected faults'

/** The storage services one sweep cell runs over. */
export type DurableCoordinatorStorage =
| SubmissionLedger
| ThreadStore
| SettlementPublisher
| StorageOwner
| CryptoDigest.Digest

export interface DurableCoordinatorConformanceOptions {
/**
* Runs one cell over its own pristine storage and releases it afterwards. Cells run
* concurrently and recovery passes scan every Thread in storage, so no two cells may share it.
*/
readonly withStorage: <A, E>(cell: Effect.Effect<A, E, DurableCoordinatorStorage>) => Effect.Effect<A, E>
/** The most cells holding storage at once. */
readonly concurrency: number
}

// The runtime, its failpoint control and its config are built afresh for every cell.
const cellLayer = Layer.mergeAll(runStorageLayer, ThreadReader.layer()).pipe(
Layer.provideMerge(
Layer.mergeAll(
WakeScheduler.layerNoop,
DurableRuntimeFailpointTestControl.layer,
ToolReconciler.uncertain,
DurableRuntimeConfig.layer({
deploymentId: Schema.decodeSync(DeploymentId)('deployment-certification'),
producerId: Schema.decodeSync(ProducerId)('producer-certification'),
settlementPollInterval: Duration.millis(50),
abortPollInterval: Duration.millis(50),
}),
),
),
)

/**
* Exercise six deterministic scenarios over disposable, pristine storage. Discover each clean
* path, arm every reached or unaccounted-for failpoint once, and require bounded recovery to
* settled, natively verified history. The final never-fired set must match the known paths
* outside these scenarios; every scenario must exercise at least one injected fault.
* Exercise six deterministic scenarios, each cell over its own pristine storage. Discover each
* clean path, arm every reached or unaccounted-for failpoint once, and require bounded recovery
* to settled, natively verified history. Cells run in waves until no cell reaches a location its
* scenario has not yet armed. The final never-fired set must match the known paths outside these
* scenarios; every scenario must exercise at least one injected fault.
*
* Provide one combined adapter Layer with SubmissionLedger, ThreadStore, SettlementPublisher,
* StorageOwner and Digest in a TestClock-backed environment. The helper owns its runtime Scope
* and supplies a no-op WakeScheduler because it re-drives lanes explicitly. Injected failures
* do not establish recovery after actual process loss or eviction.
* `withStorage` supplies SubmissionLedger, ThreadStore, SettlementPublisher, StorageOwner and
* Digest per cell in a TestClock-backed environment. Each cell owns its runtime Scope and a no-op
* WakeScheduler because it re-drives lanes explicitly. Injected failures do not establish
* recovery after actual process loss or eviction.
*/
export const durableCoordinatorConformance: Effect.Effect<
void,
DurableCoordinatorConformanceViolation | ThreadStoreError,
SubmissionLedger | ThreadStore | SettlementPublisher | StorageOwner | CryptoDigest.Digest
> = Effect.gen(function*() {
const discoveries: Array<{
readonly scenario: CoordinatorScenario
readonly outcome: SweepOutcome
readonly reached: Set<DurableRuntimeFailpointLocation>
}> = []

for (const scenario of SCENARIOS) {
const reached = new Set<DurableRuntimeFailpointLocation>()
const outcome = yield* runSweepCell(scenario, undefined, reached)

discoveries.push({ scenario, outcome, reached })
}
const observed = new Set(discoveries.flatMap(({ reached }) => [...reached]))
export const durableCoordinatorConformance = (
options: DurableCoordinatorConformanceOptions,
): Effect.Effect<void, DurableCoordinatorConformanceViolation | ThreadStoreError> =>
Effect.gen(function*() {
const runCell = Effect.fnUntraced(
function*(scenario: CoordinatorScenario, location: DurableRuntimeFailpointLocation | undefined) {
const reached = new Set<DurableRuntimeFailpointLocation>()
const outcome = yield* runSweepCell(scenario, location, reached)

return { outcome, reached }
},
Effect.provide(cellLayer),
options.withStorage,
)

// Never silently omit a new location: arm it in every shape if neither clean discovery
// nor the known never-fired set accounts for it. Recovery can expose further routes.
const unaccounted = new Set(
DurableRuntimeFailpointLocation.literals.filter(
(location) => !observed.has(location) && !UNREACHED_LOCATIONS.includes(location),
),
)
const discoveries = yield* Effect.forEach(SCENARIOS, (scenario) => runCell(scenario, undefined), {
concurrency: options.concurrency,
})

const fired = new Set<DurableRuntimeFailpointLocation>()
const sweeps = SCENARIOS.map((scenario, index) => ({
scenario,
discovery: discoveries[index],
reached: new Set(discoveries[index]?.reached),
outcomes: new Map<DurableRuntimeFailpointLocation, SweepOutcome>(),
}))

for (const { scenario, outcome, reached } of discoveries) {
if (outcome.status === 'failed') {
return yield* DurableCoordinatorConformanceViolation.make({
caseName,
message: `${scenario} discovery failed: ${outcome.detail}`,
})
for (const { scenario, discovery } of sweeps) {
if (discovery === undefined || discovery.outcome.status === 'failed') {
return yield* DurableCoordinatorConformanceViolation.make({
caseName,
message: `${scenario} discovery failed: ${discovery?.outcome.detail}`,
})
}
}
const outcomes = new Map<DurableRuntimeFailpointLocation, SweepOutcome>()
const observed = new Set(discoveries.flatMap(({ reached }) => [...reached]))

// Never silently omit a new location: arm it in every shape if neither clean discovery
// nor the known never-fired set accounts for it. Recovery can expose further routes.
const unaccounted = new Set(
DurableRuntimeFailpointLocation.literals.filter(
(location) => !observed.has(location) && !UNREACHED_LOCATIONS.includes(location),
),
)

const fired = new Set<DurableRuntimeFailpointLocation>()

while (true) {
// Schema order bounds this to one drive per location in each scenario.
const location = DurableRuntimeFailpointLocation.literals.find(
(candidate) => !outcomes.has(candidate) && (reached.has(candidate) || unaccounted.has(candidate)),
// Each wave arms every reached location not yet driven, so each location drives once per scenario.
const wave = sweeps.flatMap((sweep) =>
DurableRuntimeFailpointLocation.literals
.filter((candidate) =>
!sweep.outcomes.has(candidate) && (sweep.reached.has(candidate) || unaccounted.has(candidate))
)
.map((location) => ({ sweep, location }))
)

if (location === undefined) break
const result = yield* runSweepCell(scenario, location, reached)
if (wave.length === 0) break
const results = yield* Effect.forEach(
wave,
({ sweep, location }) =>
runCell(sweep.scenario, location).pipe(Effect.map((result) => ({ sweep, location, ...result }))),
{ concurrency: options.concurrency },
)

outcomes.set(location, result)
if (result.status === 'failed') {
for (const { sweep, location, outcome, reached } of results) {
if (outcome.status === 'failed') {
return yield* DurableCoordinatorConformanceViolation.make({
caseName,
message: `${sweep.scenario} at ${location} failed: ${outcome.detail}`,
})
}
sweep.outcomes.set(location, outcome)
for (const hit of reached) sweep.reached.add(hit)
if (outcome.failpointFired) fired.add(location)
}
}

for (const { scenario, outcomes } of sweeps) {
if (![...outcomes.values()].some((result) => result.failpointFired)) {
return yield* DurableCoordinatorConformanceViolation.make({
caseName,
message: `${scenario} at ${location} failed: ${result.detail}`,
message: `${scenario} did not fire any injected fault`,
})
}
if (result.failpointFired) fired.add(location)
}
if (![...outcomes.values()].some((result) => result.failpointFired)) {

const neverFired = DurableRuntimeFailpointLocation.literals
.filter((location) => !fired.has(location))
.sort()

const expected = [...UNREACHED_LOCATIONS].sort()

if (
neverFired.length !== expected.length ||
neverFired.some((location, index) => location !== expected[index])
) {
return yield* DurableCoordinatorConformanceViolation.make({
caseName,
message: `${scenario} did not fire any injected fault`,
message: `expected never-fired locations [${expected.join(', ')}], got [${neverFired.join(', ')}]`,
})
}
}

const neverFired = DurableRuntimeFailpointLocation.literals
.filter((location) => !fired.has(location))
.sort()

const expected = [...UNREACHED_LOCATIONS].sort()

if (
neverFired.length !== expected.length ||
neverFired.some((location, index) => location !== expected[index])
) {
return yield* DurableCoordinatorConformanceViolation.make({
caseName,
message: `expected never-fired locations [${expected.join(', ')}], got [${neverFired.join(', ')}]`,
})
}
}).pipe(
Effect.provide(
Layer.mergeAll(runStorageLayer, ThreadReader.layer()).pipe(
Layer.provideMerge(
Layer.mergeAll(
WakeScheduler.layerNoop,
DurableRuntimeFailpointTestControl.layer,
ToolReconciler.uncertain,
DurableRuntimeConfig.layer({
deploymentId: Schema.decodeSync(DeploymentId)('deployment-certification'),
producerId: Schema.decodeSync(ProducerId)('producer-certification'),
settlementPollInterval: Duration.millis(50),
abortPollInterval: Duration.millis(50),
}),
),
),
),
),
)
})
16 changes: 12 additions & 4 deletions packages/testing/test/certification-postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import * as NodeCrypto from '@effect/platform-node/NodeCrypto'
import * as PgClient from '@effect/sql-pg/PgClient'
import { it } from '@effect/vitest'
import * as PostgresStorage from '@systemfsoftware/agent-storage-postgres/postgres-storage'
import { durableCoordinatorConformance } from '@systemfsoftware/agent-testing/durable-coordinator-conformance'
import {
durableCoordinatorConformance,
type DurableCoordinatorStorage,
} from '@systemfsoftware/agent-testing/durable-coordinator-conformance'
import * as Effect from 'effect/Effect'
import * as Layer from 'effect/Layer'
import * as Redacted from 'effect/Redacted'

import { withIntegresqlDatabase } from './postgres-server.js'
import { MAX_CHECKED_OUT_DATABASES, withIntegresqlDatabase } from './postgres-server.js'

/**
* Keep coordinator checks outside the adapter package to avoid a storage-postgres -> testing cycle.
Expand Down Expand Up @@ -54,11 +57,16 @@ const withOwnedDatabase = <A, E>(
const combinedAdapters = (url: string) =>
PostgresStorage.layerWith({ observationPollInterval: 1 }).pipe(
Layer.provideMerge(NodeCrypto.layer),
Layer.provideMerge(PgClient.layer({ url: Redacted.make(url) })),
Layer.provideMerge(PgClient.layer({ url: Redacted.make(url), maxConnections: 4 })),
)

// Each cell checks out its own database; adapter connection failures are defects of the fixture.
const withStorage = <A, E>(cell: Effect.Effect<A, E, DurableCoordinatorStorage>): Effect.Effect<A, E> =>
withTemporaryDatabase((url) => cell.pipe(Effect.provide(Layer.orDie(combinedAdapters(url)))))

it.effect(
'converges PostgreSQL coordinator recovery after injected faults',
() => withTemporaryDatabase((url) => durableCoordinatorConformance.pipe(Effect.provide(combinedAdapters(url)))),
// At four connections a cell, every held database together stays under max_connections of 200.
() => durableCoordinatorConformance({ withStorage, concurrency: MAX_CHECKED_OUT_DATABASES }),
300_000,
)
15 changes: 14 additions & 1 deletion packages/testing/test/postgres-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ const READY = 'database server ready'
const FAILED = 'database server failed'
const STATUS = `${RAM}/boot-status`

/** The most databases a test in this process may hold checked out at once. */
export const MAX_CHECKED_OUT_DATABASES = 16

// Once the pool reaches its maximum with fewer than its initial size ready or recreating, IntegreSQL
// recreates the oldest checked-out database even while it is in use. The pool keeps room above every
// database a test may hold so that never happens.
const INITIAL_POOL_SIZE = 2
const MAX_POOL_SIZE = MAX_CHECKED_OUT_DATABASES + 2 * INITIAL_POOL_SIZE
// A handed-back database briefly counts as neither ready nor recreating, so headroom alone leaves a
// window. Auto-clean also waits out this lifetime, which outlasts the longest test timeout here.
const DATABASE_MINIMAL_LIFETIME_MS = 300_000

const bootScript = (binaries: string) =>
`#!/bin/bash
set -eu
Expand All @@ -46,7 +58,8 @@ as ${binaries}/pg_ctl -D ${RAM}/data -l ${RAM}/postgres.log -w -t 60 -o "-c list
cp ${GUEST}/integresql /tmp/integresql
chmod +x /tmp/integresql
INTEGRESQL_PORT=${INTEGRESQL_PORT} INTEGRESQL_PGHOST=127.0.0.1 INTEGRESQL_PGPORT=${POSTGRES_PORT} INTEGRESQL_PGUSER=postgres \\
INTEGRESQL_TEST_INITIAL_POOL_SIZE=2 INTEGRESQL_TEST_MAX_POOL_SIZE=8 /tmp/integresql > ${RAM}/integresql.log 2>&1 &
INTEGRESQL_TEST_INITIAL_POOL_SIZE=${INITIAL_POOL_SIZE} INTEGRESQL_TEST_MAX_POOL_SIZE=${MAX_POOL_SIZE} \\
INTEGRESQL_TEST_DB_MINIMAL_LIFETIME_MS=${DATABASE_MINIMAL_LIFETIME_MS} /tmp/integresql > ${RAM}/integresql.log 2>&1 &
server=$!
until ( exec 3<>/dev/tcp/127.0.0.1/${INTEGRESQL_PORT} ) 2>/dev/null; do
kill -0 "$server" || { printf 'integresql exited' > ${STATUS}; exit 1; }
Expand Down
Loading