Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔧 chore(alint): add no-benchmark-in-tests rule (#20647)

Arvin Xuc43e39cd4a92
diff --git a/alint.config.toml b/alint.config.toml
index ed5e5f0b5f7..a7e4f33a2dd 100644
--- a/alint.config.toml
+++ b/alint.config.toml
@@ -546,3 +546,24 @@ files = [ "packages/alint/fixtures/no-privileged-untrusted-electron/**" ]
lobehub = "./packages/alint/rules"
[config.group.rules]
"lobehub/no-privileged-untrusted-electron" = "warn"
+
+# Tests: a unit test asserts on behaviour, never on how long a wall-clock
+# measurement happened to take. Scope is every business test in the repo;
+# `packages/database` is left out on purpose — its query-time guards are
+# deliberate and run in the DB package's single-process suite.
+[[config.group]]
+files = [ "**/*.test.ts", "**/*.test.tsx" ]
+ignores = [ "packages/database/**", "packages/alint/fixtures/**" ]
+
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+
+[config.group.rules]
+"lobehub/no-benchmark-in-tests" = "warn"
+
+[[config.group]]
+files = [ "packages/alint/fixtures/no-benchmark-in-tests/**" ]
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+[config.group.rules]
+"lobehub/no-benchmark-in-tests" = "warn"
diff --git a/packages/alint/README.md b/packages/alint/README.md
index 472bb3675a6..56211ac31db 100644
--- a/packages/alint/README.md
+++ b/packages/alint/README.md
@@ -15,6 +15,7 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)
| `no-mode-flags` | warn | `src/**/*.tsx` | `compose-atoms` skill |
| `no-unguarded-response-field` | error | `src/**/*.tsx` | a newer client must survive an older server omitting a response field |
| `no-node-in-browser` | error | browser code in `src/` (not `app/`, `libs/`), package `*.tsx` | no Node-only npm package where the SPA runs it (paths: ESLint) |
+| `no-benchmark-in-tests` | warn | `**/*.test.ts(x)` except `packages/database` | a unit test asserts on behaviour, not on a wall-clock measurement |
| `no-unsafe-user-url-fetch` | warn | `apps/server/src` | user-controlled URLs must use SSRF-safe transport (#16601) |
| `no-unscoped-resource-mutation` | warn | database models/repositories | ownership checks for resource and junction mutations (#13683, #16586) |
| `no-untrusted-path-io` | warn | server and Electron main process | confine uploaded/remote filenames before filesystem IO (#13684, #13937) |
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/bad-elapsed-timeout.ts b/packages/alint/fixtures/no-benchmark-in-tests/bad-elapsed-timeout.ts
new file mode 100644
index 00000000000..9d651e5e3bd
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/bad-elapsed-timeout.ts
@@ -0,0 +1,16 @@
+// Fixture: a timeout contract asserted by timing the real call.
+import { describe, expect, it } from 'vitest';
+
+import { flushScheduledWork } from '../scheduleAfterResponse';
+
+describe('flushScheduledWork', () => {
+ it('stops waiting at the timeout and leaves the work running', async () => {
+ const startedAt = Date.now();
+ const flushed = await flushScheduledWork({ timeoutMs: 10 });
+ const elapsed = Date.now() - startedAt;
+
+ expect(flushed).toBe(false);
+ // alint-expect
+ expect(elapsed).toBeLessThan(60);
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/bad-linear-time-guard.ts b/packages/alint/fixtures/no-benchmark-in-tests/bad-linear-time-guard.ts
new file mode 100644
index 00000000000..72df64178de
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/bad-linear-time-guard.ts
@@ -0,0 +1,16 @@
+// Fixture: a complexity guard proven with a stopwatch instead of a deterministic signal.
+import { describe, expect, it } from 'vitest';
+
+import { parseGoalCommand } from '../goalCommand';
+
+describe('parseGoalCommand', () => {
+ it('scans adversarial separator runs in linear time', () => {
+ const input = `lh goal create "${'a;'.repeat(20_000)}`;
+
+ const startedAt = performance.now();
+ const result = parseGoalCommand(input);
+ // alint-expect
+ expect(performance.now() - startedAt).toBeLessThan(1000);
+ expect(result).toBeUndefined();
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/bad-redos-timing.ts b/packages/alint/fixtures/no-benchmark-in-tests/bad-redos-timing.ts
new file mode 100644
index 00000000000..e3d4795a108
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/bad-redos-timing.ts
@@ -0,0 +1,17 @@
+// Fixture: a ReDoS guard asserted with a wall-clock bound.
+import { describe, expect, it } from 'vitest';
+
+import { extractStatusCodeFromError } from '../googleErrorParser';
+
+describe('extractStatusCodeFromError', () => {
+ it('should not be vulnerable to ReDoS attacks', () => {
+ const maliciousInput = `Error ${'a'.repeat(10_000)} [not matching]`;
+
+ const startTime = Date.now();
+ extractStatusCodeFromError(maliciousInput);
+ const endTime = Date.now();
+
+ // alint-expect
+ expect(endTime - startTime).toBeLessThan(100);
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/good-fake-timers.ts b/packages/alint/fixtures/no-benchmark-in-tests/good-fake-timers.ts
new file mode 100644
index 00000000000..d28be0dfa29
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/good-fake-timers.ts
@@ -0,0 +1,17 @@
+// Fixture carve-out: a timeout contract driven by a fake clock, not a real one.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { flushScheduledWork } from '../scheduleAfterResponse';
+
+describe('flushScheduledWork', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('stops waiting at the timeout', async () => {
+ const flushed = flushScheduledWork({ timeoutMs: 10 });
+ await vi.advanceTimersByTimeAsync(10);
+
+ await expect(flushed).resolves.toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/good-logged-duration.ts b/packages/alint/fixtures/no-benchmark-in-tests/good-logged-duration.ts
new file mode 100644
index 00000000000..540756d224a
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/good-logged-duration.ts
@@ -0,0 +1,17 @@
+// Fixture carve-out: a clock read that is reported, never asserted on.
+import { describe, expect, it, vi } from 'vitest';
+
+import { warmCache } from '../warmCache';
+
+describe('warmCache', () => {
+ it('reports the entries it loaded', async () => {
+ const report = vi.fn();
+
+ const started = performance.now();
+ const result = await warmCache();
+ report({ elapsedMs: performance.now() - started, loaded: result.length });
+
+ expect(result).toHaveLength(3);
+ expect(report).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/good-ordering.ts b/packages/alint/fixtures/no-benchmark-in-tests/good-ordering.ts
new file mode 100644
index 00000000000..c7588e8b279
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/good-ordering.ts
@@ -0,0 +1,12 @@
+// Fixture carve-out: an ordering comparison that shares the matcher but times nothing.
+import { describe, expect, it } from 'vitest';
+
+import { serializeDocument } from '../serialize';
+
+describe('serializeDocument', () => {
+ it('keeps paragraphs in source order', () => {
+ const xml = serializeDocument([{ id: 'P1' }, { id: 'P2' }]);
+
+ expect(xml.indexOf('P1')).toBeLessThan(xml.indexOf('P2'));
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/good-stale-timestamp.ts b/packages/alint/fixtures/no-benchmark-in-tests/good-stale-timestamp.ts
new file mode 100644
index 00000000000..380d3791132
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/good-stale-timestamp.ts
@@ -0,0 +1,15 @@
+// Fixture carve-out: how old a stored timestamp is — an expiry bound, not a duration.
+import { describe, expect, it } from 'vitest';
+
+import { settleStaleRunning } from '../lease';
+
+describe('settleStaleRunning', () => {
+ it('claims the expired lease', async () => {
+ const orphanRow = { updatedAt: new Date(Date.now() - 30 * 60 * 1000), id: 'op-1' };
+
+ await settleStaleRunning(orphanRow);
+
+ const staleBefore = settleStaleRunning.mock.calls[0][1] as Date;
+ expect(Date.now() - staleBefore.getTime()).toBeGreaterThanOrEqual(10 * 60 * 1000 - 1000);
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/good-timeout-option.ts b/packages/alint/fixtures/no-benchmark-in-tests/good-timeout-option.ts
new file mode 100644
index 00000000000..94c967e766c
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/good-timeout-option.ts
@@ -0,0 +1,13 @@
+// Fixture carve-out: a millisecond field from production code, not a measured duration.
+import { describe, expect, it } from 'vitest';
+
+import { resolveUploadOptions } from '../remoteFileUpload';
+
+describe('resolveUploadOptions', () => {
+ it('keeps the upload timeout under the gateway limit', () => {
+ const options = resolveUploadOptions({ size: 1024 });
+
+ expect(options.timeout).toBeLessThan(30_000);
+ expect(options.retries).toBe(2);
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/good-timestamp-fixture.ts b/packages/alint/fixtures/no-benchmark-in-tests/good-timestamp-fixture.ts
new file mode 100644
index 00000000000..744a2b0634f
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/good-timestamp-fixture.ts
@@ -0,0 +1,16 @@
+// Fixture carve-out: a real clock used to build a timestamp, not to measure a duration.
+import { describe, expect, it } from 'vitest';
+
+import { buildSession } from '../session';
+
+describe('buildSession', () => {
+ it('expires one hour after the session was stamped', () => {
+ const now = Date.now();
+ const stale = now - 61_000;
+
+ const session = buildSession({ now, previousRefreshedAt: stale });
+
+ expect(session.createdAt).toBe(now);
+ expect(session.expiresAt).toBe(now + 3_600_000);
+ });
+});
diff --git a/packages/alint/fixtures/no-benchmark-in-tests/good-vi-waitfor.ts b/packages/alint/fixtures/no-benchmark-in-tests/good-vi-waitfor.ts
new file mode 100644
index 00000000000..5c0d5cf816c
--- /dev/null
+++ b/packages/alint/fixtures/no-benchmark-in-tests/good-vi-waitfor.ts
@@ -0,0 +1,14 @@
+// Fixture carve-out: waiting for an async condition without asserting on elapsed time.
+import { describe, expect, it, vi } from 'vitest';
+
+import { startPolling } from '../polling';
+
+describe('startPolling', () => {
+ it('polls until the callback reports done', async () => {
+ const onTick = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
+
+ await startPolling(onTick, { intervalMs: 5 });
+
+ await vi.waitFor(() => expect(onTick).toHaveBeenCalledTimes(2));
+ });
+});
diff --git a/packages/alint/rules/no-benchmark-in-tests/rule.alint.toml b/packages/alint/rules/no-benchmark-in-tests/rule.alint.toml
new file mode 100644
index 00000000000..f9b09874f97
--- /dev/null
+++ b/packages/alint/rules/no-benchmark-in-tests/rule.alint.toml
@@ -0,0 +1,29 @@
+name = "no-benchmark-in-tests"
+builtInAgent = "basic-structured"
+instruction = """
+You are reviewing one unit test file from the LobeHub repository.
+
+Team rule, from the owner's review: "除了 DB 测试之外,其他的业务场景中也有类似的单测 benchmark 场景,用了那种真实的 timer,然后跑出来的效果就是 benchmark"; "test case 是并发跑的 这个很多时候不稳定的"; "开个 PR 写一个 alint 规则 … 有多少业务测试的代码在单测里写 Benchmark 了".
+
+A unit test asserts on behaviour, never on how long a wall-clock measurement happened to take. These tests run concurrently on shared CI machines, so a stopwatch reading (`Date.now()` / `performance.now()` delta) turned into an assertion is a benchmark hiding inside a unit test: the number is machine- and load-dependent, it flakes under the parallel runner, and it stops meaning anything once the machine is busy. A speed or complexity threshold belongs in a dedicated benchmark (`vitest bench`, `*.bench.ts`) that runs single-threaded, not in a `.test.ts`.
+
+Report a test case that measures elapsed wall-clock time with a real clock and asserts on the measured number:
+
+1. an assertion whose subject is an elapsed duration read from a real timer — `expect(Date.now() - start).toBeLessThan(100)`, `expect(performance.now() - startedAt).toBeLessThan(500)`, or `expect(elapsed)…` where `elapsed` / `duration` / `executionTime` / `queryTime` / `took` / `latency` was computed from `Date.now()` / `performance.now()` / `new Date()` in the same test case;
+2. the same measured across statements (`const start = performance.now()` … `const elapsed = performance.now() - start` … `expect(elapsed).toBeLessThan(500)`): anchor on the `expect(...)` line, and in the message name the operation being timed;
+3. a test whose stated purpose is a speed or complexity threshold — "completes in under 100ms", "scans … in linear time", "stays linear on long runs", "not vulnerable to ReDoS", "should be fast" — when it proves that with a stopwatch reading instead of a deterministic signal.
+
+Anchor on the line of the elapsed-time assertion (the `expect(...)` line). In the message, name the operation being timed and the threshold, and say that a wall-clock bound is unreliable because the suite runs concurrently. In the suggestion, replace the timing bound with an assertion on the observable outcome (return value, call counts, emitted events, call ordering), or drive the clock with fake timers (`vi.useFakeTimers()` + `vi.advanceTimersByTime()` / `advanceTimersByTimeAsync()`) when the test is really about a timeout or interval contract; if a real performance guard is wanted, move it to a dedicated single-threaded benchmark (`vitest bench` / `*.bench.ts`) rather than this concurrent unit test.
+
+Do not report:
+- a controlled clock: `vi.useFakeTimers()`, `vi.advanceTimersByTime()`, `vi.advanceTimersByTimeAsync()`, `vi.setSystemTime()`, `vi.runAllTimers()`, sinon fake timers, or any elapsed value derived from an advanced virtual clock;
+- `Date.now()` / `new Date()` used to build a value rather than to measure one: `createdAt`, an id, `exp`, `expiresAt`, `deadlineAt`, a stale-`updatedAt` fixture such as `Date.now() - 60_000`, `mtimeMs`;
+- an assertion about how old an already-stored timestamp is — `expect(Date.now() - staleBefore.getTime()).toBeGreaterThanOrEqual(10 * 60 * 1000)`, an expiry or staleness bound the test wrote itself — even when it is written as a clock difference;
+- an assertion on a field that merely carries milliseconds from production code — a `timeout` option, a batch's `durationMs`, `deadlines.totalMs`, an `expiresAt.getTime()` bound, a `max_tokens`-style numeric limit;
+- comparisons that share the matcher but are not elapsed time: `expect(a.indexOf('x')).toBeLessThan(b.indexOf('y'))`, lengths, versions, numeric ids, `toHaveLength`;
+- waiting for an async condition where the elapsed time itself is not asserted (`vi.waitFor`, `expect.poll`, a polling loop guarded by a deadline);
+- a clock read that is logged, passed to a mock, or written into metadata but never asserted on;
+- `*.bench.ts` files and `vitest bench` suites — a dedicated benchmark is the intended home, and they are outside this rule's concern.
+
+If an exclusion applies, return no finding. If uncertain, use low confidence rather than forcing a finding.
+"""