Skip to content

ci: gate file size, function complexity and import cycles - #3765

Open
jordan-simonovski wants to merge 5 commits into
mainfrom
jordansimonovski/file-size-and-complexity-gates
Open

jordan-simonovski wants to merge 5 commits into
mainfrom
jordansimonovski/file-size-and-complexity-gates

Conversation

@jordan-simonovski

Copy link
Copy Markdown
Contributor

Summary

The 300-line file limit only existed as a sentence in the docs, and 239 source files are over it, nine of them past 2,000 lines. This makes the limit, and a set of function-level limits, something CI enforces, so the numbers stop rising while they are worked down.

Outcomes

  • A PR that pushes a source file past 300 lines, or adds lines to a file already over it, fails the ratchet. Tests, stories, migrations and .d.ts files are exempt.
  • A PR cannot raise a package's count of long functions (over 150 lines), complex functions (over 20), deep nesting (over 4), long parameter lists (over 4), nested ternaries or import cycles.
  • Each run of the lint job shows, on its summary page, the largest files and the warning count per rule and package against its limit. The report is advisory and cannot fail a run.
  • Moving a large file, or splitting it into parts no longer than the original, is accepted with yarn ratchet:update.

Behaviour changes for contributors

  • A small fix that adds lines to an oversized file now fails CI. The new code goes in another file, or the PR runs yarn ratchet:update --allow-growth and says why. Plain yarn ratchet:update only records files that shrank or moved.
  • Pre-commit now rejects a changed line that carries one of the new warnings, for example an edit to an existing nested ternary.
  • cli and hdx-eval had a warning limit of 0. They now sit at 74 and 44, the count the new rules find today.

Key decisions

  • The new lint rules are warnings held at today's count, not errors. Errors would need about 1,000 existing violations fixed or suppressed first.
  • File size is tracked per file, not as a count per package. A count would let a 4,000-line file keep growing.
  • The thresholds (150, 20, 4, 4) are a starting point and are open to debate in review.

Known limits

  • Two PRs that each pass can together take a file over 300 lines or add a warning, which fails main until one is fixed. 22 files sit between 281 and 300 lines.
  • A function already over a limit can keep growing, because the lint limit is a count.
  • The warning limits were measured on macOS. If CI on ubuntu counts differently, this PR's lint job will show it.

How to reproduce

Starting point: a checkout of this branch, yarn install done.

On main:

  1. Append a line to packages/api/src/utils/zod.ts (1,494 lines).
  2. Run yarn ratchet. It passes.

On this branch:

  1. Append a line to packages/api/src/utils/zod.ts.
  2. Run yarn ratchet. It fails with 1495 lines > baseline 1494.
  3. Run yarn ratchet:update. It refuses to record the growth.
  4. Run node scripts/ci/quality-report.mjs to see the report the lint job publishes.

How to test on Vercel preview

N/A, non-UI change.

The 300-line file limit was only written down, and 239 source files are
over it. The ratchet now fails when a file crosses 300 lines or a file
already over it grows. oxlint warns on long or complex functions, deep
nesting, long parameter lists, nested ternaries and import cycles, with
each package's warning limit set to today's count so it cannot rise.

The lint job writes a summary of file sizes and warnings by rule to the
run page so the totals are visible while they are worked down.
@jordan-simonovski
jordan-simonovski requested a review from a team as a code owner November 22, 2026 23:01
@vercel

vercel Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Nov 23, 2026 9:28pm UTC
hyperdx-storybook Ready Ready Preview Nov 23, 2026 9:28pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 2f4f8ea

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot added the review/tier-3 Standard — full human review required label Nov 22, 2026
@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

🟡 Tier 3 — Standard

Introduces new logic, modifies core functionality, or touches areas with non-trivial risk.

Why this tier:

  • Diff size: 613 production lines changed (Tier 2 max: < 250)
  • Cross-layer change: touches frontend (packages/app) + backend (packages/api) + shared utils (packages/common-utils)

Additional context: touches background tasks or the delivery pipeline lightly (27 lines, under the 30-line bar for Tier 4), 1 file(s) in private internal-tooling packages, excluded from the line count

Review process: Full human review — logic, architecture, edge cases.
SLA: First-pass feedback within 1 business day.

Stats
  • Production files changed: 9
  • Production lines changed: 613 (+ 155 in test files, excluded from tier calculation)
  • Branch: jordansimonovski/file-size-and-complexity-gates
  • Author: jordan-simonovski

To override this classification, remove the review/tier-3 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Duplicate code analysis

No new duplicate code introduced by this PR.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 107 in total (1.12%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

Comment thread scripts/ci/ratchet.mjs Outdated
}

/** A baselined file that is gone, or now under the limit, and was at least this long. */
function movedFrom(lines, current, baseline) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — movedFrom accepts any new large file as a 'move' if some unrelated baselined file has dropped out and was at least as long

