Skip to content

Fix api routes and test validations#137

Closed
is0692vs wants to merge 7 commits intomainfrom
jules-8376435226217890193-cd1e1d2f
Closed

Fix api routes and test validations#137
is0692vs wants to merge 7 commits intomainfrom
jules-8376435226217890193-cd1e1d2f

Conversation

@is0692vs
Copy link
Contributor

@is0692vs is0692vs commented Mar 17, 2026

This PR addresses multiple test gaps, caching flaws, and error handling bugs across `apps/api` features.

Changes:

  • `papers.test.ts`: Updated `POST /api/papers creates paper with org_only visibility` to inspect `mockDb.batch` and verify the paperOrgs insertion for `org-1`. Modified `PATCH /api/papers/:id` tag tests to verify empty tag `" "` behavior mapping to empty arrays, which properly sets up status `200`.
  • `users.test.ts`: Replaced hardcoded max cache limit logic with injected bounds. Used a custom `MAX_CACHE_SIZE` environment variable (e.g. `3`) to test the search cache eviction branch without blocking loops. Removed duplicate missing-user test.
  • `papers.ts`: Enhanced upload cleanup flow. On `catch`, `Promise.allSettled` is used to track database record cleanups and R2 deletes properly. Rejected reasons are successfully filtered, explicitly logged with `paperId` context, and original `catch` error is re-thrown safely.
  • `users.ts`: Upgraded search results caching to proper MRU ordering on hit. Previously, caching did not track accessed elements and left them to age out based on absolute TTL. Now cache hits delete and re-insert to track order properly. Used dynamic c.env.MAX_CACHE_SIZE injection.
  • `validation.test.ts`: Increased robustness for validateSlug. Added assertions to correctly reject inputs with leading or trailing hyphens.

PR created automatically by Jules for task 8376435226217890193 started by @is0692vs

Greptile Summary

このPRは apps/api の複数のテストギャップ・キャッシュ不具合・エラーハンドリングのバグを修正します。主な変更はユーザー検索キャッシュへのLRUタッチ機能追加、ペーパーアップロード失敗時のクリーンアップフロー改善、テストカバレッジの強化、およびスラグバリデーションテストの拡充です。

  • users.ts: getCachedResults でキャッシュヒット時に delete + re-insert によるLRUタッチを実装。setCachedResultsmaxSize パラメータを追加し、c.env.MAX_CACHE_SIZENumber() で適切に変換して注入する形に変更。
  • papers.ts: アップロード失敗時の catch ブロックで Promise.allSettled の結果を収集し、R2/D1 クリーンアップ失敗を paperId 付きでログ出力。元エラーを正しく re-throw するよう改善。
  • papers.test.ts: insert モックを拡張して batch 引数の詳細検証を可能にし、クリーンアップ失敗ロギングと元エラー re-throw の新テストを追加。
  • users.test.ts: LRUタッチ動作・既存キー更新時の非退避を検証する新テストを追加。MAX_CACHE_SIZE テストを小さな env 変数で高速化。
  • validation.test.ts: validateSlug に対して先頭/末尾ハイフン、全ハイフン、最小長スラグ等のエッジケーステストを追加。

Confidence Score: 3/5

  • 本番コードの変更は堅牢だが、テストの信頼性に軽微な問題が残る
  • papers.tsusers.ts の本番コード変更は正確で意図した動作を実現している。一方、users.test.ts の新テストで vi.useFakeTimers()try/finally なしで使用されており、アサション失敗時にフェイクタイマーが後続テストに漏れ込むリスクがある。また users.tsMAX_CACHE_SIZE 定数がデッドコードとして残存している。
  • apps/api/src/routes/tests/users.test.ts — フェイクタイマーの後始末パターンを要確認

Important Files Changed

