Skip to content

fix: apply comprehensive API fixes and frontend loading regression#138

Closed
is0692vs wants to merge 10 commits intomainfrom
jules-1074778561141579511-52545385
Closed

fix: apply comprehensive API fixes and frontend loading regression#138
is0692vs wants to merge 10 commits intomainfrom
jules-1074778561141579511-52545385

Conversation

@is0692vs
Copy link
Contributor

@is0692vs is0692vs commented Mar 17, 2026

This PR consolidates and supersedes #137.

Changes

  • hardens POST /api/papers cleanup so R2/D1 cleanup failures are logged without losing the original error
  • fixes the user-search cache configuration path by typing MAX_CACHE_SIZE, centralizing the default, and keeping eviction tests deterministic
  • surfaces stats loading failures in the paper detail author view
  • removes accidental runtime artifacts (*.pid, start_dev.sh) and ignores pid files
  • keeps the related API validation/tests aligned with the merged fixes

Consolidation

This PR absorbs:

Notes:

  • Review feedback from both PRs is addressed here.
  • Vercel preview is intentionally ignored for this branch; GitHub Actions remain the primary CI signal.

Greptile Summary

このPRはPOST /api/papersのクリーンアップ処理の堅牢化、ユーザー検索キャッシュのLRU実装改善、stats取得時のローディング状態リグレッション修正、および開発用一時ファイルの除去を目的としています。変更内容は全体的に正しい方向性ですが、前回レビューで指摘された2点が依然として未修正の状態です。

  • papers.ts クリーンアップ改善: 子テーブルの削除が Promise.allSettled で保護されるようになり、FK制約違反も回避できるよう削除順序が整理された
  • users.ts LRUキャッシュ修正: キャッシュヒット時にエントリを再挿入してLRU順序を維持するようになり、有効なエントリが誤って削除されていたバグも修正された
  • paper-detail-client.tsx ローディング修正: fetchStats()await されずに setStatsLoading(false) が即座に呼ばれていたリグレッションを .finally() チェーンで修正
  • validation.ts 表記統一: エラーメッセージのハイフンをエンダッシュに変更し、テストも合わせて更新
  • クリーンアップ: 開発用一時ファイル(update_layout.js)の削除と .gitignore への *.pid 等の追加
  • ⚠️ 前回指摘の未対応: await db.delete(papers)catch ブロック内でまだ try-catch に囲まれておらず、この行が失敗すると元のエラーが失われる問題が残っている
  • ⚠️ 前回指摘の未対応: fetchStats 内の catch { // Ignore }setStatsError を呼ばないため、APIエラー発生時もユーザーへのフィードバックがない状態が継続している

Confidence Score: 3/5

  • 前回レビューで指摘された2つの重要な問題(クリーンアップエラーの握りつぶし、stats エラーのサイレント無視)が未修正のためマージには注意が必要
  • ローディングリグレッションの修正やLRUキャッシュの改善など有益な変更が含まれているが、前回レビューで明示的に修正を求められた db.delete(papers) の try-catch 欠如と fetchStatssetStatsError 非呼び出しの2点が今回のPRでも解消されていない。これらは実際の障害調査やUX品質に影響するため、スコアを 3 とした。
  • apps/api/src/routes/papers.ts(クリーンアップのエラー伝播)と apps/web/src/app/papers/[id]/paper-detail-client.tsx(stats エラーのサイレント無視)に注意が必要

Important Files Changed

Filename Overview
apps/api/src/routes/papers.ts バッチ操作をシンプルな配列ビルダーに整理し、子テーブルのクリーンアップを Promise.allSettled で保護した。ただし最後の await db.delete(papers) は依然として try-catch で囲まれておらず、失敗すると元のエラーが失われる問題(前回レビューで指摘済み)が残っている。
apps/api/src/routes/users.ts キャッシュヒット時にエントリを末尾に再挿入して LRU 順序を維持するよう改善。TTL 期限切れ時のみ削除するよう修正し、誤って有効なエントリを削除していた旧バグも解消。コメントの「MRU」表記が紛らわしい点は軽微。
apps/web/src/app/papers/[id]/paper-detail-client.tsx ローディング状態のリグレッション(fetchStats を await せず即座に setStatsLoading(false) を呼んでいた問題)を .finally() で修正。ただし fetchStats 内の catch { // Ignore } はそのままで、エラー時に setStatsError が呼ばれない問題(前回指摘済み)は依然未修正。
apps/api/src/routes/tests/papers.test.ts org_only ケースのバッチ呼び出しで要素数(4件)を検証するアサーションを追加。res2 の未使用変数問題も修正。非 org ケースのバッチ長(3件)は未検証だが致命的ではない。
apps/api/src/routes/tests/users.test.ts キャッシュ上限テストのコメントを整理し、テスト名を意図が伝わりやすいものに変更。機能的な問題なし。

Sequence Diagram

sequenceDiagram
    participant Client
    participant PapersRoute as POST /api/papers
    participant R2 as R2 Bucket
    participant D1 as D1 Database

    Client->>PapersRoute: POST /api/papers (FormData)
    PapersRoute->>R2: upload files (uploadedKeys[])
    R2-->>PapersRoute: ok

    PapersRoute->>D1: db.batch([insertPaper, insertAuthor, (insertOrg?), insertFiles])
    Note over PapersRoute,D1: org_only: 4 ops / other: 3 ops

    alt batch 成功
        D1-->>PapersRoute: ok
        PapersRoute-->>Client: 201 { paper: { id } }
    else batch 失敗 (catch error)
        PapersRoute->>R2: Promise.allSettled(BUCKET.delete × N)
        Note over PapersRoute,R2: R2 削除失敗はログのみ (allSettled)
        PapersRoute->>D1: Promise.allSettled([delete paperFiles, paperOrgs, paperAuthors])
        Note over PapersRoute,D1: 子テーブル削除失敗は無視 (allSettled)
        PapersRoute->>D1: await db.delete(papers) ⚠️ try-catch なし
        Note over PapersRoute,D1: 失敗すると元の error が失われる
        PapersRoute-->>Client: throw error (元のエラー)
    end
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: apps/api/src/routes/users.ts
Line: 82-83

Comment:
**コメントの用語が紛らわしい (MRU vs LRU)**

コメントの `(MRU)` は誤解を招く恐れがあります。MRU(Most Recently Used)は「最近使われたものを削除するキャッシュ戦略」として知られており、このコードが実装している LRU(Least Recently Used、最近使われていないものを削除)とは逆の意味を持ちます。

Re-insert して末尾(最近使った位置)に移動することで LRU 順序を維持しているため、コメントを以下のように修正することを推奨します。

```suggestion
            // Re-insert to move to the end (mark as most recently used in LRU order)
            searchCache.delete(key);
```

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

Last reviewed commit: f11a727

google-labs-jules bot and others added 7 commits March 17, 2026 10:54
- \`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>
- \`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>
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`
Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
* Restore BatchItem typings in papers.ts db.batch calls.
* Use Promise.allSettled and properly sequence child table deletion in catch blocks.
* Fix private paper visibility logic by removing innerJoin in orgs.ts.
* Fix memory cache LRU ordering and eviction in users.ts.
* Clean up AI comments and strengthen tests in papers.test.ts and users.test.ts.
* Revert validation en-dash for backward test compatibility.
* Fix statsLoading async race condition in paper-detail-client.tsx.

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

Warning

Rate limit exceeded

@is0692vs has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 2 minutes and 25 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: dc67fb16-5441-41f3-825c-6c16251e49fc

📥 Commits

Reviewing files that changed from the base of the PR and between f852003 and f11a727.

📒 Files selected for processing (9)
  • .gitignore
  • 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
  • apps/api/src/utils/validation.ts
  • apps/web/src/app/papers/[id]/paper-detail-client.tsx
  • update_layout.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jules-1074778561141579511-52545385
📝 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 focuses on restoring critical fixes and addressing regressions across the API and frontend, aiming to enhance the system's stability, data integrity, and user experience. It tackles issues ranging from database transaction robustness and cache management to UI loading states and test suite clarity, ensuring that previously identified problems are correctly resolved and preventing their reintroduction.

Highlights

  • API (papers.ts) Robustness: Restored strong typing for db.batch() operations and implemented concurrent deletion of child tables (paperFiles, paperAuthors, paperOrgs) before the parent papers row in the catch block to prevent SQLite foreign key constraint violations.
  • API (orgs.ts) Regression Fix: Addressed a regression where private papers were incorrectly excluded from the authored papers list due to an erroneous innerJoin on paperOrgs, ensuring private papers are now properly retained for their authors.
  • API (users.ts) Cache Improvement: Fixed the in-memory search cache to function correctly as an LRU (Least Recently Used) cache, where cache hits now update access order, and expired items are properly deleted. The MAX_CACHE_SIZE constant was also restored.
  • Web (paper-detail-client.tsx) UI Race Condition: Resolved an asynchronous race condition where the statsLoading state was prematurely set to false before fetchStats() completed, causing the UI loading spinner to flicker. A cancelled flag was added to prevent state updates if the component unmounts.
  • Test Suite Enhancements: Cleaned up leaked AI thought process comments, strengthened the org_only paper creation test by asserting mockDb.batch array length, renamed obscure test names for clarity, and ensured vi.useFakeTimers functions correctly. The slug validation error message was reverted to use an en-dash to pass existing tests.
Changelog
  • api_dev.pid
    • Added process ID file for API development server.
  • apps/api/src/routes/tests/papers.test.ts
    • Strengthened db.batch assertion to check call count and array length.
    • Updated comments for tag update behavior in tests.
  • apps/api/src/routes/tests/users.test.ts
    • Removed AI thought process comments from cache eviction test.
    • Renamed user profile fetch test for clarity.
  • apps/api/src/routes/papers.ts
    • Introduced strong typing for db.batch operations.
    • Modified error handling to ensure child tables are deleted before the parent to prevent foreign key violations.
  • apps/api/src/routes/users.ts
    • Implemented LRU cache logic by re-inserting accessed items.
    • Ensured expired cache items are properly deleted.
  • apps/api/src/utils/tests/validation.test.ts
    • Updated slug validation error message to use an en-dash.
  • apps/api/src/utils/validation.ts
    • Changed slug validation error message to use an en-dash.
  • apps/web/src/app/papers/[id]/paper-detail-client.tsx
    • Fixed a race condition where statsLoading was prematurely set to false.
    • Added a cancelled flag to prevent state updates on unmounted components.
  • dev.pid
    • Added generic process ID file.
  • start_dev.sh
    • Added a shell script to start web and API development servers concurrently.
  • update_layout.js
    • Removed a temporary script for updating layout with Vercel analytics/speed insights.
  • web_dev.pid
    • Added process ID file for web development server.
Activity
  • The pull request was created automatically by Jules for task 1074778561141579511, initiated by @is0692vs.
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 comprehensive set of fixes across the API and frontend, addressing regressions and improving robustness. The changes to the paper creation error handling and the LRU cache implementation are significant improvements. The frontend race condition fix in paper-detail-client.tsx is also well-implemented. I've identified a potential issue with unhandled errors during cleanup in papers.ts and an issue with committing runtime artifacts. Please see my detailed comments.

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>
@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:24am

@pull-request-size pull-request-size bot added size/L and removed size/M labels Mar 17, 2026
* Add `*.pid`, `*_dev.log`, and `start_dev.sh` to `.gitignore`.
* Remove accidentally included `update_layout.js`.

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

このPRは分割し、以下の小さいPR群に置き換えます。\n\n- #139 fix(api): harden paper creation cleanup\n- #140 fix(api): tighten user search cache behavior\n- #141 fix(web): surface paper stats loading errors\n- #142 test(api): align slug validation messaging\n- #143 chore(repo): remove obsolete layout helper\n\n以降のレビューは各分割PRでお願いします。

@is0692vs is0692vs closed this Mar 17, 2026
@is0692vs is0692vs deleted the jules-1074778561141579511-52545385 branch March 17, 2026 11:35
@google-labs-jules
Copy link
Contributor

このPRは分割し、以下の小さいPR群に置き換えます。\n\n- #139 fix(api): harden paper creation cleanup\n- #140 fix(api): tighten user search cache behavior\n- #141 fix(web): surface paper stats loading errors\n- #142 test(api): align slug validation messaging\n- #143 chore(repo): remove obsolete layout helper\n\n以降のレビューは各分割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