Ticket contract for automated reporters: dedup_key, source, links, reopen window (#123)
Lint / JS (eslint) (push) Successful in 14s
Lint / PHP (phpcs PSR-12) (push) Successful in 44s
Lint / PHP requirements (version + extensions) (push) Successful in 42s
Lint / Deploy (push) Skipped
Lint / Notify on failure (push) Skipped
Lint / PHP (phpcs PSR-12) (pull_request) Successful in 1m15s
Lint / JS (eslint) (pull_request) Successful in 34s
Lint / PHP requirements (version + extensions) (pull_request) Successful in 42s
Lint / Deploy (pull_request) Skipped
Lint / Notify on failure (pull_request) Skipped
Security / PHP Security (semgrep) (push) Successful in 4m13s
Security / PHP Security (semgrep) (pull_request) Successful in 3m25s
Lint / JS (eslint) (push) Successful in 14s
Lint / PHP (phpcs PSR-12) (push) Successful in 44s
Lint / PHP requirements (version + extensions) (push) Successful in 42s
Lint / Deploy (push) Skipped
Lint / Notify on failure (push) Skipped
Lint / PHP (phpcs PSR-12) (pull_request) Successful in 1m15s
Lint / JS (eslint) (pull_request) Successful in 34s
Lint / PHP requirements (version + extensions) (pull_request) Successful in 42s
Lint / Deploy (pull_request) Skipped
Lint / Notify on failure (pull_request) Skipped
Security / PHP Security (semgrep) (push) Successful in 4m13s
Security / PHP Security (semgrep) (pull_request) Successful in 3m25s
From the thor#1 plan: each reporter (gandalf, hwmonDaemon, thor) decides
what "the same problem" is, and Tinker enforces it.
- dedup_key on create_ticket_api.php (scope:subject:kind, A-Za-z0-9_.:-,
case-sensitive). The hash becomes sha256("key:" + key) and the title is
not looked at; an invalid key is a 400. Keyless callers hash exactly as
before (checked over every prod title).
- Recurrence window for every reporter, keyed or not: a match on a ticket
closed under AUTO_REOPEN_WINDOW_DAYS (7) ago reopens it as before
(subject to the Workflow Designer); an older one gets a new ticket that
takes over the dedup slot (tickets.hash stays UNIQUE, the old ticket
gives it up), carries the key, records recurrence_of, is linked
relates_to, and gets a history comment. action: new_recurrence.
- GET api/tickets_api.php?dedup_key= returns the newest ticket with that
key plus its recurrence chain; ?source= filters the list.
- New api/ticket_link_api.php (link/unlink, read_write) through
DependencyService::link()/unlink(), now shared with MCP
link_tickets/unlink_tickets; audit rows record the key name.
- tickets.source records the API key name. Shown as the creator instead of
"System" on the dashboard and ticket page, a Source filter in the
sidebar, source in MCP results and a search_tickets filter. Comments the
create API writes name the reporter instead of a hard-coded
"hwmonDaemon", and system-linked comments display that name.
- Migration 008 (dedup_key, source, recurrence_of). Scripts:
backfill_ticket_source.php (pre-#123 tickets, where certain) and
backfill_dedup_keys.php (mapping file supplied by the app).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
13ffc51cb7
commit
7061c40d4d
20 files changed
+1025
-206
No files matched your search
+123
-114
@@ -46,6 +46,7 @@ require_once __DIR__ . '/models/TicketModel.php';
|
||||
require_once __DIR__ . '/models/WorkflowModel.php';
|
||||
require_once __DIR__ . '/helpers/UrlHelper.php';
|
||||
require_once __DIR__ . '/helpers/TicketHash.php';
|
||||
require_once __DIR__ . '/services/AutoTicketService.php';
|
||||
|
||||
$apiKeyAuth = new ApiKeyAuth($conn);
|
||||
|
||||
@@ -105,6 +106,24 @@ if (!is_numeric($priority) || (int)$priority < 1 || (int)$priority > 5) {
|
||||
}
|
||||
$priority = (int)$priority;
|
||||
|
||||
// An explicit dedup_key (#123) decides what "the same problem" is. A
|
||||
// malformed one is an error, never a silent fall back to title hashing.
|
||||
if (isset($data['dedup_key']) && $data['dedup_key'] !== '' && !TicketHash::isValidKey($data['dedup_key'])) {
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'Invalid dedup_key: use 1-128 of A-Z a-z 0-9 _ . : - (e.g. host:compute-storage-01:oom)',
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
$dedupKey = TicketHash::key($data);
|
||||
|
||||
// Which reporter this is (gandalf, hwmonDaemon, thor): the API key's name.
|
||||
// Recorded as the ticket's source and used as the author of the comments
|
||||
// this endpoint writes.
|
||||
$source = (string)($apiKeyAuth->getKeyContext()['key_name'] ?? 'API');
|
||||
$commentAuthor = mb_substr($source, 0, 50);
|
||||
|
||||
$ticketHash = TicketHash::generate($data);
|
||||
$auditLog = new AuditLogModel($conn);
|
||||
|
||||
@@ -129,14 +148,10 @@ $maxDedupAttempts = 2;
|
||||
for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
$conn->begin_transaction();
|
||||
|
||||
// Look up any existing ticket with this hash (open OR closed)
|
||||
$checkStmt = $conn->prepare("SELECT ticket_id, status, title, priority FROM tickets WHERE hash = ? ORDER BY created_at DESC LIMIT 1 FOR UPDATE");
|
||||
$checkStmt->bind_param("s", $ticketHash);
|
||||
$checkStmt->execute();
|
||||
$existing = $checkStmt->get_result()->fetch_assoc();
|
||||
$checkStmt->close();
|
||||
// Look up the ticket holding this hash (open OR closed)
|
||||
$existing = AutoTicketService::lockByHash($conn, $ticketHash);
|
||||
|
||||
if ($existing) {
|
||||
if ($existing && ($existing['status'] !== 'Closed' || $existing['closed_recently'])) {
|
||||
$existingId = $existing['ticket_id'];
|
||||
$existingStatus = $existing['status'];
|
||||
$existingTitle = $existing['title'];
|
||||
@@ -193,13 +208,13 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
$toP = (int)$changes['priority']['to'];
|
||||
$fromL = $pLabels[$fromP] ?? "P{$fromP}";
|
||||
$toL = $pLabels[$toP] ?? "P{$toP}";
|
||||
$commentText = "**hwmonDaemon raised priority {$fromL} → {$toL}.**\n\n"
|
||||
. "The latest monitoring scan reported a more severe condition for this issue, "
|
||||
. "so it now needs faster attention. Current sensor data is in the ticket description above.";
|
||||
$commentText = "**{$source} raised priority {$fromL} → {$toL}.**\n\n"
|
||||
. "The latest report described a more severe condition for this issue, "
|
||||
. "so it now needs faster attention. Current details are in the ticket description above.";
|
||||
$commentStmt = $conn->prepare(
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, 'hwmonDaemon', ?, 1)"
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
||||
);
|
||||
$commentStmt->bind_param("sis", $existingId, $userId, $commentText);
|
||||
$commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText);
|
||||
$commentStmt->execute();
|
||||
$commentStmt->close();
|
||||
}
|
||||
@@ -212,7 +227,7 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
if (!empty($auditedChanges)) {
|
||||
$auditLog->log($userId, 'update', 'ticket', $existingId, array_merge(
|
||||
$auditedChanges,
|
||||
['reason' => 'auto-updated by hwmonDaemon (condition worsened)']
|
||||
['reason' => "auto-updated by {$source} (condition worsened)"]
|
||||
));
|
||||
}
|
||||
|
||||
@@ -245,7 +260,7 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// Ticket was closed — reopen it and add a recurrence comment. Route
|
||||
// Ticket closed inside the reopen window: reopen it and add a recurrence comment. Route
|
||||
// through the Workflow Designer like every other status-write path in
|
||||
// the app, rather than forcing status='Open' via raw SQL regardless of
|
||||
// configured transition rules.
|
||||
@@ -278,37 +293,37 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
'priority' => $priority,
|
||||
], $userId);
|
||||
} else {
|
||||
error_log("create_ticket_api: hwmonDaemon recurrence for ticket $existingId — "
|
||||
error_log("create_ticket_api: {$source} recurrence for ticket $existingId: "
|
||||
. "no admin-free, comment-free transition from Closed is configured; leaving ticket Closed");
|
||||
}
|
||||
|
||||
$commentText = "**Issue recurred — ticket reopened automatically.**\n\n" .
|
||||
"hwmonDaemon detected this condition again. The ticket description reflects the "
|
||||
. "original report; see this comment's timestamp for when the issue recurred.";
|
||||
$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.";
|
||||
if ($reopenStatus === null) {
|
||||
$commentText = "**Issue recurred, but the ticket could not be reopened automatically.**\n\n"
|
||||
. "hwmonDaemon detected this condition again. No Workflow Designer transition from "
|
||||
. "{$source} detected this condition again. No Workflow Designer transition from "
|
||||
. "Closed is configured that this automation can perform unattended (no comment/admin "
|
||||
. "requirement); the ticket remains Closed. Please review and reopen manually if appropriate.";
|
||||
}
|
||||
$commentStmt = $conn->prepare(
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, 'hwmonDaemon', ?, 1)"
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
||||
);
|
||||
$commentStmt->bind_param("sis", $existingId, $userId, $commentText);
|
||||
$commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText);
|
||||
$commentStmt->execute();
|
||||
$commentStmt->close();
|
||||
|
||||
if ($reopenStatus !== null) {
|
||||
$auditLog->log($userId, 'update', 'ticket', $existingId, [
|
||||
'status' => ['from' => 'Closed', 'to' => $reopenStatus],
|
||||
'reason' => 'auto-reopened by hwmonDaemon (issue recurred)',
|
||||
'reason' => "auto-reopened by {$source} (issue recurred)",
|
||||
]);
|
||||
|
||||
// Ticket reopened — refresh dashboard stats.
|
||||
(new StatsModel($conn))->invalidateCache();
|
||||
} else {
|
||||
$auditLog->log($userId, 'update', 'ticket', $existingId, [
|
||||
'reason' => 'hwmonDaemon recurrence detected but no valid reopen transition configured; ticket left Closed',
|
||||
'reason' => "{$source} recurrence detected but no valid reopen transition configured; ticket left Closed",
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -337,89 +352,69 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// No existing ticket — create a new one. Still inside the transaction opened
|
||||
// above, so a concurrent request for the same hash is blocked on its own
|
||||
// SELECT ... FOR UPDATE until this one commits or rolls back (see comment
|
||||
// there) rather than racing this INSERT.
|
||||
// No ticket holds this hash, or the one that does closed longer ago than
|
||||
// the reopen window (#123): create a new one. In the second case the new
|
||||
// ticket is a recurrence: it takes over the hash (unique, so the old
|
||||
// ticket gives it up), records the old ticket in recurrence_of, and is
|
||||
// linked relates_to it with a history comment.
|
||||
//
|
||||
// Still inside the transaction opened above, so a concurrent request for
|
||||
// the same hash is blocked on its own SELECT ... FOR UPDATE until this one
|
||||
// commits or rolls back rather than racing this INSERT.
|
||||
//
|
||||
// Note on FOR UPDATE over a not-yet-existing key: InnoDB's gap lock in that
|
||||
// case is a shared lock, not exclusive — two concurrent transactions can
|
||||
// case is a shared lock, not exclusive, so two concurrent transactions can
|
||||
// both acquire it and both reach this INSERT. The conflict only surfaces
|
||||
// when they each request the insert-intention lock for the same gap,
|
||||
// which InnoDB resolves as a deadlock (error 1213), not by blocking one
|
||||
// of the SELECTs. The outer loop above retries that case: the loser rolls
|
||||
// back and re-runs its own SELECT ... FOR UPDATE, which by then finds the
|
||||
// winner's committed row and takes the update/escalate branch instead.
|
||||
//
|
||||
// Generate a collision-safe unique ticket_id with a pre-check + retry loop (same
|
||||
// approach as TicketModel::createTicket) so a ticket_id clash cannot happen. That
|
||||
// way a 1062 on INSERT below can only be the unique_hash (dedup) key — and with
|
||||
// the FOR UPDATE lock above, only in the unlikely case of a hash collision from
|
||||
// two genuinely different reports, not the same-hash race this used to be.
|
||||
$ticket_id = null;
|
||||
$maxAttempts = 50;
|
||||
$attempts = 0;
|
||||
do {
|
||||
try {
|
||||
$candidateId = sprintf('%09d', random_int(100000000, 999999999));
|
||||
} catch (Exception $e) {
|
||||
$candidateId = sprintf('%09d', mt_rand(100000000, 999999999));
|
||||
}
|
||||
|
||||
$idCheckStmt = $conn->prepare("SELECT ticket_id FROM tickets WHERE ticket_id = ? LIMIT 1");
|
||||
$idCheckStmt->bind_param("s", $candidateId);
|
||||
$idCheckStmt->execute();
|
||||
$idExists = $idCheckStmt->get_result()->num_rows > 0;
|
||||
$idCheckStmt->close();
|
||||
|
||||
if (!$idExists) {
|
||||
$ticket_id = $candidateId;
|
||||
}
|
||||
$attempts++;
|
||||
} while ($ticket_id === null && $attempts < $maxAttempts);
|
||||
$previous = $existing; // a Closed ticket outside the window, or null
|
||||
$previousId = $previous['ticket_id'] ?? null;
|
||||
|
||||
// A ticket_id that is free, so a 1062 on INSERT below can only be the
|
||||
// unique hash, and with the FOR UPDATE lock above only in the unlikely
|
||||
// case of a hash collision between two genuinely different reports.
|
||||
$ticket_id = AutoTicketService::newTicketId($conn);
|
||||
if ($ticket_id === null) {
|
||||
$conn->rollback();
|
||||
error_log('create_ticket_api: failed to generate a unique ticket_id after ' . $maxAttempts . ' attempts');
|
||||
error_log('create_ticket_api: failed to generate a unique ticket_id');
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$insertStmt = $conn->prepare(
|
||||
"INSERT INTO tickets (ticket_id, title, description, status, priority, category, type, hash, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||||
);
|
||||
$insertStmt->bind_param(
|
||||
"ssssssssi",
|
||||
$ticket_id,
|
||||
$title,
|
||||
$description,
|
||||
$status,
|
||||
$priority,
|
||||
$category,
|
||||
$type,
|
||||
$ticketHash,
|
||||
$userId
|
||||
);
|
||||
|
||||
try {
|
||||
$inserted = $insertStmt->execute();
|
||||
if ($previousId !== null) {
|
||||
AutoTicketService::releaseHash($conn, $previousId);
|
||||
}
|
||||
AutoTicketService::insert($conn, [
|
||||
'ticket_id' => $ticket_id,
|
||||
'title' => $title,
|
||||
'description' => $description,
|
||||
'status' => $status,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
'hash' => $ticketHash,
|
||||
'created_by' => $userId,
|
||||
'source' => $source,
|
||||
'dedup_key' => $dedupKey ?? ($previous['dedup_key'] ?? null),
|
||||
'recurrence_of' => $previousId,
|
||||
]);
|
||||
} catch (mysqli_sql_exception $e) {
|
||||
$insertStmt->close();
|
||||
$conn->rollback();
|
||||
if (in_array($e->getCode(), [1213, 1205], true) && $dedupAttempt < $maxDedupAttempts) {
|
||||
// Deadlock (1213) or lock wait timeout (1205) from a concurrent
|
||||
// insert into the same not-yet-existing hash gap — see the note
|
||||
// insert into the same not-yet-existing hash gap: see the note
|
||||
// above. Retry: the next iteration's own SELECT ... FOR UPDATE
|
||||
// will find whichever side won and take the update/escalate path.
|
||||
continue;
|
||||
}
|
||||
if ($e->getCode() === 1062) {
|
||||
// Should be unreachable in the same-hash race this issue was filed
|
||||
// for now that the SELECT above takes FOR UPDATE — kept as a
|
||||
// defensive fallback in case of a genuine hash collision between two
|
||||
// different reports.
|
||||
// Defensive: only a genuine hash collision between two different
|
||||
// reports can get here now that the SELECT above takes FOR UPDATE.
|
||||
echo json_encode(['success' => false, 'error' => 'Duplicate ticket']);
|
||||
} else {
|
||||
error_log('create_ticket_api: insert failed: ' . $e->getMessage());
|
||||
@@ -428,43 +423,57 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
}
|
||||
exit;
|
||||
}
|
||||
$insertStmt->close();
|
||||
|
||||
if ($inserted) {
|
||||
$auditLog->logTicketCreate($userId, $ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
$auditLog->logTicketCreate($userId, $ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
]);
|
||||
|
||||
if ($previousId !== null) {
|
||||
AutoTicketService::linkRecurrence($conn, $ticket_id, $previousId, (int)$userId);
|
||||
$historyText = AutoTicketService::historyComment($conn, $ticket_id, $previousId, $previous['closed_at'] ?? null);
|
||||
$commentStmt = $conn->prepare(
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
||||
);
|
||||
$commentStmt->bind_param("siss", $ticket_id, $userId, $commentAuthor, $historyText);
|
||||
$commentStmt->execute();
|
||||
$commentStmt->close();
|
||||
$auditLog->log($userId, 'update', 'ticket', $previousId, [
|
||||
'reason' => "{$source} reported this problem again after the "
|
||||
. AutoTicketService::reopenWindowDays() . "-day reopen window; continued in {$ticket_id}",
|
||||
]);
|
||||
|
||||
// New ticket created — refresh dashboard stats.
|
||||
(new StatsModel($conn))->invalidateCache();
|
||||
|
||||
$conn->commit();
|
||||
Database::close();
|
||||
|
||||
require_once __DIR__ . '/helpers/NotificationHelper.php';
|
||||
NotificationHelper::sendTicketNotification($ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
'status' => $status,
|
||||
], 'automated');
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'ticket_id' => $ticket_id,
|
||||
'message' => 'Ticket created successfully',
|
||||
]);
|
||||
} else {
|
||||
$conn->rollback();
|
||||
error_log('create_ticket_api: ticket insert reported failure: ' . $conn->error);
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
||||
}
|
||||
// Done — only the deadlock `continue` above may run the loop again.
|
||||
|
||||
// New ticket created: refresh dashboard stats.
|
||||
(new StatsModel($conn))->invalidateCache();
|
||||
|
||||
$conn->commit();
|
||||
Database::close();
|
||||
|
||||
require_once __DIR__ . '/helpers/NotificationHelper.php';
|
||||
NotificationHelper::sendTicketNotification($ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
'status' => $status,
|
||||
], 'automated');
|
||||
|
||||
$response = [
|
||||
'success' => true,
|
||||
'ticket_id' => $ticket_id,
|
||||
'message' => $previousId !== null
|
||||
? "New ticket for a recurrence of {$previousId}"
|
||||
: 'Ticket created successfully',
|
||||
'action' => $previousId !== null ? 'new_recurrence' : 'created',
|
||||
];
|
||||
if ($previousId !== null) {
|
||||
$response['previous_ticket_id'] = $previousId;
|
||||
}
|
||||
echo json_encode($response);
|
||||
// Done: only the deadlock `continue` above may run the loop again.
|
||||
// Falling through re-entered it on a closed connection, appending a
|
||||
// 500 error body after the success response for every new ticket.
|
||||
exit;
|
||||
|
||||
Reference in new issue
Block a user