Walk a small file's history by reading it whole at each commit: one call a commit instead of its folders
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- Live on dev-oscabriel, one view got through about 35 calls a second to the repo or the code store, whatever it asked and however many were under way, and a cold why or path log made 400-575 calls: a root tree per commit and the folders above the path wherever they changed (counted over local copies of changesets and click). So the calls are the cost, and a 200-commit walk by folders cannot finish in ~5 s. - A why or a path's log whose file is at most FILE_WALK_CAP (256 KiB) at the walk's first commit now reads it whole at each commit (RepoHost readFile, one call), names each version by its git blob id (SHA-1 of "blob <size>\0" and the bytes; checked against git on a file read over Artifacts' REST API), and the why's blame takes each older version's text from those reads instead of reading its blob again. About 200 calls for a 200-commit walk instead of 400-575. - A larger file, a folder, a submodule or a missing path is still looked up by its folders, as before. In a file walk a commit where the path is no file reads as none, as a missing file does, and a change of mode alone is not seen in a path's log (its ids are blob ids there). - The walk reads the head's file before the pass starts, so a binary or large file never has 200 copies read: the pass starts only for a small text file. - Tests: red first, a cold why reads the file once per commit and no folder past the head's (was 1 blob, 0 files), a path's log reads no folder (was 24 trees); a file past the cap keeps the folder walk. The overlap and slow-read tests now hold file reads, and a folder's log keeps the folder walk's (201 tree reads, at least 40 under way).
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+479 added−94 removed
- tests:+207 added−36 removed
- other:+272 added−58 removed
Provenance
- Commit
8310fed- Tree
84b0853- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
2421226
7 files changed+479 added−94 removed
added:packages/project/src/code/file-walk.ts+92 added
1+/**2+ * A walk over history that reads the file itself at each commit, one call3+ * each, rather than the folders above it. A store answers one view a few4+ * dozen calls a second, however many are under way (about 35 on5+ * dev-oscabriel, repo reads and code store calls alike), and a path four6+ * folders deep took two to three calls a commit by its folders: one root7+ * tree each, and the folders above the path wherever they changed. Read8+ * whole, the file is one call a commit, its git blob id is the SHA-1 of9+ * its bytes, and each version's text is already at hand for the blame.10+ *11+ * Only a file at most `FILE_WALK_CAP` bytes at the walk's first commit is12+ * walked this way, so a walk holds at most `READS_AT_ONCE` such files at13+ * once; a larger file, a folder, a submodule or a missing path is looked14+ * up by its folders (`tree.ts`). A commit where the path is not a file15+ * (missing, or a folder then) reads as none, as a missing file does.16+ */17+import { RepoHost, Revision } from "@repo/artifacts/repo-host";18+import type { RepoNotFound } from "@repo/artifacts/repo-host";19+import { BlobSha } from "@repo/protocol/ids";20+import type { CommitSha, RepoName, RepoPath } from "@repo/protocol/ids";21+import { Effect, Option } from "effect";22+23+/** The most a file may weigh at a walk's first commit to be read whole at each commit. */24+export const FILE_WALK_CAP = 256 * 1024;25+26+const encoder = new TextEncoder();27+28+const hex = (digest: ArrayBuffer) =>29+ [...new Uint8Array(digest)]30+ .map((byte) => byte.toString(16).padStart(2, "0"))31+ .join("");32+33+/** The git blob id of `bytes`: the SHA-1 of `blob <size>\0` and the bytes. */34+export const blobIdOf = (bytes: Uint8Array): Effect.Effect<BlobSha> =>35+ Effect.gen(function* () {36+ const header = encoder.encode(`blob ${bytes.byteLength}\0`);37+ const raw = new Uint8Array(header.byteLength + bytes.byteLength);38+39+ raw.set(header);40+ raw.set(bytes, header.byteLength);41+42+ const digest = yield* Effect.promise(() =>43+ crypto.subtle.digest("SHA-1", raw)44+ );45+46+ return BlobSha.make(hex(digest));47+ });48+49+/** The file at `path` in `commit`, read whole: none when no file is there. */50+export const fileAt = (51+ repo: RepoName,52+ commit: CommitSha,53+ path: RepoPath54+): Effect.Effect<Option.Option<Uint8Array>, RepoNotFound, RepoHost> =>55+ RepoHost.use((host) =>56+ host.readFile(repo, Revision.Commit({ sha: commit }), path)57+ );58+59+/** A file read whole at a commit: its blob id and its bytes. */60+export interface FileVersion {61+ readonly blob: BlobSha;62+ readonly bytes: Uint8Array;63+}64+65+/** The file's version at `path` in `commit`, read whole; none when no file is there. */66+export const versionAt = (67+ repo: RepoName,68+ commit: CommitSha,69+ path: RepoPath70+): Effect.Effect<Option.Option<FileVersion>, RepoNotFound, RepoHost> =>71+ Effect.flatMap(fileAt(repo, commit, path), (read) =>72+ Option.match(read, {73+ onNone: () => Effect.succeedNone,74+ onSome: (bytes) =>75+ Effect.map(blobIdOf(bytes), (blob) => Option.some({ blob, bytes })),76+ })77+ );78+79+/**80+ * The file at `path` in `commit` as a version, when a walk may read it81+ * whole at each commit: a file of at most `FILE_WALK_CAP` bytes. None82+ * means the walk looks the path up by its folders instead.83+ */84+export const walkableAt = (85+ repo: RepoName,86+ commit: CommitSha,87+ path: RepoPath88+): Effect.Effect<Option.Option<FileVersion>, RepoNotFound, RepoHost> =>89+ Effect.map(90+ versionAt(repo, commit, path),91+ Option.filter(({ bytes }) => bytes.byteLength <= FILE_WALK_CAP)92+ );modified:packages/project/src/code/log.ts+50 added-11 removed
30 unmodified lines31 import { Array, DateTime, Effect, Equal, Option } from "effect";32 33 import type { CodeProject } from "../code.ts";34 import { asOneView, CodeCache } from "./cache.ts";35+import { versionAt, walkableAt } from "./file-walk.ts";36 import {37 INCREMENT_REACH,38 keyOf,39 pathLogKept,107 unmodified lines147 onNone: () => ({ commits }),148 onSome: (at) => ({ commits, next: at }),149 });150 150-/** What sits at `path` in each commit of `commits`, in order: one lookup each. */151-const idsOf = (151+/** What sits at a path in a commit, as a walk compares it with its parent's. */152+type IdOf = (153+ commit: Commit154+) => Effect.Effect<Option.Option<string>, RepoNotFound, RepoHost>;155+156+/**157+ * How a walk from `start` looks `path` up in each commit: a file small158+ * enough there is read whole, one call a commit (`file-walk.ts`), and159+ * named by its blob id, so a change of its mode alone is not seen; any160+ * other path by its folders, named by its mode and id.161+ */162+const idOfFrom = (163 repo: RepoName,164 path: RepoPath,165+ start: Commit166+): Effect.Effect<IdOf, RepoNotFound, RepoHost> =>167+ Effect.map(walkableAt(repo, start.sha, path), (whole) =>168+ Option.match(whole, {169+ onNone: () => (commit: Commit) => idAt(repo, commit.tree, path),170+ // The start's file is read already: each commit is read once.171+ onSome:172+ ({ blob: first }) =>173+ (commit: Commit) =>174+ commit.sha === start.sha175+ ? Effect.succeedSome(`blob ${first}`)176+ : Effect.map(177+ versionAt(repo, commit.sha, path),178+ Option.map(({ blob }) => `blob ${blob}`)179+ ),180+ })181+ );182+183+/** What sits at the path in each commit of `commits`, in order: one lookup each. */184+const idsOf = (185+ idOf: IdOf,186 commits: readonly Commit[]187 ): Effect.Effect<readonly Option.Option<string>[], RepoNotFound, RepoHost> =>156- Effect.forEach(commits, ({ tree }) => idAt(repo, tree, path), {157- concurrency: READS_AT_ONCE,158- });188+ Effect.forEach(commits, idOf, { concurrency: READS_AT_ONCE });189 190 /**191 * The commits among the first `count` of `scan` that changed `path` from192 * their first parent, newest first. The log is first parents, so each1 unmodified line194 * ever say otherwise) is a parent read on its own.195 */196 const changedIn = (197 repo: RepoName,168- path: RepoPath,198+ idOf: IdOf,199 scan: readonly Commit[],200 count: number201 ): Effect.Effect<readonly CommitSha[], RepoNotFound, RepoHost> =>202 Effect.gen(function* () {203 const looked = scan.slice(0, count + 1);174- const ids = yield* idsOf(repo, path, looked);204+ const ids = yield* idsOf(idOf, looked);205 206 const changed = yield* Effect.forEach(207 looked.slice(0, count),208 (commit, at) =>9 unmodified lines218 : commitAt(repo, first).pipe(219 Effect.flatMap(220 Option.match({221 onNone: () => Effect.succeedNone,192- onSome: ({ tree }) => idAt(repo, tree, path),222+ onSome: idOf,223 })224 )225 ),226 });34 unmodified lines261 ): Effect.Effect<StoredPathLog, RepoNotFound, RepoHost> =>262 Effect.gen(function* () {263 const scanned = scan.slice(0, PATH_SCAN);264 const reachedRoot = scan.length <= PATH_SCAN;235- const kept = yield* nearestKept(repo, path, scan);265+ const [start] = scan;266 267+ if (start === undefined) {268+ return { reachedRoot, shas: [] };269+ }270+271+ const [kept, idOf] = yield* Effect.all(272+ [nearestKept(repo, path, scan), idOfFrom(repo, path, start)],273+ { concurrency: 2 }274+ );275+276 if (Option.isNone(kept)) {277 return {278 reachedRoot,240- shas: yield* changedIn(repo, path, scan, scanned.length),279+ shas: yield* changedIn(repo, idOf, scan, scanned.length),280 };281 }282 283 const { back } = kept.value;284 const inScan = new Set<string>(scanned.map(({ sha }) => sha));246- const between = yield* changedIn(repo, path, scan, back);285+ const between = yield* changedIn(repo, idOf, scan, back);286 287 return {288 reachedRoot,289 shas: [87 unmodified linesmodified:packages/project/src/code/why.ts+130 added-47 removed
37 unmodified lines38 39 import type { CodeProject } from "../code.ts";40 import { MAX_LANDINGS } from "../project.ts";41 import { asOneView } from "./cache.ts";42+import { versionAt, walkableAt } from "./file-walk.ts";43+import type { FileVersion } from "./file-walk.ts";44 import { contentsOf, contentsOfBytes, unlessTooLarge } from "./file.ts";45 import {46 INCREMENT_REACH,47 keyOf,32 unmodified lines80 )81 );82 83 /**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.84+ * The file's blob in each of `commits` (first parents, newest first), by85+ * `blobOf`, up to the first commit without the file. One pass with86+ * `READS_AT_ONCE` lookups under way and no barrier: a slow lookup holds up87+ * only itself, not the ones after it. Once a commit without the file is88+ * found, lookups further back are skipped.89 */88-const lookups = (repo: RepoName, path: RepoPath, commits: readonly Commit[]) =>90+const lookups = <E, R>(91+ commits: readonly Commit[],92+ blobOf: (commit: Commit) => Effect.Effect<Option.Option<BlobSha>, E, R>93+) =>94 Effect.gen(function* () {95 // Where the file was found missing: no lookup past it is needed.96 const missingAt = yield* Ref.make(commits.length);97 4 unmodified lines102 if (at > (yield* Ref.get(missingAt))) {103 return Option.none();104 }105 101- const blob = yield* blobAt(repo, commit, path);106+ const blob = yield* blobOf(commit);107 108 if (Option.isNone(blob)) {109 yield* Ref.update(missingAt, (was) => Math.min(was, at));110 }225 unmodified lines336 });337 });338 339 /**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.340+ * The why at `head` from its file's text and the blobs `found` in the341+ * commits before it: the newest version is the file as read, and the342+ * older ones are read in order by `readText`, `READS_AT_ONCE` under way,343+ * only until every line has its commit.344 */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> =>345+const blamed = <R>(346+ head: Commit,347+ newest: BlobSha,348+ text: string,349+ found: readonly {350+ readonly blob: Option.Option<BlobSha>;351+ readonly commit: Commit;352+ }[],353+ readText: (blob: BlobSha) => Effect.Effect<string, RepoNotFound, R>354+): Effect.Effect<StoredWhy, RepoNotFound, R> =>355 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;356 const none: StoredWhy = { blob: newest, ranges: [], shas: [] };357 370- if (Option.isNone(contents) || Option.isNone(contents.value.text)) {371- return none;372- }373-358 const { stopped, versions } = versionsOf(359 { blob: newest, commit: head },360 found361 );362 363 const [first = { blob: newest, commit: head }, ...older] = versions;380- const text = contents.value.text.value;364 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.365 const tracing = yield* Stream.fromIterable(older).pipe(366 Stream.mapEffect(367 (version) =>388- Effect.map(textOf(repo, version.blob), (read) => ({368+ Effect.map(readText(version.blob), (read) => ({369 sha: version.commit.sha,370 text: read,371 })),372 { concurrency: READS_AT_ONCE }18 unmodified lines391 ? { ...none, ranges, shas, stoppedAt: last.commit.sha }392 : { ...none, ranges, shas };393 });394 395+/**396+ * The why at `log[0]` by reading the file whole at each commit397+ * (`file-walk.ts`): one call a commit, and every version's text kept from398+ * those reads, so the blame reads nothing more.399+ */400+const walkedByFile = (401+ repo: RepoName,402+ path: RepoPath,403+ log: readonly Commit[],404+ head: Commit,405+ newest: FileVersion406+): Effect.Effect<StoredWhy, RepoNotFound, RepoHost> =>407+ Effect.gen(function* () {408+ const { text } = contentsOfBytes(newest.bytes);409+410+ if (Option.isNone(text)) {411+ return { blob: newest.blob, ranges: [], shas: [] };412+ }413+414+ // Each version's bytes, by its blob id: the commits that share one415+ // share its text.416+ const texts = new Map<string, Uint8Array>([[newest.blob, newest.bytes]]);417+418+ const found = yield* lookups(log.slice(1), (commit) =>419+ versionAt(repo, commit.sha, path).pipe(420+ Effect.map(421+ Option.map(({ blob, bytes }) => {422+ if (!texts.has(blob)) {423+ texts.set(blob, bytes);424+ }425+426+ return blob;427+ })428+ )429+ )430+ );431+432+ return yield* blamed(head, newest.blob, text.value, found, (blob) => {433+ const bytes = texts.get(blob);434+435+ return bytes === undefined436+ ? textOf(repo, blob)437+ : Effect.succeed(438+ Option.getOrElse(contentsOfBytes(bytes).text, () => "")439+ );440+ });441+ });442+443+/**444+ * The why at `log[0]` by the whole walk: by reading the file whole at each445+ * commit when it is small enough at the head, else by its folders. The446+ * head's blob and text are read beside the other commits' lookups, so447+ * nothing waits on the head's folders before the pass starts.448+ */449+const walked = (450+ repo: RepoName,451+ at: CommitSha,452+ path: RepoPath,453+ log: readonly Commit[],454+ head: Commit455+): Effect.Effect<StoredWhy, UnknownPath | RepoNotFound, RepoHost> =>456+ Effect.gen(function* () {457+ const whole = yield* walkableAt(repo, head.sha, path);458+459+ if (Option.isSome(whole)) {460+ return yield* walkedByFile(repo, path, log, head, whole.value);461+ }462+463+ const [headSide, found] = yield* Effect.all(464+ [465+ Effect.gen(function* () {466+ const blob = yield* blobAt(repo, head, path);467+468+ if (Option.isNone(blob)) {469+ return yield* new UnknownPath({ commit: at, path });470+ }471+472+ return {473+ blob: blob.value,474+ contents: yield* contentsOf(repo, blob.value),475+ };476+ }),477+ lookups(log.slice(1), (commit) => blobAt(repo, commit, path)),478+ ],479+ { concurrency: 2 }480+ );481+482+ const newest = headSide.blob;483+ const { contents } = headSide;484+485+ if (Option.isNone(contents) || Option.isNone(contents.value.text)) {486+ return { blob: newest, ranges: [], shas: [] };487+ }488+489+ return yield* blamed(490+ head,491+ newest,492+ contents.value.text.value,493+ found,494+ (blob) => textOf(repo, blob)495+ );496+ });497+498 /** The why at `at`, computed: from a kept ancestor's when one is in reach. */499 const computed = (500 repo: RepoName,501 at: CommitSha,104 unmodified linesmodified:packages/project/test/code-fixtures.ts+5 added-1 removed
446 unmodified lines447 */448 export const overlappingTrees = (449 reading: Ref.Ref<boolean>,450 peak: Ref.Ref<number>,451- kind: "blob" | "tree" = "tree"451+ kind: "blob" | "file" | "tree" = "tree"452 ) =>453 Layer.effect(454 RepoHost,455 Effect.gen(function* () {19 unmodified lines475 readBlob: (name, id) =>476 kind === "blob"477 ? Effect.andThen(slowed, host.readBlob(name, id))478 : host.readBlob(name, id),479+ readFile: (name, at, file) =>480+ kind === "file"481+ ? Effect.andThen(slowed, host.readFile(name, at, file))482+ : host.readFile(name, at, file),483 readTree: (name, id) =>484 kind === "tree"485 ? Effect.andThen(slowed, host.readTree(name, id))486 : host.readTree(name, id),3 unmodified linesmodified:packages/project/test/code-history.test.ts+180 added-22 removed
7 unmodified lines8 * 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";12+import { RepoHost, RepoSession, Revision } 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 {12 unmodified lines29 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 { FILE_WALK_CAP } from "../src/code/file-walk.ts";34 import { keyOf, StoredWhy, whyKept } from "../src/code/history.ts";35 import { WHY_SCAN } from "../src/code/why.ts";36 import { Content, writer } from "./code-fixtures.ts";37 import type { Tree } from "./code-fixtures.ts";12 unmodified lines50 */51 interface Seen {52 readonly trees: number;53 readonly blobs: number;54+ /** Files read whole at a commit (`readFile`). */55+ readonly files: number;56 readonly peak: number;57 readonly events: readonly string[];58 }59 57-const none: Seen = { blobs: 0, events: [], peak: 0, trees: 0 };60+const none: Seen = { blobs: 0, events: [], files: 0, peak: 0, trees: 0 };61 62 /** How long a read of the object `id` takes, once a test sets it. */63 type Delay = Option.Option<(id: string) => Duration.Duration>;64 9 unmodified lines74 const host = yield* RepoHost;75 const under = yield* Ref.make(0);76 77 const timed = <A, E>(75- kind: "blobs" | "trees",78+ kind: "blobs" | "files" | "trees",79 id: string,80 read: Effect.Effect<A, E>81 ) =>82 Effect.gen(function* () {27 unmodified lines110 111 return RepoHost.of({112 ...host,113 readBlob: (name, id) => timed("blobs", id, host.readBlob(name, id)),114+ // A file read at a commit is noted by the commit's id.115+ readFile: (name, at, path) =>116+ timed(117+ "files",118+ Revision.$match(at, {119+ Branch: ({ name: branch }) => branch,120+ Commit: ({ sha }) => sha,121+ }),122+ host.readFile(name, at, path)123+ ),124 readTree: (name, id) => timed("trees", id, host.readTree(name, id)),125 });126 })127 ).pipe(Layer.provide(RepoHostMemory));345 unmodified lines473 long474 );475 476 // 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;477+ // one commit's file takes a second, at most its 15 neighbours finish;478 // with no barrier, every other commit does. Wall time under a loaded479 // machine says less than this count (the walk took about a quarter of480 // the batched walk's 1,250 ms when each read took 50 ms).481 it.live(469- "goes on past a slow read: every other commit's folder is read while one takes a second",482+ "goes on past a slow read: every other commit's file is read while one takes a second",483 () =>484 within(({ delay, seen }) =>485 Effect.gen(function* () {486 const { head, shas } = yield* deepHistory(64);487 const { code } = yield* recordOf(head);488 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- );489+ // The commit after the head: the first the pass looks up. A file490+ // read is noted by its commit's id.491+ const slow = shas[62] ?? "";492 484- // The commit after the head: the first the pass looks up.485- const slow = roots[62] ?? "";486-493 yield* Ref.set(seen, none);494 yield* Ref.set(495 delay,496 Option.some((id) => Duration.millis(id === slow ? 1000 : 10))7 unmodified lines504 events.indexOf(`+${slow}`),505 events.indexOf(`-${slow}`)506 );507 502- const others = new Set(roots.slice(0, 62).map((tree) => `-${tree}`));508+ const others = new Set(shas.slice(0, 62).map((sha) => `-${sha}`));509 510 expect(511 during.filter((event) => others.has(event)).length512 ).toBeGreaterThanOrEqual(60);2 unmodified lines515 long516 );517 518 it.effect(513- "looks each commit's entry up once in a path's log",519+ "reads each commit's file once in a path's log",520 () =>521 within(({ seen }) =>522 Effect.gen(function* () {523 const { head } = yield* deepHistory(200);7 unmodified lines531 limit: 30,532 path: Option.some(RepoPath.make("count.txt")),533 });534 535+ const { files, trees } = yield* Ref.get(seen);536+537 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);538+ expect({ files, trees }).toStrictEqual({ files: 200, trees: 0 });539 })540 ),541 long542 );543+544+ it.effect(545+ "looks each commit's folder up once in a folder's log",546+ () =>547+ within(({ seen }) =>548+ Effect.gen(function* () {549+ const { head } = yield* deepHistory(200);550+ const { code } = yield* recordOf(head);551+552+ yield* Ref.set(seen, none);553+554+ const { commits } = yield* logOf(code, {555+ at: Option.none(),556+ from: 0,557+ limit: 30,558+ path: Option.some(RepoPath.make("a/b")),559+ });560+561+ expect(commits).toHaveLength(1);562+ // Each commit's root tree read once from the store, and `a`, the563+ // same tree in every commit, once. The view shares a tree read564+ // under way among its fibers, so this count holds the store's565+ // reads, not how often the walk asked.566+ expect((yield* Ref.get(seen)).trees).toBe(201);567+ })568+ ),569+ long570+ );571+572+ it.live(573+ "keeps at least 40 folder reads under way in a folder's log when each takes 50 ms",574+ () =>575+ within(({ delay, seen }) =>576+ Effect.gen(function* () {577+ const { head } = yield* deepHistory(64);578+ const { code } = yield* recordOf(head);579+580+ yield* Ref.set(seen, none);581+ yield* Ref.set(582+ delay,583+ Option.some(() => Duration.millis(50))584+ );585+586+ yield* logOf(code, {587+ at: Option.none(),588+ from: 0,589+ limit: 30,590+ path: Option.some(RepoPath.make("a/b")),591+ });592+593+ const { files, peak } = yield* Ref.get(seen);594+595+ expect(files).toBe(1);596+ expect(peak).toBeGreaterThanOrEqual(40);597+ })598+ ),599+ long600+ );601 });602 603 describe("a kept value that no longer decodes", () => {604 it.effect("is computed again and replaced", () =>14 unmodified lines619 620 const view = yield* onIsolate(whyOf(code, Option.none(), format));621 const replaced = yield* store.get(key);622 560- expect((yield* Ref.get(seen)).blobs).toBeGreaterThan(0);623+ const { blobs, files } = yield* Ref.get(seen);624+625+ expect(blobs + files).toBeGreaterThan(0);626 expect(view.ranges.length).toBeGreaterThan(0);627 expect(628 Option.flatMap(629 replaced,33 unmodified lines663 log: (name, at, limit, offset) =>664 noted(host.log(name, at, limit, offset)),665 readBlob: (name, id) => noted(host.readBlob(name, id)),666 readCommit: (name, sha) => noted(host.readCommit(name, sha)),667+ readFile: (name, at, path) => noted(host.readFile(name, at, path)),668 readTree: (name, id) => noted(host.readTree(name, id)),669 });670 })671 ).pipe(Layer.provide(RepoHostMemory));91 unmodified lines763 })764 )765 );766 });767+768+describe("a cold walk over a file", () => {769+ it.effect(770+ "reads the file once at each commit of a why and no folder past the head's",771+ () =>772+ within(({ seen }) =>773+ Effect.gen(function* () {774+ const { head } = yield* deepHistory(20);775+ const { code } = yield* recordOf(head);776+777+ yield* Ref.set(seen, none);778+ yield* whyOf(code, Option.none(), RepoPath.make("a/b/c/d/deep.txt"));779+780+ const { blobs, files, trees } = yield* Ref.get(seen);781+782+ // One read of the file per commit is one call each; the folders783+ // above it took five per commit.784+ expect({ blobs, files }).toStrictEqual({ blobs: 0, files: 20 });785+ expect(trees).toBeLessThanOrEqual(5);786+ })787+ )788+ );789+790+ it.effect(791+ "reads the file once at each commit of a path's log and no folder",792+ () =>793+ within(({ seen }) =>794+ Effect.gen(function* () {795+ const { head } = yield* deepHistory(20);796+ const { code } = yield* recordOf(head);797+798+ yield* Ref.set(seen, none);799+800+ const { commits } = yield* logOf(code, {801+ at: Option.none(),802+ from: 0,803+ limit: 30,804+ path: Option.some(RepoPath.make("a/b/c/d/deep.txt")),805+ });806+807+ const { files, trees } = yield* Ref.get(seen);808+809+ expect(commits).toHaveLength(1);810+ expect(files).toBeLessThanOrEqual(21);811+ expect(trees).toBe(0);812+ })813+ )814+ );815+816+ it.effect(817+ "looks a file past the cap up by its folders, never reading it whole at each commit",818+ () =>819+ within(({ seen }) =>820+ Effect.gen(function* () {821+ const git = yield* writer;822+ const big = "x".repeat(FILE_WALK_CAP);823+824+ const c1 = yield* git.commit(825+ "One",826+ [["big.txt", text(`${big}\n`)]],827+ [],828+ 1829+ );830+831+ const c2 = yield* git.commit(832+ "Two",833+ [["big.txt", text(`${big}\nmore\n`)]],834+ [c1],835+ 2836+ );837+838+ yield* git.push(repo, [["refs/heads/main", c2]]);839+840+ const { code } = yield* recordOf(c2);841+842+ yield* Ref.set(seen, none);843+844+ const view = yield* whyOf(845+ code,846+ Option.none(),847+ RepoPath.make("big.txt")848+ );849+850+ expect(view.ranges).toStrictEqual([851+ { end: 1, sha: c1, start: 1 },852+ { end: 2, sha: c2, start: 2 },853+ ]);854+ expect((yield* Ref.get(seen)).files).toBeLessThanOrEqual(1);855+ })856+ )857+ );858+});modified:packages/project/test/code-why.test.ts+18 added-9 removed
155 unmodified lines156 157 return { adopted, asked, code, iso, landings, readme, week };158 });159 160-/** The memory store, with each blob `readBlob` is asked for counted in `reads`. */160+/**161+ * The memory store, with each blob `readBlob` is asked for, and each file162+ * `readFile` reads whole at a commit, counted in `reads`.163+ */164 const countedBy = (reads: Ref.Ref<readonly string[]>) =>165 Layer.effect(166 RepoHost,167 Effect.gen(function* () {4 unmodified lines172 readBlob: (name, blob) =>173 Ref.update(reads, (all) => [...all, blob]).pipe(174 Effect.andThen(host.readBlob(name, blob))175 ),176+ readFile: (name, at, file) =>177+ Ref.update(reads, (all) => [...all, file]).pipe(178+ Effect.andThen(host.readFile(name, at, file))179+ ),180 });181 })182 ).pipe(Layer.provide(RepoHostMemory));183 60 unmodified lines244 }).pipe(Effect.provide(RepoHostMemory))245 );246 247 it.effect(241- "reads no blob the second time: the view is kept by (at, path)",248+ "reads no blob or file the second time: the view is kept by (at, path)",249 () =>250 Effect.gen(function* () {251 const reads = yield* Ref.make<readonly string[]>([]);252 1 unmodified line254 const { code, iso } = yield* history;255 const first = yield* whyOf(code, Option.some(iso), format);256 const counted = (yield* Ref.get(reads)).length;257 258+ // The file read whole at `iso` and at its two first parents.251- expect(counted).toBe(2);259+ expect(counted).toBe(3);260 261 const again = yield* whyOf(code, Option.some(iso), format);262 263 expect(again).toStrictEqual(first);4 unmodified lines268 })269 );270 271 it.live(264- "reads the file's blob in each commit several at a time, not one after another",272+ "reads the file in each commit several at a time, not one after another",273 () =>274 Effect.gen(function* () {275 const reading = yield* Ref.make(false);276 const peak = yield* Ref.make(0);2 unmodified lines279 const { code, shas } = yield* longHistory(64);280 281 yield* Ref.set(reading, true);282 275- // `once.txt` never changes, so the walk reads its blob in all 64283+ // `once.txt` never changes, so the walk reads it whole in all 64284 // commits.285 const { ranges } = yield* whyView(286 code,287 main,288 RepoPath.make("once.txt")289 );290 291 expect(ranges).toStrictEqual([{ end: 1, sha: shas[0], start: 1 }]);284- }).pipe(Effect.provide(overlappingTrees(reading, peak)));292+ }).pipe(Effect.provide(overlappingTrees(reading, peak, "file")));293 294 // `READS_AT_ONCE` lookups under way, and the head's own beside them.295 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);296 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE + 1);1 unmodified line298 { timeout: 30_000 }299 );300 301 it.live(294- "reads the file's older versions several at a time, not one after another",302+ "reads the file's versions several at a time, not one after another",303 () =>304 Effect.gen(function* () {305 const reading = yield* Ref.make(false);306 const peak = yield* Ref.make(0);3 unmodified lines310 311 yield* Ref.set(reading, true);312 313 // Each of the 40 lines came with a commit of its own, so the306- // blame reads every older version of `grow.txt`.314+ // blame takes every older version of `grow.txt` from the walk's315+ // reads of it.316 const { ranges } = yield* whyView(317 code,318 main,319 RepoPath.make("grow.txt")1 unmodified line321 322 expect(ranges).toStrictEqual(323 shas.map((sha, at) => ({ end: at + 1, sha, start: at + 1 }))324 );316- }).pipe(Effect.provide(overlappingTrees(reading, peak, "blob")));325+ }).pipe(Effect.provide(overlappingTrees(reading, peak, "file")));326 327 // `READS_AT_ONCE` lookups under way, and the head's own beside them.328 expect(yield* Ref.get(peak)).toBeGreaterThanOrEqual(32);329 expect(yield* Ref.get(peak)).toBeLessThanOrEqual(READS_AT_ONCE + 1);34 unmodified linesmodified:packages/project/test/code.test.ts+4 added-4 removed
435 unmodified lines436 });437 438 describe("a path's log, read live", () => {439 it.live(440- "reads its commits' trees several at a time, not one after another",440+ "reads the file in its commits several at a time, not one after another",441 () =>442 Effect.gen(function* () {443 const reading = yield* Ref.make(false);444 const peak = yield* Ref.make(0);8 unmodified lines453 path: path("once.txt"),454 });455 456 expect(commits.map(({ sha }) => sha)).toStrictEqual([shas[0]]);457- }).pipe(Effect.provide(overlappingTrees(reading, peak)));457+ }).pipe(Effect.provide(overlappingTrees(reading, peak, "file")));458 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.459+ // 64 commits, the file read whole in each: one at a time a live460+ // store 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 long177 unmodified lines