Skip to content

fix(mactrack): drop unique port_number index to stop aggregated-ports upgrade regression - #417

Closed
TheWitness wants to merge 3 commits into
developfrom
fix/mactrack-agg-ports-upgrade-crash
Closed

TheWitness wants to merge 3 commits into
developfrom
fix/mactrack-agg-ports-upgrade-crash

Conversation

@TheWitness

@TheWitness TheWitness commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Description

This is a regression fix. On every existing install, loading any Cacti page fails fatally during the plugin's config_settings hook:

PLUGIN ERROR: Plugin 'mactrack' could not update table 'mac_track_aggregated_ports'.
CMDPHP ERROR: A DB Exec Failed!, Error: Duplicate entry 'Ethernet1/1-...-0' for key 'port_number'

Root cause: mactrack_setup_database() declared port_number on mac_track_aggregated_ports as 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 carry port_number as 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_number becomes a plain non-unique index so the upgrade can never reject the table's intended multi-row-per-MAC content:

  • Schema: port_number is a plain keys[] index (not unique_keys[]), and row_id is widened to bigint(20) unsigned (the only key on the table; avoids auto-increment overflow as rows accumulate).
  • Upgrade: explicitly drops any existing port_number index (UNIQUE or not) and re-adds it non-unique. Cacti core's db_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 persistent mt_mac_separators_stripped flag.
  • Poller: the aggregated-ports INSERT no longer uses ON DUPLICATE KEY UPDATE count_rec=count_rec+1. With row_id as the only key and no unique composite, nothing can collide, so the insert is a plain append.
  • The old mactrack_database_upgrade() block's if ($keys != 7) check (an array compared to the int 7, always true) and its unconditional DROP INDEX port_number (which logged Can't DROP INDEX 'port_number' when absent) are removed.
  • Version bumped 4.10 → 4.11 so the fixed upgrade re-runs for installs whose stored version was already advanced to 4.10 by the failed upgrade.

Note: with the upsert removed, the stored count_rec column no longer increments. A follow-up may switch the Aggregated view's Count to a COUNT(*) of the accumulated rows so "times seen" stays accurate; that display change is intentionally not bundled here.

Related Issue

Regression introduced by the version bump in #411 (fix(mactrack): correct Aruba AOS-CX scanner dispatch), which advanced the plugin version 4.9 → 4.10 and re-entered the broken upgrade path on existing installs. The latent port_number unique-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_ports table 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 -l on the modified includes/database.php, poller_mactrack.php and setup.php — no syntax errors.
  • Full Pest suite via include/vendor/bin/pest --configuration plugins/mactrack/phpunit.xml: 293 passed (2695 assertions), including tests in tests/Integration/AggregatedPortsUpgradeTest.php that cover:
    • the aggregated-ports schema uses a non-unique port_number index and a bigint row_id;
    • the upgrade re-adds port_number as a plain (non-unique) index;
    • the upgrade drops an existing port_number index before re-adding it;
    • the upgrade strips MAC separators / re-indexes once, then skips on re-run;
    • the poller insert is a plain append (no ON DUPLICATE KEY UPDATE).

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation repository accordingly.

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>
@TheWitness TheWitness added the bug label Nov 12, 2026
Copilot AI balanced review requested due to automatic review settings November 12, 2026 01:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread includes/database.php Outdated

// 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, ':', ''), '-', '')");
Comment thread includes/database.php Outdated
Comment on lines +962 to +964
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
Comment thread includes/database.php
Comment on lines +699 to +708
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>
@TheWitness TheWitness changed the title fix(mactrack): prevent aggregated-ports upgrade regression that crashes Cacti fix(mactrack): drop unique port_number index to stop aggregated-ports upgrade regression Nov 12, 2026

@somethingwithproof somethingwithproof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@sonarqubecloud

Copy link
Copy Markdown

@somethingwithproof

Copy link
Copy Markdown
Member

This stops the upgrade error, but with port_number non-unique the poller's aggregation stops aggregating. count_rec is only incremented by ON DUPLICATE KEY UPDATE count_rec=count_rec+1 in poller_mactrack.php, and that only matches against a unique key. Without one, every scan inserts a new row.

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:

before (develop, after one upgrade):
row_id  port_number  mac_address   count_rec  active_last
1       Ethernet1/1  C45AB1C14EBB  1          0
2       Ethernet1/1  C45AB1C14EBB  1          0
3       Ethernet1/1  C45AB1C14EBB  1          1

after upgrading to this PR:
1       Ethernet1/1  C45AB1C14EBB  1          0

after two more poller passes:
1       Ethernet1/1  C45AB1C14EBB  1          0
4       Ethernet1/1  C45AB1C14EBB  1          0
5       Ethernet1/1  C45AB1C14EBB  1          1

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 row_id, so the surviving row is the oldest one and a currently active MAC shows active_last = 0. The self-join DELETE is quadratic in the number of duplicates per key. At a 15-minute scan interval, a key gains about 35,000 rows a year.

The alternative I tested keeps the key unique. It merges each duplicate group into its newest row in one transaction (SUM(count_rec), MIN(first_scan_date), MAX(date_last)), using a GROUP BY derived table rather than a self-join, then rebuilds port_number as UNIQUE. It runs before plugin_mactrack_install() refreshes the table, and also when the version hasn't changed. Same data afterwards: one row with count_rec = 3, then 4 after the next pass. 320k duplicate rows over 20k keys merged in about 9 seconds with the count total preserved. This is #359.

Separately, the Duplicate key name 'site_id_device_id' and Can't DROP INDEX port_number errors in the report come from two page loads running the upgrade at the same time: the version is only recorded at the end. I reproduced that with two concurrent index.php requests. A GET_LOCK around the version-changed block cleared it.

Happy to open it as a PR or push it onto this branch, whichever you prefer.

@somethingwithproof somethingwithproof left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 with GROUP BY site_id, device_id, mac_address, port_number, ip_address, vlan_id, authorized and count(*) as count_rec: one row per tuple, with the count stored in the row.
  • The aggregated view (mactrack_view_macs.php:718-731) groups by device_id, ip_address, mac_address and selects the bare count_rec and active_last. With appended rows, MySQL returns those from an arbitrary row in the group, so Count shows 1 and Active is a coin flip. Under ONLY_FULL_GROUP_BY the 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.

@TheWitness

TheWitness commented Nov 12, 2026 •

Copy link
Copy Markdown
Member Author

Superceded by #418

@TheWitness TheWitness closed this Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants