Skip to main content

Building a Guardrailed AI Translation Pipeline with ColdFusion’s Native AI APIs - Part Five: The Model Doesn’t Get a Publish Button

Draft, review, and publish AI translations without letting the model decide what goes live.

Parts three and four gave me candidate translations. The model returned the right fields, kept the placeholders intact, and didn’t insert an HTML tag where a sentence should be. That earns its output a place in a review queue, not on a public page.

I want three separate events:

  1. save the candidate as a draft
  2. have a person approve the text
  3. and publish a snapshot of what that person approved.

The distinction matters. If complete and “visible to the public” mean the same thing, one enthusiastic database update can bypass the review process. I’ve written enough enthusiastic database updates to know better.

Start by extending translation_item:

ALTER TABLE translation_item
    ADD COLUMN source_revision bigint NOT NULL DEFAULT 1,
    ADD COLUMN reviewed_by varchar(100),
    ADD COLUMN reviewed_at timestamptz,
    ADD COLUMN published_text text,
    ADD COLUMN published_source_hash char(64),
    ADD COLUMN published_revision bigint,
    ADD COLUMN published_by varchar(100),
    ADD COLUMN published_at timestamptz;

The source fingerprint still tells me what the source says. source_revision tells me whether it changed and later changed back. A previously published translation won’t quietly reappear just because the source text happens to match an older version again.

In TranslationInventory.cfc, add these assignments to the existing ON CONFLICT ... DO UPDATE SET clause. Put them before updated_at = now():

source_revision = CASE
    WHEN translation_item.source_hash = EXCLUDED.source_hash
        THEN translation_item.source_revision
    ELSE translation_item.source_revision + 1
END,
reviewed_by = CASE
    WHEN translation_item.source_hash = EXCLUDED.source_hash
        THEN translation_item.reviewed_by
    ELSE NULL
END,
reviewed_at = CASE
    WHEN translation_item.source_hash = EXCLUDED.source_hash
        THEN translation_item.reviewed_at
    ELSE NULL
END,

The scanner still retains the old translated_text for comparison when source content changes. It clears the review metadata and advances the revision. It doesn’t delete the old published snapshot, but that snapshot won’t pass the publication checks below.

Now create components/translationWorkflow.cfc:

component {
    public translationWorkflow function init( required string datasource ) {
        variables.datasource = arguments.datasource;
        return this;
    }

    public void function saveDrafts(
        required string siteId,
        required string pageId,
        required array candidates
    ) {
        if ( !arrayLen( arguments.candidates ) || arrayLen( arguments.candidates ) > 3 ) {
            throw(
                type="Translation.InvalidDraft",
                message="Expected between one and three candidate fields."
            );
        }

        var seen = {};

        transaction {
            try {
                for ( var candidate in arguments.candidates ) {
                    if (
                        !isStruct( candidate ) ||
                        !structKeyExists( candidate, "field_name" ) ||
                        !structKeyExists( candidate, "source_locale" ) ||
                        !structKeyExists( candidate, "target_locale" ) ||
                        !structKeyExists( candidate, "source_hash" ) ||
                        !structKeyExists( candidate, "translated_text" ) ||
                        !isSimpleValue( candidate.translated_text )
                    ) {
                        throw(
                            type="Translation.InvalidDraft",
                            message="A candidate is incomplete."
                        );
                    }

                    var fieldName = toString( candidate.field_name );

                    if (
                        !listFind( "title,summary,body", fieldName ) ||
                        structKeyExists( seen, fieldName ) ||
                        !reFind( "^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$", candidate.target_locale )
                    ) {
                        throw(
                            type="Translation.InvalidDraft",
                            message="A candidate has an invalid field or locale."
                        );
                    }

                    var source = this.currentSource(
                        siteId=arguments.siteId,
                        pageId=arguments.pageId,
                        fieldName=fieldName,
                        expectedHash=candidate.source_hash
                    );

                    if (
                        compareNoCase( source.locale, candidate.source_locale ) != 0 ||
                        compareNoCase( source.locale, candidate.target_locale ) == 0
                    ) {
                        throw(
                            type="Translation.InvalidDraft",
                            message="A candidate has the wrong source or target locale."
                        );
                    }

                    this.checkTranslation(
                        fieldName=fieldName,
                        sourceText=source.text,
                        translatedText=toString( candidate.translated_text )
                    );

                    var updated = queryExecute(
                        sql = "
                            UPDATE translation_item
                            SET
                                translated_text = :translatedText,
                                status = 'draft',
                                reviewed_by = NULL,
                                reviewed_at = NULL,
                                updated_at = now()
                            WHERE
                                site_id = CAST(:siteId AS uuid)
                                AND page_id = CAST(:pageId AS uuid)
                                AND field_name = :fieldName
                                AND source_locale = :sourceLocale
                                AND target_locale = :targetLocale
                                AND source_hash = :sourceHash
                                AND is_active = true
                                AND status IN ('missing', 'stale')
                            RETURNING
                                field_name
                        ",
                        params = {
                            siteId: { cfsqltype: "varchar", value: arguments.siteId },
                            pageId: { cfsqltype: "varchar", value: arguments.pageId },
                            fieldName: { cfsqltype: "varchar", value: fieldName },
                            sourceLocale: { cfsqltype: "varchar", value: source.locale },
                            targetLocale: { cfsqltype: "varchar", value: candidate.target_locale },
                            sourceHash: { cfsqltype: "varchar", value: candidate.source_hash },
                            translatedText: {
                                cfsqltype: "longvarchar",
                                value: candidate.translated_text
                            }
                        },
                        options = { datasource: variables.datasource, returnType: "array" }
                    );

                    if ( arrayLen( updated ) != 1 ) {
                        throw(
                            type="Translation.StaleDraft",
                            message="A candidate no longer matches an eligible inventory item."
                        );
                    }

                    seen[ fieldName ] = true;
                }
            } catch ( any error ) {
                transactionRollback();
                rethrow;
            }
        }
    }

    public void function approve(
        required string siteId,
        required string pageId,
        required string fieldName,
        required string targetLocale,
        required string sourceHash,
        required string reviewedText,
        required string reviewerId
    ) {
        if ( !len( trim( arguments.reviewerId ) ) || len( arguments.reviewerId ) > 100 ) {
            throw( type="Translation.InvalidReviewer", message="A reviewer is required." );
        }

        transaction {
            var source = this.currentSource(
                siteId=arguments.siteId,
                pageId=arguments.pageId,
                fieldName=arguments.fieldName,
                expectedHash=arguments.sourceHash
            );

            this.checkTranslation(
                fieldName=arguments.fieldName,
                sourceText=source.text,
                translatedText=arguments.reviewedText
            );

            var updated = queryExecute(
                sql = "
                    UPDATE translation_item
                    SET
                        translated_text = :reviewedText,
                        status = 'complete',
                        reviewed_by = :reviewerId,
                        reviewed_at = now(),
                        updated_at = now()
                    WHERE
                        site_id = CAST(:siteId AS uuid)
                        AND page_id = CAST(:pageId AS uuid)
                        AND field_name = :fieldName
                        AND target_locale = :targetLocale
                        AND source_hash = :sourceHash
                        AND is_active = true
                        AND status = 'draft'
                    RETURNING
                        field_name
                ",
                params = {
                    siteId: { cfsqltype: "varchar", value: arguments.siteId },
                    pageId: { cfsqltype: "varchar", value: arguments.pageId },
                    fieldName: { cfsqltype: "varchar", value: arguments.fieldName },
                    targetLocale: { cfsqltype: "varchar", value: arguments.targetLocale },
                    sourceHash: { cfsqltype: "varchar", value: arguments.sourceHash },
                    reviewedText: { cfsqltype: "longvarchar", value: arguments.reviewedText },
                    reviewerId: { cfsqltype: "varchar", value: arguments.reviewerId }
                },
                options = { datasource: variables.datasource, returnType: "array" }
            );

            if ( arrayLen( updated ) != 1 ) {
                throw(
                    type="Translation.StaleReview",
                    message="The draft changed or is no longer awaiting review."
                );
            }
        }
    }

    public void function publish(
        required string siteId,
        required string pageId,
        required string fieldName,
        required string targetLocale,
        required string sourceHash,
        required string publisherId
    ) {
        if ( !len( trim( arguments.publisherId ) ) || len( arguments.publisherId ) > 100 ) {
            throw( type="Translation.InvalidPublisher", message="A publisher is required." );
        }

        transaction {
            this.currentSource(
                siteId=arguments.siteId,
                pageId=arguments.pageId,
                fieldName=arguments.fieldName,
                expectedHash=arguments.sourceHash
            );

            var updated = queryExecute(
                sql = "
                    UPDATE translation_item
                    SET
                        published_text = translated_text,
                        published_source_hash = source_hash,
                        published_revision = source_revision,
                        published_by = :publisherId,
                        published_at = now(),
                        updated_at = now()
                    WHERE
                        site_id = CAST(:siteId AS uuid)
                        AND page_id = CAST(:pageId AS uuid)
                        AND field_name = :fieldName
                        AND target_locale = :targetLocale
                        AND source_hash = :sourceHash
                        AND is_active = true
                        AND status = 'complete'
                        AND reviewed_by IS NOT NULL
                        AND reviewed_at IS NOT NULL
                    RETURNING
                        field_name
                ",
                params = {
                    siteId: { cfsqltype: "varchar", value: arguments.siteId },
                    pageId: { cfsqltype: "varchar", value: arguments.pageId },
                    fieldName: { cfsqltype: "varchar", value: arguments.fieldName },
                    targetLocale: { cfsqltype: "varchar", value: arguments.targetLocale },
                    sourceHash: { cfsqltype: "varchar", value: arguments.sourceHash },
                    publisherId: { cfsqltype: "varchar", value: arguments.publisherId }
                },
                options = { datasource: variables.datasource, returnType: "array" }
            );

            if ( arrayLen( updated ) != 1 ) {
                throw(
                    type="Translation.NotPublishable",
                    message="The field is not a current, reviewed translation."
                );
            }
        }
    }


    private struct function currentSource(
        required string siteId,
        required string pageId,
        required string fieldName,
        required string expectedHash
    ) {
        if (
            !listFind( "title,summary,body", arguments.fieldName ) ||
            !reFind( "^[a-f0-9]{64}$", arguments.expectedHash )
        ) {
            throw(
                type="Translation.InvalidSource",
                message="The field or source fingerprint is invalid."
            );
        }

        var pages = queryExecute(
            sql = "
                SELECT
                    source_locale,
                    title,
                    summary,
                    body
                FROM
                    site_page
                WHERE
                    site_id = CAST(:siteId AS uuid)
                    AND id = CAST(:pageId AS uuid)
                FOR SHARE
            ",
            params = {
                siteId: { cfsqltype: "varchar", value: arguments.siteId },
                pageId: { cfsqltype: "varchar", value: arguments.pageId }
            },
            options = { datasource: variables.datasource, returnType: "array" }
        );

        if ( !arrayLen( pages ) ) {
            throw( type="Translation.PageNotFound", message="The page was not found." );
        }

        var page = pages[ 1 ];
        var sourceText = toString( page[ arguments.fieldName ] );
        var normalized = trim(
            replace( sourceText, chr( 13 ) & chr( 10 ), chr( 10 ), "all" )
        );
        var currentHash = lCase(
            hash( lCase( page.source_locale ) & ":" & normalized, "SHA-256", "UTF-8" )
        );

        if ( !len( normalized ) || compare( currentHash, arguments.expectedHash ) != 0 ) {
            throw(
                type="Translation.StaleSource",
                message="The source changed since this translation was generated."
            );
        }

        return { locale: page.source_locale, text: sourceText };
    }


    private void function checkTranslation(
        required string fieldName,
        required string sourceText,
        required string translatedText
    ) {
        var text = trim( arguments.translatedText );
        var limit = compare( arguments.fieldName, "body" ) == 0 ? 50000 : 2000;

        if (
            !len( text ) ||
            len( text ) > limit ||
            reFind( "<[A-Za-z/!]", text )
        ) {
            throw(
                type="Translation.InvalidText",
                message="The translation is blank, too long or contains markup."
            );
        }

        var pattern = "\{[A-Za-z][A-Za-z0-9_]*\}|https?://[^\s<>]+";
        var sourceTokens = reMatch( pattern, arguments.sourceText );
        var translatedTokens = reMatch( pattern, text );

        arraySort( sourceTokens, "text" );
        arraySort( translatedTokens, "text" );

        if ( compare( serializeJSON( sourceTokens ), serializeJSON( translatedTokens ) ) != 0 ) {
            throw(
                type="Translation.InvalidText",
                message="A placeholder or web address changed."
            );
        }
    }
}

saveDrafts() compares each candidate’s fingerprint with the current page, not just the inventory row. That catches a source edit even if the scanner hasn’t run again yet. It then updates only missing or stale rows. If any candidate fails, the transaction rolls the batch back; I don’t get a page with one fresh draft and two translations stranded in the machine’s digestive tract. PostgreSQL’s UPDATE ... RETURNING gives the code a direct way to distinguish “one row changed” from “nothing matched.” ColdFusion’s transaction functions handle the all-or-nothing write.

In the protected generation job from part four, replace writeDump( candidates ) with:

workflow = new components.TranslationWorkflow( "translationDemo" );
workflow.saveDrafts(
    siteId=siteId,
    pageId=pageId,
    candidates=candidates
);

The candidates are now drafts. They are not approved, and no public reader should use translated_text.

The review screen needs to show source_text beside translated_text, let a person edit the translation, and submit the edited result to approve(). I’m deliberately leaving authentication and site permissions to the existing administration interface; a tutorial shouldn’t invent a fake permission check and invite somebody to copy it into production. The handler must verify that the signed-in reviewer can manage this particular site, verify a request token, and take reviewerId from the session-not from a hidden field. ColdFusion provides CSRFGenerateToken() and CSRFVerifyToken() for that request check.

After those checks, the approval call is:

workflow.approve(
    siteId=siteId,
    pageId=pageId,
    fieldName=form.fieldName,
    targetLocale=form.targetLocale,
    sourceHash=form.sourceHash,
    reviewedText=form.reviewedText,
    reviewerId=session.user.id
);

An approval can edit the draft, but it can’t discard a protected placeholder or web address. More importantly, it can’t approve a draft against source text that has changed. The database status moves from draft to complete; the public still sees nothing.

A separate, authorized Publish action calls:

workflow.publish(
    siteId=siteId,
    pageId=pageId,
    fieldName=form.fieldName,
    targetLocale=form.targetLocale,
    sourceHash=form.sourceHash,
    publisherId=session.user.id
);

That copies the approved text into published_text with the source fingerprint and revision it belongs to. It doesn’t ask the model for another opinion. I’ve already paid for one.

The final guard is on the read side. A public page must never select translated_text because that column can hold an unreviewed draft. It should read only current published snapshots. I also don’t want a half-translated page that promises French and then wanders back into English after the heading. Create components/PublishedTranslation.cfc:

component {
    public PublishedTranslation function init( required string datasource ) {
        variables.datasource = arguments.datasource;
        return this;
    }


    public struct function page(
        required string siteId,
        required string pageId,
        required string targetLocale
    ) {
        var result = { ready: false, locale: arguments.targetLocale };

        transaction {
            var pages = queryExecute(
                sql = "
                    SELECT
                        source_locale,
                        title,
                        summary,
                        body
                    FROM
                        site_page
                    WHERE
                        site_id = CAST(:siteId AS uuid)
                        AND id = CAST(:pageId AS uuid)
                    FOR SHARE
                ",
                params = {
                    siteId: { cfsqltype: "varchar", value: arguments.siteId },
                    pageId: { cfsqltype: "varchar", value: arguments.pageId }
                },
                options = { datasource: variables.datasource, returnType: "array" }
            );

            if ( !arrayLen( pages ) ) {
                throw( type="Translation.PageNotFound", message="The page was not found." );
            }

            var source = pages[ 1 ];

            if ( compareNoCase( source.source_locale, arguments.targetLocale ) == 0 ) {
                result = {
                    ready: true,
                    locale: source.source_locale,
                    title: source.title,
                    summary: source.summary,
                    body: source.body
                };
            } else {
                var rows = queryExecute(
                    sql = "
                        SELECT
                            field_name,
                            published_text,
                            published_source_hash
                        FROM
                            translation_item
                        WHERE
                            site_id = CAST(:siteId AS uuid)
                            AND page_id = CAST(:pageId AS uuid)
                            AND target_locale = :targetLocale
                            AND is_active = true
                            AND published_text IS NOT NULL
                            AND published_source_hash = source_hash
                            AND published_revision = source_revision
                    ",
                    params = {
                        siteId: { cfsqltype: "varchar", value: arguments.siteId },
                        pageId: { cfsqltype: "varchar", value: arguments.pageId },
                        targetLocale: {
                            cfsqltype: "varchar",
                            value: arguments.targetLocale
                        }
                    },
                    options = { datasource: variables.datasource, returnType: "array" }
                );

                var published = {};

                for ( var row in rows ) {
                    published[ row.field_name ] = row;
                }

                var fields = [ "title", "summary", "body" ];
                var ready = true;

                for ( var fieldName in fields ) {
                    var sourceText = toString( source[ fieldName ] );

                    if ( !len( trim( sourceText ) ) ) {
                        continue;
                    }

                    var normalized = trim(
                        replace( sourceText, chr( 13 ) & chr( 10 ), chr( 10 ), "all" )
                    );
                    var currentHash = lCase(
                        hash( lCase( source.source_locale ) & ":" & normalized, "SHA-256", "UTF-8" )
                    );

                    if (
                        !structKeyExists( published, fieldName ) ||
                        compare( published[ fieldName ].published_source_hash, currentHash ) != 0
                    ) {
                        ready = false;
                        break;
                    }
                }

                if ( ready ) {
                    result = {
                        ready: true,
                        locale: arguments.targetLocale,
                        title: len( trim( source.title ) ) ? published.title.published_text : "",
                        summary: len( trim( source.summary ) ) ? published.summary.published_text : "",
                        body: len( trim( source.body ) ) ? published.body.published_text : ""
                    };
                }
            }
        }

        return result;
    }
}

The reader requires a published snapshot for every nonblank field, then recomputes each fingerprint from the live source page. A forgotten scanner run can’t make an old translation look current. Until every field passes, it returns ready: false and no partial translated page. The application can show a “not available in this language” page or apply its own explicit fallback policy. That choice shouldn’t happen accidentally inside a template.

For a local check:

<cfscript>
    reader = new components.PublishedTranslation( "translationDemo" );

    page = reader.page(
        siteId="11111111-1111-4111-8111-111111111111",
        pageId="22222222-2222-4222-8222-222222222222",
        targetLocale="fr-CA"
    );

    writeDump( page );
</cfscript>

You should see ready: false while any nonblank field remains unpublished. After all three fields have been reviewed and published, the result contains only the approved snapshots. Change the source title and the reader returns ready: false again-even before the next inventory scan.

That completes the important separation: a model can propose, a person can approve, and an authorised action can publish. The model has no publish button. Given some of my earlier architectural decisions, I’m considering extending that policy to myself.

In the final article, I’ll make the pipeline operational: background execution, retries, logging that doesn’t leak page content, and a way to see what failed without treating the provider bill as the monitoring dashboard.