Skip to content

refactor(core): derive KrsEdge.cyclic at model construction so analyze() stops writing the AST - #3422

Merged
kompiro merged 8 commits into
mainfrom
refactor/2791-cyclic-flag-at-construction
Oct 31, 2026
Merged

kompiro merged 8 commits into
mainfrom
refactor/2791-cyclic-flag-at-construction

Conversation

@kompiro

@kompiro kompiro commented Oct 31, 2026 •

Copy link
Copy Markdown
Owner

Purpose

Closes #2791

analyze() stamped edge.cyclic = true onto the KrsFile it was handed, so the same parsed model rendered differently before and after analyze() ran. This implements the approved Design Doc (docs/design/cyclic-flag-at-model-construction.md, #3406).

Summary

KrsEdge.cyclic is now derived while a model is built: in the Parser's post-pass, and again by the ImportResolver on the merged model, where a cycle split across files first shows up (TPL-2221). analyze() only reads. The readers (edge[cyclic], layout, routing, draw.io) are unchanged. Diff renders opt out of cyclic styling, so their output stays the same.

Changes

  • parser/cyclic-dependencies.ts (new):
    • findCyclicDependencies(file) is the old walk made pure. It returns the cyclic edge set and the warnings.
    • markCyclicEdges(file) clears the flag and then sets it from that set.
    • The walk now runs on every parse, so it is hardened against inputs that main's analyze() alone used to see:
      • An explicit stack replaces recursion, which threw RangeError on a long sync chain.
      • Each cycle hop is marked once. A downward union-find over path depths skips hops that are already marked.
      • Each hop visits only its own parallel edges, through a (from, to) index.
      • When only marking, the walk builds no warnings and no cycle paths.
    • Differential runs against main's walk over more than 6000 random graphs (self-loops, parallel and labelled edges, shuffled order, deep chains with back edges) gave identical warnings (cyclePath, loc), flagged edges and parse flags.
  • parser/parser.ts and fs/import-resolver.ts: call markCyclicEdges next to the boundaryMembership builds.
  • resolver/warnings.ts: analyze() takes findCyclicDependencies(file).warnings, and detectCyclicDependencies is removed.
  • Diff opt-out:
    • resolveStyles gets a trailing options.cyclicTag. Every resolveStyles call in compile/compile-diff.ts passes NO_CYCLIC_TAG, including the deploy diff, whose unit-to-unit edges take the service edge's style.
    • diffEdgeArray copies only flagged edges, without the flag, so the identity-keyed crossSystemSource lookup still matches.
  • Tests:
    • resolver/model-immutability.test.ts covers AC 1 and AC 3. Every example and a cyclic fixture must stay deep-equal to their structuredClone after analyze, collectModelWarnings and each builder, and the same model must render the same on either side of analyze().
    • parser/cyclic-dependencies.test.ts covers:
      • the pure walk
      • a cross-file cycle under compileProject
      • a per-file flag cleared on the merged model
      • a 20000-service chain
      • the system and deploy diffs, checking class, colour and width.
    • Old tests that asserted parse → analyze → edge.cyclic now assert that parse sets the flag and that analyze leaves it alone.
  • docs/spec/tags-annotations*.md (and the bundled skill copies): [cyclic] is assigned at parse time, and not in diff views.
  • TPL-2791: fills in its related tests.
  • Changeset: patch for @karasu-tools/core, karasu and karasu-skills.

Measurements (main 61f3b2f7 vs this branch; byte comparison rerun after every walk change)

Byte comparison of each entry point over the 85 example files plus the Dify model:

Entry point Differs
compile, compileProject, buildAllViewsSvg, buildAllViewsSvgProject, buildDrawioProject, compileSystemDiff, buildAllViewsSvgDiffProject 0 / 86
buildDrillDownSvg, buildAllLayersSvg, buildDrawio 1 / 86 (Dify only: its one cycle is now drawn red, as compile already drew it)

Parser.parse, median of 40 runs:

Model main branch
Dify 11.2 ms 11.3 ms
200 services, 1000 dense sync edges 1.1 ms 1.3 ms

Shapes built to stress the walk (Parser.parse, single run):

Model main branch
Chain of 15000, every node also calls the root 91 ms 115 ms
Hub calling 20500 services that each call back (1.03 MB) 116 ms 109 ms
Chain of 20000 sync edges 20000-deep recursion in analyze throws parses

On the chain where every node calls the root, main's analyze did not finish in 120 s; on the branch it takes about 0.7 s at 15000 services, which is the size of the warnings themselves. Per keystroke the walk now runs twice (once in parse, once in analyze) instead of once.

Before / after

No rendering change (0 acceptance-test fences, 65 example files)

Only a model with a sync cycle changes, and no example has one. In the Dify model, its one cycle is now red in the All-layers panel, the live entity view, the drill-down export and buildDrawio. Before this change it was red only in the live view, karasu render and the all-views export.

Risk

High: docs/spec/tags-annotations.md, docs/spec/tags-annotations.ja.md (plus Medium packages/core/**).

How to revert

Revert the squash commit. Nothing outside the repo changes.

Preview URL

Scope filter (new-feature PRs only)

  • N/A — not a new-feature PR
  • Pulls implementation detail into the model (code generation, DB schema, function signatures, ...)
  • Pulls runtime metrics / operational state into the model (per-pod state, live metrics, deploy status, ...)
  • Pulls time-axis / high-frequency state into the model (sequence diagrams, execution logs, traces, ...)

Dependency & license impact

  • N/A — no production dependency added or bumped across a major version

Manual Verification Checklist

N/A — all covered by automated tests

TPL impact

Disposition: Designed against proactive TPL-2791 (added in #3406). Its checklist is turned into resolver/model-immutability.test.ts, whose PASSES table new passes join. TPL-2221 is covered by the cross-file cycle and stale-flag cases in parser/cyclic-dependencies.test.ts.

Related Docs

  • docs/design/cyclic-flag-at-model-construction.md (to be promoted to ADR-2791, superseding ADR-287)
  • docs/spec/tags-annotations.md, docs/spec/tags-annotations.ja.md
  • docs/test-perspectives/TPL-2791-read-passes-do-not-write-the-model.md

🤖 Generated with Claude Code

Local review

Reviewers: /engineering:code-review (fresh subagent), coderabbit CLI --deep

# Reviewer Sev Where Finding Disposition
1 engineering Minor packages/core/src/parser/cyclic-dependencies.ts Recursive DFS inside Parser.parse throws RangeError on a deep sync chain, refusing a well-formed document fixed in f05929c
2 engineering Minor packages/core/src/parser/cyclic-dependencies.ts Clearing a per-file flag on the merged model (delete edge.cyclic) is untested fixed in f05929c
3 engineering Trivial docs/spec/tags-annotations.md Spec does not say diff views skip [cyclic] and ignore a user edge[cyclic] rule fixed in 318da0b
4 engineering Trivial packages/core/src/compile/compile-diff.ts NO_CYCLIC_TAG in compileOrgDiff is defensive only declined: the design applies the opt-out to every resolveStyles call a diff makes, so a later org edge style cannot leak
5 engineering Minor packages/core/src/parser/cyclic-dependencies.ts Per-back-edge hop walk is quadratic on a chain whose nodes all call the root, now on every parse fixed in e1ff270
6 engineering Minor packages/core/src/parser/cyclic-dependencies.ts Marking a hop scans the whole out-list, quadratic for a hub with many callers that call back fixed in 397c0f0

Summary by CodeRabbit

  • New Features
    • Synchronous dependency cycles are marked when a model is loaded, including cycles that span files in a project.
    • Cyclic edges appear red in single-model views.
  • Bug Fixes
    • Diff views no longer display cycle styling or match [cyclic] edge rules; cycles are reported as warnings instead.
    • Collecting warnings no longer changes cycle markings on the model.
  • Documentation
    • Clarified how [cyclic] behaves in model and diff views.

kompiro and others added 8 commits October 31, 2026 00:38
…nalyze() (#2791)

analyze() stamped edge.cyclic onto the KrsFile it was handed, so the same
parsed model rendered differently before and after it ran. The cycle walk
is now a pure findCyclicDependencies() under parser/, and markCyclicEdges()
sets the flag while a model is built: in the Parser post-pass and again on
the ImportResolver's merged model, where a cycle split across files shows
up (TPL-2221). analyze() only takes the warnings.

Diff renders opt out of cyclic styling so they stay as they were: every
diff resolveStyles call leaves the cyclic virtual tag off, and
diffEdgeArray copies only flagged edges without the flag, keeping the
identity-keyed cross-system lookup intact.

The per-hop edge scan in the walk now reads the hop's own outgoing edges,
since the walk runs on every parse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Deep-compares every parsed example and a cyclic fixture with its
structuredClone after analyze, collectModelWarnings and each builder, and
checks that a model renders the same on either side of analyze(). Fills in
TPL-2791's related tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Updates the tags reference and its bundled skill copies, and adds the
changeset for core, the CLI and the skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…deep chains (#2791)

The cycle walk now runs inside Parser.parse, where a recursive DFS threw
RangeError on a long sync chain and turned a well-formed document into a
parse failure (the nest submission gate, the LSP). The explicit-stack walk
keeps the recursive visit order and one shared path, so the edge set,
cyclePath and loc are unchanged; a differential run against main's walk
over 400 random graphs matched.

Adds the cases the review found unfenced: a 20000-service chain parses,
and a flag a per-file parse set is cleared on the merged model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ge-heavy chains (#2791)

Marking a cycle walked every hop of the GRAY path per back edge, so a chain
whose every node also calls the root took quadratic time, now on every
parse (15000 services: 91 ms on main, 4.5 s here). A hop marked once has
nothing left to add, so a downward union-find over path depths skips the
hops already marked, and markCyclicEdges no longer builds the warnings or
their cycle paths. Same edge set and warnings as main's walk over 3600
random graphs; the 15000-service chain parses in 126 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…whole out-list (#2791)

Marking a hop scanned every outgoing edge of its source, so a hub calling
k services that each call back took O(k^2) on every parse (20500 services:
116 ms on main, 1.1 s before this). The adjacency now also indexes edges by
(from, to), and a hop visits only its own parallel edges; the walk still
iterates the out-list, so the order is unchanged. Same edge set and
warnings as main's walk over 3000 random graphs; the hub parses in 109 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kompiro kompiro added the risk: high Review tier High: human reads the diff label Oct 31, 2026
@coderabbitai

coderabbitai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 0ffd155 and 397c0f0.

Files selected for processing: 17
  • .changeset/cyclic-flag-at-model-construction.md
  • docs/spec/tags-annotations.ja.md
  • docs/spec/tags-annotations.md
  • docs/test-perspectives/TPL-2791-read-passes-do-not-write-the-model.md
  • packages/core/src/compile/compile-diff.ts
  • packages/core/src/diff/view-diff.ts
  • packages/core/src/fs/import-resolver.ts
  • packages/core/src/parser/cyclic-dependencies.test.ts
  • packages/core/src/parser/cyclic-dependencies.ts
  • packages/core/src/parser/parser.ts
  • packages/core/src/renderer/svg-renderer.test.ts
  • packages/core/src/resolver/model-immutability.test.ts
  • packages/core/src/resolver/style-resolver.ts
  • packages/core/src/resolver/warnings.test.ts
  • packages/core/src/resolver/warnings.ts
  • packages/skills/skills/karasu-author/reference/tags-annotations.md
  • packages/skills/skills/reverse-architecture/reference/tags-annotations.md

Included review availability: This review used your included allowance. 3 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 4 reviews per hour.

Walkthrough

Cycle detection now returns edge and warning results without marking edges during analysis. Parsing and import merging mark cycle edges. Diff views remove cyclic flags and disable cyclic styling. Tests cover model immutability, cross-file and large cycles, rendering, and diff behavior.

Changes: Cycle handling

Layer / File(s) Summary
Cycle discovery and model marking
packages/core/src/parser/cyclic-dependencies.ts, packages/core/src/parser/parser.ts, packages/core/src/fs/import-resolver.ts, packages/core/src/parser/cyclic-dependencies.test.ts
Cycle discovery returns cyclic edges and warnings. Parsing marks cycle edges, and import resolution re-marks edges after merging files. Tests cover large cycles and cycles across files.
Warning analysis and read-pass behavior
packages/core/src/resolver/warnings.ts, packages/core/src/resolver/warnings.test.ts, packages/core/src/resolver/model-immutability.test.ts, packages/core/src/renderer/svg-renderer.test.ts, docs/test-perspectives/TPL-2791-read-passes-do-not-write-the-model.md
analyze() uses cycle discovery to report warnings without changing edge flags. Tests check model immutability and compare rendering before and after analysis.
Diff views omit cyclic styling
packages/core/src/resolver/style-resolver.ts, packages/core/src/compile/compile-diff.ts, packages/core/src/diff/view-diff.ts, packages/core/src/parser/cyclic-dependencies.test.ts, docs/spec/tags-annotations*.md, packages/skills/skills/*/reference/tags-annotations.md, .changeset/cyclic-flag-at-model-construction.md
Diff style resolution disables the virtual cyclic tag, and diff edges have cyclic flags removed. Tests and tag references describe this behavior. The changeset declares patch releases for three packages.

Estimated code review effort: 4 (Complex) | ~40 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

  • kompiro/karasu#3406: Documents the cycle-marking design implemented in this pull request, including the diff-view opt-out.
Merge Risk: Minimal · up to 397c0

Cycle marking and diff rendering follow the documented design. No actionable issue remains to resolve before normal merge checks.

Security architecture risk: Low · up to 397c0

This is a contained change to when cycle information is computed and displayed. Construction avoids allocating diagnostic paths, and diff processing preserves source-model flags. No new privileged operation was identified. Resource limits for large untrusted diagrams remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Attacker-controlled graph structure can influence computation, memory use, and rendered cycle state in the caller's process. The inspected change does not add external authority or establish a new tenant, service, or data-store access path. Deployment-specific shared-process exposure remains unestablished.

Trust Boundaries and Controls

  • observed — Diff suppression is limited to derived edge presentation: flagged edges are copied without cyclic state, and the style option controls virtual-tag matching. Cycle-warning collection still uses the after model, so removing cycle styling does not remove that diagnostic path.

Resilience and Maintainability Implications

  • observed — Warning-mode discovery can still allocate cycle paths whose aggregate size grows quadratically on adversarial back-edge graphs. The base analyzer already constructed these paths. New parse and merge calls explicitly disable them, so this existing resource concern is not established as introduced or worsened by the PR.

Hardening Proposals

  • proposed — If untrusted diagrams are analyzed in a shared service, establish input and execution budgets or bound cycle-warning output. This would address the pre-existing diagnostic allocation behavior, not a verified new vulnerability in this PR.
Pre-merge checks: Passed 4
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title follows the required Conventional Commits format, uses the allowed refactor(core) type and scope, has an imperative subject without a trailing period, and accurately describes the main cha…
Linked Issues check Passed The PR addresses all coding requirements in #2791. Parser and import resolution mark cyclic edges during model construction. analyze() reads cycle results without writing to the model. The reported …
Out of Scope Changes check Passed The changes stay within #2791. The cycle-walk refactor, parser and import-resolver integration, diff styling opt-out, tests, documentation, skill copies, and changeset support immutable model construc…
Full details: Title check

Explanation

The title follows the required Conventional Commits format, uses the allowed refactor(core) type and scope, has an imperative subject without a trailing period, and accurately describes the main change.

Full details: Linked Issues check

Explanation

The PR addresses all coding requirements in #2791. Parser and import resolution mark cyclic edges during model construction. analyze() reads cycle results without writing to the model. The reported immutability tests cover analyze(), warning collection, and builders. The reported render tests compare output before and after analyze(). The reported example and Dify comparisons cover current entry points, including the documented Dify cycle change caused by correcting model-construction behavior. The implementation approach is not restricted by the issue acceptance criteria.

Full details: Out of Scope Changes check

Explanation

The changes stay within #2791. The cycle-walk refactor, parser and import-resolver integration, diff styling opt-out, tests, documentation, skill copies, and changeset support immutable model construction and preserve diff behavior. No unrelated production feature or dependency change is identified.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@kompiro
kompiro marked this pull request as ready for review October 31, 2026 01:02
@kompiro
kompiro merged commit 6b82d0e into main Oct 31, 2026
29 of 31 checks passed
@kompiro
kompiro deleted the refactor/2791-cyclic-flag-at-construction branch October 31, 2026 03:52
kompiro added a commit that referenced this pull request Oct 31, 2026
detectCyclicDependencies left warnings.ts when #3422 moved the cyclic flag
to model construction; the TPL body already names findCyclicDependencies
and markCyclicEdges in parser/cyclic-dependencies.ts.

Refs #3357

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kompiro added a commit that referenced this pull request Oct 31, 2026
…ations (#3425)

* docs(tpl): 2026-10 deprecation review, refresh 15 TPLs with stale citations

Repoint line-number citations whose code moved (index.ts split in #2038,
needsQuotes rewrite in #2707, diagLocFormatter in #2715, spec/CSS drift),
drop citations of sites the VS Code shared viewer removed (#3312), record
that the gh-aw consumer of TPL-2658/TPL-2786 left in #3423, and drop the
"experimental" facet headings that language v2.0 removed (#2677).

Refs #3357

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(tpl): address local review on the 2026-10 TPL review

Correct the BARE_ID_PATTERN history in TPL-1101 (the keyword copy was
RESERVED_KEYWORDS), repoint TPL-239's drifted cli/index.ts:442 citation to
program.parseAsync, drop an em dash in TPL-1503, and place TPL-2996's
origin section before the known patterns like TPL-2658/TPL-2786.

Refs #3357

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(tpl): name #3423 as the gh-aw removal in absent-path markers

#3421 tracks the revival; the workflows and their safety test were
removed by #3423 (ADR-3421).

Refs #3357

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(tpl): drop TPL-2791's citation of the function #3422 removed

detectCyclicDependencies left warnings.ts when #3422 moved the cyclic flag
to model construction; the TPL body already names findCyclicDependencies
and markCyclicEdges in parser/cyclic-dependencies.ts.

Refs #3357

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was successfully deployed

1 active deployment
preview — 397c0f03 Deployed Oct 31, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high Review tier High: human reads the diff

Projects

None yet

Development

Successfully merging this pull request may close these issues.

analyze() mutates the AST it is given, so a KrsFile renders differently before and after it

1 participant