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 1cd9fd11af
commit ea68362310
11 changed files with 698 additions and 25 deletions

View file

@ -14,6 +14,7 @@ use App\Mail\PressReleasePublished;
use App\Mail\PressReleaseRejected;
use App\Models\AdminPreset;
use App\Models\Company;
use App\Models\KiAudit;
use App\Models\PressRelease;
use App\Models\PressReleaseAiDeclaration;
use App\Models\PressReleaseImage;
@ -136,7 +137,13 @@ class PressReleaseService
* Läuft als Re-Check **ohne Routing**: Bewertung + Audit werden
* aktualisiert, der Status bleibt unverändert. So führt das bloße
* Bearbeiten nie zu einer überraschenden automatischen Veröffentlichung
* oder Ablehnung – die Entscheidung bleibt beim regulären Workflow/Admin.
* – die Entscheidung bleibt beim regulären Workflow/Admin.
*
* Eine Ausnahme (Audit U03): Wird der Re-Check Rot und die PM wartet
* noch in `review` (etwa eine terminierte Grün-PM, die vor dem Termin
* bearbeitet wurde), lehnt der Job sie wie bei der Erstprüfung ab –
* inkl. Autorenmail –, statt sie still als rote terminierte Meldung
* liegen zu lassen. Siehe ClassifyPressRelease.
*/
public function reclassifyIfClassified(PressRelease $pressRelease): void
{
@ -272,9 +279,28 @@ class PressReleaseService
$this->publish($pressRelease, 'ki', $publishedAtOverride);
}
/**
* Quellen, die ohne menschliche Entscheidung veröffentlichen. Nur sie
* prüfen unter der Sperre, ob die freigebende Klassifikation noch zum
* Inhalt gehört (Audit U02); `admin` ist die bewusste Übersteuerung.
*/
private const AUTOMATIC_PUBLISH_SOURCES = ['ki', 'scheduler'];
/**
* @throws BlacklistViolationException Unzulässiges Wort — die PM wurde
* abgelehnt, der Autor benachrichtigt.
* @throws StaleClassificationException Nur bei automatischen Quellen
* (`ki`, `scheduler`): Die jüngste
* gültige Klassifikation gehört zu
* einer anderen Inhaltsversion als
* der gesperrten. Nichts geändert;
* eine Prüfung mit Routing für den
* aktuellen Stand ist eingeplant.
*/
public function publish(PressRelease $pressRelease, string $source = 'admin', ?Carbon $publishedAtOverride = null): void
{
$blacklistViolation = DB::transaction(function () use ($pressRelease, $source, $publishedAtOverride): ?array {
/** @var array{blacklist?: array{reason: string, word: string}, stale?: array{analyzed: string|null, current: string}}|null $outcome */
$outcome = DB::transaction(function () use ($pressRelease, $source, $publishedAtOverride): ?array {
$locked = PressRelease::query()
->withoutGlobalScope(PortalScope::class)
->whereKey($pressRelease->getKey())
@ -284,13 +310,24 @@ class PressReleaseService
$this->assertStatus($locked, [PressReleaseStatus::Review]);
$previous = $locked->status;
// Inhaltsbindung unter der Sperre (Audit U02): Der Vergleich im
// Job bzw. Scheduler liegt VOR der Sperre – hier zählt, was jetzt
// gesperrt ist. Innerhalb der Transaktion nichts ändern.
if (in_array($source, self::AUTOMATIC_PUBLISH_SOURCES, true)) {
$analyzedHash = $this->latestClassificationHash($locked);
if ($this->classificationIsStale($locked, $analyzedHash)) {
return ['stale' => ['analyzed' => $analyzedHash, 'current' => (string) $locked->content_hash]];
}
}
if ($word = $this->blacklist->findInPressRelease($locked)) {
$reason = sprintf('Automatische Ablehnung: unzulässiges Wort "%s" gefunden.', $word);
$locked->update(['status' => PressReleaseStatus::Rejected->value]);
$this->logStatusChange($locked, $previous, PressReleaseStatus::Rejected, $reason, 'blacklist');
return ['reason' => $reason, 'word' => $word];
return ['blacklist' => ['reason' => $reason, 'word' => $word]];
}
$this->consumePublishSlot($locked);
@ -307,12 +344,18 @@ class PressReleaseService
$pressRelease->refresh();
if ($blacklistViolation !== null) {
$this->notifyAuthor($pressRelease, 'rejected', $blacklistViolation['reason']);
if (isset($outcome['stale'])) {
ClassifyPressRelease::dispatch($pressRelease->id, route: true, contentHash: $outcome['stale']['current'])->onQueue('classification');
throw new StaleClassificationException($pressRelease->id, $outcome['stale']['analyzed'], $outcome['stale']['current']);
}
if (isset($outcome['blacklist'])) {
$this->notifyAuthor($pressRelease, 'rejected', $outcome['blacklist']['reason']);
throw new BlacklistViolationException(
$blacklistViolation['reason'],
$blacklistViolation['word'],
$outcome['blacklist']['reason'],
$outcome['blacklist']['word'],
);
}
@ -328,6 +371,32 @@ class PressReleaseService
$this->notifyAuthor($pressRelease, 'published');
}
/**
* Prüfsumme der jüngsten gültigen (nicht verworfenen) Klassifikation.
* Null, wenn es keine gibt oder sie aus der Zeit vor der Bindung stammt.
*/
private function latestClassificationHash(PressRelease $pressRelease): ?string
{
return KiAudit::query()
->where('press_release_id', $pressRelease->id)
->where('type', KiAudit::TYPE_CLASSIFICATION)
->whereNull('discarded_at')
->orderByDesc('id')
->value('content_hash');
}
/**
* Gleiche Übergangsregel wie im Scheduler: Altbestand ohne Prüfsumme —
* auf der PM oder im Audit (auch: noch gar kein Audit) — gilt weiter.
* Nur eine vorhandene, abweichende Summe blockiert.
*/
private function classificationIsStale(PressRelease $pressRelease, ?string $analyzedHash): bool
{
return $analyzedHash !== null
&& $pressRelease->content_hash !== null
&& $analyzedHash !== $pressRelease->content_hash;
}
/**
* Zählt beim ersten Übergang zu „published" einen PM-Slot des Eigentümers
* (Decision-Update §3.2: Slot-Verbrauch bei Veröffentlichung; abgelehnte
@ -363,11 +432,17 @@ class PressReleaseService
$plan = $user->currentPlan();
if ($plan && $user->pressReleaseQuotaUsedThisMonth() < $plan->press_release_quota) {
// Periodenwechsel atomar unter der Zeilensperre: neuer Monat →
// Zähler beginnt bei 1, sonst erhöhen (Audit F18).
// Periodenwechsel atomar unter der Zeilensperre: ein explizit
// ABWEICHENDER Monat → Zähler beginnt bei 1, sonst erhöhen
// (Audit F18). NULL (Altbestand vor der Periodenbindung) zählt
// wie der laufende Monat — dieselbe Lesart wie
// User::pressReleaseQuotaUsedThisMonth() (Audit U04).
$period = User::currentQuotaPeriod();
$continuesPeriod = $user->press_release_quota_period === null
|| $user->press_release_quota_period === $period;
$user->forceFill([
'press_release_quota_used_this_month' => $user->press_release_quota_period === $period
'press_release_quota_used_this_month' => $continuesPeriod
? (int) $user->press_release_quota_used_this_month + 1
: 1,
'press_release_quota_period' => $period,

View file

@ -0,0 +1,28 @@
<?php
namespace App\Services\PressRelease;
use RuntimeException;
/**
* Die freigebende KI-Klassifikation gehört zu einer anderen Inhaltsversion
* als der, die unter der Zeilensperre veröffentlicht werden sollte
* (Audit U02). Die automatische Veröffentlichung (KI-Job, Scheduler) bricht
* ab; eine Prüfung mit Routing für den aktuellen Stand ist bereits
* eingeplant. Manuelle Admin-Freigaben prüfen das nicht.
*/
class StaleClassificationException extends RuntimeException
{
public function __construct(
public readonly int $pressReleaseId,
public readonly ?string $analyzedHash,
public readonly string $currentHash,
) {
parent::__construct(sprintf(
'PM #%d: Die KI-Klassifikation gilt für eine ältere Inhaltsversion (%s statt %s) — nicht automatisch veröffentlicht, Prüfung neu eingeplant.',
$pressReleaseId,
$analyzedHash === null ? 'ohne Prüfsumme' : substr($analyzedHash, 0, 12),
substr($currentHash, 0, 12),
));
}
}