bounded-concurrency, and std mapLimit: a few tasks at a time #14

Merged
sionzee merged 3 commits from rules/bounded-concurrency into main 2026-11-04 21:28:20 +01:00
Owner

What

New rule bounded-concurrency (warn in recommended.json). It reports Promise.all(...) or Promise.allSettled(...) when the argument is directly list.map(cb) or Array.from(list, cb) and:

  • the list's length isn't fixed in the code. Fixed means an array literal without spreads, a const bound to one, or a binding or parameter with a tuple type ([A, B], readonly [A, B]); those are left alone.
  • the callback starts work. That means it is async, a function reference, has a block body, or its expression body calls something (call, new, await). jobs.map((job) => job.done) only picks promises that already exist and is not reported.

map starts every task before Promise.all sees one, so a list of 10,000 items means 10,000 requests, open files or queries at once. That leads to EMFILE, rate limits, or the pool queueing everything anyway.

There is no quick fix. mapLimit resolves to a Result, so swapping it in changes the type at the use site, and a mechanical rewrite would leave the code broken.

New std helper mapLimit(items, limit, fn, signal?) in @evobug/safe-ts-std/async. Its error handling follows the other helpers in async.ts: it never rejects.

  • It resolves to U[] in the order of items, or to Err with the first failure (a rejection, or a synchronous throw from fn).
  • fn(item, index, signal) gets a signal. After the first failure, or when the caller's signal aborts, no new item starts and that signal aborts. The Err then holds the failure or the caller's abort reason.
  • A limit that isn't a positive integer resolves to Err(RangeError).
  • The abort listener on the caller's signal is removed once it is done.
  • For allSettled-style "one outcome per item", the docs show (item) => unsafeAsync(() => work(item)). I didn't add a second helper for that.

Analysis change (analyze.rs): a mapLimit imported from @evobug/safe-ts-std/async is treated like unsafeAsync. Its callback runs right away (async allowed), and whatever the callback throws or rejects with counts as caught. Without this, mapLimit(files, 4, (f) => upload(f)) with a propagating upload was reported as uncaught-propagation, since any callback to an unknown function counts as detached. Only function arguments are guarded, so a throwing expression in items is still reported. A discarded await mapLimit(...) still gets must-use-result; I checked that manually inside the demo project.

Examples that are now reported, rightly: docs/guide/async.md "uploadTogether" did Promise.all(files.map(...)). It now uses mapLimit(files, 4, ...), and the prose says that this version returns an Err rather than propagating. No other example changed: examples/demo, examples/vue, the docs Vue demo components and the playground presets report exactly what they did before (diffed per file and location).

Docs: rule page docs/rules/bounded-concurrency.md, a mapLimit section in the std-helpers guide, both README tables, docs/README.md, the sidebar (Failures group) and the oxlint plugin.

Tests

  • New fixture fixtures/bounded_concurrency/main.ts: 7 reported cases and 6 accepted ones (literal, const literal, tuple, existing promises, Promise.all([a, b]), Promise.race).
  • fixtures/propagation_async: mapLimit callbacks (expression and async bodies) record caught: Gone.
  • packages/std/test/async.test.ts: 8 new mapLimit tests. They cover order and the concurrency bound, the empty list, fail-fast (nothing new started, running signal aborted with the reason), a synchronous throw, the caller's signal before and during the run, listener removal, bad limits, and per-item Results via unsafeAsync.
  • Rebased onto main at 1fe2d1d (head c41eeaf), which includes #5 (call-following), #11 (rejections vs throws, narrowing catches) and #6 (fetch-signal). The textual conflicts were only in the rule lists, README tables and sidebar: bounded-concurrency goes right after fetch-signal in each, and analyze.rs runs megamorphic, fetch_signal, then concurrency. Three things had to change for main:
    • Call-following (#5) follows ns.fn() through namespace imports, so import * as asyncStd from "@evobug/safe-ts-std/async"; asyncStd.mapLimit(ids, 4, (id) => load(id)) reported the callback's PropagateError as uncaught-propagation. is_map_limit now recognises the namespace form too, and fixtures/propagation_async has a case for it. I also checked by hand that what #5 newly follows (methods such as store.get(id) and api.find(id), namespace-imported functions, nested helpers) is recorded as caught inside a mapLimit callback, the same as inside unsafeAsync.
    • #11's promises fixture does await Promise.all(ids.map((id) => viaReturn(id))) over a readonly string[]. bounded-concurrency reports it, rightly, so that line now expects it. Under #11's analysis, a mapLimit callback that returns a rejecting promise from a non-async function, or throws before making its promise, is recorded as caught (checked by hand).
    • The npm packages work (#12): scripts/verify-packages.mjs now imports mapLimit from the published @evobug/safe-ts-std/async and runs it. ./async was already in std's exports, so nothing else needed wiring.
  • After the rebase:
    • cargo nextest run --workspace: 104 passed, 0 failed (the earlier features failure was fixed on main by #23).
    • npm run test:std: 138 passed, 0 failed.
    • npm run test:vite, npm run typecheck, npm run test:docs: passed.
    • node scripts/verify-packages.mjs: all package checks passed (Linux x64 addon only).
    • safe-ts check on examples/demo (22 problems, the demo's intended ones) and examples/vue (none): no bounded-concurrency reports.

Left out / uncertain

  • The rule can't know a list's real length. Lists that are short by construction but untyped (3 tabs, a chunk of 10) are still reported; the page says so and suggests a tuple type or mapLimit.
  • Not checked: promises collected in a loop first (promises.push(f(x))), settleAll(items.map(...)), Promise.race/any, and .map chains with something in between (items.filter(...).map(...) is checked, but items.map(...).filter(...) is not).
  • mapLimit re-exported through a project's own barrel file is not recognised (only a direct import or a namespace import of @evobug/safe-ts-std/async), so its callbacks are still treated as detached.

🤖 Generated with Claude Code

## What **New rule `bounded-concurrency`** (warn in `recommended.json`). It reports `Promise.all(...)` or `Promise.allSettled(...)` when the argument is directly `list.map(cb)` or `Array.from(list, cb)` and: - the list's length isn't fixed in the code. Fixed means an array literal without spreads, a `const` bound to one, or a binding or parameter with a tuple type (`[A, B]`, `readonly [A, B]`); those are left alone. - the callback starts work. That means it is async, a function reference, has a block body, or its expression body calls something (call, `new`, `await`). `jobs.map((job) => job.done)` only picks promises that already exist and is not reported. `map` starts every task before `Promise.all` sees one, so a list of 10,000 items means 10,000 requests, open files or queries at once. That leads to `EMFILE`, rate limits, or the pool queueing everything anyway. There is no quick fix. `mapLimit` resolves to a `Result`, so swapping it in changes the type at the use site, and a mechanical rewrite would leave the code broken. **New std helper `mapLimit(items, limit, fn, signal?)`** in `@evobug/safe-ts-std/async`. Its error handling follows the other helpers in async.ts: it never rejects. - It resolves to `U[]` in the order of `items`, or to `Err` with the first failure (a rejection, or a synchronous throw from `fn`). - `fn(item, index, signal)` gets a signal. After the first failure, or when the caller's `signal` aborts, no new item starts and that signal aborts. The `Err` then holds the failure or the caller's abort reason. - A `limit` that isn't a positive integer resolves to `Err(RangeError)`. - The abort listener on the caller's signal is removed once it is done. - For `allSettled`-style "one outcome per item", the docs show `(item) => unsafeAsync(() => work(item))`. I didn't add a second helper for that. **Analysis change (analyze.rs):** a `mapLimit` imported from `@evobug/safe-ts-std/async` is treated like `unsafeAsync`. Its callback runs right away (async allowed), and whatever the callback throws or rejects with counts as caught. Without this, `mapLimit(files, 4, (f) => upload(f))` with a propagating `upload` was reported as `uncaught-propagation`, since any callback to an unknown function counts as detached. Only function arguments are guarded, so a throwing expression in `items` is still reported. A discarded `await mapLimit(...)` still gets `must-use-result`; I checked that manually inside the demo project. **Examples that are now reported, rightly:** `docs/guide/async.md` "uploadTogether" did `Promise.all(files.map(...))`. It now uses `mapLimit(files, 4, ...)`, and the prose says that this version returns an `Err` rather than propagating. No other example changed: `examples/demo`, `examples/vue`, the docs Vue demo components and the playground presets report exactly what they did before (diffed per file and location). Docs: rule page `docs/rules/bounded-concurrency.md`, a `mapLimit` section in the std-helpers guide, both README tables, `docs/README.md`, the sidebar (Failures group) and the oxlint plugin. ## Tests - New fixture `fixtures/bounded_concurrency/main.ts`: 7 reported cases and 6 accepted ones (literal, const literal, tuple, existing promises, `Promise.all([a, b])`, `Promise.race`). - `fixtures/propagation_async`: `mapLimit` callbacks (expression and async bodies) record `caught: Gone`. - `packages/std/test/async.test.ts`: 8 new `mapLimit` tests. They cover order and the concurrency bound, the empty list, fail-fast (nothing new started, running signal aborted with the reason), a synchronous throw, the caller's signal before and during the run, listener removal, bad limits, and per-item Results via `unsafeAsync`. - Rebased onto `main` at 1fe2d1d (head c41eeaf), which includes #5 (call-following), #11 (rejections vs throws, narrowing catches) and #6 (`fetch-signal`). The textual conflicts were only in the rule lists, README tables and sidebar: `bounded-concurrency` goes right after `fetch-signal` in each, and `analyze.rs` runs `megamorphic`, `fetch_signal`, then `concurrency`. Three things had to change for main: - Call-following (#5) follows `ns.fn()` through namespace imports, so `import * as asyncStd from "@evobug/safe-ts-std/async"; asyncStd.mapLimit(ids, 4, (id) => load(id))` reported the callback's `PropagateError` as `uncaught-propagation`. `is_map_limit` now recognises the namespace form too, and `fixtures/propagation_async` has a case for it. I also checked by hand that what #5 newly follows (methods such as `store.get(id)` and `api.find(id)`, namespace-imported functions, nested helpers) is recorded as caught inside a `mapLimit` callback, the same as inside `unsafeAsync`. - #11's `promises` fixture does `await Promise.all(ids.map((id) => viaReturn(id)))` over a `readonly string[]`. `bounded-concurrency` reports it, rightly, so that line now expects it. Under #11's analysis, a `mapLimit` callback that returns a rejecting promise from a non-async function, or throws before making its promise, is recorded as caught (checked by hand). - The npm packages work (#12): `scripts/verify-packages.mjs` now imports `mapLimit` from the published `@evobug/safe-ts-std/async` and runs it. `./async` was already in std's exports, so nothing else needed wiring. - After the rebase: - `cargo nextest run --workspace`: 104 passed, 0 failed (the earlier `features` failure was fixed on main by #23). - `npm run test:std`: 138 passed, 0 failed. - `npm run test:vite`, `npm run typecheck`, `npm run test:docs`: passed. - `node scripts/verify-packages.mjs`: all package checks passed (Linux x64 addon only). - `safe-ts check` on `examples/demo` (22 problems, the demo's intended ones) and `examples/vue` (none): no `bounded-concurrency` reports. ## Left out / uncertain - The rule can't know a list's real length. Lists that are short by construction but untyped (3 tabs, a chunk of 10) are still reported; the page says so and suggests a tuple type or `mapLimit`. - Not checked: promises collected in a loop first (`promises.push(f(x))`), `settleAll(items.map(...))`, `Promise.race`/`any`, and `.map` chains with something in between (`items.filter(...).map(...)` is checked, but `items.map(...).filter(...)` is not). - `mapLimit` re-exported through a project's own barrel file is not recognised (only a direct import or a namespace import of `@evobug/safe-ts-std/async`), so its callbacks are still treated as detached. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
sionzee force-pushed rules/bounded-concurrency from 0989be65ca to a55de265de
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m31s
2026-11-03 23:25:30 +01:00
Compare
sionzee force-pushed rules/bounded-concurrency from a55de265de
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m31s
to c41eeaf051
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m19s
2026-11-03 23:36:54 +01:00
Compare
Merge main into rules/bounded-concurrency
Some checks failed
Benchmarks / bench (pull_request) Failing after 2m58s
ad92a43654
Resolve conflicts with the PRs merged before this one: both sides kept
(rule lists, std exports, package checks, CLI usage, README).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch rules/bounded-concurrency 2026-11-04 21:28:20 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!14
No description provided.