Skip to content

timestamp型に変更した上で、migrationを行うためのスクリプトを追加#18

Merged
yuito-it merged 4 commits intomainfrom
fix/ttl-index
Apr 15, 2026
Merged

timestamp型に変更した上で、migrationを行うためのスクリプトを追加#18
yuito-it merged 4 commits intomainfrom
fix/ttl-index

Conversation

@yuito-it
Copy link
Copy Markdown
Member

@yuito-it yuito-it commented Apr 15, 2026

Related Issue

Resolve #17

Reporter

Summary by CodeRabbit

リリースノート

  • バグ修正

    • 保存されるタイムスタンプ形式を文字列から日時型に変更し、扱いやすさと安定性を向上しました。
  • 新機能

    • 既存データのタイムスタンプを自動で新形式へ変換する移行処理を追加。起動時に実行できるように設定可能です。

Co-Authored-By: maruta-yadeeeeee <maruta-yadeeeeee@users.noreply.github.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 15, 2026

📝 Walkthrough

Walkthrough

メッセージのタイムスタンプ永続化形式をISO形式文字列から日付オブジェクトに変更し、既存の文字列タイムスタンプをMongoDBネイティブな日付型に変換するマイグレーション関数を追加しました。

Changes

Cohort / File(s) Summary
Timestamp Persistence and Migration
src/main.py
メッセージ保存時のtimestampmessage.created_at.isoformat()(文字列)からmessage.created_at(datetime)へ変更。migrate_timestamps_to_date()を追加し、文字列型のtimestampをMongoDBのdate型へ変換するupdate_manyパイプラインを実行するマイグレーション処理を実装。起動時にRUN_TIMESTAMP_MIGRATION=="1"ならマイグレーションを実行してからasyncio.run(main())を呼ぶよう起動フローを変更。
Deployment Configuration
argocd/base/bot-deployment.yaml
analyze-botコンテナに環境変数RUN_TIMESTAMP_MIGRATION: "1"を追加し、起動時にマイグレーションが実行されるよう設定を追加。

Sequence Diagram(s)

sequenceDiagram
    participant Runner as Runner/EntryPoint
    participant Mongo as MongoDB
    participant App as Bot Main Loop

    Runner->>Mongo: connect (if MONGODB_DSN set)
    Runner->>Mongo: update_many(filter: {"timestamp":{"$type":"string"}}, pipeline: [{"$set":{"timestamp":{"$toDate":"$timestamp"}}}])
    Mongo-->>Runner: matchedCount / modifiedCount or error
    Runner->>Mongo: close
    Runner->>App: asyncio.run(main())
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PRタイトルはtimestamp型への変更とマイグレーションスクリプト追加という実装内容を正確に反映しており、main changesを適切に説明している。
Linked Issues check ✅ Passed PR#18はIssue#17のTTLインデックス問題を解決するため、文字列型のtimestampフィールドをDateTime型に変更し、既存データのマイグレーションを実装している。
Out of Scope Changes check ✅ Passed すべての変更(timestamp型変更、マイグレーション関数追加、環境変数設定)がIssue#17解決に直接関連しており、スコープ外の変更は認識されない。

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ttl-index

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.

Copy link
Copy Markdown

@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 `@src/main.py`:
- Around line 343-345: migrate_timestamps_to_date が bot 起動時に毎回実行されているため、起動遅延と不要な
DB 負荷を招いています。main エントリ内の if __name__ == "__main__" ブロックから
migrate_timestamps_to_date() の自動実行を除去し、代わりに(1)別ファイル/スクリプトで
migrate_timestamps_to_date() を単独で実行する、または(2)argparse 等で明示フラグ(例:
--run-migration)を追加してそのフラグが渡されたときだけ migrate_timestamps_to_date()
を呼ぶように実装して下さい;対象シンボル: migrate_timestamps_to_date, main, if __name__ ==
"__main__".
- Around line 331-340: The migration currently catches all exceptions around
db.messages.update_many(filter_query, update_pipeline) and only prints the
error, allowing the process to continue with timestamp still as a string; change
this so failures stop startup: after logging the exception (from the except
block for the update_many call) re-raise the exception or exit non‑zero (e.g.,
raise or sys.exit(1)) so the bot does not continue on a failed migration; ensure
you reference the same try/except surrounding db.messages.update_many and result
(matched_count/modified_count) when modifying the handler.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2f759f89-3b62-4a9e-8bf0-69485db9a4a8

📥 Commits

Reviewing files that changed from the base of the PR and between 23a9d17 and 76c86e0.

