Problem
Each OpenCode session that triggers Plugin.init() creates its own postgres() connection (with max: 1). On sami-agents-mx with many concurrent sessions, this produces 82+ connections from a single machine. With 4 fleet machines syncing, this will exceed even 300 max_connections.
Evidence
SELECT count(*) FROM pg_stat_activity WHERE datname = 'opencode_test';
-- 82 (from sami-agents-mx alone)
Postgres max_connections was bumped from 100 to 300 as a workaround.
Fix
The plugin's server() function in src/index.ts creates a new postgres(url, { max: 1 }) on every call. Since server() is called per-directory bootstrap, each project directory gets its own connection.
Fix: use a module-level singleton keyed by connection URL. If the URL matches an existing pool, reuse it.
const pools = new Map<string, ReturnType<typeof postgres>>()
function pool(url: string) {
const hit = pools.get(url)
if (hit) return hit
const sql = postgres(url, { max: 3 })
pools.set(url, sql)
return sql
}
This drops from N connections (one per directory) to a single shared pool with 3 connections max.
Also fix
- Part FK race:
replay failed insert or update on table "part" violates foreign key constraint "part_message_id_fkey" — parts arriving before their parent message. Buffer or use ON CONFLICT DO NOTHING and retry on next event.
Problem
Each OpenCode session that triggers
Plugin.init()creates its ownpostgres()connection (withmax: 1). On sami-agents-mx with many concurrent sessions, this produces 82+ connections from a single machine. With 4 fleet machines syncing, this will exceed even 300 max_connections.Evidence
Postgres max_connections was bumped from 100 to 300 as a workaround.
Fix
The plugin's
server()function insrc/index.tscreates a newpostgres(url, { max: 1 })on every call. Sinceserver()is called per-directory bootstrap, each project directory gets its own connection.Fix: use a module-level singleton keyed by connection URL. If the URL matches an existing pool, reuse it.
This drops from N connections (one per directory) to a single shared pool with 3 connections max.
Also fix
replay failed insert or update on table "part" violates foreign key constraint "part_message_id_fkey"— parts arriving before their parent message. Buffer or useON CONFLICT DO NOTHINGand retry on next event.