ki/quota: Hash-Bindung atomar bis in den Publish-Lock, roter Re-Check lehnt ab, Kontingent-Altbestand (Block 7, U02–U04)

- Jobs speichern Ergebnis nur per bedingtem UPDATE auf den analysierten Hash;
  publish() prüft bei ki/scheduler unter der Zeilensperre die jüngste gültige
  Klassifikation und plant sonst eine neue Prüfung ein (StaleClassificationException)
- Re-Check ohne Routing: Rot bei einer PM in Review lehnt wie die Erstprüfung ab
- consumePublishSlot() zählt eine NULL-Periode wie den laufenden Monat;
  Backfill-Migration setzt die Periode für Altverbrauch
- ApiPortalResolutionTest: gemeinsame Kategorie wegen der U10-Prüfung

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Kevin Adametz 2026-09-18 12:22:22 +00:00
parent eb95b3b830
commit 082e6bb76c
11 changed files with 698 additions and 25 deletions

View file

@ -197,8 +197,11 @@ test('v1 update keeps the portal unless an explicit portal parameter is sent', f
$company = Company::factory()->businessportal24()->create();
$user->companies()->attach($company->id, ['role' => 'owner']);
// Gemeinsame Kategorie, damit der Portalwechsel nicht an der
// Kategorieprüfung (Audit U10) scheitert.
$pressRelease = PressRelease::factory()
->forPortal(Portal::Businessportal24)
->for(Category::factory()->withTranslations()->create(['portal' => Portal::Both]))
->create(['user_id' => $user->id, 'company_id' => $company->id]);
Sanctum::actingAs($user, ['press-releases:read', 'press-releases:write']);

View file

@ -11,8 +11,10 @@ use App\Models\RejectionCategory;
use App\Models\User;
use App\Services\PressRelease\Classification\ClassificationManager;
use App\Services\PressRelease\PressReleaseService;
use App\Services\PressRelease\StaleClassificationException;
use Database\Seeders\RejectionCategorySeeder;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
@ -332,3 +334,215 @@ test('a classification for unchanged content is stored with its content hash', f
->and($audit->discarded_at)->toBeNull()
->and($pressRelease->fresh()->classification)->toBe(PressReleaseClassification::Green);
});
test('a classification is not stored when the content is overtaken between the analysis and the write (Audit U02)', function () {
Queue::fake();
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', []);
$pressRelease = PressRelease::factory()->create(['title' => 'Version eins', 'text' => 'Inhalt eins', 'status' => PressReleaseStatus::Review->value]);
$hashAtDispatch = $pressRelease->content_hash;
$overtakenHash = str_repeat('b', 64);
// Ein Editor speichert Version zwei exakt vor dem Schreiben des
// Ergebnisses – nach jedem vorherigen Hash-SELECT des Jobs.
$raced = false;
DB::beforeExecuting(function (string $query) use (&$raced, $pressRelease, $overtakenHash): void {
if ($raced || ! str_starts_with($query, 'update') || ! str_contains($query, 'press_releases') || ! str_contains($query, 'classification')) {
return;
}
$raced = true;
DB::table('press_releases')->where('id', $pressRelease->id)->update(['text' => 'Inhalt zwei', 'content_hash' => $overtakenHash]);
});
(new ClassifyPressRelease($pressRelease->id, route: true, contentHash: $hashAtDispatch))->handle(
app(ClassificationManager::class),
app(PressReleaseService::class),
);
expect($raced)->toBeTrue();
$fresh = $pressRelease->fresh();
expect($fresh->classification)->toBeNull()
->and($fresh->classified_at)->toBeNull()
->and($fresh->status)->toBe(PressReleaseStatus::Review);
$audit = KiAudit::where('press_release_id', $pressRelease->id)->firstOrFail();
expect($audit->discarded_at)->not->toBeNull()
->and($audit->content_hash)->toBe($hashAtDispatch);
Queue::assertPushed(ClassifyPressRelease::class, fn (ClassifyPressRelease $job) => $job->pressReleaseId === $pressRelease->id
&& $job->route === true
&& $job->contentHash === $overtakenHash);
});
test('a classification job carrying an outdated hash discards its result and re-queues for the current hash (Audit U02)', function () {
Queue::fake();
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', []);
$pressRelease = PressRelease::factory()->create(['title' => 'Version eins', 'text' => 'Inhalt eins', 'status' => PressReleaseStatus::Review->value]);
$hashAtDispatch = $pressRelease->content_hash;
$currentHash = str_repeat('c', 64);
// Massen-Update am Query-Builder vorbei (kein Model-Event) – der Job in
// der Queue trägt noch die alte Prüfsumme.
DB::table('press_releases')->where('id', $pressRelease->id)->update(['text' => 'Inhalt zwei', 'content_hash' => $currentHash]);
(new ClassifyPressRelease($pressRelease->id, route: true, contentHash: $hashAtDispatch))->handle(
app(ClassificationManager::class),
app(PressReleaseService::class),
);
$fresh = $pressRelease->fresh();
expect($fresh->classification)->toBeNull()
->and($fresh->status)->toBe(PressReleaseStatus::Review)
->and(KiAudit::where('press_release_id', $pressRelease->id)->whereNotNull('discarded_at')->count())->toBe(1);
Queue::assertPushed(ClassifyPressRelease::class, fn (ClassifyPressRelease $job) => $job->pressReleaseId === $pressRelease->id
&& $job->route === true
&& $job->contentHash === $currentHash);
});
test('a legacy classification job without a hash still stores its result (Audit U02)', function () {
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', []);
$pressRelease = PressRelease::factory()->create(['title' => 'Altbestand', 'text' => 'Inhalt']);
DB::table('press_releases')->where('id', $pressRelease->id)->update(['content_hash' => null]);
(new ClassifyPressRelease($pressRelease->id, route: false))->handle(
app(ClassificationManager::class),
app(PressReleaseService::class),
);
expect($pressRelease->fresh()->classification)->toBe(PressReleaseClassification::Green)
->and(KiAudit::where('press_release_id', $pressRelease->id)->whereNull('discarded_at')->count())->toBe(1);
});
test('the classify job treats a stale classification at publish time as handled, not as a failure (Audit U02)', function () {
/** @var TestCase $this */
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', []);
$pressRelease = PressRelease::factory()->create(['status' => PressReleaseStatus::Review->value, 'title' => 'Sauber', 'text' => 'Inhalt']);
$service = $this->mock(PressReleaseService::class);
$service->shouldReceive('routeByClassification')
->once()
->andThrow(new StaleClassificationException($pressRelease->id, $pressRelease->content_hash, str_repeat('d', 64)));
(new ClassifyPressRelease($pressRelease->id, route: true, contentHash: $pressRelease->content_hash))->handle(
app(ClassificationManager::class),
$service,
);
expect($pressRelease->fresh()->classification)->toBe(PressReleaseClassification::Green);
});
test('a red re-check of a scheduled green release still waiting in review rejects it and notifies the author (Audit U03)', function () {
Mail::fake();
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', ['gesperrt']);
$author = User::factory()->create();
// Terminierte Grün-PM, die vor dem Termin bearbeitet wird und dabei ein
// unzulässiges Wort bekommt.
$pressRelease = PressRelease::factory()->create([
'user_id' => $author->id,
'status' => PressReleaseStatus::Review->value,
'classification' => PressReleaseClassification::Green->value,
'classified_at' => now()->subHour(),
'scheduled_at' => now()->addWeek(),
'title' => 'Sauber',
'text' => 'Inhalt',
]);
$pressRelease->update(['text' => 'Dieser Inhalt ist jetzt gesperrt.']);
// Sync-Queue: der Re-Check ohne Routing läuft sofort durch.
app(PressReleaseService::class)->reprocessAfterContentChange($pressRelease);
$fresh = $pressRelease->fresh();
expect($fresh->classification)->toBe(PressReleaseClassification::Red)
->and($fresh->status)->toBe(PressReleaseStatus::Rejected);
Mail::assertQueued(PressReleaseRejected::class, fn (PressReleaseRejected $mail) => $mail->hasTo($author->email));
$audit = KiAudit::where('press_release_id', $pressRelease->id)->where('type', KiAudit::TYPE_CLASSIFICATION)->latest('id')->firstOrFail();
expect($audit->result)->toBe('red')
->and($audit->discarded_at)->toBeNull()
->and($audit->content_hash)->toBe($fresh->content_hash);
});
test('a red re-check of a published release leaves it published (Audit U03)', function () {
Mail::fake();
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', ['gesperrt']);
$pressRelease = PressRelease::factory()->create([
'status' => PressReleaseStatus::Published->value,
'published_at' => now()->subDay(),
'classification' => PressReleaseClassification::Green->value,
'classified_at' => now()->subDay(),
'title' => 'Sauber',
'text' => 'Inhalt',
]);
$pressRelease->update(['text' => 'Dieser Inhalt ist jetzt gesperrt.']);
app(PressReleaseService::class)->reprocessAfterContentChange($pressRelease);
$fresh = $pressRelease->fresh();
expect($fresh->classification)->toBe(PressReleaseClassification::Red)
->and($fresh->status)->toBe(PressReleaseStatus::Published);
Mail::assertNothingQueued();
});
test('a red re-check of a release already held for a human decision does not auto-reject it (Audit U03)', function () {
Mail::fake();
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', ['gesperrt']);
$pressRelease = PressRelease::factory()->create([
'status' => PressReleaseStatus::Review->value,
'classification' => PressReleaseClassification::Green->value,
'classified_at' => now()->subHour(),
'manual_review_required_at' => now()->subMinute(),
'title' => 'Sauber',
'text' => 'Inhalt',
]);
$pressRelease->update(['text' => 'Dieser Inhalt ist jetzt gesperrt.']);
app(PressReleaseService::class)->reprocessAfterContentChange($pressRelease);
$fresh = $pressRelease->fresh();
expect($fresh->classification)->toBe(PressReleaseClassification::Red)
->and($fresh->status)->toBe(PressReleaseStatus::Review);
Mail::assertNothingQueued();
});
test('a green re-check without routing leaves the status untouched (Audit U03)', function () {
Mail::fake();
config()->set('scoring.classification.provider', 'deterministic');
config()->set('blacklist.words', []);
$pressRelease = PressRelease::factory()->create([
'status' => PressReleaseStatus::Review->value,
'classification' => PressReleaseClassification::Yellow->value,
'classified_at' => now()->subHour(),
'scheduled_at' => null,
'title' => 'Sauber',
'text' => 'Inhalt',
]);
$pressRelease->update(['text' => 'Inhalt, leicht überarbeitet.']);
app(PressReleaseService::class)->reprocessAfterContentChange($pressRelease);
$fresh = $pressRelease->fresh();
expect($fresh->classification)->toBe(PressReleaseClassification::Green)
->and($fresh->status)->toBe(PressReleaseStatus::Review);
Mail::assertNothingQueued();
});

View file

@ -8,6 +8,7 @@ use App\Models\PressRelease;
use App\Models\User;
use App\Services\PressRelease\ContentScore\ContentScoreManager;
use App\Services\PressRelease\PressReleaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
@ -184,3 +185,70 @@ test('the score job has a timeout that fits the http budget and retry_after (Aud
expect($job->timeout)->toBeGreaterThanOrEqual(120)
->and((int) config('queue.connections.database.retry_after'))->toBeGreaterThan($job->timeout);
});
test('a score is not stored when the content is overtaken between the analysis and the write (Audit U02)', function () {
Queue::fake();
fakeOpenAiScore(72);
$pressRelease = PressRelease::factory()->create(['title' => 'Version eins', 'text' => 'Inhalt eins']);
$hashAtDispatch = $pressRelease->content_hash;
$overtakenHash = str_repeat('b', 64);
// Ein Editor speichert Version zwei exakt vor dem Schreiben des
// Ergebnisses – nach jedem vorherigen Hash-SELECT des Jobs.
$raced = false;
DB::beforeExecuting(function (string $query) use (&$raced, $pressRelease, $overtakenHash): void {
if ($raced || ! str_starts_with($query, 'update') || ! str_contains($query, 'press_releases') || ! str_contains($query, 'content_score')) {
return;
}
$raced = true;
DB::table('press_releases')->where('id', $pressRelease->id)->update(['text' => 'Inhalt zwei', 'content_hash' => $overtakenHash]);
});
(new ScorePressRelease($pressRelease->id, contentHash: $hashAtDispatch))->handle(app(ContentScoreManager::class));
expect($raced)->toBeTrue();
$fresh = $pressRelease->fresh();
expect($fresh->content_score)->toBeNull()
->and($fresh->content_tier)->toBeNull()
->and($fresh->scored_at)->toBeNull();
$audit = KiAudit::where('press_release_id', $pressRelease->id)->firstOrFail();
expect($audit->discarded_at)->not->toBeNull()
->and($audit->content_hash)->toBe($hashAtDispatch);
Queue::assertPushed(ScorePressRelease::class, fn (ScorePressRelease $job) => $job->pressReleaseId === $pressRelease->id
&& $job->contentHash === $overtakenHash);
});
test('a score job carrying an outdated hash discards its result and re-queues for the current hash (Audit U02)', function () {
Queue::fake();
fakeOpenAiScore(72);
$pressRelease = PressRelease::factory()->create(['title' => 'Version eins', 'text' => 'Inhalt eins']);
$hashAtDispatch = $pressRelease->content_hash;
$currentHash = str_repeat('c', 64);
DB::table('press_releases')->where('id', $pressRelease->id)->update(['text' => 'Inhalt zwei', 'content_hash' => $currentHash]);
(new ScorePressRelease($pressRelease->id, contentHash: $hashAtDispatch))->handle(app(ContentScoreManager::class));
expect($pressRelease->fresh()->content_score)->toBeNull()
->and(KiAudit::where('press_release_id', $pressRelease->id)->whereNotNull('discarded_at')->count())->toBe(1);
Queue::assertPushed(ScorePressRelease::class, fn (ScorePressRelease $job) => $job->pressReleaseId === $pressRelease->id
&& $job->contentHash === $currentHash);
});
test('a legacy score job without a hash still stores its result (Audit U02)', function () {
fakeOpenAiScore(72);
$pressRelease = PressRelease::factory()->create();
DB::table('press_releases')->where('id', $pressRelease->id)->update(['content_hash' => null]);
(new ScorePressRelease($pressRelease->id))->handle(app(ContentScoreManager::class));
expect($pressRelease->fresh()->content_score)->toBe(72);
});