📒 Files selected for processing (1)
  • src/main.py

Comment thread src/main.py Outdated
Comment thread src/main.py
@otusoa
Copy link
Copy Markdown

otusoa commented Apr 15, 2026

@coderabbitai Review now

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 15, 2026

@otusoa: Sure! I'll start reviewing the changes in PR #18 now.

✅ 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.

@yuito-it
Copy link
Copy Markdown
Member Author

@coderabbitai approve

Copy link
Copy Markdown

@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: 1

♻️ Duplicate comments (1)
src/main.py (1)

347-349: ⚠️ Potential issue | 🟠 Major

migration モードでは実行後に終了させてください。

この指摘は以前のレビューと同旨です。RUN_TIMESTAMP_MIGRATION が deployment 側で常時有効なら、Pod 再起動のたびに update_many が走って不要な起動遅延と DB 負荷を持ち込みます。migration 用のワンショット実行にするか、少なくとも成功後は SystemExit(0) で終了させた方が安全です。

常時有効化されているかどうかは、次の read-only 確認で判定できます。deployment に RUN_TIMESTAMP_MIGRATION が残っていて、かつ migration 分岐の後に asyncio.run(main()) が続いていれば、この懸念は当たりです。

#!/bin/bash
set -euo pipefail

echo "== Search deployment configs for RUN_TIMESTAMP_MIGRATION =="
fd -i 'bot-deployment\.ya?ml$|deployment\.ya?ml$|values\.ya?ml$' . | while read -r f; do
  rg -n -C2 'RUN_TIMESTAMP_MIGRATION|analyze-bot' "$f" || true
done

echo
echo "== Confirm main entrypoint still starts the bot after migration =="
rg -n -C3 'RUN_TIMESTAMP_MIGRATION|migrate_timestamps_to_date|asyncio\.run\(main\)' src/main.py
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main.py` around lines 347 - 349, 現在のエントリで RUN_TIMESTAMP_MIGRATION
が有効な場合でも migrate_timestamps_to_date() 実行後に常に asyncio.run(main()) が続いており、Pod
再起動ごとにマイグレーションが走る恐れがあります。migrate_timestamps_to_date()
を呼んだ分岐内で成功時にプロセスを終了するように修正してください(例: raise SystemExit(0) または sys.exit(0)
を使って正常終了させる)、対象コードの識別子は RUN_TIMESTAMP_MIGRATION, migrate_timestamps_to_date(),
asyncio.run(main()) です。実行が失敗した場合は非ゼロで終了するようエラーハンドリングを残してください。
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main.py`:
- Around line 316-318: The current check "if not DB_DSN: print(...); return"
should be changed to fail-fast: in the DB_DSN validation block in main.py (the
code that reads DB_DSN and RUN_TIMESTAMP_MIGRATION), replace the silent return
with raising an explicit exception (e.g., RuntimeError or SystemExit) that
includes the missing-variable message so the process stops immediately and
migration mode (RUN_TIMESTAMP_MIGRATION) cannot be skipped; ensure the raised
error message mentions MONGODB_DSN and the need to set it so logs are clear.

---

Duplicate comments:
In `@src/main.py`:
- Around line 347-349: 現在のエントリで RUN_TIMESTAMP_MIGRATION が有効な場合でも
migrate_timestamps_to_date() 実行後に常に asyncio.run(main()) が続いており、Pod
再起動ごとにマイグレーションが走る恐れがあります。migrate_timestamps_to_date()
を呼んだ分岐内で成功時にプロセスを終了するように修正してください(例: raise SystemExit(0) または sys.exit(0)
を使って正常終了させる)、対象コードの識別子は RUN_TIMESTAMP_MIGRATION, migrate_timestamps_to_date(),
asyncio.run(main()) です。実行が失敗した場合は非ゼロで終了するようエラーハンドリングを残してください。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5ff061f2-c691-4a0d-878f-346b30e06578

📥 Commits

Reviewing files that changed from the base of the PR and between 76c86e0 and 28cc861.

📒 Files selected for processing (2)
  • argocd/base/bot-deployment.yaml
  • src/main.py
✅ Files skipped from review due to trivial changes (1)
  • argocd/base/bot-deployment.yaml

Comment thread src/main.py
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 15, 2026

✅ Actions performed

Comments resolved and changes approved.

@yuito-it yuito-it merged commit e576fac into main Apr 15, 2026
6 checks passed
@yuito-it yuito-it deleted the fix/ttl-index branch April 15, 2026 15:22
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.

MongoDBのTTL Indexが正しく動作しない

2 participants