Filename Overview
apps/api/src/routes/users.ts キャッシュにLRUタッチ機能(delete+re-insert)を追加し、動的なMAX_CACHE_SIZEをenv経由で注入するよう変更。Number()変換も正しく実装されているが、未使用のMAX_CACHE_SIZE定数が残っている。
apps/api/src/routes/papers.ts アップロード失敗時のクリーンアップフローを改善。R2とD1のクリーンアップ失敗を個別に収集・ログ出力し、元のエラーを正しくre-throwする実装に更新。変更は堅牢で問題なし。
apps/api/src/routes/tests/users.test.ts LRUキャッシュ動作を検証する新テストを追加。ただしsetCachedResults does not evict another entryテスト内でvi.useFakeTimers()がtry/finallyなしで使用されており、テスト失敗時にフェイクタイマーが残り後続テストに影響する可能性がある。
apps/api/src/routes/tests/papers.test.ts insertモックを拡張してbatch引数の検証を可能にし、クリーンアップフローのテストを2件追加。未使用のthrown変数が残るが、全体的にカバレッジ向上に貢献している。
apps/api/src/utils/tests/validation.test.ts validateSlugに対して先頭/末尾ハイフン、ハイフンのみ、最小長スラグ+内部ハイフンのテストケースを追加。既存の実装(SLUG_RE)と整合しており、全テストは正しく通る見込み。

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["GET /api/users/search?q=xxx"] --> B{クエリ長 >= 2?}
    B -- No --> C["空リストを返す"]
    B -- Yes --> D["getCachedResults(cacheKey)"]
    D --> E{キャッシュヒット\nかつTTL有効?}
    E -- Yes --> F["delete + re-insert\nLRUタッチ"]
    F --> G["キャッシュデータを返す"]
    E -- No --> H["期限切れエントリ削除"]
    H --> I["DBクエリ実行"]
    I --> J["setCachedResults(key, results, maxSize)"]
    J --> K{既存キーあり?}
    K -- Yes --> L["delete して LRU 更新"]
    K -- No --> M{size >= maxSize?}
    M -- Yes --> N["先頭キーを削除\n最古エントリを退避"]
    M -- No --> O["新エントリを set"]
    L --> O
    N --> O
    O --> P["結果を返す"]
Loading

Comments Outside Diff (2)

  1. apps/api/src/routes/users.ts, line 75 (link)

    P2 未使用の定数 MAX_CACHE_SIZE がデッドコードになっている

    setCachedResults にはデフォルト引数 maxSize = 1000 が追加され、呼び出し元では c.env.MAX_CACHE_SIZE を利用するようになりました。そのため、モジュールスコープで宣言された const MAX_CACHE_SIZE = 1000 はどこからも参照されなくなっています。

    (行を削除)

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/api/src/routes/users.ts
    Line: 75
    
    Comment:
    **未使用の定数 `MAX_CACHE_SIZE` がデッドコードになっている**
    
    `setCachedResults` にはデフォルト引数 `maxSize = 1000` が追加され、呼び出し元では `c.env.MAX_CACHE_SIZE` を利用するようになりました。そのため、モジュールスコープで宣言された `const MAX_CACHE_SIZE = 1000` はどこからも参照されなくなっています。
    
    
    (行を削除)
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. apps/api/src/routes/__tests__/users.test.ts, line 322-326 (link)

    P1 vi.useFakeTimers()try/finally なしで使用されている

    vi.useFakeTimers() を呼んだ後、app.request() が例外をスローした場合や、その後のアサション(line 329)が失敗した場合、vi.useRealTimers() が呼ばれずフェイクタイマーが残り続けます。これにより後続のテストがフェイクタイマーの影響を受け、断続的な失敗の原因となります。

    同じファイル内の GET /api/users/search handles cache eviction when key exists but expired(line 246)は try/finally パターンを正しく使用しているので、同様の実装を推奨します:

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/api/src/routes/__tests__/users.test.ts
    Line: 322-326
    
    Comment:
    **`vi.useFakeTimers()``try/finally` なしで使用されている**
    
    `vi.useFakeTimers()` を呼んだ後、`app.request()` が例外をスローした場合や、その後のアサション(line 329)が失敗した場合、`vi.useRealTimers()` が呼ばれずフェイクタイマーが残り続けます。これにより後続のテストがフェイクタイマーの影響を受け、断続的な失敗の原因となります。
    
    同じファイル内の `GET /api/users/search handles cache eviction when key exists but expired`(line 246)は `try/finally` パターンを正しく使用しているので、同様の実装を推奨します:
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: apps/api/src/routes/__tests__/users.test.ts
Line: 322-326

Comment:
**`vi.useFakeTimers()``try/finally` なしで使用されている**

`vi.useFakeTimers()` を呼んだ後、`app.request()` が例外をスローした場合や、その後のアサション(line 329)が失敗した場合、`vi.useRealTimers()` が呼ばれずフェイクタイマーが残り続けます。これにより後続のテストがフェイクタイマーの影響を受け、断続的な失敗の原因となります。

