Skip to content

fix: monitor timeout task SQL#617

Merged
fatelei merged 1 commit into
mainfrom
fix/monitor-timeout-tasks
Mar 4, 2026
Merged

fix: monitor timeout task SQL#617
fatelei merged 1 commit into
mainfrom
fix/monitor-timeout-tasks

Conversation

@Stream29

@Stream29 Stream29 commented Mar 2, 2026

Copy link
Copy Markdown
Contributor

Description

internal/tasks/recycle.go:86 func MonitorTimeoutTasks executes such query:
SELECT * FROM "install_tasks" WHERE status IN ($1,$2) that produces significant performance issues on DB.

Dify SaaS fixes this by adding index idx_install_tasks_status ON install_tasks (status)

This PR adds this index to internal/types/models/task.go, allowing community instances to have this optimization.

Type of Change

  • Bug fix
  • New feature
  • Refactor
  • Performance improvement
  • Other

Essential Checklist

Testing

  • I have tested the changes locally and confirmed they work as expected

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Mar 2, 2026
@gemini-code-assist

Copy link
Copy Markdown
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 addresses a significant performance bottleneck identified in the MonitorTimeoutTasks function. By introducing a new database index on install_tasks and modifying the task retrieval query to filter by created_at directly in the database, the change aims to drastically reduce the load on the production database and improve the efficiency of timeout task monitoring.

Highlights

  • Database Index Addition: A new composite index idx_install_tasks_status_created_at has been added to the install_tasks table on the status and created_at columns to improve query performance.
  • SQL Query Optimization: The MonitorTimeoutTasks function's database query for install_tasks now includes a created_at < $3 condition, leveraging the newly added index to efficiently filter timed-out tasks directly in the database.
  • In-memory Filtering Removal: The previous in-memory time.Since(task.CreatedAt) > timeout check has been removed, as the filtering is now handled by the optimized database query, reducing application-level processing.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • internal/db/init.go
    • Added logic to create the idx_install_tasks_status_created_at index on the install_tasks table during database initialization if it doesn't already exist.
  • internal/tasks/recycle.go
    • Modified the MonitorTimeoutTasks function to include a created_at filter in the db.GetAll query.
    • Removed the time.Since(task.CreatedAt) > timeout check, as the database now handles the time-based filtering.
    • Adjusted the initialization of tasksToProcess to reflect the direct database filtering.
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.

@Stream29 Stream29 requested a review from Yeuoly March 2, 2026 18:25

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request effectively addresses a performance issue by adding a database index and modifying the query to filter timed-out tasks at the database level. The changes are logical and well-implemented. I've included a couple of suggestions to further improve the code by using more idiomatic GORM features, which will enhance maintainability and readability.

Comment thread internal/db/init.go Outdated
Comment on lines +63 to +65
err := DifyPluginDB.Exec(
"CREATE INDEX " + installTasksStatusCreatedAtIndexName + " ON install_tasks (status, created_at)",
).Error

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.

medium

To improve database portability and avoid raw SQL, it's better to use GORM's CreateIndex method. This will also make the code cleaner and less prone to typos in table or column names. GORM will correctly generate the index name idx_install_tasks_status_created_at for the composite index on the status and created_at columns.

		err := DifyPluginDB.Migrator().CreateIndex(&models.InstallTask{}, "status", "created_at")

Comment thread internal/tasks/recycle.go
Comment on lines 106 to 123
tasks, err := db.GetAll[models.InstallTask](
db.InArray("status", []any{
string(models.InstallTaskStatusPending),
string(models.InstallTaskStatusRunning),
}),
db.WhereSQL("created_at < ?", deadline),
)
if err != nil {
log.Error("failed to get all tasks", "error", err)
continue
}
tasksToProcess := make([]*models.InstallTask, 0, len(tasks))
for i := range tasks {
task := &tasks[i]
if time.Since(task.CreatedAt) > timeout {
log.Info("task timed out", "task_id", task.ID)
tasksToProcess = append(tasksToProcess, task)
}
log.Info("task timed out", "task_id", task.ID)
tasksToProcess = append(tasksToProcess, task)
}
markTasksAsTimeout(tasksToProcess)

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.

medium

This block can be simplified by fetching a slice of pointers directly from the database. By changing db.GetAll[models.InstallTask] to db.GetAll[*models.InstallTask], you can avoid creating and populating the tasksToProcess slice. This makes the code cleaner and slightly more efficient.

			tasks, err := db.GetAll[*models.InstallTask](
				db.InArray("status", []any{
					string(models.InstallTaskStatusPending),
					string(models.InstallTaskStatusRunning),
				}),
				db.WhereSQL("created_at < ?", deadline),
			)
			if err != nil {
				log.Error("failed to get all tasks", "error", err)
				continue
			}
			for _, task := range tasks {
				log.Info("task timed out", "task_id", task.ID)
			}
			markTasksAsTimeout(tasks)

@dosubot dosubot Bot added the plugin-daemon label Mar 2, 2026
@Stream29 Stream29 force-pushed the fix/monitor-timeout-tasks branch from 954937a to 3a94422 Compare March 3, 2026 12:10
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Mar 3, 2026
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Mar 4, 2026
@fatelei fatelei merged commit 752cfbd into main Mar 4, 2026
7 checks passed
@fatelei fatelei deleted the fix/monitor-timeout-tasks branch March 4, 2026 10:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm This PR has been approved by a maintainer plugin-daemon size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants