Skip to content
Myr

Merge perf/gate-path into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents c007606, 2f2c840 · Browse files · 9 files+694 added−37 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+694 added−37 removed

  • tests:+462 added−3 removed
  • other:+232 added−34 removed

9 files+694 added−37 removed

modified:apps/platform/src/workflows/answer/lanes.ts+48 added-22 removed
305 unmodified lines
306 readonly counts: readonly MeasuredCount[];307 readonly uncounted: Option.Option<RatchetName>;308}309310/** What the lane running a command printed, or nothing. */311const printedBy =312 (lanes: readonly CheckLane[], ran: CheckRun) => (command: string) =>313 Option.getOrElse(314 Option.flatMap(315 Option.fromUndefinedOr(lanes.find((lane) => lane.command === command)),316 ({ lane }) => outputOf(ran, lane)317 ),318 () => ""319 );320321/** The ratchets' counts, read from the lanes a run printed. */310const countRatchets = <E, R>(322const countRatchets = (323 run: AnswerRun,312 job: (lanes: readonly CheckLane[]) => Effect.Effect<CheckRun, E, R>313): Effect.Effect<Counted, E, R> =>324 lanes: readonly CheckLane[],325 ran: CheckRun326): Effect.Effect<Counted> =>327 Effect.gen(function* () {328 const specs = run.counts?.ratchets ?? [];329330 if (!Array.isReadonlyArrayNonEmpty(specs)) {331 return { counts: [], uncounted: Option.none() };332 }333321 const lanes = countLanes(specs);334 const printed = printedBy(lanes, ran);335323 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) }),
6 unmodified lines
346 onSuccess: (all) => ({ counts: all.flat(), uncounted: Option.none() }),347 });348 });349350/** The ratchets' lanes, counted in the cheap stage. */351const countingLanesOf = (run: AnswerRun, stage: Stage): readonly CheckLane[] =>352 stage === "cheap" && run.counts !== undefined353 ? countLanes(run.counts.ratchets)354 : [];355356const namesApart = (357 lanes: readonly CheckLane[],358 counting: readonly CheckLane[]359) => counting.every((count) => lanes.every(({ lane }) => lane !== count.lane));360361const countFields = (counted: Counted): Pick<Ran, "counts" | "uncounted"> =>362 Option.match(counted.uncounted, {363 onNone: () => ({ counts: counted.counts }),364 onSome: (uncounted) => ({ counts: counted.counts, uncounted }),
23 unmodified lines
388 const remerges = LandingState.guards.Checking(run.state)389 ? run.state.remerges390 : 0;391381 const counting = stage === "cheap" && run.counts !== undefined;392 const counting = countingLanesOf(run, stage);393383 if (!Array.isReadonlyArrayNonEmpty(lanes) && !counting) {394 if (395 !Array.isReadonlyArrayNonEmpty(lanes) &&396 !Array.isReadonlyArrayNonEmpty(counting)397 ) {398 return StageRun.cases.Ran.make({ checked, lanes: [] });399 }400401 const block = yield* runBlockOf(checked);
9 unmodified lines
411 run: block,412 })413 .pipe(Effect.flatMap((ran) => countedAskLane(run, ran)));414401 const counts = counting402 ? countFields(yield* countRatchets(run, job))415 // The ratchets are counted in the stage's own job, one container for416 // both, unless a ratchet is named as a lane is: then it runs apart.417 const together =418 !Array.isReadonlyArrayNonEmpty(lanes) || namesApart(lanes, counting);419420 const firstRun = yield* job(together ? [...lanes, ...counting] : lanes);421422 const counts = Array.isReadonlyArrayNonEmpty(counting)423 ? countFields(424 yield* countRatchets(425 run,426 counting,427 together ? firstRun : yield* job(counting)428 )429 )430 : {};431432 if (!Array.isReadonlyArrayNonEmpty(lanes)) {433 return StageRun.cases.Ran.make({
2 unmodified lines
436 ...counts,437 });438 }439413 const firstRun = yield* job(lanes);440 const first = byLane(firstRun);441442 const troubled = lanes.filter(({ lane }) =>443 isTrouble(first.results.get(lane)?.result ?? "blocked")
131 unmodified lines
modified:apps/platform/src/workflows/answer/program.ts+13 added-8 removed
243 unmodified lines
244 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),248 const onMain = yield* Effect.forEach(toCompareOnMain(ran), (lane) =>249 Effect.map(250 step(251 `main:${ran.checked.main}:${lane.lane}`,252 LaneOutcome,253 laneOnMain(ran.checked, lane)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 ),255 (outcome) => [lane.lane, outcome] as const256 )261 { concurrency: "unbounded" }262 );263264 return {265 ran,
399 unmodified lines
modified:apps/platform/test/workflows/answer.fixtures.ts+37 added-2 removed
1import { RefName, RepoHost } from "@repo/artifacts/repo-host";2import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";3import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";4import { CheckAt, CheckRunner, shaOf } from "@repo/checks/check-runner";5import type { CheckJob, LaneEvidence } from "@repo/checks/check-runner";5import type {6 CheckJob,7 LaneEvidence,8 LaneOutput,9} from "@repo/checks/check-runner";10import { EvidenceStoreMemory } from "@repo/checks/evidence-store/memory";11import { AlarmsMemory } from "@repo/project/alarms/memory";12import { AnswerRuns } from "@repo/project/answer-runs";13import type { AnswerReport } from "@repo/project/answer-runs";
134 unmodified lines
148 lane: LaneName,149 runs: readonly ScriptedRun[]150 ) => Effect.Effect<void>;151 readonly jobs: Effect.Effect<readonly CheckJob[]>;152 /** What a lane prints on its stdout at a tree, for a ratchet's count. */153 readonly print: (154 at: CheckAt,155 lane: LaneName,156 stdout: string157 ) => Effect.Effect<void>;158 }159>()("test/Checker") {}160161const keyOf = (at: CheckAt, lane: LaneName) => `${shaOf(at)}:${lane}`;
5 unmodified lines
167 >(new Map());168169 const served = yield* Ref.make<ReadonlyMap<string, number>>(new Map());170 const jobs = yield* Ref.make<readonly CheckJob[]>([]);171 const printed = yield* Ref.make<ReadonlyMap<string, string>>(new Map());172173 const next = (174 key: string,175 runs: Array.NonEmptyReadonlyArray<ScriptedRun>
49 unmodified lines
225 ? [{ lane: lane.lane }]226 : [{ lane: lane.lane, signature: one.signature }];227 });228218 return { durationMs: lanes.length, evidence, heldBack: [], lanes };229 const outputs = yield* Effect.map(Ref.get(printed), (texts) =>230 ran.flatMap(({ lane }): LaneOutput[] =>231 lane.output === "stdout"232 ? [233 {234 lane: lane.lane,235 stdout: texts.get(keyOf(job.at, lane.lane)) ?? "",236 },237 ]238 : []239 )240 );241242 const result = {243 durationMs: lanes.length,244 evidence,245 heldBack: [],246 lanes,247 };248249 return outputs.length === 0 ? result : { ...result, outputs };250 });251252 return Context.make(CheckRunner, { run }).pipe(253 Context.add(Checker, {254 jobs: Ref.get(jobs),255 print: (at, lane, stdout) =>256 Ref.update(printed, (texts) =>257 new Map(texts).set(keyOf(at, lane), stdout)258 ),259 script: (at, lane, runs) =>260 Ref.update(scripts, (known) =>261 new Map(known).set(keyOf(at, lane), runs)262 ),
347 unmodified lines
modified:apps/platform/test/workflows/answer.test.ts+50 added-1 removed
13 unmodified lines
14import type { Lander } from "@repo/project/lander";15import { LanderJob } from "@repo/project/lander/memory";16import { Projects } from "@repo/project/projects";17import { Verdict } from "@repo/protocol/domain/answer";18import { RatchetMeasure } from "@repo/protocol/domain/check";19import { Command, JsonPath } from "@repo/protocol/domain/common";20import { ProjectEvent } from "@repo/protocol/domain/event";21import { Outcome } from "@repo/protocol/domain/outcome";22import type { Policy } from "@repo/protocol/domain/policy";20import { keyOf, LaneName, RequestId } from "@repo/protocol/ids";23import { keyOf, LaneName, RatchetName, RequestId } from "@repo/protocol/ids";24import type { CommitSha, LandedSha } from "@repo/protocol/ids";25import {26 ChecksFailed,27 Flake,
136 unmodified lines
164 });165166const landedAt = (sha: LandedSha) => Outcome.cases.Landed.make({ sha });167168const sized = RatchetName.make("bundle-bytes");169170const sizedLane = LaneName.make(sized);171172/** The project's policy with one ratchet, read as a metric off a command's JSON. */173const withRatchet: Policy = {174 ...policy,175 ratchets: [176 {177 measure: RatchetMeasure.cases.Metric.make({178 command: Command.make("bun run size"),179 path: JsonPath.make("$.bytes"),180 }),181 name: sized,182 },183 ],184};185186const cleanAnswer = Effect.tap(admitted(), (answer) => allGreen(answer.merged));187188const withoutMessage = Layer.effect(189 Projects,
238 unmodified lines
428 }).pipe(Effect.provide(world))429 );430431 it.effect(432 "3. the cheap stage counts the policy's ratchets in its own job, one container for the lanes and the counts",433 () =>434 Effect.gen(function* () {435 const answer = yield* admitted();436437 yield* allGreen(answer.merged);438 yield* Checker.use((script) =>439 Effect.andThen(440 script.script(answer.merged, sizedLane, [{ result: "passed" }]),441 script.print(answer.merged, sizedLane, '{ "bytes": 0 }')442 )443 );444445 const outcome = yield* run(answer, yield* freshSteps());446447 expect(outcome).toStrictEqual(landedAt(yield* mainTip));448 expect(449 (yield* jobsOn(answer.merged)).map(({ lanes }) =>450 lanes.map(({ lane }) => lane)451 )452 ).toStrictEqual([453 [lint, "types", sizedLane],454 [askLane, unit],455 ]);456 }).pipe(Effect.provide(worldWith(withRatchet)))457 );458459 it.effect(460 "3. a lane that never got going and then fails on its fresh run is the answer's failure",461 () =>462 Effect.gen(function* () {463 const answer = yield* admitted();
585 unmodified lines
modified:packages/project/src/outbox.ts+48 added-2 removed
1import { RefName, RepoHost } from "@repo/artifacts/repo-host";2import { CheckAt, CheckRunner } from "@repo/checks/check-runner";3import { Verdict } from "@repo/protocol/domain/answer";4import type { ProjectEvent } from "@repo/protocol/domain/event";5import { RunBlock } from "@repo/protocol/domain/run";6import {7 CommitSha,8 Handle,9 LandedSha,10 ProjectName,11 RepoName,12 RequestId,13 TreeSha,14} from "@repo/protocol/ids";12import type { ProjectName } from "@repo/protocol/ids";15import { Array, DateTime, Effect, Option, Order, Schema, Struct } from "effect";1617import { AnswerRuns } from "./answer-runs.ts";18import type { AnswerQueue } from "./answer-runs.ts";19import { DraftParams, DraftRuns } from "./draft-runs.ts";20import { noRunEnv } from "./env-port.ts";21import { Lander, Rebuild } from "./lander.ts";22import { backoff } from "./landing.ts";23import { MetricPoint, Metrics } from "./metrics.ts";24import type { OutboxRow } from "./project-store/rows.ts";
26 unmodified lines
51 Schema.TaggedStruct("StartDraft", DraftParams.fields),52 Schema.TaggedStruct("Measured", {53 points: Schema.NonEmptyArray(MetricPoint),54 }),55 /**56 * One Checker job with no lanes on a landed commit, so its setup snapshot57 * is there before the next answer: the Checker keeps a snapshot only for58 * the project's own commits, and an answer's tree alone never makes one.59 */60 Schema.TaggedStruct("WarmSetup", {61 at: LandedSha,62 project: ProjectName,63 repo: RepoName,64 run: RunBlock,65 }),66]).pipe(Schema.toTaggedUnion("_tag"));6768export type OutboxBody = typeof OutboxBody.Type;69
63 unmodified lines
133 Array.of134 )135 : Effect.succeed([]);136137/** Kept in the commit that keeps the landing, under the landing's SHA: one job per landing, however often it is heard. */138export const warmRow = (139 job: Omit<Extract<OutboxBody, { readonly _tag: "WarmSetup" }>, "_tag">,140 at: DateTime.Utc141) =>142 outboxRow(`warm:${job.at}`, OutboxBody.cases.WarmSetup.make(job), at);143144export const isDue = (row: OutboxRow, now: DateTime.Utc) =>145 DateTime.isLessThanOrEqualTo(row.notBefore, now);146147export interface OutboxRun {
76 unmodified lines
224 claim: (ids: readonly string[]) => Effect.Effect<readonly string[]>225): Effect.Effect<226 OutboxRun,227 never,207 AnswerRuns | Lander | Projection | RepoHost228 AnswerRuns | CheckRunner | Lander | Projection | RepoHost229> =>230 Effect.gen(function* () {231 const decoded = yield* Effect.forEach(rows, (row) =>232 Effect.map(Effect.orDie(decodeBody(row.body)), (body) => ({ body, row }))
62 unmodified lines
295 ({ body, row }) =>296 Effect.as(metrics.write(body.points), ran(row, true, now))297 );298299 // Best effort, once: a setup the Checker could not keep is installed300 // again by the next answer, as it would have been.301 const warmed = yield* Effect.forEach(of("WarmSetup"), ({ body, row }) =>302 Effect.as(303 CheckRunner.use((runner) =>304 runner.run({305 ...noRunEnv,306 at: CheckAt.cases.Commit.make({ commit: body.at }),307 lanes: [],308 project: body.project,309 repo: body.repo,310 run: body.run,311 })312 ).pipe(313 Effect.catchTag("VerifierBlocked", () =>314 Effect.logWarning("the setup snapshot was not warmed").pipe(315 Effect.annotateLogs({ landed: body.at, project: body.project })316 )317 )318 ),319 ran(row, true, now)320 )321 );322323 const runs = yield* Effect.forEach(of("StartAnswer"), ({ body, row }) =>324 Effect.as(325 AnswerRuns.use((answers) => answers.start(body.requestId, queue)),326 ran(row, true, now)
6 unmodified lines
333 ...kept,334 ...planned,335 ...drafts,336 ...measured,337 ...warmed,338 ...runs,339 ]);340 });
modified:packages/project/src/project.ts+46 added-2 removed
277 unmodified lines
278 OutboxBody,279 projectedRows,280 runOutbox,281 startRow,282 warmRow,283} from "./outbox.ts";284import { ProjectStore } from "./project-store.ts";285import type { ProjectSnapshot, ProjectWrites } from "./project-store.ts";286import type {
15 unmodified lines
302import type { Projection } from "./projection.ts";303import { askToLand, holdsSlot, leave, queueOf, storedQueue } from "./queue.ts";304import { afterLanding, decideRaise } from "./ratchets.ts";305import type { RatchetBaseline } from "./ratchets.ts";306import { bundleKeyAt, bundleThrough } from "./rules-bundle.ts";307import {308 AdmissionPlan,309 AdmissionReport,310 HeldBackJob,
1722 unmodified lines
2033 withPorts(facts).pipe(2034 Effect.flatMap((found) => layered(snapshotNow(h, writes), found))2035 );20362037 /**2038 * One Checker job per landing whose policy has a setup, so the setup2039 * snapshot for the landed lockfiles is there before the next answer;2040 * nothing when the policy runs no setup, since no snapshot is kept then.2041 */2042 const warmRows = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2043 Effect.gen(function* () {2044 if (!Array.isReadonlyArrayNonEmpty(writes.landings)) {2045 return [];2046 }20472048 const row = writes.project.get("row");20492050 const policy =2051 row?.policy === undefined2052 ? h.policy2053 : Option.some(yield* Effect.orDie(decodePolicy(row.policy)));20542055 if (Option.isNone(policy) || policy.value.run.setup === undefined) {2056 return [];2057 }20582059 const { run } = policy.value;20602061 return yield* Effect.forEach(writes.landings, ({ sha }) =>2062 warmRow({ at: sha, project: name, repo, run }, now)2063 );2064 });20652066 const commit = (h: Hydrated, writes: Writes, now: DateTime.Utc) =>2067 Effect.gen(function* () {2068 if (isEmpty(writes)) {2069 return [];
10 unmodified lines
2080 now2081 )2082 );20832053 const outbox = [...writes.outbox, ...landed.flat(), ...projected];2084 const warmed = yield* warmRows(h, writes, now);20852086 const outbox = [2087 ...writes.outbox,2088 ...landed.flat(),2089 ...warmed,2090 ...projected,2091 ];20922093 const queue = yield* Effect.forEach(writes.queue.values(), (each) =>2094 storedQueue(each)2095 );2096
287 unmodified lines
2384 Option.map(previous, ({ vouch }) => vouch.file),2385 () => RepoPath.make(`${Brand.configDir}/vouched.td`)2386 );23872388 // Bundled once per change to the config folder: a landing that leaves2389 // the folder's tree as it was reads the bundle the last one kept.2350 const bundle = yield* Effect.option(lander.bundleRules({ at, repo }));2390 const bundle = yield* Effect.option(2391 Effect.flatMap(withPorts(bundleKeyAt(repo, at)), (key) =>2392 bundleThrough(key, lander.bundleRules({ at, repo }))2393 )2394 );23952396 if (Option.isNone(bundle)) {2397 yield* Effect.logWarning(2398 `the config folder at ${at} could not be read`
3263 unmodified lines
added:packages/project/src/rules-bundle.ts+77 added
added:packages/project/test/rules-bundle.test.ts+277 added
1import { describe, expect, it } from "@effect/vitest";2import { RefName, RepoHost } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { CheckSpec } from "@repo/protocol/domain/check";5import {6 AskId,7 CommitSha,8 keyOf,9 LandedSha,10 LaneName,11 RepoName,12} from "@repo/protocol/ids";13import { Person } from "@repo/protocol/principal";14import type { ConfigBundle } from "@repo/rules/rules-evaluator";15import { advanceTo } from "@repo/testkit/clock";16import type { Files } from "@repo/testkit/git-client";17import { aProject, withAsk } from "@repo/testkit/scenarios";18import { Array, Context, Effect, Layer, Option, Ref, Schema } from "effect";1920import { CodeStore } from "../src/code-store.ts";21import { CodeStoreMemory } from "../src/code-store/memory.ts";22import { Lander } from "../src/lander.ts";23import type { ProjectApi } from "../src/project.ts";24import { projectService } from "../src/project.ts";25import {26 bundleKeyAt,27 bundleThrough,28 rulesBundleKept,29} from "../src/rules-bundle.ts";30import { CheckScript, composedAt, Pusher, worldOf } from "./world.ts";3132const scenario = aProject().pipe(33 withAsk({ id: "parse-iso", territory: "packages/parser" }),34 withAsk({ id: "trim-input", territory: "." })35);3637const { policy } = scenario;3839const repo = RepoName.make(keyOf(scenario.project));4041const mainRef = RefName.make("refs/heads/main");4243const alice = Person.make({ handle: scenario.initializer });4445const start: Files = [46 [47 "package.json",48 '{ "name": "alice/datekit", "workspaces": ["packages/*"] }\n',49 ],50 ["packages/parser/src/parse.ts", "export const parse = (s) => ({});\n"],51 ["src/trim.ts", "export const trim = (s) => s;\n"],52];5354class BundleCount extends Context.Service<55 BundleCount,56 { readonly count: Effect.Effect<number> }57>()("test/BundleCount") {}5859/** The world's Lander, each bundle it makes counted. */60const counted = Layer.effectContext(61 Effect.gen(function* () {62 const inner = yield* Lander;63 const count = yield* Ref.make(0);6465 const lander = Lander.of({66 ...inner,67 bundleRules: (job) =>68 Effect.andThen(69 Ref.update(count, (n) => n + 1),70 inner.bundleRules(job)71 ),72 });7374 return Context.make(Lander, lander).pipe(75 Context.add(BundleCount, { count: Ref.get(count) })76 );77 })78).pipe(Layer.provideMerge(worldOf({ policy }, "memory")));7980const mainTip = Effect.gen(function* () {81 const refs = yield* (yield* RepoHost).refs(repo).pipe(Effect.orDie);8283 return LandedSha.make(84 Option.getOrThrow(Option.fromNullishOr(refs.get(mainRef)))85 );86});8788const openAsk = (api: ProjectApi, id: string) =>89 Effect.gen(function* () {90 const ask = Option.getOrThrow(91 Array.findFirst(policy.asks, (each) => each.id === id)92 );9394 if (!CheckSpec.guards.RedThenGreen(ask.check)) {95 return yield* Effect.die(`${id}'s check is not red-then-green`);96 }9798 const files = Array.make(99 { content: `export default "${id}";\n`, path: ask.file },100 { content: `it("${id}", () => {});\n`, path: ask.check.path }101 );102103 const landed = yield* mainTip;104105 yield* CheckScript.use(106 Effect.fnUntraced(function* (checker) {107 yield* checker.script(108 yield* composedAt(repo, landed, files),109 LaneName.make("redThenGreen"),110 ["failed", "failed"]111 );112 })113 );114115 return yield* api.openAsk(alice, { ask: AskId.make(id), files });116 });117118const bundle: ConfigBundle = {119 entry: `${Brand.configDir}/project.ts`,120 modules: { [`${Brand.configDir}/policy.json`]: "{}" },121 sdkVersion: "0.0.0",122};123124describe("a commit's rules bundle", () => {125 it.effect(126 "is keyed by its config folder's tree, so a commit that keeps the folder shares the key",127 () =>128 Effect.gen(function* () {129 const push = (parent: Option.Option<CommitSha>, files: Files) =>130 Pusher.use((pusher) => pusher.push(repo, parent, files));131132 yield* advanceTo("2026-10-07T12:00:00Z");133 yield* (yield* projectService(scenario.project)).initProject(alice, {});134135 const bare = yield* push(Option.none(), start);136137 const configured = yield* push(Option.some(bare), [138 ...start,139 [`${Brand.configDir}/policy.json`, "{}\n"],140 ]);141142 const sameFolder = yield* push(Option.some(configured), [143 ...start,144 ["src/trim.ts", "export const trim = (s) => s.trim();\n"],145 [`${Brand.configDir}/policy.json`, "{}\n"],146 ]);147148 const changedFolder = yield* push(Option.some(sameFolder), [149 ...start,150 [`${Brand.configDir}/policy.json`, '{ "kinds": [] }\n'],151 ]);152153 const keys = yield* Effect.all([154 bundleKeyAt(repo, bare),155 bundleKeyAt(repo, configured),156 bundleKeyAt(repo, sameFolder),157 bundleKeyAt(repo, changedFolder),158 ]);159160 const unknown = yield* bundleKeyAt(161 repo,162 CommitSha.make("0000000000000000000000000000000000000000")163 );164165 expect({166 bareIsNone: keys[0],167 changedDiffers:168 Option.getOrThrow(keys[3]) !== Option.getOrThrow(keys[1]),169 configuredDiffers:170 Option.getOrThrow(keys[1]) !== Option.getOrThrow(keys[0]),171 prefixed: Option.getOrThrow(keys[1]).startsWith(172 `${repo}/rules-bundle/v`173 ),174 sameShares: keys[2],175 unknown,176 }).toStrictEqual({177 bareIsNone: Option.map(keys[0], (key) =>178 key.replace(/[^/]+$/u, "none")179 ),180 changedDiffers: true,181 configuredDiffers: true,182 prefixed: true,183 sameShares: keys[1],184 unknown: Option.none(),185 });186 }).pipe(Effect.provide(worldOf({ policy }, "memory")))187 );188189 it.effect(190 "is kept once made, and a kept one that no longer decodes is made again",191 () =>192 Effect.gen(function* () {193 const store = yield* CodeStore;194 const made = yield* Ref.make(0);195 const key = Option.some(`${repo}/rules-bundle/test`);196197 const make = Effect.andThen(198 Ref.update(made, (n) => n + 1),199 Effect.succeed(bundle)200 );201202 const first = yield* bundleThrough(key, make);203 const second = yield* bundleThrough(key, make);204 const madeOnce = yield* Ref.get(made);205206 yield* store.put(Option.getOrThrow(key), '{"entry":"no modules"}');207208 const replaced = yield* bundleThrough(key, make);209 const madeAgain = yield* Ref.get(made);210211 const kept = Option.flatMap(212 yield* store.get(Option.getOrThrow(key)),213 Schema.decodeUnknownOption(214 Schema.fromJsonString(rulesBundleKept.schema)215 )216 );217218 // Without a key (the commit could not be read) every call bundles.219 const unkeyed = yield* bundleThrough(Option.none(), make);220 const madeUnkeyed = yield* Ref.get(made);221222 expect({223 first,224 kept,225 madeAgain,226 madeOnce,227 madeUnkeyed,228 replaced,229 second,230 unkeyed,231 }).toStrictEqual({232 first: bundle,233 kept: Option.some(bundle),234 madeAgain: 2,235 madeOnce: 1,236 madeUnkeyed: 3,237 replaced: bundle,238 second: bundle,239 unkeyed: bundle,240 });241 }).pipe(Effect.provide(CodeStoreMemory))242 );243244 it.effect(245 "is made once per change to the folder across a project's landings: an ask's composed commit and its landing share one",246 () =>247 Effect.gen(function* () {248 yield* advanceTo("2026-10-07T12:00:00Z");249250 const { count } = yield* BundleCount;251 const api = yield* projectService(scenario.project);252253 yield* api.initProject(alice, {});254255 const first = yield* Pusher.use((pusher) =>256 pusher.push(repo, Option.none(), start, "Start")257 );258259 yield* api.recordFirstPush(alice, first);260261 const afterFirst = yield* count;262263 yield* openAsk(api, "parse-iso");264265 const afterOne = yield* count;266267 yield* openAsk(api, "trim-input");268269 const afterTwo = yield* count;270271 // One bundle for the first push's tree, and one per opening: the272 // ask's composed commit is bundled and its landing, the same273 // folder, reads it back.274 expect([afterFirst, afterOne, afterTwo]).toStrictEqual([1, 2, 3]);275 }).pipe(Effect.provide(Layer.merge(counted, CodeStoreMemory)))276 );277});
added:packages/project/test/warm-setup.test.ts+98 added
1import { describe, expect, it } from "@effect/vitest";2import { CheckAt } from "@repo/checks/check-runner";3import type { CheckJob } from "@repo/checks/check-runner";4import { Command } from "@repo/protocol/domain/common";5import type { Policy } from "@repo/protocol/domain/policy";6import { keyOf, RepoName } from "@repo/protocol/ids";7import { Person } from "@repo/protocol/principal";8import { advanceTo } from "@repo/testkit/clock";9import type { Files } from "@repo/testkit/git-client";10import { aProject } from "@repo/testkit/scenarios";11import { Effect, Option } from "effect";1213import { projectService } from "../src/project.ts";14import { CheckScript, Pusher, worldOf } from "./world.ts";1516const scenario = aProject();1718const repo = RepoName.make(keyOf(scenario.project));1920const alice = Person.make({ handle: scenario.initializer });2122const start: Files = [23 ["package.json", '{ "name": "alice/datekit", "private": true }\n'],24 ["bun.lock", "{}\n"],25 ["src/trim.ts", "export const trim = (s) => s;\n"],26];2728const installing: Policy = {29 ...scenario.policy,30 run: {31 ...scenario.policy.run,32 setup: Command.make("bun install --frozen-lockfile"),33 },34};3536const shape = ({ at, lanes, project, repo: on, run }: CheckJob) => ({37 at,38 lanes,39 project,40 repo: on,41 setup: run.setup,42});4344const firstLanding = Effect.gen(function* () {45 yield* advanceTo("2026-10-07T12:00:00Z");4647 const api = yield* projectService(scenario.project);4849 yield* api.initProject(alice, {});5051 const first = yield* Pusher.use((pusher) =>52 pusher.push(repo, Option.none(), start, "Start")53 );5455 yield* api.recordFirstPush(alice, first);5657 return { api, first };58});5960const jobs = CheckScript.use((script) => script.jobs);6162describe("a landing's setup snapshot", () => {63 it.effect(64 "is warmed by one Checker job with no lanes on the landed commit, once however often the outbox runs",65 () =>66 Effect.gen(function* () {67 const { api, first } = yield* firstLanding;6869 const afterLanding = (yield* jobs).map(shape);7071 yield* api.onAlarm();72 yield* api.onAlarm();7374 const afterAlarms = (yield* jobs).map(shape);7576 expect({ afterAlarms, afterLanding }).toStrictEqual({77 afterAlarms: afterLanding,78 afterLanding: [79 {80 at: CheckAt.cases.Commit.make({ commit: first }),81 lanes: [],82 project: scenario.project,83 repo,84 setup: "bun install --frozen-lockfile",85 },86 ],87 });88 }).pipe(Effect.provide(worldOf({ policy: installing }, "memory")))89 );9091 it.effect("is not warmed when the policy runs no setup", () =>92 Effect.gen(function* () {93 yield* firstLanding;9495 expect(yield* jobs).toStrictEqual([]);96 }).pipe(Effect.provide(worldOf({ policy: scenario.policy }, "memory")))97 );98});