同じファイル内の `GET /api/users/search handles cache eviction when key exists but expired`(line 246)は `try/finally` パターンを正しく使用しているので、同様の実装を推奨します:

```suggestion
        vi.useFakeTimers();
        try {
        vi.setSystemTime(Date.now() + 61 * 1000);
        await app.request(`/api/users/search?q=aa`, { headers: { Authorization: `Bearer ${token}` } }, tinyEnv);
        } finally {
        vi.useRealTimers();
        }
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: apps/api/src/routes/__tests__/papers.test.ts
Line: 113-129

Comment:
**`thrown` 変数が宣言されているが使用されていない**

`thrown``catch` ブロックで `true` にセットされていますが、その後のアサションでは一切参照されていません。テストのコメントには「either thrown or 500 response」と記載されており、`thrown` フラグを使った分岐確認は意図されていないようです。デッドコードを削除してテストの意図を明確にすることを推奨します。

```suggestion
        try {
            await app.request(
                "http://localhost/api/papers",
                {
                    method: "POST",
                    headers: {
                        Authorization: `Bearer ${token}`,
                        Origin: "http://localhost:3000",
                    },
                    body: form,
                },
                { ...env, BUCKET: mockBucket } as any,
            );
        } catch {
            // エラーが伝播された場合も許容(500レスポンスまたはスロー)
        }
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: apps/api/src/routes/users.ts
Line: 75

Comment:
**`MAX_CACHE_SIZE` 定数が使われていない**

`setCachedResults` がデフォルト値 `1000` を持つ `maxSize` パラメータを受け取るようになったため、この定数はどこからも参照されなくなりました。デッドコードとして残っており、実際のデフォルト値(`setCachedResults` のデフォルト引数)との同期外れが将来的に混乱を招く可能性があります。削除することを推奨します。

```suggestion

```

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 422ade4

