Skip to content
Myr

program.ts

This file

Path

apps/platform/src/workflows/answer/program.ts

746 lines · 23.4 KiB · TypeScript

Last changed by

Merge build/613-answer-held-back-and-guards: an answer is judged by the sealed suite it was pinned to, lands with a Held-back: trailer, and can't carry layer content or a stored valueoscabrielbefore adoptionc3d7b1b

History of this file

Take it

1/**2 * The Answer Workflow's program (spec §5 steps 7–8): 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 W2's in-process run 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 W2's 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 */185const portCall = (186  params: AnswerParams,187  call: Call<"Land" | "Merge">,188  effect: LandingEffect,189  prepare: (run: AnswerRun) => Effect.Effect<AnswerRun, never, Projects> = (190    run191  ) => Effect.succeed(run)192) =>193  Effect.flatMap(load(params), (run) =>194    Option.isSome(run) && waitsOn(run.value, call)195      ? Effect.flatMap(prepare(run.value), (ready) => runStep(ready, effect))196      : Effect.succeedNone197  );198199/** A verdict as its note holds it: JSON. */200const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));201202/**203 * The stored write-only value `verdict`'s note would carry, by its item:204 * the project scans the note before it leaves the run (VL §8.6). Only the205 * platform's log hears which item, never the value.206 */207const leakIn = (params: AnswerParams, verdict: Verdict, where: string) =>208  Effect.gen(function* () {209    const text = yield* Effect.orDie(encodeVerdict(verdict));210    const api = yield* projectOf(params.project);211    const found = yield* api.scanForValues({ text });212213    if (Option.isSome(found)) {214      yield* Effect.logWarning(215        "an answer's verdict note held a stored write-only value; it was not written"216      ).pipe(217        Effect.annotateLogs({218          item: found.value,219          project: params.project,220          requestId: params.requestId,221          where,222        })223      );224    }225226    return found;227  });228229/**230 * The run as its land takes it: the verdict `Lander.land` writes as the231 * landed commit's note on canonical is left off when it holds a stored232 * value, so the landing writes no note; the verdict stands in the project.233 */234const withSafeNote = (params: AnswerParams) => (run: AnswerRun) =>235  run.verdict === undefined236    ? Effect.succeed(run)237    : Effect.map(leakIn(params, run.verdict, "canonical"), (leaked) =>238        Option.isSome(leaked) ? Struct.omit(run, ["verdict"]) : run239      );240241/** The answer's head merged onto the main the call names. */242const merge = (params: AnswerParams, call: Call<"Merge">) =>243  portCall(244    params,245    call,246    LandingEffect.Merge({247      base: call.base,248      fork: call.fork,249      head: call.head,250      main: call.main,251    })252  );253254/**255 * The checked tree landed on main as the platform's commit, through the256 * project's landing slot (the run waits on a land only while it holds the257 * slot). A main that moved sends the answer back to merge; a busy repo258 * fails the step, for its retries.259 */260const land = (params: AnswerParams, call: Call<"Land">) =>261  Effect.flatMap(262    portCall(263      params,264      call,265      LandingEffect.Land({ main: call.main, tree: call.tree }),266      withSafeNote(params)267    ),268    (given) =>269      Option.isSome(given) && LandingCommand.$is("Busy")(given.value.command)270        ? Effect.fail(new LandBusy({ attempt: given.value.command.attempt }))271        : Effect.succeed(given)272  );273274/**275 * One stage's lanes on the merged tree, then each failing lane on main, one276 * step per (main, lane), and the gate's classification of each failure.277 */278const stage = (279  params: AnswerParams,280  tree: Call<"RunChecks">["tree"],281  name: Stage,282  attempt: number283) =>284  Effect.gen(function* () {285    const { step } = yield* StepRunner;286287    const ran = yield* step(288      `${name}#${attempt}`,289      StageRun,290      Effect.flatMap(load(params), (run) =>291        Option.match(run, {292          onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),293          onSome: (found) => runStage(found, tree, name),294        })295      )296    );297298    if (!StageRun.guards.Ran(ran)) {299      return { ran, refusals: [] };300    }301302    const onMain = yield* Effect.forEach(toCompareOnMain(ran), (lane) =>303      Effect.map(304        step(305          `main:${ran.checked.main}:${lane.lane}`,306          LaneOutcome,307          laneOnMain(ran.checked, lane)308        ),309        (outcome) => [lane.lane, outcome] as const310      )311    );312313    return {314      ran,315      refusals: refusalsOf(ran, new Map<LaneName, LaneOutcome>(onMain)),316    };317  });318319/**320 * The refusals of the cheap stage's counts: a ratchet whose command printed321 * no count the platform can read is the gate's trouble, never the answer's322 * (`VerifierBlocked`), and the project hears which one in its log.323 */324const uncountedRefusals = (cheap: StageRun) =>325  StageRun.guards.Ran(cheap) && cheap.uncounted !== undefined326    ? Effect.as(327        Effect.logWarning(328          `the ratchet ${cheap.uncounted} printed no count on ${cheap.checked.tree}`329        ),330        [new VerifierBlocked({})]331      )332    : Effect.succeed([]);333334/** What a port step came to: its report, and the held-back run it judged, if any. */335interface Ran {336  readonly given: Option.Option<Reported>;337  readonly judged: Option.Option<Judged>;338}339340const ranOnly = (given: Option.Option<Reported>): Ran => ({341  given,342  judged: Option.none(),343});344345/**346 * An answer that adds a file holding a stored write-only value, until its347 * deciders can be asked: the run refuses it as the platform's trouble348 * (`VerifierBlocked`, which names nothing, so the scan is no oracle on349 * which item a guess matched), and only the platform's log says which350 * items, never a value. The `SecretInTree` decision on the deciders' Today351 * that should hold it instead (`AwaitingDecision` for its answerer) is the352 * project service's to open.353 */354const quarantine = (355  params: AnswerParams,356  items: readonly EnvKey[]357): Effect.Effect<readonly VerifierBlocked[]> =>358  Array.isReadonlyArrayEmpty(items)359    ? Effect.succeed([])360    : Effect.as(361        Effect.logWarning(362          "an answer adds a file holding a stored write-only value"363        ).pipe(364          Effect.annotateLogs({365            items: items.join(","),366            project: params.project,367            requestId: params.requestId,368          })369        ),370        [new VerifierBlocked({})]371      );372373/** The checks reported refused before any lane ran: the landing guards' refusals. */374const guardedOut = (375  params: AnswerParams,376  call: Call<"RunChecks">,377  run: Extract<GuardRun, { readonly _tag: "Guarded" }>378) =>379  Effect.map(quarantine(params, run.quarantined), (quarantined): Ran =>380    ranOnly(381      reported(382        LandingCommand.Checked({383          decisions: [],384          finish: run.finish,385          refusals: [...run.refusals, ...quarantined],386          tree: call.tree,387        }),388        { heldBack: [], lanes: [] }389      )390    )391  );392393/**394 * The checks on the exact merged tree: first the landing guards (when the395 * visibility cartridge provides them, `guards.ts`), then the cheap stage396 * (its lanes, and the ratchets' counts), then, if it passed, the ask's own397 * check and every other project lane, then, if those passed and a398 * held-back suite judges the answer, its held-back run (step 7 (d),399 * `held-back.ts`; `earlier` carries over to an unchanged patch). The first400 * stage that refuses ends them, with its refusals and its lanes. The counts401 * go to the project with the report, which judges them against its402 * baselines (spec §5 step 7 (b)) and opens the decisions a reasoned escape403 * asks for (step 7 (e)).404 */405const checks = (406  params: AnswerParams,407  call: Call<"RunChecks">,408  attempt: number,409  earlier: Option.Option<Judged>410): Effect.Effect<Ran, never, AnswerPorts> =>411  Effect.gen(function* () {412    const guarded = yield* guards(params, call.tree, attempt);413414    if (Option.isSome(guarded) && !passes(guarded.value)) {415      return yield* GuardRun.match(guarded.value, {416        Blocked: ({ attempt: at }) =>417          Effect.succeed(418            ranOnly(reported(LandingCommand.Blocked({ attempt: at })))419          ),420        Guarded: (run) => guardedOut(params, call, run),421        Moved: () => Effect.succeed(ranOnly(Option.none())),422      });423    }424425    const ran = yield* stage(params, call.tree, "cheap", attempt);426427    const cheap = {428      ...ran,429      refusals: [...ran.refusals, ...(yield* uncountedRefusals(ran.ran))],430    };431432    const judged =433      StageRun.guards.Ran(cheap.ran) && cheap.refusals.length === 0434        ? yield* stage(params, call.tree, "checks", attempt)435        : undefined;436437    const last = judged ?? cheap;438439    const sealed =440      judged !== undefined &&441      StageRun.guards.Ran(judged.ran) &&442      judged.refusals.length === 0 &&443      judged.ran.checked.sealed === true444        ? yield* heldBack(params, call.tree, attempt, earlier)445        : unsealed;446447    const counts = StageRun.guards.Ran(cheap.ran)448      ? Option.fromUndefinedOr(cheap.ran.counts)449      : Option.none();450451    if (HeldBackRun.guards.Blocked(sealed)) {452      return ranOnly(453        reported(LandingCommand.Blocked({ attempt: sealed.attempt }))454      );455    }456457    const held = HeldBackRun.guards.Judged(sealed)458      ? Option.some(sealed)459      : Option.none();460461    const given = StageRun.match(last.ran, {462      Blocked: ({ attempt: at }) =>463        reported(LandingCommand.Blocked({ attempt: at })),464      Moved: () => Option.none(),465      Ran: ({ checked, lanes }) =>466        reported(467          LandingCommand.Checked({468            decisions: [],469            finish: checked.finish,470            refusals: [471              ...last.refusals,472              ...Option.match(held, {473                onNone: () => [],474                onSome: ({ refusals }) => refusals,475              }),476            ],477            tree: call.tree,478          }),479          {480            heldBack: Option.match(held, {481              onNone: () => [],482              onSome: ({ results }) => results,483            }),484            lanes: [485              ...(judged !== undefined && StageRun.guards.Ran(cheap.ran)486                ? cheap.ran.lanes487                : []),488              ...lanes,489            ].map(({ result }) => result),490            ...Option.match(counts, {491              onNone: () => ({}),492              onSome: (ratchets) => ({ ratchets }),493            }),494          }495        ),496    });497498    return { given, judged: held };499  });500501/**502 * A port step's report given to the project, and the calls to run next.503 * When nothing comes next, or the step had nothing to report, the run's own504 * state says what it waits on: a person, the landing slot, a retry, or505 * nothing (the report was given already, by a step whose effect ran twice).506 */507const record = (params: AnswerParams, given: Option.Option<Reported>) =>508  Effect.gen(function* () {509    const api = yield* projectOf(params.project);510511    if (Option.isSome(given)) {512      const advanced = yield* api.advanceAnswer(513        params.requestId,514        given.value.command,515        given.value.report516      );517518      const calls = callsOf(advanced.effects);519520      if (Array.isReadonlyArrayNonEmpty(calls)) {521        return { effects: calls, outcome: advanced.outcome } satisfies Steps;522      }523    }524525    const run = yield* api.answer(params.requestId);526527    if (Option.isNone(run)) {528      return yield* Effect.die(new UnknownRequest(params));529    }530531    return {532      effects: callsOf(nextSteps(run.value)),533      outcome: outcomeOf(run.value.state),534    } satisfies Steps;535  });536537/**538 * What writing an answer's verdict note came to, kept as the step's value:539 * a replay reads it back, and a note that could not be written never fails540 * the run, in this run or a replay (W3 313 #5).541 */542const Noted = Schema.TaggedUnion({543  /** The answer has no verdict to note: no tree of it was checked. */544  Unjudged: {},545  /** The note could not be written, for this reason; the verdict stands in the project. */546  Unwritten: { reason: Schema.String },547  Written: { changed: Schema.Boolean, notesTip: CommitSha },548});549550/** How often a busy fork is asked again for the note before it is given up. */551const noteRetry = {552  schedule: Schedule.exponential("250 millis"),553  times: 2,554  while: Schema.is(HostBusy),555};556557/** The verdict as `verdict` shows it: the one the checks gave, with where the answer stands now. */558const shownVerdict = (run: AnswerRun) =>559  Option.map(Option.fromUndefinedOr(run.verdict), (made): Verdict => ({560    ...made,561    outcome: outcomeOf(run.state),562  }));563564/** The answer's verdict, as it stands, written as the note on its head in its fork. */565const noteVerdict = (params: AnswerParams) =>566  Effect.gen(function* () {567    const run = yield* load(params);568569    const judged = Option.flatMap(run, (found) =>570      Option.map(shownVerdict(found), (verdict) => ({571        fork: found.state.request.fork,572        verdict,573      }))574    );575576    if (Option.isNone(judged)) {577      return Noted.cases.Unjudged.make({});578    }579580    const { fork, verdict } = judged.value;581582    // The note leaves the run for the answer's fork: a note that holds a583    // stored value is not written; the verdict stands in the project.584    if (Option.isSome(yield* leakIn(params, verdict, "fork"))) {585      return Noted.cases.Unwritten.make({ reason: "SecretInOutput" });586    }587588    const written = yield* writeVerdictNote({589      fork,590      head: verdict.head,591      verdict,592    }).pipe(Effect.retry(noteRetry));593594    return Noted.cases.Written.make(written);595  }).pipe(596    // Anything but an interruption is recorded: the note is bookkeeping, and597    // a fork its answerer filled with refs of their own may break it.598    Effect.catchCause((cause) =>599      Cause.hasInterruptsOnly(cause)600        ? Effect.interrupt601        : Effect.as(602            Effect.logWarning(603              "an answer's verdict note was not written",604              cause605            ),606            Noted.cases.Unwritten.make({607              reason: Option.match(Cause.findErrorOption(cause), {608                onNone: () => "defect",609                onSome: ({ _tag }) => _tag,610              }),611            })612          )613    )614  );615616/**617 * Once the run stops, the verdict note on the answer's head in its fork618 * (spec D22, W4 407): the verdict as `verdict` shows it, so an answerer619 * reads where the answer stands with plain git, refused, waiting or620 * landed. Its own step, named for the outcome the run stopped at, so a621 * replay reads the record and a restarted run writes the same note again,622 * which changes nothing. The canonical note is `Lander.land`'s.623 */624const notes = (625  params: AnswerParams,626  outcome: Outcome627): Effect.Effect<void, never, AnswerPorts> =>628  Effect.flatMap(StepRunner, ({ step }) =>629    Effect.asVoid(step(`notes:${outcome._tag}`, Noted, noteVerdict(params)))630  );631632/** The port call a step runs, under its name. */633const portStep = (634  params: AnswerParams,635  call: Call<"Land" | "Merge" | "RunChecks">,636  attempt: number,637  earlier: Option.Option<Judged>638): Effect.Effect<Ran, never, AnswerPorts> =>639  Effect.flatMap(StepRunner, ({ step }) =>640    Match.valueTags(call, {641      Land: (landing) =>642        step(643          `land#${attempt}`,644          Reporting,645          land(params, landing),646          landRetry647        ).pipe(648          Effect.catchTag("LandBusy", ({ attempt: at }) =>649            Effect.succeed(reported(LandingCommand.Busy({ attempt: at })))650          ),651          Effect.map(ranOnly)652        ),653      Merge: (merging) =>654        Effect.map(655          step(`merge#${attempt}`, Reporting, merge(params, merging)),656          ranOnly657        ),658      RunChecks: (checking) => checks(params, checking, attempt, earlier),659    })660  );661662const nameOf = {663  Land: "land",664  Merge: "merge",665  RunChecks: "checks",666} as const satisfies Record<keyof Attempts, string>;667668/**669 * Runs the calls `at` names, one after another, until none is left.670 * `earlier` is the last held-back run of this Workflow, which carries over671 * to a later check of an unchanged patch.672 */673const carry = (674  params: AnswerParams,675  at: Steps,676  attempts: Attempts,677  earlier: Option.Option<Judged>678): Effect.Effect<Outcome, never, AnswerPorts> =>679  Effect.gen(function* () {680    // A retry is the project's to start, at its alarm.681    if (at.effects.some(NextStep.guards.Retry)) {682      return at.outcome;683    }684685    const call = at.effects.find(686      (each): each is Call<"Land" | "Merge" | "RunChecks"> =>687        !NextStep.guards.Retry(each)688    );689690    if (call === undefined) {691      return at.outcome;692    }693694    const attempt = attempts[call._tag] + 1;695    const { given, judged } = yield* portStep(params, call, attempt, earlier);696    const { step } = yield* StepRunner;697698    const next = yield* step(699      `record:${nameOf[call._tag]}#${attempt}`,700      Steps,701      record(params, given)702    );703704    if (Option.isNone(given)) {705      return next.outcome;706    }707708    return yield* carry(709      params,710      next,711      { ...attempts, [call._tag]: attempt },712      Option.orElse(judged, () => earlier)713    );714  });715716/**717 * Carries one admitted answer as far as it goes now: merged onto main,718 * checked on the merged tree, and landed through its project's serial719 * queue, or refused, or waiting. The same request run again converges on720 * one outcome and one landing (principle 8).721 */722export const runAnswer = (723  params: AnswerParams724): Effect.Effect<Outcome, never, AnswerPorts> =>725  Effect.gen(function* () {726    const { step } = yield* StepRunner;727    const run = yield* step("load", Schema.Option(AnswerRun), load(params));728729    if (Option.isNone(run)) {730      return yield* Effect.die(new UnknownRequest(params));731    }732733    const outcome = yield* carry(734      params,735      {736        effects: callsOf(nextSteps(run.value)),737        outcome: outcomeOf(run.value.state),738      },739      { Land: 0, Merge: 0, RunChecks: 0 },740      Option.none()741    );742743    yield* notes(params, outcome);744745    return outcome;746  });