2026-02-28 05:22:07 +00:00
|
|
|
package router
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
"errors"
|
2026-02-28 05:22:07 +00:00
|
|
|
"fmt"
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
"reflect"
|
2026-02-28 05:22:07 +00:00
|
|
|
"sync"
|
|
|
|
|
"time"
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
"unsafe"
|
2026-02-28 05:22:07 +00:00
|
|
|
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/application/service"
|
2026-02-28 05:22:07 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
2026-09-22 11:58:10 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/middleware/asynqdl"
|
2026-02-28 05:22:07 +00:00
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
"github.com/hibiken/asynq"
|
|
|
|
|
"go.uber.org/dig"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// SyncTaskExecutor executes tasks synchronously (in a goroutine) without Redis.
|
|
|
|
|
// Used in Lite mode as a drop-in replacement for *asynq.Client.
|
|
|
|
|
type SyncTaskExecutor struct {
|
|
|
|
|
mu sync.RWMutex
|
|
|
|
|
handlers map[string]func(context.Context, *asynq.Task) error
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
// onFinalFailure mirrors the asynq dead-letter callback: it runs once a
|
|
|
|
|
// task exhausts its retries, so a document whose task gave up is marked
|
|
|
|
|
// failed instead of spinning until the housekeeping sweep.
|
|
|
|
|
onFinalFailure func(context.Context, *asynq.Task, error)
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewSyncTaskExecutor() *SyncTaskExecutor {
|
|
|
|
|
return &SyncTaskExecutor{
|
|
|
|
|
handlers: make(map[string]func(context.Context, *asynq.Task) error),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RegisterHandler registers a handler for a given task type pattern.
|
|
|
|
|
func (e *SyncTaskExecutor) RegisterHandler(pattern string, handler func(context.Context, *asynq.Task) error) {
|
|
|
|
|
e.mu.Lock()
|
|
|
|
|
defer e.mu.Unlock()
|
|
|
|
|
e.handlers[pattern] = handler
|
|
|
|
|
}
|
|
|
|
|
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
// SetFinalFailureHook installs the callback run after a task's last failed
|
|
|
|
|
// attempt. It receives the error of that attempt, including asynq.SkipRetry.
|
|
|
|
|
func (e *SyncTaskExecutor) SetFinalFailureHook(fn func(context.Context, *asynq.Task, error)) {
|
|
|
|
|
e.mu.Lock()
|
|
|
|
|
defer e.mu.Unlock()
|
|
|
|
|
e.onFinalFailure = fn
|
|
|
|
|
}
|
2026-02-28 05:22:07 +00:00
|
|
|
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
// syncTaskOptions is the subset of asynq options the executor honours.
|
|
|
|
|
type syncTaskOptions struct {
|
|
|
|
|
delay time.Duration
|
|
|
|
|
maxRetry int
|
|
|
|
|
timeout time.Duration
|
|
|
|
|
deadline time.Time
|
|
|
|
|
}
|
2026-02-28 05:22:07 +00:00
|
|
|
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
// resolveSyncTaskOptions merges the options given to asynq.NewTask with the
|
|
|
|
|
// ones given to Enqueue, the latter winning, as asynq.Client does.
|
|
|
|
|
//
|
|
|
|
|
// Unlike asynq, a task with neither Timeout nor Deadline gets no default
|
|
|
|
|
// timeout: Lite has always run those unbounded (large imports on a laptop),
|
|
|
|
|
// and the document pipeline sets its own timeouts explicitly.
|
|
|
|
|
func resolveSyncTaskOptions(task *asynq.Task, opts []asynq.Option) syncTaskOptions {
|
|
|
|
|
resolved := syncTaskOptions{maxRetry: 25} // asynq default
|
|
|
|
|
all := append(append([]asynq.Option{}, asynqTaskOptions(task)...), opts...)
|
|
|
|
|
for _, opt := range all {
|
2026-04-28 10:08:20 +00:00
|
|
|
switch opt.Type() {
|
|
|
|
|
case asynq.ProcessInOpt:
|
|
|
|
|
if d, ok := opt.Value().(time.Duration); ok {
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
resolved.delay = d
|
|
|
|
|
}
|
|
|
|
|
case asynq.ProcessAtOpt:
|
|
|
|
|
if at, ok := opt.Value().(time.Time); ok {
|
|
|
|
|
resolved.delay = time.Until(at)
|
2026-04-28 10:08:20 +00:00
|
|
|
}
|
|
|
|
|
case asynq.MaxRetryOpt:
|
|
|
|
|
if n, ok := opt.Value().(int); ok {
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
resolved.maxRetry = n
|
|
|
|
|
}
|
|
|
|
|
case asynq.TimeoutOpt:
|
|
|
|
|
if d, ok := opt.Value().(time.Duration); ok {
|
|
|
|
|
resolved.timeout = d
|
|
|
|
|
}
|
|
|
|
|
case asynq.DeadlineOpt:
|
|
|
|
|
if at, ok := opt.Value().(time.Time); ok {
|
|
|
|
|
resolved.deadline = at
|
2026-04-28 10:08:20 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
if resolved.maxRetry < 0 {
|
|
|
|
|
resolved.maxRetry = 0
|
|
|
|
|
}
|
|
|
|
|
return resolved
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// asynqTaskOptions returns the options passed to asynq.NewTask. asynq keeps
|
|
|
|
|
// them in an unexported field and only merges them inside Client.Enqueue, so
|
|
|
|
|
// an executor standing in for the client has to read the field itself.
|
|
|
|
|
// Without this, every Lite task ran with 25 retries and no timeout, since
|
|
|
|
|
// callers put MaxRetry / Timeout on NewTask. TestAsynqTaskOptionsReadsNewTaskOptions
|
|
|
|
|
// breaks if an asynq upgrade renames the field.
|
|
|
|
|
func asynqTaskOptions(task *asynq.Task) []asynq.Option {
|
|
|
|
|
if task == nil {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
field := reflect.ValueOf(task).Elem().FieldByName("opts")
|
|
|
|
|
if !field.IsValid() || field.Type() != reflect.TypeOf([]asynq.Option(nil)) {
|
|
|
|
|
return nil
|
2026-04-28 10:08:20 +00:00
|
|
|
}
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
return *(*[]asynq.Option)(unsafe.Pointer(field.UnsafeAddr()))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// attemptContext bounds one attempt the way asynq does: by the task's
|
|
|
|
|
// Timeout, and by its Deadline when that comes first.
|
|
|
|
|
func (o syncTaskOptions) attemptContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
|
|
|
|
var deadline time.Time
|
|
|
|
|
if o.timeout > 0 {
|
|
|
|
|
deadline = time.Now().Add(o.timeout)
|
|
|
|
|
}
|
|
|
|
|
if !o.deadline.IsZero() && (deadline.IsZero() || o.deadline.Before(deadline)) {
|
|
|
|
|
deadline = o.deadline
|
|
|
|
|
}
|
|
|
|
|
if deadline.IsZero() {
|
|
|
|
|
return context.WithCancel(ctx)
|
|
|
|
|
}
|
|
|
|
|
return context.WithDeadline(ctx, deadline)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Enqueue satisfies interfaces.TaskEnqueuer.
|
|
|
|
|
// Instead of queuing to Redis, it dispatches the task to a goroutine.
|
|
|
|
|
// Supports ProcessIn / ProcessAt (delay), MaxRetry, Timeout and Deadline for
|
|
|
|
|
// parity with asynq, whether they were given here or to asynq.NewTask.
|
|
|
|
|
func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error) {
|
|
|
|
|
e.mu.RLock()
|
|
|
|
|
handler, ok := e.handlers[task.Type()]
|
|
|
|
|
onFinalFailure := e.onFinalFailure
|
|
|
|
|
e.mu.RUnlock()
|
|
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
|
return nil, fmt.Errorf("sync task executor: no handler registered for type %q", task.Type())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
options := resolveSyncTaskOptions(task, opts)
|
|
|
|
|
maxRetry := options.maxRetry
|
2026-04-28 10:08:20 +00:00
|
|
|
|
2026-02-28 05:22:07 +00:00
|
|
|
taskID := uuid.New().String()
|
|
|
|
|
info := &asynq.TaskInfo{
|
|
|
|
|
ID: taskID,
|
|
|
|
|
Queue: "sync",
|
|
|
|
|
Type: task.Type(),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
go func() {
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
if options.delay > 0 {
|
|
|
|
|
time.Sleep(options.delay)
|
2026-04-28 10:08:20 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-09 10:30:44 +00:00
|
|
|
// Tag as a background worker execution so the per-model concurrency
|
|
|
|
|
// governor throttles Lite-mode ingestion/enrichment LLM calls, mirroring
|
|
|
|
|
// the asynq backgroundTaskMiddleware in the Redis path.
|
|
|
|
|
ctx := types.WithBackgroundTask(context.Background())
|
2026-02-28 05:22:07 +00:00
|
|
|
start := time.Now()
|
|
|
|
|
logger.Infof(ctx, "[SyncTask] Executing task type=%s id=%s", task.Type(), taskID)
|
2026-04-28 10:08:20 +00:00
|
|
|
|
|
|
|
|
var lastErr error
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
var attemptCtx context.Context
|
2026-04-28 10:08:20 +00:00
|
|
|
for attempt := 0; attempt <= maxRetry; attempt++ {
|
|
|
|
|
if attempt > 0 {
|
|
|
|
|
backoff := time.Duration(attempt) * 5 * time.Second
|
|
|
|
|
if backoff > 30*time.Second {
|
|
|
|
|
backoff = 30 * time.Second
|
|
|
|
|
}
|
|
|
|
|
logger.Infof(ctx, "[SyncTask] Retrying task type=%s id=%s attempt=%d/%d backoff=%s",
|
|
|
|
|
task.Type(), taskID, attempt, maxRetry, backoff)
|
|
|
|
|
time.Sleep(backoff)
|
|
|
|
|
}
|
|
|
|
|
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
var cancel context.CancelFunc
|
|
|
|
|
attemptCtx, cancel = options.attemptContext(types.WithTaskRetryMetadata(ctx, attempt, maxRetry))
|
2026-09-22 11:58:10 +00:00
|
|
|
// An unrecovered panic here would take down the whole process.
|
|
|
|
|
lastErr = asynqdl.CallRecovered(attemptCtx, task, handler)
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
cancel()
|
2026-04-28 10:08:20 +00:00
|
|
|
if lastErr == nil {
|
|
|
|
|
logger.Infof(ctx, "[SyncTask] Task completed type=%s id=%s elapsed=%v",
|
|
|
|
|
task.Type(), taskID, time.Since(start))
|
|
|
|
|
return
|
|
|
|
|
}
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
if errors.Is(lastErr, asynq.SkipRetry) {
|
|
|
|
|
break
|
|
|
|
|
}
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
2026-04-28 10:08:20 +00:00
|
|
|
|
|
|
|
|
logger.Errorf(ctx, "[SyncTask] Task failed (exhausted retries) type=%s id=%s elapsed=%v err=%v",
|
|
|
|
|
task.Type(), taskID, time.Since(start), lastErr)
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
if onFinalFailure != nil {
|
|
|
|
|
// The attempt's own context may be past its deadline; the
|
|
|
|
|
// callback only writes status, so give it a fresh bound.
|
|
|
|
|
cbCtx, cancel := context.WithTimeout(context.WithoutCancel(attemptCtx), 30*time.Second)
|
|
|
|
|
defer cancel()
|
|
|
|
|
func() {
|
|
|
|
|
defer func() {
|
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
|
logger.Errorf(ctx, "[SyncTask] final-failure hook panicked for type=%s id=%s: %v",
|
|
|
|
|
task.Type(), taskID, r)
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
onFinalFailure(cbCtx, task, lastErr)
|
|
|
|
|
}()
|
|
|
|
|
}
|
2026-02-28 05:22:07 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
return info, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type SyncTaskParams struct {
|
|
|
|
|
dig.In
|
|
|
|
|
|
|
|
|
|
Executor *SyncTaskExecutor
|
|
|
|
|
KnowledgeService interfaces.KnowledgeService
|
|
|
|
|
KnowledgeBaseService interfaces.KnowledgeBaseService
|
|
|
|
|
TagService interfaces.KnowledgeTagService
|
2026-03-27 07:02:40 +00:00
|
|
|
DataSourceService interfaces.DataSourceService
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
SpanTracker service.SpanTracker
|
2026-02-28 05:22:07 +00:00
|
|
|
ChunkExtractor interfaces.TaskHandler `name:"chunkExtractor"`
|
|
|
|
|
DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`
|
|
|
|
|
ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`
|
2026-04-16 06:59:23 +00:00
|
|
|
KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"`
|
2026-08-05 13:56:58 +00:00
|
|
|
KnowledgeAutoTag interfaces.TaskHandler `name:"knowledgeAutoTag"`
|
feat(knowledge): derive knowledge base descriptions from document profiles (#3370)
* feat(knowledge): derive knowledge base descriptions from document profiles
Knowledge bases only had a hand-written description, which most users
leave empty, so agents bound to several knowledge bases had nothing to
route on and searched all of them. This adds a generated description
that is derived from per-document data instead of maintained by a model.
Document profile: the summary call now returns JSON with a 2-3 sentence
summary plus a gist, 3-5 topic keywords, a document type and one
typical question (knowledges.profile). Input is capped at 8k chars and
output at 1024 tokens; plain-text replies from custom templates still
work and simply carry no profile. The summary chunk embeds the gist and
short summary.
Knowledge base aggregate: a database-only fold over those rows (counts
per file type, tag, normalized topic and doc type; stratified samples of
titles and questions; a hash of the inputs). Deleting, moving or
re-parsing a document changes nothing but the rows, so the next rebuild
is exact without any model judgement.
Description text: one small model call over the aggregate yields a
gist, merged topics and typical questions (knowledge_bases.
generated_profile). The call is skipped when the aggregate hash is
unchanged; failures keep the previous text and record the error; an
empty knowledge base clears it. The manual description is never
touched, and the agent runtime context renders both so the model can
pass knowledge_base_ids instead of fanning out.
Refreshes are requested from summary task exit, post-process completion,
deletion, cross-KB moves and enabling the option, debounced per
knowledge base in 30 s windows via kb:profile on the summary queue.
POST /knowledge-bases/:id/profile/generate regenerates synchronously.
profile_config (enabled, model_id, custom_instructions) opts a document
knowledge base in; the settings dialog shows the generated card with
regenerate and adopt-as-description actions in five locales. Search
results now log hits per chunk type so the value of indexing summary
chunks can be measured.
Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the
SQLite schema test expects the new version and columns.
* fix(knowledge): keep generated descriptions out of duplicates and refresh clones
DuplicateKnowledgeBase copies the source row through JSON, which carried
generated_profile onto a knowledge base that has no documents yet, so
an empty duplicate advertised the source's topics. The duplicate now
starts without a generated description and keeps profile_config so it
derives its own once documents arrive.
CopyKnowledgeBase builds the target field by field and skipped
profile_config, and the clone task never asked for a description after
copying the documents, so a clone stayed undescribed until its next
upload. The target now carries a copy of profile_config and both clone
paths request a refresh on completion.
* fix(knowledge): refresh the loaded clone target and carry document profiles
ProcessKBClone requested the description refresh with the reservation
stub it builds before CopyKnowledgeBase runs. For the main create path
that stub has neither a type nor profile_config, so the refresh helper
rejected it and nothing was enqueued. The refresh now uses the loaded
target returned by CopyKnowledgeBase.
cloneKnowledge copied the summary text but not the structured profile,
so even a scheduled refresh would have aggregated titles without topics
until every clone was re-summarized. Cloned documents now carry an
independent copy of the profile.
2026-09-17 14:21:55 +00:00
|
|
|
KnowledgeBaseProfile interfaces.TaskHandler `name:"knowledgeBaseProfile"`
|
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
|
|
|
WikiIngest interfaces.TaskHandler `name:"wikiIngest"`
|
2026-09-26 06:57:16 +00:00
|
|
|
TemporaryDocument interfaces.TemporaryDocumentService
|
|
|
|
|
MemoryService interfaces.MemoryService
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RegisterSyncHandlers registers all task handlers on the SyncTaskExecutor.
|
|
|
|
|
// Used in Lite mode instead of RunAsynqServer.
|
|
|
|
|
func RegisterSyncHandlers(params SyncTaskParams) {
|
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696)
Reparse:
- Open the new attempt only after override validation and cleanup pass.
A rejected reparse used to leave the previous run's subtasks treating
themselves as superseded, so the row stayed in finalizing for good.
- Cancel the previous run's queued tasks when it is still in flight.
ProcessDocument, processChunks, post-process, image tasks, wiki ops and
the dead-letter callback now skip work that belongs to a superseded
attempt.
- Summary tasks write only their own columns. A full-row save after the
LLM call could put finalizing over the new run's processing row.
Errors that were acked with the row still in flight:
- A failed post-process enqueue is retried in place and then returned,
so the task retries instead of leaving the row in processing.
- Transient tenant/knowledge reads and the processing write now retry.
- An image whose orphan check fails on its final attempt is still
counted. Empty manual content fails the row.
Counters:
- FinalizeSubtask runs its decrement and promote in one transaction.
Slot releases retry, and the post-process shortfall release keeps
going past a failed release.
Wiki:
- A synthesis model that cannot be built releases the KB's pending
documents on the final attempt instead of retrying forever.
- Panics in map/reduce workers become per-document failures.
- Housekeeping protects a row held by a wiki op for at most 48h.
Lite mode:
- SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry,
Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the
same final-failure callback as the dead-letter middleware.
- The multimodal fan-in counter is kept in process, so post-process
waits for every image.
Also:
- Housekeeping recovers summaries left pending on finished rows. Cancel
and stall recovery close unfinished summaries.
- Housekeeping sweeps no longer overlap.
- Data source URL ingest writes only the metadata column.
- The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
|
|
|
// Same callback the asynq dead-letter middleware runs in standard mode.
|
|
|
|
|
if failer := newDeadLetterKnowledgeFailer(params.KnowledgeService, params.SpanTracker); failer != nil {
|
|
|
|
|
params.Executor.SetFinalFailureHook(failer)
|
|
|
|
|
}
|
2026-02-28 05:22:07 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeChunkExtract, params.ChunkExtractor.Handle)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeDataTableSummary, params.DataTableSummary.Handle)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeDocumentProcess, params.KnowledgeService.ProcessDocument)
|
2026-07-16 06:48:20 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeTemporaryDocumentProcess, params.TemporaryDocument.Process)
|
2026-03-17 11:26:29 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeManualProcess, params.KnowledgeService.ProcessManualUpdate)
|
2026-02-28 05:22:07 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeFAQImport, params.KnowledgeService.ProcessFAQImport)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeQuestionGeneration, params.KnowledgeService.ProcessQuestionGeneration)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeSummaryGeneration, params.KnowledgeService.ProcessSummaryGeneration)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeKBClone, params.KnowledgeService.ProcessKBClone)
|
2026-03-09 05:14:42 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeMove, params.KnowledgeService.ProcessKnowledgeMove)
|
2026-02-28 05:22:07 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeListDelete, params.KnowledgeService.ProcessKnowledgeListDelete)
|
2026-06-25 15:51:38 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeListReparse, params.KnowledgeService.ProcessKnowledgeListReparse)
|
2026-02-28 05:22:07 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeIndexDelete, params.TagService.ProcessIndexDelete)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeKBDelete, params.KnowledgeBaseService.ProcessKBDelete)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeImageMultimodal, params.ImageMultimodal.Handle)
|
2026-04-16 06:59:23 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)
|
2026-08-05 13:56:58 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeAutoTag, params.KnowledgeAutoTag.Handle)
|
feat(knowledge): derive knowledge base descriptions from document profiles (#3370)
* feat(knowledge): derive knowledge base descriptions from document profiles
Knowledge bases only had a hand-written description, which most users
leave empty, so agents bound to several knowledge bases had nothing to
route on and searched all of them. This adds a generated description
that is derived from per-document data instead of maintained by a model.
Document profile: the summary call now returns JSON with a 2-3 sentence
summary plus a gist, 3-5 topic keywords, a document type and one
typical question (knowledges.profile). Input is capped at 8k chars and
output at 1024 tokens; plain-text replies from custom templates still
work and simply carry no profile. The summary chunk embeds the gist and
short summary.
Knowledge base aggregate: a database-only fold over those rows (counts
per file type, tag, normalized topic and doc type; stratified samples of
titles and questions; a hash of the inputs). Deleting, moving or
re-parsing a document changes nothing but the rows, so the next rebuild
is exact without any model judgement.
Description text: one small model call over the aggregate yields a
gist, merged topics and typical questions (knowledge_bases.
generated_profile). The call is skipped when the aggregate hash is
unchanged; failures keep the previous text and record the error; an
empty knowledge base clears it. The manual description is never
touched, and the agent runtime context renders both so the model can
pass knowledge_base_ids instead of fanning out.
Refreshes are requested from summary task exit, post-process completion,
deletion, cross-KB moves and enabling the option, debounced per
knowledge base in 30 s windows via kb:profile on the summary queue.
POST /knowledge-bases/:id/profile/generate regenerates synchronously.
profile_config (enabled, model_id, custom_instructions) opts a document
knowledge base in; the settings dialog shows the generated card with
regenerate and adopt-as-description actions in five locales. Search
results now log hits per chunk type so the value of indexing summary
chunks can be measured.
Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the
SQLite schema test expects the new version and columns.
* fix(knowledge): keep generated descriptions out of duplicates and refresh clones
DuplicateKnowledgeBase copies the source row through JSON, which carried
generated_profile onto a knowledge base that has no documents yet, so
an empty duplicate advertised the source's topics. The duplicate now
starts without a generated description and keeps profile_config so it
derives its own once documents arrive.
CopyKnowledgeBase builds the target field by field and skipped
profile_config, and the clone task never asked for a description after
copying the documents, so a clone stayed undescribed until its next
upload. The target now carries a copy of profile_config and both clone
paths request a refresh on completion.
* fix(knowledge): refresh the loaded clone target and carry document profiles
ProcessKBClone requested the description refresh with the reservation
stub it builds before CopyKnowledgeBase runs. For the main create path
that stub has neither a type nor profile_config, so the refresh helper
rejected it and nothing was enqueued. The refresh now uses the loaded
target returned by CopyKnowledgeBase.
cloneKnowledge copied the summary text but not the structured profile,
so even a scheduled refresh would have aggregated titles without topics
until every clone was re-summarized. Cloned documents now carry an
independent copy of the profile.
2026-09-17 14:21:55 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeBaseProfile, params.KnowledgeBaseProfile.Handle)
|
2026-03-27 07:02:40 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)
|
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeWikiIngest, params.WikiIngest.Handle)
|
2026-07-09 05:27:47 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeWikiFinalize, params.WikiIngest.Handle)
|
2026-08-13 07:09:12 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeMemoryExtract, params.MemoryService.Handle)
|
2026-02-28 05:22:07 +00:00
|
|
|
logger.Infof(context.Background(), "[SyncTask] All task handlers registered (Lite mode, no Redis)")
|
|
|
|
|
}
|