- \`papers.test.ts\`: Assert paperOrgs insertion for org_only papers, verify empty string mapping behavior.
- \`users.test.ts\`: Use custom MAX_CACHE_SIZE via environment variable for LRU limits and remove duplicate 404 test block.
- \`papers.ts\`: Log partial cleanup failures and re-throw origin errors in POST /api/papers.
- \`users.ts\`: Delete and re-insert cached objects on hits to apply true MRU ordering to LRU cache.
- \`validation.test.ts\`: Validate rejection of leading and trailing hyphens.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@google-labs-jules
Copy link
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@vercel
Copy link

vercel bot commented Mar 17, 2026

Deployment failed with the following error:

Resource is limited - try again in 24 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/hirokis-projects-afd618c7?upgradeToPro=build-rate-limit

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed タイトルはプルリクエストの主な変更点を明確に要約しており、APIルートとテスト検証の修正という内容を的確に反映しています。
Description check ✅ Passed PR説明は変更セットに関連している。テスト改善、キャッシュ仕様変更、エラーハンドリング改善など複数のファイルに対する具体的な変更内容が記述されており、提供されたサマリーと一致している。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jules-8376435226217890193-cd1e1d2f
📝 Coding Plan
  • Generate coding plan for human review comments

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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the stability and reliability of the API by addressing several critical areas. It enhances testing coverage for key functionalities, refines caching mechanisms for better performance, and strengthens error handling during resource cleanup. These changes collectively lead to a more robust and predictable API behavior, reducing potential issues and improving maintainability.

Highlights

  • API Test Enhancements: Enhanced papers.test.ts to verify paperOrgs insertion during paper creation and refined PATCH /api/papers/:id tag tests to confirm 200 status when handling empty string tags. Also, users.test.ts now uses an injected MAX_CACHE_SIZE environment variable for more flexible testing of search cache eviction.
  • Robust Error Handling: Improved error handling in papers.ts during paper upload cleanup by utilizing Promise.allSettled for R2 and database deletions, ensuring all cleanup operations are attempted and any failures are explicitly logged with contextual information.
  • Optimized Caching Strategy: Upgraded the user search results caching in users.ts to a Most Recently Used (MRU) strategy, which ensures frequently accessed items remain in the cache, and integrated dynamic cache size configuration via environment variables.
  • Input Validation Improvements: Added new test assertions to validation.test.ts to ensure the validateSlug utility correctly rejects inputs containing leading or trailing hyphens, increasing the robustness of slug validation.
Changelog
  • apps/api/src/routes/tests/papers.test.ts
    • Modified mockDb.insert to return detailed insert operation data for testing.
    • Updated POST /api/papers test to assert mockDb.batch was called and contained an org-1 insertion.
    • Adjusted PATCH /api/papers/:id tag tests to expect a 200 status when an empty string array is provided for tags.
  • apps/api/src/routes/tests/users.test.ts
    • Introduced a smallEnv with a custom MAX_CACHE_SIZE for targeted cache eviction testing.
    • Refactored cache eviction test to verify mockDb.select call count after cache fill and eviction.
    • Removed a redundant test case for a missing user.
  • apps/api/src/routes/papers.ts
    • Refactored the catch block in POST /api/papers to use Promise.allSettled for concurrent R2 and D1 cleanup operations.
    • Implemented logging for any rejected cleanup promises, providing paperId and reason.
  • apps/api/src/routes/users.ts
    • Modified getCachedResults to delete and re-set cached items on hit, implementing MRU logic.
    • Updated setCachedResults to accept a maxSize parameter, defaulting to 1000, and used c.env.MAX_CACHE_SIZE for dynamic configuration.
  • apps/api/src/utils/tests/validation.test.ts
    • Added new test cases to validateSlug to ensure strings with leading or trailing hyphens are rejected.
Activity
  • The pull request was created automatically by Jules for task 8376435226217890193, started by @is0692vs. No human activity has been recorded yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a good set of fixes and improvements across API routes and their tests. The changes enhance test coverage for paper creation, make user cache tests more efficient, and improve error logging in the paper upload process. The implementation of an MRU cache for user search is a definite improvement. I have one suggestion regarding the handling of the cache size configuration to make it more robust.

.all();

setCachedResults(cacheKey, results);
setCachedResults(cacheKey, results, c.env.MAX_CACHE_SIZE as any as number ?? 1000);
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The type assertion as any as number is not safe as it bypasses TypeScript's type checking and doesn't correctly parse a string value from environment variables. This can lead to unexpected behavior if the environment variable is not a number. Using Number() provides explicit and safer type conversion, with a reliable fallback for invalid or missing values. Additionally, consider defining the fallback value 1000 as a pre-defined constant to improve maintainability, as per repository guidelines on avoiding hardcoded values.

Suggested change
setCachedResults(cacheKey, results, c.env.MAX_CACHE_SIZE as any as number ?? 1000);
setCachedResults(cacheKey, results, Number(c.env.MAX_CACHE_SIZE) || 1000);
References
  1. Use pre-defined constants for validation logic instead of hardcoding values to improve maintainability.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Note

Unit test generation is a public access feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

- \`papers.test.ts\`: Assert paperOrgs insertion for org_only papers, verify empty string mapping behavior.
- \`users.test.ts\`: Use custom MAX_CACHE_SIZE via environment variable for LRU limits and remove duplicate 404 test block.
- \`papers.ts\`: Log partial cleanup failures and re-throw origin errors in POST /api/papers.
- \`users.ts\`: Delete and re-insert cached objects on hits to apply true MRU ordering to LRU cache.
- \`validation.test.ts\`: Validate rejection of leading and trailing hyphens.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Note

Docstrings generation - SUCCESS
Generated docstrings and committed to branch jules-8376435226217890193-cd1e1d2f (commit: 8b0c0f868f9285bcb08f96617b91e70f554c0be9)

Docstrings generation was requested by @is0692vs.

The following files were modified:

* `apps/api/src/routes/users.ts`

These files were ignored:
* `apps/api/src/routes/__tests__/papers.test.ts`
* `apps/api/src/routes/__tests__/users.test.ts`
* `apps/api/src/utils/__tests__/validation.test.ts`
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Plan generation is already in progress for this pull request. Please wait for it to complete.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/api/src/routes/users.ts`:
- Around line 88-91: The function setCachedResults currently duplicates the
default cache size (maxSize = 1000) with a caller-side fallback (|| 1000);
remove the redundant fallback and centralize the default by using the existing
MAX_CACHE_SIZE constant as the single source of truth. Update setCachedResults
signature to accept maxSize = MAX_CACHE_SIZE (or rely on the existing signature
if already set) and remove any "|| 1000" fallbacks where setCachedResults is
called so callers can pass a test-specific size when needed; reference function
setCachedResults and constant MAX_CACHE_SIZE to locate the changes.
- Line 136: The code is failing because Env lacks MAX_CACHE_SIZE and the
cast/`??` order is wrong; add MAX_CACHE_SIZE?: string to the Env type
declaration and change the call that uses c.env.MAX_CACHE_SIZE (the
setCachedResults(cacheKey, results, ... ) call) to coerce the env string to a
number with the nullish fallback applied first, e.g. Number(c.env.MAX_CACHE_SIZE
?? '1000') or parseInt(c.env.MAX_CACHE_SIZE ?? '1000', 10), so the fallback is
used when the env is undefined and the value passed to setCachedResults is a
proper number.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ca1b7eae-070d-4150-a718-f3407243d4dc

