fixes
This commit is contained in:
1 parent
c92ee93482
commit
af670e79f0
9 files changed
+667
-104
No files matched your search
@@ -285,6 +285,11 @@ func isKnownBuiltInVariantSet(prompts company.LangPromptMap, versions []aiprompt
|
||||
}
|
||||
}
|
||||
for lang, val := range prompts {
|
||||
// The v3 localized plain-text template was not in the v6 migration
|
||||
// allowlist, which left non-A1 companies using five 100-word sections.
|
||||
if isExactOldDefaultLanguage(val, lang, versions, cache, historical) {
|
||||
continue
|
||||
}
|
||||
val = strings.TrimSpace(val)
|
||||
if val == "" {
|
||||
continue
|
||||
@@ -346,6 +351,196 @@ func upgradeOldDefault(ctx context.Context, pool *pgxpool.Pool, row categoryRow,
|
||||
return result.RowsAffected() > 0, err
|
||||
}
|
||||
|
||||
// isExactOldDefaultLanguage recognizes prior SHIPPED locale values, including
|
||||
// the v3 plain-text Croatian/Bulgarian instructions that the old migrations
|
||||
// missed. It never matches arbitrary text by language, length or keywords.
|
||||
func isExactOldDefaultLanguage(value, lang string, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation) bool {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
if old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang); err == nil && value == old {
|
||||
return true
|
||||
}
|
||||
if old, err := aiprompts.PreviousOfflineDefaultPromptV6(lang); err == nil && value == old {
|
||||
return true
|
||||
}
|
||||
if lang != "*" && lang != "en" {
|
||||
for _, oldFn := range []func(string) (string, error){aiprompts.PreviousOfflineDefaultPromptV3, aiprompts.PreviousOfflineDefaultPromptV6} {
|
||||
old, err := oldFn(lang)
|
||||
if err == nil && value == aiprompts.ExtractEnhanceSectionBody(old, aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, prior := range versions {
|
||||
if prior.Overlay == "" {
|
||||
continue
|
||||
}
|
||||
if (lang == "*" || lang == "en") && value == strings.TrimSpace(prior.Overlay) {
|
||||
return true
|
||||
}
|
||||
for _, old := range knownCacheValues(prior.Overlay, cache, historical, lang) {
|
||||
if value == strings.TrimSpace(old) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// patchKnownRoleSections upgrades a matching old default ROLE, even when the
|
||||
// company customized an unrelated role (e.g. title). The custom role remains
|
||||
// unchanged. Only exact bundled historical strings qualify for replacement.
|
||||
func patchKnownRoleSections(value, lang, replacement string, versions []aiprompts.CategoryFormulaDefaults) (string, bool) {
|
||||
if !aiprompts.CategoryEnhanceHasRoleSections(value) || !aiprompts.CategoryEnhanceHasRoleSections(replacement) {
|
||||
return "", false
|
||||
}
|
||||
extract := func(prompt, start, end string) string {
|
||||
return aiprompts.ExtractEnhanceSectionBody(prompt, start, end)
|
||||
}
|
||||
starts := [3]string{aiprompts.SectionTitleStart, aiprompts.SectionDescriptionStart, aiprompts.SectionMetaStart}
|
||||
ends := [3]string{aiprompts.SectionTitleEnd, aiprompts.SectionDescriptionEnd, aiprompts.SectionMetaEnd}
|
||||
oldParts := [3]string{}
|
||||
for i := range starts {
|
||||
oldParts[i] = extract(value, starts[i], ends[i])
|
||||
}
|
||||
// Do not normalize a prompt containing preambles, extra text, or custom markup.
|
||||
if strings.TrimSpace(value) != aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
||||
TitleRules: oldParts[0], DescriptionRules: oldParts[1], MetaRules: oldParts[2], WasLegacy: true,
|
||||
}) {
|
||||
return "", false
|
||||
}
|
||||
parts := oldParts
|
||||
changed := false
|
||||
for _, oldFn := range []func(string) (string, error){aiprompts.PreviousOfflineDefaultPromptV3, aiprompts.PreviousOfflineDefaultPromptV6} {
|
||||
old, err := oldFn(lang)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for i := range starts {
|
||||
prev := extract(old, starts[i], ends[i])
|
||||
newText := extract(replacement, starts[i], ends[i])
|
||||
if prev != "" && parts[i] == prev && newText != "" && parts[i] != newText {
|
||||
parts[i] = newText
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
// Older English categories used category-specific built-in naming with
|
||||
// the five-H2 boilerplate. Match only shipped role text; never guess by
|
||||
// counting H2s or searching for marketing words.
|
||||
if lang == "en" {
|
||||
for _, prior := range versions[1:] {
|
||||
if prior.Overlay == "" {
|
||||
continue
|
||||
}
|
||||
for i := range starts {
|
||||
prev := extract(prior.Overlay, starts[i], ends[i])
|
||||
newText := extract(replacement, starts[i], ends[i])
|
||||
if prev != "" && parts[i] == prev && newText != "" && parts[i] != newText {
|
||||
parts[i] = newText
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return "", false
|
||||
}
|
||||
return aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
||||
TitleRules: parts[0], DescriptionRules: parts[1], MetaRules: parts[2], WasLegacy: true,
|
||||
}), true
|
||||
}
|
||||
|
||||
// repairOldLocaleDefaults upgrades specific released default values without
|
||||
// relying on the other language entries or the title/description JSON columns.
|
||||
// This is deliberately separate from the all-or-nothing category upgrade: an
|
||||
// unrelated custom locale or formula must not prevent safe default repairs.
|
||||
func repairOldLocaleDefaults(prompts company.LangPromptMap, versions []aiprompts.CategoryFormulaDefaults, cache, historical map[string]*defaultTranslation, targetLangs []string) (company.LangPromptMap, int) {
|
||||
allowed := map[string]bool{}
|
||||
for _, lang := range targetLangs {
|
||||
allowed[lang] = true
|
||||
}
|
||||
next := make(company.LangPromptMap, len(prompts))
|
||||
updates := 0
|
||||
for lang, value := range prompts {
|
||||
next[lang] = value
|
||||
if lang != "*" && !allowed[lang] {
|
||||
continue
|
||||
}
|
||||
locale := lang
|
||||
if lang == "*" {
|
||||
locale = "en"
|
||||
if !allowed[locale] {
|
||||
continue
|
||||
}
|
||||
}
|
||||
replacement, err := aiprompts.OfflineDefaultPrompt(locale)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if lang == "*" || lang == "en" {
|
||||
replacement = versions[0].Overlay
|
||||
}
|
||||
if strings.TrimSpace(replacement) == strings.TrimSpace(value) {
|
||||
continue
|
||||
}
|
||||
if isExactOldDefaultLanguage(value, lang, versions, cache, historical) {
|
||||
next[lang] = replacement
|
||||
updates++
|
||||
} else if patched, ok := patchKnownRoleSections(value, locale, replacement, versions); ok {
|
||||
next[lang] = patched
|
||||
updates++
|
||||
}
|
||||
}
|
||||
return next, updates
|
||||
}
|
||||
|
||||
// repairOldFormulaField replaces an exact known platform JSON formula, leaving
|
||||
// edited company formulas untouched. A language-agnostic old HTML constraint
|
||||
// can otherwise override an already-migrated localized prompt in the API.
|
||||
func repairOldFormulaField(value string, versions []aiprompts.CategoryFormulaDefaults, title bool) (string, bool) {
|
||||
if len(versions) < 2 {
|
||||
return value, false
|
||||
}
|
||||
current := versions[0].DescriptionTemplateJSON
|
||||
if title {
|
||||
current = versions[0].TitleTemplateJSON
|
||||
}
|
||||
if matchesDefaultFormula(value, current) {
|
||||
return value, false
|
||||
}
|
||||
for _, old := range versions[1:] {
|
||||
previous := old.DescriptionTemplateJSON
|
||||
if title {
|
||||
previous = old.TitleTemplateJSON
|
||||
}
|
||||
if previous != "" && matchesDefaultFormula(value, previous) {
|
||||
return current, true
|
||||
}
|
||||
}
|
||||
return value, false
|
||||
}
|
||||
|
||||
// persistRepairedDefaults applies a compare-and-swap update to all three
|
||||
// columns, even when only a single field changed. Racing admin edits are safe.
|
||||
func persistRepairedDefaults(ctx context.Context, pool *pgxpool.Pool, row categoryRow, next company.LangPromptMap, title, description string) (bool, error) {
|
||||
encoded, err := company.EncodeLangPromptMap(next)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
|
||||
title_template = NULLIF($5, '')::jsonb,
|
||||
description_template = NULLIF($6, '')::jsonb,
|
||||
updated_at = now()
|
||||
WHERE id = $1 AND company_id = $2 AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb
|
||||
AND COALESCE(title_template::text, '') = $7
|
||||
AND COALESCE(description_template::text, '') = $8`,
|
||||
row.ID, row.Company, string(row.Raw), string(encoded), title, description, row.Title, row.Desc)
|
||||
return result.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
// replaceKnownBuiltInLocales upgrades only exact released DEFAULT locale values.
|
||||
// A1 can contain its own custom Slovenian category prompt alongside an old
|
||||
// platform-generated English translation. Preserve its custom languages, name
|
||||
@@ -388,6 +583,9 @@ func replaceKnownBuiltInLocales(prompts company.LangPromptMap, versions []aiprom
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
if !matched && isExactOldDefaultLanguage(val, lang, versions, cache, historical) {
|
||||
matched = true
|
||||
}
|
||||
if matched {
|
||||
prompts[lang] = replacement
|
||||
updates++
|
||||
@@ -582,7 +780,7 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
eligible, changed, custom, upgraded, protected, a1Removed, a1Updated, a1Locales := 0, 0, 0, 0, 0, 0, 0, 0
|
||||
eligible, changed, custom, upgraded, protected, a1Removed, a1Updated, a1Locales, localeRepaired := 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
for _, row := range categories {
|
||||
// A1 has its own Slovenian category instructions. Never apply the
|
||||
// global platform-default backfill to this customer.
|
||||
@@ -636,6 +834,27 @@ func main() {
|
||||
if !isKnownBuiltInVariantSet(row.Prompts, versions, cache, historical) ||
|
||||
!isKnownBuiltInFormula(row.Title, versions, true) ||
|
||||
!isKnownBuiltInFormula(row.Desc, versions, false) {
|
||||
// Repair only exact-match *shipped* defaults when a different
|
||||
// language or a structured formula was intentionally customized.
|
||||
next, repaired := repairOldLocaleDefaults(row.Prompts, versions, cache, historical, targetLangs)
|
||||
title, repairedTitle := repairOldFormulaField(row.Title, versions, true)
|
||||
desc, repairedDesc := repairOldFormulaField(row.Desc, versions, false)
|
||||
if repaired != 0 || repairedTitle || repairedDesc {
|
||||
eligible++
|
||||
if *dryRun {
|
||||
localeRepaired += repaired
|
||||
continue
|
||||
}
|
||||
updated, updateErr := persistRepairedDefaults(ctx, pool, row, next, title, desc)
|
||||
if updateErr != nil {
|
||||
failures++
|
||||
log.Printf("FAIL repairing default locales company=%s category=%s: %v", row.Company, row.UID, updateErr)
|
||||
} else if updated {
|
||||
changed++
|
||||
localeRepaired += repaired
|
||||
}
|
||||
continue
|
||||
}
|
||||
custom++
|
||||
continue
|
||||
}
|
||||
@@ -654,7 +873,7 @@ func main() {
|
||||
}
|
||||
|
||||
}
|
||||
log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_legacy_sections_normalized=%d A1_default_locales_upgraded=%d A1_categories_updated=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Locales, a1Updated, failures, *dryRun)
|
||||
log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_legacy_sections_normalized=%d A1_default_locales_upgraded=%d A1_categories_updated=%d non_a1_legacy_locales_repaired=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Locales, a1Updated, localeRepaired, failures, *dryRun)
|
||||
if *dryRun && missing > 0 {
|
||||
log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM")
|
||||
}
|
||||
|
||||
@@ -68,3 +68,122 @@ func TestV6SharedCacheMigrationUsesHistoricalExactStrings(t *testing.T) {
|
||||
t.Fatal("custom company locale overwritten")
|
||||
}
|
||||
}
|
||||
|
||||
// Reproduces the non-A1 records from the production report: the v3 seed
|
||||
// generated only a translated paragraph of five-H2 instructions in hr/bg,
|
||||
// while the English company variant still used five literal HTML H2 blocks.
|
||||
func TestV3NonA1DescriptionMigrationAcrossAll25Languages(t *testing.T) {
|
||||
canonical := aiprompts.DefaultCategoryFormula("", "Bathroom mixers")
|
||||
prior := aiprompts.PriorDefaultCategoryFormula("", "Bathroom mixers")
|
||||
versions := []aiprompts.CategoryFormulaDefaults{canonical, prior}
|
||||
oldPrompts := company.LangPromptMap{}
|
||||
for _, lang := range company.ContentLanguages {
|
||||
old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldPrompts[lang] = old
|
||||
}
|
||||
oldPrompts["*"] = prior.Overlay
|
||||
// A manually customized German description must remain untouched.
|
||||
oldPrompts["de"] = "--- Title ---\nMein Shop Titel\n--- End Title ---\n\n--- Description ---\nEigenes Unternehmen\n--- End Description ---\n\n--- Meta ---\nMeine Meta\n--- End Meta ---"
|
||||
got, count := repairOldLocaleDefaults(oldPrompts, versions, nil, nil, company.ContentLanguages)
|
||||
if count != len(company.ContentLanguages) { // 24 translated + wildcard; custom de untouched
|
||||
t.Fatalf("repaired %d entries; want %d", count, len(company.ContentLanguages))
|
||||
}
|
||||
if got["de"] != oldPrompts["de"] {
|
||||
t.Fatal("custom German company formula overwritten")
|
||||
}
|
||||
for _, lang := range company.ContentLanguages {
|
||||
if lang == "de" {
|
||||
continue
|
||||
}
|
||||
expected, err := aiprompts.OfflineDefaultPrompt(lang)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lang == "en" {
|
||||
expected = canonical.Overlay
|
||||
}
|
||||
if got[lang] != expected {
|
||||
t.Fatalf("%s retained obsolete default", lang)
|
||||
}
|
||||
body := aiprompts.DescriptionSectionInstructions(got[lang])
|
||||
if strings.Count(body, "<h2>{") != 2 || strings.Count(body, "<p>{") != 2 || strings.Count(body, "<ul><li>{") != 1 {
|
||||
t.Fatalf("%s did not receive HTML scaffold: %s", lang, body)
|
||||
}
|
||||
if !strings.HasPrefix(body, "<p>{") {
|
||||
t.Fatalf("%s not starting with intro", lang)
|
||||
}
|
||||
}
|
||||
if got["*"] != canonical.Overlay {
|
||||
t.Fatal("shared English five-H2 default survived migration")
|
||||
}
|
||||
twice, further := repairOldLocaleDefaults(got, versions, nil, nil, company.ContentLanguages)
|
||||
if further != 0 {
|
||||
t.Fatalf("migration is not idempotent: %+v", twice)
|
||||
}
|
||||
}
|
||||
|
||||
func TestV3ExactReportedCroatianAndBulgarianMigration(t *testing.T) {
|
||||
snippets := map[string]string{
|
||||
"hr": "Napiši pet različitih naslova H2, a ispod svakog odlomak od približno 100 riječi.",
|
||||
"bg": "Напиши пет различни заглавия H2, всяко следвано от абзац с около 100 думи.",
|
||||
}
|
||||
current := aiprompts.DefaultCategoryFormula("", "Any")
|
||||
for lang, expected := range snippets {
|
||||
old, err := aiprompts.PreviousOfflineDefaultPromptV3(lang)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(old, expected) {
|
||||
t.Fatalf("lost exact %s regression fixture", lang)
|
||||
}
|
||||
if !isExactOldDefaultLanguage(old, lang, []aiprompts.CategoryFormulaDefaults{current}, nil, nil) {
|
||||
t.Fatalf("%s historical snapshot not recognized", lang)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestV3CustomRolePreservedWhileDefaultDescriptionRepaired(t *testing.T) {
|
||||
current := aiprompts.DefaultCategoryFormula("", "Other")
|
||||
old, err := aiprompts.PreviousOfflineDefaultPromptV3("hr")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
originalTitle := "Korisnički prilagođene upute za naslov"
|
||||
legacy := aiprompts.BuildCategoryEnhanceOverlay(aiprompts.LegacyEnhanceParts{
|
||||
TitleRules: originalTitle,
|
||||
DescriptionRules: aiprompts.ExtractEnhanceSectionBody(old, aiprompts.SectionDescriptionStart, aiprompts.SectionDescriptionEnd),
|
||||
MetaRules: "Korisnički SEO meta",
|
||||
})
|
||||
next, changed := repairOldLocaleDefaults(company.LangPromptMap{"hr": legacy}, []aiprompts.CategoryFormulaDefaults{current}, nil, nil, company.ContentLanguages)
|
||||
if changed != 1 {
|
||||
t.Fatalf("description partial migration changed=%d", changed)
|
||||
}
|
||||
updated := next["hr"]
|
||||
if aiprompts.ExtractEnhanceSectionBody(updated, aiprompts.SectionTitleStart, aiprompts.SectionTitleEnd) != originalTitle ||
|
||||
aiprompts.ExtractEnhanceSectionBody(updated, aiprompts.SectionMetaStart, aiprompts.SectionMetaEnd) != "Korisnički SEO meta" {
|
||||
t.Fatal("company-authored title/meta were overwritten")
|
||||
}
|
||||
if !strings.HasPrefix(aiprompts.DescriptionSectionInstructions(updated), "<p>{") {
|
||||
t.Fatal("old default Croatian description not repaired")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyDescriptionConstraintMustNotOverrideLocalizedPrompt(t *testing.T) {
|
||||
canonical := aiprompts.DefaultCategoryFormula("", "Bathroom mixers")
|
||||
previous := aiprompts.PriorDefaultCategoryFormula("", "Bathroom mixers")
|
||||
versions := []aiprompts.CategoryFormulaDefaults{canonical, previous}
|
||||
patched, ok := repairOldFormulaField(previous.DescriptionTemplateJSON, versions, false)
|
||||
if !ok || patched != canonical.DescriptionTemplateJSON {
|
||||
t.Fatal("old language-neutral five-H2 description formula was not upgraded")
|
||||
}
|
||||
own := `{"sections":[{"type":"p","instructions":"Custom layout"}]}`
|
||||
if updated, changed := repairOldFormulaField(own, versions, false); changed || updated != own {
|
||||
t.Fatal("custom formula was overwritten")
|
||||
}
|
||||
if updated, changed := repairOldFormulaField(canonical.DescriptionTemplateJSON, versions, false); changed || updated != canonical.DescriptionTemplateJSON {
|
||||
t.Fatal("canonical formula should be idempotent")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user