movedFrom matches on line count alone. It also treats a file that shrank under 300 lines as a move source. Shrinkage is only a warning (compareSizes line 177), so stale entries stay in the committed baseline. Any later PR can then add an unrelated new file, for example a 900-line one while fixtures.ts: 1010 is stale, and plain yarn ratchet:update records it without --allow-growth. One source can also license any number of new files. Fix: require a real link to the source, such as the same basename or the source deleted in this diff, and consume each source once, or limit the parts' total to the source's size. Add a test where an unrelated new file and a stale entry exist together.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d342943, same change as the P1 thread: sources must be deleted, each is consumed by line count, and a same-named source is preferred. Not requiring a matching basename, since splitting a file into differently named parts is the case this exists for.

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

4 finding(s): 🔴 0 P0/P1 · 🟡 3 P2 · 🔵 1 P3

3 posted as inline comment(s) on the changed lines. 1 P3 folded at the bottom.

🔵 1 P3 — no action needed before merge
  • 🔵 P3 scripts/ci/quality-report.mjs:748 — commentBody repeats the totals logic from sizeSection and lintSection, and the limit parser repeats parseArgs → commentBody recomputes the excess-lines sum (also in sizeSection, line 703) and the per-package pkg total/limit string (also in lintSection, lines 719-729), so the PR comment and the step summary can drift apart. Fix: move excess(large) and packageTotals(byPackage) into helpers that both sections call. Separately, lintPackage reads the limit with its own /--max-warnings (\d+)/ regex. parseArgs in scripts/ci/oxlint-warnings.mjs already handles both --max-warnings N and --max-warnings=N. With the regex, a script written as --max-warnings=300 shows the limit as ?. Reuse parseArgs on the split script string instead.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found. This is CI tooling (ratchet scripts, oxlint config, a workflow step) with no production code path. The core move/split budget logic (findMoves/compareSizes/nextSizeBaseline), the merge-conclusion MERGE_HEAD line-intersection, and the always()/continue-on-error/outcome == 'success' workflow gating all hold up under analysis. All three prior review threads (move-source-must-be-deleted, per-source line budget, common-utils-built-before-report) are confirmed resolved. The findings below are reliability and test-coverage hardening on the new advisory report.

🟡 P2 — recommended

  • scripts/ci/quality-report.mjs:108 — The per-package loop in main() calls lintPackage → runOxlint, which calls process.exit(status || 2) when oxlint emits unparseable JSON (broken .oxlintrc.json, oxlint panic, OOM, maxBuffer overflow); one bad package aborts the whole report, so $GITHUB_STEP_SUMMARY gets nothing and the comment step (gated on outcome == 'success') silently never posts.
    • Fix: Wrap the per-package lintPackage call in try/catch and emit a placeholder row so a single failing package degrades to a partial report instead of total loss.
    • reliability
  • scripts/ci/quality-report.mjs:89 — lintPackage() (limit-regex parse, oxlint invocation, rule tally) and main() (--comment path, runUrl construction, writeFileSync) have no tests; only the three pure formatters are covered, leaving the error paths and env/arg handling to surface only in CI.
    • Fix: Add tests for lintPackage's limit parse and rule tally, and for main()'s --comment/runUrl branches including the GITHUB_RUN_ID-absent case.
    • testing, reliability
🔵 P3 nitpicks (5)
  • scripts/ci/quality-report.mjs:93 — The limit is scraped with /--max-warnings (\d+)/ (space form only), but the authoritative parseArgs in oxlint-warnings.mjs also accepts --max-warnings=N; if any package switches to the = form the report silently prints ? for its limit with no error.
    • Fix: Broaden to /--max-warnings[= ](\d+)/, or export the limit extraction from oxlint-warnings.mjs so one parser defines the accepted syntax.
    • maintainability, testing
  • scripts/ci/quality-report.mjs:74 — sizeSection and commentBody each independently recompute excess = reduce(sum + n - MAX_FILE_LINES) and render the same "N source files over 300 lines" sentence, so the two copies drift the moment the wording or limit semantics change.
    • Fix: Extract a single sizeSummary(large) helper returning {count, excess} and call it from both.
    • maintainability
  • scripts/ci/oxlint-warnings.mjs:201 — The merge-conclusion branch of changedLines (the MERGE_HEAD intersection and its try/catch fallback) is exercised only through intersectLines in isolation; the behaviorally important fallback branch has no end-to-end coverage.
    • Fix: Add a temp-git-repo test covering both the MERGE_HEAD-present intersection and the MERGE_HEAD-absent fallback.
    • testing
  • scripts/ci/ratchet.mjs:124 — The collectLargeFiles test only exercises src/__tests__/big.test.ts, which matches two SIZE_EXEMPT alternatives at once; __mocks__, __fixtures__, tests/, migrations/, .spec, .stories.tsx, and .d.ts are uncovered, so dropping one branch would fail no test.
    • Fix: Add an oversized fixture for each remaining exempt branch plus a non-exempt .tsx that must be collected.
    • testing
  • .github/workflows/main.yml:16 — pull-requests: write is granted to the whole lint job, which also runs PR-authored nx build and node --test code; on same-repo PRs that executes alongside a write-capable token (fork PRs get a read-only token automatically since the event is pull_request, not pull_request_target).
    • Fix: Move the comment step into a separate job with pull-requests: write that consumes the quality-comment.md artifact, leaving lint at contents: read.
    • security

