Skip to content

Commit 49982f7

Browse files
ymichaelclaude
andauthored
Stop hand-editing the @bb/db data export list (#7554)
## Human comments ## What was wrong `packages/db/src/data/index.ts` re-exported every public data function, type, and constant by name: 582 lines, 512 names across 38 modules. Adding or renaming any data function meant editing that list, and 82 commits touched it in the last 60 days, so two open PRs that each add a data function usually conflicted there. The list also served as the public/private filter for `@bb/db`. It hid 11 helper modules entirely and, inconsistently, about 20 helpers in otherwise-public modules. Only one of those hidden groups was deliberate: the environment-lifecycle writers, which `apps/server` reaches through `@bb/db/internal-environment-lifecycle`. ## What changed - `packages/db/src/data/index.ts` is now one `export * from "./<module>.js"` line per public module (38 lines). A module is public if and only if it is listed there; unlisted modules stay package-private. Adding, renaming, or deleting a function in a public module no longer touches a shared file. Only a new public module adds one line. That happened in 9 of the 82 commits, and a sorted one-line-per-module list conflicts only on adjacent insertions. - The deliberately internal environment writers moved out of `environments.ts` into a new private module, `packages/db/src/data/environment-lifecycle.ts`: `applyEnvironmentLifecycleEvent`, `applyEnvironmentLifecycleEventInTransaction`, `recordProvisionedEnvironmentWorkspace`, and the shared `updateEnvironmentMetadataRecord`. So the root `@bb/db` still does not expose them. `updateEnvironmentMetadata` and `recordEnvironmentCurrentBranch` share the private record writer, and every writer reads through `getEnvironment`, so those three live in that module too. `environments.ts` imports and re-exports them, so they stay public. The private module imports nothing from `environments.ts`, so the dependency runs one way and the data modules still have no value-import cycles, as on main. `@bb/db/internal-environment-lifecycle` now re-exports from the new module and exports the same 4 values and 2 types as before. - `CreateProjectSourceInput` was declared, with different shapes, in both `projects.ts` and `project-sources.ts`. Star exports reject that (TS2308), and no code outside the two files used either alias, so both aliases are deleted and their one use each now names the underlying type. - The old barrel also re-exported `COMPLETED_EVENT_OUTPUT_RETENTION_MS` and `RETAINED_EVENT_OUTPUT_TARGETS` from `src/retained-event-output.ts` (not a data module). That re-export moved to `src/index.ts`. - Query-cost cases for the six moved functions are now keyed `packages/db/src/data/environment-lifecycle.ts#…`, because `listQueryFunctions` keys functions by their declaring file. Relative imports in `environments.test.ts`, `environment-lifecycle.test.ts`, and `hosts-environments-cases.ts` point at the new file. Export surface change (computed with the TypeScript checker over `src/index.ts` and `src/internal-environment-lifecycle.ts`, before vs after): - Removed: none. Every existing `@bb/db` and `@bb/db/internal-environment-lifecycle` import keeps working, so no caller changed. - Added to `@bb/db`: 230 types and 20 values that their modules already exported but the list left out. Most of the types already appear in public signatures, for example `CreateThreadInput` and `ListThreadsOptions`. The values: `ACTIVE_PENDING_INTERACTION_STATUSES`, `ACTIVE_THREAD_STATUSES`, `appendStoredThreadEventInTransaction`, `bumpThreadEventRewriteGeneration`, `copyRetainedEventOutputs`, `getContextWindowUsagePruningBoundarySequence`, `listActiveVisiblePinnedThreadRoots`, `markHostSeen`, `MAX_COMPLETED_EVENT_OUTPUT_MIGRATION_EVENT_DATA_BYTES`, `NON_TERMINAL_SESSION_STATUSES`, `prepareLegacyImageGenerationOutputData`, `PRUNABLE_THREAD_EVENT_TYPES`, `pruneContextWindowUsageEventsInTransaction`, `pruneTokenUsageEventsInTransaction`, `resolveStoredProviderSessions`, `THREAD_PRUNING_ADVANCE_WORK_BUDGET_MS`, `ThreadLifecycleEventNotAppliedError`, `toProjectSource`, `upsertThreadSearchSegmentBatch`, `upsertThreadSearchSegments`. Each is a sibling of names that were already public (for example, the plural `appendStoredThreadEventsInTransaction` and `getStoredProviderSession` were public), so hiding them was incidental, not a boundary. Alternatives rejected: - Delete the barrel and use a `@bb/db/data/*` subpath: this would rewrite imports in 451 files, conflict with every open PR, and expose the private helper modules. - Generate the barrel: this would add a Turbo task and a gitignored artifact to produce the same thing `export *` already gives. - Keep named exports but split them per module: the central-list conflicts would remain. No wire, CLI, or plugin-API change. ## How you verified - Export-surface diff before vs after with the TypeScript checker, over `src/index.ts` and `src/internal-environment-lifecycle.ts`: 0 names removed; the additions are listed above. - Import cycles: a scan of value imports among `packages/db/src/data/*.ts` finds none on main and none on this branch. - Collision safety: temporarily re-adding a duplicate type name made `tsrs --noEmit` fail with `TS2308: Module "./project-sources.js" has already exported a member named ...`, so a future clash fails typecheck instead of silently dropping a name. - `pnpm exec turbo run typecheck --filter='...@bb/db'` passed (`@bb/db`, `@bb/server`, `@bb/host-daemon`, `@bb/scripts`, `@bb/integration-tests`). - `vitest run` on `test/data/environments`, `environment-lifecycle`, `projects`, `project-sources`, and `prompt-history`: 50/50 passed. - Query-cost coverage (`listQueryFunctions` vs `QUERY_COST_CASES`): no missing cases, no stale cases. - `oxlint` on the changed files: clean. `lint:type-aware --filter=@bb/db`: passed. - CI runs the full suites. 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent f266dc1 commit 49982f7

10 files changed

Lines changed: 335 additions & 852 deletions

‎packages/db/scripts/query-costs/hosts-environments-cases.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import {
22
applyEnvironmentLifecycleEvent,
33
applyEnvironmentLifecycleEventInTransaction,
4+
recordProvisionedEnvironmentWorkspace,
5+
} from "../../src/data/environment-lifecycle.js";
6+
import {
47
bindEnvironmentPath,
58
claimEnvironmentPath,
69
createEnvironment,
@@ -16,7 +19,6 @@ import {
1619
listRetiredLoadedEnvironmentIdsOnHost,
1720
markHostEnvironmentsDestroyed,
1821
recordEnvironmentCurrentBranch,
19-
recordProvisionedEnvironmentWorkspace,
2022
releaseFinishedEnvironmentPreparationOwners,
2123
reserveEnvironment,
2224
updateEnvironmentMetadata,
@@ -121,6 +123,7 @@ import {
121123
} from "./hosts-environments-seed.js";
122124

123125
const ENVIRONMENTS = "packages/db/src/data/environments.ts";
126+
const ENVIRONMENT_LIFECYCLE = "packages/db/src/data/environment-lifecycle.ts";
124127
const HOSTS = "packages/db/src/data/hosts.ts";
125128
const MACHINES = "packages/db/src/data/machines.ts";
126129
const BACKFILL = "packages/db/src/data/project-attachment-backfill.ts";
@@ -180,15 +183,15 @@ function firstNeighborThreadId(fixture: HistoryFixture): string {
180183

181184
const ENVIRONMENT_CASES: readonly Case[] = [
182185
{
183-
name: `${ENVIRONMENTS}#updateEnvironmentMetadata`,
186+
name: `${ENVIRONMENT_LIFECYCLE}#updateEnvironmentMetadata`,
184187
run: (db, _fixture, seed) =>
185188
updateEnvironmentMetadata(db, noopNotifier, seed.readyEnvironmentId, {
186189
name: "Fix flaky deploy",
187190
mergeBaseBranch: "release",
188191
}),
189192
},
190193
{
191-
name: `${ENVIRONMENTS}#recordEnvironmentCurrentBranch`,
194+
name: `${ENVIRONMENT_LIFECYCLE}#recordEnvironmentCurrentBranch`,
192195
run: (db, _fixture, seed) =>
193196
recordEnvironmentCurrentBranch(
194197
db,
@@ -198,7 +201,7 @@ const ENVIRONMENT_CASES: readonly Case[] = [
198201
),
199202
},
200203
{
201-
name: `${ENVIRONMENTS}#recordProvisionedEnvironmentWorkspace`,
204+
name: `${ENVIRONMENT_LIFECYCLE}#recordProvisionedEnvironmentWorkspace`,
202205
prepare: (db, fixture, seed) => {
203206
preparedEnvironment = reserveFixtureEnvironment(db, fixture, seed);
204207
},
@@ -218,7 +221,7 @@ const ENVIRONMENT_CASES: readonly Case[] = [
218221
),
219222
},
220223
{
221-
name: `${ENVIRONMENTS}#applyEnvironmentLifecycleEvent`,
224+
name: `${ENVIRONMENT_LIFECYCLE}#applyEnvironmentLifecycleEvent`,
222225
run: (db, _fixture, seed) =>
223226
applyEnvironmentLifecycleEvent(db, noopNotifier, {
224227
environmentId: seed.readyEnvironmentId,
@@ -249,7 +252,7 @@ const ENVIRONMENT_CASES: readonly Case[] = [
249252
}),
250253
},
251254
{
252-
name: `${ENVIRONMENTS}#getEnvironment`,
255+
name: `${ENVIRONMENT_LIFECYCLE}#getEnvironment`,
253256
run: (db, _fixture, seed) => getEnvironment(db, seed.readyEnvironmentId),
254257
},
255258
{
@@ -298,7 +301,7 @@ const ENVIRONMENT_CASES: readonly Case[] = [
298301
}),
299302
},
300303
{
301-
name: `${ENVIRONMENTS}#applyEnvironmentLifecycleEventInTransaction`,
304+
name: `${ENVIRONMENT_LIFECYCLE}#applyEnvironmentLifecycleEventInTransaction`,
302305
run: (db, _fixture, seed) =>
303306
db.transaction((tx) =>
304307
applyEnvironmentLifecycleEventInTransaction(tx, {
Lines changed: 261 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
import { and, eq, placeholder } from "drizzle-orm";
2+
import type {
3+
DiscoveredWorkspaceProperties,
4+
EnvironmentChangeKind,
5+
EnvironmentLifecycleEvent,
6+
EnvironmentLifecycleNoopReason,
7+
} from "@bb/domain";
8+
import { evaluateEnvironmentLifecycleEvent } from "@bb/domain";
9+
import { prepareCachedQuery } from "../connection.js";
10+
import type {
11+
DbConnection,
12+
DbQueryConnection,
13+
DbTransaction,
14+
} from "../connection.js";
15+
import type { DbNotifier } from "../notifier.js";
16+
import { environments } from "../schema.js";
17+
18+
type EnvironmentRow = typeof environments.$inferSelect;
19+
type EnvironmentReadConnection = DbConnection | DbTransaction;
20+
type EnvironmentWriteConnection = DbConnection | DbTransaction;
21+
22+
const prepareGetEnvironment = (db: DbQueryConnection) =>
23+
db
24+
.select()
25+
.from(environments)
26+
.where(eq(environments.id, placeholder("id")))
27+
.prepare();
28+
29+
export function getEnvironment(db: EnvironmentReadConnection, id: string) {
30+
return prepareCachedQuery(db, prepareGetEnvironment).get({ id }) ?? null;
31+
}
32+
33+
interface EnvironmentMetadataUpdateColumns {
34+
baseBranch?: string | null;
35+
branchName?: string | null;
36+
defaultBranch?: string | null;
37+
isGitRepo?: boolean;
38+
isWorktree?: boolean;
39+
mergeBaseBranch?: string | null;
40+
name?: string | null;
41+
path?: string | null;
42+
}
43+
44+
interface EnvironmentMetadataChangeArgs {
45+
existing: EnvironmentRow;
46+
metadata: EnvironmentMetadataUpdateColumns;
47+
updated: EnvironmentRow;
48+
}
49+
50+
function buildEnvironmentMetadataUpdateSet(
51+
input: EnvironmentMetadataUpdateColumns,
52+
): EnvironmentMetadataUpdateColumns {
53+
const set: EnvironmentMetadataUpdateColumns = {};
54+
if ("baseBranch" in input) set.baseBranch = input.baseBranch;
55+
if ("path" in input) set.path = input.path;
56+
if ("isGitRepo" in input) set.isGitRepo = input.isGitRepo;
57+
if ("isWorktree" in input) set.isWorktree = input.isWorktree;
58+
if ("branchName" in input) set.branchName = input.branchName;
59+
if ("defaultBranch" in input) set.defaultBranch = input.defaultBranch;
60+
if ("mergeBaseBranch" in input) set.mergeBaseBranch = input.mergeBaseBranch;
61+
if ("name" in input) set.name = input.name;
62+
return set;
63+
}
64+
65+
function environmentMetadataChanged(
66+
args: EnvironmentMetadataChangeArgs,
67+
): boolean {
68+
return (
69+
("baseBranch" in args.metadata &&
70+
args.updated.baseBranch !== args.existing.baseBranch) ||
71+
("path" in args.metadata && args.updated.path !== args.existing.path) ||
72+
("isGitRepo" in args.metadata &&
73+
args.updated.isGitRepo !== args.existing.isGitRepo) ||
74+
("isWorktree" in args.metadata &&
75+
args.updated.isWorktree !== args.existing.isWorktree) ||
76+
("branchName" in args.metadata &&
77+
args.updated.branchName !== args.existing.branchName) ||
78+
("defaultBranch" in args.metadata &&
79+
args.updated.defaultBranch !== args.existing.defaultBranch) ||
80+
("mergeBaseBranch" in args.metadata &&
81+
args.updated.mergeBaseBranch !== args.existing.mergeBaseBranch) ||
82+
("name" in args.metadata && args.updated.name !== args.existing.name)
83+
);
84+
}
85+
86+
function updateEnvironmentMetadataRecord(
87+
db: EnvironmentWriteConnection,
88+
notifier: DbNotifier,
89+
id: string,
90+
metadataInput: EnvironmentMetadataUpdateColumns,
91+
) {
92+
const existing = getEnvironment(db, id);
93+
if (!existing) return null;
94+
95+
const metadata = buildEnvironmentMetadataUpdateSet(metadataInput);
96+
const updated = db
97+
.update(environments)
98+
.set({
99+
...metadata,
100+
updatedAt: Date.now(),
101+
})
102+
.where(eq(environments.id, id))
103+
.returning()
104+
.get();
105+
106+
if (!updated) {
107+
return null;
108+
}
109+
110+
if (environmentMetadataChanged({ existing, metadata, updated })) {
111+
notifier.notifyEnvironment(id, ["metadata-changed"]);
112+
}
113+
114+
return updated;
115+
}
116+
117+
export interface UpdateEnvironmentMetadataInput {
118+
mergeBaseBranch?: string | null;
119+
name?: string | null;
120+
}
121+
122+
export interface RecordEnvironmentCurrentBranchInput {
123+
branchName: string | null;
124+
}
125+
126+
export function updateEnvironmentMetadata(
127+
db: EnvironmentWriteConnection,
128+
notifier: DbNotifier,
129+
id: string,
130+
input: UpdateEnvironmentMetadataInput,
131+
) {
132+
return updateEnvironmentMetadataRecord(db, notifier, id, input);
133+
}
134+
135+
export function recordEnvironmentCurrentBranch(
136+
db: EnvironmentWriteConnection,
137+
notifier: DbNotifier,
138+
id: string,
139+
input: RecordEnvironmentCurrentBranchInput,
140+
) {
141+
return updateEnvironmentMetadataRecord(db, notifier, id, {
142+
branchName: input.branchName,
143+
});
144+
}
145+
146+
export interface RecordProvisionedEnvironmentWorkspaceInput extends DiscoveredWorkspaceProperties {
147+
baseBranch?: string | null;
148+
mergeBaseBranch?: string | null;
149+
}
150+
151+
export function recordProvisionedEnvironmentWorkspace(
152+
db: EnvironmentWriteConnection,
153+
notifier: DbNotifier,
154+
id: string,
155+
input: RecordProvisionedEnvironmentWorkspaceInput,
156+
) {
157+
return updateEnvironmentMetadataRecord(db, notifier, id, {
158+
path: input.path,
159+
isGitRepo: input.isGitRepo,
160+
isWorktree: input.isWorktree,
161+
branchName: input.branchName,
162+
defaultBranch: input.defaultBranch,
163+
...(input.baseBranch !== undefined ? { baseBranch: input.baseBranch } : {}),
164+
...(input.mergeBaseBranch !== undefined
165+
? { mergeBaseBranch: input.mergeBaseBranch }
166+
: {}),
167+
});
168+
}
169+
170+
export type ApplyEnvironmentLifecycleEventNoopReason =
171+
| EnvironmentLifecycleNoopReason
172+
| "not-found"
173+
| "cas-conflict";
174+
175+
export type ApplyEnvironmentLifecycleEventOutcome =
176+
| {
177+
applied: true;
178+
changes: EnvironmentChangeKind[];
179+
environment: EnvironmentRow;
180+
}
181+
| {
182+
applied: false;
183+
detail: string;
184+
reason: ApplyEnvironmentLifecycleEventNoopReason;
185+
};
186+
187+
export interface ApplyEnvironmentLifecycleEventArgs {
188+
environmentId: string;
189+
event: EnvironmentLifecycleEvent;
190+
}
191+
192+
export function applyEnvironmentLifecycleEventInTransaction(
193+
db: DbTransaction,
194+
args: ApplyEnvironmentLifecycleEventArgs,
195+
): ApplyEnvironmentLifecycleEventOutcome {
196+
const environment = getEnvironment(db, args.environmentId);
197+
if (!environment) {
198+
return {
199+
applied: false,
200+
detail: `environment not found: ${args.environmentId}`,
201+
reason: "not-found",
202+
};
203+
}
204+
205+
const evaluation = evaluateEnvironmentLifecycleEvent({
206+
environment,
207+
event: args.event,
208+
});
209+
if ("noop" in evaluation) {
210+
return {
211+
applied: false,
212+
detail: evaluation.detail,
213+
reason: evaluation.noop,
214+
};
215+
}
216+
217+
const now = Date.now();
218+
const set: Partial<typeof environments.$inferInsert> = {
219+
status: evaluation.to,
220+
updatedAt: now,
221+
};
222+
if (evaluation.to === "destroyed") {
223+
set.path = null;
224+
}
225+
226+
const updated = db
227+
.update(environments)
228+
.set(set)
229+
.where(
230+
and(
231+
eq(environments.id, args.environmentId),
232+
eq(environments.status, environment.status),
233+
),
234+
)
235+
.returning()
236+
.get();
237+
if (!updated) {
238+
return {
239+
applied: false,
240+
detail: `state changed while applying ${args.event.type} from status ${environment.status}`,
241+
reason: "cas-conflict",
242+
};
243+
}
244+
245+
return { applied: true, changes: ["status-changed"], environment: updated };
246+
}
247+
248+
export function applyEnvironmentLifecycleEvent(
249+
db: DbConnection,
250+
notifier: DbNotifier,
251+
args: ApplyEnvironmentLifecycleEventArgs,
252+
): ApplyEnvironmentLifecycleEventOutcome {
253+
const outcome = db.transaction(
254+
(tx) => applyEnvironmentLifecycleEventInTransaction(tx, args),
255+
{ behavior: "immediate" },
256+
);
257+
if (outcome.applied) {
258+
notifier.notifyEnvironment(args.environmentId, outcome.changes);
259+
}
260+
return outcome;
261+
}

0 commit comments

Comments
 (0)