Keep why and a path's log by commit id in the code store, carry them forward from a kept ancestor, and walk without batch barriers
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- New code/history.ts: StoredWhy {blob, ranges, shas, stoppedAt?} and StoredPathLog {shas, reachedRoot} under <repo>/<kind>/v<version>/<commit>/<scan>/<sha256(path)> (WHY_VERSION 1, LOG_VERSION 1, INCREMENT_REACH 16, all in the header). Read order: the isolate's CodeCache, then CodeStore, then compute; a computed value goes into both; a value that fails to decode is a miss and is replaced. main and tags resolve first; only the canonical repo is keyed. Landings and texts are never kept: each why view reads its commits by id and asks the record for their landings in one batch, so a later landing shows at once. - Incremental: a why with one kept at a first-parent ancestor within 16 commits carries its ranges forward through each changed version (one line diff each; inserted lines go to the commit that made them; stoppedAt kept only while a line still names it), and reads no blob when the file did not change. A path's log is the ancestor's list plus the commits between that changed the path, cut to the scan. A file missing in a commit between falls back to the whole walk. - Cold walks: READS_AT_ONCE 48 (from 16). The why's blob lookups are one Effect.forEach with no barrier (a slow lookup holds up only itself; lookups past the file's birth are skipped), the head's blob and text read beside them. Stream.mapEffect's ordered output stalls behind a slow head after 48 elements, so it is kept only for the older texts, where stopping once every line is settled matters. The path log looks each commit's entry up once and compares neighbours (half the reads), and always scans its 200 commits so the kept history is whole; pages and `next` are cut from it as before. - asOneView (cache.ts): within one view a light read another of its fibers began is joined, not read again (a four-deep path's shared folders are read once), held only in the view's scope (no isolate state, no pending read outliving the request). - RepoSession and inRepoSession in the RepoHost port: reads in a session share what the host opens per repo. The binding adapter holds one handle per repo for the session (opened one at a time, finished handles only, disposed when the session ends); outside one, a handle per read as before. Other adapters ignore it. - The binding asks a rate-limited call again from 250 ms, doubling, at most four more times; past that the read dies and the view answers its error. ASSUMPTION: Artifacts' docs list no rate-limit code, so it is read from a code or message naming the limit or "too many requests"; 1009 records a live one. ASSUMPTION: binding.get is a round trip; 1009 times a cold why. - The fake Artifacts binding takes `rateLimited: n` to refuse the next n reads. - Tests: code-history.test.ts (a why and a path's log page read on a second isolate with no tree or blob read and one landings batch; one landing past a kept why reads at most two blobs and equals the whole walk, none when the file is unchanged; the path log past a kept one reads at most four trees and equals the whole scan; landings show on the next view; at 50 ms per read at least 40 under way; with one commit's folder taking a second, at least 60 of the other 62 finish meanwhile; a 200-commit path log reads each root tree once; a corrupt value is recomputed and replaced). binding.test.ts: one handle per session, disposed once; a rate-limited read retries and succeeds, and dies past four. code-why/code tests' concurrency bounds follow READS_AT_ONCE. A wall-time check was tried and dropped: about 320 ms of the batched 1,250 ms alone, but 513 ms under verify's load.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+1641 added−211 removed
- tests:+656 added−8 removed
- other:+985 added−203 removed
Provenance
- Commit
01199d6- Tree
c2dcdc6- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
51f046c
12 files changed+1641 added−211 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+74 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.272+ */273+export const inRepoSession = <A, E, R>(274+ effect: Effect.Effect<A, E, R>275+): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>276+ Effect.scoped(277+ Effect.gen(function* () {278+ const scope = yield* Effect.scope;279+ const opening = yield* Semaphore.make(1);280+ const held = new Map<string, unknown>();281+282+ const session: RepoSessionApi = {283+ hold: <B, F>(key: string, open: Effect.Effect<B, F, Scope.Scope>) =>284+ opening.withPermits(1)(285+ Effect.suspend(() => {286+ if (held.has(key)) {287+ // SAFETY: each key names one kind of value, which a caller288+ // opens with one effect, so what it holds is a `B`.289+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- one session holds every kind of value, so its map is typed `unknown`; see SAFETY.290+ return Effect.succeed(held.get(key) as B);291+ }292+293+ return Effect.tap(Scope.provide(open, scope), (value) =>294+ Effect.sync(() => {295+ held.set(key, value);296+ })297+ );298+ })299+ ),300+ };301+302+ return yield* Effect.provideService(303+ effect,304+ RepoSession,305+ Option.some(session)306+ );307+ })308+ );modified:packages/artifacts/test/binding.test.ts+73 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.effect("asks again after a rate-limited read, then reads", () =>1040+ within(1041+ () =>1042+ Effect.gen(function* () {1043+ const repos = yield* RepoHost;1044+ const name = RepoName.make("limited");1045+ const { first } = yield* seeded(name);1046+ const read = yield* onTestClock(repos.readCommit(name, first));1047+1048+ expect(1049+ Exit.map(1050+ read,1051+ Option.map(({ sha }) => sha)1052+ )1053+ ).toStrictEqual(Exit.succeed(Option.some(first)));1054+ }),1055+ { rateLimited: 3 }1056+ )1057+ );1058+1059+ it.effect(1060+ "fails the read once four asks after the first were all rate limited",1061+ () =>1062+ within(1063+ () =>1064+ Effect.gen(function* () {1065+ const repos = yield* RepoHost;1066+ const name = RepoName.make("throttled");1067+ const { first } = yield* seeded(name);1068+ const read = yield* onTestClock(repos.readCommit(name, first));1069+1070+ expect(Exit.hasDies(read)).toBeTruthy();1071+ }),1072+ { rateLimited: 5 }1073+ )1074+ );1075+});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+167 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`, then the `CodeStore`, then the20+ * walk; what a walk computed is put in both. A walk may start from what is21+ * kept at a first-parent ancestor at most `INCREMENT_REACH` commits back,22+ * so a new landing on main costs a handful of reads.23+ */24+import { WhyRange } from "@repo/protocol/domain/code";25+import { BlobSha, CommitSha } from "@repo/protocol/ids";26+import type { RepoName, RepoPath } from "@repo/protocol/ids";27+import { Effect, Option, Schema } from "effect";28+29+import { CodeStore } from "../code-store.ts";30+import { CodeCache } from "./cache.ts";31+32+/** The why walk's algorithm version, in its keys. */33+export const WHY_VERSION = 1;34+35+/** The path log's algorithm version, in its keys. */36+export const LOG_VERSION = 1;37+38+/** How many first-parent commits back a walk looks for a kept result to start from. */39+export const INCREMENT_REACH = 16;40+41+/**42+ * Why each line is there at a commit: the path's blob there, the ranges,43+ * the commits they name (newest first), and where the walk stopped.44+ */45+export const StoredWhy = Schema.Struct({46+ blob: BlobSha,47+ ranges: Schema.Array(WhyRange),48+ shas: Schema.Array(CommitSha),49+ stoppedAt: Schema.optionalKey(CommitSha),50+});51+52+export type StoredWhy = typeof StoredWhy.Type;53+54+/**55+ * A path's history from a commit: the first-parent commits of the scan56+ * that changed it, newest first, and whether the scan reached the root.57+ */58+export const StoredPathLog = Schema.Struct({59+ reachedRoot: Schema.Boolean,60+ shas: Schema.Array(CommitSha),61+});62+63+export type StoredPathLog = typeof StoredPathLog.Type;64+65+/** The lowercase hex SHA-256 of `text`. */66+const sha256 = (text: string) =>67+ Effect.map(68+ Effect.promise(() =>69+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))70+ ),71+ (digest) =>72+ [...new Uint8Array(digest)]73+ .map((byte) => byte.toString(16).padStart(2, "0"))74+ .join("")75+ );76+77+/** One kind of kept history: its key's kind and version, and its value. */78+export interface Kept<A> {79+ readonly kind: string;80+ readonly version: number;81+ readonly schema: Schema.Codec<A, unknown>;82+}83+84+export const whyKept: Kept<StoredWhy> = {85+ kind: "why",86+ schema: StoredWhy,87+ version: WHY_VERSION,88+};89+90+export const pathLogKept: Kept<StoredPathLog> = {91+ kind: "path-log",92+ schema: StoredPathLog,93+ version: LOG_VERSION,94+};95+96+/** Where `kept` is kept for `path` from `commit`, scanning `scan` commits. */97+export const keyOf = <A>(98+ kept: Kept<A>,99+ at: {100+ readonly repo: RepoName;101+ readonly commit: CommitSha;102+ readonly scan: number;103+ readonly path: RepoPath;104+ }105+) =>106+ Effect.map(107+ sha256(at.path),108+ (hash) =>109+ `${at.repo}/${kept.kind}/v${kept.version}/${at.commit}/${at.scan}/${hash}`110+ );111+112+/**113+ * What is kept under `key`: the isolate's cache first, then the store. A114+ * miss is never cached, so a value another isolate keeps later is found.115+ */116+export const recall = <A>(117+ kept: Kept<A>,118+ key: string119+): Effect.Effect<Option.Option<A>> =>120+ Effect.gen(function* () {121+ const cache = yield* CodeCache;122+ const store = yield* CodeStore;123+124+ const decode = Schema.decodeUnknownOption(125+ Schema.fromJsonString(kept.schema)126+ );127+128+ return yield* cache.through(129+ key,130+ Effect.map(store.get(key), Option.flatMap(decode)),131+ { keep: Option.isSome }132+ );133+ });134+135+/** `value` kept under `key`, in the isolate's cache and in the store. */136+export const remember = <A>(137+ kept: Kept<A>,138+ key: string,139+ value: A140+): Effect.Effect<void> =>141+ Effect.gen(function* () {142+ const cache = yield* CodeCache;143+ const store = yield* CodeStore;144+145+ const encoded = yield* Schema.encodeEffect(146+ Schema.fromJsonString(kept.schema)147+ )(value).pipe(Effect.orDie);148+149+ yield* store.put(key, encoded);150+ yield* cache.through(key, Effect.succeedSome(value), {});151+ });152+153+/**154+ * What is kept under `key`, else `compute` run and its value kept: a155+ * failure is never kept.156+ */157+export const throughHistory = <A, E, R>(158+ kept: Kept<A>,159+ key: string,160+ compute: Effect.Effect<A, E, R>161+): Effect.Effect<A, E, R> =>162+ Effect.flatMap(recall(kept, key), (found) =>163+ Option.match(found, {164+ onNone: () => Effect.tap(compute, (value) => remember(kept, key, value)),165+ onSome: Effect.succeed,166+ })167+ );modified:packages/project/src/code/log.ts+156 added-54 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 */19 import { Revision, RepoHost } from "@repo/artifacts/repo-host";20 import type {21 Commit,8 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 );1 unmodified linemodified: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+402 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+ // The commits it names are read through one session, as the walk's are.518+ return yield* inRepoSession(viewOf(project, commit, path, kept));519+ }).pipe(Effect.catchTag("RepoNotFound", Effect.die));added:packages/project/test/code-history.test.ts+571 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 } from "@repo/artifacts/repo-host";13+import { RepoHostMemory } from "@repo/artifacts/repo-host/memory";14+import type { LandingView } from "@repo/protocol/domain/landing";15+import {16+ AskId,17+ Handle,18+ LandedSha,19+ ProjectName,20+ RepoName,21+ RepoPath,22+} from "@repo/protocol/ids";23+import type { CommitSha } from "@repo/protocol/ids";24+import { DateTime, Duration, Effect, Layer, Option, Ref, Schema } from "effect";25+26+import { CodeStore } from "../src/code-store.ts";27+import { CodeStoreCounts, CodeStoreMemory } from "../src/code-store/memory.ts";28+import { logOf, whyOf } from "../src/code.ts";29+import type { CodeProject } from "../src/code.ts";30+import { CodeCacheLive } from "../src/code/cache.ts";31+import { keyOf, StoredWhy, whyKept } from "../src/code/history.ts";32+import { WHY_SCAN } from "../src/code/why.ts";33+import { Content, writer } from "./code-fixtures.ts";34+import type { Tree } from "./code-fixtures.ts";35+36+const project = ProjectName.make("histkit");37+38+const repo = RepoName.make(project);39+40+const format = RepoPath.make("src/format.ts");41+42+const text = (value: string) => Content.Text({ text: value });43+44+/**45+ * What the counting host saw: trees and blobs read, the most under way at46+ * once, and each read's start (`+<id>`) and end (`-<id>`) in order.47+ */48+interface Seen {49+ readonly trees: number;50+ readonly blobs: number;51+ readonly peak: number;52+ readonly events: readonly string[];53+}54+55+const none: Seen = { blobs: 0, events: [], peak: 0, trees: 0 };56+57+/** How long a read of the object `id` takes, once a test sets it. */58+type Delay = Option.Option<(id: string) => Duration.Duration>;59+60+/**61+ * The memory store, each tree and blob read counted in `seen` and, once62+ * `delay` is set, taking as long as it says: a live store answers each63+ * read in tens to hundreds of milliseconds.64+ */65+const counted = (seen: Ref.Ref<Seen>, delay: Ref.Ref<Delay>) =>66+ Layer.effect(67+ RepoHost,68+ Effect.gen(function* () {69+ const host = yield* RepoHost;70+ const under = yield* Ref.make(0);71+72+ const timed = <A, E>(73+ kind: "blobs" | "trees",74+ id: string,75+ read: Effect.Effect<A, E>76+ ) =>77+ Effect.gen(function* () {78+ const now = yield* Ref.updateAndGet(under, (count) => count + 1);79+80+ yield* Ref.update(seen, (was) => ({81+ ...was,82+ events: [...was.events, `+${id}`],83+ [kind]: was[kind] + 1,84+ peak: Math.max(was.peak, now),85+ }));86+87+ const wait = yield* Ref.get(delay);88+89+ if (Option.isSome(wait)) {90+ yield* Effect.sleep(wait.value(id));91+ }92+93+ return yield* read;94+ }).pipe(95+ Effect.ensuring(96+ Effect.andThen(97+ Ref.update(under, (count) => count - 1),98+ Ref.update(seen, (was) => ({99+ ...was,100+ events: [...was.events, `-${id}`],101+ }))102+ )103+ )104+ );105+106+ return RepoHost.of({107+ ...host,108+ readBlob: (name, id) => timed("blobs", id, host.readBlob(name, id)),109+ readTree: (name, id) => timed("trees", id, host.readTree(name, id)),110+ });111+ })112+ ).pipe(Layer.provide(RepoHostMemory));113+114+const landingOf = (sha: CommitSha, ask: string): LandingView => ({115+ ask: AskId.make(ask),116+ assisted: [],117+ author: Handle.make("bob"),118+ credits: [],119+ landedAt: DateTime.makeUnsafe("2026-10-07T12:00:00Z"),120+ project,121+ sha: LandedSha.make(sha),122+});123+124+/** A project's record whose landings a test may add to, each batch asked for counted. */125+const recordOf = (head: CommitSha) =>126+ Effect.gen(function* () {127+ const landed = yield* Ref.make<readonly LandingView[]>([]);128+ const asked = yield* Ref.make(0);129+130+ const code: CodeProject = {131+ forks: Effect.succeed([]),132+ head: Effect.succeedSome(LandedSha.make(head)),133+ landings: (shas) =>134+ Effect.gen(function* () {135+ yield* Ref.update(asked, (count) => count + 1);136+137+ return (yield* Ref.get(landed)).filter(({ sha }) =>138+ shas.includes(sha)139+ );140+ }),141+ project,142+ repo,143+ };144+145+ return { asked, code, landed };146+ });147+148+/** histkit's tree: its README and `src/format.ts`. */149+const filesOf = (formatted: string, readme: string): Tree => [150+ ["README.md", text(readme)],151+ ["src/format.ts", text(formatted)],152+];153+154+/**155+ * histkit: `src/format.ts` grows over four commits (one leaves it alone),156+ * then two children of the fourth: `grown` inserts two lines and changes157+ * one, `still` changes only the README.158+ */159+const history = Effect.gen(function* () {160+ const git = yield* writer;161+162+ const c1 = yield* git.commit("Adopt", filesOf("a\nb\n", "# one\n"), [], 1);163+ const c2 = yield* git.commit("Readme", filesOf("a\nb\n", "# two\n"), [c1], 2);164+165+ const c3 = yield* git.commit(166+ "Land iso",167+ filesOf("a\niso\nb\n", "# two\n"),168+ [c2],169+ 3170+ );171+172+ const c4 = yield* git.commit(173+ "Land week",174+ filesOf("a\niso\nb\nweek\n", "# two\n"),175+ [c3],176+ 4177+ );178+179+ const grown = yield* git.commit(180+ "Land more",181+ filesOf("a\nx\ny\niso, changed\nb\nweek\n", "# two\n"),182+ [c4],183+ 5184+ );185+186+ const still = yield* git.commit(187+ "Readme again",188+ filesOf("a\niso\nb\nweek\n", "# three\n"),189+ [c4],190+ 6191+ );192+193+ yield* git.push(repo, [194+ ["refs/heads/main", grown],195+ ["refs/heads/still", still],196+ ]);197+198+ return { c1, c3, c4, grown, still };199+});200+201+/** `effect` on a fresh isolate: a code cache of its own. */202+const onIsolate = <A, E, R>(effect: Effect.Effect<A, E, R>) =>203+ Effect.provide(effect, CodeCacheLive(100));204+205+/** `effect` with a store of its own, empty: the whole walk, from nothing. */206+const fromNothing = <A, E, R>(effect: Effect.Effect<A, E, R>) =>207+ onIsolate(Effect.provide(effect, CodeStoreMemory));208+209+/** A view's ranges, the commits it names and where it stopped. */210+const whyOfView = (view: {211+ readonly ranges: readonly unknown[];212+ readonly commits: readonly { readonly sha: CommitSha }[];213+ readonly stoppedAt?: CommitSha;214+}) => ({215+ commits: view.commits.map(({ sha }) => sha),216+ ranges: view.ranges,217+ stoppedAt: view.stoppedAt,218+});219+220+/** A test body over the counting host and one store every isolate shares. */221+const within = <A, E>(222+ body: (counts: {223+ readonly seen: Ref.Ref<Seen>;224+ readonly delay: Ref.Ref<Delay>;225+ }) => Effect.Effect<A, E, RepoHost | CodeStoreCounts>226+) =>227+ Effect.gen(function* () {228+ const seen = yield* Ref.make(none);229+ const delay = yield* Ref.make<Delay>(Option.none());230+231+ return yield* body({ delay, seen }).pipe(232+ Effect.provide(Layer.merge(counted(seen, delay), CodeStoreMemory))233+ );234+ });235+236+const long = { timeout: 30_000 };237+238+describe("code history kept across isolates", () => {239+ it.effect(240+ "reads a why another isolate computed without a tree or a blob, asking only for its landings",241+ () =>242+ within(({ seen }) =>243+ Effect.gen(function* () {244+ const { grown } = yield* history;245+ const { asked, code } = yield* recordOf(grown);246+ const first = yield* onIsolate(whyOf(code, Option.none(), format));247+248+ yield* Ref.set(seen, none);249+ yield* Ref.set(asked, 0);250+251+ const again = yield* onIsolate(whyOf(code, Option.none(), format));252+253+ expect(again).toStrictEqual(first);254+ expect(yield* Ref.get(seen)).toStrictEqual(none);255+ expect(yield* Ref.get(asked)).toBe(1);256+ })257+ )258+ );259+260+ it.effect(261+ "reads a path's log page another isolate computed without a tree or a blob",262+ () =>263+ within(({ seen }) =>264+ Effect.gen(function* () {265+ const { grown } = yield* history;266+ const { code } = yield* recordOf(grown);267+268+ const page = {269+ at: Option.none(),270+ from: 0,271+ limit: 2,272+ path: Option.some(format),273+ };274+275+ const first = yield* onIsolate(logOf(code, page));276+277+ yield* Ref.set(seen, none);278+279+ const again = yield* onIsolate(logOf(code, page));280+281+ expect(again).toStrictEqual(first);282+ expect(first.commits).toHaveLength(2);283+ expect(yield* Ref.get(seen)).toStrictEqual(none);284+ })285+ )286+ );287+});288+289+/** The first page of `src/format.ts`'s log from `from`. */290+const formatLog = (from: CommitSha) => ({291+ at: Option.some(from),292+ from: 0,293+ limit: 30,294+ path: Option.some(format),295+});296+297+describe("code history one landing past a kept result", () => {298+ it.effect(299+ "reads only the two versions' blobs for a why, and agrees with the whole walk",300+ () =>301+ within(({ seen }) =>302+ Effect.gen(function* () {303+ const { c4, grown } = yield* history;304+ const { code } = yield* recordOf(grown);305+306+ yield* onIsolate(whyOf(code, Option.some(c4), format));307+ yield* Ref.set(seen, none);308+309+ const next = yield* onIsolate(310+ whyOf(code, Option.some(grown), format)311+ );312+313+ const counts = yield* Ref.get(seen);314+ const whole = yield* fromNothing(whyOf(code, Option.none(), format));315+316+ expect(counts.blobs).toBeLessThanOrEqual(2);317+ expect(whyOfView(next)).toStrictEqual(whyOfView(whole));318+ expect(whyOfView(next).commits).toContain(grown);319+ })320+ )321+ );322+323+ it.effect(324+ "reads no blob for a why when the landing left the file alone",325+ () =>326+ within(({ seen }) =>327+ Effect.gen(function* () {328+ const { c4, grown, still } = yield* history;329+ const { code } = yield* recordOf(grown);330+ const kept = yield* onIsolate(whyOf(code, Option.some(c4), format));331+332+ yield* Ref.set(seen, none);333+334+ const next = yield* onIsolate(335+ whyOf(code, Option.some(still), format)336+ );337+338+ expect((yield* Ref.get(seen)).blobs).toBe(0);339+ expect(whyOfView(next)).toStrictEqual(whyOfView(kept));340+ expect(next.at).toBe(still);341+ })342+ )343+ );344+345+ it.effect(346+ "reads only the new commits' entries for a path's log, and agrees with the whole scan",347+ () =>348+ within(({ seen }) =>349+ Effect.gen(function* () {350+ const { c4, grown } = yield* history;351+ const { code } = yield* recordOf(grown);352+353+ yield* onIsolate(logOf(code, formatLog(c4)));354+ yield* Ref.set(seen, none);355+356+ const next = yield* onIsolate(logOf(code, formatLog(grown)));357+ const counts = yield* Ref.get(seen);358+ const whole = yield* fromNothing(logOf(code, formatLog(grown)));359+360+ // `src/format.ts` two folders down, in `grown` and in `c4`.361+ expect(counts.trees).toBeLessThanOrEqual(4);362+ expect(next).toStrictEqual(whole);363+ expect(next.commits.map(({ sha }) => sha)[0]).toBe(grown);364+ })365+ )366+ );367+});368+369+describe("landings beside kept history", () => {370+ it.effect("show on the next view once the record has them", () =>371+ within(() =>372+ Effect.gen(function* () {373+ const { c1, grown } = yield* history;374+ const { code, landed } = yield* recordOf(grown);375+376+ // One isolate, so the second view finds the first's history kept.377+ const [before, after] = yield* onIsolate(378+ Effect.gen(function* () {379+ const first = yield* whyOf(code, Option.none(), format);380+381+ yield* Ref.set(landed, [landingOf(c1, "adopt")]);382+383+ return [first, yield* whyOf(code, Option.none(), format)] as const;384+ })385+ );386+387+ expect(before.landings).toStrictEqual([]);388+ expect(after.landings.map(({ ask, sha }) => [sha, ask])).toStrictEqual([389+ [c1, "adopt"],390+ ]);391+ })392+ )393+ );394+});395+396+/**397+ * `count` commits: each changes `count.txt` at the root and leaves398+ * `a/b/c/d/deep.txt` alone, so the commits' root trees all differ and the399+ * folders under them never do.400+ */401+const deepHistory = (count: number) =>402+ Effect.gen(function* () {403+ const git = yield* writer;404+ const shas: CommitSha[] = [];405+406+ for (let at = 1; at <= count; at += 1) {407+ shas.push(408+ yield* git.commit(409+ `Commit ${at}`,410+ [411+ ["a/b/c/d/deep.txt", text("deep\n")],412+ ["count.txt", text(`${at}\n`)],413+ ],414+ shas.slice(-1),415+ at416+ )417+ );418+ }419+420+ const head = shas.at(-1);421+422+ if (head === undefined) {423+ return yield* Effect.die("no commits");424+ }425+426+ yield* git.push(repo, [["refs/heads/main", head]]);427+428+ return { head, shas };429+ });430+431+describe("a cold walk", () => {432+ it.live(433+ "keeps at least 40 reads under way when each takes 50 ms",434+ () =>435+ within(({ delay, seen }) =>436+ Effect.gen(function* () {437+ const { head, shas } = yield* deepHistory(64);438+ const { code } = yield* recordOf(head);439+440+ yield* Ref.set(seen, none);441+ yield* Ref.set(442+ delay,443+ Option.some(() => Duration.millis(50))444+ );445+446+ const view = yield* whyOf(447+ code,448+ Option.none(),449+ RepoPath.make("a/b/c/d/deep.txt")450+ );451+452+ expect(view.ranges).toStrictEqual([453+ { end: 1, sha: shas[0], start: 1 },454+ ]);455+ expect((yield* Ref.get(seen)).peak).toBeGreaterThanOrEqual(40);456+ })457+ ),458+ long459+ );460+461+ // Counted, not timed: a batch of 16 waits for its slowest read, so while462+ // one commit's folder takes a second, at most its 15 neighbours finish;463+ // with no barrier, every other commit does. Wall time under a loaded464+ // machine says less than this count (the walk took about a quarter of465+ // the batched walk's 1,250 ms when each read took 50 ms).466+ it.live(467+ "goes on past a slow read: every other commit's folder is read while one takes a second",468+ () =>469+ within(({ delay, seen }) =>470+ Effect.gen(function* () {471+ const { head, shas } = yield* deepHistory(64);472+ const { code } = yield* recordOf(head);473+474+ const roots = yield* Effect.forEach(shas, (sha) =>475+ RepoHost.use((host) => host.readCommit(repo, sha)).pipe(476+ Effect.flatMap(Effect.fromOption),477+ Effect.map(({ tree }) => tree),478+ Effect.orDie479+ )480+ );481+482+ // The commit after the head: the first the pass looks up.483+ const slow = roots[62] ?? "";484+485+ yield* Ref.set(seen, none);486+ yield* Ref.set(487+ delay,488+ Option.some((id) => Duration.millis(id === slow ? 1000 : 10))489+ );490+491+ yield* whyOf(code, Option.none(), RepoPath.make("a/b/c/d/deep.txt"));492+493+ const { events } = yield* Ref.get(seen);494+495+ const during = events.slice(496+ events.indexOf(`+${slow}`),497+ events.indexOf(`-${slow}`)498+ );499+500+ const others = new Set(roots.slice(0, 62).map((tree) => `-${tree}`));501+502+ expect(503+ during.filter((event) => others.has(event)).length504+ ).toBeGreaterThanOrEqual(60);505+ })506+ ),507+ long508+ );509+510+ it.effect(511+ "looks each commit's entry up once in a path's log",512+ () =>513+ within(({ seen }) =>514+ Effect.gen(function* () {515+ const { head } = yield* deepHistory(200);516+ const { code } = yield* recordOf(head);517+518+ yield* Ref.set(seen, none);519+520+ const { commits } = yield* logOf(code, {521+ at: Option.none(),522+ from: 0,523+ limit: 30,524+ path: Option.some(RepoPath.make("count.txt")),525+ });526+527+ expect(commits).toHaveLength(30);528+ // Each commit's root tree once: no commit is looked up again as529+ // the one after it's parent.530+ expect((yield* Ref.get(seen)).trees).toBe(200);531+ })532+ ),533+ long534+ );535+});536+537+describe("a kept value that no longer decodes", () => {538+ it.effect("is computed again and replaced", () =>539+ within(({ seen }) =>540+ Effect.gen(function* () {541+ const { grown } = yield* history;542+ const { code } = yield* recordOf(grown);543+ const store = yield* CodeStore;544+545+ const key = yield* keyOf(whyKept, {546+ commit: grown,547+ path: format,548+ repo,549+ scan: WHY_SCAN,550+ });551+552+ yield* store.put(key, '{"blob":"not an id"}');553+554+ const view = yield* onIsolate(whyOf(code, Option.none(), format));555+ const replaced = yield* store.get(key);556+557+ expect((yield* Ref.get(seen)).blobs).toBeGreaterThan(0);558+ expect(view.ranges.length).toBeGreaterThan(0);559+ expect(560+ Option.flatMap(561+ replaced,562+ Schema.decodeUnknownOption(Schema.fromJsonString(StoredWhy))563+ ).pipe(Option.map(({ ranges }) => ranges))564+ ).toStrictEqual(Option.some(view.ranges));565+ expect(566+ (yield* CodeStoreCounts.use(({ counts }) => counts)).puts567+ ).toBeGreaterThanOrEqual(2);568+ })569+ )570+ );571+});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