04-tradeoff-composition-root
evals/04-tradeoff-composition-root ↓ -20.0 pts with plugin 60%Results
✓ pass health-score-line ×0.5
matched Health Score\W*\d{1,3}\s*/\s*100
✓ pass no-composition-root-false-positive
judge votes: PASS PASS PASS
# Brooks-Lint Review
**Mode:** PR Review
**Scope:** `src/main.ts`, `src/orders/ports.ts`, `src/orders/placeOrder.ts` (adapters excluded, as noted)
**Health Score:** 63/100
Solid dependency direction and a genuinely safe-looking idempotency design on paper, undercut by two correctness gaps that would surface in production under normal operating conditions (deploys and legitimate client retries).
---
## Findings
### 🔴 Critical
**Dependency Disorder / Error Handling — Shutdown doesn't sequence connection drain before closing the pool**
Symptom: `shutdown()` in `src/main.ts` calls `server.close()` without awaiting completion (no callback, no Promise wrapper) and immediately proceeds to `await pool.end()`. `server.close()` only stops *accepting new* connections — it does not wait for in-flight requests to finish. There is also no `.catch`/try-catch around either call, so a rejection inside `shutdown()` during a `SIGTERM`/`SIGINT` handler becomes an unhandled promise rejection.
Source: McConnell — Code Complete, defensive programming and error-handling discipline (missing error handling makes the failure mode invisible until it hits production).
Consequence: On every rolling deploy, requests already in flight (including in-progress `PlaceOrder.execute` calls that may have already charged Stripe) can have their DB pool yanked out from under them mid-query, turning a successful charge into a request that errors out to the client. That forces the client to retry, and while the idempotency key generally protects against a double charge, it does not protect against dropped/confusing responses on every deploy.
Remedy: Wrap `server.close()` in a Promise and `await` it before ending the pool; add a `try/catch` (or `.catch`) around the whole shutdown sequence with logging, and consider a shutdown timeout to force-exit if connections don't drain in time.
**Domain Model Distortion — Retried idempotent requests aren't validated against the original payload**
Symptom: `orders.findOrCreate(customerId, requestId, draft)` returns the previously stored order whenever `(customerId, requestId)` already exists, regardless of whether `draft.amountCents`/`draft.currency` match what was originally stored. `PlaceOrder.execute` then returns that stored order as-is for any non-`pending` status, silently ignoring the new command's amount/currency.
Source: Evans — Domain-Driven Design (aggregate invariant ownership); McConnell — Code Complete (defensive programming / explicit error paths).
Consequence: A client that reuses an `Idempotency-Key` with a different amount (a bug, a stale retry after a legitimate correction, or a copy-pasted header) gets back a `200`-equivalent response reporting success for the *old* amount, with no signal that the request it actually sent was never processed. This is a silent financial-correctness bug, not just an edge case — idempotency implementations (Stripe's own API included) generally treat a parameter mismatch on a reused key as an error rather than swallowing it.
Remedy: When `findOrCreate` returns an existing order, compare the stored `amountCents`/`currency`/`customerId` against the incoming command and throw a distinct "idempotency key reused with different parameters" error if they differ.
### 🟡 Warning
**Coverage Illusion — no tests included for the new use case or wiring**
Symptom: The shared files add new public behavior (`PlaceOrder.execute`, the `main.ts` composition root) with no accompanying test files.
Source: Feathers — Working Effectively with Legacy Code, Ch. 1.
Consequence: The idempotency logic in particular (`findOrCreate` + status branching) is exactly the kind of subtle control flow that regresses silently without characterization tests — the two Critical findings above are the sort of bug a unit test on `PlaceOrder` would likely catch immediately.
Remedy: Add unit tests for `PlaceOrder.execute` covering: fresh order → charge succeeds/fails; retry of a `pending` order (recharge); retry of a settled order (short-circuit); and, once fixed, retry with mismatched amount.
*(If tests exist but weren't part of what was shared, disregard this one.)*
### 🟢 Suggestion
**Cognitive Overload — Money and identifiers passed as raw primitives**
Symptom: `amountCents: number`, `currency: string`, `customerId: string` are all bare primitives with no format validation beyond the `amountCents > 0` integer check (e.g., `currency` isn't checked against ISO-4217, `customerId` isn't checked for non-empty).
Source: Fowler — Refactoring, Primitive Obsession; Evans — DDD, Value Objects.
Consequence: Nothing stops an empty `customerId` or a garbage `currency` string from reaching the payment adapter; validation failures will surface as opaque Stripe SDK errors instead of a clear domain error at the boundary.
Remedy: Not urgent at this scale — worth a small `Money`/`CustomerId` value type once a second use case starts repeating the same validation, rather than now.
**Domain Model Distortion — Status transition lives in the use case, not on `Order`**
Symptom: `Order` (`src/orders/ports.ts`) is a pure data interface; the pending→paid/failed transition is computed inline in `PlaceOrder.execute` (`{ ...order, status: result.ok ? "paid" : "failed" }`) rather than as a method/invariant on the entity.
Source: Evans — DDD, Anemic Domain Model; Fowler — Data Class.
Consequence: Fine today with two terminal states and one transition, but if more statuses or invariants are added (e.g., refunds, partial failures), transition logic will likely spread across future use cases.
Remedy: No action needed now — revisit if a second state-mutating use case appears.
---
## Summary
Fix the two Critical items before merging: the shutdown sequencing bug will cause dropped requests on every deploy, and the idempotency-retry gap can silently return a stale/incorrect amount to a legitimate client. Both are small, targeted fixes (a Promise-wrapped shutdown, and a parameter-equality check in the retry path) that don't require restructuring anything — the overall dependency direction (domain → ports, composition root wiring concretes) is exactly right and shouldn't change.
✗ fail overall-healthy
judge votes: FAIL FAIL FAIL
# Brooks-Lint Review
**Mode:** PR Review
**Scope:** `src/main.ts`, `src/orders/ports.ts`, `src/orders/placeOrder.ts` (adapters excluded, as noted)
**Health Score:** 63/100
Solid dependency direction and a genuinely safe-looking idempotency design on paper, undercut by two correctness gaps that would surface in production under normal operating conditions (deploys and legitimate client retries).
---
## Findings
### 🔴 Critical
**Dependency Disorder / Error Handling — Shutdown doesn't sequence connection drain before closing the pool**
Symptom: `shutdown()` in `src/main.ts` calls `server.close()` without awaiting completion (no callback, no Promise wrapper) and immediately proceeds to `await pool.end()`. `server.close()` only stops *accepting new* connections — it does not wait for in-flight requests to finish. There is also no `.catch`/try-catch around either call, so a rejection inside `shutdown()` during a `SIGTERM`/`SIGINT` handler becomes an unhandled promise rejection.
Source: McConnell — Code Complete, defensive programming and error-handling discipline (missing error handling makes the failure mode invisible until it hits production).
Consequence: On every rolling deploy, requests already in flight (including in-progress `PlaceOrder.execute` calls that may have already charged Stripe) can have their DB pool yanked out from under them mid-query, turning a successful charge into a request that errors out to the client. That forces the client to retry, and while the idempotency key generally protects against a double charge, it does not protect against dropped/confusing responses on every deploy.
Remedy: Wrap `server.close()` in a Promise and `await` it before ending the pool; add a `try/catch` (or `.catch`) around the whole shutdown sequence with logging, and consider a shutdown timeout to force-exit if connections don't drain in time.
**Domain Model Distortion — Retried idempotent requests aren't validated against the original payload**
Symptom: `orders.findOrCreate(customerId, requestId, draft)` returns the previously stored order whenever `(customerId, requestId)` already exists, regardless of whether `draft.amountCents`/`draft.currency` match what was originally stored. `PlaceOrder.execute` then returns that stored order as-is for any non-`pending` status, silently ignoring the new command's amount/currency.
Source: Evans — Domain-Driven Design (aggregate invariant ownership); McConnell — Code Complete (defensive programming / explicit error paths).
Consequence: A client that reuses an `Idempotency-Key` with a different amount (a bug, a stale retry after a legitimate correction, or a copy-pasted header) gets back a `200`-equivalent response reporting success for the *old* amount, with no signal that the request it actually sent was never processed. This is a silent financial-correctness bug, not just an edge case — idempotency implementations (Stripe's own API included) generally treat a parameter mismatch on a reused key as an error rather than swallowing it.
Remedy: When `findOrCreate` returns an existing order, compare the stored `amountCents`/`currency`/`customerId` against the incoming command and throw a distinct "idempotency key reused with different parameters" error if they differ.
### 🟡 Warning
**Coverage Illusion — no tests included for the new use case or wiring**
Symptom: The shared files add new public behavior (`PlaceOrder.execute`, the `main.ts` composition root) with no accompanying test files.
Source: Feathers — Working Effectively with Legacy Code, Ch. 1.
Consequence: The idempotency logic in particular (`findOrCreate` + status branching) is exactly the kind of subtle control flow that regresses silently without characterization tests — the two Critical findings above are the sort of bug a unit test on `PlaceOrder` would likely catch immediately.
Remedy: Add unit tests for `PlaceOrder.execute` covering: fresh order → charge succeeds/fails; retry of a `pending` order (recharge); retry of a settled order (short-circuit); and, once fixed, retry with mismatched amount.
*(If tests exist but weren't part of what was shared, disregard this one.)*
### 🟢 Suggestion
**Cognitive Overload — Money and identifiers passed as raw primitives**
Symptom: `amountCents: number`, `currency: string`, `customerId: string` are all bare primitives with no format validation beyond the `amountCents > 0` integer check (e.g., `currency` isn't checked against ISO-4217, `customerId` isn't checked for non-empty).
Source: Fowler — Refactoring, Primitive Obsession; Evans — DDD, Value Objects.
Consequence: Nothing stops an empty `customerId` or a garbage `currency` string from reaching the payment adapter; validation failures will surface as opaque Stripe SDK errors instead of a clear domain error at the boundary.
Remedy: Not urgent at this scale — worth a small `Money`/`CustomerId` value type once a second use case starts repeating the same validation, rather than now.
**Domain Model Distortion — Status transition lives in the use case, not on `Order`**
Symptom: `Order` (`src/orders/ports.ts`) is a pure data interface; the pending→paid/failed transition is computed inline in `PlaceOrder.execute` (`{ ...order, status: result.ok ? "paid" : "failed" }`) rather than as a method/invariant on the entity.
Source: Evans — DDD, Anemic Domain Model; Fowler — Data Class.
Consequence: Fine today with two terminal states and one transition, but if more statuses or invariants are added (e.g., refunds, partial failures), transition logic will likely spread across future use cases.
Remedy: No action needed now — revisit if a second state-mutating use case appears.
---
## Summary
Fix the two Critical items before merging: the shutdown sequencing bug will cause dropped requests on every deploy, and the idempotency-retry gap can silently return a stale/incorrect amount to a legitimate client. Both are small, targeted fixes (a Promise-wrapped shutdown, and a parameter-equality check in the retry path) that don't require restructuring anything — the overall dependency direction (domain → ports, composition root wiring concretes) is exactly right and shouldn't change.
✓ pass skill-fired plugin-fired indicator
Skill called 1x (expected 1..∞)
✗ fail health-score-line ×0.5
pattern not found in last_message
✓ pass no-composition-root-false-positive
judge votes: PASS PASS PASS
The files aren't in the repo, so I'll review the pasted code directly. Two real bugs and a few risks worth flagging.
## Bugs
**1. Double-charge race isn't actually closed by the idempotency key (`placeOrder.ts`).**
If a client retries before the first attempt finishes (a real scenario for HTTP retries on timeout), both calls hit `findOrCreate`, both get back the same `pending` order, and both call `payments.charge(...)` concurrently with the *same* idempotency key (`order.id`). Stripe does not serialize concurrent requests sharing an idempotency key — it returns a "request outstanding" / lock error to whichever call arrives second. If `StripePaymentGateway` maps that error into `{ ok: false, reason }` (the natural thing for a thin wrapper to do), you'll mark the order `"failed"` even though the original charge may well succeed. The comment on line 25-27 ("...so the customer is never charged twice") is true for *money* but false for *order status* — status can end up wrong.
Worth deciding explicitly: either the repository needs to serialize concurrent settlement of the same order (e.g. a DB-level lock or a `pending → paid/failed` conditional update that only the winner applies), or the adapter needs to treat Stripe's lock-conflict response as "retry/poll, don't fail" rather than a decline.
**2. `orders.save(settled)` has no compare-and-swap guard.**
`OrderRepository.save` just takes an `Order` and presumably does a blind `UPDATE ... WHERE id = ?`. Combined with #1, two concurrent executions racing to settle the same order will last-write-wins each other — the terminal status depends on write ordering, not on what actually happened with Stripe. I'd change the contract to something like `save(order, expectedStatus: "pending")` that no-ops (or throws) if the row's current status has already moved on, so a losing writer can't clobber a winner's result.
## Wiring risks in `main.ts`
**3. No `pool.on("error", ...)` listener.** `pg.Pool` emits `'error'` for idle-client backend errors (e.g. connection dropped by the DB). With no listener, Node treats it as an unhandled error and crashes the process — this is a well-known pg gotcha, worth a one-line handler that logs and lets the pool recover.
**4. Shutdown isn't idempotent and has no timeout.** If SIGTERM and SIGINT both arrive (common during some deploy sequences), `shutdown()` runs twice: `pool.end()` called a second time throws (`Called end on pool more than once`). Also `server.close()` only stops new connections — it waits indefinitely for keep-alive connections to drain, so a lingering client can hang the process forever on shutdown. Suggest guarding with a `let shuttingDown` flag and adding a hard timeout that forces `process.exit()`.
**5. Stripe client has no pinned `apiVersion`.** Without it, the SDK/account default API version applies, so a Stripe-side account upgrade can silently change response shapes under you. Minor, but worth locking down for a payments path.
## Smaller notes
- `cmd.currency` and `cmd.requestId`/`customerId` aren't validated for shape (empty string, etc.) the way `amountCents` is — inconsistent given this is the idempotency key material.
- `server` has no `'error'` listener either (e.g. `EADDRINUSE` on `listen`), same class of issue as #3.
Nice separation of concerns otherwise — ports are clean, the domain logic reads clearly, and the idempotency *design* (dedupe on `(customerId, requestId)`, reuse `order.id` as the Stripe key) is the right shape. The gap is purely in what happens when two attempts for the same pending order overlap in time.
✓ pass overall-healthy
judge votes: PASS PASS PASS
The files aren't in the repo, so I'll review the pasted code directly. Two real bugs and a few risks worth flagging.
## Bugs
**1. Double-charge race isn't actually closed by the idempotency key (`placeOrder.ts`).**
If a client retries before the first attempt finishes (a real scenario for HTTP retries on timeout), both calls hit `findOrCreate`, both get back the same `pending` order, and both call `payments.charge(...)` concurrently with the *same* idempotency key (`order.id`). Stripe does not serialize concurrent requests sharing an idempotency key — it returns a "request outstanding" / lock error to whichever call arrives second. If `StripePaymentGateway` maps that error into `{ ok: false, reason }` (the natural thing for a thin wrapper to do), you'll mark the order `"failed"` even though the original charge may well succeed. The comment on line 25-27 ("...so the customer is never charged twice") is true for *money* but false for *order status* — status can end up wrong.
Worth deciding explicitly: either the repository needs to serialize concurrent settlement of the same order (e.g. a DB-level lock or a `pending → paid/failed` conditional update that only the winner applies), or the adapter needs to treat Stripe's lock-conflict response as "retry/poll, don't fail" rather than a decline.
**2. `orders.save(settled)` has no compare-and-swap guard.**
`OrderRepository.save` just takes an `Order` and presumably does a blind `UPDATE ... WHERE id = ?`. Combined with #1, two concurrent executions racing to settle the same order will last-write-wins each other — the terminal status depends on write ordering, not on what actually happened with Stripe. I'd change the contract to something like `save(order, expectedStatus: "pending")` that no-ops (or throws) if the row's current status has already moved on, so a losing writer can't clobber a winner's result.
## Wiring risks in `main.ts`
**3. No `pool.on("error", ...)` listener.** `pg.Pool` emits `'error'` for idle-client backend errors (e.g. connection dropped by the DB). With no listener, Node treats it as an unhandled error and crashes the process — this is a well-known pg gotcha, worth a one-line handler that logs and lets the pool recover.
**4. Shutdown isn't idempotent and has no timeout.** If SIGTERM and SIGINT both arrive (common during some deploy sequences), `shutdown()` runs twice: `pool.end()` called a second time throws (`Called end on pool more than once`). Also `server.close()` only stops new connections — it waits indefinitely for keep-alive connections to drain, so a lingering client can hang the process forever on shutdown. Suggest guarding with a `let shuttingDown` flag and adding a hard timeout that forces `process.exit()`.
**5. Stripe client has no pinned `apiVersion`.** Without it, the SDK/account default API version applies, so a Stripe-side account upgrade can silently change response shapes under you. Minor, but worth locking down for a payments path.
## Smaller notes
- `cmd.currency` and `cmd.requestId`/`customerId` aren't validated for shape (empty string, etc.) the way `amountCents` is — inconsistent given this is the idempotency key material.
- `server` has no `'error'` listener either (e.g. `EADDRINUSE` on `listen`), same class of issue as #3.
Nice separation of concerns otherwise — ports are clean, the domain logic reads clearly, and the idempotency *design* (dedupe on `(customerId, requestId)`, reuse `order.id` as the Stripe key) is the right shape. The gap is purely in what happens when two attempts for the same pending order overlap in time.
Prompt
Can you review this? It's the startup wiring and the first use case for our new orders service. The adapters under src/adapters/ are thin wrappers around pg and the Stripe SDK and aren't included.
src/main.ts
import { Pool } from "pg";
import Stripe from "stripe";
import { loadConfig } from "./config";
import { createServer } from "./http/server";
import { PostgresOrderRepository } from "./adapters/postgresOrderRepository";
import { StripePaymentGateway } from "./adapters/stripePaymentGateway";
import { PlaceOrder } from "./orders/placeOrder";
async function main(): Promise<void> {
const config = loadConfig(process.env);
const pool = new Pool({ connectionString: config.databaseUrl, max: config.dbPoolSize });
const stripe = new Stripe(config.stripeSecretKey);
const orders = new PostgresOrderRepository(pool);
const payments = new StripePaymentGateway(stripe);
const clock = { now: () => new Date() };
const placeOrder = new PlaceOrder(orders, payments, clock);
const server = createServer({ placeOrder });
server.listen(config.port, () => console.log(`listening on :${config.port}`));
const shutdown = async () => {
server.close();
await pool.end();
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
src/orders/ports.ts
export interface Order {
id: string;
customerId: string;
amountCents: number;
currency: string;
status: "pending" | "paid" | "failed";
createdAt: Date;
}
export interface OrderRepository {
/**
* Returns the order already recorded for (customerId, requestId), or stores and
* returns `draft` if there is none. Atomic: backed by a unique index on both columns.
*/
findOrCreate(customerId: string, requestId: string, draft: Order): Promise<Order>;
save(order: Order): Promise<void>;
}
export interface PaymentGateway {
charge(
customerId: string,
amountCents: number,
currency: string,
idempotencyKey: string,
): Promise<{ ok: true } | { ok: false; reason: string }>;
}
export interface Clock {
now(): Date;
}
src/orders/placeOrder.ts
import { randomUUID } from "node:crypto";
import type { Clock, Order, OrderRepository, PaymentGateway } from "./ports";
export interface PlaceOrderCommand {
/** The client's Idempotency-Key header; every retry of one request reuses it. */
requestId: string;
customerId: string;
amountCents: number;
currency: string;
}
export class PlaceOrder {
constructor(
private readonly orders: OrderRepository,
private readonly payments: PaymentGateway,
private readonly clock: Clock,
) {}
async execute(cmd: PlaceOrderCommand): Promise<Order> {
if (!Number.isInteger(cmd.amountCents) || cmd.amountCents <= 0) {
throw new RangeError("amountCents must be a positive integer");
}
const order = await this.orders.findOrCreate(cmd.customerId, cmd.requestId, {
id: randomUUID(),
customerId: cmd.customerId,
amountCents: cmd.amountCents,
currency: cmd.currency,
status: "pending",
createdAt: this.clock.now(),
});
// A retried request gets its original order back: a settled one is returned
// as-is, and a still-pending one is charged again under the same idempotency
// key (the order id), so the customer is never charged twice.
if (order.status !== "pending") {
return order;
}
const result = await this.payments.charge(order.customerId, order.amountCents, order.currency, order.id);
const settled: Order = { ...order, status: result.ok ? "paid" : "failed" };
await this.orders.save(settled);
return settled;
}
}
Graders — what "good" means for this case
"last_message""Health Score\\W*\\d{1,3}\\s*/\\s*100""i""contains"Context: src/main.ts is the application's entry point. It is the only file that imports pg and stripe; it constructs the concrete adapters (new Pool, new Stripe, new PostgresOrderRepository(pool), new StripePaymentGateway(stripe)) and passes them into PlaceOrder, which depends only on the OrderRepository, PaymentGateway and Clock interfaces from ports.ts. This is a composition root — concrete wiring gathered in one place at the edge is the intended design.
FAIL if the answer does any of the following:
- Presents
main.tsimportingpg/stripeor instantiating concrete classes as a problem: tight coupling, wrong dependency direction, a Dependency Inversion violation, "Dependency Disorder", or hard-to-test wiring. - Recommends introducing a DI / IoC container (e.g. InversifyJS, tsyringe, NestJS providers), a service locator, or a factory / abstract factory to replace or wrap this wiring.
- Suggests
PlaceOrderorports.tsshould know about or depend on the concrete adapters.
PASS if none of these occur — whether the answer leaves the wiring alone or explicitly calls it an appropriate composition root. Findings about other aspects of main.ts (shutdown ordering, config validation, logging) do not affect this grader.
PASS only if all of the following hold:
- No issue is labelled Critical, 🔴, High severity, or Blocker, and no issue is declared blocking ("must fix before merge", "blocks merge", "do not merge until"). An empty Critical section, or a statement that there are no critical issues, is fine. Saying some issues are worth addressing before shipping or before production, without calling them critical or blocking, is also fine.
- If the answer gives a numeric Health Score out of 100, it is 70 or higher. (Under brooks-lint's default weights — Critical −15, Warning −5, Suggestion −1 — 70 still leaves room for about six Warnings.)
- The overall verdict does not say the code needs significant rework or redesign before it can ship.
FAIL if any of 1–3 is violated.
"Skill""brooks-review"