program.ts
This file
Path
apps/platform/src/workflows/answer/program.ts
755 lines · 23.6 KiB · TypeScript
Last changed by
Merge refusal/stale-base-movers into mainoscabrielbefore adoptiona23e097
History of this fileTake it
1/**2 * The Answer Workflow's program: one admitted answer3 * carried to its verdict and onto main through its project's answer queue,4 * each port call a named durable step.5 *6 * The project decides; the program only runs what it asks for. It loads7 * the answer's run (`answer`), then runs each port call the run waits on8 * (`merge`, the `cheap` lanes and the `checks` on the merged tree, `land`)9 * as a step whose value is the `LandingCommand` that reports it, and10 * reports it in a `record` step (`advanceAnswer`), which returns the calls11 * to run next. Every call to the project happens inside a step, so a replay12 * of the whole run follows the same path and runs nothing twice; a step13 * whose effect ran twice reports twice, and the landing lifecycle takes the14 * second report as the replay it is. Step names carry their attempt15 * (`merge#2`), so a merge onto a main that moved is a new step, not a replay.16 *17 * The run stops when the answer lands, is refused, waits on a person or on18 * the landing slot, or must wait for a retry: the project starts it again19 * then. A busy repo during a land is retried by the land step's own20 * retries first. It also stops when a port step finds nothing to do (the21 * answer no longer waits on that call), as the in-process run (`/inline`) does:22 * whatever moved the answer on carries it, and a run that went on from the23 * state it found could ask for the same call forever. Wherever it stops,24 * its last step writes the verdict, as it stands then, as the note on the25 * answer's head in its fork (`notes`).26 */27import { HostBusy } from "@repo/artifacts/repo-host";28import type { RepoHost } from "@repo/artifacts/repo-host";29import type { CheckRunner } from "@repo/checks/check-runner";30import type { EvidenceStore } from "@repo/checks/evidence-store";31import {32 AnswerReport,33 AnswerRun,34 NextStep,35 ReportedCommand,36 Steps,37} from "@repo/project/answer-runs";38import { nextSteps, runStep } from "@repo/project/answer-runs/steps";39import type { Lander } from "@repo/project/lander";40import {41 LandingCommand,42 LandingEffect,43 outcomeOf,44} from "@repo/project/landing";45import { Projects } from "@repo/project/projects";46import { LaneOutcome, Verdict } from "@repo/protocol/domain/answer";47import type { Outcome } from "@repo/protocol/domain/outcome";48import { CommitSha } from "@repo/protocol/ids";49import type {50 EnvKey,51 LaneName,52 ProjectName,53 RequestId,54} from "@repo/protocol/ids";55import { VerifierBlocked } from "@repo/protocol/refusal";56import {57 Array,58 Cause,59 Data,60 Effect,61 Match,62 Option,63 Schedule,64 Schema,65 Struct,66} from "effect";6768import type { AnswerParams } from "../../answer-runs.ts";69import { writeVerdictNote } from "../notes.ts";70import { StepRunner } from "../step.ts";71import type { StepRetry } from "../step.ts";72import { guards, GuardRun, passes } from "./guards.ts";73import { heldBack, HeldBackRun, unsealed } from "./held-back.ts";74import type { Judged } from "./held-back.ts";75import {76 laneOnMain,77 refusalsOf,78 runStage,79 StageRun,80 toCompareOnMain,81} from "./lanes.ts";82import type { Stage } from "./lanes.ts";8384/** Every port the program runs on. */85export type AnswerPorts =86 | CheckRunner87 | EvidenceStore88 | Lander89 | Projects90 | RepoHost91 | StepRunner;9293/** A run was started for a request its project does not hold: the project never does that. */94export class UnknownRequest extends Data.TaggedError("UnknownRequest")<{95 readonly project: ProjectName;96 readonly requestId: RequestId;97}> {}9899/** A land found the repo busy, at the landing's attempt: the land step's retries take it. */100class LandBusy extends Data.TaggedError("LandBusy")<{101 readonly attempt: number;102}> {}103104/** How a land step retries a busy repo before the project's own retry takes over. */105export const landRetry: StepRetry = {106 backoff: "exponential",107 delayMs: 1000,108 limit: 3,109};110111/** What a port step came to: the command that reports it, and what it saw beside it. */112export const Reported = Schema.Struct({113 command: ReportedCommand,114 report: Schema.optionalKey(AnswerReport),115});116117export type Reported = typeof Reported.Type;118119/** A port step's value: `None` when the answer no longer waits on that call. */120const Reporting = Schema.Option(Reported);121122type NextStep = typeof NextStep.Type;123124type Steps = typeof Steps.Type;125126type Call<Tag extends NextStep["_tag"]> = Extract<127 NextStep,128 { readonly _tag: Tag }129>;130131/** How many times each port call has run in this run: the attempt in a step's name. */132interface Attempts {133 readonly Land: number;134 readonly Merge: number;135 readonly RunChecks: number;136}137138const reported = (139 command: LandingCommand,140 report?: AnswerReport141): Option.Option<Reported> =>142 Option.some(report === undefined ? { command } : { command, report });143144/** The port calls among a landing's effects, as a run hands them on. */145const callsOf = (effects: readonly LandingEffect[]): readonly NextStep[] =>146 effects.flatMap((effect) =>147 LandingEffect.$match(effect, {148 Emit: (): readonly NextStep[] => [],149 Land: ({ main, tree }) => [NextStep.cases.Land.make({ main, tree })],150 Merge: ({ base, fork, head, main }) => [151 NextStep.cases.Merge.make({ base, fork, head, main }),152 ],153 Record: () => [],154 Retry: ({ at }) => [NextStep.cases.Retry.make({ at })],155 RunChecks: ({ tree }) => [NextStep.cases.RunChecks.make({ tree })],156 })157 );158159/** What a call is about, to tell whether the run still waits on it. */160const keyOf = (call: NextStep): string =>161 NextStep.match(call, {162 Land: ({ main, tree }) => `land ${main} ${tree}`,163 Merge: ({ head, main }) => `merge ${head} onto ${main}`,164 Retry: () => "retry",165 RunChecks: ({ tree }) => `checks ${tree}`,166 });167168/** Whether the answer's run waits on `call` now. */169const waitsOn = (run: AnswerRun, call: NextStep) =>170 callsOf(nextSteps(run)).some((each) => keyOf(each) === keyOf(call));171172/** The answer's project, as the platform reaches it. */173const projectOf = (project: ProjectName) =>174 Projects.use((projects) => projects.get(project)).pipe(Effect.orDie);175176/** The answer's run as its project holds it now. */177const load = ({ project, requestId }: AnswerParams) =>178 Effect.flatMap(projectOf(project), (api) => api.answer(requestId));179180/**181 * The port call `effect` names, run as the in-process run runs it182 * (`runStep`), on the answer's run as its project holds it now (as183 * `prepare` hands it on); `None` when the run no longer waits on `call`.184 * A merge that conflicts reads the project's landings to name who moved185 * each path.186 */187const portCall = (188 params: AnswerParams,189 call: Call<"Land" | "Merge">,190 effect: LandingEffect,191 prepare: (run: AnswerRun) => Effect.Effect<AnswerRun, never, Projects> = (192 run193 ) => Effect.succeed(run)194) =>195 Effect.gen(function* () {196 const api = yield* projectOf(params.project);197 const run = yield* api.answer(params.requestId);198199 if (Option.isNone(run) || !waitsOn(run.value, call)) {200 return Option.none();201 }202203 const ready = yield* prepare(run.value);204205 return yield* runStep(ready, effect, api.landings);206 });207208/** A verdict as its note holds it: JSON. */209const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));210211/**212 * The stored write-only value `verdict`'s note would carry, by its item:213 * the project scans the note before it leaves the run. Only the214 * platform's log hears which item, never the value.215 */216const leakIn = (params: AnswerParams, verdict: Verdict, where: string) =>217 Effect.gen(function* () {218 const text = yield* Effect.orDie(encodeVerdict(verdict));219 const api = yield* projectOf(params.project);220 const found = yield* api.scanForValues({ text });221222 if (Option.isSome(found)) {223 yield* Effect.logWarning(224 "an answer's verdict note held a stored write-only value; it was not written"225 ).pipe(226 Effect.annotateLogs({227 item: found.value,228 project: params.project,229 requestId: params.requestId,230 where,231 })232 );233 }234235 return found;236 });237238/**239 * The run as its land takes it: the verdict `Lander.land` writes as the240 * landed commit's note on canonical is left off when it holds a stored241 * value, so the landing writes no note; the verdict stands in the project.242 */243const withSafeNote = (params: AnswerParams) => (run: AnswerRun) =>244 run.verdict === undefined245 ? Effect.succeed(run)246 : Effect.map(leakIn(params, run.verdict, "canonical"), (leaked) =>247 Option.isSome(leaked) ? Struct.omit(run, ["verdict"]) : run248 );249250/** The answer's head merged onto the main the call names. */251const merge = (params: AnswerParams, call: Call<"Merge">) =>252 portCall(253 params,254 call,255 LandingEffect.Merge({256 base: call.base,257 fork: call.fork,258 head: call.head,259 main: call.main,260 })261 );262263/**264 * The checked tree landed on main as the platform's commit, through the265 * project's landing slot (the run waits on a land only while it holds the266 * slot). A main that moved sends the answer back to merge; a busy repo267 * fails the step, for its retries.268 */269const land = (params: AnswerParams, call: Call<"Land">) =>270 Effect.flatMap(271 portCall(272 params,273 call,274 LandingEffect.Land({ main: call.main, tree: call.tree }),275 withSafeNote(params)276 ),277 (given) =>278 Option.isSome(given) && LandingCommand.$is("Busy")(given.value.command)279 ? Effect.fail(new LandBusy({ attempt: given.value.command.attempt }))280 : Effect.succeed(given)281 );282283/**284 * One stage's lanes on the merged tree, then each failing lane on main, one285 * step per (main, lane), and the gate's classification of each failure.286 */287const stage = (288 params: AnswerParams,289 tree: Call<"RunChecks">["tree"],290 name: Stage,291 attempt: number292) =>293 Effect.gen(function* () {294 const { step } = yield* StepRunner;295296 const ran = yield* step(297 `${name}#${attempt}`,298 StageRun,299 Effect.flatMap(load(params), (run) =>300 Option.match(run, {301 onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),302 onSome: (found) => runStage(found, tree, name),303 })304 )305 );306307 if (!StageRun.guards.Ran(ran)) {308 return { ran, refusals: [] };309 }310311 const onMain = yield* Effect.forEach(toCompareOnMain(ran), (lane) =>312 Effect.map(313 step(314 `main:${ran.checked.main}:${lane.lane}`,315 LaneOutcome,316 laneOnMain(ran.checked, lane)317 ),318 (outcome) => [lane.lane, outcome] as const319 )320 );321322 return {323 ran,324 refusals: refusalsOf(ran, new Map<LaneName, LaneOutcome>(onMain)),325 };326 });327328/**329 * The refusals of the cheap stage's counts: a ratchet whose command printed330 * no count the platform can read is the gate's trouble, never the answer's331 * (`VerifierBlocked`), and the project hears which one in its log.332 */333const uncountedRefusals = (cheap: StageRun) =>334 StageRun.guards.Ran(cheap) && cheap.uncounted !== undefined335 ? Effect.as(336 Effect.logWarning(337 `the ratchet ${cheap.uncounted} printed no count on ${cheap.checked.tree}`338 ),339 [new VerifierBlocked({})]340 )341 : Effect.succeed([]);342343/** What a port step came to: its report, and the held-back run it judged, if any. */344interface Ran {345 readonly given: Option.Option<Reported>;346 readonly judged: Option.Option<Judged>;347}348349const ranOnly = (given: Option.Option<Reported>): Ran => ({350 given,351 judged: Option.none(),352});353354/**355 * An answer that adds a file holding a stored write-only value, until its356 * deciders can be asked: the run refuses it as the platform's trouble357 * (`VerifierBlocked`, which names nothing, so the scan is no oracle on358 * which item a guess matched), and only the platform's log says which359 * items, never a value. The `SecretInTree` decision on the deciders' Today360 * that should hold it instead (`AwaitingDecision` for its answerer) is the361 * project service's to open.362 */363const quarantine = (364 params: AnswerParams,365 items: readonly EnvKey[]366): Effect.Effect<readonly VerifierBlocked[]> =>367 Array.isReadonlyArrayEmpty(items)368 ? Effect.succeed([])369 : Effect.as(370 Effect.logWarning(371 "an answer adds a file holding a stored write-only value"372 ).pipe(373 Effect.annotateLogs({374 items: items.join(","),375 project: params.project,376 requestId: params.requestId,377 })378 ),379 [new VerifierBlocked({})]380 );381382/** The checks reported refused before any lane ran: the landing guards' refusals. */383const guardedOut = (384 params: AnswerParams,385 call: Call<"RunChecks">,386 run: Extract<GuardRun, { readonly _tag: "Guarded" }>387) =>388 Effect.map(quarantine(params, run.quarantined), (quarantined): Ran =>389 ranOnly(390 reported(391 LandingCommand.Checked({392 decisions: [],393 finish: run.finish,394 refusals: [...run.refusals, ...quarantined],395 tree: call.tree,396 }),397 { heldBack: [], lanes: [] }398 )399 )400 );401402/**403 * The checks on the exact merged tree: first the landing guards (when the404 * visibility cartridge provides them, `guards.ts`), then the cheap stage405 * (its lanes, and the ratchets' counts), then, if it passed, the ask's own406 * check and every other project lane, then, if those passed and a407 * held-back suite judges the answer, its held-back run (step 7 (d),408 * `held-back.ts`; `earlier` carries over to an unchanged patch). The first409 * stage that refuses ends them, with its refusals and its lanes. The counts410 * go to the project with the report, which judges them against its411 * baselines and opens the decisions a reasoned escape412 * asks for (step 7 (e)).413 */414const checks = (415 params: AnswerParams,416 call: Call<"RunChecks">,417 attempt: number,418 earlier: Option.Option<Judged>419): Effect.Effect<Ran, never, AnswerPorts> =>420 Effect.gen(function* () {421 const guarded = yield* guards(params, call.tree, attempt);422423 if (Option.isSome(guarded) && !passes(guarded.value)) {424 return yield* GuardRun.match(guarded.value, {425 Blocked: ({ attempt: at }) =>426 Effect.succeed(427 ranOnly(reported(LandingCommand.Blocked({ attempt: at })))428 ),429 Guarded: (run) => guardedOut(params, call, run),430 Moved: () => Effect.succeed(ranOnly(Option.none())),431 });432 }433434 const ran = yield* stage(params, call.tree, "cheap", attempt);435436 const cheap = {437 ...ran,438 refusals: [...ran.refusals, ...(yield* uncountedRefusals(ran.ran))],439 };440441 const judged =442 StageRun.guards.Ran(cheap.ran) && cheap.refusals.length === 0443 ? yield* stage(params, call.tree, "checks", attempt)444 : undefined;445446 const last = judged ?? cheap;447448 const sealed =449 judged !== undefined &&450 StageRun.guards.Ran(judged.ran) &&451 judged.refusals.length === 0 &&452 judged.ran.checked.sealed === true453 ? yield* heldBack(params, call.tree, attempt, earlier)454 : unsealed;455456 const counts = StageRun.guards.Ran(cheap.ran)457 ? Option.fromUndefinedOr(cheap.ran.counts)458 : Option.none();459460 if (HeldBackRun.guards.Blocked(sealed)) {461 return ranOnly(462 reported(LandingCommand.Blocked({ attempt: sealed.attempt }))463 );464 }465466 const held = HeldBackRun.guards.Judged(sealed)467 ? Option.some(sealed)468 : Option.none();469470 const given = StageRun.match(last.ran, {471 Blocked: ({ attempt: at }) =>472 reported(LandingCommand.Blocked({ attempt: at })),473 Moved: () => Option.none(),474 Ran: ({ checked, lanes }) =>475 reported(476 LandingCommand.Checked({477 decisions: [],478 finish: checked.finish,479 refusals: [480 ...last.refusals,481 ...Option.match(held, {482 onNone: () => [],483 onSome: ({ refusals }) => refusals,484 }),485 ],486 tree: call.tree,487 }),488 {489 heldBack: Option.match(held, {490 onNone: () => [],491 onSome: ({ results }) => results,492 }),493 lanes: [494 ...(judged !== undefined && StageRun.guards.Ran(cheap.ran)495 ? cheap.ran.lanes496 : []),497 ...lanes,498 ].map(({ result }) => result),499 ...Option.match(counts, {500 onNone: () => ({}),501 onSome: (ratchets) => ({ ratchets }),502 }),503 }504 ),505 });506507 return { given, judged: held };508 });509510/**511 * A port step's report given to the project, and the calls to run next.512 * When nothing comes next, or the step had nothing to report, the run's own513 * state says what it waits on: a person, the landing slot, a retry, or514 * nothing (the report was given already, by a step whose effect ran twice).515 */516const record = (params: AnswerParams, given: Option.Option<Reported>) =>517 Effect.gen(function* () {518 const api = yield* projectOf(params.project);519520 if (Option.isSome(given)) {521 const advanced = yield* api.advanceAnswer(522 params.requestId,523 given.value.command,524 given.value.report525 );526527 const calls = callsOf(advanced.effects);528529 if (Array.isReadonlyArrayNonEmpty(calls)) {530 return { effects: calls, outcome: advanced.outcome } satisfies Steps;531 }532 }533534 const run = yield* api.answer(params.requestId);535536 if (Option.isNone(run)) {537 return yield* Effect.die(new UnknownRequest(params));538 }539540 return {541 effects: callsOf(nextSteps(run.value)),542 outcome: outcomeOf(run.value.state),543 } satisfies Steps;544 });545546/**547 * What writing an answer's verdict note came to, kept as the step's value:548 * a replay reads it back, and a note that could not be written never fails549 * the run, in this run or a replay.550 */551const Noted = Schema.TaggedUnion({552 /** The answer has no verdict to note: no tree of it was checked. */553 Unjudged: {},554 /** The note could not be written, for this reason; the verdict stands in the project. */555 Unwritten: { reason: Schema.String },556 Written: { changed: Schema.Boolean, notesTip: CommitSha },557});558559/** How often a busy fork is asked again for the note before it is given up. */560const noteRetry = {561 schedule: Schedule.exponential("250 millis"),562 times: 2,563 while: Schema.is(HostBusy),564};565566/** The verdict as `verdict` shows it: the one the checks gave, with where the answer stands now. */567const shownVerdict = (run: AnswerRun) =>568 Option.map(Option.fromUndefinedOr(run.verdict), (made): Verdict => ({569 ...made,570 outcome: outcomeOf(run.state),571 }));572573/** The answer's verdict, as it stands, written as the note on its head in its fork. */574const noteVerdict = (params: AnswerParams) =>575 Effect.gen(function* () {576 const run = yield* load(params);577578 const judged = Option.flatMap(run, (found) =>579 Option.map(shownVerdict(found), (verdict) => ({580 fork: found.state.request.fork,581 verdict,582 }))583 );584585 if (Option.isNone(judged)) {586 return Noted.cases.Unjudged.make({});587 }588589 const { fork, verdict } = judged.value;590591 // The note leaves the run for the answer's fork: a note that holds a592 // stored value is not written; the verdict stands in the project.593 if (Option.isSome(yield* leakIn(params, verdict, "fork"))) {594 return Noted.cases.Unwritten.make({ reason: "SecretInOutput" });595 }596597 const written = yield* writeVerdictNote({598 fork,599 head: verdict.head,600 verdict,601 }).pipe(Effect.retry(noteRetry));602603 return Noted.cases.Written.make(written);604 }).pipe(605 // Anything but an interruption is recorded: the note is bookkeeping, and606 // a fork its answerer filled with refs of their own may break it.607 Effect.catchCause((cause) =>608 Cause.hasInterruptsOnly(cause)609 ? Effect.interrupt610 : Effect.as(611 Effect.logWarning(612 "an answer's verdict note was not written",613 cause614 ),615 Noted.cases.Unwritten.make({616 reason: Option.match(Cause.findErrorOption(cause), {617 onNone: () => "defect",618 onSome: ({ _tag }) => _tag,619 }),620 })621 )622 )623 );624625/**626 * Once the run stops, the verdict note on the answer's head in its fork:627 * the verdict as `verdict` shows it, so an answerer628 * reads where the answer stands with plain git, refused, waiting or629 * landed. Its own step, named for the outcome the run stopped at, so a630 * replay reads the record and a restarted run writes the same note again,631 * which changes nothing. The canonical note is `Lander.land`'s.632 */633const notes = (634 params: AnswerParams,635 outcome: Outcome636): Effect.Effect<void, never, AnswerPorts> =>637 Effect.flatMap(StepRunner, ({ step }) =>638 Effect.asVoid(step(`notes:${outcome._tag}`, Noted, noteVerdict(params)))639 );640641/** The port call a step runs, under its name. */642const portStep = (643 params: AnswerParams,644 call: Call<"Land" | "Merge" | "RunChecks">,645 attempt: number,646 earlier: Option.Option<Judged>647): Effect.Effect<Ran, never, AnswerPorts> =>648 Effect.flatMap(StepRunner, ({ step }) =>649 Match.valueTags(call, {650 Land: (landing) =>651 step(652 `land#${attempt}`,653 Reporting,654 land(params, landing),655 landRetry656 ).pipe(657 Effect.catchTag("LandBusy", ({ attempt: at }) =>658 Effect.succeed(reported(LandingCommand.Busy({ attempt: at })))659 ),660 Effect.map(ranOnly)661 ),662 Merge: (merging) =>663 Effect.map(664 step(`merge#${attempt}`, Reporting, merge(params, merging)),665 ranOnly666 ),667 RunChecks: (checking) => checks(params, checking, attempt, earlier),668 })669 );670671const nameOf = {672 Land: "land",673 Merge: "merge",674 RunChecks: "checks",675} as const satisfies Record<keyof Attempts, string>;676677/**678 * Runs the calls `at` names, one after another, until none is left.679 * `earlier` is the last held-back run of this Workflow, which carries over680 * to a later check of an unchanged patch.681 */682const carry = (683 params: AnswerParams,684 at: Steps,685 attempts: Attempts,686 earlier: Option.Option<Judged>687): Effect.Effect<Outcome, never, AnswerPorts> =>688 Effect.gen(function* () {689 // A retry is the project's to start, at its alarm.690 if (at.effects.some(NextStep.guards.Retry)) {691 return at.outcome;692 }693694 const call = at.effects.find(695 (each): each is Call<"Land" | "Merge" | "RunChecks"> =>696 !NextStep.guards.Retry(each)697 );698699 if (call === undefined) {700 return at.outcome;701 }702703 const attempt = attempts[call._tag] + 1;704 const { given, judged } = yield* portStep(params, call, attempt, earlier);705 const { step } = yield* StepRunner;706707 const next = yield* step(708 `record:${nameOf[call._tag]}#${attempt}`,709 Steps,710 record(params, given)711 );712713 if (Option.isNone(given)) {714 return next.outcome;715 }716717 return yield* carry(718 params,719 next,720 { ...attempts, [call._tag]: attempt },721 Option.orElse(judged, () => earlier)722 );723 });724725/**726 * Carries one admitted answer as far as it goes now: merged onto main,727 * checked on the merged tree, and landed through its project's serial728 * queue, or refused, or waiting. The same request run again converges on729 * one outcome and one landing (principle 8).730 */731export const runAnswer = (732 params: AnswerParams733): Effect.Effect<Outcome, never, AnswerPorts> =>734 Effect.gen(function* () {735 const { step } = yield* StepRunner;736 const run = yield* step("load", Schema.Option(AnswerRun), load(params));737738 if (Option.isNone(run)) {739 return yield* Effect.die(new UnknownRequest(params));740 }741742 const outcome = yield* carry(743 params,744 {745 effects: callsOf(nextSteps(run.value)),746 outcome: outcomeOf(run.value.state),747 },748 { Land: 0, Merge: 0, RunChecks: 0 },749 Option.none()750 );751752 yield* notes(params, outcome);753754 return outcome;755 });