Files
warmbly/internal/app/warmupcontent/service.go
T

285 lines
9.8 KiB
Go

// Package warmupcontent runs the offline warmup-content generator: it calls
// the AI client, lints each result, and caches accepted threads in the
// warmup_conversations bank for the live send path to draw from. Generation is
// always scheduled offline and never runs on the send hot path.
package warmupcontent
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/warmbly/warmbly/internal/pkg/generation"
"github.com/warmbly/warmbly/internal/pkg/typesafe"
"github.com/warmbly/warmbly/internal/repository"
)
// ErrNotConfigured is returned when generation is requested but no AI client is
// wired (the provider is not OpenAI or AI_API_KEY is unset).
var ErrNotConfigured = errors.New("warmup AI generation is not configured")
var ErrGenerationStopped = errors.New("warmup content generation is stopped")
// defaultThemes seed topic variety when a generation run doesn't pin a theme.
var defaultThemes = []string{
"productivity", "learning a new skill", "collaboration", "industry trends", "tools and workflow",
"networking", "giving feedback", "quarterly planning", "book recommendations", "wellness",
"conferences and meetups", "career growth", "remote work setups", "meetings", "team culture",
"customer support", "writing clearly", "travel tips", "local community", "hiring and interviews",
"mentoring", "documentation", "podcasts", "cooking", "weekend hobbies", "running and cycling",
"home office", "coffee and tea", "language learning", "photography", "gardening", "moving house",
"volunteering", "presentations", "note-taking", "project handoffs", "freelancing", "small business seasons",
"design and layout", "spreadsheets", "naming things", "backing up files", "onboarding new teammates",
"retrospectives", "saying no to extra scope", "time off and rest", "music practice", "board games",
}
// maxPerBatch bounds a single Batch API submission. Batch is async and cheap so
// it tolerates a much larger fan-out than the sync path; OpenAI itself allows up
// to 50,000 requests per batch input file.
const maxPerBatch = 2000
const (
minimumAdaptiveThreads = 200
maximumAdaptiveThreads = 5000
scheduledBatchMax = 250
)
// AdaptiveThreadTarget sizes the bank from recent demand while bounding model
// spend. The configured target is a floor, not an ongoing tuning obligation.
func AdaptiveThreadTarget(sevenDaySends, configuredFloor int) int {
if configuredFloor <= 0 {
configuredFloor = minimumAdaptiveThreads
}
averageDaily := (sevenDaySends + 6) / 7
target := averageDaily
if target < configuredFloor {
target = configuredFloor
}
if target > maximumAdaptiveThreads {
target = maximumAdaptiveThreads
}
return target
}
// GenerateRequest describes one generation run.
type GenerateRequest struct {
RequestedBy *uuid.UUID
Trigger string // "schedule"
PoolType string
Segment string
Theme string
Model string
Count int
// MaxMessages overrides the per-thread follow-up count for this run; 0 falls
// back to the controller policy.
MaxMessages int
// CompletionWindow is the OpenAI Batch API processing window (batch path
// only); empty defaults to "24h".
CompletionWindow string
}
// Service drives offline warmup content generation.
type Service interface {
// GenerateBatch submits an async OpenAI Batch API run (~50% cheaper) and
// returns the job ID immediately. Results are ingested later by PollBatches.
GenerateBatch(ctx context.Context, req GenerateRequest) (uuid.UUID, error)
// PollBatches reconciles in-flight batch jobs against OpenAI: it ingests
// what a finished, expired or cancelled batch produced and marks the
// job failed only when it produced nothing.
PollBatches(ctx context.Context) error
// CancelBatch asks OpenAI to cancel an in-flight batch; the job stays
// running until PollBatches ingests what finished before the cancel.
CancelBatch(ctx context.Context, jobID uuid.UUID) error
// RunScheduled tops every enabled pool/segment up toward its target.
RunScheduled(ctx context.Context) error
// Enabled reports whether an AI client is configured.
Enabled() bool
// WireJudge selects TypeSafe review; nil uses a separate OpenAI review.
WireJudge(asker typesafe.Asker)
}
type service struct {
repo repository.WarmupContentRepository
gen generationBackend
// judge rejects generated threads that carry a pitch or read as filler.
// Without TypeSafe, the configured generator performs a separate review.
judge typesafe.Asker
}
type generationBackend interface {
CheckModel(context.Context, string) error
SubmitBatch(context.Context, []generation.BatchRequest, string) (string, string, error)
GetBatch(context.Context, string) (generation.BatchState, error)
CancelBatch(context.Context, string) error
FetchBatchResults(context.Context, string) ([]generation.BatchResult, error)
ReviewConversation(context.Context, generation.Conversation, string) (*generation.WarmupReview, error)
}
// NewService creates the generation service. gen may be nil (provider not OpenAI),
// in which case generation requests return ErrNotConfigured.
func NewService(repo repository.WarmupContentRepository, gen *generation.GenerationClient) Service {
svc := &service{repo: repo}
if gen != nil {
svc.gen = gen
}
return svc
}
func (s *service) Enabled() bool { return s.gen != nil }
func (s *service) WireJudge(asker typesafe.Asker) { s.judge = asker }
func (s *service) RunScheduled(ctx context.Context) error {
if s.gen == nil {
return nil
}
settings, err := s.repo.GetGenerationSettings(ctx)
if err != nil || settings == nil {
return err
}
if !settings.GenerationEnabled || !settings.ScheduleEnabled {
return nil
}
if expired, err := s.repo.ExpireStaleScheduledJobs(ctx, time.Now().Add(-15*time.Minute)); err != nil {
return err
} else if expired > 0 {
log.Warn().Int64("expired", expired).Msg("warmup generation: released stale batch reservations")
}
if retired, err := s.repo.RetireRiskyConversations(ctx, time.Now().AddDate(0, 0, -14), 20, 3, 0.15); err != nil {
return err
} else if retired > 0 {
log.Warn().Int("retired", retired).Msg("warmup generation: retired threads with unsafe spam placement")
}
remaining := dailyRemaining(ctx, s.repo, settings.DailyGenerationCap)
if settings.DailyGenerationCap > 0 && remaining <= 0 {
log.Info().Msg("warmup generation: daily cap reached; scheduled run skipped")
return nil
}
mailboxDemand, err := s.repo.WarmupMailboxDemandSince(ctx, time.Now().AddDate(0, 0, -7))
if err != nil {
return err
}
var scheduleErr error
for _, pool := range settings.Pools {
if !pool.Enabled {
continue
}
segmentSet := map[string]struct{}{"": {}}
for _, segment := range pool.Segments {
segmentSet[segment] = struct{}{}
}
for segment := range segmentSet {
active, err := s.repo.CountAvailableConversations(ctx, pool.PoolType, segment)
if err != nil {
return err
}
target := AdaptiveThreadTarget(mailboxDemand, pool.TargetActiveThreads)
// Refresh unused stock within the replacement budget; preserve ongoing threads.
if settings.RefreshEnabled && active >= target {
recycle := settings.RefreshPerRun
if recycle > 25 {
recycle = 25
}
if settings.DailyGenerationCap > 0 && recycle > remaining {
recycle = remaining
}
if recycle > 0 {
retired, err := s.repo.RefreshUnusedConversations(ctx, pool.PoolType, segment, recycle)
if err != nil {
log.Warn().Err(err).Str("segment", segment).Msg("warmup generation: refresh retirement failed")
} else if retired > 0 {
active -= retired
log.Info().Int("retired", retired).Str("segment", segment).Msg("warmup generation: recycled unused threads for refresh")
}
}
}
deficit := target - active
if deficit <= 0 {
continue
}
count := deficit
if count > scheduledBatchMax {
count = scheduledBatchMax
}
if settings.DailyGenerationCap > 0 && count > remaining {
count = remaining
}
if count <= 0 {
continue
}
// Scheduled work is asynchronous and discounted. It never holds the
// scheduler loop open on model latency, and the durable job is picked up
// by the batch poller after restarts.
_, err = s.GenerateBatch(ctx, GenerateRequest{
Trigger: "schedule",
PoolType: pool.PoolType,
Segment: segment,
Model: settings.Model,
Count: count,
})
if errors.Is(err, repository.ErrScheduledGenerationInFlight) {
// Its output is not in the bank until the poller ingests it, so the deficit stands meanwhile.
continue
}
if err != nil {
log.Warn().Err(err).Str("segment", segment).Msg("warmup generation: scheduled batch not submitted")
scheduleErr = errors.Join(scheduleErr, fmt.Errorf("warmup batch submission failed for %s: %w", segmentLabel(segment), err))
continue
}
if settings.DailyGenerationCap > 0 {
remaining -= count
if remaining <= 0 {
return scheduleErr
}
}
}
}
return scheduleErr
}
// segmentLabel names a library segment; "" is the shared library every mailbox draws from.
func segmentLabel(segment string) string {
if segment == "" {
return "the shared library"
}
return fmt.Sprintf("segment %q", segment)
}
func cleanMessages(in []string) []string {
out := make([]string, 0, len(in))
for _, m := range in {
m = strings.TrimSpace(m)
out = append(out, m)
}
return out
}
// Only surrounding whitespace may change; reply positions and facts are fixed.
func preserveCanonicalThread(subject, description string, messages []string) (string, string, []string) {
return strings.TrimSpace(subject), strings.TrimSpace(description), cleanMessages(messages)
}
func dailyRemaining(ctx context.Context, repo repository.WarmupContentRepository, dailyCap int) int {
if dailyCap <= 0 {
return 1 << 30 // effectively unlimited
}
since := time.Now().Truncate(24 * time.Hour)
used, err := repo.ReservedGenerationCountSince(ctx, since)
if err != nil {
return 0
}
return dailyCap - used
}