Skip to content

feat: partition mac_track_ports by scan date - #427

Merged
TheWitness merged 22 commits into
developfrom
feature/mactrack-range-partitioning
Nov 16, 2026
Merged

TheWitness merged 22 commits into
developfrom
feature/mactrack-range-partitioning

Conversation

@somethingwithproof

@somethingwithproof somethingwithproof commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Closes #426.

Partitions mac_track_ports by RANGE (UNIX_TIMESTAMP(scan_date)) so that retention drops expired partitions instead of deleting rows.

What changes

  • Layout. New installs create mac_track_ports partitioned, with only a dMaxValue partition that the poller splits at each scan. Existing tables are left alone until an operator converts them from Utilities (Convert Port Table) or with mactrack_convert.php. The conversion copies the data into mac_track_ports_new one scan at a time, compares the row counts, and swaps the tables with one RENAME TABLE. Until the rename, a failure leaves the original table in use.
  • Granularity. One partition per scan by default. The new Port Partition Size setting selects hourly or daily partitions instead. When retention would pass the partition cap (1024 on MariaDB, 512 on MySQL, dMaxValue included), MacTrack uses the next coarser size and reports that it did. The projection counts the extra day that builds up between daily maintenance runs.
  • Loading. A per-scan partition is filled by loading mac_track_ports_stage and exchanging it in, using WITHOUT VALIDATION where the server accepts it (MySQL 5.7.5+, MariaDB 11.4+). Hourly and daily partitions are loaded directly. Any failure loads the scan directly into mac_track_ports, and the reason is recorded. An exchange that fails once is retried at the next scan; if the retry fails too, its rows are inserted directly.
  • Retention. Maintenance drops the partitions whose bound has passed. Hourly and daily layouts create at least a full day ahead, with capacity reserved for those future partitions; per-scan partitions remain on demand. Unpartitioned tables keep the row delete.
  • Scan dates. mac_track_scan_dates records each scan date and feeds the View MACs scan date list, which used to run a DISTINCT over the whole table. Retention and deletes by device, site or MAC address prune it, and Utilities can rebuild it.
  • Status. Utilities reports the layout, the partition count against the cap, the last scan's load path and the last maintenance run.

Locking and #423

DDL on the partitions takes a named lock with a short lock_wait_timeout. The conversion, the background upgrade CLI from #423, and the Utilities rebuild and optimize actions all take the poller's scan lock. Both lock names include a hash of the database name, so two Cacti databases on one server do not block each other. The conversion also refuses to start while a background upgrade is registered or its mac_track_aggregated_ports_upgrade table still exists.

Utilities

The Utilities actions that change data go through one confirmation step, which the new port table actions reuse. Optimize rebuilds and analyzes only the partition containing the latest stored observation, skipping empty future partitions. A whole-table OPTIMIZE is used only for unpartitioned tables. Both scan and partition locks protect the operation.

The Process Status page gains three sections, so an operator can see what MacTrack is doing while maintenance or an upgrade runs:

  • Current Activity: the scan phase (scanning, waiting for DNS, moving results), the maintenance step, an aggregated ports rebuild with an estimate of the rows left, or a port table conversion, each with its start time. If the recorded process has exited it says so, and it also shows why the poller last skipped a run.
  • Last Maintenance Steps: how long each step of the last maintenance run took.
  • Table Sizes: estimated rows, data, index and free space for each MacTrack table, from one information_schema query, plus free disk space when the database runs on the same host.

Testing

  • 741 unit tests pass (6 environment-dependent skips, 3,404 assertions) on PHP 8.2, 8.3 and 8.4. The existing Clover filter measures 100% patch coverage (797/797 executable lines); script entrypoints are outside that filter. DST retention cases also pass in America/Los_Angeles.
  • The Process Status sections were checked in a browser on a live Cacti develop install for idle, a stopped maintenance step, a pending rebuild and a finished maintenance run.
  • The translation template check passes, php -l is clean on every changed file, and the new files pass the Cacti php-cs-fixer rules.
  • The conversion, exchange, fallback and maintenance paths were also run against MariaDB and MySQL servers with a profiling harness. The harness is not part of this PR. The measurements are in the comments below.

Daily/weekly/disabled conversion options, the weekly default, and matching web controls are in the dependent #437. Merge this PR first.

Current GitHub checks pass: PHP 8.2–8.6 integration matrix, CodeQL and SonarCloud.

@somethingwithproof

Copy link
Copy Markdown
Member Author

Measurements at this PR's code, all from one DigitalOcean droplet, using the plugin's own partition code against pinned server images.

Per-scan cost over time. 192 scans of 20,000 rows each, with a reader querying the table throughout. The time is the mean of the first and last tenth of scans.

Server Partitioned: stage load and exchange Unpartitioned: direct load, first to last
MariaDB 10.5 0.92-1.09 s 1.2 to 4.2 s
MariaDB 11.8 0.86-0.93 s 1.0 to 13.2 s
MySQL 8.4 1.38-1.51 s 1.6 to 12.6 s
  • The exchange stayed under 0.1 s on MariaDB at every partition count from 49 to 193. On MySQL it grew from 0.04 to 0.16 s.
  • The reader's slowest query was 0.14-0.27 s with partitions and 0.43-3.5 s without.
  • Every scan took the exchange path. None fell back, and no rows landed in dMaxValue.

Partition count. 200,000 rows in 1 to 2,048 hourly partitions, on MariaDB 10.5, 10.6, 10.11, 11.4 and 11.8 and on MySQL 8.0 and 8.4.

  • MariaDB: split, exchange and drop stay flat up to 2,048 partitions, at 0.014-0.033 s, 0.10-0.41 s and 0.003-0.014 s. Two drops at 2,048 partitions took about 1 s.
  • MySQL: each of those operations grows by about 1.1-1.7 ms per partition: 0.46-1.0 s at 512 partitions, 1.0-2.0 s at 1,024 and 2.1-3.5 s at 2,048. Each one holds the metadata lock for that long, so readers wait.
  • Lookups: a lookup that prunes to one partition took about 1 ms at every count.
  • Creating the table: about 5-6 ms per partition on MariaDB and 14-18 ms on MySQL. That cost is paid once, at conversion.
  • WITHOUT VALIDATION: MariaDB 10.5 to 10.11 reject it, and the plugin checks for support before using it. On 11.4 and 11.8 it brings the exchange down to 0.005-0.033 s.

So the caps stay where they are: 1,024 partitions on MariaDB, and 512 on MySQL, which keeps each MySQL partition operation at about 1 s or less.

Two small follow-ups are pushed here. The translation template now has the two messages it was missing. The db_execute_prepared() test stub now accepts core's $log argument, which was behind SonarCloud's "too many arguments" report.

@TheWitness TheWitness 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.

Make sure we have at least one day always in the rears (created ahead of time). So that the reorganization never has to move records under normal conditions.

I'll have some more comments.

Comment thread lib/mactrack_functions.php Resolved

@TheWitness TheWitness 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.

Applying the same optimization rule from the mac_track_ips comment: a whole-table OPTIMIZE on the now range-partitioned mac_track_ports should instead target only the current/hot partition. (The mac_track_aggregated_ports conversion is not part of this PR - it is already on develop via #418/#425 - so I did not comment on it here.)

Comment thread mactrack_utilities.php Resolved
@TheWitness

Copy link
Copy Markdown
Member

Review summary

Two items from a pass over this PR, plus one finding that falls outside it.

1. OPTIMIZE should target only the hot partition (in this PR)

mactrack_utilities.php → mactrack_utilities_optimize_ports() runs OPTIMIZE TABLE mac_track_ports (line ~792). Now that mac_track_ports is range-partitioned, a whole-table OPTIMIZE rebuilds the entire table. Same rule as the existing mac_track_ips comment — touch only the current/hot partition:

ALTER TABLE mac_track_ports REBUILD PARTITION <current_day>;
ALTER TABLE mac_track_ports ANALYZE PARTITION <current_day>;

Fall back to a whole-table OPTIMIZE only for the legacy (non-partitioned) layout. (Left as an inline review comment on mactrack_utilities.php:792.)

2. mac_track_aggregated_ports conversion — NOT part of this PR

The conversion of mac_track_aggregated_ports to the compressed (separator-less MAC) format with the unique port_number key lives in mactrack_rebuild_aggregated_ports() in includes/database.php. That function is already on develop (merged via #418 and #425); this PR's only includes/database.php change is a 10-line fresh-install bootstrap in mactrack_setup_database(). So I did not add an inline comment on it here.

For the record, as it currently stands on develop, that conversion does the two things we want to avoid on this very large table:

  • Uses a transaction — each scan date is wrapped in db_begin_transaction() / db_commit_transaction() (with db_rollback_transaction() on failure).
  • Deletes records during the conversion — it drains each date from the source with DELETE FROM $source WHERE date_last = ? inside that transaction, rather than simply copying all dates and dropping the whole $source table once at the end.

The preferred shape is a plain per-scan-date INSERT ... SELECT ... ON DUPLICATE KEY UPDATE with no transaction and no per-date DELETE, draining the source only via a single final DROP TABLE $source. The descriptive comments (function PHPDoc ~line 836 and the inline (c + d) comment ~line 930) would also need correcting to match. That cleanup belongs on develop (or a follow-up PR), not here.

@TheWitness

TheWitness commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Some additional comments from our slack thread:

Did a review on the partition change and aggregated ports changes per our findings last night.  We need a CLI to enable the partitioning too.  My fear is that the REORGANIZE partition would take some time, so maybe use the same procedure as what we did with the aggregated ports:

  1. Find the range based upon the partitioning scheme (daily/weekly/disabled)
  2. Rename table
  3. Create the partitioned table to hold the full observed range from above.
  4. Copy one range at a time into the new partition
  5. Drop the renamed table.

That way is non-service impacting.  Maybe block the data collection if it starts when this happens.  Warn about that in the CLI.
It’s a maintenance activity.  So, off hours.  Could take a while.  Partition pruning needs to work 😉
The user should be able to select the partitioning scheme they want.  I think daily, and weekly should be sufficient.  For me, I would disable too just another drop-down argument.  The default on new installs should be weekly. I guess if you start out with a daily partition and move to weekly, or from a partitioned table to a non-partitioned table, maybe that CLI does the normalization using the above process.

@TheWitness

TheWitness commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Last thing, can we ensure that the the table pruning is working. I suspect that it's not. For Syslog we were using the following partition scheme for range partitions which is confirmed to work.

PARTITION BY RANGE (UNIX_TIMESTAMP(logtime))

and for syslog, and I'm not sure it works.

PARTITION BY RANGE (TO_DAYS(scan_date))

We should try to be consistent and always use timestamps for those range type table partitioning schemas.

@somethingwithproof

Copy link
Copy Markdown
Member Author

Addressed the review in 6ebcebe and restacked #437 on it. All current checks pass, including the PHP 8.2–8.6 integration matrix, CodeQL and SonarCloud.

Hourly and daily maintenance now create at least a full day ahead, with the extra hourly capacity included in the partition projection. Per-scan mode still creates its exchange partition on demand; the daily/weekly modes and new weekly default are in #437. Weekly maintenance creates the next week ahead as well.

The port-table Utilities action now rebuilds and analyzes only the latest populated partition. The inline reply includes MariaDB/MySQL benchmark results and the checks that confirmed other partitions were untouched. The obsolete daily IP-table OPTIMIZE stays removed after the rebase. I also fixed the DST retention-day regression exposed by CI.

#437 provides --partition=daily|weekly|disabled and --keep-old, plus matching web controls. It prepares the full observed range, copies by period, checks counts, and swaps atomically. I kept copy-then-swap rather than renaming the source first so readers retain the original table and interrupted copies can restart. Scans are excluded during conversion. The conversion and pruning checks passed on both MariaDB and MySQL, including daily/weekly/disabled transitions; the layout uses RANGE (UNIX_TIMESTAMP(scan_date)).

The separate aggregated-port conversion cleanup you identified remains outside these PRs, as requested in the review. This rebase preserves the current develop implementation instead of changing that migration here.

@somethingwithproof

Copy link
Copy Markdown
Member Author

Partitions are now created at least a day ahead in every mode (a498bfb).

  • Maintenance creates partitions through two days past now, so a full day is still created ahead when the next daily run starts. Before, it created only one day, which could run down to minutes before the next run.
  • Per-scan mode used to split dMaxValue on every scan. Maintenance now also creates daily slots ahead (aYYYYMMDD). Each scan carves its partition off the front of the empty slot that covers it, after checking that the slot holds no rows. Under normal conditions no scan reorganizes dMaxValue or moves rows. Only the recovery split after a failed load moves rows.
  • The partition-count projection reserves room for the extra days and the slots, so 15-minute scans with 7 days project 780 partitions.
  • Optimize now also rebuilds and analyzes only the hot partition on the old TO_DAYS daily layout.
  • The prompts now say that scheduled scans are skipped while an optimize or conversion holds the scan lock. The old wording said they wait.

Tests cover carving from an empty slot, loading directly into a slot that already holds rows, and coverage a day ahead at the next run for hourly, daily and per-scan partitions.

Retention on mac_track_ports deleted expired rows one by one, which on a
large table runs for minutes, holds row locks against the next scan and
leaves the space allocated. The View MACs scan date list also ran a
DISTINCT over the whole table on every page load.

mac_track_ports can now be partitioned by RANGE (UNIX_TIMESTAMP(scan_date)):
- New installs create the table partitioned. Existing tables stay as
  they are until an operator converts them from Utilities or with
  mactrack_convert.php, which copies the data into a new table, compares
  the row counts and swaps the two with one RENAME TABLE.
- Each scan gets its own partition by default. The new Port Partition
  Size setting selects hourly or daily partitions instead, and MacTrack
  falls back to a coarser size when retention would pass the partition
  cap (1024 on MariaDB, 512 on MySQL).
- A per-scan partition is filled by loading a stage table and exchanging
  it in; hourly and daily partitions are loaded directly. Any failure
  loads the scan directly and records why.
- Retention drops expired partitions instead of deleting rows.
- mac_track_scan_dates records each scan date for the View MACs list.
- Utilities reports the layout, the last scan's load and maintenance.

Unpartitioned tables keep working as before, with row deletes. The
conversion refuses to start while a background database upgrade is
running, and the upgrade CLI and the conversion share the poller's
mactrack_scan lock.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Cacti checks the CSRF token on POST requests only. The Utilities actions
that delete or rebuild data ran on a GET, and a confirm=true parameter
stood in for the confirmation. They now run only on a POST; a GET shows
a form that posts the action back. With Confirm Utilities Prompt off, the
Utilities page shows the actions as buttons that post directly.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Rebuild Scan Dates, Optimize Port Table and Convert Port Table go
through the POST-only gate like the other Utilities actions. Rebuild
and Optimize hold the scan lock, so a rebuild cannot delete the date of
a scan it has not read and an OPTIMIZE cannot hold up a conversion's
rename. A second conversion that finds another one running leaves that
one's status alone.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Rows left in mac_track_temp_ports with an earlier scan date (a device
rescan, or a poller run that stopped before the temp table was cleared)
were copied into the stage table and exchanged into the new scan's
partition, where reads of their own date never found them. On servers
that validate the exchange it failed instead, on every retry. The stage
table now gets only rows of the current scan; the others are inserted
directly, so they land in the partitions that cover their dates.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
A failed exchange stayed pending with its rows in the stage table until
an exchange succeeded, which never happens when the table changed after
the failure or retention dropped the partition. When the retry fails
too, the stage rows are now inserted directly and the stage table is
cleared once every insert succeeded. The stage-table check also compares
column collations and character sets and the table collation, which
EXCHANGE requires to match.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Expired partitions are dropped only at the daily maintenance run, so up
to one more day of partitions builds up than retention alone projects,
plus dMaxValue and one partition made ahead. The projection now counts
them, so 15-minute scans with 10 days of retention fall back to hourly
partitions instead of reaching the cap every day. The cap is also
checked before each split, so a recovery split followed by the scan's
own split can no longer pass it by one.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
The scan date list is kept up one row at a time, so a delete by device,
site or MAC address that removed a scan's last rows left its date in the
View MACs list until retention aged it out. Those deletes now remove the
dates that no longer have a row, one scan_date index lookup per date.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
GET_LOCK names are shared by every database on the server, so two Cacti
installs on one server blocked each other's scans and partition DDL.
Name the locks after the database, as the aggregated-ports upgrade lock
already does.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
The template lacked the busy message the Utilities actions show while a
scan or conversion runs, and the confirmation for rebuilding the scan
date list. Regenerated with locales/build_gettext.sh.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
mactrack_partition_exec() passes $log = false as core allows. The stub
took two parameters, so analysis that resolves the call to it reported
too many arguments.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Add lib/mactrack_activity.php: the current step is kept in the mt_activity
option, the last maintenance run's step timings in mt_maint_steps_last,
and the poller's deferral reason in mt_poller_deferred. The state helper
ranks the aggregated-ports rebuild, a port table conversion, a recorded
step (noting when its process has gone), running scanners and idle. Row
figures come from information_schema estimates, never COUNT(*), because
the port tables can hold tens of millions of rows. Table sizes and the
database disk space (only when the database is on this host) are read the
same way.

Database maintenance now notes each heavy step and clears it in a finally
block, so an exception cannot leave maintenance shown as running.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Note the scanning, DNS resolver wait and result transfer phases so the
Process Status page can show them, and record whether a run was skipped
for a database upgrade or a leftover aggregated-ports rebuild table. A
normal run clears the note.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Add a Current Activity section (state, since, detail, last skipped poller
run), the step timings of the last maintenance run, and a table of
MacTrack table sizes with row estimates and the database disk space.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
…n days

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
…tions

Maintenance now creates partitions through two days past now, so a full
day is still created ahead at the next daily run. In per-scan mode it
creates daily slots (aYYYYMMDD) ahead, and each scan carves its partition
off the front of the empty slot covering it, so no scan reorganizes
dMaxValue or moves rows in normal operation. The partition projection
reserves room for the extra days and slots.

The Utilities optimize action also rebuilds only the hot partition of the
legacy TO_DAYS layout. Messages now say scheduled scans are skipped, not
delayed, while an optimize or conversion holds the scan lock.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
@somethingwithproof
somethingwithproof force-pushed the feature/mactrack-range-partitioning branch from a498bfb to cf8a85a Compare November 16, 2026 17:59
@sonarqubecloud

Copy link
Copy Markdown

@TheWitness
TheWitness merged commit 8b300a2 into develop Nov 16, 2026
9 checks passed
@TheWitness
TheWitness deleted the feature/mactrack-range-partitioning branch November 16, 2026 18:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Partition mac_track_ports by scan date so retention drops partitions

2 participants