Skip to content

Commit 7968f59

Browse files
Inject db into TrueFoundryAgentStore for advisory locks (#588)
* Inject db into TrueFoundryAgentStore for advisory locks * added code comments
1 parent 1672aed commit 7968f59

5 files changed

Lines changed: 135 additions & 83 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@truefoundry/trueforge": patch
3+
---
4+
5+
Use injected `db` for TrueFoundryAgentStore advisory-lock transactions.

‎packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,6 @@ export class PostgresAgentStore implements IAgentStore<Transaction<Database>> {
8181
return row === undefined ? undefined : toRecord(row);
8282
}
8383

84-
withTransaction<T>(fn: (transaction: Transaction<Database>) => Promise<T>): Promise<T> {
85-
return this.#db.transaction().execute(fn);
86-
}
87-
8884
async createAgent(input: CreateAgentInput, transaction?: Transaction<Database>): Promise<AgentRecord> {
8985
const db = transaction ?? this.#db;
9086
try {

‎packages/trueforge/src/main.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ import {
5151
type TurnStreamingEvent,
5252
} from '@truefoundry/trueforge-core/agent-session';
5353
import { RequestReplyExecutor, RequestReplyRouter } from '@truefoundry/trueforge-core/request-reply';
54-
import type { Transaction } from 'kysely';
54+
import type { Kysely, Transaction } from 'kysely';
5555
import type { RedisClientType } from 'redis';
5656
import type { Logger } from 'winston';
5757

@@ -197,8 +197,9 @@ function buildResolveMcpServerStore<TTransaction>(options: {
197197
function buildResolveAgentStore(options: {
198198
persistenceStore: PostgresAgentStore;
199199
client: TrueFoundryServiceFoundryServerClient | undefined;
200+
db: Kysely<PostgresDatabase>;
200201
}): (c?: Context) => IAgentStore<Transaction<PostgresDatabase>> {
201-
const { persistenceStore, client } = options;
202+
const { persistenceStore, client, db } = options;
202203
if (!client) {
203204
return () => persistenceStore;
204205
}
@@ -209,6 +210,7 @@ function buildResolveAgentStore(options: {
209210
inner: persistenceStore,
210211
client,
211212
accessToken: requireRequestCredentialToken(c),
213+
db,
212214
})
213215
: persistenceStore;
214216
}
@@ -348,6 +350,7 @@ async function createDistributedPersistence(options: {
348350
resolveAgentStore: buildResolveAgentStore({
349351
persistenceStore: agentStore,
350352
client: serviceFoundryClient,
353+
db,
351354
}),
352355
withTransaction: callback => db.transaction().execute(callback),
353356
tokenStore,

‎packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts‎

Lines changed: 48 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
2-
import { sql, type Transaction } from 'kysely';
2+
import { sql, type Kysely, type Transaction } from 'kysely';
33
import {
44
type AgentRecord,
55
type CreateAgentInput,
@@ -9,6 +9,7 @@ import {
99
type ListAgentsInput,
1010
type UpdateAgentInput,
1111
} from '../db/agentStore';
12+
import { PostgresAgentStore } from '../db/postgres/agent-store/PostgresAgentStore';
1213
import type { Database } from '../db/postgres/types';
1314
import {
1415
TrueFoundryServiceFoundryServerClient,
@@ -34,57 +35,79 @@ function toPutRemoteAgentPayload({
3435
};
3536
}
3637

37-
type TrueFoundryAgentInner<TTransaction> = IAgentStore<TTransaction> & {
38-
withTransaction<T>(fn: (transaction: TTransaction) => Promise<T>): Promise<T>;
39-
};
40-
4138
/**
42-
* create: createDB(null) → putRemote → updateDB(external_id) | on put/update fail → deleteDB (+ deleteRemote if put ok)
43-
* update: lock → get → putRemote(new) → updateDB | on DB fail → putRemote(old) | both fail → AggregateError
44-
* delete: lock → get → deleteRemote(404 ok) → deleteDB
39+
* Postgres agent store that keeps a matching ServiceFoundry remote agent in sync.
40+
*
41+
* DB and ServiceFoundry are not one atomic transaction. Cleanup on failure is
42+
* best-effort: a delete/restore step can itself fail, leaving temporary SF↔DB skew
43+
* (orphan remote, orphan local row, or mismatched manifest). create / update /
44+
* delete stay retryable — a later successful call is expected to recover.
45+
*
46+
* create
47+
* Happy path: insert local row (external_id null) → put remote → set external_id.
48+
* Name clash on insert: throw; no remote call.
49+
* putRemote fails: delete local row; rethrow.
50+
* update(external_id) fails after put: delete remote (if put returned an id), then
51+
* delete local; if cleanup also fails, AggregateError (primary + cleanup errors).
52+
*
53+
* update (manifest)
54+
* Happy path: lock → load row → put remote (new manifest) → write local.
55+
* Missing row: return undefined (no remote call).
56+
* putRemote fails: leave local unchanged; rethrow.
57+
* local write fails after put: best-effort putRemote(old manifest); if restore fails,
58+
* AggregateError; if restore ok, rethrow the DB error (local still old, remote restored).
59+
* external_id-only patches skip ServiceFoundry and go straight to the inner store.
60+
*
61+
* delete
62+
* Happy path: lock → load row → delete remote when external_id is set → delete local.
63+
* Missing row or null external_id: skip remote; still delete local (idempotent).
64+
* remote delete fails: do not delete local; rethrow (local kept so retry can finish).
4565
*/
46-
export class TrueFoundryAgentStore<
47-
TTransaction extends Transaction<Database> = Transaction<Database>,
48-
> implements IAgentStore<TTransaction> {
49-
readonly #inner: TrueFoundryAgentInner<TTransaction>;
66+
export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>> {
67+
readonly #inner: PostgresAgentStore;
5068
readonly #client: TrueFoundryServiceFoundryServerClient;
5169
readonly #accessToken: string;
70+
readonly #db: Kysely<Database>;
5271

5372
constructor(input: {
54-
inner: TrueFoundryAgentInner<TTransaction>;
73+
inner: PostgresAgentStore;
5574
client: TrueFoundryServiceFoundryServerClient;
5675
accessToken: string;
76+
db: Kysely<Database>;
5777
}) {
5878
this.#inner = input.inner;
5979
this.#client = input.client;
6080
this.#accessToken = input.accessToken;
81+
this.#db = input.db;
6182
}
6283

63-
listAgents(input: ListAgentsInput, transaction?: TTransaction): Promise<AgentRecord[]> {
84+
listAgents(input: ListAgentsInput, transaction?: Transaction<Database>): Promise<AgentRecord[]> {
6485
return this.#inner.listAgents(input, transaction);
6586
}
6687

67-
getAgent(input: GetAgentInput, transaction?: TTransaction): Promise<AgentRecord | undefined> {
88+
getAgent(input: GetAgentInput, transaction?: Transaction<Database>): Promise<AgentRecord | undefined> {
6889
return this.#inner.getAgent(input, transaction);
6990
}
7091

71-
// Serializes updates for this tenant ID and agent id.
72-
// Prevents concurrent MCP writes from desyncing the remote agent.
92+
// Takes a Postgres transaction advisory lock for this tenant + agent id so concurrent
93+
// update/delete cannot desync ServiceFoundry MCP grants. The lock only lasts for the
94+
// lifetime of a DB transaction: if the caller passed one, use it; otherwise open a
95+
// short transaction on db just for this critical section.
7396
#withUpdateLock<T>(
7497
input: { tenant_id: string; id: string },
75-
transaction: TTransaction | undefined,
76-
fn: (transaction: TTransaction) => Promise<T>,
98+
transaction: Transaction<Database> | undefined,
99+
fn: (transaction: Transaction<Database>) => Promise<T>,
77100
): Promise<T> {
78-
const run = async (txn: TTransaction) => {
101+
const run = async (txn: Transaction<Database>) => {
79102
const key = `tf:agent:${input.tenant_id}:${input.id}`;
80103
await sql`SELECT pg_advisory_xact_lock(hashtext(${key}))`.execute(txn);
81104
return fn(txn);
82105
};
83-
return transaction !== undefined ? run(transaction) : this.#inner.withTransaction(run);
106+
return transaction !== undefined ? run(transaction) : this.#db.transaction().execute(run);
84107
}
85108

86-
async createAgent(input: CreateAgentInput, transaction?: TTransaction): Promise<AgentRecord> {
87-
// Lets the DB unique constraint pick one winner for this tenant ID and name.
109+
async createAgent(input: CreateAgentInput, transaction?: Transaction<Database>): Promise<AgentRecord> {
110+
// Unique (tenant_id, name) picks one winner even when transaction is omitted (auto-commit inserts).
88111
// Prevents concurrent requests from both creating the same remote agent.
89112
const created = await this.#inner.createAgent({ ...input, external_id: null }, transaction);
90113

@@ -123,7 +146,7 @@ export class TrueFoundryAgentStore<
123146
}
124147
}
125148

126-
async updateAgent(input: UpdateAgentInput, transaction?: TTransaction): Promise<AgentRecord | undefined> {
149+
async updateAgent(input: UpdateAgentInput, transaction?: Transaction<Database>): Promise<AgentRecord | undefined> {
127150
const nextManifest = input.manifest;
128151
if (nextManifest === undefined) {
129152
// No manifest means only `external_id` changed; pass through to the inner store.
@@ -169,7 +192,7 @@ export class TrueFoundryAgentStore<
169192
});
170193
}
171194

172-
async deleteAgent(input: DeleteAgentInput, transaction?: TTransaction): Promise<void> {
195+
async deleteAgent(input: DeleteAgentInput, transaction?: Transaction<Database>): Promise<void> {
173196
return this.#withUpdateLock(input, transaction, async txn => {
174197
const previous = await this.#inner.getAgent({ tenant_id: input.tenant_id, id: input.id }, txn);
175198
if (previous?.external_id) {

0 commit comments

Comments
 (0)