Skip to content

Commit ad826e4

Browse files
ovflowdavivkeller
andauthored
perf: let metadata and section-pages start on their dependency's first chunk (#1240)
* perf: let metadata and section-pages start on their dependency's first chunk With more than one thread, metadata and section-pages now start on the first chunk of their dependency instead of waiting for all of it, so parsing, metadata and section pages overlap. The generated files are unchanged. section-pages passes each module's entries on as they arrive and adds the chunk pages after the last of them, in module order, as if built from the whole input at once. A module's chunk pages need all of its entries, and a chunk need not hold whole modules, so groupWholeModules regroups streamed entries into batches of whole modules, and rejects a module whose entries come back after another's. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Sonnet 5.5 <noreply@anthropic.com> * docs: mention toBatches in the changeset, as it comes with groupWholeModules worker.stream no longer reads its input with toBatches, so the helper now comes with groupWholeModules, its first caller. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> * refactor: drop groupWholeModules, as metadata's chunks hold whole modules From the review. A module is one file: parseApiDoc sets every entry's api once per file, and worker.stream never splits an item, so each of metadata's chunks already holds whole modules. section-pages reads its input as it comes with toBatches instead of regrouping it, and the helper and its tests go. Co-authored-by: Aviv Keller <me@aviv.sh> Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> * test: check the streamed section pages without copies of what core has The two tests comparing section-pages' batched output with its whole input become one: both compared against the same output. core's collectAsyncGenerator replaces a local copy of it, and html's test gives section-pages its entries as an array, which it reads as one batch, so it needs no stream of its own. toBatches' test no longer defines a generator body it never runs. The comment on section-pages' chunk pages says batches, as chunk already means a page there. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> * docs: point generators that stream their input to toBatches Every streaming generator reads its input through toBatches, which takes both the stream and the collected array one thread gives, but the docs for writing one only said to accept both. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> * refactor: always give a generator that streams its input an async iterable From the review, which asked for it. With one thread the input is still collected first, as interleaving the stages there would only keep every stage's data alive at once, but it now arrives as its only chunk instead of as the array. A generator that sets streamsInput reads its input with one for await either way, so toBatches goes, and the types take only the async iterable. core's once, which the cache already used to stream a result that doesn't, moves to utils/generators.mjs next to the other generator helpers. The test of one thread reads a source of two chunks, so it shows they arrive as one. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Aviv Keller <me@aviv.sh>
1 parent 41920cb commit ad826e4

16 files changed

Lines changed: 204 additions & 47 deletions

File tree

‎.changeset/stream-input.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
'@doc-kit/core': minor
33
---
44

5-
Generators can set `streamsInput: true` to receive their dependency's output as an async iterable of chunks as they are produced, instead of waiting for all of it. The cache runs a streamed generator once for every reader, and lets a chunk go once all of them have read it.
5+
Generators can set `streamsInput: true` to receive their dependency's output as an async iterable of chunks as they are produced, instead of waiting for all of it. With one thread, the input is collected first and arrives as its only chunk. The cache runs a streamed generator once for every reader, and lets a chunk go once all of them have read it.

‎.changeset/stream-metadata.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@doc-kit/core': minor
3+
'@doc-kit/generator-react': minor
4+
---
5+
6+
`metadata` and `section-pages` stream their input: with more than one thread, they start on their dependency's first chunk, so parsing, metadata and section pages overlap. The generated files are unchanged.

‎docs/creating-generators.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,10 @@ export default {
342342
```
343343
344344
- A dependency that doesn't stream arrives as a single chunk.
345-
- With one thread, `input` is still the collected array, so accept both.
345+
- With one thread, `input` is collected first and arrives as its only chunk.
346346
- `input` can be iterated only once.
347+
- `metadata`'s chunks hold whole files, and a file is one module, so a chunk
348+
holds all the entries of each module in it.
347349
348350
## Declaring a dependent
349351

‎packages/core/src/__tests__/generators.test.mjs‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -142,11 +142,25 @@ const syntheticGenerators = {
142142
yield* input;
143143
},
144144
},
145+
// A source of two chunks, and a reader that tells which it got
146+
'two-chunks': {
147+
name: 'two-chunks',
148+
hasParallelProcessor: true,
149+
generate: async () =>
150+
(async function* () {
151+
yield [1];
152+
yield [2];
153+
})(),
154+
},
145155
'shape-reader': {
146156
name: 'shape-reader',
147-
dependsOn: 'metadata',
157+
dependsOn: 'two-chunks',
148158
streamsInput: true,
149-
generate: async input => ({ array: Array.isArray(input) }),
159+
generate: async input => {
160+
const chunks = await Array.fromAsync(input);
161+
162+
return { chunks };
163+
},
150164
},
151165
};
152166

@@ -339,7 +353,7 @@ describe('createGenerator orchestration', () => {
339353
assert.deepStrictEqual(unhandled, []);
340354
});
341355

342-
it('gives a generator that streams its input the whole input with one thread', async () => {
356+
it('gives a generator that streams its input the whole input as one chunk with one thread', async () => {
343357
const one = await createGenerator().runGenerators({
344358
target: ['shape-reader'],
345359
threads: 1,
@@ -349,8 +363,8 @@ describe('createGenerator orchestration', () => {
349363
threads: 2,
350364
});
351365

352-
assert.deepStrictEqual(one, [{ array: true }]);
353-
assert.deepStrictEqual(two, [{ array: false }]);
366+
assert.deepStrictEqual(one, [{ chunks: [[1, 2]] }]);
367+
assert.deepStrictEqual(two, [{ chunks: [[1], [2]] }]);
354368
});
355369

356370
it('returns no results with discardResults', async () => {

‎packages/core/src/caching.mjs‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
import logger from './logger/index.mjs';
4+
import { once } from './utils/generators.mjs';
45
import { isAsyncIterable } from './utils/misc.mjs';
56
import { createTee } from './utils/tee.mjs';
67

@@ -37,17 +38,6 @@ export const collectAsyncGenerator = async generator => {
3738
return results;
3839
};
3940

40-
/**
41-
* Gives a value as the single chunk of an async generator.
42-
*
43-
* @template T
44-
* @param {T} value
45-
* @returns {AsyncGenerator<T>}
46-
*/
47-
async function* once(value) {
48-
yield value;
49-
}
50-
5141
/**
5242
* Creates the cache that backs the generator pipeline. It is the single owner
5343
* of every piece of caching the orchestrator needs.

‎packages/core/src/generators.mjs‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { resolvePipeline } from './generators/pipeline.mjs';
99
import logger from './logger/index.mjs';
1010
import createWorkerPool from './threading/index.mjs';
1111
import createParallelWorker from './threading/parallel.mjs';
12+
import { once } from './utils/generators.mjs';
1213
import { loadMarkdownPlugins } from './utils/markdown/plugins.mjs';
1314
import { isAsyncIterable } from './utils/misc.mjs';
1415

@@ -31,15 +32,30 @@ const createGenerator = () => {
3132
* Gets the input from a dependency generator, collected or streamed.
3233
*
3334
* @param {string | undefined} dependsOn - Resolved dependency specifier
34-
* @param {boolean} [streamed] - Whether to stream its chunks
35+
* @param {boolean} [streamsInput] - Whether to give it as an async iterable
36+
* of its chunks
37+
* @param {number} threads - The number of threads the run uses
3538
* @returns {Promise<unknown>}
3639
*/
37-
const getDependencyInput = async (dependsOn, streamed) => {
40+
const getDependencyInput = async (dependsOn, streamsInput, threads) => {
3841
if (!dependsOn) {
3942
return undefined;
4043
}
4144

42-
return streamed ? cache.stream(dependsOn) : cache.consume(dependsOn);
45+
if (!streamsInput) {
46+
return cache.consume(dependsOn);
47+
}
48+
49+
if (threads > 1) {
50+
return cache.stream(dependsOn);
51+
}
52+
53+
// With one thread nothing runs alongside, so streaming would only keep
54+
// every stage's data alive at once: the input is collected whole first,
55+
// and given as its only chunk
56+
const whole = await cache.consume(dependsOn);
57+
58+
return once(whole);
4359
};
4460

4561
/**
@@ -76,11 +92,10 @@ const createGenerator = () => {
7692
cache.store(
7793
specifier,
7894
(async () => {
79-
// With one thread nothing runs alongside, so streaming would only keep
80-
// every stage's data alive at once: each stage takes its input whole
8195
const dependencyInput = await getDependencyInput(
8296
dependsOn,
83-
streamsInput && configuration.threads > 1
97+
streamsInput,
98+
configuration.threads
8499
);
85100

86101
generatorsLogger.debug(`Starting "${name}"`);

‎packages/core/src/generators/metadata/index.mjs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ export default {
1616

1717
hasParallelProcessor: true,
1818

19+
streamsInput: true,
20+
1921
markdown: {
2022
remarkPlugins: [
2123
'remark-parse',

‎packages/core/src/generators/metadata/types.d.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { Position } from 'unist';
33

44
export type Generator = GeneratorMetadata<
55
{},
6-
Generate<Array<Root>, AsyncGenerator<MetadataEntry>>,
6+
Generate<AsyncIterable<Array<Root>>, AsyncGenerator<MetadataEntry>>,
77
ProcessChunk<Root, MetadataEntry, Record<string, string>>
88
>;
99

‎packages/core/src/generators/types.d.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ declare global {
7373
/**
7474
* Receive the dependency's output as an async iterable of its chunks, as
7575
* they are produced, instead of one collected array. With one thread, the
76-
* input is still a collected array, so accept both.
76+
* input is collected first and arrives as its only chunk.
7777
*/
7878
streamsInput?: boolean;
7979

‎packages/core/src/utils/__tests__/generators.test.mjs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
getVersionFromSemVer,
88
coerceSemVer,
99
getCompatibleVersions,
10+
once,
1011
} from '../generators.mjs';
1112

1213
describe('getEntryDescription', () => {
@@ -138,3 +139,11 @@ describe('getCompatibleVersions', () => {
138139
assert.equal(result.length, 2);
139140
});
140141
});
142+
143+
describe('once', () => {
144+
it('gives a value as the only chunk', async () => {
145+
const chunks = await Array.fromAsync(once([1, 2]));
146+
147+
assert.deepEqual(chunks, [[1, 2]]);
148+
});
149+
});

0 commit comments

Comments
 (0)