Skip to content
Myr

lanes.ts

This file

Path

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

548 lines · 15.5 KiB · TypeScript

Last changed by

Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8

History of this file

Take it

1// The merged tree is checked in the answer's fork, where `Lander.merge` keeps it, so a2// merge needs no write token on the canonical repo.3import {4  CheckAt,5  CheckLane,6  CheckRunner,7  outputOf,8} from "@repo/checks/check-runner";9import type { CheckRun, LaneEvidence } from "@repo/checks/check-runner";10import { EvidenceStore } from "@repo/checks/evidence-store";11import { lintToZeroCount } from "@repo/checks/kinds/lint-to-zero";12import { countLanes, measure } from "@repo/checks/kinds/ratchet";13import { classifyFailure } from "@repo/gate/classify";14import { MeasuredCount, runBlockOf } from "@repo/project/answer-runs";15import type { AnswerRun } from "@repo/project/answer-runs";16import { noRunEnv, UnlandedRunEnv } from "@repo/project/env-port";17import { LandingState } from "@repo/project/landing";18import { Projects } from "@repo/project/projects";19import { LaneOutcome, LaneResult } from "@repo/protocol/domain/answer";20import { CheckSpec } from "@repo/protocol/domain/check";21import { AskKind } from "@repo/protocol/domain/kind";22import { RunBlock } from "@repo/protocol/domain/run";23import {24  CommitSha,25  LandedSha,26  LaneName,27  ProjectName,28  RatchetName,29  RepoName,30  RepoPath,31  RequestId,32  TreeSha,33} from "@repo/protocol/ids";34import { ChecksFailed } from "@repo/protocol/refusal";35import type { Flake, StaleBase, VerifierBlocked } from "@repo/protocol/refusal";36import { Array, Effect, Option, Order, Result, Schema } from "effect";3738export const cheapLanes = ["format", "lint", "types"] as const;3940export type Stage = "cheap" | "checks";4142const isCheap = (lane: LaneName) =>43  cheapLanes.some((name): boolean => name === lane);4445export const lanesFor = (run: AnswerRun, stage: Stage): readonly CheckLane[] =>46  run.lanes.filter(47    ({ lane }) =>48      (stage === "cheap") === (isCheap(lane) && lane !== run.askLane)49  );5051export const Checked = Schema.Struct({52  askLane: Schema.optionalKey(LaneName),53  attempt: Schema.Int,54  base: CommitSha,55  changed: Schema.Array(RepoPath),56  env: Schema.optionalKey(UnlandedRunEnv),57  finish: AskKind.fields.finish,58  fork: RepoName,59  main: LandedSha,60  project: ProjectName,61  repo: RepoName,62  requestId: RequestId,63  run: Schema.optionalKey(RunBlock),64  sealed: Schema.optionalKey(Schema.Boolean),65  tree: TreeSha,66});6768export type Checked = typeof Checked.Type;6970export const LaneRun = Schema.Struct({71  check: CheckLane,72  failingPaths: Schema.Array(RepoPath),73  first: LaneOutcome,74  rerun: Schema.optionalKey(LaneOutcome),75  result: LaneResult,76});7778export type LaneRun = typeof LaneRun.Type;7980export const StageRun = Schema.TaggedUnion({81  Blocked: { attempt: Schema.Int },82  Moved: {},83  Ran: {84    checked: Checked,85    counts: Schema.optionalKey(Schema.Array(MeasuredCount)),86    lanes: Schema.Array(LaneRun),87    uncounted: Schema.optionalKey(RatchetName),88  },89});9091export type StageRun = typeof StageRun.Type;9293type Ran = Extract<StageRun, { readonly _tag: "Ran" }>;9495// The extension starts with a letter, so an address and port (`127.0.0.1:8080`) is no file.96const LOCATION =97  /(?<![\w./@+-])(?<path>(?:[\w@+-][\w.@+-]*\/)*[\w@+-][\w.@+-]*\.[A-Za-z][A-Za-z0-9]*):\d+/gu;9899const TEST_FILE =100  /(?:^|\/)(?:tests?|__tests__)\/|\.(?:test|spec)\.[A-Za-z0-9]+$/u;101102export const failingPathsOf = (output: string): readonly RepoPath[] =>103  Array.sort(104    Array.dedupe(105      [...output.matchAll(LOCATION)].flatMap(({ groups }) =>106        groups?.path === undefined || TEST_FILE.test(groups.path)107          ? []108          : [groups.path]109      )110    ),111    Order.String112  ).map((path) => RepoPath.make(path));113114export const laneLog = (115  result: LaneResult,116  evidence: Option.Option<LaneEvidence>117): string =>118  [119    `${result.lane}: ${result.result} in ${result.durationMs} ms`,120    `$ ${result.command}`,121    ...Option.toArray(122      Option.flatMap(evidence, ({ signature }) =>123        Option.fromUndefinedOr(signature)124      )125    ),126    ...Option.toArray(127      Option.flatMap(evidence, ({ weakness }) =>128        Option.fromUndefinedOr(weakness)129      )130    ),131  ].join("\n");132133export const { withheld } = ChecksFailed;134135const isTrouble = (result: LaneOutcome) =>136  result === "flaked" || result === "blocked";137138interface ByLane {139  readonly evidence: ReadonlyMap<LaneName, LaneEvidence>;140  readonly results: ReadonlyMap<LaneName, LaneResult>;141}142143const byLane = (run: CheckRun): ByLane => ({144  evidence: new Map(run.evidence.map((each) => [each.lane, each])),145  results: new Map(run.lanes.map((each) => [each.lane, each])),146});147148const noRun: ByLane = { evidence: new Map(), results: new Map() };149150interface Standing {151  readonly check: CheckLane;152  readonly first: LaneResult;153  readonly again: Option.Option<LaneResult>;154  readonly stands: LaneResult;155  readonly said: Option.Option<LaneEvidence>;156}157158const standingOf = (159  lane: CheckLane,160  first: ByLane,161  fresh: ByLane162): Standing => {163  const began = first.results.get(lane.lane) ?? {164    command: lane.command,165    durationMs: 0,166    lane: lane.lane,167    result: "blocked",168  };169170  const again = Option.fromUndefinedOr(fresh.results.get(lane.lane));171172  return {173    again,174    check: lane,175    first: began,176    said: Option.fromUndefinedOr(177      (Option.isSome(again) ? fresh : first).evidence.get(lane.lane)178    ),179    stands: Option.getOrElse(again, () => began),180  };181};182183const laneRunOf = (checked: Checked, standing: Standing): LaneRun => {184  const signature = Option.getOrElse(185    Option.flatMap(standing.said, ({ signature: said }) =>186      Option.fromUndefinedOr(said)187    ),188    () => ""189  );190191  const judged: LaneRun = {192    check: standing.check,193    failingPaths:194      standing.first.lane === checked.askLane ? [] : failingPathsOf(signature),195    first: standing.first.result,196    result: standing.stands,197  };198199  return Option.match(standing.again, {200    onNone: () => judged,201    onSome: ({ result }) => ({ ...judged, rerun: result }),202  });203};204205const checkedOf = (run: AnswerRun, tree: TreeSha): Option.Option<Checked> => {206  const { state } = run;207208  if (!LandingState.guards.Checking(state) || state.tree !== tree) {209    return Option.none();210  }211212  const { request } = state;213214  const checked = {215    attempt: state.attempt,216    base: request.base,217    changed: state.changes.map(({ path }) => path),218    finish: run.finish,219    fork: request.fork,220    main: state.main,221    project: request.project,222    repo: run.repo,223    requestId: request.requestId,224    tree: state.tree,225  };226227  const asked =228    run.askLane === undefined ? checked : { ...checked, askLane: run.askLane };229230  const blocked = run.run === undefined ? asked : { ...asked, run: run.run };231232  const carried =233    run.env === undefined ? blocked : { ...blocked, env: run.env };234235  return Option.some(236    run.sealed === true ? { ...carried, sealed: true } : carried237  );238};239240const withLane = (241  ran: CheckRun,242  result: LaneResult,243  evidence: Option.Option<LaneEvidence>244): CheckRun => ({245  ...ran,246  evidence: [247    ...ran.evidence.filter(({ lane }) => lane !== result.lane),248    ...Option.toArray(evidence),249  ],250  lanes: ran.lanes.map((each) => (each.lane === result.lane ? result : each)),251});252253// A lint with findings anywhere exits 1, so its exit code says nothing here.254const countedAskLane = (255  run: AnswerRun,256  ran: CheckRun257): Effect.Effect<CheckRun> => {258  const { ask, askLane } = run;259260  const result = ran.lanes.find(({ lane }) => lane === askLane);261262  if (263    ask === undefined ||264    askLane === undefined ||265    !CheckSpec.guards.LintToZero(ask.check) ||266    result === undefined ||267    isTrouble(result.result)268  ) {269    return Effect.succeed(ran);270  }271272  const { check } = ask;273274  return Effect.fromOption(outputOf(ran, askLane)).pipe(275    Effect.flatMap((stdout) =>276      lintToZeroCount({277        asked: ask.territory,278        check,279        modules: run.counts?.modules ?? [],280        stdout,281      })282    ),283    Effect.map((count) =>284      count === 0285        ? withLane(ran, { ...result, result: "passed" }, Option.none())286        : withLane(287            ran,288            { ...result, result: "failed" },289            Option.some({290              lane: askLane,291              signature: `${check.rule}: ${count} in ${check.territory ?? ask.territory.module}`,292            })293          )294    ),295    Effect.orElseSucceed(() =>296      withLane(297        ran,298        { ...result, result: "loadError" },299        Option.some({ lane: askLane })300      )301    )302  );303};304305interface Counted {306  readonly counts: readonly MeasuredCount[];307  readonly uncounted: Option.Option<RatchetName>;308}309310const countRatchets = <E, R>(311  run: AnswerRun,312  job: (lanes: readonly CheckLane[]) => Effect.Effect<CheckRun, E, R>313): Effect.Effect<Counted, E, R> =>314  Effect.gen(function* () {315    const specs = run.counts?.ratchets ?? [];316317    if (!Array.isReadonlyArrayNonEmpty(specs)) {318      return { counts: [], uncounted: Option.none() };319    }320321    const lanes = countLanes(specs);322323    const ran = yield* job(lanes);324325    const printed = (command: string) =>326      Option.getOrElse(327        Option.flatMap(328          Option.fromUndefinedOr(329            lanes.find((lane) => lane.command === command)330          ),331          ({ lane }) => outputOf(ran, lane)332        ),333        () => ""334      );335336    const counts = yield* Effect.forEach(specs, (spec) =>337      measure(338        spec,339        (command) => Effect.succeed({ code: 0, stdout: printed(command) }),340        run.counts?.modules ?? []341      ).pipe(Effect.mapError(() => spec.name))342    ).pipe(Effect.result);343344    return Result.match(counts, {345      onFailure: (name) => ({ counts: [], uncounted: Option.some(name) }),346      onSuccess: (all) => ({ counts: all.flat(), uncounted: Option.none() }),347    });348  });349350const countFields = (counted: Counted): Pick<Ran, "counts" | "uncounted"> =>351  Option.match(counted.uncounted, {352    onNone: () => ({ counts: counted.counts }),353    onSome: (uncounted) => ({ counts: counted.counts, uncounted }),354  });355356export const runStage = (357  run: AnswerRun,358  tree: TreeSha,359  stage: Stage360): Effect.Effect<StageRun, never, CheckRunner | EvidenceStore | Projects> =>361  Option.match(checkedOf(run, tree), {362    onNone: () => Effect.succeed(StageRun.cases.Moved.make({})),363    onSome: (checked) =>364      Effect.gen(function* () {365        const runner = yield* CheckRunner;366        const evidence = yield* EvidenceStore;367        const lanes = lanesFor(run, stage);368369        // The project scans each log for its stored values here, where the values are;370        // never in the sandbox.371        const api = yield* Projects.use((projects) =>372          projects.get(checked.project)373        ).pipe(Effect.orDie);374375        const scan = (text: string) => api.scanForValues({ text });376377        const remerges = LandingState.guards.Checking(run.state)378          ? run.state.remerges379          : 0;380381        const counting = stage === "cheap" && run.counts !== undefined;382383        if (!Array.isReadonlyArrayNonEmpty(lanes) && !counting) {384          return StageRun.cases.Ran.make({ checked, lanes: [] });385        }386387        const block = yield* runBlockOf(checked);388389        const job = (each: readonly CheckLane[]) =>390          runner391            .run({392              ...(checked.env ?? noRunEnv),393              at: CheckAt.cases.Tree.make({ tree }),394              lanes: each,395              project: checked.project,396              repo: checked.fork,397              run: block,398            })399            .pipe(Effect.flatMap((ran) => countedAskLane(run, ran)));400401        const counts = counting402          ? countFields(yield* countRatchets(run, job))403          : {};404405        if (!Array.isReadonlyArrayNonEmpty(lanes)) {406          return StageRun.cases.Ran.make({407            checked,408            lanes: [],409            ...counts,410          });411        }412413        const firstRun = yield* job(lanes);414        const first = byLane(firstRun);415416        const troubled = lanes.filter(({ lane }) =>417          isTrouble(first.results.get(lane)?.result ?? "blocked")418        );419420        const fresh = Array.isReadonlyArrayNonEmpty(troubled)421          ? byLane(yield* job(troubled))422          : noRun;423424        const laneRuns = yield* Effect.forEach(lanes, (lane) => {425          const standing = standingOf(lane, first, fresh);426          const judged = laneRunOf(checked, standing);427428          if (standing.first.result === "passed") {429            return Effect.succeed(judged);430          }431432          const text = laneLog(standing.stands, standing.said);433434          return Effect.flatMap(scan(text), (found) =>435            Option.match(found, {436              onNone: () =>437                Effect.map(438                  evidence.put({439                    attempt: remerges + 1,440                    lane: lane.lane,441                    project: checked.project,442                    requestId: checked.requestId,443                    text,444                  }),445                  (logRef) => ({446                    ...judged,447                    result: { ...judged.result, logRef },448                  })449                ),450              onSome: (item) =>451                Effect.as(452                  Effect.logWarning(453                    "a lane's log held a stored write-only value; it was not kept"454                  ).pipe(455                    Effect.annotateLogs({456                      item,457                      lane: lane.lane,458                      project: checked.project,459                      requestId: checked.requestId,460                    })461                  ),462                  {463                    ...judged,464                    result: { ...judged.result, logRef: withheld },465                  }466                ),467            })468          );469        });470471        return StageRun.cases.Ran.make({472          checked,473          lanes: laneRuns,474          ...counts,475        });476      }).pipe(477        Effect.catchTag("VerifierBlocked", () =>478          Effect.succeed(479            StageRun.cases.Blocked.make({ attempt: checked.attempt })480          )481        )482      ),483  });484485export const toCompareOnMain = (ran: Ran): readonly CheckLane[] =>486  ran.lanes487    .filter(488      ({ check, first }) =>489        first !== "passed" && check.lane !== ran.checked.askLane490    )491    .map(({ check }) => check);492493export const refusalsOf = (494  ran: Ran,495  onMain: ReadonlyMap<LaneName, LaneOutcome>496): readonly (ChecksFailed | Flake | StaleBase | VerifierBlocked)[] => {497  const { checked } = ran;498  const changed = new Set(checked.changed);499500  return Array.getSomes(501    ran.lanes.map(({ failingPaths, first, rerun, result }) =>502      Option.flatMap(Option.fromUndefinedOr(result.logRef), (logRef) =>503        classifyFailure(504          {505            command: result.command,506            failingPaths,507            isDoctor: false,508            lane: result.lane,509            logRef,510            onMain:511              result.lane === checked.askLane512                ? "passed"513                : (onMain.get(result.lane) ?? "blocked"),514            onMerged: first,515            rerun: Option.fromUndefinedOr(rerun),516          },517          changed,518          { base: checked.base, main: checked.main }519        )520      )521    )522  );523};524525export const laneOnMain = (526  checked: Checked,527  lane: CheckLane528): Effect.Effect<LaneOutcome, never, CheckRunner> =>529  Effect.flatMap(runBlockOf(checked), (block) =>530    CheckRunner.use((runner) =>531      runner.run({532        ...(checked.env ?? noRunEnv),533        at: CheckAt.cases.Commit.make({ commit: checked.main }),534        lanes: [lane],535        project: checked.project,536        repo: checked.repo,537        run: block,538      })539    )540  ).pipe(541    Effect.map(542      ({ lanes }): LaneOutcome =>543        lanes.find((each) => each.lane === lane.lane)?.result ?? "blocked"544    ),545    Effect.catchTag("VerifierBlocked", () =>546      Effect.succeed<LaneOutcome>("blocked")547    )548  );