Skip to content

Commit dcf6fe1

Browse files
test: boot the Postgres suites in the house microVM with IntegreSQL (#13)
The Postgres suites ran against a service container that the test process had to find through EFFECT_AGENT_TEST_POSTGRES_URL. They now follow the fleet's integration-database pattern: Postgres and the digest-pinned IntegreSQL layer boot inside a microVM on the runner's KVM device, each case checks its own database out of IntegreSQL, and the hand-back retries until the case's pooled connections drain. Nothing needs a Docker daemon, a service container, or a shared server; EFFECT_AGENT_TEST_POSTGRES_URL still points the suites at a server you run yourself. CI gains the KVM grant and the IntegreSQL layer cache the other repositories use, and the separate three-major job is gone: the node matrix now runs every suite, including the Postgres ones. Verified without any server or container: storage-postgres 106/106 and the testing package's coordinator certification 1/1, both booting the microVM.
1 parent f910758 commit dcf6fe1

13 files changed

Lines changed: 742 additions & 72 deletions

‎.github/workflows/ci.yml‎

Lines changed: 13 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -68,69 +68,28 @@ jobs:
6868
fail-fast: false
6969
matrix:
7070
node: [22, 24]
71-
services:
72-
postgres:
73-
image: postgres:17-alpine
74-
env:
75-
POSTGRES_PASSWORD: postgres
76-
POSTGRES_DB: effect_agent
77-
ports:
78-
- 55432:5432
79-
options: >-
80-
--health-cmd pg_isready
81-
--health-interval 5s
82-
--health-timeout 5s
83-
--health-retries 10
8471
steps:
8572
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
8673
with:
8774
persist-credentials: false
75+
# The integration suites boot Postgres and IntegreSQL in microVMs, which need the runner's KVM device.
76+
- name: Grant KVM
77+
run: |
78+
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
79+
sudo udevadm control --reload-rules
80+
sudo udevadm trigger --name-match=kvm
8881
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
8982
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
9083
with:
9184
node-version: ${{ matrix.node }}
9285
- uses: ./.github/actions/pnpm-store
93-
- run: pnpm install --frozen-lockfile
94-
- run: pnpm test
95-
env:
96-
EFFECT_AGENT_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:55432/effect_agent
97-
98-
# Transaction rollback and connection cleanup cannot be proven against an in-process double, so the Postgres
99-
# storage suite runs against real servers on each supported major.
100-
storage-postgres:
101-
name: test (postgres ${{ matrix.postgres }})
102-
runs-on: ubuntu-latest
103-
timeout-minutes: 20
104-
strategy:
105-
fail-fast: false
106-
matrix:
107-
postgres: ["16", "17", "18"]
108-
services:
109-
postgres:
110-
image: postgres:${{ matrix.postgres }}-alpine
111-
env:
112-
POSTGRES_PASSWORD: postgres
113-
POSTGRES_DB: effect_agent
114-
ports:
115-
- 55432:5432
116-
options: >-
117-
--health-cmd pg_isready
118-
--health-interval 5s
119-
--health-timeout 5s
120-
--health-retries 10
121-
steps:
122-
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
123-
with:
124-
persist-credentials: false
125-
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
126-
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
86+
# The fixtures pull the digest-pinned IntegreSQL layer from ghcr.io once and keep it here.
87+
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
12788
with:
128-
node-version: 24
129-
- uses: ./.github/actions/pnpm-store
89+
path: ~/.cache/agent/integresql-layers
90+
key: integresql-${{ runner.arch }}-${{ hashFiles('packages/storage-postgres/test/integresql-binary.ts') }}
13091
- run: pnpm install --frozen-lockfile
131-
- run: pnpm --filter @systemfsoftware/agent-storage-postgres test
132-
env:
133-
EFFECT_AGENT_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:55432/effect_agent
92+
- run: pnpm test
13493

13594
# The one check the ruleset requires and the merge queue gates on; the name matches the shared CI of the other
13695
# systemfsoftware repositories. List every other job in `needs`: a job left out is not gated. The job always runs,
@@ -140,20 +99,19 @@ jobs:
14099
name: checks / check
141100
runs-on: ubuntu-latest
142101
timeout-minutes: 5
143-
needs: [static-checks, changeset, test, storage-postgres]
102+
needs: [static-checks, changeset, test]
144103
if: ${{ always() }}
145104
steps:
146105
- name: Require every job to succeed
147106
env:
148107
STATIC_CHECKS: ${{ needs.static-checks.result }}
149108
TEST: ${{ needs.test.result }}
150-
STORAGE_POSTGRES: ${{ needs.storage-postgres.result }}
151109
CHANGESET: ${{ needs.changeset.result }}
152110
EVENT: ${{ github.event_name }}
153111
HEAD_REF: ${{ github.head_ref }}
154112
run: |
155113
status=0
156-
for pair in "static-checks:$STATIC_CHECKS" "test:$TEST" "storage-postgres:$STORAGE_POSTGRES"; do
114+
for pair in "static-checks:$STATIC_CHECKS" "test:$TEST"; do
157115
case "$pair" in
158116
*:success) ;;
159117
*) echo "A required job finished as: $pair"; status=1 ;;

‎oxlint.baseline.json‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@
2727
"packages/platform-cloudflare/test/scheduling.test.ts",
2828
"packages/platform-cloudflare/test/subagent-harness.ts",
2929
"packages/pr-review-action/src/github.ts",
30+
"packages/storage-postgres/test/integresql-binary.ts",
3031
"packages/storage-sql/src/SqlStorage.ts",
31-
"packages/testing/src/DurableCoordinatorConformance.ts"
32+
"packages/testing/src/DurableCoordinatorConformance.ts",
33+
"packages/testing/test/integresql-binary.ts"
3234
],
3335
"@systemfsoftware/cell-architecture/ban-unknown": [
3436
"packages/ai-decision/src/AutoModel.ts",
@@ -183,6 +185,8 @@
183185
"packages/storage-memory/src/MemoryThreadStore.ts",
184186
"packages/storage-memory/test/durable-thread-head.test.ts",
185187
"packages/storage-postgres/src/internal/storage-layout.ts",
188+
"packages/storage-postgres/test/integresql-binary.ts",
189+
"packages/storage-postgres/test/postgres-server.ts",
186190
"packages/storage-postgres/test/postgres-submission-ledger-faults.test.ts",
187191
"packages/storage-postgres/test/postgres-thread-store-faults.test.ts",
188192
"packages/storage-sql/src/SqlActivityStore.ts",
@@ -217,6 +221,8 @@
217221
"packages/testing/test/durable-runtime.test.ts",
218222
"packages/testing/test/durable-subagents.test.ts",
219223
"packages/testing/test/durable-tools.test.ts",
224+
"packages/testing/test/integresql-binary.ts",
225+
"packages/testing/test/postgres-server.ts",
220226
"packages/testing/test/travel-planner-subagents-durable.test.ts",
221227
"scripts/verify-record-format.ts",
222228
"test/fixtures/instrumented-storage.ts"

‎packages/storage-postgres/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@
5151
"@effect/platform-node": "catalog:",
5252
"@effect/sql-pg": "catalog:",
5353
"@effect/vitest": "catalog:",
54+
"@systemfsoftware/effect-microsandbox": "catalog:",
55+
"@systemfsoftware/effect-readiness": "catalog:",
5456
"effect": "catalog:",
5557
"tsdown": "catalog:",
5658
"typescript": "catalog:",

‎packages/storage-postgres/test/harness.ts‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,25 @@ import * as Effect from 'effect/Effect'
66
import * as Layer from 'effect/Layer'
77
import * as Redacted from 'effect/Redacted'
88

9+
import { withIntegresqlDatabase } from './postgres-server.js'
10+
911
/**
1012
* A live Postgres is required for transaction rollback and connection cleanup;
11-
* an in-process double cannot establish those properties. `EFFECT_AGENT_TEST_POSTGRES_URL` points CI at its own service.
13+
* an in-process double cannot establish those properties. Unset, the suite boots
14+
* Postgres in a microVM and checks a database out of IntegreSQL; set
15+
* `EFFECT_AGENT_TEST_POSTGRES_URL` to point it at a server you already run.
1216
*/
13-
const adminUrl = process.env.EFFECT_AGENT_TEST_POSTGRES_URL ??
14-
'postgres://postgres:postgres@localhost:55432/effect_agent'
17+
const configuredUrl = process.env.EFFECT_AGENT_TEST_POSTGRES_URL
1518

1619
let databaseCounter = 0
1720

18-
const admin = <A, E>(effect: Effect.Effect<A, E, PgClient.PgClient>) =>
21+
const admin = <A, E>(url: string, effect: Effect.Effect<A, E, PgClient.PgClient>) =>
1922
effect.pipe(
20-
Effect.provide(PgClient.layer({ url: Redacted.make(adminUrl), maxConnections: 1 })),
23+
Effect.provide(PgClient.layer({ url: Redacted.make(url), maxConnections: 1 })),
2124
Effect.catchTag('SqlError', (error) =>
2225
Effect.die(
2326
new Error(
24-
'The storage-postgres tests need a reachable configured Postgres server ' +
25-
'(set EFFECT_AGENT_TEST_POSTGRES_URL, or run one with ' +
26-
'`docker run -d -p 55432:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=effect_agent postgres:17-alpine`).',
27+
'The configured Postgres server (EFFECT_AGENT_TEST_POSTGRES_URL) is unreachable.',
2728
{ cause: error },
2829
),
2930
)),
@@ -35,6 +36,14 @@ const admin = <A, E>(effect: Effect.Effect<A, E, PgClient.PgClient>) =>
3536
*/
3637
export const withTemporaryDatabase = <A, E>(
3738
use: (url: string) => Effect.Effect<A, E>,
39+
): Effect.Effect<A, E> =>
40+
configuredUrl === undefined
41+
? withIntegresqlDatabase(use).pipe(Effect.orDie)
42+
: withOwnedDatabase(configuredUrl, use)
43+
44+
const withOwnedDatabase = <A, E>(
45+
adminUrl: string,
46+
use: (url: string) => Effect.Effect<A, E>,
3847
): Effect.Effect<A, E> =>
3948
Effect.acquireUseRelease(
4049
Effect.sync(() => {
@@ -44,6 +53,7 @@ export const withTemporaryDatabase = <A, E>(
4453
}).pipe(
4554
Effect.tap((database) =>
4655
admin(
56+
adminUrl,
4757
Effect.flatMap(PgClient.PgClient, (sql) => sql.unsafe(`CREATE DATABASE ${database}`)),
4858
)
4959
),
@@ -57,6 +67,7 @@ export const withTemporaryDatabase = <A, E>(
5767
},
5868
(database) =>
5969
admin(
70+
adminUrl,
6071
Effect.flatMap(PgClient.PgClient, (sql) => sql.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`)),
6172
).pipe(Effect.ignore),
6273
)
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import * as Data from 'effect/Data'
2+
import * as Effect from 'effect/Effect'
3+
import * as HttpClient from 'effect/http/HttpClient'
4+
import * as HttpClientRequest from 'effect/http/HttpClientRequest'
5+
import * as HttpClientResponse from 'effect/http/HttpClientResponse'
6+
import * as Schedule from 'effect/Schedule'
7+
import * as Schema from 'effect/Schema'
8+
import { createHash } from 'node:crypto'
9+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
10+
import { homedir } from 'node:os'
11+
import path from 'node:path'
12+
import { arch } from 'node:process'
13+
import { gunzipSync } from 'node:zlib'
14+
15+
const REPOSITORY = 'allaboutapps/integresql'
16+
17+
const V1_1_0_LAYER_DIGESTS: Readonly<Record<string, string>> = {
18+
x64: 'sha256:8e4268615a42a8e45def4ecc7397241c9b598c3731e4c0a0c951c39e0c48093c',
19+
arm64: 'sha256:77ba01934c00eb411a42df97af551d904dcc02b8d3db1027101378923f32aab3',
20+
}
21+
22+
const CACHE = path.join(homedir(), '.cache', 'agent', 'integresql-layers')
23+
24+
const BLOCK = 512
25+
26+
export class IntegresqlUnavailable extends Data.TaggedError('IntegresqlUnavailable')<{ readonly reason: string }> {
27+
override get message(): string {
28+
return `the pinned IntegreSQL binary is unavailable: ${this.reason}`
29+
}
30+
}
31+
32+
const unavailable = (cause: unknown) =>
33+
new IntegresqlUnavailable({ reason: cause instanceof Error ? cause.message : String(cause) })
34+
35+
const digestOf = (bytes: Uint8Array): string => `sha256:${createHash('sha256').update(bytes).digest('hex')}`
36+
37+
const entryOf = (archive: Uint8Array, name: string): Uint8Array | undefined => {
38+
let offset = 0
39+
while (offset + BLOCK <= archive.length) {
40+
const header = Buffer.from(archive.subarray(offset, offset + BLOCK))
41+
const nameEnd = header.indexOf(0)
42+
const entry = header.toString('latin1', 0, nameEnd === -1 || nameEnd > 100 ? 100 : nameEnd).replace(/^\.\//, '')
43+
if (entry === '') return undefined
44+
const size = Number.parseInt(header.toString('latin1', 124, 136).replace(/\0/g, '').trim(), 8)
45+
const data = offset + BLOCK
46+
if (entry === name) return archive.subarray(data, data + size)
47+
offset = data + Math.ceil(size / BLOCK) * BLOCK
48+
}
49+
return undefined
50+
}
51+
52+
const TokenAnswer = Schema.Struct({ token: Schema.String })
53+
54+
const pulled = Effect.fnUntraced(
55+
function*(digest: string) {
56+
const client = yield* HttpClient.HttpClient
57+
const { token } = yield* client.get(`https://ghcr.io/token?scope=repository:${REPOSITORY}:pull`).pipe(
58+
Effect.flatMap(HttpClientResponse.filterStatusOk),
59+
Effect.flatMap(HttpClientResponse.schemaBodyJson(TokenAnswer)),
60+
)
61+
const response = yield* client.execute(
62+
HttpClientRequest.get(`https://ghcr.io/v2/${REPOSITORY}/blobs/${digest}`).pipe(
63+
HttpClientRequest.bearerToken(token),
64+
),
65+
).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk))
66+
return new Uint8Array(yield* response.arrayBuffer)
67+
},
68+
Effect.retry({ schedule: Schedule.exponential('1 second'), times: 4 }),
69+
Effect.mapError(unavailable),
70+
)
71+
72+
const cached = (file: string) =>
73+
Effect.promise(() => readFile(file).then((bytes) => new Uint8Array(bytes), () => undefined))
74+
75+
const kept = (file: string, blob: Uint8Array) =>
76+
Effect.tryPromise({
77+
try: async () => {
78+
await mkdir(CACHE, { recursive: true })
79+
const staged = `${file}.${process.pid}.partial`
80+
await writeFile(staged, blob)
81+
await rename(staged, file)
82+
},
83+
catch: unavailable,
84+
})
85+
86+
const layerOf = Effect.fnUntraced(function*(digest: string) {
87+
const file = path.join(CACHE, digest.slice('sha256:'.length))
88+
const hit = yield* cached(file)
89+
if (hit && digestOf(hit) === digest) return hit
90+
const blob = yield* pulled(digest)
91+
if (digestOf(blob) !== digest) {
92+
return yield* new IntegresqlUnavailable({ reason: `the pulled layer is ${digestOf(blob)}, not ${digest}` })
93+
}
94+
yield* kept(file, blob)
95+
return blob
96+
})
97+
98+
export const integresqlBinary = Effect.gen(function*() {
99+
const digest = V1_1_0_LAYER_DIGESTS[arch]
100+
if (!digest) return yield* new IntegresqlUnavailable({ reason: `no pinned layer for ${arch}` })
101+
const blob = yield* layerOf(digest)
102+
const archive = yield* Effect.try({ try: () => gunzipSync(blob), catch: unavailable })
103+
const binary = entryOf(archive, 'integresql')
104+
if (!binary) return yield* new IntegresqlUnavailable({ reason: `layer ${digest} holds no /integresql` })
105+
return binary
106+
})

0 commit comments

Comments
 (0)