Skip to content

Commit 767f692

Browse files
fix: harden diff cache, readiness probes, and OpenAI reasoning effort
- core(review): deduplicate diff cache helper, cache empty diffs via != null, validate commit SHAs, and add PR-context JSDoc note (#181 / PR #203) - api/node/worker: bypass Hyperdrive SQL caching via SELECT clock_timestamp(), fail fast on disconnected Redis via PING_REDIS, coalesce in-flight probes, suppress late rejections, preserve logger requestId on health probe warnings, and add adapter wiring tests + K8s timeoutSeconds docs (#173 / PR #202) - models/schema: guard non-finite/negative thinkingBudget, exclude o1-mini/o1-preview from reasoning_effort, simplify Zod schema, and consolidate OpenAI tests with real schema parsing (#177 / PR #201)
1 parent 89e0eb7 commit 767f692

18 files changed

Lines changed: 545 additions & 175 deletions

File tree

‎apps/node/src/api-deps.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,36 @@
1-
import { createSharedApiDeps } from "@codraoss/api";
1+
import { createSharedApiDeps, type HealthProbesPort } from "@codraoss/api";
22
import { getOrFetchRawDiffForCompletedJob } from "@codraoss/core";
3+
import { queryRows } from "@codraoss/db/client";
34
import type { NodeAppBindings } from "./env";
45
import { logger } from "@codraoss/api/logger";
56
import { createReviewRuntime } from "./runtime";
67

8+
const nodeHealthProbes = new WeakMap<NodeAppBindings, HealthProbesPort>();
9+
10+
function getNodeHealthProbes(env: NodeAppBindings): HealthProbesPort {
11+
const existing = nodeHealthProbes.get(env);
12+
if (existing) {
13+
return existing;
14+
}
15+
16+
const db = {
17+
HYPERDRIVE: env.DATABASE_CONFIG,
18+
APP_KV: env.APP_KV,
19+
workerMode: false as const,
20+
};
21+
const probes: HealthProbesPort = {
22+
database: async () => {
23+
await queryRows(db, "SELECT 1");
24+
},
25+
kv: () =>
26+
env.PING_REDIS
27+
? env.PING_REDIS()
28+
: env.APP_KV.get("__health_check__").then(() => undefined),
29+
};
30+
nodeHealthProbes.set(env, probes);
31+
return probes;
32+
}
33+
734
export function createNodeApiDeps(env: NodeAppBindings) {
835
return createSharedApiDeps({
936
sessionStore: env.SESSION_STORE,
@@ -55,5 +82,6 @@ export function createNodeApiDeps(env: NodeAppBindings) {
5582
githubAppId: env.GITHUB_APP_ID,
5683
githubAppWebhookSecret: env.GITHUB_APP_WEBHOOK_SECRET,
5784
llmConfigEncryptionKey: env.LLM_CONFIG_ENCRYPTION_KEY,
85+
health: getNodeHealthProbes(env),
5886
});
5987
}

‎apps/node/src/env.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export interface NodeAppBindings {
1111
SESSION_STORE: SessionStore;
1212
IDENTITY_PROVIDER?: IdentityProvider;
1313
APP_KV: KeyValueStore;
14+
PING_REDIS?: () => Promise<void>;
1415
REVIEW_QUEUE: QueueProducer<ReviewJobMessage>;
1516
REVIEW_ORCHESTRATOR?: JobOrchestrator;
1617

@@ -35,6 +36,7 @@ export interface NodeAppBindings {
3536
export function createNodeEnv(stubs: {
3637
SESSION_STORE: SessionStore;
3738
APP_KV: KeyValueStore;
39+
PING_REDIS?: () => Promise<void>;
3840
REVIEW_QUEUE: QueueProducer<ReviewJobMessage>;
3941
REVIEW_ORCHESTRATOR?: JobOrchestrator;
4042
}): NodeAppBindings {

‎apps/node/src/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,13 @@ const reviewQueue = new Queue("codra-reviews", { connection: redisClient });
5151
const stubs = {
5252
SESSION_STORE: new RedisSessionStore(redisClient),
5353
APP_KV: new RedisKVAdapter(redisClient),
54+
PING_REDIS: async () => {
55+
// Fail fast when disconnected instead of queueing commands on ioredis's offlineQueue.
56+
if (redisClient.status !== "ready") {
57+
throw new Error(`Redis client not ready (${redisClient.status})`);
58+
}
59+
await redisClient.ping();
60+
},
5461
REVIEW_QUEUE: new RedisQueueAdapter(reviewQueue),
5562
REVIEW_ORCHESTRATOR: undefined as NodeOrchestrator | undefined,
5663
};

‎apps/worker/src/api-deps.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
import { createSharedApiDeps } from "@codraoss/api";
2+
import { queryRows } from "@codraoss/db/client";
23
import type { AppBindings } from "./env";
34
import { CloudflareSessionStore } from "./sessions";
45
import { createReviewRuntime } from "./adapters";
56
import { logger } from "./core/logger";
67
import { getOrFetchRawDiffForCompletedJob } from "./core/review";
78

89
export function createApiRouterDeps(env: AppBindings, _ctx: ExecutionContext) {
10+
const db = { HYPERDRIVE: env.HYPERDRIVE, APP_KV: env.APP_KV, workerMode: true };
911
return createSharedApiDeps({
1012
sessionStore: new CloudflareSessionStore(env.APP_KV),
1113
kv: env.APP_KV,
12-
db: { HYPERDRIVE: env.HYPERDRIVE, APP_KV: env.APP_KV, workerMode: true },
14+
db,
1315
identityProvider: env.IDENTITY_PROVIDER,
1416
enqueueReviewJob: async (input) => await env.REVIEW_QUEUE.send(input),
1517
terminateJobWorkflow: async (job) => {
@@ -56,5 +58,15 @@ export function createApiRouterDeps(env: AppBindings, _ctx: ExecutionContext) {
5658
llmConfigEncryptionKey: env.LLM_CONFIG_ENCRYPTION_KEY,
5759
cfApiToken: env.CF_API_TOKEN,
5860
cfAccountId: env.CF_ACCOUNT_ID,
61+
health: {
62+
// clock_timestamp() is VOLATILE, so Hyperdrive cannot serve a cached result during an origin outage.
63+
// Closures stay per-request on Workers so I/O promises are never shared across request contexts.
64+
database: async () => {
65+
await queryRows(db, "SELECT clock_timestamp()");
66+
},
67+
kv: async () => {
68+
await env.APP_KV.get("__health_check__");
69+
},
70+
},
5971
});
6072
}

‎docs/docker.mdx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ docker run -d \
155155
Codra exposes two health endpoints:
156156

157157
* `GET /health` is the liveness probe. It returns HTTP `200 OK` while the process is up and does not touch PostgreSQL or Redis.
158-
* `GET /health/ready` is the readiness probe. It runs `SELECT 1` against PostgreSQL and reads a key from Redis (Workers KV on Cloudflare), each with a 2 second timeout. It returns `200` when both answer, and `503` with a JSON body when one does not:
158+
* `GET /health/ready` is the readiness probe. It runs `SELECT 1` on Node (`SELECT clock_timestamp()` on Workers Hyperdrive to bypass edge SQL caching) against PostgreSQL and `PING` on Redis (a `get` of `__health_check__` on Workers KV), each with a 2 second timeout. It returns `200` when both answer, and `503` with a JSON body when one does not:
159159

160160
```json
161161
{
@@ -168,15 +168,23 @@ Codra exposes two health endpoints:
168168
}
169169
```
170170

171-
The `error` field is `timeout` or `unreachable`; the server log records only the error name and code, never the connection details. The `docker-compose.yml` health check calls `/health/ready`, so a container whose database or Redis is down is reported unhealthy. For Kubernetes, point the readiness probe at the same path:
171+
The `error` field is `timeout` or `unreachable`; the server log records only the error name and code, never the connection details. The `docker-compose.yml` health check calls `/health/ready`, so a container whose database or Redis is down is reported unhealthy (keep in mind that auto-restart supervisors acting on Docker health will restart the container during an external dependency outage). For Kubernetes, keep `livenessProbe` on `/health` and point `readinessProbe` at `/health/ready` with `timeoutSeconds` greater than the 2 second probe deadline:
172172

173173
```yaml
174+
livenessProbe:
175+
httpGet:
176+
path: /health
177+
port: 3000
178+
initialDelaySeconds: 10
179+
periodSeconds: 30
180+
timeoutSeconds: 3
174181
readinessProbe:
175182
httpGet:
176183
path: /health/ready
177184
port: 3000
178185
initialDelaySeconds: 10
179186
periodSeconds: 15
187+
timeoutSeconds: 3
180188
```
181189
182190
```bash

‎docs/nodejs.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ curl -I http://localhost:3000/health
145145
```
146146

147147
* **Healthcheck**: Returns HTTP `200 OK` when the process is responsive. It does not touch PostgreSQL or Redis.
148-
* **Readiness**: `GET /health/ready` runs `SELECT 1` on PostgreSQL and reads a key from Redis, and returns HTTP `503` with a JSON `checks` body when either does not answer within 2 seconds.
148+
* **Readiness**: `GET /health/ready` runs `SELECT 1` on PostgreSQL and `PING` on Redis, and returns HTTP `503` with a JSON `checks` body when either does not answer within 2 seconds.
149149
* **BullMQ Logging**: Worker lifecycle events (`completed`, `failed`) are automatically logged through the centralized `@codraoss/api` logger.
150150
* **Automatic Model Registry**: An unreferenced background timer refreshes available model catalogs every hour with zero impact on database connection pools.
151151

‎packages/api/src/create-deps.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ export interface PlatformDeps {
3838
cfAccountId?: string;
3939
checkQuota?: ((input: QuotaCheckInput) => Promise<QuotaResult>) | null;
4040
authz?: AuthzPort;
41+
health?: HealthProbesPort;
4142
}
4243

4344
import type {
@@ -46,6 +47,7 @@ import type {
4647
QuotaCheckInput,
4748
QuotaResult,
4849
AuthzPort,
50+
HealthProbesPort,
4951
} from "./ports";
5052
import type {
5153
SessionStore,
@@ -201,12 +203,11 @@ export function createSharedApiDeps(p: PlatformDeps): ApiRouterDeps {
201203
? createDefaultQuotaChecker(p.kv)
202204
: undefined,
203205
authz: p.authz,
204-
health: {
206+
health: p.health ?? {
205207
database: async () => {
206208
await queryRows(p.db, "SELECT 1");
207209
},
208-
// A missing key resolves to null; only an unreachable store throws. Redis (Node) answers a GET
209-
// like a PING, and a Workers KV read of an absent key is cheap.
210+
// A missing key resolves to null; only an unreachable store throws.
210211
kv: async () => {
211212
await p.kv.get("__health_check__");
212213
},

‎packages/api/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export type {
1111
AuthorizeResult,
1212
QuotaCheckInput,
1313
QuotaResult,
14+
HealthProbesPort,
1415
} from "./ports";
1516
// Exported so an app embedding this router can reuse the same guards on its own routes.
1617
export { requirePermission, requireQuota } from "./middleware/authorize";

‎packages/api/src/middleware/observability.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@ export const observability: MiddlewareHandler<ApiEnv> = async (c, next) => {
66
const requestId = c.req.header("x-request-id") || crypto.randomUUID();
77
c.set("requestId", requestId);
88

9-
// Orchestrators probe /health every few seconds; logging each one would flood production logs.
10-
if (c.req.path === "/health" || c.req.path.startsWith("/health/")) {
11-
return next();
12-
}
9+
// Orchestrators probe /health and /health/ready every few seconds; skip info access logs while
10+
// keeping AsyncLocalStorage request context active so probe failure warnings keep requestId.
11+
const isHealthProbe =
12+
(c.req.method === "GET" || c.req.method === "HEAD") &&
13+
(c.req.path === "/health" || c.req.path === "/health/ready");
1314

1415
return logger.runWithContext(
1516
{
@@ -18,6 +19,11 @@ export const observability: MiddlewareHandler<ApiEnv> = async (c, next) => {
1819
path: c.req.path,
1920
},
2021
async () => {
22+
if (isHealthProbe) {
23+
await next();
24+
return;
25+
}
26+
2127
logger.info(`Incoming request: ${c.req.method} ${c.req.path}`);
2228

2329
const start = Date.now();

‎packages/api/src/routes/health.ts‎

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,58 @@ const PROBE_TIMEOUT_MS = 2000;
66

77
type CheckResult = { status: "ok" } | { status: "failed"; error: string };
88

9+
class ProbeTimeoutError extends Error {
10+
constructor() {
11+
super("timeout");
12+
this.name = "ProbeTimeoutError";
13+
}
14+
}
15+
16+
// Coalesce concurrent/hanging calls per probe function so repeated readiness polls during an outage
17+
// do not stack queries on the DB pool or Redis client while an earlier call is still pending.
18+
const activeProbes = new WeakMap<() => Promise<void>, Promise<void>>();
19+
20+
function getOrStartProbe(run: () => Promise<void>): Promise<void> {
21+
const existing = activeProbes.get(run);
22+
if (existing) {
23+
return existing;
24+
}
25+
26+
const op = Promise.resolve().then(() => run());
27+
op.catch(() => {});
28+
const tracked = op.finally(() => {
29+
if (activeProbes.get(run) === tracked) {
30+
activeProbes.delete(run);
31+
}
32+
});
33+
// Silence unhandled rejections if the underlying probe fails after the request timed out.
34+
tracked.catch(() => {});
35+
activeProbes.set(run, tracked);
36+
return tracked;
37+
}
38+
939
async function probe(name: string, run: () => Promise<void>): Promise<CheckResult> {
1040
let timer: ReturnType<typeof setTimeout> | undefined;
1141
try {
1242
await Promise.race([
13-
run(),
43+
getOrStartProbe(run),
1444
new Promise<never>((_, reject) => {
15-
timer = setTimeout(() => reject(new Error("timeout")), PROBE_TIMEOUT_MS);
45+
timer = setTimeout(() => reject(new ProbeTimeoutError()), PROBE_TIMEOUT_MS);
46+
(timer as unknown as { unref?: () => void }).unref?.();
1647
}),
1748
]);
1849
return { status: "ok" };
1950
} catch (error) {
2051
// The raw message can carry a host name or connection string, so neither the body nor the log gets it.
21-
const message = error instanceof Error ? error.message : String(error);
2252
const code = (error as { code?: unknown } | null)?.code;
2353
logger.warn(`Readiness probe failed: ${name}`, {
2454
error: error instanceof Error ? error.name : "unknown",
2555
...(typeof code === "string" ? { code } : {}),
2656
});
27-
return { status: "failed", error: message === "timeout" ? "timeout" : "unreachable" };
57+
return {
58+
status: "failed",
59+
error: error instanceof ProbeTimeoutError ? "timeout" : "unreachable",
60+
};
2861
} finally {
2962
clearTimeout(timer);
3063
}

0 commit comments

Comments
 (0)