Skip to content
Myr

Keep the wall clock out of a date's constructor, give one bundle one source from either adapter, and bound what the bun adapter reads

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

Review fixes for 204 before merge: - Prelude: `Date.prototype.constructor` still pointed at the real Date, so `new Date().constructor.now()` read the wall clock and a config using it evaluated differently each time (principle 8). It now points at the frozen Date. - Source: /json labelled a config folder with no policy.json `defaults` while /bun labelled the same bundle `config`. Both now use `statedWithoutCode` in config-folder.ts, which follows spec 2.5 and the first commit's rule: `defaults` only for an empty bundle. It also removes the copy of that logic each adapter had. - /bun output: the host held all of the child's stdout and stderr, so a config that printed without end could exhaust memory before its time limit, a crash instead of RulesFailed. It now keeps the last 16 MiB of stdout (the result is its last line) and the last 64 KiB of stderr, and drains the rest. - EvaluationFacts.ci's doc names what checks' finder and judge closure read (manifests and configs as well as CI), as 205's Comments ask. - Tests: the replay test's "equal facts" case now also runs the clock-reading config, which before passed even without a prelude. Its stamp adds the constructor's clock, crypto.getRandomValues and crypto.randomUUID. New evaluate cases: no env beyond PATH and no fetch in config code; a stderr flood gives a bounded detail; /json and /bun agree on a folder that holds no policy; /json over an empty bundle gives the defaults. Each fix's case failed by assertion first (the constructor, the flood and the source); the env case passed as written and stays as a guard.

authored by oscabriel · committed by oscabriel · parent 6c120ce · Browse files · 7 files+151 added−47 removed
This commit

State

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

Diff stats

7 files+151 added−47 removed

  • tests:+89 added−16 removed
  • other:+62 added−31 removed

7 files+151 added−47 removed

modified:packages/rules/src/rules-evaluator/bun-prelude.ts+6 added
modified:packages/rules/src/rules-evaluator/bun.ts+28 added-21 removed
1import type { PolicyInput } from "@repo/protocol/domain/policy";1import {2 Config,3 DateTime,4 Duration,5 Effect,6 FileSystem,7 Layer,9 Option,8 Path,9 Schema,10 Stream,11} from "effect";
3 unmodified lines
15import {16 Collected,17 askModules,18 fromCollected,21 fromPolicyJson,19 projectModule,20 statedWithoutCode,21} from "../config-folder.ts";22import { defaultPolicyInput } from "../defaults.ts";23import { Finishers, finishPolicy } from "../finish.ts";24import { RulesEvaluator, RulesFailed } from "../rules-evaluator.ts";
72 unmodified lines
9798const fromFailed = ({ detail, reason }: Extract<Output, { _tag: "Failed" }>) =>99 new RulesFailed({ detail, reason });100103const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>104 bytes.pipe(Stream.decodeText(), Stream.mkString);101// The most of the subprocess's output the host keeps, from the end: config102// code may print without end, the result is stdout's last line, and what103// broke is told at the end of stderr.104const resultLimit = 16 * 1024 * 1024;105106const logLimit = 64 * 1024;107108/** The last `limit` characters a stream prints; the rest is read and dropped. */109const tailOf = <E>(bytes: Stream.Stream<Uint8Array, E>, limit: number) =>110 bytes.pipe(111 Stream.decodeText(),112 // Cut at twice the limit, so each character is copied only a few times.113 Stream.runFold(114 () => "",115 (kept: string, chunk: string) =>116 kept.length + chunk.length > 2 * limit117 ? `${kept}${chunk}`.slice(-limit)118 : `${kept}${chunk}`119 ),120 Effect.map((kept) => kept.slice(-limit))121 );122123/** The project module and ask files, as the main imports them. */124const modulesOf = (125 written: ReadonlyMap<string, string>,126 project: string | undefined,
11 unmodified lines
138 : { asks: asksWritten, project: at(project) };139};140141/**125 * The policy input a bundle states without running code: its `policy.json`,126 * or the defaults (from the config folder when there is one).127 */128const withoutCode = (bundle: ConfigBundle) =>129 Effect.map(130 fromPolicyJson(bundle),131 Option.getOrElse((): PolicyInput =>132 Object.keys(bundle.modules).length === 0133 ? defaultPolicyInput134 : { ...defaultPolicyInput, source: "config" }135 )136 );137138/**142 * `RulesEvaluator` over a `bun` subprocess. Each evaluation writes the143 * bundle's modules into a scoped temp directory (every import of the sdk144 * pointed at the sdk's own entry), runs `bun --preload <prelude> <main>`145 * with no inherited env beyond `PATH`, frozen time and randomness, and a
104 unmodified lines
250 )251 );252253 const [stdout, stderr, exitCode] = yield* Effect.all(251 [text(child.stdout), text(child.stderr), child.exitCode],254 [255 tailOf(child.stdout, resultLimit),256 tailOf(child.stderr, logLimit),257 child.exitCode,258 ],259 { concurrency: "unbounded" }260 ).pipe(Effect.mapError((failure) => loadFailed(failure.message)));261262 const last = stdout.trimEnd().split("\n").at(-1) ?? "";
83 unmodified lines
346 // Without a project module, `policy.json` (or the defaults) is the347 // base the ask files join; with one, it is never read.348 const fallback =349 project === undefined343 ? yield* withoutCode(modules)350 ? yield* statedWithoutCode(modules)351 : defaultPolicyInput;352353 const policy =354 project === undefined && asks.length === 0
29 unmodified lines
modified:packages/rules/src/rules-evaluator/json.ts+3 added-8 removed
modified:packages/rules/src/config-folder.ts+20 added-1 removed
1import { AskInput, PolicyInput } from "@repo/protocol/domain/policy";2import { AskId, Handle, RepoPath } from "@repo/protocol/ids";3import { Effect, Option, Schema, Struct } from "effect";45import { defaultPolicyInput } from "./defaults.ts";6import { RulesFailed } from "./rules-evaluator.ts";7import type { ConfigBundle } from "./rules-evaluator.ts";89// An ask file: `<id>.ask.ts`, or the `.js` a bundler writes for it.
48 unmodified lines
58/**59 * The policy a committed `policy.json` states, when the bundle has one. It60 * carries its asks inline.61 */61export const fromPolicyJson = (62const fromPolicyJson = (63 bundle: ConfigBundle64): Effect.Effect<Option.Option<PolicyInput>, RulesFailed> => {65 const path = policyJsonOf(bundle);66 const source = bundle.modules[path];
7 unmodified lines
74 Effect.mapError(failedAt(path))75 );76};7778/**79 * The policy input a bundle states without running code: its `policy.json`,80 * or else the defaults. Its source is the config folder whenever there is81 * one, and the defaults only when there is none (spec §2.5), so every82 * adapter gives one bundle the same source.83 */84export const statedWithoutCode = (85 bundle: ConfigBundle86): Effect.Effect<PolicyInput, RulesFailed> =>87 Effect.map(88 fromPolicyJson(bundle),89 Option.getOrElse((): PolicyInput =>90 Object.keys(bundle.modules).length === 091 ? defaultPolicyInput92 : { ...defaultPolicyInput, source: "config" }93 )94 );9596/** What the config folder's modules exported, as data, read back from the sandbox. */97export const Collected = Schema.Struct({98 asks: Schema.Array(Schema.Struct({ ask: Schema.Json, path: Schema.String })),99 /** Absent when the bundle has no project module; `null` when it exports nothing. */
88 unmodified lines
modified:packages/rules/src/rules-evaluator.ts+5 added-1 removed
37 unmodified lines
38 * rule code never reads the repo, the network or the clock. The same facts39 * always give the same policy (principle 8).40 */41export const EvaluationFacts = Schema.Struct({42 /** The project's CI and hook files, where a `run: fromCI` block is found. */42 /**43 * The files `checks`' finder and judge closure read, where a `run: fromCI`44 * block is found: CI workflows, hook configs, `package.json`s and the45 * configs that decide what the checks do.46 */47 ci: Schema.Array(Schema.Struct({ content: Schema.String, path: RepoPath })),48 /** The person who made the project; `owners` resolves to them (spec D20). */49 initializer: Handle,50 /** The frozen clock rule code sees, and when its asks count as opened. */
52 unmodified lines
modified:packages/rules/test/evaluate.test.ts+61 added-3 removed
397 unmodified lines
398 )399 )400 );401402 it.live("runs config code with no env beyond PATH, and no fetch", () =>403 Effect.gen(function* () {404 const base = yield* baseProject;405406 const project = [407 base.replace("export default ", "const base = "),408 "const seen = [...Object.keys(process.env).toSorted(), typeof fetch];",409 "export default { ...base, weakening: { markers: seen } };",410 ].join("\n");411412 const policy = yield* evaluated(bundleOf({ "project.ts": project }));413414 expect(policy.weakening).toStrictEqual({415 markers: ["PATH", "undefined"],416 });417 }).pipe(Effect.provide(bunEvaluator()))418 );419420 it.live("keeps only the end of a config's endless output", () =>421 Effect.gen(function* () {422 const failure = yield* failed(423 bundleOf({424 "project.ts": [425 'const flood = "x".repeat(8 * 1024 * 1024) + "the end";',426 "await new Promise((done) => process.stderr.write(flood, done));",427 "process.exit(3);",428 ].join("\n"),429 })430 );431432 expect(failure.detail.length).toBeLessThanOrEqual(64 * 1024);433 expect(failure.detail).toMatch(/x+the end$/u);434 }).pipe(Effect.provide(bunEvaluator()))435 );436437 it.live("calls a function-valued rule with the facts it is given", () =>438 Effect.gen(function* () {439 const evaluator = yield* RulesEvaluator;440 const modules = yield* folder("cm");
21 unmodified lines
462 );463 }).pipe(Effect.provide(jsonEvaluator))464 );465431 it.live("gives the defaults when there is no policy.json", () =>466 it.live(467 "gives the defaults, from the folder, when there is no policy.json",468 () =>469 Effect.gen(function* () {470 expect(yield* evaluated(yield* folder("cm"))).toStrictEqual({471 ...defaultsEncoded,472 source: "config",473 });474 }).pipe(Effect.provide(jsonEvaluator))475 );476477 it.live("gives the defaults to a project with no config folder", () =>478 Effect.gen(function* () {433 expect(yield* evaluated(yield* folder("cm"))).toStrictEqual(434 defaultsEncoded479 expect(yield* evaluated(bundleOf({}))).toStrictEqual(defaultsEncoded);480 }).pipe(Effect.provide(jsonEvaluator))481 );482483 it.live("agrees with /bun on a folder that holds no policy", () =>484 Effect.gen(function* () {485 const modules = bundleOf({ "vouched.td": "priya\n" });486 const fromJson = yield* evaluated(modules);487488 const fromBun = yield* evaluated(modules).pipe(489 Effect.provide(bunEvaluator())490 );491492 expect(fromJson).toStrictEqual({ ...defaultsEncoded, source: "config" });493 expect(fromBun).toStrictEqual(fromJson);494 }).pipe(Effect.provide(jsonEvaluator))495 );496497 it.live("has no function-valued rules to call", () =>
14 unmodified lines
modified:packages/rules/test/replay.test.ts+28 added-13 removed
25 unmodified lines
2627/**28 * A config whose `project.ts` reads the clock and randomness while it loads,29 * and puts what it read into an ask's context: the wall clock, a dated30 * `new Date()`, a `Math.random()`, and a `new Date(0)` that names its time.30 * `new Date()`, the clock reached through a date's own constructor, a31 * `new Date(0)` that names its time, then `Math.random()`,32 * `crypto.getRandomValues()` and `crypto.randomUUID()`.33 */34const readsTheClock = Effect.map(baseProject, (base) =>35 bundleOf({36 "asks/stamp.ask.ts": [
9 unmodified lines
46 "project.ts": [47 "export const stamp = [",48 " String(Date.now()),",49 " new Date().toISOString(),",48 " String(Math.random()),",50 " String(new Date().constructor.now()),",51 " new Date(0).toISOString(),",52 " String(Math.random()),",53 ' crypto.getRandomValues(new Uint32Array(2)).join(","),',54 " crypto.randomUUID(),",55 "];",56 base,57 ].join("\n"),58 })
5 unmodified lines
6465describe("evaluating a config folder twice", () => {66 it.live("gives equal policies for equal facts", () =>67 Effect.gen(function* () {63 const modules = yield* folder("cm");64 const first = yield* evaluated(modules);65 const second = yield* evaluated(modules);68 for (const modules of [yield* folder("cm"), yield* readsTheClock]) {69 const first = yield* evaluated(modules);70 const second = yield* evaluated(modules);7167 expect(second).toStrictEqual(first);72 expect(second).toStrictEqual(first);73 }74 }).pipe(Effect.provide(bunEvaluator()))75 );7677 it.live("gives config code the facts' clock, not the wall clock", () =>
7 unmodified lines
85 now: DateTime.makeUnsafe("2027-01-01T00:00:00.000Z"),86 })87 );8883 expect(first?.slice(0, 2)).toStrictEqual([nowMs, now]);89 expect(first?.slice(0, 3)).toStrictEqual([nowMs, now, nowMs]);9085 expect(later?.slice(0, 2)).toStrictEqual([91 expect(later?.slice(0, 3)).toStrictEqual([92 "1798761600000",93 "2027-01-01T00:00:00.000Z",94 "1798761600000",95 ]);9697 // A date that names its own time is left alone.98 expect(first?.[3]).toBe("1970-01-01T00:00:00.000Z");
3 unmodified lines
102 it.live("gives config code randomness from the facts' seed", () =>103 Effect.gen(function* () {104 const modules = yield* readsTheClock;105106 // Math.random(), crypto.getRandomValues() and crypto.randomUUID().107 const randomWith = (seed: number) =>108 Effect.map(109 evaluated(modules, { ...facts, seed }),102 (policy) => stampOf(policy)?.[2]110 (policy) => stampOf(policy)?.slice(4) ?? []111 );112113 const first = yield* randomWith(7);114 const other = yield* randomWith(8);115107 expect(yield* randomWith(7)).toBe(first);108 expect(yield* randomWith(8)).not.toBe(first);109 expect(Number(first)).toBeGreaterThanOrEqual(0);110 expect(Number(first)).toBeLessThan(1);116 // The same seed gives the same three values; another seed changes each.117 expect({118 again: yield* randomWith(7),119 changed: other.map((value, index) => value !== first[index]),120 }).toStrictEqual({ again: first, changed: [true, true, true] });121 expect(Number(first[0])).toBeGreaterThanOrEqual(0);122 expect(Number(first[0])).toBeLessThan(1);123 expect(first[2]).toMatch(124 /^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/u125 );126 }).pipe(Effect.provide(bunEvaluator()))127 );128});