Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Hosted Jev follow-up: a stalled Redis never holds ⌘B, early hang-ups ask nothing (#1177)

Dee6f850be68ce0
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index eaca88551..6c4aeab37 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -214,8 +214,9 @@ const envSchema = z.object({
// (routes/jevRoute.ts). Optional here, but the route fails CLOSED without it. Give it its own key with
// a credit limit on OpenRouter: that limit is the budget, the route's per-account caps only spread it.
JEV_OPENROUTER_API_KEY: z.string().optional(),
- // Decisions a day across every account, on top of each account's own cap: at ~$0.00017 each, the default is
- // about $34 a day. Past it ⌘B says Harness's Jev budget has run out until the next UTC day.
+ // Decisions a day across every account, on top of each account's own cap: at an average ⌘B (~$0.00017),
+ // the default is about $34 a day. A decision at the route's size bounds costs several times that, so the
+ // key's OpenRouter credit limit stays the hard cap. Past it ⌘B says Harness's Jev budget has run out until the next UTC day.
JEV_DAILY_DECISIONS: z.coerce.number().int().positive().default(200_000),
// TTL for the in-memory subdomain→machineId cache on the public app-proxy hot path
diff --git a/backend/src/lib/bus.test.ts b/backend/src/lib/bus.test.ts
index f000f321e..3126bb45f 100644
--- a/backend/src/lib/bus.test.ts
+++ b/backend/src/lib/bus.test.ts
@@ -39,6 +39,17 @@ vi.mock('ioredis', () => {
get = vi.fn(async (_key: string): Promise<string | null> => null)
pipelines: FakePipeline[] = []
pipeline() { const p = new FakePipeline(); this.pipelines.push(p); return p }
+ multiCalls: Array<{ cmd: string; args: unknown[] }> = []
+ multiResult: unknown = [[null, 'OK'], [null, 1]]
+ multi() {
+ const calls = this.multiCalls, result = () => this.multiResult
+ const m = {
+ set: (...args: unknown[]) => { calls.push({ cmd: 'set', args }); return m },
+ incr: (...args: unknown[]) => { calls.push({ cmd: 'incr', args }); return m },
+ exec: async () => result(),
+ }
+ return m
+ }
opts: unknown
constructor(_url: string, opts: unknown) { this.opts = opts; state.instances.push(this) }
}
@@ -56,6 +67,7 @@ type MockFn = ReturnType<typeof vi.fn>
const pub = state.instances[0] as unknown as {
publish: MockFn; subscribe: MockFn; opts: unknown
eval: MockFn; get: MockFn
+ multiCalls: Array<{ cmd: string; args: unknown[] }>; multiResult: unknown
pipelines: Array<{ calls: Array<{ cmd: string; args: unknown[] }> }>
}
@@ -187,3 +199,23 @@ describe('consumeNewIdQuota', () => {
expect(await bus.consumeNewIdQuota('device', 'u1')).toBe(true)
})
})
+
+describe('redisCount', () => {
+ beforeEach(() => { pub.multiCalls.length = 0; pub.multiResult = [[null, 'OK'], [null, 1]] })
+
+ it('starts a window once, with its expiry, and counts in it', async () => {
+ pub.multiResult = [[null, null], [null, 7]]
+ expect(await bus.redisCount('jev:m:u1:42', 60_000)).toBe(7)
+ expect(pub.multiCalls).toEqual([
+ { cmd: 'set', args: ['jev:m:u1:42', '0', 'PX', 60_000, 'NX'] },
+ { cmd: 'incr', args: ['jev:m:u1:42'] },
+ ])
+ })
+
+ it('throws when the count did not happen, so the caller counts elsewhere', async () => {
+ pub.multiResult = [[null, 'OK'], [new Error('READONLY'), null]]
+ await expect(bus.redisCount('k', 1_000)).rejects.toThrow('READONLY')
+ pub.multiResult = null
+ await expect(bus.redisCount('k', 1_000)).rejects.toThrow('redis count failed')
+ })
+})
diff --git a/backend/src/routes/jevRoute.test.ts b/backend/src/routes/jevRoute.test.ts
index 9d728b1d8..7a0d28d17 100644
--- a/backend/src/routes/jevRoute.test.ts
+++ b/backend/src/routes/jevRoute.test.ts
@@ -189,6 +189,21 @@ describe('POST /api/route/jev', () => {
expect((await post(app, body())).statusCode).toBe(429)
})
+ it('does not wait on a stalled shared count, and leaves it alone for a while after', async () => {
+ jevSays(good)
+ const error = vi.spyOn(logger, 'error').mockImplementation(() => logger)
+ const stalled = vi.fn<JevCounter>(() => new Promise(() => {}))
+ const app = await build(stalled)
+ const started = Date.now()
+ expect((await post(app, body())).statusCode).toBe(200)
+ // One stalled count, then this process's own: well inside the CLI's 8 s.
+ expect(Date.now() - started).toBeLessThan(2_000)
+ expect(stalled).toHaveBeenCalledTimes(1)
+ expect((await post(app, body())).statusCode).toBe(200)
+ expect(stalled).toHaveBeenCalledTimes(1)
+ expect(error.mock.calls.filter(([line]) => String(line).includes('shared count failed'))).toHaveLength(1)
+ })
+
it('never logs the words', async () => {
const lines: unknown[] = []
for (const level of ['info', 'error', 'warn', 'debug'] as const) {
diff --git a/backend/src/routes/jevRoute.ts b/backend/src/routes/jevRoute.ts
index 8bc00c586..5c5768c62 100644
--- a/backend/src/routes/jevRoute.ts
+++ b/backend/src/routes/jevRoute.ts
@@ -24,7 +24,7 @@
* spend everyone's share: a person presses ⌘B, a loop does not. The caps count in Redis, shared by every
* process and pod; a process-local count would multiply by both and reset on every deploy.
*/
-import type { FastifyInstance } from 'fastify'
+import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
import { z } from 'zod'
import { env } from '../config/env.js'
import { validateBody } from '../middlewares/validation.js'
@@ -50,6 +50,11 @@ const MAX_INSTRUCTION_CHARS = 1_500
/** Bytes, for a request at those bounds in any script: enforced before the body is parsed. */
const MAX_BODY_BYTES = 512 * 1024
+/** A shared count slower than this is a stalled Redis: three in a row must still leave the CLI its 8 s. */
+const SHARED_COUNT_MS = 300
+/** After one fails, count in this process for this long before trying the shared count again. */
+const SHARED_RETRY_MS = 10_000
+
/** Per account: a burst of quick ⌘B presses passes, a client in a loop does not get far. */
const MINUTE_MS = 60_000
const PER_MINUTE = 30
@@ -155,11 +160,25 @@ export async function jevRouteRoutes(app: FastifyInstance, options: JevRouteOpti
const now = options.now ?? Date.now
const local = localJevCounter(now)
const shared = options.count ?? local
- // Redis down must not mean uncapped: count in this process until it answers again.
- const count: JevCounter = (key, ttlMs) => shared(key, ttlMs).catch((err: unknown) => {
- logger.error('jev-route: shared count failed, counting in this process', { error: err instanceof Error ? err.message : String(err) })
- return local(key, ttlMs)
- })
+ // Redis down or stalled must mean neither uncapped nor a ⌘B that waits on it: count in this process, and
+ // try the shared count again a little later (one log line per failure, not three per request).
+ let sharedAfter = 0
+ const count: JevCounter = async (key, ttlMs) => {
+ if (now() < sharedAfter) return local(key, ttlMs)
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([
+ shared(key, ttlMs),
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(`no answer in ${SHARED_COUNT_MS} ms`)), SHARED_COUNT_MS) }),
+ ])
+ } catch (err) {
+ sharedAfter = now() + SHARED_RETRY_MS
+ logger.error('jev-route: shared count failed, counting in this process', { error: err instanceof Error ? err.message : String(err) })
+ return local(key, ttlMs)
+ } finally {
+ clearTimeout(timer)
+ }
+ }
app.post<{ Body: JevBody }>(JEV_ROUTE_PATH, { bodyLimit: MAX_BODY_BYTES, preHandler: [validateBody(jevBodySchema)] }, async (req, reply) => {
// Fail CLOSED: an absent key must never read as "decide some other way" on a path that spends credit.
@@ -168,6 +187,20 @@ export async function jevRouteRoutes(app: FastifyInstance, options: JevRouteOpti
sendError(reply, 'Jev is not set up on this server', 'JEV_NOT_CONFIGURED', 503)
return
}
+ // A caller that hangs up has nobody waiting on the answer: do not start, or stop paying for, its decision.
+ // The daemon's own gateway holds its connection open for up to 20 s, so for ⌘B the real bound is
+ // TIMEOUT_MS below; this is for a caller that does hang up.
+ const gone = new AbortController()
+ const onClose = () => { if (!reply.raw.writableFinished) gone.abort() }
+ reply.raw.once('close', onClose)
+ try {
+ await decide(req, reply, gone.signal)
+ } finally {
+ reply.raw.off('close', onClose)
+ }
+ })
+
+ async function decide(req: FastifyRequest<{ Body: JevBody }>, reply: FastifyReply, gone: AbortSignal): Promise<void> {
const userId = req.user?.sub ?? ''
const over = await jevAllowance(count, userId, now(), env.JEV_DAILY_DECISIONS)
if (over === 'account') {
@@ -180,16 +213,13 @@ export async function jevRouteRoutes(app: FastifyInstance, options: JevRouteOpti
return
}
+ if (gone.aborted) return
const started = Date.now()
const { state, questions } = req.body
- // A CLI that gave up has nobody waiting on the answer: stop paying for it.
- const gone = new AbortController()
- const onClose = () => { if (!reply.raw.writableFinished) gone.abort() }
- reply.raw.once('close', onClose)
try {
const res = await fetch(ENDPOINT, {
method: 'POST',
- signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), gone.signal]),
+ signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), gone]),
headers: {
Authorization: `Bearer ${env.JEV_OPENROUTER_API_KEY}`,
'Content-Type': 'application/json',
@@ -228,10 +258,8 @@ export async function jevRouteRoutes(app: FastifyInstance, options: JevRouteOpti
})
sendSuccess(reply, { answers })
} catch (err) {
- logger.error('jev-route failed', { userId, ms: Date.now() - started, gone: gone.signal.aborted, error: err instanceof Error ? err.name : String(err) })
+ logger.error('jev-route failed', { userId, ms: Date.now() - started, gone: gone.aborted, error: err instanceof Error ? err.name : String(err) })
sendError(reply, 'Jev did not answer', 'JEV_UNAVAILABLE', 502)
- } finally {
- reply.raw.off('close', onClose)
}
- })
+ }
}
diff --git a/cli/src/lib/jev/jevClient.spec.ts b/cli/src/lib/jev/jevClient.spec.ts
index fffcbf080..1bceaed0c 100644
--- a/cli/src/lib/jev/jevClient.spec.ts
+++ b/cli/src/lib/jev/jevClient.spec.ts
@@ -221,6 +221,7 @@ describe("asking Jev on Harness's key", () => {
[504, { success: false, error: { code: 'BACKEND_TIMEOUT' } }, 'UNAVAILABLE', "Harness's server did not answer in time"],
[502, { success: false, error: { code: 'BACKEND_UNREACHABLE' } }, 'UNAVAILABLE', "Harness's server cannot be reached"],
[503, { error: 'SERVICE_UNAVAILABLE' }, 'UNAVAILABLE', "Harness's server cannot be reached"],
+ [503, { error: 'GATEWAY_UNAVAILABLE' }, 'UNAVAILABLE', "Harness's server cannot be reached"],
[404, {}, 'UNAVAILABLE', "Harness's server cannot decide yet"],
[503, { success: false, error: { code: 'JEV_NOT_CONFIGURED' } }, 'UNAVAILABLE', "Harness's server answered 503"],
[502, { error: 7 }, 'UNAVAILABLE', "Harness's server answered 502"],
@@ -239,7 +240,9 @@ describe("asking Jev on Harness's key", () => {
const asked = decide(never)(STATE, QUESTIONS, caller.signal)
caller.abort(new Error('the window closed'))
await expect(asked).rejects.toThrow('the window closed')
- // Already gone before it asked.
- await expect(decide(never)(STATE, QUESTIONS, caller.signal)).rejects.toThrow('the window closed')
+ // Already gone before it asked: nothing is asked, so nothing is paid for.
+ const unasked = vi.fn<AccountBackend>(() => new Promise(() => {}))
+ await expect(decide(unasked)(STATE, QUESTIONS, caller.signal)).rejects.toThrow('the window closed')
+ expect(unasked).not.toHaveBeenCalled()
})
})
diff --git a/cli/src/lib/jev/jevClient.ts b/cli/src/lib/jev/jevClient.ts
index 1d3f5b330..d40deb5a8 100644
--- a/cli/src/lib/jev/jevClient.ts
+++ b/cli/src/lib/jev/jevClient.ts
@@ -89,7 +89,7 @@ function hostedRefusal(status: number, code: string | undefined): JevUnavailable
if (code === 'JEV_CREDITS') return new JevUnavailable('CREDITS', "Harness's Jev budget has run out")
if (code === 'JEV_BUSY') return new JevUnavailable('BUSY', 'Jev is busy')
if (code === 'BACKEND_TIMEOUT') return new JevUnavailable('UNAVAILABLE', "Harness's server did not answer in time")
- if (code === 'BACKEND_UNREACHABLE' || code === 'SERVICE_UNAVAILABLE') return new JevUnavailable('UNAVAILABLE', "Harness's server cannot be reached")
+ if (code === 'BACKEND_UNREACHABLE' || code === 'SERVICE_UNAVAILABLE' || code === 'GATEWAY_UNAVAILABLE') return new JevUnavailable('UNAVAILABLE', "Harness's server cannot be reached")
// An older backend, before the route: the CLI self-updates on its own schedule and can arrive first.
if (status === 404) return new JevUnavailable('UNAVAILABLE', "Harness's server cannot decide yet")
return new JevUnavailable('UNAVAILABLE', `Harness's server answered ${status}`)
@@ -119,6 +119,8 @@ export function createJevDecide(options: {
const abort = signal ? AbortSignal.any([signal, timeout]) : timeout
if (!key) {
if (!options.backend) throw new JevUnavailable('NO_KEY', 'no OpenRouter key on this computer')
+ // Nobody waiting already: ask nothing, since an asked decision is paid for whether or not it is read.
+ if (abort.aborted) throw abort.reason
const answer = await bounded(options.backend('POST', HOSTED_JEV_PATH, { state, questions }), abort)
if (answer.status !== 200) throw hostedRefusal(answer.status, errorCode(answer.body))
return readAnswers((answer.body.data as { answers?: unknown } | undefined)?.answers)