Skip to content
Myr

program.ts

This file

Path

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

664 lines · 18.0 KiB · TypeScript

Last changed by

Merge perf/gate-path into mainoscabrielbefore adoption3704c58

History of this file

Take it

1// Step names carry their attempt (`merge#2`), so a merge onto a main that moved is a2// new step, not a replay. The run stops when a port step finds nothing to do, or it3// could ask for the same call forever.4import { HostBusy } from "@repo/artifacts/repo-host";5import type { RepoHost } from "@repo/artifacts/repo-host";6import type { CheckRunner } from "@repo/checks/check-runner";7import type { EvidenceStore } from "@repo/checks/evidence-store";8import {9  AnswerReport,10  AnswerRun,11  NextStep,12  ReportedCommand,13  Steps,14} from "@repo/project/answer-runs";15import { nextSteps, runStep } from "@repo/project/answer-runs/steps";16import type { Lander } from "@repo/project/lander";17import {18  LandingCommand,19  LandingEffect,20  outcomeOf,21} from "@repo/project/landing";22import { Projects } from "@repo/project/projects";23import { LaneOutcome, Verdict } from "@repo/protocol/domain/answer";24import type { Outcome, StageName } from "@repo/protocol/domain/outcome";25import { CommitSha } from "@repo/protocol/ids";26import type {27  EnvKey,28  LaneName,29  ProjectName,30  RequestId,31} from "@repo/protocol/ids";32import { VerifierBlocked } from "@repo/protocol/refusal";33import type { Refusal } from "@repo/protocol/refusal";34import {35  Array,36  Cause,37  Data,38  Effect,39  Match,40  Option,41  Schedule,42  Schema,43  Struct,44} from "effect";4546import type { AnswerParams } from "../../answer-runs.ts";47import { writeVerdictNote } from "../notes.ts";48import { StepRunner } from "../step.ts";49import type { StepRetry } from "../step.ts";50import { guards, GuardRun, passes } from "./guards.ts";51import { heldBack, HeldBackRun, unsealed } from "./held-back.ts";52import type { Judged } from "./held-back.ts";53import {54  laneOnMain,55  refusalsOf,56  runStage,57  StageRun,58  toCompareOnMain,59} from "./lanes.ts";60import type { Stage } from "./lanes.ts";6162export type AnswerPorts =63  | CheckRunner64  | EvidenceStore65  | Lander66  | Projects67  | RepoHost68  | StepRunner;6970export class UnknownRequest extends Data.TaggedError("UnknownRequest")<{71  readonly project: ProjectName;72  readonly requestId: RequestId;73}> {}7475class LandBusy extends Data.TaggedError("LandBusy")<{76  readonly attempt: number;77}> {}7879export const landRetry: StepRetry = {80  backoff: "exponential",81  delayMs: 1000,82  limit: 3,83};8485export const Reported = Schema.Struct({86  command: ReportedCommand,87  report: Schema.optionalKey(AnswerReport),88});8990export type Reported = typeof Reported.Type;9192const Reporting = Schema.Option(Reported);9394type NextStep = typeof NextStep.Type;9596type Steps = typeof Steps.Type;9798type Call<Tag extends NextStep["_tag"]> = Extract<99  NextStep,100  { readonly _tag: Tag }101>;102103interface Attempts {104  readonly Land: number;105  readonly Merge: number;106  readonly RunChecks: number;107}108109const reported = (110  command: LandingCommand,111  report?: AnswerReport112): Option.Option<Reported> =>113  Option.some(report === undefined ? { command } : { command, report });114115const callsOf = (effects: readonly LandingEffect[]): readonly NextStep[] =>116  effects.flatMap((effect) =>117    LandingEffect.$match(effect, {118      Emit: (): readonly NextStep[] => [],119      Land: ({ main, tree }) => [NextStep.cases.Land.make({ main, tree })],120      Merge: ({ base, fork, head, main }) => [121        NextStep.cases.Merge.make({ base, fork, head, main }),122      ],123      Record: () => [],124      Retry: ({ at }) => [NextStep.cases.Retry.make({ at })],125      RunChecks: ({ tree }) => [NextStep.cases.RunChecks.make({ tree })],126    })127  );128129const keyOf = (call: NextStep): string =>130  NextStep.match(call, {131    Land: ({ main, tree }) => `land ${main} ${tree}`,132    Merge: ({ head, main }) => `merge ${head} onto ${main}`,133    Retry: () => "retry",134    RunChecks: ({ tree }) => `checks ${tree}`,135  });136137const waitsOn = (run: AnswerRun, call: NextStep) =>138  callsOf(nextSteps(run)).some((each) => keyOf(each) === keyOf(call));139140const projectOf = (project: ProjectName) =>141  Projects.use((projects) => projects.get(project)).pipe(Effect.orDie);142143const load = ({ project, requestId }: AnswerParams) =>144  Effect.flatMap(projectOf(project), (api) => api.answer(requestId));145146const portCall = (147  params: AnswerParams,148  call: Call<"Land" | "Merge">,149  effect: LandingEffect,150  prepare: (run: AnswerRun) => Effect.Effect<AnswerRun, never, Projects> = (151    run152  ) => Effect.succeed(run)153) =>154  Effect.gen(function* () {155    const api = yield* projectOf(params.project);156    const run = yield* api.answer(params.requestId);157158    if (Option.isNone(run) || !waitsOn(run.value, call)) {159      return Option.none();160    }161162    const ready = yield* prepare(run.value);163164    return yield* runStep(ready, effect, api.landings);165  });166167const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));168169const leakIn = (params: AnswerParams, verdict: Verdict, where: string) =>170  Effect.gen(function* () {171    const text = yield* Effect.orDie(encodeVerdict(verdict));172    const api = yield* projectOf(params.project);173    const found = yield* api.scanForValues({ text });174175    if (Option.isSome(found)) {176      yield* Effect.logWarning(177        "an answer's verdict note held a stored write-only value; it was not written"178      ).pipe(179        Effect.annotateLogs({180          item: found.value,181          project: params.project,182          requestId: params.requestId,183          where,184        })185      );186    }187188    return found;189  });190191const withSafeNote = (params: AnswerParams) => (run: AnswerRun) =>192  run.verdict === undefined193    ? Effect.succeed(run)194    : Effect.map(leakIn(params, run.verdict, "canonical"), (leaked) =>195        Option.isSome(leaked) ? Struct.omit(run, ["verdict"]) : run196      );197198const merge = (params: AnswerParams, call: Call<"Merge">) =>199  portCall(200    params,201    call,202    LandingEffect.Merge({203      base: call.base,204      fork: call.fork,205      head: call.head,206      main: call.main,207    })208  );209210const land = (params: AnswerParams, call: Call<"Land">) =>211  Effect.flatMap(212    portCall(213      params,214      call,215      LandingEffect.Land({ main: call.main, tree: call.tree }),216      withSafeNote(params)217    ),218    (given) =>219      Option.isSome(given) && LandingCommand.$is("Busy")(given.value.command)220        ? Effect.fail(new LandBusy({ attempt: given.value.command.attempt }))221        : Effect.succeed(given)222  );223224const stage = (225  params: AnswerParams,226  tree: Call<"RunChecks">["tree"],227  name: Stage,228  attempt: number229) =>230  Effect.gen(function* () {231    const { step } = yield* StepRunner;232233    const ran = yield* step(234      `${name}#${attempt}`,235      StageRun,236      Effect.flatMap(load(params), (run) =>237        Option.match(run, {238          onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),239          onSome: (found) => runStage(found, tree, name),240        })241      )242    );243244    if (!StageRun.guards.Ran(ran)) {245      return { ran, refusals: [] };246    }247248    // Each lane's comparison is its own container job and its own step, so249    // they run at once: a step's name is its lane's, replayed or not.250    const onMain = yield* Effect.forEach(251      toCompareOnMain(ran),252      (lane) =>253        Effect.map(254          step(255            `main:${ran.checked.main}:${lane.lane}`,256            LaneOutcome,257            laneOnMain(ran.checked, lane)258          ),259          (outcome) => [lane.lane, outcome] as const260        ),261      { concurrency: "unbounded" }262    );263264    return {265      ran,266      refusals: refusalsOf(ran, new Map<LaneName, LaneOutcome>(onMain)),267    };268  });269270const uncountedRefusals = (cheap: StageRun) =>271  StageRun.guards.Ran(cheap) && cheap.uncounted !== undefined272    ? Effect.as(273        Effect.logWarning(274          `the ratchet ${cheap.uncounted} printed no count on ${cheap.checked.tree}`275        ),276        [new VerifierBlocked({})]277      )278    : Effect.succeed([]);279280interface Ran {281  readonly given: Option.Option<Reported>;282  readonly judged: Option.Option<Judged>;283}284285/** The checks stage runs only when the cheap one refused nothing, and the held-back one only when neither did. */286const refusingStage = (input: {287  readonly checked: boolean;288  readonly held: readonly Refusal[];289  readonly last: readonly Refusal[];290}): Option.Option<StageName> => {291  if (input.held.length > 0) {292    return Option.some("heldBack");293  }294295  if (input.last.length > 0) {296    return Option.some(input.checked ? "checks" : "cheap");297  }298299  return Option.none();300};301302const ranOnly = (given: Option.Option<Reported>): Ran => ({303  given,304  judged: Option.none(),305});306307// `VerifierBlocked` names nothing, so the scan is no oracle on which item a guess308// matched; only the platform's log names the items, never a value.309const quarantine = (310  params: AnswerParams,311  items: readonly EnvKey[]312): Effect.Effect<readonly VerifierBlocked[]> =>313  Array.isReadonlyArrayEmpty(items)314    ? Effect.succeed([])315    : Effect.as(316        Effect.logWarning(317          "an answer adds a file holding a stored write-only value"318        ).pipe(319          Effect.annotateLogs({320            items: items.join(","),321            project: params.project,322            requestId: params.requestId,323          })324        ),325        [new VerifierBlocked({})]326      );327328const guardedOut = (329  params: AnswerParams,330  call: Call<"RunChecks">,331  run: Extract<GuardRun, { readonly _tag: "Guarded" }>332) =>333  Effect.map(quarantine(params, run.quarantined), (quarantined): Ran =>334    ranOnly(335      reported(336        LandingCommand.Checked({337          decisions: [],338          finish: run.finish,339          refusals: [...run.refusals, ...quarantined],340          tree: call.tree,341        }),342        // The landing guards hold the shape of the tree, as stage 1 does a push's.343        { heldBack: [], lanes: [], stage: "shape" }344      )345    )346  );347348const checks = (349  params: AnswerParams,350  call: Call<"RunChecks">,351  attempt: number,352  earlier: Option.Option<Judged>353): Effect.Effect<Ran, never, AnswerPorts> =>354  Effect.gen(function* () {355    const guarded = yield* guards(params, call.tree, attempt);356357    if (Option.isSome(guarded) && !passes(guarded.value)) {358      return yield* GuardRun.match(guarded.value, {359        Blocked: ({ attempt: at }) =>360          Effect.succeed(361            ranOnly(reported(LandingCommand.Blocked({ attempt: at })))362          ),363        Guarded: (run) => guardedOut(params, call, run),364        Moved: () => Effect.succeed(ranOnly(Option.none())),365      });366    }367368    const ran = yield* stage(params, call.tree, "cheap", attempt);369370    const cheap = {371      ...ran,372      refusals: [...ran.refusals, ...(yield* uncountedRefusals(ran.ran))],373    };374375    const judged =376      StageRun.guards.Ran(cheap.ran) && cheap.refusals.length === 0377        ? yield* stage(params, call.tree, "checks", attempt)378        : undefined;379380    const last = judged ?? cheap;381382    const sealed =383      judged !== undefined &&384      StageRun.guards.Ran(judged.ran) &&385      judged.refusals.length === 0 &&386      judged.ran.checked.sealed === true387        ? yield* heldBack(params, call.tree, attempt, earlier)388        : unsealed;389390    const counts = StageRun.guards.Ran(cheap.ran)391      ? Option.fromUndefinedOr(cheap.ran.counts)392      : Option.none();393394    if (HeldBackRun.guards.Blocked(sealed)) {395      return ranOnly(396        reported(LandingCommand.Blocked({ attempt: sealed.attempt }))397      );398    }399400    const held = HeldBackRun.guards.Judged(sealed)401      ? Option.some(sealed)402      : Option.none();403404    const refusedAt = refusingStage({405      checked: judged !== undefined,406      held: Option.match(held, {407        onNone: () => [],408        onSome: ({ refusals }) => refusals,409      }),410      last: last.refusals,411    });412413    const given = StageRun.match(last.ran, {414      Blocked: ({ attempt: at }) =>415        reported(LandingCommand.Blocked({ attempt: at })),416      Moved: () => Option.none(),417      Ran: ({ checked, lanes }) =>418        reported(419          LandingCommand.Checked({420            decisions: [],421            finish: checked.finish,422            refusals: [423              ...last.refusals,424              ...Option.match(held, {425                onNone: () => [],426                onSome: ({ refusals }) => refusals,427              }),428            ],429            tree: call.tree,430          }),431          {432            heldBack: Option.match(held, {433              onNone: () => [],434              onSome: ({ results }) => results,435            }),436            lanes: [437              ...(judged !== undefined && StageRun.guards.Ran(cheap.ran)438                ? cheap.ran.lanes439                : []),440              ...lanes,441            ].map(({ result }) => result),442            ...Option.match(counts, {443              onNone: () => ({}),444              onSome: (ratchets) => ({ ratchets }),445            }),446            ...Option.match(refusedAt, {447              onNone: () => ({}),448              onSome: (refusing) => ({ stage: refusing }),449            }),450          }451        ),452    });453454    return { given, judged: held };455  });456457const record = (params: AnswerParams, given: Option.Option<Reported>) =>458  Effect.gen(function* () {459    const api = yield* projectOf(params.project);460461    if (Option.isSome(given)) {462      const advanced = yield* api.advanceAnswer(463        params.requestId,464        given.value.command,465        given.value.report466      );467468      const calls = callsOf(advanced.effects);469470      if (Array.isReadonlyArrayNonEmpty(calls)) {471        return { effects: calls, outcome: advanced.outcome } satisfies Steps;472      }473    }474475    const run = yield* api.answer(params.requestId);476477    if (Option.isNone(run)) {478      return yield* Effect.die(new UnknownRequest(params));479    }480481    return {482      effects: callsOf(nextSteps(run.value)),483      outcome: outcomeOf(run.value.state),484    } satisfies Steps;485  });486487const Noted = Schema.TaggedUnion({488  Unjudged: {},489  Unwritten: { reason: Schema.String },490  Written: { changed: Schema.Boolean, notesTip: CommitSha },491});492493const noteRetry = {494  schedule: Schedule.exponential("250 millis"),495  times: 2,496  while: Schema.is(HostBusy),497};498499const shownVerdict = (run: AnswerRun) =>500  Option.map(Option.fromUndefinedOr(run.verdict), (made): Verdict => ({501    ...made,502    outcome: outcomeOf(run.state),503  }));504505const noteVerdict = (params: AnswerParams) =>506  Effect.gen(function* () {507    const run = yield* load(params);508509    const judged = Option.flatMap(run, (found) =>510      Option.map(shownVerdict(found), (verdict) => ({511        fork: found.state.request.fork,512        verdict,513      }))514    );515516    if (Option.isNone(judged)) {517      return Noted.cases.Unjudged.make({});518    }519520    const { fork, verdict } = judged.value;521522    // A note that holds a stored value is not written; the verdict stands in the project.523    if (Option.isSome(yield* leakIn(params, verdict, "fork"))) {524      return Noted.cases.Unwritten.make({ reason: "SecretInOutput" });525    }526527    const written = yield* writeVerdictNote({528      fork,529      head: verdict.head,530      verdict,531    }).pipe(Effect.retry(noteRetry));532533    return Noted.cases.Written.make(written);534  }).pipe(535    // Anything but an interruption is recorded: the note is bookkeeping, and a fork its536    // answerer filled with refs of their own may break it.537    Effect.catchCause((cause) =>538      Cause.hasInterruptsOnly(cause)539        ? Effect.interrupt540        : Effect.as(541            Effect.logWarning(542              "an answer's verdict note was not written",543              cause544            ),545            Noted.cases.Unwritten.make({546              reason: Option.match(Cause.findErrorOption(cause), {547                onNone: () => "defect",548                onSome: ({ _tag }) => _tag,549              }),550            })551          )552    )553  );554555const notes = (556  params: AnswerParams,557  outcome: Outcome558): Effect.Effect<void, never, AnswerPorts> =>559  Effect.flatMap(StepRunner, ({ step }) =>560    Effect.asVoid(step(`notes:${outcome._tag}`, Noted, noteVerdict(params)))561  );562563const portStep = (564  params: AnswerParams,565  call: Call<"Land" | "Merge" | "RunChecks">,566  attempt: number,567  earlier: Option.Option<Judged>568): Effect.Effect<Ran, never, AnswerPorts> =>569  Effect.flatMap(StepRunner, ({ step }) =>570    Match.valueTags(call, {571      Land: (landing) =>572        step(573          `land#${attempt}`,574          Reporting,575          land(params, landing),576          landRetry577        ).pipe(578          Effect.catchTag("LandBusy", ({ attempt: at }) =>579            Effect.succeed(reported(LandingCommand.Busy({ attempt: at })))580          ),581          Effect.map(ranOnly)582        ),583      Merge: (merging) =>584        Effect.map(585          step(`merge#${attempt}`, Reporting, merge(params, merging)),586          ranOnly587        ),588      RunChecks: (checking) => checks(params, checking, attempt, earlier),589    })590  );591592const nameOf = {593  Land: "land",594  Merge: "merge",595  RunChecks: "checks",596} as const satisfies Record<keyof Attempts, string>;597598const carry = (599  params: AnswerParams,600  at: Steps,601  attempts: Attempts,602  earlier: Option.Option<Judged>603): Effect.Effect<Outcome, never, AnswerPorts> =>604  Effect.gen(function* () {605    if (at.effects.some(NextStep.guards.Retry)) {606      return at.outcome;607    }608609    const call = at.effects.find(610      (each): each is Call<"Land" | "Merge" | "RunChecks"> =>611        !NextStep.guards.Retry(each)612    );613614    if (call === undefined) {615      return at.outcome;616    }617618    const attempt = attempts[call._tag] + 1;619    const { given, judged } = yield* portStep(params, call, attempt, earlier);620    const { step } = yield* StepRunner;621622    const next = yield* step(623      `record:${nameOf[call._tag]}#${attempt}`,624      Steps,625      record(params, given)626    );627628    if (Option.isNone(given)) {629      return next.outcome;630    }631632    return yield* carry(633      params,634      next,635      { ...attempts, [call._tag]: attempt },636      Option.orElse(judged, () => earlier)637    );638  });639640export const runAnswer = (641  params: AnswerParams642): Effect.Effect<Outcome, never, AnswerPorts> =>643  Effect.gen(function* () {644    const { step } = yield* StepRunner;645    const run = yield* step("load", Schema.Option(AnswerRun), load(params));646647    if (Option.isNone(run)) {648      return yield* Effect.die(new UnknownRequest(params));649    }650651    const outcome = yield* carry(652      params,653      {654        effects: callsOf(nextSteps(run.value)),655        outcome: outcomeOf(run.value.state),656      },657      { Land: 0, Merge: 0, RunChecks: 0 },658      Option.none()659    );660661    yield* notes(params, outcome);662663    return outcome;664  });