feat(images): retry Cloudflare NSFW-blocked prompts with a sanitized fallback

Cloudflare's Workers AI FLUX.1 schnell content filter sometimes rejects
peptide-comic prompts as NSFW (HTTP 400, errors[].code === 3030). On
2026-04-20 this produced a silent publish-without-featured-image for
post #650 ("Semaglutide vs Tirzepatide") — the LLM-rewritten scene
tripped the filter and we had no recovery path.

New behaviour: on a 3030 response, the Cloudflare provider throws a
typed PRAutoBlogger_Image_NSFW_Blocked exception. The batch wrapper
catches it and tags the per-slot result with
`error_type: nsfw_blocked`. Image_Pipeline hands the results to a new
PRAutoBlogger_Image_NSFW_Retry helper, which reruns the blocked slot
once with a sanitized fallback prompt (title + style suffix, no LLM
rewrite). On success the retry result replaces the error entry; on a
second block, a WARNING is logged and the pipeline publishes without
that image — same terminal behaviour we had before, just explicit.

Files:

- New providers/class-image-nsfw-blocked.php — typed exception.
- providers/class-cloudflare-image-support.php — is_nsfw_error() +
  throw_if_nsfw() helpers.
- providers/class-cloudflare-image-provider.php — calls throw_if_nsfw
  inside the 4xx branch; batch catches the typed exception and marks
  the result with error_type.
- core/class-image-prompt-builder.php — new public build_fallback_prompt
  shim so the retry layer can reach the rule-based fallback without
  going through the LLM path.
- New core/class-image-nsfw-retry.php — single-shot retry helper.
- core/class-image-pipeline.php — invokes the retry between batch
  completion and per-slot processing.
- admin/class-settings-fields-extended.php — new toggle
  `prautoblogger_image_nsfw_retry` (default on) in the Images section.

Tests:

- CloudflareImageProviderTest — 3030 response throws NSFW exception;
  batch tags the per-slot result with `error_type: nsfw_blocked`.
- ImagePipelineTest — retry succeeds when provider returns a good
  result on the second call; retry is skipped when the setting is off.

Cost impact: worst-case an extra Cloudflare call per NSFW-blocked slot
(~$0.000834). Current incidence ~2% of generations; ~+$0.00002 per
generation amortized. Immaterial.

Uninstall: new option covered by the existing prautoblogger_% LIKE
sweep in uninstall.php.

Part of the v0.8.0 image bundle (issues from thread image-mime-bug).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
peptiderepo
2026-04-21 01:06:59 +07:00
parent a3ed663bae
commit fb1451c4dc
9 changed files with 420 additions and 28 deletions

View File

@@ -264,6 +264,88 @@ class ImagePipelineTest extends BaseTestCase {
unset( $GLOBALS['wpdb'] );
}
/**
* NSFW-blocked slots should be retried once with a sanitized fallback
* prompt. Retry success replaces the error entry with a real image.
*/
public function test_nsfw_blocked_slot_is_retried_with_fallback_prompt(): void {
// NSFW retry is default on; explicit for clarity.
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
static $options = [
'prautoblogger_image_enabled' => '1',
'prautoblogger_image_nsfw_retry' => '1',
'prautoblogger_image_style_suffix' => 'Style: test suffix',
'prautoblogger_log_level' => 'info',
];
return $options[ $key ] ?? $default;
} );
$success_result = [
'bytes' => 'fake_image_bytes',
'mime_type' => 'image/png',
'width' => 1200,
'height' => 632,
'model' => 'flux-1-schnell',
'cost_usd' => 0.000834,
'latency_ms' => 1500,
];
$provider = $this->createMock( \PRAutoBlogger_Image_Provider_Interface::class );
$provider->method( 'estimate_cost' )->willReturn( 0.001 );
// First batch: NSFW. Second batch (retry for image_a): success.
$provider->expects( $this->exactly( 2 ) )
->method( 'generate_image_batch' )
->willReturnOnConsecutiveCalls(
[ 'image_a' => [ 'error' => 'NSFW', 'error_type' => 'nsfw_blocked' ] ],
[ 'image_a' => $success_result ]
);
$cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
$cost_tracker->method( 'would_exceed_budget' )->willReturn( false );
Functions\when( 'get_temp_dir' )->justReturn( '/tmp/' );
Functions\when( 'media_handle_sideload' )->justReturn( 42 );
$pipeline = new \PRAutoBlogger_Image_Pipeline( $provider, $cost_tracker );
$result = $pipeline->generate_and_attach_images( 1, [ 'post_title' => 'Test Article' ] );
// Retry succeeded — image_a_id set, no errors.
$this->assertArrayHasKey( 'image_a_id', $result );
$this->assertEmpty( $result['errors'] );
}
/**
* When `prautoblogger_image_nsfw_retry` is off, blocked slots stay
* blocked — no second HTTP call, pipeline publishes without that
* image. Failsafe for when the filter gets trigger-happy.
*/
public function test_nsfw_retry_skipped_when_setting_disabled(): void {
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
static $options = [
'prautoblogger_image_enabled' => '1',
'prautoblogger_image_nsfw_retry' => '0',
];
return $options[ $key ] ?? $default;
} );
$provider = $this->createMock( \PRAutoBlogger_Image_Provider_Interface::class );
$provider->method( 'estimate_cost' )->willReturn( 0.001 );
$provider->expects( $this->exactly( 1 ) )
->method( 'generate_image_batch' )
->willReturn( [
'image_a' => [ 'error' => 'NSFW', 'error_type' => 'nsfw_blocked' ],
] );
$cost_tracker = $this->createMock( \PRAutoBlogger_Cost_Tracker::class );
$cost_tracker->method( 'would_exceed_budget' )->willReturn( false );
$pipeline = new \PRAutoBlogger_Image_Pipeline( $provider, $cost_tracker );
$result = $pipeline->generate_and_attach_images( 1, [ 'post_title' => 'Test Article' ] );
$this->assertArrayNotHasKey( 'image_a_id', $result );
$this->assertNotEmpty( $result['errors'] );
}
/**
* Test graceful handling when one image in the batch returns an error.
*/

View File

@@ -189,6 +189,57 @@ class CloudflareImageProviderTest extends BaseTestCase {
}
}
/**
* A 400 carrying Cloudflare's NSFW code (3030) must throw the typed
* PRAutoBlogger_Image_NSFW_Blocked exception, not a generic
* RuntimeException. Image_NSFW_Retry keys off the typed exception to
* decide whether to rebuild the prompt and retry.
*/
public function test_generate_image_throws_nsfw_blocked_on_code_3030(): void {
$this->with_token( 'test-token' );
$nsfw_body = '{"errors":[{"message":"AiError: Input prompt contains NSFW content.","code":3030}]}';
Functions\when( 'wp_remote_post' )->justReturn( [
'body' => $nsfw_body,
'response' => [ 'code' => 400 ],
'headers' => [],
] );
Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 400 );
Functions\when( 'wp_remote_retrieve_body' )->justReturn( $nsfw_body );
$provider = new \PRAutoBlogger_Cloudflare_Image_Provider();
$this->expectException( \PRAutoBlogger_Image_NSFW_Blocked::class );
$provider->generate_image( 'some peptide prompt', 1080, 1080 );
}
/**
* A non-3030 4xx (e.g. 401 bad token) must NOT be tagged NSFW — the
* retry path would be wasted work there.
*/
public function test_generate_image_batch_tags_nsfw_errors_distinctly(): void {
$this->with_token( 'test-token' );
$nsfw_body = '{"errors":[{"message":"AiError: Input prompt contains NSFW content.","code":3030}]}';
Functions\when( 'wp_remote_post' )->justReturn( [
'body' => $nsfw_body,
'response' => [ 'code' => 400 ],
'headers' => [],
] );
Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 400 );
Functions\when( 'wp_remote_retrieve_body' )->justReturn( $nsfw_body );
$provider = new \PRAutoBlogger_Cloudflare_Image_Provider();
$results = $provider->generate_image_batch( [
'image_a' => [ 'prompt' => 'some prompt', 'width' => 1080, 'height' => 1080 ],
] );
$this->assertArrayHasKey( 'image_a', $results );
$this->assertSame( 'nsfw_blocked', $results['image_a']['error_type'] ?? null );
$this->assertArrayHasKey( 'error', $results['image_a'] );
}
/**
* Response shape must be one of: image/* bytes OR JSON envelope with
* base64 image. Anything else is a contract breach — fail loudly.