- Notifications
You must be signed in to change notification settings - Fork 0
fix(text): repair extraction glyph artifacts app-wide and route all document-derived text through formatters#121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c09f808
fix(text): repair extraction glyph artifacts app-wide and route all d…
BigSimmo b83242a
Merge remote-tracking branch 'origin/main' into claude/clever-heisenb…
BigSimmo 143ec9f
style: prettier pass over formatting-cleanup files
BigSimmo 85cde9c
Merge remote-tracking branch 'origin/main' into claude/clever-heisenb…
BigSimmo fd8c5fd
fix(review): validate --limit at parse time, reject unknown flags, cl…
BigSimmo 9e2c89c
fix(review): address Copilot P2 findings — whitespace-like controls, …
BigSimmo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,263 @@ | ||
| /** | ||
| * In-place text-normalization backfill (no re-index, no re-embed). | ||
| * | ||
| * Applies the shared, lossless `normalizeExtractedGlyphs` transform to the stored | ||
| * `document_chunks.content` (and `section_heading`) of already-indexed documents. | ||
| * Only rows whose text actually changes are updated. Embeddings are NEVER | ||
| * recomputed, so vector/semantic retrieval is unchanged by construction; the | ||
| * generated `search_tsv` column refreshes automatically and can only improve. | ||
| * | ||
| * Safety: | ||
| * - Confirms the Supabase project before writing. | ||
| * - Dry-run by default; requires BOTH --write and --confirm to mutate. | ||
| * - Writes a JSON backup of every changed row (id, old content/heading) before | ||
| * updating, so the change is fully revertible. | ||
| * | ||
| * Usage: | ||
| * npm run backfill:text-normalization # dry-run, all indexed docs | ||
| * npm run backfill:text-normalization -- --limit 50 # dry-run sample | ||
| * npm run backfill:text-normalization -- --document-id <id> # single document | ||
| * npm run backfill:text-normalization -- --write --confirm # apply (with backup) | ||
| */ | ||
| import { mkdirSync, writeFileSync } from "node:fs"; | ||
| import { resolve } from "node:path"; | ||
| import { loadEnvConfig } from "@next/env"; | ||
| loadEnvConfig(process.cwd()); | ||
| type Args = { | ||
| limit: number; | ||
| documentId?: string; | ||
| write: boolean; | ||
| confirm: boolean; | ||
| }; | ||
| // The backup is deliberately NOT optional: every write run must leave a | ||
| // revertible artifact, so there is no --no-backup escape hatch. | ||
| function parseArgs(argv: string[]): Args { | ||
| const args: Args = { limit: 0, write: false, confirm: false }; | ||
| for (let index = 0; index < argv.length; index += 1) { | ||
| const token = argv[index]; | ||
| if (token === "--write") { | ||
| args.write = true; | ||
| continue; | ||
| } | ||
| if (token === "--confirm") { | ||
| args.confirm = true; | ||
| continue; | ||
| } | ||
| if (token !== "--limit" && token !== "--document-id") { | ||
| throw new Error(`Unknown flag: ${token}`); | ||
| } | ||
| const value = argv[index + 1]; | ||
| if (!value || value.startsWith("--")) throw new Error(`Missing value for ${token}`); | ||
| index += 1; | ||
| if (token === "--limit") { | ||
| const parsed = Number.parseInt(value, 10); | ||
| // Validate at parse time: NaN and 0 are falsy, so a later truthiness | ||
| // check would silently treat "--limit foo" / "--limit 0" as unlimited. | ||
| if (!Number.isInteger(parsed) || parsed <= 0) { | ||
| throw new Error(`--limit must be a positive integer (got "${value}").`); | ||
| } | ||
| args.limit = parsed; | ||
| } | ||
| if (token === "--document-id") args.documentId = value; | ||
| } | ||
| return args; | ||
| } | ||
| type ChunkRow = { | ||
| id: string; | ||
| document_id: string; | ||
| content: string | null; | ||
| section_heading: string | null; | ||
| retrieval_synopsis: string | null; | ||
| }; | ||
| type ChangedRow = { | ||
| id: string; | ||
| document_id: string; | ||
| content_changed: boolean; | ||
| heading_changed: boolean; | ||
| synopsis_changed: boolean; | ||
| old_content: string | null; | ||
| new_content: string | null; | ||
| old_section_heading: string | null; | ||
| new_section_heading: string | null; | ||
| old_retrieval_synopsis: string | null; | ||
| new_retrieval_synopsis: string | null; | ||
| }; | ||
| type SelectResult = Promise<{ data: ChunkRow[] | null; error: { message: string } | null }> & { | ||
| eq: (column: string, value: unknown) => SelectResult; | ||
| order: (column: string, opts: { ascending: boolean }) => SelectResult; | ||
| range: (from: number, to: number) => SelectResult; | ||
| }; | ||
| type AdminClient = { | ||
| from: (table: string) => { | ||
| select: (columns: string) => SelectResult; | ||
| update: (patch: Record<string, string | null>) => { | ||
| eq: (column: string, value: unknown) => Promise<{ error: { message: string } | null }>; | ||
| }; | ||
| }; | ||
| }; | ||
| const PAGE_SIZE = 1000; | ||
| async function main() { | ||
| const args = parseArgs(process.argv.slice(2)); | ||
| const [{ requireServerEnv }, { createAdminClient }, { normalizeExtractedGlyphs }, projectModule] = await Promise.all([ | ||
| import("@/lib/env"), | ||
| import("@/lib/supabase/admin"), | ||
| import("@/lib/source-text-sanitizer"), | ||
| import("@/lib/supabase/project"), | ||
| ]); | ||
| requireServerEnv(); | ||
| const { checkSupabaseProjectConfig, expectedSupabaseProject, formatSupabaseProjectCheck } = projectModule; | ||
| const projectCheck = checkSupabaseProjectConfig( | ||
| { | ||
| NEXT_PUBLIC_SUPABASE_URL: process.env.NEXT_PUBLIC_SUPABASE_URL, | ||
| SUPABASE_PROJECT_REF: process.env.SUPABASE_PROJECT_REF, | ||
| SUPABASE_PROJECT_NAME: process.env.SUPABASE_PROJECT_NAME, | ||
| }, | ||
| { requireMetadata: false }, | ||
| ); | ||
| if (projectCheck.status === "missing" || projectCheck.status === "mismatch") { | ||
| console.error(formatSupabaseProjectCheck(projectCheck)); | ||
| throw new Error(`Refusing to run: Supabase project is not ${expectedSupabaseProject.name}.`); | ||
| } | ||
| const supabase = createAdminClient() as unknown as AdminClient; | ||
| const writeEnabled = args.write && args.confirm; | ||
| if (args.write && !args.confirm) console.log("WRITE requested without --confirm; staying in dry-run mode."); | ||
| console.log( | ||
| `Text-normalization backfill ${writeEnabled ? "WRITE" : "DRY-RUN"} against ${expectedSupabaseProject.name} (${expectedSupabaseProject.ref})`, | ||
| ); | ||
| let changed: ChangedRow[] = []; | ||
| const sampleDiffs: Array<{ id: string; before: string; after: string }> = []; | ||
| let scanned = 0; | ||
| let offset = 0; | ||
| for (;;) { | ||
| let query = supabase | ||
| .from("document_chunks") | ||
| .select("id,document_id,content,section_heading,retrieval_synopsis") | ||
| .order("id", { ascending: true }) | ||
| .range(offset, offset + PAGE_SIZE - 1); | ||
| if (args.documentId) query = query.eq("document_id", args.documentId); | ||
| const { data, error } = (await query) as { data: ChunkRow[] | null; error: { message: string } | null }; | ||
| if (error) throw new Error(error.message); | ||
| const rows = data ?? []; | ||
| if (rows.length === 0) break; | ||
| for (const row of rows) { | ||
| scanned += 1; | ||
| const newContent = row.content == null ? row.content : normalizeExtractedGlyphs(row.content); | ||
| const newHeading = | ||
| row.section_heading == null ? row.section_heading : normalizeExtractedGlyphs(row.section_heading); | ||
| const newSynopsis = | ||
| row.retrieval_synopsis == null ? row.retrieval_synopsis : normalizeExtractedGlyphs(row.retrieval_synopsis); | ||
| const contentChanged = newContent !== row.content; | ||
| const headingChanged = newHeading !== row.section_heading; | ||
| const synopsisChanged = newSynopsis !== row.retrieval_synopsis; | ||
| if (!contentChanged && !headingChanged && !synopsisChanged) continue; | ||
| changed.push({ | ||
| id: row.id, | ||
| document_id: row.document_id, | ||
| content_changed: contentChanged, | ||
| heading_changed: headingChanged, | ||
| synopsis_changed: synopsisChanged, | ||
| old_content: row.content, | ||
| new_content: newContent, | ||
| old_section_heading: row.section_heading, | ||
| new_section_heading: newHeading, | ||
| old_retrieval_synopsis: row.retrieval_synopsis, | ||
| new_retrieval_synopsis: newSynopsis, | ||
| }); | ||
BigSimmo marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| if (contentChanged && sampleDiffs.length < 8) { | ||
| sampleDiffs.push({ | ||
| id: row.id, | ||
| before: (row.content ?? "").slice(0, 160), | ||
| after: (newContent ?? "").slice(0, 160), | ||
| }); | ||
| } | ||
| } | ||
| offset += rows.length; | ||
| if (rows.length < PAGE_SIZE) break; | ||
| if (args.limit && changed.length >= args.limit) break; | ||
| } | ||
| // --limit bounds the number of rows we will WRITE, not just how far we page. | ||
| if (args.limit && changed.length > args.limit) changed = changed.slice(0, args.limit); | ||
| console.log( | ||
| `Scanned ${scanned} chunks; ${changed.length} would change${args.limit ? ` (capped at --limit ${args.limit})` : ""}.`, | ||
| ); | ||
| for (const diff of sampleDiffs) { | ||
| console.log(`\n chunk ${diff.id}`); | ||
| console.log(` before: ${JSON.stringify(diff.before)}`); | ||
| console.log(` after: ${JSON.stringify(diff.after)}`); | ||
| } | ||
| if (changed.length === 0) { | ||
| console.log("\nNothing to update."); | ||
| return; | ||
| } | ||
| if (!writeEnabled) { | ||
| console.log("\nDRY-RUN complete. Re-run with --write --confirm to apply (a JSON backup is written first)."); | ||
| return; | ||
| } | ||
| // Mandatory revertible backup before any write — there is no opt-out. | ||
| const backupDir = resolve(process.cwd(), "output", "backfills"); | ||
| mkdirSync(backupDir, { recursive: true }); | ||
| const stamp = new Date().toISOString().replace(/[:.]/g, "-"); | ||
| const backupPath = resolve(backupDir, `text-normalization-${stamp}.json`); | ||
| writeFileSync( | ||
| backupPath, | ||
| JSON.stringify( | ||
| changed.map((row) => ({ | ||
| id: row.id, | ||
| document_id: row.document_id, | ||
| old_content: row.old_content, | ||
| old_section_heading: row.old_section_heading, | ||
| old_retrieval_synopsis: row.old_retrieval_synopsis, | ||
| })), | ||
| null, | ||
| 2, | ||
| ), | ||
| "utf8", | ||
| ); | ||
| console.log(`\nBackup of ${changed.length} rows written to ${backupPath}`); | ||
| let updated = 0; | ||
| for (const row of changed) { | ||
| const patch: Record<string, string | null> = {}; | ||
| if (row.content_changed) patch.content = row.new_content; | ||
| if (row.heading_changed) patch.section_heading = row.new_section_heading; | ||
| if (row.synopsis_changed) patch.retrieval_synopsis = row.new_retrieval_synopsis; | ||
| const { error } = (await supabase.from("document_chunks").update(patch).eq("id", row.id)) as { | ||
| error: { message: string } | null; | ||
| }; | ||
| if (error) throw new Error(`Update failed for chunk ${row.id}: ${error.message}`); | ||
| updated += 1; | ||
| if (updated % 250 === 0) console.log(` updated ${updated}/${changed.length}`); | ||
| } | ||
| console.log(`\nDone. Updated ${updated} chunks in place (no embeddings changed).`); | ||
| } | ||
| main().catch((error) => { | ||
| console.error(error instanceof Error ? error.message : error); | ||
| process.exit(1); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When existing chunks have glyph artifacts in extracted headings, this backfill normalizes
section_headingbut leavesdocument_chunks.section_pathuntouched because it is not selected or patched. Search/ranking paths still combinesection_pathinto section text/haystacks (for examplesrc/lib/clinical-search.tsjoinsresult.section_path), so a confirmed write run can leave the old ligatures/soft hyphens leaking into retrieval context and facets even after the heading itself was cleaned.Useful? React with 👍 / 👎.