Reviewers (6): correctness, reliability, testing, maintainability, security, project-standards, previous-comments. (The correctness and adversarial personas were dispatched but did not return before synthesis; the orchestrator's own analysis of the move-budget logic, MERGE_HEAD path, and workflow gating covered their scope and surfaced no additional P0/P1.)

Testing gaps:

  • scripts/ci/quality-report.mjs: lintPackage() and main() (including the runOxlint failure path) have no coverage.
  • scripts/ci/oxlint-warnings.mjs: the changedLines MERGE_HEAD merge path and its fallback are untested end-to-end.
  • scripts/ci/ratchet.mjs: most SIZE_EXEMPT branches and the findMoves same-basename tie-break are never exercised.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

❌ 1 test failed • 476 passed • 1 skipped • 1086s

Status Count
✅ Passed 476
❌ Failed 1
⚠️ Flaky 8
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

The report was only on the run summary page, which nobody opens. The lint
job now posts it as one comment per PR, updated on each push, with the
tables collapsed.
Comment thread scripts/ci/ratchet.mjs Resolved
Comment thread .github/workflows/main.yml Resolved
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Code quality report

  • 239 source files over 300 lines, 100616 lines over the limit in total
  • oxlint warnings (count/limit): api 309/309, app 785/785, cli 74/74, common-utils 233/233, hdx-eval 44/44

Full report

A baselined file that shrank under 300 lines, or any unrelated deleted
file, let a new oversized file through plain ratchet:update. A source now
has to be gone from disk and covers new files only up to its own line
count. Also builds common-utils before the quality report so its
type-aware counts match what ci:lint gates on.
runs-on: ubuntu-24.04
permissions:
contents: read
pull-requests: write

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — The whole lint job now gets pull-requests: write, though only the last comment step needs it

Every step in the job runs with a token that can write to PRs, including yarn install lifecycle scripts, nx tasks and PR-authored scripts, and so do push runs, which never comment. Only the comment step needs that scope. Fix: drop pull-requests: write from lint, upload quality-comment.md as an artifact, and post it from a small follow-up job (needs: lint, if: github.event_name == 'pull_request') that alone has pull-requests: write.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

wrn14897
wrn14897 previously approved these changes Nov 23, 2026
Warning limits recounted on top of main's lower ones (api 309, app 785),
and the file size baseline refreshed for files that changed on main.

Concluding a merge no longer fails pre-commit on warnings in lines that
came in unchanged from the other parent.
id: quality
if: always()
continue-on-error: true
timeout-minutes: 3

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — The 'advisory' quality report can still time out and fail the whole lint job

continue-on-error and the step's 3-minute timeout-minutes do not protect against the job's timeout-minutes: 8 (line 12). If the job runs past 8 minutes, GitHub fails the job, not just the step. This step rebuilds common-utils and then runs a second type-aware oxlint over all five packages, after ci:lint has already linted them (on push runs, every package via run-many). That can add up to 3 minutes to the job. If the limit is hit, the advisory report turns the lint job red, and on push runs it also skips Save nx computation cache (line 105). Fix: raise the job timeout by the step's budget, or move the report into its own job so it cannot affect the gating job.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

# --max-warnings. This only makes the totals visible on the run page.
- name: Code quality report
id: quality
if: always()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — if: always() keeps the report running after the run is cancelled

The workflow sets concurrency.cancel-in-progress: true, so a new push cancels the old run. always() still runs on cancellation, so the cancelled run keeps rebuilding common-utils and linting every package for up to 3 minutes, holding the runner. The comment step at line 90 has the same problem. Fix: use !cancelled() in both conditions.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

Comment thread scripts/ci/ratchet.mjs
for (const [file, max] of Object.entries(baseline)) {
if ((current[file] ?? 0) < max) {
messages.push(
`! ${file}: ${current[file] ?? `under ${MAX_FILE_LINES + 1}`} lines < baseline ${max} — run \`yarn ratchet:update\` to lock the improvement in`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — A deleted or moved file is reported as 'under 301 lines'

When a baselined file is gone from disk (moved or split), current[file] is undefined, so the second loop prints ! a.ts: under 301 lines < baseline 500. That sits next to the moved or split from a.ts error and tells the contributor the file still exists and shrank. Fix: pass exists into this branch and print deleted / moved when !exists(file), keeping under 301 for files that really shrank.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 2f4f8eaf Deployed Nov 23, 2026 by vercel[bot]
Preview – hyperdx-storybook — 2f4f8eaf Deployed Nov 23, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-3 Standard — full human review required

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants