Merge build/1003
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 1a364b9, 81a3dda · Browse files · 12 files·+1813 added−213 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+1813 added−213 removed
- tests:+813 added−8 removed
- other:+1000 added−205 removed
Provenance
- Commit
e8561dc- Tree
f017172- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
1a364b9- Parent 2
81a3dda
12 files changed+1813 added−213 removed
modified:packages/artifacts/src/repo-host/binding.ts+64 added-13 removed
8 unmodified lines9 * second 500 after that may be the fork the first made: it is, if it lists10 * `main`;11 * - reads name a branch by its short name and a commit by its id, never12 * `refs/…`, so `refs` and `push` go over git smart HTTP instead;13- * - a busy receive-pack is `HostBusy`.13+ * - a busy receive-pack is `HostBusy`;14+ * - a call refused for Artifacts' rate limit (2,000 requests per 10 s per15+ * repo) is asked again from 250 ms apart, doubling, at most four more16+ * times; past that it fails as the call's own failure would.17 *18 * Refs and pushes use a token the adapter mints for the one call and revokes19 * after it; the token goes nowhere but the `Authorization` header of the20 * adapter's own requests. The day-long write token a create, a fork or an21 * import hands back is revoked at once: any write token can force-push22 * `main`, and no caller needs it. A repo still being23 * created is asked for again, from 250 ms apart, up to seven more times24 * (about 32 s); one still being imported up to sixteen (about 3 minutes),22- * each sleep at most 16 s. Every repo handle is disposed after use.25+ * each sleep at most 16 s. Every repo handle is disposed after use: after26+ * each read, or, for reads in one `RepoSession`, once when the session27+ * ends, so a view's many reads ask `get` for one handle.28 */29 import {30 Data,31 DateTime,16 unmodified lines48 RefName,49 RepoExists,50 RepoHost,51 RepoNotFound,52+ RepoSession,53 TreeEntry,54 } from "../repo-host.ts";55 import type {56 RepoName,36 unmodified lines93 class MaybeForked extends Data.TaggedError("MaybeForked")<{94 readonly thrown: Thrown;95 }> {}96 91-/** A promise of the binding's, failing with what it threw, read. */97+/**98+ * How Artifacts words a refusal for its rate limit. ASSUMPTION: none has99+ * been seen live and its error codes list none, so it is read from a code100+ * or a message that names the limit, as an HTTP 429's "Too Many Requests"101+ * does.102+ */103+const RATE_LIMITED = /rate[ _-]?limit|too[ _-]many[ _-]requests/iu;104+105+const isRateLimited = ({ error, message }: Thrown) =>106+ RATE_LIMITED.test(message) ||107+ (Predicate.hasProperty(error, "code") &&108+ Predicate.isString(error.code) &&109+ RATE_LIMITED.test(error.code));110+111+/** From 250 ms apart, doubling, four more asks while the limit refuses. */112+const whileLimited = Schedule.exponential(Duration.millis(250)).pipe(113+ Schedule.setInputType<Thrown>(),114+ Schedule.while(115+ ({ attempt: asked, input }) => asked <= 4 && isRateLimited(input)116+ )117+);118+119+/**120+ * A promise of the binding's, failing with what it threw, read; asked121+ * again while Artifacts' rate limit refuses it.122+ */123 const attempt = <A>(run: () => Promise<A>) =>124 Effect.tryPromise({125 catch: (error) => {126 const message = error instanceof Error ? error.message : String(error);7 unmodified lines134 135 return new Thrown({ code, error, message });136 },137 try: run,107- });138+ }).pipe(Effect.retry(whileLimited));139 140 const threw =141 (code: Code) =>142 (thrown: Thrown): boolean =>118 unmodified lines261 Effect.retry(whileMaking),262 Effect.catchTag("Thrown", (thrown) => fromArtifactsError(name, thrown))263 );264 265+/** Gives a handle back: the binding's handles are RPC stubs. */266+const disposeOf = (repo: ArtifactsRepo) =>267+ Effect.sync(() => {268+ repo[Symbol.dispose]();269+ });270+271 /** `use` over a handle to `name`, disposed after, whatever `use` came to. */272 const withRepo = <A, E, R>(273 binding: Artifacts,274 name: RepoName,275 use: (repo: ArtifactsRepo) => Effect.Effect<A, E, R>276 ) =>277 Effect.scoped(241- Effect.acquireRelease(handleOf(binding, name), (repo) =>242- Effect.sync(() => {243- repo[Symbol.dispose]();244- })245- ).pipe(Effect.flatMap(use))278+ Effect.acquireRelease(handleOf(binding, name), disposeOf).pipe(279+ Effect.flatMap(use)280+ )281 );282 283 /**284 * The repo `made` names, its initial write token revoked: nothing the230 unmodified lines515 // The service alone: the layer's whole context would carry its Scope, and516 // every call's finalizers would wait for the layer's end.517 const fetch = yield* Fetch;518 484- /** A read of `name`'s, failing only with `RepoNotFound`. */519+ /**520+ * A read of `name`'s, failing only with `RepoNotFound`: over the521+ * session's handle to `name` when the read runs in a `RepoSession`,522+ * else over a handle of its own.523+ */524 const read = <A>(525 name: RepoName,526 use: (527 repo: ArtifactsRepo528 ) => Effect.Effect<A, RepoNotFound | RepoExists | ForkInProgress, Fetch>529 ) =>491- onlyNotFound(withRepo(binding, name, use)).pipe(492- Effect.provideService(Fetch, fetch)493- );530+ Effect.gen(function* () {531+ const session = yield* RepoSession;532 533+ return yield* Option.match(session, {534+ onNone: () => withRepo(binding, name, use),535+ onSome: ({ hold }) =>536+ Effect.flatMap(537+ hold(538+ `binding:${name}`,539+ Effect.acquireRelease(handleOf(binding, name), disposeOf)540+ ),541+ use542+ ),543+ });544+ }).pipe(onlyNotFound, Effect.provideService(Fetch, fetch));545+546 return RepoHost.of({547 create: (name) =>548 call(name, () => binding.create(name)).pipe(549 Effect.flatMap((made) => withoutToken(binding, made, name)),94 unmodified linesmodified:packages/artifacts/src/repo-host.ts+80 added-6 removed
1 import { CommitSha, RepoName } from "@repo/protocol/ids";2 import type { RepoPath } from "@repo/protocol/ids";3-import { Context, Data, Schema } from "effect";4-import type {5- Array,6- DateTime,7- Duration,3+import {4+ Context,5+ Data,6 Effect,7 Option,10- Redacted,8+ Schema,9+ Scope,10+ Semaphore,11 } from "effect";12+import type { Array, DateTime, Duration, Redacted } from "effect";13 import type { FsClient } from "isomorphic-git";14 15 /** A repo's name in its namespace: the one `RepoName`, from the domain. */16 export { RepoName } from "@repo/protocol/ids";221 unmodified lines238 updates: Array.NonEmptyReadonlyArray<RefUpdate>239 ) => Effect.Effect<readonly RefOutcome[], RepoNotFound | HostBusy>;240 }241 >()("artifacts/RepoHost") {}242+243+/**244+ * What the reads of one session may share: a host keeps what it opens on a245+ * repo (the binding's handle) under `key` until the session ends, rather246+ * than opening and closing it for each read. One opening at a time, and247+ * only a finished value is kept, so no read waits on another's opening248+ * past its own session.249+ */250+export interface RepoSessionApi {251+ readonly hold: <A, E>(252+ key: string,253+ open: Effect.Effect<A, E, Scope.Scope>254+ ) => Effect.Effect<A, E>;255+}256+257+/**258+ * The session reads run in, if any. A `Context.Reference` whose default is259+ * none, so each read opens and closes what it needs, as a host without a260+ * session does. It lives in one request's context, never in an isolate's261+ * state: a Worker whose client goes away is cancelled where it stands, so262+ * nothing a request holds may outlive it.263+ */264+export const RepoSession = Context.Reference<Option.Option<RepoSessionApi>>(265+ "artifacts/RepoSession",266+ { defaultValue: Option.none }267+);268+269+/**270+ * `effect` with its reads in one session: what a host holds for them is271+ * released when `effect` ends, whatever it came to. Inside a session272+ * already, `effect` joins it, so a view whose parts each ask for a273+ * session still reads over one handle.274+ */275+export const inRepoSession = <A, E, R>(276+ effect: Effect.Effect<A, E, R>277+): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>278+ Effect.scoped(279+ Effect.gen(function* () {280+ if (Option.isSome(yield* RepoSession)) {281+ return yield* effect;282+ }283+284+ const scope = yield* Effect.scope;285+ const opening = yield* Semaphore.make(1);286+ const held = new Map<string, unknown>();287+288+ const session: RepoSessionApi = {289+ hold: <B, F>(key: string, open: Effect.Effect<B, F, Scope.Scope>) =>290+ opening.withPermits(1)(291+ Effect.suspend(() => {292+ if (held.has(key)) {293+ // SAFETY: each key names one kind of value, which a caller294+ // opens with one effect, so what it holds is a `B`.295+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one session holds every kind of value, so its map is typed `unknown`; see SAFETY.296+ return Effect.succeed(held.get(key) as B);297+ }298+299+ return Effect.tap(Scope.provide(open, scope), (value) =>300+ Effect.sync(() => {301+ held.set(key, value);302+ })303+ );304+ })305+ ),306+ };307+308+ return yield* Effect.provideService(309+ effect,310+ RepoSession,311+ Option.some(session)312+ );313+ })314+ );modified:packages/artifacts/test/binding.test.ts+101 added
28 unmodified lines29 import {30 BranchName,31 ForkInProgress,32 HostBusy,33+ inRepoSession,34 ObjectId,35 RefName,36 RefOutcome,37 RepoExists,962 unmodified lines1000 { importing: 40 }1001 )1002 );1003 });1004+1005+describe("reads in one session, and Artifacts' rate limit", () => {1006+ const at = Revision.Branch({ name: BranchName.make("main") });1007+1008+ it.live(1009+ "asks for one handle for every read of one session, and disposes it once",1010+ () =>1011+ within(({ counts }) =>1012+ Effect.gen(function* () {1013+ const repos = yield* RepoHost;1014+ const name = RepoName.make("session");1015+ const { first } = yield* seeded(name);1016+ const before = { ...counts };1017+1018+ const read = yield* inRepoSession(1019+ Effect.all(1020+ [1021+ repos.readCommit(name, first),1022+ repos.log(name, at, 5),1023+ repos.readFile(name, at, RepoPath.make("a.txt")),1024+ repos.readCommit(name, first),1025+ ],1026+ { concurrency: 4 }1027+ )1028+ ).pipe(Effect.orDie);1029+1030+ expect(read[1].map(({ sha }) => sha)).toStrictEqual([first]);1031+ expect([1032+ counts.gets - before.gets,1033+ counts.disposed - before.disposed,1034+ ]).toStrictEqual([1, 1]);1035+ })1036+ )1037+ );1038+1039+ it.live(1040+ "reads in a session inside another over the outer session's handle",1041+ () =>1042+ within(({ counts }) =>1043+ Effect.gen(function* () {1044+ const repos = yield* RepoHost;1045+ const name = RepoName.make("nested");1046+ const { first } = yield* seeded(name);1047+ const before = { ...counts };1048+1049+ yield* inRepoSession(1050+ Effect.all([1051+ repos.readCommit(name, first),1052+ inRepoSession(repos.log(name, at, 5)),1053+ repos.readFile(name, at, RepoPath.make("a.txt")),1054+ ])1055+ ).pipe(Effect.orDie);1056+1057+ expect([1058+ counts.gets - before.gets,1059+ counts.disposed - before.disposed,1060+ ]).toStrictEqual([1, 1]);1061+ })1062+ )1063+ );1064+1065+ it.effect(1066+ "asks again after each of four rate-limited reads, then reads",1067+ () =>1068+ within(1069+ () =>1070+ Effect.gen(function* () {1071+ const repos = yield* RepoHost;1072+ const name = RepoName.make("limited");1073+ const { first } = yield* seeded(name);1074+ const read = yield* onTestClock(repos.readCommit(name, first));1075+1076+ expect(1077+ Exit.map(1078+ read,1079+ Option.map(({ sha }) => sha)1080+ )1081+ ).toStrictEqual(Exit.succeed(Option.some(first)));1082+ }),1083+ { rateLimited: 4 }1084+ )1085+ );1086+1087+ it.effect(1088+ "fails the read once four asks after the first were all rate limited",1089+ () =>1090+ within(1091+ () =>1092+ Effect.gen(function* () {1093+ const repos = yield* RepoHost;1094+ const name = RepoName.make("throttled");1095+ const { first } = yield* seeded(name);1096+ const read = yield* onTestClock(repos.readCommit(name, first));1097+1098+ expect(Exit.hasDies(read)).toBeTruthy();1099+ }),1100+ { rateLimited: 5 }1101+ )1102+ );1103+});modified:packages/project/src/code/cache.ts+80 added-1 removed
10 unmodified lines111213141516171819201621222324252696 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819910 unmodified lines * Entries come in two weights, each in a cache of its own, so a count of * entries bounds the memory they take: trees and commits are light (a few * KiB), while a file's text, a commit's path list or changes and a page of * the log are heavy (up to hundreds of KiB), and an isolate holds 128 MB. * * One view's walk (`asOneView`) also shares its light reads among its own * fibers while they are under way, and reads its repo through one session: * only for the view, never in the isolate's state. */import { inRepoSession } from "@repo/artifacts/repo-host";import { Cache, Context, Effect, Layer, Option } from "effect";import { Cache, Context, Deferred, Effect, Exit, Layer, Option } from "effect";import type { Cause, Scope } from "effect";
/** How a read's value is kept. */export interface Keeping<A> { /** Whether the value may weigh up to hundreds of KiB (a text, a list). */96 unmodified lines
return reads; }) );
/** What a read under way came to, as the read that joins it: typed as it is. */const joined = <B, F>( under: Deferred.Deferred<Exit.Exit<unknown, unknown>>): Effect.Effect<B, F> => Effect.flatMap(Deferred.await(under), (exit) => { if (Exit.isSuccess(exit)) { // SAFETY: every key names one kind of read (`<repo>:<kind>:<id>`), so // the read under it was typed as the one that joins it. // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one view shares every kind of read, so its map holds `unknown`; see SAFETY. return Effect.succeed(exit.value as B); }
// SAFETY: as above, for the read's failure. // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one view shares every kind of read, so its map holds `unknown`; see SAFETY. return Effect.failCause(exit.cause as Cause.Cause<F>); });
/** * `effect` as one view: a light read one of its fibers began (a tree, a * commit) is joined by the others rather than read again, its result kept * for the rest of the view, and every repo read runs in one `RepoSession`. * A walk's lookups run many at once, and two commits whose folders are the * same read each folder once. The reads under way live in the view's own * scope: a read the view started runs on whichever of its fibers asked for * it first gave up, and ends with the view, so nothing outlives the * request. Heavy reads, and reads a `keep` may turn down, go * straight through. */export const asOneView = <A, E, R>( effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> => inRepoSession( Effect.gen(function* () { const outer = yield* CodeCache; const scope = yield* Effect.scope;
const reading = new Map< string, Deferred.Deferred<Exit.Exit<unknown, unknown>> >();
const shared: CodeReads = { through: <B, F, S>( key: string, read: Effect.Effect<B, F, S>, keeping: Keeping<B> = {} ) => keeping.heavy === true || keeping.keep !== undefined ? outer.through(key, read, keeping) : Effect.suspend(() => { const found = reading.get(key);
if (found !== undefined) { return joined<B, F>(found); }
const done = Deferred.makeUnsafe<Exit.Exit<unknown, unknown>>();
reading.set(key, done);
return Effect.forkIn( Effect.exit(outer.through(key, read, keeping)).pipe( Effect.flatMap((exit) => Deferred.succeed(done, exit)) ), scope ).pipe(Effect.andThen(joined<B, F>(done))); }), };
return yield* Effect.provideService(effect, CodeCache, shared); }) );added:packages/project/src/code/history.ts+168 added
1+/**2+ * Code history kept by immutable ids: what a why or a3+ * path's log computed from a commit, which that commit's content fixes for4+ * good, so any isolate reads it back instead of walking history again.5+ *6+ * Keys: `<repo>/<kind>/v<version>/<commit>/<scan>/<sha256(path)>`, where7+ * `kind` is `why` (version `WHY_VERSION`) or `path-log` (version8+ * `LOG_VERSION`), `commit` is a commit id (never `main` or a tag's name:9+ * those resolve first), `scan` is how many first-parent commits the walk10+ * took, and the path is hashed so a key stays under the store's 1,02411+ * bytes. Only a project's canonical repo is ever keyed (principle 7). A12+ * version moves when its algorithm changes, so an old value is never read13+ * as a new one.14+ *15+ * Values: ids and ranges, encoded with Schema; never a file's text, and16+ * never a landing (each view asks the project's record for those, so a17+ * later landing shows at once). A value that fails to decode is a miss.18+ *19+ * Read order: the isolate's `CodeCache` (with the heavy reads: a why's20+ * ranges grow with its file), then the `CodeStore`, then the walk; what a21+ * walk computed is put in both. A walk may start from what is22+ * kept at a first-parent ancestor at most `INCREMENT_REACH` commits back,23+ * so a new landing on main costs a handful of reads.24+ */25+import { WhyRange } from "@repo/protocol/domain/code";26+import { BlobSha, CommitSha } from "@repo/protocol/ids";27+import type { RepoName, RepoPath } from "@repo/protocol/ids";28+import { Effect, Option, Schema } from "effect";29+30+import { CodeStore } from "../code-store.ts";31+import { CodeCache } from "./cache.ts";32+33+/** The why walk's algorithm version, in its keys. */34+export const WHY_VERSION = 1;35+36+/** The path log's algorithm version, in its keys. */37+export const LOG_VERSION = 1;38+39+/** How many first-parent commits back a walk looks for a kept result to start from. */40+export const INCREMENT_REACH = 16;41+42+/**43+ * Why each line is there at a commit: the path's blob there, the ranges,44+ * the commits they name (newest first), and where the walk stopped.45+ */46+export const StoredWhy = Schema.Struct({47+ blob: BlobSha,48+ ranges: Schema.Array(WhyRange),49+ shas: Schema.Array(CommitSha),50+ stoppedAt: Schema.optionalKey(CommitSha),51+});52+53+export type StoredWhy = typeof StoredWhy.Type;54+55+/**56+ * A path's history from a commit: the first-parent commits of the scan57+ * that changed it, newest first, and whether the scan reached the root.58+ */59+export const StoredPathLog = Schema.Struct({60+ reachedRoot: Schema.Boolean,61+ shas: Schema.Array(CommitSha),62+});63+64+export type StoredPathLog = typeof StoredPathLog.Type;65+66+/** The lowercase hex SHA-256 of `text`. */67+const sha256 = (text: string) =>68+ Effect.map(69+ Effect.promise(() =>70+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))71+ ),72+ (digest) =>73+ [...new Uint8Array(digest)]74+ .map((byte) => byte.toString(16).padStart(2, "0"))75+ .join("")76+ );77+78+/** One kind of kept history: its key's kind and version, and its value. */79+export interface Kept<A> {80+ readonly kind: string;81+ readonly version: number;82+ readonly schema: Schema.Codec<A, unknown>;83+}84+85+export const whyKept: Kept<StoredWhy> = {86+ kind: "why",87+ schema: StoredWhy,88+ version: WHY_VERSION,89+};90+91+export const pathLogKept: Kept<StoredPathLog> = {92+ kind: "path-log",93+ schema: StoredPathLog,94+ version: LOG_VERSION,95+};96+97+/** Where `kept` is kept for `path` from `commit`, scanning `scan` commits. */98+export const keyOf = <A>(99+ kept: Kept<A>,100+ at: {101+ readonly repo: RepoName;102+ readonly commit: CommitSha;103+ readonly scan: number;104+ readonly path: RepoPath;105+ }106+) =>107+ Effect.map(108+ sha256(at.path),109+ (hash) =>110+ `${at.repo}/${kept.kind}/v${kept.version}/${at.commit}/${at.scan}/${hash}`111+ );112+113+/**114+ * What is kept under `key`: the isolate's cache first, then the store. A115+ * miss is never cached, so a value another isolate keeps later is found.116+ */117+export const recall = <A>(118+ kept: Kept<A>,119+ key: string120+): Effect.Effect<Option.Option<A>> =>121+ Effect.gen(function* () {122+ const cache = yield* CodeCache;123+ const store = yield* CodeStore;124+125+ const decode = Schema.decodeUnknownOption(126+ Schema.fromJsonString(kept.schema)127+ );128+129+ return yield* cache.through(130+ key,131+ Effect.map(store.get(key), Option.flatMap(decode)),132+ { heavy: true, keep: Option.isSome }133+ );134+ });135+136+/** `value` kept under `key`, in the isolate's cache and in the store. */137+export const remember = <A>(138+ kept: Kept<A>,139+ key: string,140+ value: A141+): Effect.Effect<void> =>142+ Effect.gen(function* () {143+ const cache = yield* CodeCache;144+ const store = yield* CodeStore;145+146+ const encoded = yield* Schema.encodeEffect(147+ Schema.fromJsonString(kept.schema)148+ )(value).pipe(Effect.orDie);149+150+ yield* store.put(key, encoded);151+ yield* cache.through(key, Effect.succeedSome(value), { heavy: true });152+ });153+154+/**155+ * What is kept under `key`, else `compute` run and its value kept: a156+ * failure is never kept.157+ */158+export const throughHistory = <A, E, R>(159+ kept: Kept<A>,160+ key: string,161+ compute: Effect.Effect<A, E, R>162+): Effect.Effect<A, E, R> =>163+ Effect.flatMap(recall(kept, key), (found) =>164+ Option.match(found, {165+ onNone: () => Effect.tap(compute, (value) => remember(kept, key, value)),166+ onSome: Effect.succeed,167+ })168+ );modified:packages/project/src/code/log.ts+161 added-56 removed
3 unmodified lines4 * only where the project's record has one, so a trailer in an imported5 * commit never reads as a landing. With a path, only the commits whose6 * first-parent change touched it, scanning at most 200 commits a call;7 * `next` is where the scan stopped, so the next page resumes it.8+ *9+ * A path's history from the scan's first commit is kept by immutable ids10+ * (`history.ts`) under `<repo>/path-log/v<LOG_VERSION>/<commit>/<scan>/11+ * <sha256(path)>`: the commits of the scan that changed the path, newest12+ * first, and whether the scan reached the root; pages are cut from it.13+ * Kept nowhere yet, it is the history kept at the nearest first-parent14+ * ancestor within `INCREMENT_REACH` commits plus the commits between that15+ * changed the path, cut to the scan; else each commit of the scan has its16+ * entry looked up once (`READS_AT_ONCE` under way, in one ordered pass),17+ * and neighbours compared.18 */9-import { Revision, RepoHost } from "@repo/artifacts/repo-host";19+import { inRepoSession, Revision, RepoHost } from "@repo/artifacts/repo-host";20 import type {21 Commit,22 RepoNotFound,23 TreeEntry,6 unmodified lines30 import type { UnknownRevision } from "@repo/protocol/refusal";31 import { Array, DateTime, Effect, Equal, Option } from "effect";32 33 import type { CodeProject } from "../code.ts";24-import { CodeCache } from "./cache.ts";34+import { asOneView, CodeCache } from "./cache.ts";35+import {36+ INCREMENT_REACH,37+ keyOf,38+ pathLogKept,39+ recall,40+ throughHistory,41+} from "./history.ts";42+import type { StoredPathLog } from "./history.ts";43 import { commitAt, resolveRev } from "./revision.ts";44 import { entryAt, READS_AT_ONCE } from "./tree.ts";45 46 /** The most commits one page holds. */59 unmodified lines106 /**107 * `count` first-parent commits from `sha`, the first `from` skipped: a108 * commit's history never changes, so the page is kept by its start.109 */92-const pageOf = (110+export const pageOf = (111 repo: RepoName,112 sha: CommitSha,113 from: number,114 count: number31 unmodified lines146 onNone: () => ({ commits }),147 onSome: (at) => ({ commits, next: at }),148 });149 150+/** What sits at `path` in each commit of `commits`, in order: one lookup each. */151+const idsOf = (152+ repo: RepoName,153+ path: RepoPath,154+ commits: readonly Commit[]155+): Effect.Effect<readonly Option.Option<string>[], RepoNotFound, RepoHost> =>156+ Effect.forEach(commits, ({ tree }) => idAt(repo, tree, path), {157+ concurrency: READS_AT_ONCE,158+ });159+160+/**161+ * The commits among the first `count` of `scan` that changed `path` from162+ * their first parent, newest first. The log is first parents, so each163+ * commit's parent is the next in `scan`; only past it (or should the log164+ * ever say otherwise) is a parent read on its own.165+ */166+const changedIn = (167+ repo: RepoName,168+ path: RepoPath,169+ scan: readonly Commit[],170+ count: number171+): Effect.Effect<readonly CommitSha[], RepoNotFound, RepoHost> =>172+ Effect.gen(function* () {173+ const looked = scan.slice(0, count + 1);174+ const ids = yield* idsOf(repo, path, looked);175+176+ const changed = yield* Effect.forEach(177+ looked.slice(0, count),178+ (commit, at) =>179+ Effect.gen(function* () {180+ const parent = Option.fromUndefinedOr(commit.parents[0]);181+ const after = looked[at + 1];182+183+ const before = yield* Option.match(parent, {184+ onNone: () => Effect.succeedNone,185+ onSome: (first) =>186+ after !== undefined && after.sha === first187+ ? Effect.succeed(ids[at + 1] ?? Option.none())188+ : commitAt(repo, first).pipe(189+ Effect.flatMap(190+ Option.match({191+ onNone: () => Effect.succeedNone,192+ onSome: ({ tree }) => idAt(repo, tree, path),193+ })194+ )195+ ),196+ });197+198+ return Equal.equals(ids[at] ?? Option.none(), before)199+ ? Option.none()200+ : Option.some(commit.sha);201+ }),202+ { concurrency: READS_AT_ONCE }203+ );204+205+ return Array.getSomes(changed);206+ });207+208+/** The path's history from `scan[0]`, kept at the nearest ancestor within reach. */209+const nearestKept = (repo: RepoName, path: RepoPath, scan: readonly Commit[]) =>210+ Effect.map(211+ Effect.forEach(212+ scan.slice(1, INCREMENT_REACH + 1),213+ ({ sha }) =>214+ Effect.flatMap(215+ keyOf(pathLogKept, { commit: sha, path, repo, scan: PATH_SCAN }),216+ (key) => recall(pathLogKept, key)217+ ),218+ { concurrency: INCREMENT_REACH }219+ ),220+ (found) =>221+ Array.findFirst(found, (kept, at) =>222+ Option.map(kept, (value) => ({ back: at + 1, kept: value }))223+ )224+ );225+226+/** The path's history over `scan` (at most `PATH_SCAN` commits and the parent of its last). */227+const historyOf = (228+ repo: RepoName,229+ path: RepoPath,230+ scan: readonly Commit[]231+): Effect.Effect<StoredPathLog, RepoNotFound, RepoHost> =>232+ Effect.gen(function* () {233+ const scanned = scan.slice(0, PATH_SCAN);234+ const reachedRoot = scan.length <= PATH_SCAN;235+ const kept = yield* nearestKept(repo, path, scan);236+237+ if (Option.isNone(kept)) {238+ return {239+ reachedRoot,240+ shas: yield* changedIn(repo, path, scan, scanned.length),241+ };242+ }243+244+ const { back } = kept.value;245+ const inScan = new Set<string>(scanned.map(({ sha }) => sha));246+ const between = yield* changedIn(repo, path, scan, back);247+248+ return {249+ reachedRoot,250+ shas: [251+ ...between,252+ ...kept.value.kept.shas.filter((sha) => inScan.has(sha)),253+ ],254+ };255+ });256+257 /** A page of first-parent commits from `at`, each landing with its record. */258 export const logPage = (259 project: CodeProject,260 input: {26 unmodified lines287 const scan = yield* pageOf(repo, sha, from, PATH_SCAN + 1).pipe(288 Effect.orDie289 );290 166- const scanned = scan.slice(0, PATH_SCAN);167- const touched: Commit[] = [];291+ const [start] = scan;292 169- /** Whether the commit at `at` in the scan changed `path` from its first parent. */170- const changedAt = (at: number, commit: Commit) =>171- Effect.gen(function* () {172- const parent = Option.fromUndefinedOr(commit.parents[0]);173- const after = Option.fromUndefinedOr(scan[at + 1]);293+ if (start === undefined) {294+ return pageWith([], Option.none());295+ }296 175- // The log is first parents, so the next commit in it is this one's176- // parent; only past the scan is the parent read on its own.177- const parentCommit = yield* Option.match(parent, {178- onNone: () => Effect.succeedNone,179- onSome: (first) =>180- Option.exists(after, ({ sha: next }) => next === first)181- ? Effect.succeed(after)182- : commitAt(repo, first),183- });297+ const key = yield* keyOf(pathLogKept, {298+ commit: start.sha,299+ path,300+ repo,301+ scan: PATH_SCAN,302+ });303 185- const parentTree = Option.map(parentCommit, ({ tree }) => tree);304+ const { shas } = yield* throughHistory(305+ pathLogKept,306+ key,307+ asOneView(historyOf(repo, path, scan))308+ ).pipe(Effect.orDie);309 187- const [now, before] = yield* Effect.all(188- [189- idAt(repo, commit.tree, path),190- Option.match(parentTree, {191- onNone: () => Effect.succeedNone,192- onSome: (tree) => idAt(repo, tree, path),193- }),194- ],195- { concurrency: 2 }196- );310+ const at = new Map(scan.map((commit, index) => [commit.sha, index]));311 198- return !Equal.equals(now, before);199- }).pipe(Effect.orDie);312+ const touched = shas.slice(0, limit).flatMap((changed) => {313+ const commit = scan[at.get(changed) ?? scan.length];314 201- // Each batch is read together, then walked in order, so a page that202- // fills stops the scan where its last commit is.203- for (const batch of Array.chunksOf([...scanned.entries()], READS_AT_ONCE)) {204- const changed = yield* Effect.forEach(205- batch,206- ([at, commit]) => changedAt(at, commit),207- { concurrency: READS_AT_ONCE }208- );315+ return commit === undefined ? [] : [commit];316+ });317 210- for (const [[at, commit], touches] of Array.zip(batch, changed)) {211- if (touches) {212- touched.push(commit);213- }318+ const commits = yield* commitViews(project, touched);319+ const newest = touched.at(-1);320+ const last = newest === undefined ? undefined : at.get(newest.sha);321 215- if (touched.length === limit) {216- const commits = yield* commitViews(project, touched);217-218- return pageWith(219- commits,220- at + 1 < scan.length ? Option.some(from + at + 1) : Option.none()221- );322+ // A page that fills stops the scan at its last commit.323+ if (touched.length === limit && last !== undefined) {324+ return pageWith(325+ commits,326+ last + 1 < scan.length ? Option.some(from + last + 1) : Option.none()327+ );222- }223- }328 }329 226- const commits = yield* commitViews(project, touched);227-330 return pageWith(331 commits,332 scan.length > PATH_SCAN ? Option.some(from + PATH_SCAN) : Option.none()333 );232- });334+ }).pipe(335+ // The scan and the walk over it: one session, one handle.336+ inRepoSession337+ );modified:packages/project/src/code/tree.ts+8 added-5 removed
17 unmodified lines18 import { commitAt, resolveRev } from "./revision.ts";19 20 /**21 * How many commits a walk over history (a path's log, why each line is22- * there) reads at once. A live store answers each read in tens of23- * milliseconds, so one at a time a 200-commit walk took a minute on24- * dev-oscabriel; sixteen at once stays far under the store's 2,00025- * requests per 10 s per repo.22+ * there) has under way at once, in one ordered pass with no batch to wait23+ * on. A live store answers each read in tens to hundreds of milliseconds,24+ * and a path four folders deep chains five reads per commit, so one at a25+ * time a 200-commit walk took a minute on dev-oscabriel and sixteen at26+ * once in batches still 14-28 s. Forty-eight at once, at a few27+ * hundred milliseconds each, stays under the store's 2,000 requests per28+ * 10 s per repo for one viewer.29 */27-export const READS_AT_ONCE = 16;30+export const READS_AT_ONCE = 48;31 32 /** The entries of the tree `id`; a tree a commit or a tree names is always there. */33 export const entriesOf = (34 repo: RepoName,163 unmodified linesmodified:packages/project/src/code/why.ts+405 added-118 removed
1 /**2 * Why each line of a file is there (ADR 0019): a first-parent blame from3- * a revision. The walk takes at most `WHY_SCAN` first-parent commits from4- * the log and the path's blob at each (trees kept by id through5- * `CodeCache`, `READS_AT_ONCE` commits read together), keeps the commits6- * where the blob changed, then reads those blobs newest first, a batch at7- * a time, only until every line has its commit (`@repo/git/blame`). Each commit a line points at comes back as a reader8- * sees it, and the landings among them come from the project's record in9- * one batch, so an imported commit never reads as a landing. Lines older10- * than the walk reached point at the commit it stopped at, named11- * `stoppedAt`. A binary file, or one past 1 MiB, has no ranges. The whole12- * view is kept by `(at, path)`: what a commit holds never changes.3+ * a revision, kept by immutable ids (`history.ts`): the path's blob at the4+ * commit, the ranges, the commits they name and where the walk stopped,5+ * under `<repo>/why/v<WHY_VERSION>/<commit>/<scan>/<sha256(path)>`. Each6+ * view reads the commits it names (kept by id) and asks the project's7+ * record for their landings in one batch, so an imported commit never8+ * reads as a landing and a later landing shows at once.9+ *10+ * Kept nowhere yet, the why is computed from the nearest first-parent11+ * ancestor within `INCREMENT_REACH` commits that has one: each line is12+ * carried forward through the file's versions between them (a line diff13+ * per change), and a line a version inserted goes to the commit that made14+ * it. Otherwise the walk takes at most `WHY_SCAN` first-parent commits from15+ * the log, looks up the path's blob in each (`READS_AT_ONCE` under way, in16+ * order, with no batch to wait on, until the file's first commit), then17+ * reads the changed versions newest first only until every line has its18+ * commit (`@repo/git/blame`). Lines older than the walk reached point at19+ * the commit it stopped at, named `stoppedAt`. A binary file, or one past20+ * 1 MiB, has no ranges.21 */14-import { ObjectId, Revision, RepoHost } from "@repo/artifacts/repo-host";22+import { inRepoSession, ObjectId, RepoHost } from "@repo/artifacts/repo-host";23 import type { Commit, RepoNotFound } from "@repo/artifacts/repo-host";16-import { blameFrom, isSettled, settle, traceBack } from "@repo/git/blame";17-import type { Rev, WhyView } from "@repo/protocol/domain/code";24+import {25+ blameFrom,26+ isSettled,27+ linesOf,28+ settle,29+ traceBack,30+} from "@repo/git/blame";31+import { Edit, lineDiff } from "@repo/git/line-diff";32+import type { Rev, WhyRange, WhyView } from "@repo/protocol/domain/code";33 import { BlobSha } from "@repo/protocol/ids";34 import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";35 import { UnknownPath } from "@repo/protocol/refusal";36 import type { UnknownRevision } from "@repo/protocol/refusal";22-import { Array, Effect, Option } from "effect";37+import { Array, Effect, Option, Ref, Stream } from "effect";38 39 import type { CodeProject } from "../code.ts";40 import { MAX_LANDINGS } from "../project.ts";26-import { CodeCache } from "./cache.ts";41+import { asOneView } from "./cache.ts";42 import { contentsOf, contentsOfBytes, unlessTooLarge } from "./file.ts";43+import {44+ INCREMENT_REACH,45+ keyOf,46+ recall,47+ throughHistory,48+ whyKept,49+} from "./history.ts";50+import type { StoredWhy } from "./history.ts";28-import { commitViews } from "./log.ts";51+import { commitViews, pageOf } from "./log.ts";52 import { commitAt, resolveRev } from "./revision.ts";53 import { entryAt, READS_AT_ONCE } from "./tree.ts";54 55 /** The most first-parent commits one view walks. */4 unmodified lines60 readonly blob: BlobSha;61 readonly commit: Commit;62 }63 64+/** The file's versions newest first, and whether the walk stopped short of its first commit. */65+interface Versions {66+ readonly versions: readonly Version[];67+ readonly stopped: boolean;68+}69+70 /** The file's blob at `path` in `commit`, if a file is there. */71 const blobAt = (repo: RepoName, commit: Commit, path: RepoPath) =>72 Effect.map(73 entryAt(repo, commit.tree, path),4 unmodified lines78 )79 );80 81 /**53- * The file's versions newest first, from the commits of `log` (first54- * parents, newest first, starting with the blob `newest`), and whether the55- * walk stopped short of the file's first commit.82+ * The file's blob in each of `commits` (first parents, newest first), up to83+ * the first commit without the file. One pass with `READS_AT_ONCE` lookups84+ * under way and no barrier: a slow lookup holds up only itself, not the85+ * ones after it. Once a commit without the file is found, lookups further86+ * back are skipped.87 */57-const versionsOf = (58- repo: RepoName,59- path: RepoPath,60- log: readonly Commit[],61- newest: Version62-): Effect.Effect<63- { readonly versions: readonly Version[]; readonly stopped: boolean },64- RepoNotFound,65- RepoHost66-> =>88+const lookups = (repo: RepoName, path: RepoPath, commits: readonly Commit[]) =>89 Effect.gen(function* () {68- const versions: Version[] = [];69- let current = newest;90+ // Where the file was found missing: no lookup past it is needed.91+ const missingAt = yield* Ref.make(commits.length);92 71- // Each batch's blobs are read together, then walked in order.72- for (const batch of Array.chunksOf(log.slice(1), READS_AT_ONCE)) {73- const blobs = yield* Effect.forEach(74- batch,75- (commit) => blobAt(repo, commit, path),76- { concurrency: READS_AT_ONCE }77- );93+ const found = yield* Effect.forEach(94+ commits,95+ (commit, at) =>96+ Effect.gen(function* () {97+ if (at > (yield* Ref.get(missingAt))) {98+ return Option.none();99+ }100 79- for (const [commit, blob] of Array.zip(batch, blobs)) {80- if (Option.contains(blob, current.blob)) {81- current = { blob: current.blob, commit };82- } else {83- versions.push(current);101+ const blob = yield* blobAt(repo, commit, path);102 103 if (Option.isNone(blob)) {86- // The file was born in the commit after this one.87- return { stopped: false, versions };104+ yield* Ref.update(missingAt, (was) => Math.min(was, at));105 }106 90- current = { blob: blob.value, commit };91- }107+ return Option.some({ blob, commit });108+ }),109+ { concurrency: READS_AT_ONCE }110+ );111+112+ const looked = Array.getSomes(found);113+ const missing = looked.findIndex(({ blob }) => Option.isNone(blob));114+115+ return missing === -1 ? looked : looked.slice(0, missing + 1);116+ });117+118+/**119+ * The file's versions newest first, from `newest` and the blobs `found` in120+ * the commits before it, and whether the walk stopped short of the file's121+ * first commit.122+ */123+const versionsOf = (124+ newest: Version,125+ found: readonly {126+ readonly blob: Option.Option<BlobSha>;127+ readonly commit: Commit;128+ }[]129+): Versions => {130+ const versions: Version[] = [];131+ let current = newest;132+133+ for (const { blob, commit } of found) {134+ if (Option.contains(blob, current.blob)) {135+ current = { blob: current.blob, commit };136+ } else {137+ versions.push(current);138+139+ if (Option.isNone(blob)) {140+ // The file was born in the commit after this one.141+ return { stopped: false, versions };142 }143+144+ current = { blob: blob.value, commit };145 }146+ }147 95- versions.push(current);148+ versions.push(current);149 97- return {98- stopped: current.commit.parents.length > 0,99- versions,100- };101- });150+ return {151+ stopped: current.commit.parents.length > 0,152+ versions,153+ };154+};155 156 /**157 * An older version's text as the blame reads it, empty for a binary or too158 * large one. Read past the cache: old versions are seldom viewed, and13 unmodified lines172 Effect.forEach(Array.chunksOf(shas, MAX_LANDINGS), project.landings),173 Array.flatten174 );175 123-/** The view, read: `at` is a commit of the canonical repo. */124-const read = (125- project: CodeProject,126- at: CommitSha,176+/** Each line's commit, from ranges of consecutive lines numbered from 1. */177+const ownersOf = (ranges: readonly WhyRange[]): readonly CommitSha[] =>178+ ranges.flatMap(({ end, sha, start }) =>179+ Array.makeBy(end - start + 1, () => sha)180+ );181+182+/** Each line's commit as ranges of consecutive lines, numbered from 1. */183+const rangesOf = (owners: readonly CommitSha[]): readonly WhyRange[] => {184+ const ranges: WhyRange[] = [];185+186+ for (const [index, sha] of owners.entries()) {187+ const last = ranges.at(-1);188+ const line = index + 1;189+190+ if (last !== undefined && last.sha === sha && last.end === index) {191+ ranges[ranges.length - 1] = { ...last, end: line };192+ } else {193+ ranges.push({ end: line, sha, start: line });194+ }195+ }196+197+ return ranges;198+};199+200+/**201+ * Each line of `after`'s commit, carried forward from `before`'s: a line202+ * the diff keeps keeps its commit, and a line `after` inserted goes to203+ * `sha`, the commit that made `after`.204+ */205+const carried = (206+ before: { readonly text: string; readonly owners: readonly CommitSha[] },207+ after: string,208+ sha: CommitSha209+): readonly CommitSha[] => {210+ const lines = linesOf(after);211+ const owners: CommitSha[] = lines.map(() => sha);212+213+ for (const edit of lineDiff(linesOf(before.text), lines)) {214+ if (Edit.$is("Equal")(edit)) {215+ for (let at = 0; at < edit.count; at += 1) {216+ owners[edit.newStart + at] = before.owners[edit.oldStart + at] ?? sha;217+ }218+ }219+ }220+221+ return owners;222+};223+224+/** The why kept at `log[at]`'s nearest ancestor within reach, and how far back. */225+const nearestKept = (226+ repo: RepoName,227 path: RepoPath,228+ log: readonly Commit[],229 scan: number230+) =>231+ Effect.map(232+ Effect.forEach(233+ log.slice(1, INCREMENT_REACH + 1),234+ ({ sha }) =>235+ Effect.flatMap(236+ keyOf(whyKept, { commit: sha, path, repo, scan }),237+ (key) => recall(whyKept, key)238+ ),239+ { concurrency: INCREMENT_REACH }240+ ),241+ (found) =>242+ Array.findFirst(found, (kept, at) =>243+ Option.map(kept, (value) => ({ back: at + 1, kept: value }))244+ )245+ );246+247+/**248+ * The why at `log[0]`, whose blob is `newest`, carried forward from `kept`249+ * at `log[back]` through the blobs `between` them; none when the file is250+ * missing in a commit between (its history starts again there, so the251+ * whole walk answers).252+ */253+const forward = (254+ repo: RepoName,255+ log: readonly Commit[],256+ newest: BlobSha,257+ between: readonly Option.Option<BlobSha>[],258+ from: { readonly back: number; readonly kept: StoredWhy }129-): Effect.Effect<WhyView, UnknownPath | RepoNotFound, RepoHost> =>259+): Effect.Effect<Option.Option<StoredWhy>, RepoNotFound, RepoHost> =>260 Effect.gen(function* () {131- const { repo } = project;261+ if (!between.every(Option.isSome)) {262+ return Option.none();263+ }264 133- const head = yield* commitAt(repo, at).pipe(134- Effect.flatMap(Effect.fromOption),135- Effect.orDie265+ const blobs = [newest, ...between.map(Option.getOrThrow)];266+267+ // Each version the commits made, oldest first: where a commit's blob268+ // differs from its parent's.269+ const changes = blobs270+ .flatMap((blob, at) => {271+ const parent = blobs[at + 1] ?? from.kept.blob;272+ const commit = log[at];273+274+ return blob === parent || commit === undefined275+ ? []276+ : [{ blob, sha: commit.sha }];277+ })278+ .toReversed();279+280+ if (changes.length === 0) {281+ return Option.some(from.kept);282+ }283+284+ const newestContents = yield* contentsOf(repo, newest);285+286+ if (287+ Option.isNone(newestContents) ||288+ Option.isNone(newestContents.value.text)289+ ) {290+ return Option.some({ blob: newest, ranges: [], shas: [] });291+ }292+293+ const newestText = newestContents.value.text.value;294+295+ const [base, ...texts] = yield* Effect.forEach(296+ [{ blob: from.kept.blob }, ...changes],297+ ({ blob }) =>298+ blob === newest ? Effect.succeed(newestText) : textOf(repo, blob),299+ { concurrency: READS_AT_ONCE }300 );301 138- const blob = yield* blobAt(repo, head, path);302+ let tracing = {303+ owners: ownersOf(from.kept.ranges),304+ text: base ?? "",305+ };306 140- if (Option.isNone(blob)) {141- return yield* new UnknownPath({ commit: at, path });307+ for (const [{ sha }, text] of Array.zip(changes, texts)) {308+ tracing = { owners: carried(tracing, text, sha), text };309 }310 144- const none: WhyView = { at, commits: [], landings: [], path, ranges: [] };311+ const named = new Set<string>(tracing.owners);312+ const added = changes.map(({ sha }) => sha).toReversed();313 146- const contents = yield* contentsOf(repo, blob.value);314+ const shas = [...added, ...from.kept.shas].filter(315+ (sha, at, all) => named.has(sha) && all.indexOf(sha) === at316+ );317 318+ const stoppedAt = Option.filter(319+ Option.fromUndefinedOr(from.kept.stoppedAt),320+ (sha) => named.has(sha)321+ );322+323+ return Option.some({324+ blob: newest,325+ ranges: rangesOf(tracing.owners),326+ shas,327+ ...Option.match(stoppedAt, {328+ onNone: () => ({}),329+ onSome: (sha) => ({ stoppedAt: sha }),330+ }),331+ });332+ });333+334+/**335+ * The why at `log[0]` by the whole walk. The head's blob and text are read336+ * beside the other commits' lookups, so nothing waits on the head's337+ * folders before the pass starts.338+ */339+const walked = (340+ repo: RepoName,341+ at: CommitSha,342+ path: RepoPath,343+ log: readonly Commit[],344+ head: Commit345+): Effect.Effect<StoredWhy, UnknownPath | RepoNotFound, RepoHost> =>346+ Effect.gen(function* () {347+ const [headSide, found] = yield* Effect.all(348+ [349+ Effect.gen(function* () {350+ const blob = yield* blobAt(repo, head, path);351+352+ if (Option.isNone(blob)) {353+ return yield* new UnknownPath({ commit: at, path });354+ }355+356+ return {357+ blob: blob.value,358+ contents: yield* contentsOf(repo, blob.value),359+ };360+ }),361+ lookups(repo, path, log.slice(1)),362+ ],363+ { concurrency: 2 }364+ );365+366+ const newest = headSide.blob;367+ const { contents } = headSide;368+ const none: StoredWhy = { blob: newest, ranges: [], shas: [] };369+370 if (Option.isNone(contents) || Option.isNone(contents.value.text)) {371 return none;372 }373 152- const log = yield* RepoHost.use((host) =>153- host.log(repo, Revision.Commit({ sha: at }), Math.max(1, scan))374+ const { stopped, versions } = versionsOf(375+ { blob: newest, commit: head },376+ found377 );378 156- const { stopped, versions } = yield* versionsOf(repo, path, log, {157- blob: blob.value,158- commit: head,159- });379+ const [first = { blob: newest, commit: head }, ...older] = versions;380+ const text = contents.value.text.value;381 161- const [newest = { blob: blob.value, commit: head }, ...older] = versions;382+ // The newest version is the file as read: its text is at hand. The383+ // older ones are read in order, `READS_AT_ONCE` under way, only until384+ // every line has its commit.385+ const tracing = yield* Stream.fromIterable(older).pipe(386+ Stream.mapEffect(387+ (version) =>388+ Effect.map(textOf(repo, version.blob), (read) => ({389+ sha: version.commit.sha,390+ text: read,391+ })),392+ { concurrency: READS_AT_ONCE }393+ ),394+ Stream.scan(() => blameFrom({ sha: first.commit.sha, text }), traceBack),395+ Stream.takeUntil(isSettled),396+ Stream.runLast,397+ Effect.map(Option.getOrThrow)398+ );399 163- // The newest version is the file as read: its text is at hand.164- let tracing = blameFrom({165- sha: newest.commit.sha,166- text: contents.value.text.value,167- });400+ const { ranges, reachedEnd } = settle(tracing);401+ const named = new Set<string>(ranges.map(({ sha }) => sha));402 169- // Each batch of older versions is read together, then traced in170- // order, until every line has its commit.171- for (const batch of Array.chunksOf(older, READS_AT_ONCE)) {172- if (isSettled(tracing)) {173- break;174- }403+ const shas = versions404+ .map(({ commit }) => commit.sha)405+ .filter((sha) => named.has(sha));406 176- const texts = yield* Effect.forEach(177- batch,178- (version) => textOf(repo, version.blob),407+ const last = versions.at(-1);408+409+ // Lines the walk did not see brought: they point at where it stopped.410+ return stopped && reachedEnd && last !== undefined411+ ? { ...none, ranges, shas, stoppedAt: last.commit.sha }412+ : { ...none, ranges, shas };413+ });414+415+/** The why at `at`, computed: from a kept ancestor's when one is in reach. */416+const computed = (417+ repo: RepoName,418+ at: CommitSha,419+ path: RepoPath,420+ scan: number421+): Effect.Effect<StoredWhy, UnknownPath | RepoNotFound, RepoHost> =>422+ Effect.gen(function* () {423+ const log = yield* pageOf(repo, at, 0, Math.max(1, scan));424+ const [head] = log;425+426+ if (head === undefined) {427+ return yield* Effect.die(`${repo} has no log from ${at}`);428+ }429+430+ const kept = yield* nearestKept(repo, path, log, scan);431+432+ if (Option.isSome(kept)) {433+ const [newest, ...between] = yield* Effect.forEach(434+ log.slice(0, kept.value.back),435+ (commit) => blobAt(repo, commit, path),436 { concurrency: READS_AT_ONCE }437 );438 182- for (const [version, text] of Array.zip(batch, texts)) {183- if (isSettled(tracing)) {184- break;185- }439+ if (newest === undefined || Option.isNone(newest)) {440+ return yield* new UnknownPath({ commit: at, path });441+ }442 187- tracing = traceBack(tracing, { sha: version.commit.sha, text });443+ const carriedForward = yield* forward(444+ repo,445+ log,446+ newest.value,447+ between,448+ kept.value449+ );450+451+ if (Option.isSome(carriedForward)) {452+ return carriedForward.value;453 }454 }455 191- const { ranges, reachedEnd } = settle(tracing);192- const named = new Set<string>(ranges.map(({ sha }) => sha));456+ return yield* walked(repo, at, path, log, head);457+ });458 194- const commits = versions195- .map(({ commit }) => commit)196- .filter(({ sha }) => named.has(sha));459+/** The view of `kept`: each commit it names as a reader sees it, and their landings. */460+const viewOf = (461+ project: CodeProject,462+ at: CommitSha,463+ path: RepoPath,464+ kept: StoredWhy465+): Effect.Effect<WhyView, RepoNotFound, RepoHost> =>466+ Effect.gen(function* () {467+ const commits = yield* Effect.forEach(468+ kept.shas,469+ (sha) =>470+ commitAt(project.repo, sha).pipe(471+ Effect.flatMap(Effect.fromOption),472+ Effect.catchTag("NoSuchElementError", () =>473+ Effect.die(`${project.repo} has no commit ${sha}`)474+ )475+ ),476+ { concurrency: READS_AT_ONCE }477+ );478 479 const views = yield* commitViews(480 { ...project, landings: () => Effect.succeed([]) },481 commits482 );483 203- const landings = yield* landingsOf(204- project,205- commits.map(({ sha }) => sha)206- );484+ const landings = yield* landingsOf(project, kept.shas);485 208- const found: WhyView = { ...none, commits: views, landings, ranges };209- const last = versions.at(-1);210-211- // Lines the walk did not see brought: they point at where it stopped.212- return stopped && reachedEnd && last !== undefined213- ? { ...found, stoppedAt: last.commit.sha }214- : found;486+ return {487+ at,488+ commits: views,489+ landings,490+ path,491+ ranges: kept.ranges,492+ ...Option.match(Option.fromUndefinedOr(kept.stoppedAt), {493+ onNone: () => ({}),494+ onSome: (stoppedAt) => ({ stoppedAt }),495+ }),496+ };497 });498 499 /** Why each line of `path` at `at` is there, walking at most `scan` commits. */500 export const whyView = (3 unmodified lines504 scan: number = WHY_SCAN505 ): Effect.Effect<WhyView, UnknownRevision | UnknownPath, RepoHost> =>506 Effect.gen(function* () {507 const commit = yield* resolveRev(project, at);226- const cache = yield* CodeCache;508+ const { repo } = project;509+ const key = yield* keyOf(whyKept, { commit, path, repo, scan });510 228- return yield* cache229- .through(230- `${project.repo}:why:${commit}:${scan}:${path}`,231- read(project, commit, path, scan),232- { heavy: true }233- )234- .pipe(Effect.catchTag("RepoNotFound", Effect.die));235- });511+ const kept = yield* throughHistory(512+ whyKept,513+ key,514+ asOneView(computed(repo, commit, path, scan))515+ );516+517+ return yield* viewOf(project, commit, path, kept);518+ }).pipe(519+ // The walk and the commits it names: one session, one handle.520+ inRepoSession,521+ Effect.catchTag("RepoNotFound", Effect.die)522+ );added:packages/project/test/code-history.test.ts+700 added
1+/**2+ * Code history kept by immutable ids, over the memory repo3+ * host behind a wrapper that counts the trees and blobs read, the memory4+ * code store, and a fresh `CodeCacheLive` for each isolate: a why and a5+ * path's log computed on one isolate are read back on another without a6+ * walk; one landing past a kept result costs a handful of reads and agrees7+ * with the whole walk; landings are always asked fresh; a cold walk keeps8+ * many reads under way and looks each commit's entry up once; a value9+ * that no longer decodes is computed again and replaced.10+ */11+import { describe, expect, it } from "@effect/vitest";12+import { RepoHost, RepoSession } from "@repo/artifacts/repo-host";13+import type { RepoSessionApi } from "@repo/artifacts/repo-host";14+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";15+import type { LandingView } from "@repo/protocol/domain/landing";16+import {17+ AskId,18+ Handle,19+ LandedSha,20+ ProjectName,21+ RepoName,22+ RepoPath,23+} from "@repo/protocol/ids";24+import type { CommitSha } from "@repo/protocol/ids";25+import { DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";26+27+import { CodeStore } from "../src/code-store.ts";28+import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";29+import { logOf, whyOf } from "../src/code.ts";30+import type { CodeProject } from "../src/code.ts";31+import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";32+import type { CodeReads } from "../src/code/cache.ts";33+import { keyOf, StoredWhy, whyKept } from "../src/code/history.ts";34+import { WHY_SCAN } from "../src/code/why.ts";35+import { Content, writer } from "./code-fixtures.ts";36+import type { Tree } from "./code-fixtures.ts";37+38+const project = ProjectName.make("histkit");39+40+const repo = RepoName.make(project);41+42+const format = RepoPath.make("src/format.ts");43+44+const text = (value: string) => Content.Text({ text: value });45+46+/**47+ * What the counting host saw: trees and blobs read, the most under way at48+ * once, and each read's start (`+<id>`) and end (`-<id>`) in order.49+ */50+interface Seen {51+ readonly trees: number;52+ readonly blobs: number;53+ readonly peak: number;54+ readonly events: readonly string[];55+}56+57+const none: Seen = { blobs: 0, events: [], peak: 0, trees: 0 };58+59+/** How long a read of the object `id` takes, once a test sets it. */60+type Delay = Option.Option<(id: string) => Duration.Duration>;61+62+/**63+ * The memory store, each tree and blob read counted in `seen` and, once64+ * `delay` is set, taking as long as it says: a live store answers each65+ * read in tens to hundreds of milliseconds.66+ */67+const counted = (seen: Ref.Ref<Seen>, delay: Ref.Ref<Delay>) =>68+ Layer.effect(69+ RepoHost,70+ Effect.gen(function* () {71+ const host = yield* RepoHost;72+ const under = yield* Ref.make(0);73+74+ const timed = <A, E>(75+ kind: "blobs" | "trees",76+ id: string,77+ read: Effect.Effect<A, E>78+ ) =>79+ Effect.gen(function* () {80+ const now = yield* Ref.updateAndGet(under, (count) => count + 1);81+82+ yield* Ref.update(seen, (was) => ({83+ ...was,84+ events: [...was.events, `+${id}`],85+ [kind]: was[kind] + 1,86+ peak: Math.max(was.peak, now),87+ }));88+89+ const wait = yield* Ref.get(delay);90+91+ if (Option.isSome(wait)) {92+ yield* Effect.sleep(wait.value(id));93+ }94+95+ return yield* read;96+ }).pipe(97+ Effect.ensuring(98+ Effect.andThen(99+ Ref.update(under, (count) => count - 1),100+ Ref.update(seen, (was) => ({101+ ...was,102+ events: [...was.events, `-${id}`],103+ }))104+ )105+ )106+ );107+108+ return RepoHost.of({109+ ...host,110+ readBlob: (name, id) => timed("blobs", id, host.readBlob(name, id)),111+ readTree: (name, id) => timed("trees", id, host.readTree(name, id)),112+ });113+ })114+ ).pipe(Layer.provide(RepoHostMemory));115+116+const landingOf = (sha: CommitSha, ask: string): LandingView => ({117+ ask: AskId.make(ask),118+ assisted: [],119+ author: Handle.make("bob"),120+ credits: [],121+ landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),122+ project,123+ sha: LandedSha.make(sha),124+});125+126+/** A project's record whose landings a test may add to, each batch asked for counted. */127+const recordOf = (head: CommitSha) =>128+ Effect.gen(function* () {129+ const landed = yield* Ref.make<readonly LandingView[]>([]);130+ const asked = yield* Ref.make(0);131+132+ const code: CodeProject = {133+ forks: Effect.succeed([]),134+ head: Effect.succeedSome(LandedSha.make(head)),135+ landings: (shas) =>136+ Effect.gen(function* () {137+ yield* Ref.update(asked, (count) => count + 1);138+139+ return (yield* Ref.get(landed)).filter(({ sha }) =>140+ shas.includes(sha)141+ );142+ }),143+ project,144+ repo,145+ };146+147+ return { asked, code, landed };148+ });149+150+/** histkit's tree: its README and `src/format.ts`. */151+const filesOf = (formatted: string, readme: string): Tree => [152+ ["README.md", text(readme)],153+ ["src/format.ts", text(formatted)],154+];155+156+/**157+ * histkit: `src/format.ts` grows over four commits (one leaves it alone),158+ * then two children of the fourth: `grown` inserts two lines and changes159+ * one, `still` changes only the README.160+ */161+const history = Effect.gen(function* () {162+ const git = yield* writer;163+164+ const c1 = yield* git.commit("Adopt", filesOf("a\nb\n", "# one\n"), [], 1);165+ const c2 = yield* git.commit("Readme", filesOf("a\nb\n", "# two\n"), [c1], 2);166+167+ const c3 = yield* git.commit(168+ "Land iso",169+ filesOf("a\niso\nb\n", "# two\n"),170+ [c2],171+ 3172+ );173+174+ const c4 = yield* git.commit(175+ "Land week",176+ filesOf("a\niso\nb\nweek\n", "# two\n"),177+ [c3],178+ 4179+ );180+181+ const grown = yield* git.commit(182+ "Land more",183+ filesOf("a\nx\ny\niso, changed\nb\nweek\n", "# two\n"),184+ [c4],185+ 5186+ );187+188+ const still = yield* git.commit(189+ "Readme again",190+ filesOf("a\niso\nb\nweek\n", "# three\n"),191+ [c4],192+ 6193+ );194+195+ yield* git.push(repo, [196+ ["refs/heads/main", grown],197+ ["refs/heads/still", still],198+ ]);199+200+ return { c1, c3, c4, grown, still };201+});202+203+/** `effect` on a fresh isolate: a code cache of its own. */204+const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>205+ Effect.provide(effect, CodeCacheLive(100));206+207+/** `effect` with a store of its own, empty: the whole walk, from nothing. */208+const fromNothing = <A, E, R>(effect: Effect.Effect<A, E, R>) =>209+ onIsolate(Effect.provide(effect, CodeStoreMemory));210+211+/** A view's ranges, the commits it names and where it stopped. */212+const whyOfView = (view: {213+ readonly ranges: readonly unknown[];214+ readonly commits: readonly { readonly sha: CommitSha }[];215+ readonly stoppedAt?: CommitSha;216+}) => ({217+ commits: view.commits.map(({ sha }) => sha),218+ ranges: view.ranges,219+ stoppedAt: view.stoppedAt,220+});221+222+/** A test body over the counting host and one store every isolate shares. */223+const within = <A, E>(224+ body: (counts: {225+ readonly seen: Ref.Ref<Seen>;226+ readonly delay: Ref.Ref<Delay>;227+ }) => Effect.Effect<A, E, RepoHost | CodeStoreCounts>228+) =>229+ Effect.gen(function* () {230+ const seen = yield* Ref.make(none);231+ const delay = yield* Ref.make<Delay>(Option.none());232+233+ return yield* body({ delay, seen }).pipe(234+ Effect.provide(Layer.merge(counted(seen, delay), CodeStoreMemory))235+ );236+ });237+238+const long = { timeout: 30_000 };239+240+describe("code history kept across isolates", () => {241+ it.effect(242+ "reads a why another isolate computed without a tree or a blob, asking only for its landings",243+ () =>244+ within(({ seen }) =>245+ Effect.gen(function* () {246+ const { grown } = yield* history;247+ const { asked, code } = yield* recordOf(grown);248+ const first = yield* onIsolate(whyOf(code, Option.none(), format));249+250+ yield* Ref.set(seen, none);251+ yield* Ref.set(asked, 0);252+253+ const again = yield* onIsolate(whyOf(code, Option.none(), format));254+255+ expect(again).toStrictEqual(first);256+ expect(yield* Ref.get(seen)).toStrictEqual(none);257+ expect(yield* Ref.get(asked)).toBe(1);258+ })259+ )260+ );261+262+ it.effect(263+ "reads a path's log page another isolate computed without a tree or a blob",264+ () =>265+ within(({ seen }) =>266+ Effect.gen(function* () {267+ const { grown } = yield* history;268+ const { code } = yield* recordOf(grown);269+270+ const page = {271+ at: Option.none(),272+ from: 0,273+ limit: 2,274+ path: Option.some(format),275+ };276+277+ const first = yield* onIsolate(logOf(code, page));278+279+ yield* Ref.set(seen, none);280+281+ const again = yield* onIsolate(logOf(code, page));282+283+ expect(again).toStrictEqual(first);284+ expect(first.commits).toHaveLength(2);285+ expect(yield* Ref.get(seen)).toStrictEqual(none);286+ })287+ )288+ );289+});290+291+/** The first page of `src/format.ts`'s log from `from`. */292+const formatLog = (from: CommitSha) => ({293+ at: Option.some(from),294+ from: 0,295+ limit: 30,296+ path: Option.some(format),297+});298+299+describe("code history one landing past a kept result", () => {300+ it.effect(301+ "reads only the two versions' blobs for a why, and agrees with the whole walk",302+ () =>303+ within(({ seen }) =>304+ Effect.gen(function* () {305+ const { c4, grown } = yield* history;306+ const { code } = yield* recordOf(grown);307+308+ yield* onIsolate(whyOf(code, Option.some(c4), format));309+ yield* Ref.set(seen, none);310+311+ const next = yield* onIsolate(312+ whyOf(code, Option.some(grown), format)313+ );314+315+ const counts = yield* Ref.get(seen);316+ const whole = yield* fromNothing(whyOf(code, Option.none(), format));317+318+ expect(counts.blobs).toBeLessThanOrEqual(2);319+ expect(whyOfView(next)).toStrictEqual(whyOfView(whole));320+ expect(whyOfView(next).commits).toContain(grown);321+ })322+ )323+ );324+325+ it.effect(326+ "reads no blob for a why when the landing left the file alone",327+ () =>328+ within(({ seen }) =>329+ Effect.gen(function* () {330+ const { c4, grown, still } = yield* history;331+ const { code } = yield* recordOf(grown);332+ const kept = yield* onIsolate(whyOf(code, Option.some(c4), format));333+334+ yield* Ref.set(seen, none);335+336+ const next = yield* onIsolate(337+ whyOf(code, Option.some(still), format)338+ );339+340+ expect((yield* Ref.get(seen)).blobs).toBe(0);341+ expect(whyOfView(next)).toStrictEqual(whyOfView(kept));342+ expect(next.at).toBe(still);343+ })344+ )345+ );346+347+ it.effect(348+ "reads only the new commits' entries for a path's log, and agrees with the whole scan",349+ () =>350+ within(({ seen }) =>351+ Effect.gen(function* () {352+ const { c4, grown } = yield* history;353+ const { code } = yield* recordOf(grown);354+355+ yield* onIsolate(logOf(code, formatLog(c4)));356+ yield* Ref.set(seen, none);357+358+ const next = yield* onIsolate(logOf(code, formatLog(grown)));359+ const counts = yield* Ref.get(seen);360+ const whole = yield* fromNothing(logOf(code, formatLog(grown)));361+362+ // `src/format.ts` two folders down, in `grown` and in `c4`.363+ expect(counts.trees).toBeLessThanOrEqual(4);364+ expect(next).toStrictEqual(whole);365+ expect(next.commits.map(({ sha }) => sha)[0]).toBe(grown);366+ })367+ )368+ );369+});370+371+describe("landings beside kept history", () => {372+ it.effect("show on the next view once the record has them", () =>373+ within(() =>374+ Effect.gen(function* () {375+ const { c1, grown } = yield* history;376+ const { code, landed } = yield* recordOf(grown);377+378+ // One isolate, so the second view finds the first's history kept.379+ const [before, after] = yield* onIsolate(380+ Effect.gen(function* () {381+ const first = yield* whyOf(code, Option.none(), format);382+383+ yield* Ref.set(landed, [landingOf(c1, "adopt")]);384+385+ return [first, yield* whyOf(code, Option.none(), format)] as const;386+ })387+ );388+389+ expect(before.landings).toStrictEqual([]);390+ expect(after.landings.map(({ ask, sha }) => [sha, ask])).toStrictEqual([391+ [c1, "adopt"],392+ ]);393+ })394+ )395+ );396+});397+398+/**399+ * `count` commits: each changes `count.txt` at the root and leaves400+ * `a/b/c/d/deep.txt` alone, so the commits' root trees all differ and the401+ * folders under them never do.402+ */403+const deepHistory = (count: number) =>404+ Effect.gen(function* () {405+ const git = yield* writer;406+ const shas: CommitSha[] = [];407+408+ for (let at = 1; at <= count; at += 1) {409+ shas.push(410+ yield* git.commit(411+ `Commit ${at}`,412+ [413+ ["a/b/c/d/deep.txt", text("deep\n")],414+ ["count.txt", text(`${at}\n`)],415+ ],416+ shas.slice(-1),417+ at418+ )419+ );420+ }421+422+ const head = shas.at(-1);423+424+ if (head === undefined) {425+ return yield* Effect.die("no commits");426+ }427+428+ yield* git.push(repo, [["refs/heads/main", head]]);429+430+ return { head, shas };431+ });432+433+describe("a cold walk", () => {434+ it.live(435+ "keeps at least 40 reads under way when each takes 50 ms",436+ () =>437+ within(({ delay, seen }) =>438+ Effect.gen(function* () {439+ const { head, shas } = yield* deepHistory(64);440+ const { code } = yield* recordOf(head);441+442+ yield* Ref.set(seen, none);443+ yield* Ref.set(444+ delay,445+ Option.some(() => Duration.millis(50))446+ );447+448+ const view = yield* whyOf(449+ code,450+ Option.none(),451+ RepoPath.make("a/b/c/d/deep.txt")452+ );453+454+ expect(view.ranges).toStrictEqual([455+ { end: 1, sha: shas[0], start: 1 },456+ ]);457+ expect((yield* Ref.get(seen)).peak).toBeGreaterThanOrEqual(40);458+ })459+ ),460+ long461+ );462+463+ // Counted, not timed: a batch of 16 waits for its slowest read, so while464+ // one commit's folder takes a second, at most its 15 neighbours finish;465+ // with no barrier, every other commit does. Wall time under a loaded466+ // machine says less than this count (the walk took about a quarter of467+ // the batched walk's 1,250 ms when each read took 50 ms).468+ it.live(469+ "goes on past a slow read: every other commit's folder is read while one takes a second",470+ () =>471+ within(({ delay, seen }) =>472+ Effect.gen(function* () {473+ const { head, shas } = yield* deepHistory(64);474+ const { code } = yield* recordOf(head);475+476+ const roots = yield* Effect.forEach(shas, (sha) =>477+ RepoHost.use((host) => host.readCommit(repo, sha)).pipe(478+ Effect.flatMap(Effect.fromOption),479+ Effect.map(({ tree }) => tree),480+ Effect.orDie481+ )482+ );483+484+ // The commit after the head: the first the pass looks up.485+ const slow = roots[62] ?? "";486+487+ yield* Ref.set(seen, none);488+ yield* Ref.set(489+ delay,490+ Option.some((id) => Duration.millis(id === slow ? 1000 : 10))491+ );492+493+ yield* whyOf(code, Option.none(), RepoPath.make("a/b/c/d/deep.txt"));494+495+ const { events } = yield* Ref.get(seen);496+497+ const during = events.slice(498+ events.indexOf(`+${slow}`),499+ events.indexOf(`-${slow}`)500+ );501+502+ const others = new Set(roots.slice(0, 62).map((tree) => `-${tree}`));503+504+ expect(505+ during.filter((event) => others.has(event)).length506+ ).toBeGreaterThanOrEqual(60);507+ })508+ ),509+ long510+ );511+512+ it.effect(513+ "looks each commit's entry up once in a path's log",514+ () =>515+ within(({ seen }) =>516+ Effect.gen(function* () {517+ const { head } = yield* deepHistory(200);518+ const { code } = yield* recordOf(head);519+520+ yield* Ref.set(seen, none);521+522+ const { commits } = yield* logOf(code, {523+ at: Option.none(),524+ from: 0,525+ limit: 30,526+ path: Option.some(RepoPath.make("count.txt")),527+ });528+529+ expect(commits).toHaveLength(30);530+ // Each commit's root tree read once from the store. The view531+ // shares a tree read under way among its fibers, so this count532+ // holds the store's reads, not how often the walk asked.533+ expect((yield* Ref.get(seen)).trees).toBe(200);534+ })535+ ),536+ long537+ );538+});539+540+describe("a kept value that no longer decodes", () => {541+ it.effect("is computed again and replaced", () =>542+ within(({ seen }) =>543+ Effect.gen(function* () {544+ const { grown } = yield* history;545+ const { code } = yield* recordOf(grown);546+ const store = yield* CodeStore;547+548+ const key = yield* keyOf(whyKept, {549+ commit: grown,550+ path: format,551+ repo,552+ scan: WHY_SCAN,553+ });554+555+ yield* store.put(key, '{"blob":"not an id"}');556+557+ const view = yield* onIsolate(whyOf(code, Option.none(), format));558+ const replaced = yield* store.get(key);559+560+ expect((yield* Ref.get(seen)).blobs).toBeGreaterThan(0);561+ expect(view.ranges.length).toBeGreaterThan(0);562+ expect(563+ Option.flatMap(564+ replaced,565+ Schema.decodeUnknownOption(Schema.fromJsonString(StoredWhy))566+ ).pipe(Option.map(({ ranges }) => ranges))567+ ).toStrictEqual(Option.some(view.ranges));568+ expect(569+ (yield* CodeStoreCounts.use(({ counts }) => counts)).puts570+ ).toBeGreaterThanOrEqual(2);571+ })572+ )573+ );574+});575+576+/**577+ * The memory store, the session each commit, tree, blob and log read ran578+ * in noted in `sessions`, in order.579+ */580+const sessioned = (581+ sessions: Ref.Ref<readonly Option.Option<RepoSessionApi>[]>582+) => {583+ const noted = <A, E>(read: Effect.Effect<A, E>) =>584+ Effect.flatMap(RepoSession, (session) =>585+ Effect.andThen(586+ Ref.update(sessions, (was) => [...was, session]),587+ read588+ )589+ );590+591+ return Layer.effect(592+ RepoHost,593+ Effect.gen(function* () {594+ const host = yield* RepoHost;595+596+ return RepoHost.of({597+ ...host,598+ log: (name, at, limit, offset) =>599+ noted(host.log(name, at, limit, offset)),600+ readBlob: (name, id) => noted(host.readBlob(name, id)),601+ readCommit: (name, sha) => noted(host.readCommit(name, sha)),602+ readTree: (name, id) => noted(host.readTree(name, id)),603+ });604+ })605+ ).pipe(Layer.provide(RepoHostMemory));606+};607+608+/** How many sessions `sessions` names, and whether a read ran in none. */609+const sessionsIn = (sessions: readonly Option.Option<RepoSessionApi>[]) => ({610+ outside: sessions.some(Option.isNone),611+ sessions: new Set(sessions.flatMap(Option.toArray)).size,612+});613+614+describe("one view's reads", () => {615+ it.effect("of a cold why all run in one session", () =>616+ Effect.gen(function* () {617+ const sessions = yield* Ref.make<618+ readonly Option.Option<RepoSessionApi>[]619+ >([]);620+621+ yield* Effect.gen(function* () {622+ const { grown } = yield* history;623+ const { code } = yield* recordOf(grown);624+625+ yield* Ref.set(sessions, []);626+ yield* onIsolate(whyOf(code, Option.none(), format));627+ }).pipe(628+ Effect.provide(Layer.merge(sessioned(sessions), CodeStoreMemory))629+ );630+631+ expect(sessionsIn(yield* Ref.get(sessions))).toStrictEqual({632+ outside: false,633+ sessions: 1,634+ });635+ })636+ );637+638+ it.effect("of a cold path's log page all run in one session", () =>639+ Effect.gen(function* () {640+ const sessions = yield* Ref.make<641+ readonly Option.Option<RepoSessionApi>[]642+ >([]);643+644+ yield* Effect.gen(function* () {645+ const { grown } = yield* history;646+ const { code } = yield* recordOf(grown);647+648+ yield* Ref.set(sessions, []);649+ yield* onIsolate(logOf(code, formatLog(grown)));650+ }).pipe(651+ Effect.provide(Layer.merge(sessioned(sessions), CodeStoreMemory))652+ );653+654+ expect(sessionsIn(yield* Ref.get(sessions))).toStrictEqual({655+ outside: false,656+ sessions: 1,657+ });658+ })659+ );660+});661+662+describe("kept history in the isolate's cache", () => {663+ it.effect(664+ "is kept with the heavy reads: a why's ranges grow with its file",665+ () =>666+ within(() =>667+ Effect.gen(function* () {668+ const { grown } = yield* history;669+ const { code } = yield* recordOf(grown);670+671+ const seen = yield* Ref.make<readonly (readonly [string, boolean])[]>(672+ []673+ );674+675+ const spy: CodeReads = {676+ through: (key, read, keeping = {}) =>677+ Effect.andThen(678+ Ref.update(seen, (was) => [679+ ...was,680+ [key, keeping.heavy === true] as const,681+ ]),682+ read683+ ),684+ };685+686+ yield* Effect.all([687+ whyOf(code, Option.none(), format),688+ logOf(code, formatLog(grown)),689+ ]).pipe(Effect.provideService(CodeCache, spy));690+691+ const kept = (yield* Ref.get(seen)).filter(([key]) =>692+ /\/(?:why|path-log)\/v\d+\//u.test(key)693+ );694+695+ expect(kept.length).toBeGreaterThan(0);696+ expect(kept.filter(([, heavy]) => !heavy)).toStrictEqual([]);697+ })698+ )699+ );700+});modified:packages/project/test/code-why.test.ts+7 added-4 removed
23 unmodified lines24 25 import { whyOf } from "../src/code.ts";26 import type { CodeProject } from "../src/code.ts";27 import { CodeCacheLive } from "../src/code/cache.ts";28+import { READS_AT_ONCE } from "../src/code/tree.ts";29 import { whyView } from "../src/code/why.ts";30 import {31 Content,32 growingHistory,249 unmodified lines282 283 expect(ranges).toStrictEqual([{ end: 1, sha: shas[0], start: 1 }]);284 }).pipe(Effect.provide(overlappingTrees(reading, peak)));285 286+ // `READS_AT_ONCE` lookups under way, and the head's own beside them.285- expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(8);286- expect(yield* Ref.get(peak)).toBeLessThanOrEqual(16);287+ expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);288+ expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE + 1);289 }),290 { timeout: 30_000 }291 );292 21 unmodified lines314 shas.map((sha, at) => ({ end: at + 1, sha, start: at + 1 }))315 );316 }).pipe(Effect.provide(overlappingTrees(reading, peak, "blob")));317 318+ // `READS_AT_ONCE` lookups under way, and the head's own beside them.316- expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(8);317- expect(yield* Ref.get(peak)).toBeLessThanOrEqual(16);319+ expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);320+ expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE + 1);321 }),322 { timeout: 30_000 }323 );324 30 unmodified linesmodified:packages/project/test/code.test.ts+5 added-4 removed
28 unmodified lines29 } from "../src/code.ts";30 import { CodeCache, CodeCacheLive } from "../src/code/cache.ts";31 import { filesUnder } from "../src/code/paths.ts";32 import { compareTags } from "../src/code/refs.ts";33+import { READS_AT_ONCE } from "../src/code/tree.ts";34 import {35 big,36 datekit,37 fork,417 unmodified lines455 456 expect(commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);457 }).pipe(Effect.provide(overlappingTrees(reading, peak)));458 458- // 64 commits, two trees each: one at a time a live store took a459- // minute for 200; sixteen commits at once, each its two trees.460- expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(8);461- expect(yield* Ref.get(peak)).toBeLessThanOrEqual(32);459+ // 64 commits, each its one root tree: one at a time a live store460+ // took a minute for 200; `READS_AT_ONCE` commits at once now.461+ expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);462+ expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE);463 }),464 long465 );466 });175 unmodified linesmodified:packages/testkit/src/fake-artifacts-binding.ts+34 added-6 removed
7 unmodified lines8 * - under load, a fork answers HTTP 500 after making the repo, and the retry9 * answers 409: pass `{ forkFailures: n }`;10 * - reads by ref resolve short branch names and commit ids only, never11 * `refs/heads/main`;12- * - `info().lastPushAt` stays `null` after pushes.12+ * - `info().lastPushAt` stays `null` after pushes;13+ * - past 2,000 requests per 10 s a repo's reads are refused as rate limited:14+ * pass `{ rateLimited: n }` to refuse the next `n` reads (ASSUMPTION: the15+ * refusal names the limit in its message, as an HTTP 429's "Too Many16+ * Requests" does; no live one has been seen yet).17 *18 * It takes its host structurally (`HostLike`), so `@repo/testkit` depends on19 * no adapter package: a `RepoHost` service value satisfies `HostLike`. Each20 * call runs the host's Effect with `Effect.runPromise`, since the binding is160 unmodified lines181 * `IMPORT_IN_PROGRESS`: an import Artifacts is still copying after182 * `import()` returned, as a large one is.183 */184 readonly importing?: number;185+ /** How many of the next reads (a blob, a tree, a commit, a log) are refused as rate limited. */186+ readonly rateLimited?: number;187 }188 189 /** A refusal the binding throws, before it becomes the thrown error. */190 class Refused extends Data.TaggedError("Refused")<{132 unmodified lines323 options: FakeOptions = {}324 ): Artifacts => {325 const kept = new Map<RepoName, Kept>();326 let forkFailures = options.forkFailures ?? 0;327+ let rateLimited = options.rateLimited ?? 0;328 let made = 0;329 // Each imported repo's `get`s still to answer that the import runs on.330 const importing = new Map<RepoName, number>();331 12 unmodified lines344 Effect.runPromise(345 Effect.mapError(effect, (failure) => thrown(refusalOf(failure)))346 );347 348+ /** What a read past the rate limit throws (see the module's doc). */349+ const limited = () =>350+ options.codeless === true351+ ? new Error("ArtifactsError: Too many requests: rate limit exceeded")352+ : Object.assign(new Error("Too many requests: rate limit exceeded"), {353+ code: "RATE_LIMITED",354+ name: "ArtifactsError" as const,355+ numericCode: 0,356+ });357+358+ /** One read, refused while the scripted rate limit lasts. */359+ const read = <A>(effect: Effect.Effect<A, Refused | HostError>) => {360+ if (rateLimited > 0) {361+ rateLimited -= 1;362+363+ return Promise.reject(limited());364+ }365+366+ return run(effect);367+ };368+369 const remoteOf = (name: RepoName) =>370 options.remoteBase === undefined371 ? host.remote(name)372 : host.remote(name).pipe(Effect.as(`${options.remoteBase}/${name}.git`));149 unmodified lines522 })523 )524 ),525 log: (logOptions) =>498- run(526+ read(527 Effect.gen(function* () {528 const ref = logOptions?.ref ?? "HEAD";529 const limit = Math.min(logOptions?.limit ?? 50, 1000);530 const offset = logOptions?.offset ?? 0;12 unmodified lines543 return commits.slice(offset).map(metadataOf);544 })545 ),546 readBlob: (hash) =>519- run(547+ read(548 objectId(hash).pipe(549 Effect.flatMap((blob) => host.readBlob(name, blob)),550 Effect.map((bytes) => Option.getOrNull(Option.map(bytes, blobOf)))551 )552 ),553 readCommit: (hash) =>526- run(554+ read(555 objectId(hash).pipe(556 Effect.flatMap((sha) => host.readCommit(name, CommitSha.make(sha))),557 Effect.map((commit) =>558 Option.getOrNull(Option.map(commit, metadataOf))559 )560 )561 ),562 readFile: ({ path, ref }) =>535- run(563+ read(564 Effect.gen(function* () {565 const file = decodePath(path);566 const at = revisionOf(ref);567 13 unmodified lines581 return Option.getOrNull(Option.map(bytes, blobOf));582 })583 ),584 readTree: (hash) =>557- run(585+ read(586 objectId(hash).pipe(587 Effect.flatMap((tree) => host.readTree(name, tree)),588 Effect.map((entries) =>589 Option.getOrNull(Option.map(entries, (each) => each.map(entryOf)))128 unmodified lines