📥 Commits

Reviewing files that changed from the base of the PR and between 9839835 and d9765de.

📒 Files selected for processing (5)
  • apps/api/src/routes/__tests__/papers.test.ts
  • apps/api/src/routes/__tests__/users.test.ts
  • apps/api/src/routes/papers.ts
  • apps/api/src/routes/users.ts
  • apps/api/src/utils/__tests__/validation.test.ts

Comment on lines +88 to +91
function setCachedResults(key: string, data: any[], maxSize = 1000) {
if (searchCache.has(key)) {
searchCache.delete(key);
} else if (searchCache.size >= MAX_CACHE_SIZE) {
} else if (searchCache.size >= maxSize) {
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

maxSizeパラメータのデフォルト値が重複しています。

setCachedResults関数のデフォルト値maxSize = 1000と、呼び出し側のフォールバック|| 1000(修正後)が重複しています。どちらか一方で十分です。

♻️ リファクタリング案

デフォルト値を関数シグネチャに統一する場合:

-function setCachedResults(key: string, data: any[], maxSize = 1000) {
+function setCachedResults(key: string, data: any[], maxSize?: number) {
+    const effectiveMaxSize = maxSize ?? MAX_CACHE_SIZE;
     if (searchCache.has(key)) {
         searchCache.delete(key);
-    } else if (searchCache.size >= maxSize) {
+    } else if (searchCache.size >= effectiveMaxSize) {

これにより、MAX_CACHE_SIZE定数(line 75)をデフォルト値として再利用し、テスト時のみ異なる値を注入できます。

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function setCachedResults(key: string, data: any[], maxSize = 1000) {
if (searchCache.has(key)) {
searchCache.delete(key);
} else if (searchCache.size >= MAX_CACHE_SIZE) {
} else if (searchCache.size >= maxSize) {
function setCachedResults(key: string, data: any[], maxSize?: number) {
const effectiveMaxSize = maxSize ?? MAX_CACHE_SIZE;
if (searchCache.has(key)) {
searchCache.delete(key);
} else if (searchCache.size >= effectiveMaxSize) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/api/src/routes/users.ts` around lines 88 - 91, The function
setCachedResults currently duplicates the default cache size (maxSize = 1000)
with a caller-side fallback (|| 1000); remove the redundant fallback and
centralize the default by using the existing MAX_CACHE_SIZE constant as the
single source of truth. Update setCachedResults signature to accept maxSize =
MAX_CACHE_SIZE (or rely on the existing signature if already set) and remove any
"|| 1000" fallbacks where setCachedResults is called so callers can pass a
test-specific size when needed; reference function setCachedResults and constant
MAX_CACHE_SIZE to locate the changes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Plan generation is already in progress for this pull request. Please wait for it to complete.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@vercel
Copy link

vercel bot commented Mar 17, 2026

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

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
open-shelf Ignored Ignored Mar 17, 2026 11:01am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Summary

  • 安全でないas any as numberパターンをNumber()による明示的な型変換に置き換え
  • ハードコードされたフォールバック値1000を既存のMAX_CACHE_SIZE定数で置き換え
  • Env型への追加により、anyキャストを不要にし完全な型安全性を実現
  • 既存のコードベースパターン(オプショナル環境変数の定義方法、インライン定数の使用)に準拠
🤖 Prompt for AI Agents
このフェーズでは、PRレビューで指摘された安全でない型アサーションとハードコードされた値の2つの問題を解決し、型安全性と保守性を向上させる。

**Task 1: `apps/api/src/types.ts` の修正**
- `Env`型に`MAX_CACHE_SIZE?: string`をオプショナルプロパティとして追加する
- `ALLOWED_ORIGINS`、`ENABLE_TEST_AUTH`等の既存のオプショナル環境変数と同様のパターンに従うこと
- 環境変数は文字列として読み込まれるため、型は`string`(`number`ではない)とすること

**Task 2: `apps/api/src/routes/users.ts` の修正**
- line 136付近の`setCachedResults`呼び出しを修正する
- `((c.env as any).MAX_CACHE_SIZE as number) ?? 1000` を
`Number(c.env.MAX_CACHE_SIZE) || MAX_CACHE_SIZE` に置き換える
- `Number()`により文字列から数値への明示的な変換を行い、NaNや未定義の場合はfalsyとなるため`||`演算子でフォールバックする
- フォールバック値はハードコードされた`1000`ではなく、line 74で既に定義されている`MAX_CACHE_SIZE`定数を使用すること

is0692vs and others added 2 commits March 17, 2026 20:08
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

✅ Unit tests committed locally. Commit: 6a8eb1c80b9e74b819b70fd15867488a9bf6dab1

@pull-request-size pull-request-size bot added size/L and removed size/M labels Mar 17, 2026
Replaced parallel `Promise.all` with a sequential `for...await` loop to populate the cache boundary, ensuring a deterministic insertion order to stabilize the eviction expectations for the `limit0` query.

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@pull-request-size pull-request-size bot added size/M and removed size/L labels Mar 17, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 17, 2026

Summary

  • users.ts の as any キャストを削除し、Env 型に MAX_CACHE_SIZE を追加することで型安全性を確保
  • 既存の未使用ローカル定数 MAX_CACHE_SIZE をフォールバック値として活用し、ハードコード値を排除
  • papers.test.ts のデッドコード(未使用の thrown 変数)を削除
  • users.test.ts の並行リクエストを順次リクエストに変更し、テストのフレーキネスを解消
🤖 Prompt for AI Agents
Task: 1

このフェーズでは、users.ts の型アサーション問題と papers.test.ts の未使用変数問題の2つのコード品質修正を行う。

**タスク1: users.ts の MAX_CACHE_SIZE 型定義と使用箇所の修正**
- Env 型定義ファイル(または users.ts 内の Env 型宣言)に `MAX_CACHE_SIZE?: string` フィールドを追加する
- users.ts の Line 136 にある `setCachedResults` 呼び出しを以下のように修正する:
- `(c.env as any).MAX_CACHE_SIZE` を `c.env.MAX_CACHE_SIZE` に変更し、`as any` キャストを削除
  - ハードコードされたフォールバック値 `1000` を既存のローカル定数 `MAX_CACHE_SIZE` に置き換え
- 修正後の呼び出し: `setCachedResults(cacheKey, results, Number(c.env.MAX_CACHE_SIZE) ||
MAX_CACHE_SIZE)`

**タスク2: papers.test.ts の未使用変数 `thrown` の削除**
- `apps/api/src/routes/__tests__/papers.test.ts` を編集する
  - Line 113 の `let thrown = false;` 宣言を削除
  - Line 128 の catch ブロック内の `thrown = true;` 代入を削除
  - try/catch 構造自体は維持する(catch ブロックは空のままでよい)
===============================================================================

Task: 2

このフェーズでは、users.test.ts のキャッシュ eviction
テストにおけるフレーキネスを解消するため、並行リクエストを順次リクエストに変更する。

- `apps/api/src/routes/__tests__/users.test.ts` の Lines 348-352 を修正する
- 以下の変更を行う:
  - `Promise.all` を使った並行実行パターン(リクエスト配列を作成して `Promise.all(reqs)` で一括実行)を削除
  - 代わりに for ループ内で各リクエストを `await` して順次実行するパターンに置き換え
- この変更により、`limit0` → `limit1` → `limit2` の順序でキャッシュへの挿入が保証され、eviction
テストの期待動作が決定論的になる

is0692vs added a commit that referenced this pull request Mar 17, 2026
@is0692vs
Copy link
Contributor Author

このPRは #138 に統合しました。以降のレビューは統合先PRでお願いします。

@is0692vs is0692vs closed this Mar 17, 2026
@is0692vs is0692vs deleted the jules-8376435226217890193-cd1e1d2f branch March 17, 2026 11:26
@google-labs-jules
Copy link
Contributor

このPRは #138 に統合しました。以降のレビューは統合先PRでお願いします。

了解しました。このPRが別のPRに統合されたことを確認しました。こちらの作業は停止し、以降の対応は不要と認識しております。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant