Repository navigation
fix(mactrack): drop unique port_number index to stop aggregated-ports upgrade regression - #417
TheWitness wants to merge 3 commits into
Conversation
Bumping the plugin version in #411 re-entered the install/upgrade path on every existing install. mactrack_setup_database() declares `port_number` on mac_track_aggregated_ports as a UNIQUE composite key, but legacy installs carry it as a non-unique index that let duplicate aggregated rows accumulate. api_plugin_db_table_create() then tried to convert that index to UNIQUE and aborted with "Duplicate entry ... for key port_number", cascading into a fatal "could not update table" plugin error on every Cacti page load. - Add mactrack_dedupe_aggregated_ports(): normalize MAC formatting and prune duplicate rows (keeping the lowest row_id) so the unique key can be applied cleanly. Safe to re-run; no-op when the table is absent. - Call it in mactrack_setup_database() before the table is (re)created. - Stop mactrack_database_upgrade() from dropping/recreating `port_number` as a non-unique index (it contradicted the schema and ran on every upgrade due to an array-vs-int comparison); gate the one-time MAC normalization behind a persistent flag. - Bump version to 4.11 so the fixed upgrade re-runs for affected installs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
The migration can fail on normalized-MAC key collisions, incorrectly mark incomplete work as complete, and permanently discard observation metadata when deleting duplicates.
3 open issues
What changed in this PR
This PR addresses the MacTrack upgrade regression exposed by #411, where duplicate aggregated-port rows prevent unique-key creation and disrupt Cacti page loads.
Changes:
- Normalize and deduplicate aggregated ports before schema updates.
- Remove conflicting index recreation and gate legacy MAC normalization with a persistent flag.
- Bump the plugin to 4.11 and add upgrade regression tests.
| File | Description |
|---|---|
tests/Integration/AggregatedPortsUpgradeTest.php |
Adds coverage for deduplication, setup invocation, index handling, and normalization gating. |
INFO |
Bumps the version to 4.11 to trigger another upgrade. |
includes/database.php |
Adds aggregated-port cleanup and revises legacy migration handling. |
CHANGELOG.md |
Documents the upgrade regression fix. |
Review effort: Balanced
|
|
||
| // Strip separators first so rows that differ only by MAC formatting | ||
| // collapse into genuine duplicates. | ||
| db_execute("UPDATE mac_track_aggregated_ports SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); |
| SELECT MIN(row_id) AS keep_id | ||
| FROM mac_track_aggregated_ports | ||
| GROUP BY port_number, mac_address, ip_address, device_id, site_id, vlan_id, authorized |
| db_execute("UPDATE mac_track_dot1x SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); | ||
| db_execute("UPDATE mac_track_ips SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); | ||
| db_execute("UPDATE mac_track_macauth SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); | ||
| db_execute("UPDATE mac_track_macwatch SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); | ||
| db_execute("UPDATE mac_track_ports SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); | ||
| db_execute("UPDATE mac_track_temp_ports SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); | ||
| db_execute("UPDATE mac_track_arp SET mac_address = REPLACE(REPLACE(mac_address, ':', ''), '-', '')"); | ||
| db_execute("UPDATE mac_track_oui_database SET vendor_mac = REPLACE(REPLACE(vendor_mac, ':', ''), '-', '')"); | ||
|
|
||
| set_config_option('mt_mac_separators_stripped', 'on'); |
Follow-up to the aggregated-ports upgrade crash fix. Rather than enforce a UNIQUE `port_number` key (and dedupe to satisfy it), make it a plain non-unique index so the upgrade can never reject duplicate rows: - Schema: `port_number` is now a plain `keys[]` index and `row_id` is `bigint(20) unsigned` (avoids auto-increment overflow on large tables). - Upgrade explicitly drops any existing `port_number` index and re-adds it non-unique. db_update_table() reconciles indexes by column set only and will not convert a UNIQUE key on its own. - Duplicates are still pruned, now via a self-join DELETE keyed on the composite index (keeping the lowest row_id) instead of a NOT IN / derived-table subquery, which scales better on large tables. - mactrack_setup_database() no longer dedupes up front; the one-time cleanup lives in the flag-gated upgrade block. Tests updated accordingly (self-join dedupe, non-unique re-index, bigint row_id schema guard, drop-before-readd path). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
somethingwithproof
left a comment
There was a problem hiding this comment.
CI is green, but I don't think dropping the UNIQUE key is safe, and the dedupe loses data. Two blockers, then suggestions.
Blocker: the poller upsert depends on this key (poller_mactrack.php:1103-1116, includes/database.php:1013)
The aggregation step is INSERT ... SELECT ... ON DUPLICATE KEY UPDATE count_rec=count_rec+1, active_last=1, date_last=.... The UNIQUE port_number composite key is the only thing that makes it an upsert.
With a plain index the ON DUPLICATE KEY clause never fires. Every poll inserts a fresh row for each (port, MAC, IP, device, site, vlan, authorized) tuple, with count_rec=1 and first_scan_date=scan_date.
The table then grows by about one full copy per poll, count_rec and first_scan_date become meaningless, and active_last tracking is wrong. That is how legacy installs accumulated duplicates in the first place. This PR would make it the schema on fresh installs too.
The one-time dedupe doesn't help, since duplicates reappear on the next poll. mactrack_utilities.php:539 (recreate aggregated data) groups on the same tuple and assumes one row per tuple.
Suggested fix: keep UNIQUE. In the upgrade, merge duplicates first, then drop and re-add the key as UNIQUE in a single ALTER. Make sure the merge runs before api_plugin_db_table_create() can try to apply the key, since that is what raises "Duplicate entry ... for key 'port_number'". If you really want to drop uniqueness, the poller INSERT needs a different dedupe mechanism, and that should be in this PR.
Blocker: the dedupe keeps the wrong row (includes/database.php:960-976)
keep.row_id < agg.row_id keeps the oldest observation. It has active_last=0, an old date_last, and only its own count_rec. The newest row, with active_last=1 and the current date_last, is deleted.
After upgrade, mactrack_view_macs.php:722 and :1066 show stale last-seen and inactive state for every duplicated tuple. Merge into the survivor before deleting: SUM(count_rec), MIN(first_scan_date), MAX(date_last), MAX(active_last). Set date_last explicitly, because the column auto-updates.
Suggestion: make the index swap atomic (includes/database.php:712-716)
Separate DROP INDEX and ADD INDEX leave a window with no index on a large table. Use ALTER TABLE ... DROP INDEX port_number, ADD ... port_number (...) in one statement.
Suggestion: split out the row_id bigint change (includes/database.php:994)
int to bigint is an ALGORITHM=COPY table rebuild that blocks writes. It runs from the config_settings hook on a web request, and concurrent page loads can each attempt it. It is also unrelated to this regression.
Suggestion: batch the DELETE (includes/database.php:965)
A single self-join DELETE on a multi-million-row table is one huge transaction. Consider batching per device_id.
Suggestion: test the real behaviour (tests/Integration/AggregatedPortsUpgradeTest.php)
The tests assert SQL strings against stubs, and testAggregatedPortsSchemaIsNonUniqueWithBigintRowId asserts the schema this change introduces. Nothing exercises the poller INSERT against a real table.
Please add a DB-backed test that upgrades with duplicate rows present and then runs the aggregation twice. It should assert there is one row with count_rec=2.
Nit: includes/database.php:720 sets mt_mac_separators_stripped unconditionally, even if an earlier UPDATE failed. That matters for the mac_track_macauth and mac_track_macwatch normalizations, which can still collide on their unique/primary MAC keys.
…sert Correct the earlier revision: the aggregated-ports table is meant to hold multiple rows per MAC (the MAC view counts them to show how often a MAC was seen), so removing "duplicates" was wrong. - Remove mactrack_dedupe_aggregated_ports() entirely; the upgrade no longer prunes rows. It still normalizes MAC formatting and converts the legacy UNIQUE port_number index to a plain index. - Poller: drop the ON DUPLICATE KEY UPDATE clause from the aggregated-ports INSERT. With row_id (bigint unsigned) as the only key and no unique composite, nothing can collide, so the insert is a plain append. - Keep the schema change from the prior commit: port_number is a plain (non-unique) index and row_id is bigint unsigned. Tests updated: drop the dedupe tests, keep the non-unique/bigint schema and index-conversion coverage, add a guard that the poller insert is not an upsert. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
|
This stops the upgrade error, but with Repro on Cacti 1.2.x + MariaDB 10.11. I made the key non-unique with the current 4.9 block, ran three poller aggregation passes, upgraded to this branch, then ran two more passes: So the Count column in the aggregated MAC view stays at 1, and the table grows by one row per MAC per scan. The cleanup also keeps the lowest The alternative I tested keeps the key unique. It merges each duplicate group into its newest row in one transaction ( Separately, the Happy to open it as a PR or push it onto this branch, whichever you prefer. |
somethingwithproof
left a comment
There was a problem hiding this comment.
bd73013 removes the dedupe, so the row-loss blocker is gone. The upsert blocker still holds, and dropping ON DUPLICATE KEY UPDATE makes it the intended behaviour, not a side effect.
Blocker: the rest of the plugin assumes one row per tuple with a counter, not one row per observation.
mactrack_utilities.php:538-546(Recreate Aggregated Data) builds the table withGROUP BY site_id, device_id, mac_address, port_number, ip_address, vlan_id, authorizedandcount(*)ascount_rec: one row per tuple, with the count stored in the row.- The aggregated view (
mactrack_view_macs.php:718-731) groups bydevice_id, ip_address, mac_addressand selects the barecount_recandactive_last. With appended rows, MySQL returns those from an arbitrary row in the group, so Count shows 1 and Active is a coin flip. UnderONLY_FULL_GROUP_BYthe query is rejected outright. - Nothing ever prunes
mac_track_aggregated_ports(it's only truncated by the utilities or deleted per device/site), so the table grows by one row per MAC per scan forever. At a 15-minute interval that's about 35k rows per key per year.
The PR body defers the Count fix to a follow-up, but that leaves Count, Active and table growth all broken on every install in the meantime. The tested alternative in the comment above (merge each duplicate group into its newest row, keep port_number UNIQUE, take a GET_LOCK around the upgrade) fixes the crash without changing the data model. I'd rather land that, or keep the upsert and fix the upgrade ordering here.
The row_id bigint widening and the separate DROP/ADD index statements from my earlier review still apply. CI is green.
|
Superceded by #418 |





Description
This is a regression fix. On every existing install, loading any Cacti page fails fatally during the plugin's
config_settingshook:Root cause:
mactrack_setup_database()declaredport_numberonmac_track_aggregated_portsas a UNIQUE composite key. But that table keeps multiple rows per MAC by design — the MAC Addresses (Aggregated) view counts them to show how often a MAC has been seen — so legacy installs carryport_numberas a non-unique index with many such rows. When the upgrade path re-runs,api_plugin_db_table_create()tried to apply the UNIQUE key, aborted on those rows, and cascaded into the fatal "could not update table" error on every page load.Fix
port_numberbecomes a plain non-unique index so the upgrade can never reject the table's intended multi-row-per-MAC content:port_numberis a plainkeys[]index (notunique_keys[]), androw_idis widened tobigint(20) unsigned(the only key on the table; avoids auto-increment overflow as rows accumulate).port_numberindex (UNIQUE or not) and re-adds it non-unique. Cacti core'sdb_update_table()reconciles indexes by column set only and will not drop a UNIQUE key on its own. The one-time MAC-separator normalization and the re-index are gated behind a persistentmt_mac_separators_strippedflag.INSERTno longer usesON DUPLICATE KEY UPDATE count_rec=count_rec+1. Withrow_idas the only key and no unique composite, nothing can collide, so the insert is a plain append.mactrack_database_upgrade()block'sif ($keys != 7)check (an array compared to the int7, always true) and its unconditionalDROP INDEX port_number(which loggedCan't DROP INDEX 'port_number'when absent) are removed.4.10 → 4.11so the fixed upgrade re-runs for installs whose stored version was already advanced to 4.10 by the failed upgrade.Related Issue
Regression introduced by the version bump in #411 (
fix(mactrack): correct Aruba AOS-CX scanner dispatch), which advanced the plugin version4.9 → 4.10and re-entered the broken upgrade path on existing installs. The latentport_numberunique-key contradiction predates that PR but was dormant until the version bump re-triggered the upgrade.Motivation and Context
Without this fix, upgrading MacTrack takes the entire Cacti UI down for any install whose
mac_track_aggregated_portstable holds the multiple-rows-per-MAC content it is designed to hold (the common case for long-running installs).How Has This Been Tested?
php -lon the modifiedincludes/database.php,poller_mactrack.phpandsetup.php— no syntax errors.include/vendor/bin/pest --configuration plugins/mactrack/phpunit.xml: 293 passed (2695 assertions), including tests intests/Integration/AggregatedPortsUpgradeTest.phpthat cover:port_numberindex and abigintrow_id;port_numberas a plain (non-unique) index;port_numberindex before re-adding it;ON DUPLICATE KEY UPDATE).Types of changes
Checklist: