Skip to content
Open
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
68 changes: 13 additions & 55 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,69 +68,28 @@ jobs:
fail-fast: false
matrix:
node: [22, 24]
services:
postgres:
image: postgres:17-alpine
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: effect_agent
ports:
- 55432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# The integration suites boot Postgres and IntegreSQL in microVMs, which need the runner's KVM device.
- name: Grant KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: ${{ matrix.node }}
- uses: ./.github/actions/pnpm-store
- run: pnpm install --frozen-lockfile
- run: pnpm test
env:
EFFECT_AGENT_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:55432/effect_agent

# Transaction rollback and connection cleanup cannot be proven against an in-process double, so the Postgres
# storage suite runs against real servers on each supported major.
storage-postgres:
name: test (postgres ${{ matrix.postgres }})
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
postgres: ["16", "17", "18"]
services:
postgres:
image: postgres:${{ matrix.postgres }}-alpine
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: effect_agent
ports:
- 55432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
# The fixtures pull the digest-pinned IntegreSQL layer from ghcr.io once and keep it here.
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
node-version: 24
- uses: ./.github/actions/pnpm-store
path: ~/.cache/agent/integresql-layers
key: integresql-${{ runner.arch }}-${{ hashFiles('packages/storage-postgres/test/integresql-binary.ts') }}
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @systemfsoftware/agent-storage-postgres test
env:
EFFECT_AGENT_TEST_POSTGRES_URL: postgres://postgres:postgres@localhost:55432/effect_agent
- run: pnpm test

# The one check the ruleset requires and the merge queue gates on; the name matches the shared CI of the other
# systemfsoftware repositories. List every other job in `needs`: a job left out is not gated. The job always runs,
Expand All @@ -140,20 +99,19 @@ jobs:
name: checks / check
runs-on: ubuntu-latest
timeout-minutes: 5
needs: [static-checks, changeset, test, storage-postgres]
needs: [static-checks, changeset, test]
if: ${{ always() }}
steps:
- name: Require every job to succeed
env:
STATIC_CHECKS: ${{ needs.static-checks.result }}
TEST: ${{ needs.test.result }}
STORAGE_POSTGRES: ${{ needs.storage-postgres.result }}
CHANGESET: ${{ needs.changeset.result }}
EVENT: ${{ github.event_name }}
HEAD_REF: ${{ github.head_ref }}
run: |
status=0
for pair in "static-checks:$STATIC_CHECKS" "test:$TEST" "storage-postgres:$STORAGE_POSTGRES"; do
for pair in "static-checks:$STATIC_CHECKS" "test:$TEST"; do
case "$pair" in
*:success) ;;
*) echo "A required job finished as: $pair"; status=1 ;;
Expand Down
8 changes: 7 additions & 1 deletion oxlint.baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@
"packages/platform-cloudflare/test/scheduling.test.ts",
"packages/platform-cloudflare/test/subagent-harness.ts",
"packages/pr-review-action/src/github.ts",
"packages/storage-postgres/test/integresql-binary.ts",
"packages/storage-sql/src/SqlStorage.ts",
"packages/testing/src/DurableCoordinatorConformance.ts"
"packages/testing/src/DurableCoordinatorConformance.ts",
"packages/testing/test/integresql-binary.ts"
],
"@systemfsoftware/cell-architecture/ban-unknown": [
"packages/ai-decision/src/AutoModel.ts",
Expand Down Expand Up @@ -183,6 +185,8 @@
"packages/storage-memory/src/MemoryThreadStore.ts",
"packages/storage-memory/test/durable-thread-head.test.ts",
"packages/storage-postgres/src/internal/storage-layout.ts",
"packages/storage-postgres/test/integresql-binary.ts",
"packages/storage-postgres/test/postgres-server.ts",
"packages/storage-postgres/test/postgres-submission-ledger-faults.test.ts",
"packages/storage-postgres/test/postgres-thread-store-faults.test.ts",
"packages/storage-sql/src/SqlActivityStore.ts",
Expand Down Expand Up @@ -217,6 +221,8 @@
"packages/testing/test/durable-runtime.test.ts",
"packages/testing/test/durable-subagents.test.ts",
"packages/testing/test/durable-tools.test.ts",
"packages/testing/test/integresql-binary.ts",
"packages/testing/test/postgres-server.ts",
"packages/testing/test/travel-planner-subagents-durable.test.ts",
"scripts/verify-record-format.ts",
"test/fixtures/instrumented-storage.ts"
Expand Down
2 changes: 2 additions & 0 deletions packages/storage-postgres/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@
"@effect/platform-node": "catalog:",
"@effect/sql-pg": "catalog:",
"@effect/vitest": "catalog:",
"@systemfsoftware/effect-microsandbox": "catalog:",
"@systemfsoftware/effect-readiness": "catalog:",
"effect": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
Expand Down
27 changes: 19 additions & 8 deletions packages/storage-postgres/test/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,25 @@ import * as Effect from 'effect/Effect'
import * as Layer from 'effect/Layer'
import * as Redacted from 'effect/Redacted'

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

/**
* A live Postgres is required for transaction rollback and connection cleanup;
* an in-process double cannot establish those properties. `EFFECT_AGENT_TEST_POSTGRES_URL` points CI at its own service.
* an in-process double cannot establish those properties. Unset, the suite boots
* Postgres in a microVM and checks a database out of IntegreSQL; set
* `EFFECT_AGENT_TEST_POSTGRES_URL` to point it at a server you already run.
*/
const adminUrl = process.env.EFFECT_AGENT_TEST_POSTGRES_URL ??
'postgres://postgres:postgres@localhost:55432/effect_agent'
const configuredUrl = process.env.EFFECT_AGENT_TEST_POSTGRES_URL

let databaseCounter = 0

const admin = <A, E>(effect: Effect.Effect<A, E, PgClient.PgClient>) =>
const admin = <A, E>(url: string, effect: Effect.Effect<A, E, PgClient.PgClient>) =>
effect.pipe(
Effect.provide(PgClient.layer({ url: Redacted.make(adminUrl), maxConnections: 1 })),
Effect.provide(PgClient.layer({ url: Redacted.make(url), maxConnections: 1 })),
Effect.catchTag('SqlError', (error) =>
Effect.die(
new Error(
'The storage-postgres tests need a reachable configured Postgres server ' +
'(set EFFECT_AGENT_TEST_POSTGRES_URL, or run one with ' +
'`docker run -d -p 55432:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=effect_agent postgres:17-alpine`).',
'The configured Postgres server (EFFECT_AGENT_TEST_POSTGRES_URL) is unreachable.',
{ cause: error },
),
)),
Expand All @@ -35,6 +36,14 @@ const admin = <A, E>(effect: Effect.Effect<A, E, PgClient.PgClient>) =>
*/
export const withTemporaryDatabase = <A, E>(
use: (url: string) => Effect.Effect<A, E>,
): Effect.Effect<A, E> =>
configuredUrl === undefined
? withIntegresqlDatabase(use).pipe(Effect.orDie)
: withOwnedDatabase(configuredUrl, use)

const withOwnedDatabase = <A, E>(
adminUrl: string,
use: (url: string) => Effect.Effect<A, E>,
): Effect.Effect<A, E> =>
Effect.acquireUseRelease(
Effect.sync(() => {
Expand All @@ -44,6 +53,7 @@ export const withTemporaryDatabase = <A, E>(
}).pipe(
Effect.tap((database) =>
admin(
adminUrl,
Effect.flatMap(PgClient.PgClient, (sql) => sql.unsafe(`CREATE DATABASE ${database}`)),
)
),
Expand All @@ -57,6 +67,7 @@ export const withTemporaryDatabase = <A, E>(
},
(database) =>
admin(
adminUrl,
Effect.flatMap(PgClient.PgClient, (sql) => sql.unsafe(`DROP DATABASE IF EXISTS ${database} WITH (FORCE)`)),
).pipe(Effect.ignore),
)
Expand Down
106 changes: 106 additions & 0 deletions packages/storage-postgres/test/integresql-binary.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import * as Data from 'effect/Data'
import * as Effect from 'effect/Effect'
import * as HttpClient from 'effect/http/HttpClient'
import * as HttpClientRequest from 'effect/http/HttpClientRequest'
import * as HttpClientResponse from 'effect/http/HttpClientResponse'
import * as Schedule from 'effect/Schedule'
import * as Schema from 'effect/Schema'
import { createHash } from 'node:crypto'
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import path from 'node:path'
import { arch } from 'node:process'
import { gunzipSync } from 'node:zlib'

const REPOSITORY = 'allaboutapps/integresql'

const V1_1_0_LAYER_DIGESTS: Readonly<Record<string, string>> = {
x64: 'sha256:8e4268615a42a8e45def4ecc7397241c9b598c3731e4c0a0c951c39e0c48093c',
arm64: 'sha256:77ba01934c00eb411a42df97af551d904dcc02b8d3db1027101378923f32aab3',
}

const CACHE = path.join(homedir(), '.cache', 'agent', 'integresql-layers')

const BLOCK = 512

export class IntegresqlUnavailable extends Data.TaggedError('IntegresqlUnavailable')<{ readonly reason: string }> {
override get message(): string {
return `the pinned IntegreSQL binary is unavailable: ${this.reason}`
}
}

const unavailable = (cause: unknown) =>
new IntegresqlUnavailable({ reason: cause instanceof Error ? cause.message : String(cause) })

const digestOf = (bytes: Uint8Array): string => `sha256:${createHash('sha256').update(bytes).digest('hex')}`

const entryOf = (archive: Uint8Array, name: string): Uint8Array | undefined => {
let offset = 0
while (offset + BLOCK <= archive.length) {
const header = Buffer.from(archive.subarray(offset, offset + BLOCK))
const nameEnd = header.indexOf(0)
const entry = header.toString('latin1', 0, nameEnd === -1 || nameEnd > 100 ? 100 : nameEnd).replace(/^\.\//, '')
if (entry === '') return undefined
const size = Number.parseInt(header.toString('latin1', 124, 136).replace(/\0/g, '').trim(), 8)
const data = offset + BLOCK
if (entry === name) return archive.subarray(data, data + size)
offset = data + Math.ceil(size / BLOCK) * BLOCK
}
return undefined
}

const TokenAnswer = Schema.Struct({ token: Schema.String })

const pulled = Effect.fnUntraced(
function*(digest: string) {
const client = yield* HttpClient.HttpClient
const { token } = yield* client.get(`https://ghcr.io/token?scope=repository:${REPOSITORY}:pull`).pipe(
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap(HttpClientResponse.schemaBodyJson(TokenAnswer)),
)
const response = yield* client.execute(
HttpClientRequest.get(`https://ghcr.io/v2/${REPOSITORY}/blobs/${digest}`).pipe(
HttpClientRequest.bearerToken(token),
),
).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk))
return new Uint8Array(yield* response.arrayBuffer)
},
Effect.retry({ schedule: Schedule.exponential('1 second'), times: 4 }),
Effect.mapError(unavailable),
)

const cached = (file: string) =>
Effect.promise(() => readFile(file).then((bytes) => new Uint8Array(bytes), () => undefined))

const kept = (file: string, blob: Uint8Array) =>
Effect.tryPromise({
try: async () => {
await mkdir(CACHE, { recursive: true })
const staged = `${file}.${process.pid}.partial`
await writeFile(staged, blob)
await rename(staged, file)
},
catch: unavailable,
})

const layerOf = Effect.fnUntraced(function*(digest: string) {
const file = path.join(CACHE, digest.slice('sha256:'.length))
const hit = yield* cached(file)
if (hit && digestOf(hit) === digest) return hit
const blob = yield* pulled(digest)
if (digestOf(blob) !== digest) {
return yield* new IntegresqlUnavailable({ reason: `the pulled layer is ${digestOf(blob)}, not ${digest}` })
}
yield* kept(file, blob)
return blob
})

export const integresqlBinary = Effect.gen(function*() {
const digest = V1_1_0_LAYER_DIGESTS[arch]
if (!digest) return yield* new IntegresqlUnavailable({ reason: `no pinned layer for ${arch}` })
const blob = yield* layerOf(digest)
const archive = yield* Effect.try({ try: () => gunzipSync(blob), catch: unavailable })
const binary = entryOf(archive, 'integresql')
if (!binary) return yield* new IntegresqlUnavailable({ reason: `layer ${digest} holds no /integresql` })
return binary
})
Loading
Loading