Documentation
¶
Overview ¶
Package recordingbackfill implements the one-time backfill described in issue #166: migrate call-recording audio files and their JSON sidecars that were ingested BEFORE v0.21.2 (#164) and therefore still carry the raw phone number in plaintext — either in the on-disk filename ({rawNumber}_{timestamp}.ext) or in the sidecar's "number" field (instead of the current number_hash-only scheme).
The SourceID hazard and the chosen strategy ¶
WhisperCollector computes SourceID as "transcript:" + relPath, where relPath is the audio file's path relative to WHISPER_AUDIO_DIR:
sourceID := "transcript:" + relPath
(internal/collector/whisper.go, CollectStream). Renaming an audio file therefore changes its SourceID. Left unhandled, this would:
- Make WhisperCollector treat the renamed file as brand new on its next scan (its computed SourceID is absent from the indexed set), paying to re-transcribe audio that was already transcribed, AND
- Cause the scheduler's MarkDeleted pass (DocumentStore.MarkDeleted, internal/store/document.go) to soft-delete the OLD SourceID's document, because the old SourceID is no longer present in the audio directory's current active-source-ID set — orphaning the original transcript.
This package avoids both by renaming the SourceID of the existing call-transcript document in Postgres (documents.source_id) IN THE SAME migration step as the filesystem rename, rather than the alternative of leaving the filename in plaintext (which does not fix the PII exposure that is the entire point of this backfill) or accepting the re-transcription + orphaned-document cost.
Ordering is chosen for crash-safety: the DB rename happens BEFORE the filesystem rename, using an UPDATE keyed on the OLD SourceID. If the process crashes between the DB update and the file rename, the file is still under its old name, so the old SourceID can still be recomputed on the next run and the UPDATE simply becomes a no-op (zero rows matched) instead of a duplicate or lost update. See planAudioFile and Run.
A defensive conflict check (RenameConflict) additionally guards against the (unexpected) case where a document already exists under the NEW SourceID — e.g. because the file was already re-transcribed under its new name by a prior partial run gone wrong. In that case the rename is a Postgres unique violation; this package treats it as a handled, non-fatal outcome and leaves the file untouched for manual review rather than silently losing data.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type LogFunc ¶
LogFunc receives one human-readable line per planned or applied action. May be nil, in which case per-file logging is skipped (summary counts are still accurate).
type Plan ¶
type Plan struct {
OldAudioPath string
NewAudioPath string // == OldAudioPath when no rename is needed
OldSidecarPath string // "" when no sidecar exists
NewSidecarPath string // "" when no sidecar; == OldSidecarPath when the path is unchanged
OldSourceID string // "" unless NeedsSourceIDUpdate
NewSourceID string
NumHash string // resolved smsmap.ShortHash(rawNumber); "" if unresolved
RawNumberFrom string // "filename" | "sidecar" | "" — for logging/audit only
Sidecar *sidecarRaw // original sidecar fields carried through to the rewrite; nil if none existed
NeedsRename bool
NeedsSourceIDUpdate bool
NeedsSidecarRewrite bool
AlreadyMigrated bool // true: nothing to do, file is CONFIRMED already in the new scheme
// Unrecognized is true when the filename is shaped like a call recording
// (matches reCallRecordingSuffix) but its prefix cannot be identified as
// EITHER an already-migrated hash (reHashPrefix) OR a legacy phone
// number (looksLikePhoneNumber / sidecar.Number), and no sidecar
// declares it a call recording (which would instead trigger Skip). This
// is deliberately kept distinct from AlreadyMigrated: such a file is NOT
// confirmed to be safely migrated, only unidentifiable — conflating the
// two would silently hide files that need manual review from the
// summary (issue #166 Finding 4).
Unrecognized bool
Skip bool // true: could not determine a phone number; do nothing (never guess)
SkipReason string
}
Plan describes the migration decision for a single audio file (and its optional sidecar). Planning is a pure function of its inputs (no direct I/O) so it can be unit tested without a filesystem or database.
func (Plan) SafeOldAudioPath ¶
SafeOldAudioPath returns a PII-safe form of OldAudioPath for logging. See redactAuditPath.
func (Plan) SafeOldSidecarPath ¶
SafeOldSidecarPath returns a PII-safe form of OldSidecarPath for logging. OldSidecarPath is always exactly OldAudioPath+".meta.json" (see Run, which always derives sidecarPath this way before calling planAudioFile), so it is redacted using the same audio-path logic.
func (Plan) SafeOldSourceID ¶
SafeOldSourceID returns a PII-safe form of OldSourceID for logging. OldSourceID ("transcript:"+relPath) is only ever populated in the same branch of planAudioFile that computes NewSourceID, from the identical numHash/timestamp — so the relative-path base component is redacted the same way as the audio path, while the "transcript:" marker and any directory segments are preserved untouched.
type PostgresSourceIDStore ¶
PostgresSourceIDStore is the production SourceIDStore, backed directly by the shared pgx pool exposed via internal/store.Postgres.Pool(). Direct SQL is used here — rather than adding a new method to internal/store.DocumentStore — so that this one-time backfill tool does not require changes to files owned by other in-flight work.
func NewPostgresSourceIDStore ¶
func NewPostgresSourceIDStore(pool *pgxpool.Pool) *PostgresSourceIDStore
NewPostgresSourceIDStore returns a PostgresSourceIDStore backed by pool.
func (*PostgresSourceIDStore) RenameCallTranscriptSourceID ¶
func (s *PostgresSourceIDStore) RenameCallTranscriptSourceID(ctx context.Context, oldSourceID, newSourceID string) (RenameResult, error)
RenameCallTranscriptSourceID renames the source_id of the call document (source_type='call' post migration 033, or the deprecated pre-migration 'call-transcript') currently stored under oldSourceID to newSourceID. Only standalone transcript documents (source_id still "transcript:{relPath}") are ever matched here — a document merged via store.AttachTranscript is keyed by the call-log-formula SourceID instead and has nothing to rename. Both active and soft-deleted rows are eligible (no status filter) — the SourceID identity must stay correct regardless of the document's current lifecycle state.
Returns:
- RenameApplied — exactly one row was found and renamed.
- RenameNoOp — no row matched oldSourceID (already renamed by a prior run, or never ingested). Not an error; the caller proceeds with the filesystem mutation.
- RenameConflict — the rename would violate the UNIQUE(source_type, source_id) constraint because a document already exists under newSourceID. The caller must leave the file untouched.
type RenameResult ¶
type RenameResult int
RenameResult is the outcome of a SourceIDStore.RenameCallTranscriptSourceID call.
const ( // RenameApplied means a row matching oldSourceID was found and renamed. RenameApplied RenameResult = iota // RenameNoOp means no row matched oldSourceID — either it was already // renamed by a prior (possibly crashed) run, or no document was ever // ingested under that SourceID. Both are safe to proceed from. RenameNoOp // RenameConflict means a row already exists under newSourceID (unique // violation on (source_type, source_id)). The caller must NOT rename the // file in this case — the document graph is already inconsistent and // needs manual review rather than an automated guess. RenameConflict )
type RunConfig ¶
type RunConfig struct {
// RootDir is the recording directory to walk recursively. Must match
// WHISPER_AUDIO_DIR so that computed SourceIDs match WhisperCollector's.
RootDir string
// DryRun, when true, only plans and logs actions — no file or database
// mutation occurs. DRY_RUN is the caller's responsibility to default to
// true (see cmd/recordingbackfill).
DryRun bool
}
RunConfig configures a single Run invocation.
type SourceIDStore ¶
type SourceIDStore interface {
RenameCallTranscriptSourceID(ctx context.Context, oldSourceID, newSourceID string) (RenameResult, error)
}
SourceIDStore is the persistence dependency for renaming a call-transcript document's source_id. Kept as an interface — rather than a concrete *store.DocumentStore — so unit tests can stub it without a live Postgres connection.
type Summary ¶
type Summary struct {
TotalFiles int
Renamed int
SidecarRewritten int
AlreadyMigrated int
// Unrecognized counts files whose filename is call-recording-shaped but
// whose prefix could not be identified as either an already-migrated
// hash or a legacy phone number (see Plan.Unrecognized). These are left
// untouched but tracked separately from AlreadyMigrated so operators can
// audit migration completeness (issue #166 Finding 4).
Unrecognized int
Skipped int
Conflicts int
Errors int
}
Summary aggregates per-file outcomes across a full Run.
func Run ¶
Run walks cfg.RootDir, plans a migration for every candidate audio file, and — unless cfg.DryRun — applies it. Errors on individual files are logged and counted in the returned Summary rather than aborting the whole walk (matching the partial-success pattern used by WhisperCollector.Collect).
store may be nil when cfg.DryRun is true (no file whose plan requires a database call will reach the store in that mode).