Keep each draft round its own Workflow instance, and say why a draft step gave up
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- draftId kept only the first 100 characters, so a long project name (ProjectName has no bound) cut off the proposal and the round: two rounds or two proposals shared one instance, and since a complete instance is never restarted, the later round never ran. The `-<proposal>-r<round>` suffix is now kept whole, and a cut project name carries a hash of the whole name. - A `draft-<n>` step whose retries ran out was recorded as `rate-limited` whatever happened; the gave-up record now keeps the DraftFailed reason, else `model-error` (a drafter that died), so the next attempt's feedback says what went wrong. - The Draft branch of `Answer.run` decoded the env twice (once for workerPorts, once for draftPorts); it decodes it once (principle 2). - answer.ts's new type imports sat above the module comment; moved below it. - Tests added in apps/platform/test/workflows/draft.test.ts: a model rate-limited past its retries spends the attempt and a replay ends the same way; a drafter that dies is fed back as model-error; a Checker blocked past the rehearsal's retries ends the round Failed{VerifierBlocked} without another draft; rehearse-1 gets the blocked retries; long-named rounds keep distinct ids within 100 characters. - Platform entry: 1,659,162 of 1,900,000.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+203 added−17 removed
- tests:+151 added−4 removed
- other:+52 added−13 removed
Provenance
- Commit
d40eb00- Tree
52db455- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
fb60580
4 files changed+203 added−17 removed
modified:apps/platform/src/workflows/answer.ts+11 added-5 removed
123123413 unmodified lines181920212223242526272894 unmodified lines123124125126127127128129130131132132133134135136137138139140141142143144145146147148import type { RepoHost } from "@repo/artifacts/repo-host";import type { Drafter } from "@repo/drafting/drafter";import type { Projects } from "@repo/project/projects";/** * The `Answer` Workflow: carries one admitted answer through merge, checks * and landing, each a durable step. The class is thin: * it decodes its params, runs `runAnswer` with its steps over the engine's13 unmodified lines * `draftSteps` (W9-D14), over the Worker's ports and the drafter * (`draftPorts`), with each step's timeout handed to the engine. A draft's * output is `null` too. */import type { RepoHost } from "@repo/artifacts/repo-host";import type { Drafter } from "@repo/drafting/drafter";import type { Projects } from "@repo/project/projects";import { Outcome } from "@repo/protocol/domain/outcome";import { WorkflowEntrypoint } from "cloudflare:workers";import type { WorkflowEvent } from "cloudflare:workers";import { Effect, Layer, Schema } from "effect";94 unmodified lines event: Readonly<WorkflowEvent<typeof WorkflowParams.Encoded>>, step: EngineSteps ): Promise<OutcomeEncoded | null> { const config = decodeEnv(this.env); const ports = Layer.unwrap(Effect.map(config, workerPorts)); const { payload } = event;
if (drafts(payload)) { // The env decoded once: the Worker's ports and the drafter from it. return runDraftWorkflow( Layer.merge(ports, Layer.unwrap(Effect.map(config, draftPorts))), Layer.unwrap( Effect.map(config, (decoded) => Layer.merge(workerPorts(decoded), draftPorts(decoded)) ) ), payload, step ); }
const ports = Layer.unwrap(Effect.map(config, workerPorts));
return admits(payload) ? runAdmission(ports, payload, step) : runWorkflow(ports, payload, step); }}modified:apps/platform/src/answer-runs.ts+32 added-6 removed
62 unmodified lines63 /** The instance an admission runs as: one per project, layer and pushed head. */64 export const admissionId = (params: AdmissionParams) =>65 `admit-${params.project}-${params.layer}-${params.head}`.slice(0, ID_LENGTH);66 67-/** The instance a draft's round runs as: one per project, proposal and round. */67+/** A modulus for `tagOf`: the Mersenne prime 2^31 - 1, so every step stays a safe integer. */68+const TAG_MODULUS = 2_147_483_647;69+70+/** A polynomial hash of `text`'s code points, in base 36: a short, stable tag for a name cut short. */71+const tagOf = (text: string) => {72+ let hash = 0;73+74+ for (const unit of text) {75+ hash = (hash * 31 + (unit.codePointAt(0) ?? 0)) % TAG_MODULUS;76+ }77+78+ return hash.toString(36);79+};80+81+/**82+ * The instance a draft's round runs as: one per project, proposal and83+ * round. The proposal and round are kept whole: a project name too long for84+ * the engine's id is cut, and tagged with a hash of the whole name, so no85+ * two rounds share an instance (a complete one is never run again).86+ */87 export const draftId = (88 params: Pick<DraftParams, "project" | "proposal" | "round">70-) =>71- `draft-${params.project}-${params.proposal}-r${params.round}`.slice(72- 0,73- ID_LENGTH74- );89+) => {90+ const suffix = `-${params.proposal}-r${params.round}`;91+ const whole = `draft-${params.project}${suffix}`;92+93+ if (whole.length <= ID_LENGTH) {94+ return whole;95+ }96+97+ const tag = `-${tagOf(params.project)}`;98+99+ return `${whole.slice(0, ID_LENGTH - tag.length - suffix.length)}${tag}${suffix}`;100+};modified:apps/platform/test/workflows/draft.test.ts+151 added-4 removed
24 unmodified lines25 import {26 AskId,27 LandedSha,28 LaneName,29+ ProjectName,30 ProposalId,31 RepoName,32 RepoPath,33 } from "@repo/protocol/ids";34 import { Anonymous, Person } from "@repo/protocol/principal";35 import { CapReached } from "@repo/protocol/refusal";36 import { advanceTo } from "@repo/testkit/clock";37 import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";37-import { Context, Effect, Layer, Option, Ref, Schema } from "effect";38+import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";39 40 import { DraftRunsWorkflow } from "../../src/adapters/draft-runs-workflow.ts";41 import type { DraftWorkflow } from "../../src/adapters/draft-runs-workflow.ts";42 import { DraftParams, draftId } from "../../src/answer-runs.ts";259 unmodified lines302 )303 );304 305 it.effect(306+ "spends the attempt of a model still rate-limited once its step's retries are spent, and a replay ends the same way",307+ () =>308+ Effect.gen(function* () {309+ const { api, main } = yield* proposed;310+311+ yield* scripted(main, red, "failed");312+313+ const steps = yield* memoSteps();314+315+ yield* draftSteps(params).pipe(Effect.provide(steps));316+317+ const settled = {318+ asked: (yield* asked).map(({ attempt }) => attempt),319+ draft: yield* draftOfProposal(api),320+ feedback: (yield* asked)[5]?.feedback,321+ };322+323+ // The finished instance, run again: `draft-1` is thrown again,324+ // unrun, and its `gave-up` record says what the first run made of it.325+ yield* draftSteps(params).pipe(Effect.provide(steps));326+327+ expect({328+ replayed: {329+ asked: (yield* asked).length,330+ draft: yield* draftOfProposal(api),331+ },332+ settled,333+ }).toStrictEqual({334+ replayed: { asked: 6, draft: settled.draft },335+ settled: {336+ asked: [1, 1, 1, 1, 1, 2],337+ draft: DraftState.cases.Ready.make({338+ attempts: 2,339+ model,340+ red: {341+ lane: redThenGreen,342+ signature: "redThenGreen: expected 41, got undefined",343+ },344+ round: 1,345+ }),346+ feedback:347+ "Your reply gave no draft (rate-limited): answer with one JSON object that matches the schema, and nothing else.",348+ },349+ });350+ }).pipe(351+ Effect.provide(352+ worldDrafting([353+ ...Array.replicate(new DraftFailed({ reason: "rate-limited" }), 5),354+ red,355+ ])356+ )357+ )358+ );359+360+ it.effect(361+ "tells the next attempt the model erred, not that it was rate-limited, when the drafter dies",362+ () =>363+ Effect.gen(function* () {364+ const { api } = yield* proposed;365+366+ yield* draftSteps(params).pipe(Effect.provide(yield* memoSteps()));367+368+ const inputs = yield* asked;369+370+ expect({371+ asked: inputs.map(({ attempt }) => attempt),372+ draft: yield* draftOfProposal(api),373+ feedback: inputs[1]?.feedback,374+ }).toStrictEqual({375+ asked: [1, 2, 3],376+ draft: DraftState.cases.Failed.make({377+ attempts: 3,378+ model,379+ refusal: "IncompleteBrief",380+ round: 1,381+ }),382+ feedback:383+ "Your reply gave no draft (model-error): answer with one JSON object that matches the schema, and nothing else.",384+ });385+ }).pipe(Effect.provide(worldDrafting([])))386+ );387+388+ it.effect(389+ "ends the round Failed with VerifierBlocked, asking no other draft, when the Checker stays blocked past the rehearsal's retries",390+ () =>391+ Effect.gen(function* () {392+ const { api } = yield* proposed;393+394+ // Nothing scripted for the draft's commit: the Checker cannot run it.395+ const steps = yield* memoSteps();396+397+ yield* draftSteps(params).pipe(Effect.provide(steps));398+ yield* draftSteps(params).pipe(Effect.provide(steps));399+400+ expect({401+ asked: (yield* asked).length,402+ decisions: (yield* proposalDecisions(api)).length,403+ draft: yield* draftOfProposal(api),404+ }).toStrictEqual({405+ asked: 1,406+ decisions: 1,407+ draft: DraftState.cases.Failed.make({408+ attempts: 1,409+ model,410+ refusal: "VerifierBlocked",411+ round: 1,412+ }),413+ });414+ }).pipe(Effect.provide(worldDrafting([red])))415+ );416+417+ it.effect(418 "stops after its context when the proposal is gone: no attempt, no settling",419 () =>420 Effect.gen(function* () {421 yield* proposed;87 unmodified lines509 expect(draftId(params)).toBe(`draft-${project}-${proposal}-r1`);510 })511 );512 513+ it("keeps every round of a long-named project's proposals its own instance, within the engine's 100 characters", () => {514+ const long = ProjectName.make(`${"a-long-project-name".repeat(6)}x`);515+ const longToo = ProjectName.make(`${"a-long-project-name".repeat(6)}y`);516+ const other = ProposalId.make("prop-000002");517+518+ const rounds = [519+ { project: long, proposal, round: 1 },520+ { project: long, proposal, round: 2 },521+ { project: long, proposal: other, round: 1 },522+ { project: longToo, proposal, round: 1 },523+ ];524+525+ const ids = rounds.map(draftId);526+527+ expect({528+ distinct: new Set(ids).size,529+ fit: ids.every(530+ (id) => id.length <= 100 && /^[a-zA-Z0-9_][a-zA-Z0-9-_]*$/u.test(id)531+ ),532+ named: rounds.every((round, at) =>533+ (ids[at] ?? "").endsWith(`-${round.proposal}-r${round.round}`)534+ ),535+ }).toStrictEqual({ distinct: 4, fit: true, named: true });536+ });537+538 it.effect(539 "starts an errored round's instance again, and never a complete one, which would ask the model again",540 () =>541 Effect.gen(function* () {65 unmodified lines607 "rehearse-1",608 "settle",609 ]);610 611+ expect({612+ draft: new Map(configs).get("draft-1"),613+ rehearse: new Map(configs).get("rehearse-1"),614+ }).toStrictEqual({473- expect(new Map(configs).get("draft-1")).toStrictEqual({474- retries: { backoff: "exponential", delay: 15_000, limit: 4 },475- timeout: "10 minutes",615+ draft: {616+ retries: { backoff: "exponential", delay: 15_000, limit: 4 },617+ timeout: "10 minutes",618+ },619+ rehearse: {620+ retries: { backoff: "exponential", delay: 60_000, limit: 3 },621+ timeout: "10 minutes",622+ },623 });624 625 expect(626 configs.filter(([, config]) => config.timeout !== "10 minutes")56 unmodified linesmodified:packages/drafting/src/run.ts+9 added-2 removed
244 unmodified lines245 )246 ),247 rateLimitedRetry248 ).pipe(249+ // A model still rate-limited once the retries are spent, or a250+ // drafter that died: either way a spent attempt, said as it was.249- Effect.catchCause(() =>251+ Effect.catchCause((cause) =>252 step(253 `draft-${attempt}:gave-up`,254 Attempted,255 Effect.succeed(254- Attempted.cases.Spent.make({ reason: "rate-limited" })256+ Attempted.cases.Spent.make({257+ reason: Option.match(Cause.findErrorOption(cause), {258+ onNone: () => "model-error" as const,259+ onSome: ({ reason }) => reason,260+ }),261+ })262 )263 )264 )265 );104 unmodified lines