View file

@ -272,3 +272,61 @@ test('the monthly reset is idempotent and leaves this month\'s consumption alone
->and($lastMonth->fresh()->press_release_quota_period)->toBe('2026-09')
->and($unknown->fresh()->press_release_quota_used_this_month)->toBe(0);
});
test('legacy consumption without a period counts as this month and continues the counter on publish (Audit U04)', function () {
Carbon::setTestNow('2026-09-18 10:00:00');
// Altbestand aus der Zeit vor der Periodenbindung: 2 von 3 verbraucht,
// Monat unbekannt (NULL).
$user = quotaTestSubscriber(planQuota: 3, used: 2);
expect($user->press_release_quota_period)->toBeNull()
->and($user->pressReleaseQuotaRemaining())->toBe(1);
$pr = quotaTestPressRelease($user, 'review');
app(PressReleaseService::class)->publish($pr);
$fresh = $user->fresh();
expect($fresh->press_release_quota_used_this_month)->toBe(3)
->and($fresh->press_release_quota_period)->toBe('2026-09')
->and($fresh->pressReleaseQuotaRemaining())->toBe(0);
$second = quotaTestPressRelease($user, 'review');
expect(fn () => app(PressReleaseService::class)->publish($second))
->toThrow(QuotaExceededException::class);
});
test('the backfill migration pins legacy consumption to the migration month so the next month frees it (Audit U04)', function () {
Carbon::setTestNow('2026-09-18 10:00:00');
$user = quotaTestSubscriber(planQuota: 3, used: 3);
$untouched = User::factory()->create(['press_release_quota_used_this_month' => 0, 'press_release_quota_period' => null]);
$pinned = User::factory()->create(['press_release_quota_used_this_month' => 1, 'press_release_quota_period' => '2026-08']);
expect($user->pressReleaseQuotaRemaining())->toBe(0);
// Heutige Lesart ohne Backfill: NULL gilt als laufender Monat – der
// Monatswechsel gibt ohne Reset-Cron nichts frei.
Carbon::setTestNow('2026-10-02 10:00:00');
expect($user->fresh()->pressReleaseQuotaRemaining())->toBe(0);
Carbon::setTestNow('2026-09-18 10:00:00');
$migration = require base_path('database/migrations/2026_09_18_190000_backfill_press_release_quota_period.php');
$migration->up();
expect($user->fresh()->press_release_quota_period)->toBe('2026-09')
->and($user->fresh()->press_release_quota_used_this_month)->toBe(3)
->and($untouched->fresh()->press_release_quota_period)->toBeNull()
->and($pinned->fresh()->press_release_quota_period)->toBe('2026-08');
// Nach dem Backfill erkennt der Monatswechsel den Altverbrauch als Vormonat.
Carbon::setTestNow('2026-10-02 10:00:00');
expect($user->fresh()->pressReleaseQuotaRemaining())->toBe(3);
$pr = quotaTestPressRelease($user, 'review');
app(PressReleaseService::class)->publish($pr);
$fresh = $user->fresh();
expect($fresh->press_release_quota_used_this_month)->toBe(1)
->and($fresh->press_release_quota_period)->toBe('2026-10')
->and($fresh->pressReleaseQuotaRemaining())->toBe(2);
});

View file

@ -8,6 +8,7 @@ use App\Models\KiAudit;
use App\Models\PressRelease;
use App\Models\PressReleaseStatusLog;
use App\Services\PressRelease\PressReleaseService;
use App\Services\PressRelease\StaleClassificationException;
use Database\Seeders\RolesAndPermissionsSeeder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan;
@ -316,3 +317,100 @@ test('the scheduler re-checks a due release whose classification predates the la
&& $job->route === true
&& $job->contentHash === $stale->fresh()->content_hash);
});
test('an automatic publish refuses a classification whose hash no longer matches the locked content (Audit U02)', function () {
/** @var TestCase $this */
Queue::fake();
$pr = PressRelease::factory()->create([
'status' => PressReleaseStatus::Review->value,
'classification' => PressReleaseClassification::Green->value,
'title' => 'Version zwei',
'text' => 'Inhalt zwei',
'published_at' => null,
]);
// Grünes Urteil gehört zu Version eins – die PM trägt inzwischen Version zwei.
KiAudit::factory()->create([
'press_release_id' => $pr->id,
'type' => KiAudit::TYPE_CLASSIFICATION,
'result' => 'green',
'content_hash' => str_repeat('a', 64),
]);
expect(fn () => app(PressReleaseService::class)->publish($pr, source: 'scheduler'))
->toThrow(StaleClassificationException::class);
expect($pr->fresh()->status)->toBe(PressReleaseStatus::Review)
->and(PressReleaseStatusLog::query()->where('press_release_id', $pr->id)->count())->toBe(0);
Queue::assertPushedOn('classification', ClassifyPressRelease::class, fn (ClassifyPressRelease $job) => $job->pressReleaseId === $pr->id
&& $job->route === true
&& $job->contentHash === $pr->content_hash);
});
test('a manual admin publish overrides a stale classification (Audit U02)', function () {
/** @var TestCase $this */
Queue::fake();
$pr = PressRelease::factory()->create([
'status' => PressReleaseStatus::Review->value,
'classification' => PressReleaseClassification::Green->value,
'title' => 'Version zwei',
'text' => 'Inhalt zwei',
'published_at' => null,
]);
KiAudit::factory()->create([
'press_release_id' => $pr->id,
'type' => KiAudit::TYPE_CLASSIFICATION,
'result' => 'green',
'content_hash' => str_repeat('a', 64),
]);
app(PressReleaseService::class)->publish($pr, source: 'admin');
expect($pr->fresh()->status)->toBe(PressReleaseStatus::Published);
Queue::assertNotPushed(ClassifyPressRelease::class);
});
test('an automatic publish lets a legacy release without an audit hash through (Audit U02)', function () {
/** @var TestCase $this */
Queue::fake();
$pr = PressRelease::factory()->create([
'status' => PressReleaseStatus::Review->value,
'classification' => PressReleaseClassification::Green->value,
'published_at' => null,
]);
KiAudit::factory()->create([
'press_release_id' => $pr->id,
'type' => KiAudit::TYPE_CLASSIFICATION,
'result' => 'green',
'content_hash' => null,
]);
app(PressReleaseService::class)->publish($pr, source: 'scheduler');
expect($pr->fresh()->status)->toBe(PressReleaseStatus::Published);
});
test('the scheduler counts a stale classification at publish time as a re-check, not as a failure (Audit U02)', function () {
/** @var TestCase $this */
Carbon::setTestNow('2026-06-01 12:00:00');
$due = PressRelease::factory()->create([
'status' => PressReleaseStatus::Review->value,
'classification' => PressReleaseClassification::Green->value,
'scheduled_at' => '2026-06-01 11:55:00',
'published_at' => null,
]);
$this->mock(PressReleaseService::class)
->shouldReceive('publish')
->once()
->andThrow(new StaleClassificationException($due->id, str_repeat('a', 64), (string) $due->content_hash));
$this->artisan(PublishScheduledPressReleases::class)
->expectsOutputToContain('[RECHECK')
->expectsOutputToContain('1 neu zur Prüfung, 0 fehlgeschlagen')
->assertSuccessful();
});