This commit is contained in:
greeneclipse committed 2026-10-27 14:53:19 +01:00
1 parent c347d2418f
commit 1ad180a052
49 files changed
+6339 -89

No files matched your search

+3
View File
@@ -116,6 +116,9 @@ type ProductInput struct {
// CategoryAttrKeys maps category unique_id → attribute keys (job cache).
// When set, enhance resolves allowlist from the step result category.
CategoryAttrKeys map[string]map[string]struct{}
// FeedAttrKeys are the supplier's parsed spec keys (set by StepParseSpecs). For an
// uncategorized product they extend the core allowlist so feed specs survive.
FeedAttrKeys map[string]struct{}
// Prior* are loaded from the last processed_products row for this raw product.
PriorEnhanceHash string
PriorProcessedName string
@@ -42,7 +42,7 @@ func BackfillCompanyProcessedAttributes(ctx context.Context, pool *pgxpool.Pool,
}
attrs := decodeAttrMap(attrsJSON)
procAttrs := decodeAttrMap(procAttrsJSON)
allowed := allowedAttrKeysFromSets(sets, category)
allowed := persistAllowedAttrKeys(sets, category)
cleanAttrs := AttrsForPersist(attrs, allowed)
cleanProc := AttrsForPersist(procAttrs, allowed)
if len(cleanProc) == 0 {
+24 -35
View File
@@ -3,7 +3,6 @@ package processing
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"sort"
@@ -13,12 +12,6 @@ import (
"github.com/descrybe/descrybe-v2/apps/api/internal/aiaudit"
)
// ErrCategoryNotFound fails a product whose category could not be determined:
// the model's pick was outside the taxonomy, or it scored below the confidence
// floor. Processing stops for that product instead of enhancing it under a
// category nobody believes in.
var ErrCategoryNotFound = errors.New("product category could not be determined")
// MaxCategorizeOptions caps the taxonomy list injected into the categorize LLM
// prompt (token/cost bound). Prefer stable sort by display name then unique_id.
const MaxCategorizeOptions = 200
@@ -29,7 +22,8 @@ const MaxCategorizeOptions = 200
// like {"categoryId":"1","confidence":0.08} is the model saying "I do not know" —
// taking it at face value files a camping chair under Generators and then drives
// that category's title/description formula, producing confidently wrong copy.
// Below this floor the product fails with ErrCategoryNotFound instead.
// Below this floor the pick is discarded and the product continues uncategorized
// (generic enhance template, feed attributes kept) instead of under a wrong formula.
const DefaultMinCategorizeConfidence = 0.75
// MaxTokensCategorize budgets a short JSON reply {"categoryId","confidence"}.
@@ -134,16 +128,17 @@ func ProductCategorizeUser(name, description string, opts []categoryOption) stri
// tryAICategorize asks the Completer to pick a company taxonomy unique_id when
// Category is still empty after mapped/prior/vector. Never invents outside taxonomy:
// responses are coerced then filtered to namesByUID / valid unique_ids.
func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in ProductInput, policy StepPolicy) error {
// responses are coerced then filtered to namesByUID / valid unique_ids. A rejected
// pick leaves Category empty; supplier feeds without categories must still process.
func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in ProductInput, policy StepPolicy) {
if out == nil || strings.TrimSpace(out.Category) != "" {
return nil
return
}
if !policy.AllowAI {
return nil
return
}
if e == nil || !e.CompleterEnabled() {
return nil
return
}
opts := categoryOptionsFromNames(in.CategoryNamesByUID)
if len(opts) == 0 {
@@ -152,7 +147,7 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"status": "skipped",
"reason": "no_taxonomy",
})
return nil
return
}
name := strings.TrimSpace(out.Name)
if name == "" {
@@ -168,7 +163,7 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"status": "skipped",
"reason": "empty_product",
})
return nil
return
}
system := ProductCategorizeSystem
@@ -185,7 +180,7 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"error": TruncateError(err),
"tokens": comp.TotalTokens,
})
return nil
return
}
raw := categoryIDFromCategorizeJSON(obj)
@@ -202,12 +197,13 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"returned": raw,
"tokens": comp.TotalTokens,
})
return fmt.Errorf("%w: model returned %q, which is not in the company taxonomy",
ErrCategoryNotFound, truncateRunes(raw, 60))
log.Printf("processing: category rejected returned=%q reason=not_in_taxonomy; continuing uncategorized",
truncateRunes(raw, 60))
return
}
// A confident-looking id with a low score is the model guessing. Refuse it
// rather than driving the wrong category's formula with it.
// rather than driving the wrong category's formula with it; process uncategorized.
if min := policy.CategorizeConfidence(); hasConfidence && confidence < min {
out.Notes = append(out.Notes, fmt.Sprintf(
"ai_categorize: no category found (confidence %.2f below %.2f)", confidence, min))
@@ -219,10 +215,9 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
"minimum": min,
"tokens": comp.TotalTokens,
})
log.Printf("processing: category rejected uid=%s confidence=%.2f min=%.2f reason=low_confidence",
log.Printf("processing: category rejected uid=%s confidence=%.2f min=%.2f reason=low_confidence; continuing uncategorized",
resolved, confidence, min)
return fmt.Errorf("%w: best match %q scored %.2f, below the %.2f minimum",
ErrCategoryNotFound, truncateRunes(resolved, 60), confidence, min)
return
}
out.Category = SanitizeText(resolved)
@@ -244,7 +239,6 @@ func tryAICategorize(ctx context.Context, e *Engine, out *StepResult, in Product
if hasConfidence {
out.Notes = append(out.Notes, fmt.Sprintf("ai_categorize: confidence %.2f", confidence))
}
return nil
}
// categorizeConfidenceFromJSON reads the model's self-reported score. ok=false when
@@ -317,12 +311,10 @@ func firstAvailableCategoryIDFromPrompt(user string) string {
}
// runCategorizeStep applies vector then LLM taxonomy selection when Category empty.
// runCategorizeStep returns ErrCategoryNotFound when the model was asked for a
// category and could not give a usable one — the caller fails the product rather
// than enhancing it under a guess.
func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *StepResult, in ProductInput, categoryNames []string, policy StepPolicy) error {
// Category is optional: when nothing usable is found the product continues without one.
func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *StepResult, in ProductInput, categoryNames []string, policy StepPolicy) {
if out == nil {
return nil
return
}
if strings.TrimSpace(out.Category) != "" {
appendStepLog(out.GPTResponse, StepCategorize, map[string]any{
@@ -330,7 +322,7 @@ func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *St
"reason": "already_set",
"category": out.Category,
})
return nil
return
}
if !policy.AllowAI {
out.Notes = append(out.Notes, "categorize: skipped (AI not allowed)")
@@ -338,24 +330,21 @@ func runCategorizeStep(ctx context.Context, e *Engine, companyID string, out *St
"status": "skipped",
"reason": "entitlement_can_use_ai",
})
return nil
return
}
tryVectorCategorize(ctx, e, companyID, out, categoryNames, policy)
if strings.TrimSpace(out.Category) != "" {
return nil
return
}
// Taxonomy picks and copy generation share one Completer; tag the role so the
// admin inspector can tell them apart.
if err := tryAICategorize(aiaudit.WithCall(ctx, aiaudit.CallContext{Role: aiaudit.RoleCategorize}), e, out, in, policy); err != nil {
return err
}
tryAICategorize(aiaudit.WithCall(ctx, aiaudit.CallContext{Role: aiaudit.RoleCategorize}), e, out, in, policy)
if strings.TrimSpace(out.Category) == "" {
appendStepLog(out.GPTResponse, StepCategorize, map[string]any{
"status": "unset",
"reason": "no_vector_or_ai_match",
})
}
return nil
}
// MappedCategorySourceKey marks a mapped_data.category this pipeline wrote itself.
@@ -2,7 +2,6 @@ package processing
import (
"context"
"errors"
"strings"
"testing"
)
@@ -63,20 +62,15 @@ func TestTryAICategorize_rejectsInventedID(t *testing.T) {
}},
Vector: NoopVectorCategorizer{},
}
// An id outside the taxonomy means the category could not be determined. The
// product must fail rather than continue uncategorised into enhance, which
// would generate copy with no formula behind it.
// An id outside the taxonomy is never stored; the product continues uncategorized.
out, err := e.RunSteps(context.Background(), "co", ProductInput{
Name: "Widget",
CategoryNamesByUID: map[string]string{
"50": "Štedilniki",
},
}, "full", nil, StepPolicy{AllowAI: true})
if !errors.Is(err, ErrCategoryNotFound) {
t.Fatalf("err=%v want ErrCategoryNotFound", err)
}
if !strings.Contains(err.Error(), "99999") {
t.Fatalf("error should name the rejected id, got %v", err)
if err != nil {
t.Fatalf("an invented id must not fail the product, got %v", err)
}
if out.Category != "" {
t.Fatalf("Category=%q want empty (invented id rejected)", out.Category)
@@ -2,7 +2,6 @@ package processing
import (
"context"
"errors"
"fmt"
"strings"
"testing"
@@ -37,27 +36,28 @@ func categorizeInput() ProductInput {
// The reported case: the model always answers with SOME id, so a low score is it
// saying "I do not know". Taking it at face value files a camping chair under
// Generators and then drives that category's formula.
func TestRunSteps_lowConfidenceCategoryFailsTheProduct(t *testing.T) {
// Generators and then drives that category's formula. The guess is discarded, but
// the product still processes uncategorized (supplier feeds often have no category).
func TestRunSteps_lowConfidenceCategoryProcessesUncategorized(t *testing.T) {
t.Parallel()
e, enhanceCalls := categorizeEngine(`{"categoryId":"1","confidence":0.08}`)
out, err := e.RunSteps(context.Background(), "co", categorizeInput(), "full", nil,
StepPolicy{AllowAI: true})
if !errors.Is(err, ErrCategoryNotFound) {
t.Fatalf("err=%v want ErrCategoryNotFound", err)
}
for _, want := range []string{"0.08", "0.75"} {
if !strings.Contains(err.Error(), want) {
t.Fatalf("error should report the score and the minimum, got %v", err)
}
if err != nil {
t.Fatalf("an undetermined category must not fail the product, got %v", err)
}
if out.Category != "" {
t.Fatalf("a rejected pick must not be persisted, got %q", out.Category)
}
// The whole point: stop before spending an enhance call on the wrong category.
if *enhanceCalls != 0 {
t.Fatalf("enhance ran %d time(s) after the category was rejected", *enhanceCalls)
notes := strings.Join(out.Notes, " ")
for _, want := range []string{"0.08", "0.75"} {
if !strings.Contains(notes, want) {
t.Fatalf("notes should report the score and the minimum, got %v", out.Notes)
}
}
if *enhanceCalls == 0 {
t.Fatal("enhance should still run without a category")
}
}
+11 -1
View File
@@ -1124,6 +1124,16 @@ func categoryAttrKeysFromCache(cache *jobScopedCache) map[string]map[string]stru
return cache.categoryAttrKeys
}
// persistAllowedAttrKeys is the post-RunSteps allowlist. Uncategorized attrs were
// already limited to core + supplier spec keys inside RunSteps, so they are only
// sanitized here; re-filtering to core keys would drop the supplier's specs.
func persistAllowedAttrKeys(sets map[string]map[string]struct{}, categoryUID string) map[string]struct{} {
if strings.TrimSpace(categoryUID) == "" {
return nil
}
return allowedAttrKeysFromSets(sets, categoryUID)
}
// allowedAttrKeysFromSets picks category keys when present; empty non-nil → core only.
// When sets is nil, returns nil (sanitize-only / unit tests).
func allowedAttrKeysFromSets(sets map[string]map[string]struct{}, categoryUID string) map[string]struct{} {
@@ -1684,7 +1694,7 @@ func (p *Pipeline) processOne(ctx context.Context, companyID, jobID uuid.UUID, i
syncCategoryName(&result, cache.categoryNamesByUID)
}
// Re-apply after category validation so allowlist matches the persisted category.
allowed := allowedAttrKeysForCategory(cache, result.Category)
allowed := persistAllowedAttrKeys(categoryAttrKeysFromCache(cache), result.Category)
result.Attributes = AttrsForPersist(result.Attributes, allowed)
result.ProcessedAttributes = AttrsForPersist(result.ProcessedAttributes, allowed)
if len(result.ProcessedAttributes) == 0 {
+20 -1
View File
@@ -235,13 +235,32 @@ func AttrsForPersist(attrs map[string]any, allowed map[string]struct{}) map[stri
// enhanceAllowedAttrKeys prefers category_attributes for the resolved category;
// falls back to AllowedAttrKeys (nil = sanitize-only for unit tests).
// Uncategorized products have no schema to enforce, so the supplier's own spec keys
// are allowed too: the model may refine them but cannot invent new keys.
func enhanceAllowedAttrKeys(in ProductInput, categoryUID string) map[string]struct{} {
if in.CategoryAttrKeys != nil {
return allowedAttrKeysFromSets(in.CategoryAttrKeys, categoryUID)
allowed := allowedAttrKeysFromSets(in.CategoryAttrKeys, categoryUID)
if strings.TrimSpace(categoryUID) == "" {
for k := range in.FeedAttrKeys {
allowed[k] = struct{}{}
}
}
return allowed
}
return in.AllowedAttrKeys
}
// attrKeySet returns the canonical keys of attrs (see FilterAttributesByAllowed).
func attrKeySet(attrs map[string]any) map[string]struct{} {
out := make(map[string]struct{}, len(attrs))
for k := range attrs {
if canon := canonicalizeAttrKey(k); canon != "" {
out[canon] = struct{}{}
}
}
return out
}
// FilterAttributesByAllowed keeps coreCharacteristicAttrKeys plus keys present in
// allowed (after canonicalizeAttrKey). When allowed is nil, returns attrs unchanged.
func FilterAttributesByAllowed(attrs map[string]any, allowed map[string]struct{}) map[string]any {
+4 -8
View File
@@ -95,6 +95,7 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
}
}
attrs = SanitizeProductAttributes(parsed)
in.FeedAttrKeys = attrKeySet(attrs)
// Map feed/spec labels onto category_attributes (formula) keys early.
if allowed := enhanceAllowedAttrKeys(in, out.Category); allowed != nil {
attrs = MapAttrsOntoAllowedKeys(attrs, allowed)
@@ -225,11 +226,8 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
case StepCategorize:
// Vector (if enabled) then LLM taxonomy pick when category still empty.
// A category the model could not determine fails the product here, before
// enhance spends a call writing copy for the wrong category.
if err := runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy); err != nil {
return out, err
}
// An undetermined category leaves the product uncategorized; it still processes.
runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy)
case StepAIEnhance:
preservePriorEnhanceHash := func() {
@@ -569,9 +567,7 @@ func (e *Engine) RunSteps(ctx context.Context, companyID string, in ProductInput
// Pipelines without StepCategorize (normalize_only) still run vector + LLM
// categorize when category is empty so downstream steps are not fed a blank.
if !stepsContain(steps, StepCategorize) {
if err := runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy); err != nil {
return out, err
}
runCategorizeStep(ctx, e, companyID, &out, in, categoryNames, policy)
}
// Record why category stayed empty for every pipeline, including the ones that
// now categorize inside the loop (enhance / title / description).
@@ -0,0 +1,49 @@
package processing
import (
"context"
"testing"
)
// Supplier feeds without categories (pilot: Koopman, Trbovc Excel) must keep their
// own specs; the model may refine those keys but not invent new ones.
func TestRunSteps_uncategorizedKeepsSupplierSpecs(t *testing.T) {
t.Parallel()
e := &Engine{
Completer: stubCompleter{fn: func(system, user string) (Completion, error) {
return Completion{
Text: `{"name":"Advent wreath gold 41 cm","description":"<p>Gold wreath.</p>","attrs":{"volume_in_m3":"0.882","color":"gold","battery_life":"200 h"}}`,
TotalTokens: 5,
}, nil
}},
Vector: NoopVectorCategorizer{},
}
in := ProductInput{
GTIN: "8721461009242",
Name: "WREATH ADVENT 41CM GOLD",
Mapped: map[string]any{
"name": "WREATH ADVENT 41CM GOLD",
"specifications": map[string]any{"Volume in m3": "0.882", "Statistic no": "06049099"},
},
// Production job cache: taxonomy keys exist, but this product has no category.
CategoryAttrKeys: map[string]map[string]struct{}{},
}
out, err := e.RunSteps(context.Background(), "co", in, "full", nil, StepPolicy{AllowAI: true})
if err != nil {
t.Fatal(err)
}
if out.Category != "" {
t.Fatalf("Category=%q want empty", out.Category)
}
for _, want := range []string{"volume_in_m3", "statistic_no", "color"} {
if _, ok := out.Attributes[want]; !ok {
t.Fatalf("missing %q in %v", want, out.Attributes)
}
}
if _, ok := out.Attributes["battery_life"]; ok {
t.Fatalf("model-invented key persisted: %v", out.Attributes)
}
if got := persistAllowedAttrKeys(map[string]map[string]struct{}{}, ""); got != nil {
t.Fatalf("persist allowlist for uncategorized = %v want nil (already constrained)", got)
}
}