From 6133cbacc933ae1e704f6a87ec121170fb2fae47 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sat, 28 Nov 2026 23:20:28 -0500 Subject: [PATCH] Automated reopen: keep recurrence_noted when the workflow has no Closed -> Open (#126) #128 made automated reports reopen a ticket closed inside the reopen window regardless of the Workflow Designer's admin/comment requirements, and dropped recurrence_noted entirely. The #126 decision keeps one case: a workflow with no Closed -> Open transition at all is a deliberate "never reopen" setup, so the ticket stays Closed and the response is recurrence_noted. That path is what posted 2,110 "could not be reopened" comments before #123, so it now leaves one note per closed period; later reports while the ticket stays Closed only write the audit row (which still feeds the recurrence counts). No notification is sent when nothing reopened. Prod has an active Closed -> Open (admin + comment), so prod behaviour is unchanged: reports inside the window reopen. Closes #126 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- create_ticket_api.php | 102 ++++++++++++++++++++------------- services/AutoTicketService.php | 40 ++++++++++++- 3 files changed, 101 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 092d764..9f28678 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,7 @@ Content-Type: application/json - **Source**: the API key's name (`gandalf`, `hwmonDaemon`, `thor`) is stored in `tickets.source` and shown as the creator instead of "System"; the dashboard has a Source filter. Comments this endpoint writes (escalation, recurrence) are authored by the key name too. Tickets from before #123: `php scripts/backfill_ticket_source.php --dry-run`, then without - **`dedup_key` (preferred, #123)**: the reporter decides what "the same problem" is by sending `dedup_key` (`scope:subject:kind`, 1-128 of `A-Za-z0-9_.:-`, case-sensitive, e.g. `host:compute-storage-01:oom`, `cluster:ceph:BLUESTORE_SLOW_OP_ALERT`). The hash is then `sha256("key:" + dedup_key)` and the title is not looked at; an invalid key is a 400. When an app starts sending keys, give its existing tickets theirs with `php scripts/backfill_dedup_keys.php --map=file.json [--dry-run]` (the app supplies `{ticket_id: dedup_key}`), or its next reports open duplicates - **Deduplication without a key**: Generates a SHA-256 hash from the issue category, hostname, and device (no time window). A repeat alert matching an existing **open** ticket updates its title/description and escalates the priority if the condition worsened -- **Recurrence (every reporter, keyed or not)**: a report matching a **Closed** ticket that closed less than `AUTO_REOPEN_WINDOW_DAYS` (default 7) ago reopens it to Open. Automated reopens skip the Workflow Designer (its Closed → Open rule is for people; prod requires admin + comment there, which no reporter can give); the audit entry says so. A ticket closed longer ago is left alone: a **new ticket** takes over the dedup slot, carries the same `dedup_key`, records the old one in `recurrence_of`, is linked `relates_to` it, and gets a history comment (times seen in the last 7 and 30 days, when it last cleared). Response `action`: `created`, `updated`, `deduplicated`, `reopened` or `new_recurrence` (with `previous_ticket_id`). (`recurrence_noted` is no longer returned.) +- **Recurrence (every reporter, keyed or not)**: a report matching a **Closed** ticket that closed less than `AUTO_REOPEN_WINDOW_DAYS` (default 7) ago reopens it to Open (#126). Automated reopens skip the Workflow Designer's requirements (its Closed → Open rule is for people; prod requires admin + comment there, which no reporter can give); the audit entry says so. Only a workflow with **no** Closed → Open transition at all leaves the ticket Closed (`recurrence_noted`): one note per closed period, later reports go to the audit log only. A ticket closed longer ago is left alone: a **new ticket** takes over the dedup slot, carries the same `dedup_key`, records the old one in `recurrence_of`, is linked `relates_to` it, and gets a history comment (times seen in the last 7 and 30 days, when it last cleared). Response `action`: `created`, `updated`, `deduplicated`, `reopened`, `recurrence_noted` or `new_recurrence` (with `previous_ticket_id`) - Cluster-wide issues (Ceph health, etc.) deduplicate across all nodes (hostname excluded from hash) - Automated network tickets are keyed per problem, not just per host: on the optional `check_code` payload field when sent (it must name the instance, e.g. `iface_down:enp3s0`), otherwise on the title text outside the `[tags]`. After deploying this change (#116), run `php scripts/rehash_network_tickets.php --dry-run`, then without `--dry-run`, so open network tickets keep matching their alerts. The hash logic lives in `helpers/TicketHash.php` - `description` is rendered as markdown on the ticket page, the same as markdown comments (#114). Reporters should send markdown: `##` sections, tables for key/value data and fenced code blocks for raw command output. Fixed-width box layouts lose their alignment. diff --git a/create_ticket_api.php b/create_ticket_api.php index 9fe9be7..4373e55 100644 --- a/create_ticket_api.php +++ b/create_ticket_api.php @@ -259,58 +259,82 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) { exit; } - // Ticket closed inside the reopen window: reopen it and add a recurrence - // comment. Automated reporters reopen regardless of the Workflow - // Designer (operator decision, 2026-11-28): prod's Closed -> Open needs - // admin + comment, which no unattended reporter can give, so the rule + // Ticket closed inside the reopen window (#126). Automated reporters + // reopen it to Open whatever the Workflow Designer requires of people + // (operator decision, 2026-11-27): prod's Closed -> Open needs admin + + // a comment, which no unattended reporter can give, so honouring it // only ever produced a "could not be reopened" note on every report // (2,110 of them before #123). People still go through the workflow. - $ticketModel = new TicketModel($conn); - $ticketModel->updateTicket([ - 'ticket_id' => $existingId, - 'title' => $title, - 'description' => $description, - 'category' => $category, - 'type' => $type, - 'status' => 'Open', - 'priority' => $priority, - ], $userId); + // A workflow with no Closed -> Open transition at all is a deliberate + // "never reopen" setup: the ticket stays Closed (recurrence_noted). + require_once __DIR__ . '/models/WorkflowModel.php'; + $reopen = AutoTicketService::reopenConfigured(new WorkflowModel($conn)); - $commentText = "**Issue recurred, ticket reopened automatically.**\n\n" - . "{$source} detected this condition again. The ticket description reflects the " - . "latest report; see this comment's timestamp for when the issue recurred."; - $commentStmt = $conn->prepare( - "INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)" - ); - $commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText); - $commentStmt->execute(); - $commentStmt->close(); + if ($reopen) { + (new TicketModel($conn))->updateTicket([ + 'ticket_id' => $existingId, + 'title' => $title, + 'description' => $description, + 'category' => $category, + 'type' => $type, + 'status' => 'Open', + 'priority' => $priority, + ], $userId); - $auditLog->log($userId, 'update', 'ticket', $existingId, [ - 'status' => ['from' => 'Closed', 'to' => 'Open'], - 'reason' => "auto-reopened by {$source} (issue recurred; automated reopen skips the Workflow Designer)", - ]); + $commentText = "**Issue recurred, ticket reopened automatically.**\n\n" + . "{$source} detected this condition again. The ticket description reflects the " + . "latest report; see this comment's timestamp for when the issue recurred."; + $auditLog->log($userId, 'update', 'ticket', $existingId, [ + 'status' => ['from' => 'Closed', 'to' => 'Open'], + 'reason' => "auto-reopened by {$source} (issue recurred; automated reopen skips the Workflow Designer)", + ]); + // Ticket reopened: refresh dashboard stats. + (new StatsModel($conn))->invalidateCache(); + } else { + // One note per closed period: reporters run hourly, and a comment + // per report is what buried tickets before #123. The audit row is + // still written each time (it feeds the recurrence counts). + $commentText = AutoTicketService::recurrenceNotedSince($conn, $existingId, $existing['closed_at']) + ? null + : AutoTicketService::RECURRENCE_NOTED_HEADING . "\n\n" + . "{$source} detected this condition again. The Workflow Designer has no Closed -> Open " + . "transition, so the ticket stays Closed; reopen it by hand if needed. Later reports " + . "while it stays Closed are recorded in the audit log only."; + $auditLog->log($userId, 'update', 'ticket', $existingId, [ + 'reason' => "{$source} recurrence detected but the workflow has no Closed -> Open transition; ticket left Closed", + ]); + } - // Ticket reopened: refresh dashboard stats. - (new StatsModel($conn))->invalidateCache(); + if ($commentText !== null) { + $commentStmt = $conn->prepare( + "INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)" + ); + $commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText); + $commentStmt->execute(); + $commentStmt->close(); + } $conn->commit(); Database::close(); - require_once __DIR__ . '/helpers/NotificationHelper.php'; - NotificationHelper::sendTicketNotification($existingId, [ - 'title' => $title, - 'priority' => $priority, - 'category' => $category, - 'type' => $type, - 'status' => 'Open', - ], 'automated'); + if ($reopen) { + require_once __DIR__ . '/helpers/NotificationHelper.php'; + NotificationHelper::sendTicketNotification($existingId, [ + 'title' => $title, + 'priority' => $priority, + 'category' => $category, + 'type' => $type, + 'status' => 'Open', + ], 'automated'); + } echo json_encode([ 'success' => true, 'ticket_id' => $existingId, - 'message' => 'Existing closed ticket reopened', - 'action' => 'reopened', + 'message' => $reopen + ? 'Existing closed ticket reopened' + : 'Recurrence noted; ticket left Closed (the workflow has no Closed -> Open transition)', + 'action' => $reopen ? 'reopened' : 'recurrence_noted', ]); exit; } diff --git a/services/AutoTicketService.php b/services/AutoTicketService.php index 4f80fee..b048d13 100644 --- a/services/AutoTicketService.php +++ b/services/AutoTicketService.php @@ -9,8 +9,10 @@ * transaction; nothing here commits or rolls back. * * Recurrence rule, the same for every reporter: a report whose dedup hash - * matches a Closed ticket reopens it (skipping the Workflow Designer) when it - * closed less than AUTO_REOPEN_WINDOW_DAYS ago. Otherwise a new ticket takes over the hash, is + * matches a Closed ticket that closed less than AUTO_REOPEN_WINDOW_DAYS ago + * reopens it, skipping the Workflow Designer's admin/comment requirements + * (#126); only a workflow with no Closed -> Open transition at all leaves it + * Closed (recurrence_noted). Otherwise a new ticket takes over the hash, is * linked relates_to the old one, records it in recurrence_of, and gets a * history comment. tickets.hash is UNIQUE, so the old ticket gives up its hash * (set to NULL) and keeps its dedup_key. @@ -23,12 +25,44 @@ class AutoTicketService /** Longest recurrence chain walked for the history line. */ private const MAX_CHAIN = 50; + /** First line of the note left on a ticket that stays Closed on recurrence. */ + public const RECURRENCE_NOTED_HEADING = '**Issue recurred; the ticket stays Closed.**'; + public static function reopenWindowDays(): int { $days = (int)($GLOBALS['config']['AUTO_REOPEN_WINDOW_DAYS'] ?? 7); return $days > 0 ? $days : 7; } + /** + * Whether an automated report may reopen a recently closed ticket: the + * Workflow Designer has an active Closed -> Open transition, whatever it + * requires of people (admin, comment). None at all means "never reopen". + */ + public static function reopenConfigured(WorkflowModel $workflow): bool + { + return $workflow->getTransitionRequirements('Closed', 'Open') !== null; + } + + /** + * Whether this Closed ticket already carries a recurrence note from its + * current closed period, so later reports don't add another. + */ + public static function recurrenceNotedSince(mysqli $conn, string $ticketId, ?string $closedAt): bool + { + $heading = self::RECURRENCE_NOTED_HEADING . '%'; + $since = $closedAt ?: '1970-01-01 00:00:00'; + $stmt = $conn->prepare( + "SELECT 1 FROM ticket_comments + WHERE ticket_id = ? AND comment_text LIKE ? AND created_at >= ? LIMIT 1" + ); + $stmt->bind_param('sss', $ticketId, $heading, $since); + $stmt->execute(); + $found = $stmt->get_result()->num_rows > 0; + $stmt->close(); + return $found; + } + /** * The ticket holding this dedup hash, locked FOR UPDATE, with * closed_recently = whether it closed inside the reopen window. A Closed @@ -154,7 +188,7 @@ class AutoTicketService * How many times this problem came up in the last $days: tickets in the * chain opened in that time, plus reports that reopened one of them (or * were noted on it while it stayed Closed because the Workflow Designer - * allows no unattended reopen). + * has no Closed -> Open transition). * * @param list $chain */ -- 2.47.3