Skip to content

refactor: Rip out Router.staticCache - #172

Merged
nielsenko merged 2 commits into
serverpod:mainfrom
nielsenko:rip-out-static-cache
Sep 18, 2025
Merged

nielsenko merged 2 commits into
serverpod:mainfrom
nielsenko:rip-out-static-cache

Conversation

@nielsenko

@nielsenko nielsenko commented Sep 17, 2025 •

Copy link
Copy Markdown
Collaborator

Description

This PR disables an optimization in the Router regarding static paths, ie. paths without any dynamic elements (/:id/, /*/, /**).

It does so because a bug was identified that caused LookupResult to contain wrong matched and remaining properties on subsequent lookups in certain cases.

Related Issues

Fixes: #173

Pre-Launch Checklist

Please ensure that your PR meets the following requirements before submitting:

  • This update focuses on a single feature or bug fix. (For multiple fixes, please submit separate PRs.)
  • I have read and followed the Dart Style Guide and formatted the code using dart format.
  • I have referenced at least one issue this PR fixes or is related to.
  • I have updated/added relevant documentation (doc comments with ///), ensuring consistency with existing project documentation.
  • I have added new tests to verify the changes.
  • All existing and new tests pass successfully.
  • I have documented any breaking changes below.

Breaking Changes

  • Includes breaking changes.
  • No breaking changes.

This just disables an internal optimization.

Summary by CodeRabbit

  • New Features
    • No user-facing feature changes.
  • Performance
    • Reduced memory overhead and simplified route lookups by removing redundant caching, improving consistency under dynamic route updates.
  • Refactor
    • Simplified routing internals without altering public APIs or configuration.
  • Bug Fixes
    • None.
  • Documentation
    • None.
  • Tests
    • None.
  • Chores
    • None.

@coderabbitai

coderabbitai Bot commented Sep 17, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Removed the Router static route cache and all related logic. add, attach, and lookup now operate solely on the unified PathTrie (_allRoutes). No public API signatures changed.

Changes

Cohort / File(s) Summary of Changes
Router internals (cache removal)
lib/src/router/router.dart
Eliminated _staticCache and dart:collection import; updated add(...) to use _allRoutes.addOrUpdateInPlace without caching; removed cache clearing in attach(...); simplified lookup(...) to query _allRoutes directly without pre/post caching.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Router
  participant PathTrie as _allRoutes (PathTrie)

  rect rgba(230,240,255,0.5)
  note right of Router: New flow (no static cache)
  Client->>Router: lookup(path)
  Router->>PathTrie: find(path)
  PathTrie-->>Router: RouteMatch | null
  Router-->>Client: result
  end
Loading
sequenceDiagram
  autonumber
  participant Client
  participant Router
  participant StaticCache as Static Cache (removed)
  participant PathTrie as _allRoutes (PathTrie)

  rect rgba(255,245,230,0.5)
  note right of Router: Old flow (with static cache)
  Client->>Router: lookup(path)
  Router->>StaticCache: get(path)
  alt hit
    StaticCache-->>Router: RouteMatch
    Router-->>Client: result
  else miss
    Router->>PathTrie: find(path)
    PathTrie-->>Router: RouteMatch | null
    Router->>StaticCache: put(path, result)
    Router-->>Client: result
  end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • feat: Router class #52 — Also modifies router.dart internals; likely earlier introduction or alteration of Router behavior that this PR updates by removing the static cache.
  • feat: Support Router.attach #62 — Touches add, attach, and lookup paths in Router; closely related to the current refactor toward unified _allRoutes handling without a separate cache.

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "refactor: Rip out Router.staticCache" is concise, follows conventional-commit style, and directly summarizes the primary change (removal of Router.staticCache/internal static-path caching) described in the diff and PR objectives, so it clearly communicates the main intent to reviewers scanning history.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Description Check ✅ Passed The PR description clearly explains what changed (disabling the Router static-path optimization) and why (a bug causing incorrect LookupResult matched/remaining values), includes a Related Issues entry ("Fixes: #173"), and provides the required template sections (Description, Related Issues, Pre-Launch Checklist, Breaking Changes). The Pre-Launch Checklist is mostly filled but shows an inconsistency where "referenced issue" is unchecked despite the "Fixes: #173" entry, and "added new tests" is unchecked so it is unclear whether tests were added to cover the regression. Overall the description is mostly complete and informative but would benefit from clarifying the testing status and fixing the checklist inconsistency.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codecov

codecov Bot commented Sep 17, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.82%. Comparing base (e21db89) to head (1036bff).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #172      +/-   ##
==========================================
- Coverage   91.84%   91.82%   -0.03%     
==========================================
  Files          85       85              
  Lines        3128     3118      -10     
  Branches     1620     1616       -4     
==========================================
- Hits         2873     2863      -10     
  Misses        255      255              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread lib/src/router/router.dart Resolved
@nielsenko
nielsenko requested review from a team and SandPod September 17, 2025 11:03
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Sep 17, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
lib/src/router/router.dart (2)

75-82: Doc comment still references “static first”; clarify post‑cache removal.

Now that there’s no separate static cache, make the comment reflect PathTrie matching semantics instead of an implementation detail.

Apply this diff:

-  /// The input [path] string is normalized before lookup. Static routes are
-  /// checked first, followed by dynamic routes in the trie.
+  /// The input [path] string is normalized before lookup. Matching follows
+  /// PathTrie semantics (static segments preferred over params/wildcards);
+  /// no separate static cache is used.

82-96: Add regressions for tail-wildcard/param edge cases.

Please add tests that previously triggered the bug:

  • Prefer static over wildcard: '/users' vs '/**'.
  • Tail wildcard with no params: '/files/**' matched by '/files' and '/files/a/b'.
  • Param vs wildcard precedence: '/:id' over '/**' for '/a'.

I can draft test cases if helpful.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44378bc and e1599f7.

📒 Files selected for processing (1)
  • lib/src/router/router.dart (1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: nielsenko
PR: serverpod/relic#62
File: lib/src/router/router.dart:31-38
Timestamp: 2025-05-09T07:55:38.627Z
Learning: In the Relic router implementation, attaching a sub-router doesn't require clearing the parent router's static cache because it only adds new routes without affecting existing cache entries. The sub-router's cache is cleared primarily to save memory.
Learnt from: nielsenko
PR: serverpod/relic#62
File: lib/src/router/router.dart:0-0
Timestamp: 2025-05-09T10:11:33.427Z
Learning: In the Router implementation, re-adding a route with the same path isn't currently allowed and will throw an ArgumentError from _allRoutes.add(), but handling cache invalidation or updates proactively is important for future-proofing in case route updates are later supported.
📚 Learning: 2025-05-09T07:55:38.627Z
Learnt from: nielsenko
PR: serverpod/relic#62
File: lib/src/router/router.dart:31-38
Timestamp: 2025-05-09T07:55:38.627Z
Learning: In the Relic router implementation, attaching a sub-router doesn't require clearing the parent router's static cache because it only adds new routes without affecting existing cache entries. The sub-router's cache is cleared primarily to save memory.

Applied to files:

  • lib/src/router/router.dart
📚 Learning: 2025-05-05T14:40:00.323Z
Learnt from: nielsenko
PR: serverpod/relic#52
File: lib/src/router/router.dart:37-53
Timestamp: 2025-05-05T14:40:00.323Z
Learning: In the Router and PathTrie implementation in Dart, both static and dynamic routes consistently throw ArgumentError when attempting to add duplicate routes, despite comments suggesting dynamic routes would be overwritten with a warning.

Applied to files:

  • lib/src/router/router.dart
📚 Learning: 2025-05-09T10:11:33.427Z
Learnt from: nielsenko
PR: serverpod/relic#62
File: lib/src/router/router.dart:0-0
Timestamp: 2025-05-09T10:11:33.427Z
Learning: In the Router implementation, re-adding a route with the same path isn't currently allowed and will throw an ArgumentError from _allRoutes.add(), but handling cache invalidation or updates proactively is important for future-proofing in case route updates are later supported.

Applied to files:

  • lib/src/router/router.dart
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Run Unit Tests (macos-latest, beta, upgrade)
  • GitHub Check: Run Unit Tests (macos-latest, beta, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, stable, downgrade)
  • GitHub Check: Run Unit Tests (macos-latest, 3.5.0, upgrade)
  • GitHub Check: Run Unit Tests (windows-latest, beta, upgrade)
🔇 Additional comments (1)
lib/src/router/router.dart (1)

61-64: LGTM: switching to PathTrie.addOrUpdateInPlace removes the brittle static-cache path.

Per‑verb duplicate protection is preserved via _RouterEntry.add(). Looks good.

@nielsenko
nielsenko marked this pull request as ready for review September 17, 2025 11:13
@nielsenko nielsenko self-assigned this Sep 17, 2025
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@CodeRabbit Add issue to re-enable the static route optimization without re-introducing this issue.

@coderabbitai

coderabbitai Bot commented Sep 17, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

I'll create an issue to track re-enabling the static route optimization. Let me first examine the changes to better understand what was removed.

Based on the changes and your request, I'll create an issue to track re-enabling the static route optimization properly.

@nielsenko I've created an issue to track re-enabling the static route optimization. The issue references this PR and your request, and has been assigned to you. It outlines the background context and what needs to be done to safely re-implement the optimization that was removed due to the bug.


🏁 Script executed:

#!/bin/bash
# Get more details about the changes made in this PR
git log --oneline -n 5
echo "=== Examining the router.dart file to understand the removed static cache ==="
cat lib/src/router/router.dart | head -50
echo "=== Looking for any comments or documentation about the static cache ==="
rg -n -C3 "static.*cache|staticCache|optimization" --type dart

Length of output: 5748


🏁 Script executed:

#!/bin/bash
# Create GitHub issue for re-enabling static route optimization
gh issue create \
  --title "Re-enable static route optimization without bug" \
  --body "## Background

This follows up on PR #172 (https://github.com/serverpod/relic/pull/172) where the static route cache optimization was disabled due to a bug.

The static cache optimization provided performance benefits for static paths (paths without dynamic elements like /:id/, /*/, /**/) by caching lookup results in \`Router._staticCache\`.

## Request

Re-enable the static route optimization while ensuring the underlying bug that caused its removal is properly fixed.

## Context

- Original optimization removed in PR #172: https://github.com/serverpod/relic/pull/172
- User request: https://github.com/serverpod/relic/pull/172#issuecomment-[current-comment-id]
- Requested by: @nielsenko

The optimization involved:
- Caching static route lookups in \`_staticCache\` 
- Priming cache entries when routes were added
- Clearing cache when sub-routers were attached
- Fast lookup path for cached static routes

## Acceptance Criteria

- [ ] Identify and fix the root cause of the bug that required disabling the optimization
- [ ] Re-implement static route caching with proper safeguards
- [ ] Add tests to prevent regression of the original bug
- [ ] Verify performance benefits are maintained" \
  --assignee nielsenko

Length of output: 45


@nielsenko I've successfully created issue #174 to track re-enabling the static route optimization: #174

The issue includes:

  • Background context referencing this PR where the optimization was disabled
  • Details about what the static cache optimization provided
  • Clear acceptance criteria for safely re-implementing it
  • Assignment to you as requested
  • References to this PR and your comment as backlinks

The issue is now available for tracking the work to restore the performance benefits of static route caching while ensuring the underlying bug is properly addressed.

@SandPod SandPod left a comment

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.

Please add a test that validates the bug is no longer present.

@SandPod

SandPod commented Sep 18, 2025

Copy link
Copy Markdown
Contributor

^ A bit harsh comment. Changes are fine but please add a test that validates the bug no longer exists and ensures we don't run into the same issue again in the future.

@nielsenko

Copy link
Copy Markdown
Collaborator Author

Please add a test that validates the bug is no longer present.

Done

@nielsenko
nielsenko requested a review from SandPod September 18, 2025 08:26

@SandPod SandPod left a comment

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.

👍

@nielsenko

Copy link
Copy Markdown
Collaborator Author

Rebased on top of main

@nielsenko
nielsenko merged commit b708b9b into serverpod:main Sep 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ctx.remainingPath differs for the same path

2 participants