Skip to content

Commit 33e9d6d

Browse files
Take the agent update lock in TrueFoundryAgentStore. Do not pass it in from main.
TrueFoundry mode cannot run with STANDALONE=true.
1 parent ed35613 commit 33e9d6d

7 files changed

Lines changed: 133 additions & 161 deletions

File tree

‎.changeset/20260902194500-truefoundry-agent-store.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"@truefoundry/trueforge": patch
33
---
44

5-
Sync ServiceFoundry remote agents on create/update/delete and store the remote id in `external_id`. Filter `listAgents` by `external_ids`. Keep general ServiceFoundry HTTP at 10s and agent CRUD calls at 3s.
5+
Sync ServiceFoundry remote agents on create/update/delete and store the remote id in `external_id`. Filter `listAgents` by `external_ids`. Keep general ServiceFoundry HTTP at 10s and agent CRUD calls at 3s. Require `STANDALONE=false` when `TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set.

‎packages/trueforge/src/config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -728,6 +728,10 @@ if (isTrueFoundryModeEnabled(configuration) && isOidcConfigured(configuration))
728728
);
729729
}
730730

731+
if (isTrueFoundryModeEnabled(configuration) && configuration.STANDALONE) {
732+
throw new Error('TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL requires STANDALONE=false.');
733+
}
734+
731735
/**
732736
* Public origin for OAuth callbacks.
733737
* Standalone (non-development) → `http://localhost:$PORT`; otherwise `PUBLIC_BASE_URL`

‎packages/trueforge/src/db/agentUpdateLock.ts‎

Lines changed: 0 additions & 12 deletions
This file was deleted.

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

Lines changed: 0 additions & 15 deletions
This file was deleted.

‎packages/trueforge/src/main.ts‎

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,10 @@ import { SkillCatalog } from './catalog/SkillCatalog';
6666
import { type DistributedServerConfiguration } from './config';
6767
import { createController } from './controller';
6868
import type { IAgentStore } from './db/agentStore';
69-
import type { WithAgentUpdateLock } from './db/agentUpdateLock';
70-
import { withoutAgentUpdateLock } from './db/agentUpdateLock';
7169
import type { IMcpServerStore, IMcpServerWithAuthStore } from './db/mcpServerStore';
7270
import { McpServerWithAuthStore } from './db/McpServerWithAuthStore';
7371
import type { IModelProviderStore } from './db/modelProviderStore';
74-
import { createPostgresAgentUpdateLock } from './db/postgres/agent-store/agentUpdateLock';
72+
import type { PostgresAgentStore } from './db/postgres/agent-store/PostgresAgentStore';
7573
import type { Database as PostgresDatabase } from './db/postgres/types';
7674
import type { ISandboxProviderStore } from './db/sandboxProviderStore';
7775
import type { IScheduleStore } from './db/scheduleStore';
@@ -194,22 +192,17 @@ function buildResolveMcpServerStore<TTransaction>(options: {
194192
* Per-request agent store resolver. In TrueFoundry mode every request gets a token-bound
195193
* decorator over DB persistence; otherwise the persistence store is reused as-is.
196194
*/
197-
function buildResolveAgentStore<TTransaction>(options: {
198-
persistenceStore: IAgentStore<TTransaction>;
199-
client: TrueFoundryServiceFoundryServerClient | undefined;
200-
withUpdateLock: WithAgentUpdateLock<TTransaction>;
201-
}): (c?: Context) => IAgentStore<TTransaction> {
202-
const { persistenceStore, client, withUpdateLock } = options;
203-
if (!client) {
204-
return () => persistenceStore;
205-
}
195+
function buildResolveAgentStore(options: {
196+
persistenceStore: PostgresAgentStore;
197+
client: TrueFoundryServiceFoundryServerClient;
198+
}): (c?: Context) => IAgentStore<Transaction<PostgresDatabase>> {
199+
const { persistenceStore, client } = options;
206200
return c =>
207201
c
208-
? new TrueFoundryAgentStore<TTransaction>({
202+
? new TrueFoundryAgentStore({
209203
inner: persistenceStore,
210204
client,
211205
accessToken: requireRequestCredentialToken(c),
212-
withUpdateLock,
213206
})
214207
: persistenceStore;
215208
}
@@ -255,24 +248,19 @@ async function createStandalonePersistence(options: {
255248

256249
const tokenStore = new SqliteOAuthTokenStore(db);
257250
const agentStore = new SqliteAgentStore(db);
258-
const serviceFoundryClient = createServiceFoundryServerClient(logger);
259251
return {
260252
sessionStore: new SqliteSessionStore(db),
261253
sessionMetricsStore: new SqliteSessionMetricsStore(db),
262254
resolveModelProviderStore: buildResolveModelProviderStore({
263255
persistenceStore: new SqliteModelProviderStore(db),
264-
client: serviceFoundryClient,
256+
client: undefined,
265257
}),
266258
resolveMcpServerStore: buildResolveMcpServerStore({
267259
persistenceStore: new SqliteMcpServerStore(db),
268260
tokenStore,
269-
client: serviceFoundryClient,
270-
}),
271-
resolveAgentStore: buildResolveAgentStore({
272-
persistenceStore: agentStore,
273-
client: serviceFoundryClient,
274-
withUpdateLock: withoutAgentUpdateLock(),
261+
client: undefined,
275262
}),
263+
resolveAgentStore: () => agentStore,
276264
withTransaction: callback => db.transaction().execute(callback),
277265
tokenStore,
278266
skillStore: new SqliteSkillStore(db),
@@ -351,11 +339,13 @@ async function createDistributedPersistence(options: {
351339
tokenStore,
352340
client: serviceFoundryClient,
353341
}),
354-
resolveAgentStore: buildResolveAgentStore({
355-
persistenceStore: agentStore,
356-
client: serviceFoundryClient,
357-
withUpdateLock: createPostgresAgentUpdateLock(db),
358-
}),
342+
resolveAgentStore:
343+
serviceFoundryClient === undefined
344+
? () => agentStore
345+
: buildResolveAgentStore({
346+
persistenceStore: agentStore,
347+
client: serviceFoundryClient,
348+
}),
359349
withTransaction: callback => db.transaction().execute(callback),
360350
tokenStore,
361351
skillStore: new PostgresSkillStore(db),

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

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';
2+
import { sql, type Transaction } from 'kysely';
23
import {
34
type AgentRecord,
45
type CreateAgentInput,
@@ -8,7 +9,7 @@ import {
89
type ListAgentsInput,
910
type UpdateAgentInput,
1011
} from '../db/agentStore';
11-
import type { WithAgentUpdateLock } from '../db/agentUpdateLock';
12+
import type { Database } from '../db/postgres/types';
1213
import {
1314
TrueFoundryServiceFoundryServerClient,
1415
type PutRemoteAgentInput,
@@ -38,33 +39,44 @@ function toPutRemoteAgentPayload({
3839
* update: lock → get → putRemote(new) → updateDB | on DB fail → putRemote(old) | both fail → AggregateError
3940
* delete: lock → get → deleteRemote(404 ok) → deleteDB
4041
*/
41-
export class TrueFoundryAgentStore<TTransaction = never> implements IAgentStore<TTransaction> {
42+
export class TrueFoundryAgentStore<
43+
TTransaction extends Transaction<Database> = Transaction<Database>,
44+
> implements IAgentStore<TTransaction> {
4245
readonly #inner: IAgentStore<TTransaction>;
4346
readonly #client: TrueFoundryServiceFoundryServerClient;
4447
readonly #accessToken: string;
45-
readonly #withUpdateLock: WithAgentUpdateLock<TTransaction>;
4648

4749
constructor(input: {
4850
inner: IAgentStore<TTransaction>;
4951
client: TrueFoundryServiceFoundryServerClient;
5052
accessToken: string;
51-
withUpdateLock: WithAgentUpdateLock<TTransaction>;
5253
}) {
5354
this.#inner = input.inner;
5455
this.#client = input.client;
5556
this.#accessToken = input.accessToken;
56-
this.#withUpdateLock = input.withUpdateLock;
5757
}
5858

59-
listAgents(input: ListAgentsInput, transaction?: TTransaction): Promise<AgentRecord[]> {
59+
listAgents(input: ListAgentsInput, transaction: TTransaction): Promise<AgentRecord[]> {
6060
return this.#inner.listAgents(input, transaction);
6161
}
6262

63-
getAgent(input: GetAgentInput, transaction?: TTransaction): Promise<AgentRecord | undefined> {
63+
getAgent(input: GetAgentInput, transaction: TTransaction): Promise<AgentRecord | undefined> {
6464
return this.#inner.getAgent(input, transaction);
6565
}
6666

67-
async createAgent(input: CreateAgentInput, transaction?: TTransaction): Promise<AgentRecord> {
67+
// Serializes updates for this tenant ID and agent id.
68+
// Prevents concurrent MCP writes from desyncing the remote agent.
69+
async #withUpdateLock<T>(
70+
input: { tenant_id: string; id: string },
71+
transaction: TTransaction,
72+
fn: (transaction: TTransaction) => Promise<T>,
73+
): Promise<T> {
74+
const key = `tf:agent:${input.tenant_id}:${input.id}`;
75+
await sql`SELECT pg_advisory_xact_lock(hashtext(${key}))`.execute(transaction);
76+
return fn(transaction);
77+
}
78+
79+
async createAgent(input: CreateAgentInput, transaction: TTransaction): Promise<AgentRecord> {
6880
// Lets the DB unique constraint pick one winner for this tenant ID and name.
6981
// Prevents concurrent requests from both creating the same remote agent.
7082
const created = await this.#inner.createAgent({ ...input, external_id: null }, transaction);
@@ -104,16 +116,14 @@ export class TrueFoundryAgentStore<TTransaction = never> implements IAgentStore<
104116
}
105117
}
106118

107-
async updateAgent(input: UpdateAgentInput, transaction?: TTransaction): Promise<AgentRecord | undefined> {
119+
async updateAgent(input: UpdateAgentInput, transaction: TTransaction): Promise<AgentRecord | undefined> {
108120
const nextManifest = input.manifest;
109121
if (nextManifest === undefined) {
110122
// No manifest means only `external_id` changed; pass through to the inner store.
111123
return this.#inner.updateAgent(input, transaction);
112124
}
113125

114-
// Serialize same-agent updates (incl. SF HTTP) so concurrent MCP writes cannot desync.
115-
return this.#withUpdateLock({ tenant_id: input.tenant_id, id: input.id }, async lockedTransaction => {
116-
const txn = lockedTransaction ?? transaction;
126+
return this.#withUpdateLock(input, transaction, async txn => {
117127
const previous = await this.#inner.getAgent({ tenant_id: input.tenant_id, id: input.id }, txn);
118128
if (previous === undefined) {
119129
return undefined;
@@ -152,10 +162,8 @@ export class TrueFoundryAgentStore<TTransaction = never> implements IAgentStore<
152162
});
153163
}
154164

155-
async deleteAgent(input: DeleteAgentInput, transaction?: TTransaction): Promise<void> {
156-
// Same lock as update so delete cannot remove the remote between update's get and putRemote.
157-
return this.#withUpdateLock({ tenant_id: input.tenant_id, id: input.id }, async lockedTransaction => {
158-
const txn = lockedTransaction ?? transaction;
165+
async deleteAgent(input: DeleteAgentInput, transaction: TTransaction): Promise<void> {
166+
return this.#withUpdateLock(input, transaction, async txn => {
159167
const previous = await this.#inner.getAgent({ tenant_id: input.tenant_id, id: input.id }, txn);
160168
if (previous?.external_id) {
161169
await this.#client.deleteRemoteAgent({

0 commit comments

Comments
 (0)