From 9a77ee0606214efec4a7d91004d8c58058490414 Mon Sep 17 00:00:00 2001 From: Jash Date: Sun, 16 Aug 2026 16:24:16 +0530 Subject: [PATCH 1/5] fix: lock the shared Storage row before per-monitor rows when deleting events fixes #4964 --- scripts/ZoneMinder/lib/ZoneMinder/Event.pm | 75 +++++++++---- .../ZoneMinder/t/event_delete_lock_order.t | 105 ++++++++++++++++++ 2 files changed, 161 insertions(+), 19 deletions(-) create mode 100644 scripts/ZoneMinder/t/event_delete_lock_order.t diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm index 30fd7a1b91..6814838371 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm @@ -395,10 +395,20 @@ sub delete { my $in_transaction = $ZoneMinder::Database::dbh->{AutoCommit} ? 0 : 1; + # Storage[Id] is taken first, before anything per-monitor. It is the only + # row here shared across monitors, so it has to be the coarsest lock in the + # order. Taking it last (as the old lock_and_load did, after the deletes + # had already X-locked Event_Summaries[MonitorId]) meant a batch deleting + # events for monitor A held Event_Summaries[A] and waited on Storage, while + # a concurrent batch on monitor B held Storage and waited on + # Event_Summaries[B]: an ABBA cycle. It only bites when the caller manages + # the transaction, because then the deletes have not committed and their + # locks are still held when Storage is requested. + # # InnoDB X-locks the matched Events row during WHERE evaluation, before # either BEFORE or AFTER trigger bodies fire, so the lock acquisition # order is the same regardless of trigger timing: - # Events[Id] -> Events_Hour/Day/Week/Month[EventId] -> Event_Summaries[MonitorId] + # Storage[Id] -> Events[Id] -> Events_Hour/Day/Week/Month[EventId] -> Event_Summaries[MonitorId] # event_delete_trigger (BEFORE DELETE on Events) and event_update_trigger # (AFTER UPDATE on Events) both propagate into the bucket tables, whose # own triggers then UPDATE Event_Summaries — that's the canonical chain. @@ -415,6 +425,13 @@ sub delete { # # Retry on deadlock (MariaDB ER_LOCK_DEADLOCK = 1213) only when we own # the TX; if the caller is managing one, bail and let them decide. + + # Resolved once, outside the retry loop: DiskSpace() can stat the event + # directory and Storage() can hit the db, and neither changes between + # attempts. + my $storage = $event->Storage(); + my $reclaim = $event->DiskSpace(); + my $attempt = 0; my $max_attempts = 5; while (1) { @@ -428,16 +445,36 @@ sub delete { $ZoneMinder::Database::dbh->begin_work(); } + my @statements; + + # Reclaim the event's disk usage first, so the shared Storage row is + # locked ahead of the per-monitor rows the deletes below will touch. + # A single atomic decrement replaces the old lock_and_load + save + # read-modify-write: the UPDATE takes the same X lock the SELECT ... FOR + # UPDATE did, without a window between read and write, and GREATEST() + # keeps DiskSpace from going negative if the accounting has drifted. + # This also puts the reclaim inside the delete transaction, so it rolls + # back with the deletes instead of being applied after a commit. + if ($reclaim and $storage->Id()) { + push @statements, [ + 'UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) - ?, 0) WHERE Id=?', + $reclaim, $storage->Id(), + ]; + } + # Order: Stats -> Event_Data -> Frames -> Events (least to greatest reference depth) - my $err = 0; - my $errstr = ''; - foreach my $sql ( + push @statements, map { [$_, $$event{Id}] } ( 'DELETE FROM Stats WHERE EventId=?', 'DELETE FROM Event_Data WHERE EventId=?', 'DELETE FROM Frames WHERE EventId=?', 'DELETE FROM Events WHERE Id=?', - ) { - ZoneMinder::Database::zmDbDo($sql, $$event{Id}); + ); + + my $err = 0; + my $errstr = ''; + foreach my $statement (@statements) { + my ($sql, @params) = @$statement; + ZoneMinder::Database::zmDbDo($sql, @params); $err = $ZoneMinder::Database::dbh->err() // 0; if ($err) { # Capture before rollback, which can clear errstr on some drivers. @@ -463,12 +500,6 @@ sub delete { Debug("Deadlock deleting event $$event{Id} attempt $attempt/$max_attempts, retrying"); select(undef, undef, undef, 0.05 * (1 << $attempt) + rand(0.05)); } - - my $storage = $event->Storage(); - if ($event->DiskSpace() and $storage->Id()) { - $storage->lock_and_load(); - $storage->save({DiskSpace=>$storage->DiskSpace()-$event->DiskSpace()}); - } } if ( ( $in_zmaudit or (!$Config{ZM_OPT_FAST_DELETE})) and $event->Storage()->DoDelete() ) { @@ -831,13 +862,19 @@ sub MoveTo { $ZoneMinder::Database::dbh->commit() if !$was_in_transaction; # Update storage diskspace. The triggers no longer do this. This is ... less important so do it outside the transaction - if ($old_diskspace and $$OldStorage{Id}) { - $OldStorage->lock_and_load(); - $OldStorage->save({DiskSpace => $OldStorage->DiskSpace()-$old_diskspace}); - } - if ($new_diskspace and $$NewStorage{Id}) { - $NewStorage->lock_and_load(); - $NewStorage->save({DiskSpace => $NewStorage->DiskSpace()+$new_diskspace}); + # Atomic adjustments rather than lock_and_load + save: outside a transaction + # the SELECT ... FOR UPDATE released its lock as soon as it committed, so the + # read and the write raced and concurrent movers could lose an update. Lowest + # Storage Id first, so two movers swapping events between the same pair of + # storage areas cannot deadlock against each other. + my @adjustments; + push @adjustments, [$$OldStorage{Id}, -$old_diskspace] if $old_diskspace and $$OldStorage{Id}; + push @adjustments, [$$NewStorage{Id}, $new_diskspace] if $new_diskspace and $$NewStorage{Id}; + foreach my $adjustment (sort { $$a[0] <=> $$b[0] } @adjustments) { + my ($storage_id, $delta) = @$adjustment; + ZoneMinder::Database::zmDbDo( + 'UPDATE Storage SET DiskSpace = GREATEST(COALESCE(DiskSpace,0) + ?, 0) WHERE Id=?', + $delta, $storage_id); } $self->delete_files($OldStorage); diff --git a/scripts/ZoneMinder/t/event_delete_lock_order.t b/scripts/ZoneMinder/t/event_delete_lock_order.t new file mode 100644 index 0000000000..fe478b50f9 --- /dev/null +++ b/scripts/ZoneMinder/t/event_delete_lock_order.t @@ -0,0 +1,105 @@ +use strict; +use warnings; +use Test::More; +use File::Temp qw(tempdir); + +eval { require ZoneMinder::Event; 1 } or plan skip_all => "cannot load ZoneMinder::Event: $@"; +require ZoneMinder::Database; +plan tests => 11; + +# Storage is shared across monitors; Event_Summaries is per-monitor. delete() +# has to take the coarse Storage row before the deletes cascade into the fine +# per-monitor rows, otherwise two concurrent batches on different monitors +# deadlock (issue #4964). Nothing here needs a database: we record the order +# statements are issued in. + +my $storage_dir = tempdir(CLEANUP => 1); + +{ + package Test::Storage; + sub new { my ($class, $id, $path) = @_; return bless {Id => $id, Path => $path, DiskSpace => 1_000_000}, $class } + sub Id { return $_[0]{Id} } + sub Path { return $_[0]{Path} } + sub DoDelete { return 0 } # keep delete() out of the filesystem + # The pre-fix code reclaimed disk space through these two rather than + # through zmDbDo. They are here so that code path runs to completion and + # the ordering assertions below are what fail, rather than a missing method. + sub lock_and_load { return 1 } + sub DiskSpace { return $_[0]{DiskSpace} } + sub save { return '' } +} + +{ + package Test::STH; + # Just enough statement handle for ZoneMinder::Logger's INSERT INTO Logs. + sub new { return bless {}, shift } + sub execute { return 1 } + sub finish { return 1 } + sub errstr { return '' } +} + +{ + package Test::DBH; + # AutoCommit off means "caller is managing the transaction", which is the + # batch path where the deadlock actually bites. + sub new { return bless {AutoCommit => 0}, shift } + sub ping { return 1 } + sub err { return 0 } + sub errstr { return '' } + sub begin_work { return 1 } + sub commit { return 1 } + sub rollback { return 1 } + sub do { return 1 } + sub prepare { return Test::STH->new() } + sub prepare_cached { return Test::STH->new() } + sub selectrow_hashref { return undef } + sub quote { return $_[1] } +} + +my @issued; +{ + no warnings 'redefine', 'once'; + *ZoneMinder::Database::zmDbDo = sub { push @issued, [@_]; return 1 }; +} + +sub run_delete { + my ($diskspace) = @_; + @issued = (); + no warnings "once"; + $ZoneMinder::Database::dbh = Test::DBH->new(); + + my $event = new ZoneMinder::Event(); + $$event{Id} = 42; + $$event{MonitorId} = 8; + $$event{StartDateTime} = '2026-01-01 00:00:00'; + $$event{Storage} = Test::Storage->new(2, $storage_dir); + $$event{StorageId} = 2; + $$event{Path} = $storage_dir; + $event->DiskSpace($diskspace); + + $event->delete(); + return map { $_->[0] } @issued; +} + +my @sql = run_delete(4096); + +is(scalar(@sql), 5, 'one Storage update plus the four deletes'); +like($sql[0], qr/^UPDATE Storage /, 'Storage is locked first, before any delete'); +like($sql[0], qr/GREATEST/, 'DiskSpace is clamped so it cannot go negative'); +is_deeply([$issued[0][1], $issued[0][2]], [4096, 2], + 'Storage update is parameterised by reclaim and storage id'); + +my ($storage_at) = grep { $sql[$_] =~ /^UPDATE Storage / } 0 .. $#sql; +my ($events_at) = grep { $sql[$_] =~ /DELETE FROM Events / } 0 .. $#sql; +ok(defined($storage_at) && defined($events_at) && $storage_at < $events_at, + 'Storage precedes the Events delete that cascades into Event_Summaries'); + +is($sql[1], 'DELETE FROM Stats WHERE EventId=?', 'Stats deleted first of the event rows'); +is($sql[2], 'DELETE FROM Event_Data WHERE EventId=?', 'then Event_Data'); +is($sql[3], 'DELETE FROM Frames WHERE EventId=?', 'then Frames'); +is($sql[4], 'DELETE FROM Events WHERE Id=?', 'Events last, so its triggers run after its dependants are gone'); + +# With nothing to reclaim there is no reason to touch the shared row at all. +my @no_reclaim = run_delete(0); +is(scalar(@no_reclaim), 4, 'no Storage update when the event has no disk usage'); +unlike($no_reclaim[0], qr/^UPDATE Storage /, 'first statement is a delete when there is nothing to reclaim'); From dc606ee46c2516f51124d07d6c52e3fd1be4b164 Mon Sep 17 00:00:00 2001 From: Jash Date: Fri, 21 Aug 2026 08:35:16 +0530 Subject: [PATCH 2/5] docs: correct the MoveTo storage comment about transaction scope refs #4964 --- scripts/ZoneMinder/lib/ZoneMinder/Event.pm | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm index 6814838371..336ea0fd25 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm @@ -861,12 +861,21 @@ sub MoveTo { } $ZoneMinder::Database::dbh->commit() if !$was_in_transaction; - # Update storage diskspace. The triggers no longer do this. This is ... less important so do it outside the transaction - # Atomic adjustments rather than lock_and_load + save: outside a transaction - # the SELECT ... FOR UPDATE released its lock as soon as it committed, so the - # read and the write raced and concurrent movers could lose an update. Lowest - # Storage Id first, so two movers swapping events between the same pair of - # storage areas cannot deadlock against each other. + # Update storage diskspace. The triggers no longer do this. + # Atomic adjustments rather than lock_and_load + save: when we own the + # transaction the SELECT ... FOR UPDATE released its lock the moment it + # committed, so the read and the write raced and concurrent movers could lose + # an update. Lowest Storage Id first, so two movers swapping events between + # the same pair of storage areas cannot deadlock against each other. + # + # Note these are NOT outside a transaction when the caller owns one, which a + # filter with LockRows does. In that case Storage is locked here, after this + # sub has already locked the Event and its save() has cascaded into the bucket + # and Event_Summaries rows, so the order is the reverse of the Storage-first + # order delete() now uses. That inversion predates this change and is left + # alone deliberately: locking Storage before lock_and_load would hold a row on + # a shared storage area for the whole of CopyTo, serialising every move on + # that area behind one file copy. my @adjustments; push @adjustments, [$$OldStorage{Id}, -$old_diskspace] if $old_diskspace and $$OldStorage{Id}; push @adjustments, [$$NewStorage{Id}, $new_diskspace] if $new_diskspace and $$NewStorage{Id}; From d0ef2b7b20ada3d99b378b6471cc76a1dc5af486 Mon Sep 17 00:00:00 2001 From: Jash Date: Wed, 26 Aug 2026 09:34:22 +0530 Subject: [PATCH 3/5] fix: put the disk space reclaim back when a caller-owned delete transaction fails refs #4964 --- scripts/ZoneMinder/lib/ZoneMinder/Event.pm | 17 +++++++++- .../ZoneMinder/t/event_delete_lock_order.t | 32 ++++++++++++++++--- 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm index 5f5e533054..854fa0e5ec 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm @@ -447,6 +447,7 @@ sub delete { my $err = 0; my $errstr = ''; + my $reclaimed = 0; # Reclaim the disk usage FIRST, so the shared Storage row is locked ahead # of the per-monitor rows the deletes below touch. Doing it afterwards @@ -459,7 +460,11 @@ sub delete { if ($reclaim and $storage->Id()) { $storage->adjust_diskspace(-$reclaim); $err = $ZoneMinder::Database::dbh->err() // 0; - $errstr = $ZoneMinder::Database::dbh->errstr() // '' if $err; + if ($err) { + $errstr = $ZoneMinder::Database::dbh->errstr() // ''; + } else { + $reclaimed = 1; + } } # Order: Stats -> Event_Data -> Frames -> Events (least to greatest reference depth) @@ -485,6 +490,16 @@ sub delete { } $ZoneMinder::Database::dbh->rollback() if !$in_transaction; + + # That rollback undoes the reclaim when we own the transaction. When the + # caller owns it we cannot roll back, and zmfilter ignores what delete() + # returns and commits regardless (scripts/zmfilter.pl.in), so a reclaim + # left standing would commit a DiskSpace decrement for an event that is + # still there. Put it back. + if ($reclaimed and $in_transaction) { + $storage->adjust_diskspace($reclaim); + } + if ($in_transaction or $err != 1213 or $attempt >= $max_attempts) { # 1213 = ER_LOCK_DEADLOCK # Surface the final failure ourselves — zmDbDo suppresses its Error # log on 1213 inside a caller-managed TX (we own the retry), and the diff --git a/scripts/ZoneMinder/t/event_delete_lock_order.t b/scripts/ZoneMinder/t/event_delete_lock_order.t index 127680f1cc..751c05c36a 100644 --- a/scripts/ZoneMinder/t/event_delete_lock_order.t +++ b/scripts/ZoneMinder/t/event_delete_lock_order.t @@ -5,7 +5,7 @@ use File::Temp qw(tempdir); eval { require ZoneMinder::Event; 1 } or plan skip_all => "cannot load ZoneMinder::Event: $@"; require ZoneMinder::Database; -plan tests => 11; +plan tests => 15; # Storage is shared across monitors; Event_Summaries is per-monitor. delete() # has to take the coarse Storage row before the deletes cascade into the fine @@ -53,10 +53,10 @@ my $storage_dir = tempdir(CLEANUP => 1); package Test::DBH; # AutoCommit off means "caller is managing the transaction", which is the # batch path where the deadlock actually bites. - sub new { return bless {AutoCommit => 0}, shift } + sub new { return bless {AutoCommit => 0, err => 0}, shift } sub ping { return 1 } - sub err { return 0 } - sub errstr { return '' } + sub err { return $_[0]{err} } + sub errstr { return $_[0]{err} ? 'mock failure' : '' } sub begin_work { return 1 } sub commit { return 1 } sub rollback { return 1 } @@ -68,9 +68,17 @@ my $storage_dir = tempdir(CLEANUP => 1); } my @issued; +my $fail_on = ''; { no warnings 'redefine', 'once'; - *ZoneMinder::Database::zmDbDo = sub { push @issued, [@_]; return 1 }; + *ZoneMinder::Database::zmDbDo = sub { + push @issued, [@_]; + # $fail_on lets a test make one statement fail, so the compensating path runs. + if ($fail_on and $_[0] =~ /\Q$fail_on\E/) { + $ZoneMinder::Database::dbh->{err} = 1205; # lock wait timeout, not a deadlock + } + return 1; + }; } sub run_delete { @@ -110,6 +118,20 @@ is($sql[2], 'DELETE FROM Event_Data WHERE EventId=?', 'then Event_Data'); is($sql[3], 'DELETE FROM Frames WHERE EventId=?', 'then Frames'); is($sql[4], 'DELETE FROM Events WHERE Id=?', 'Events last, so its triggers run after its dependants are gone'); +# A failed delete inside a caller-managed transaction must not leave the reclaim +# standing. delete() cannot roll back a transaction it does not own, and zmfilter +# ignores what delete() returns and commits anyway, so a decrement left in place +# would be committed against an event that still exists. +$fail_on = 'DELETE FROM Stats'; +my @failed = run_delete(4096); +$fail_on = ''; + +my @storage_stmts = grep { $_->[0] =~ /^UPDATE Storage/ } @issued; +is(scalar(@storage_stmts), 2, 'the reclaim is followed by a compensating adjustment'); +is($storage_stmts[0][1], -4096, 'first takes the space off'); +is($storage_stmts[1][1], 4096, 'second puts it back'); +is($storage_stmts[0][2], $storage_stmts[1][2], 'both target the same storage area'); + # With nothing to reclaim there is no reason to touch the shared row at all. my @no_reclaim = run_delete(0); is(scalar(@no_reclaim), 4, 'no Storage update when the event has no disk usage'); From f22b8b5e35971568527e9bf8ded478ed8e5ca092 Mon Sep 17 00:00:00 2001 From: Jash Date: Sun, 8 Nov 2026 15:02:13 +0530 Subject: [PATCH 4/5] fix: reclaim disk space inside delete's own transaction instead of locking Storage first, refs #4964 --- scripts/ZoneMinder/lib/ZoneMinder/Event.pm | 63 ++-- .../ZoneMinder/t/event_delete_lock_order.t | 138 --------- scripts/ZoneMinder/t/event_delete_reclaim.t | 268 ++++++++++++++++++ 3 files changed, 288 insertions(+), 181 deletions(-) delete mode 100644 scripts/ZoneMinder/t/event_delete_lock_order.t create mode 100644 scripts/ZoneMinder/t/event_delete_reclaim.t diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm index 555344f3c8..15db103563 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm @@ -424,20 +424,10 @@ sub delete { my $in_transaction = $ZoneMinder::Database::dbh->{AutoCommit} ? 0 : 1; - # Storage[Id] is taken first, before anything per-monitor. It is the only - # row here shared across monitors, so it has to be the coarsest lock in the - # order. Taking it last (as the old lock_and_load did, after the deletes - # had already X-locked Event_Summaries[MonitorId]) meant a batch deleting - # events for monitor A held Event_Summaries[A] and waited on Storage, while - # a concurrent batch on monitor B held Storage and waited on - # Event_Summaries[B]: an ABBA cycle. It only bites when the caller manages - # the transaction, because then the deletes have not committed and their - # locks are still held when Storage is requested. - # # InnoDB X-locks the matched Events row during WHERE evaluation, before # either BEFORE or AFTER trigger bodies fire, so the lock acquisition # order is the same regardless of trigger timing: - # Storage[Id] -> Events[Id] -> Events_Hour/Day/Week/Month[EventId] -> Event_Summaries[MonitorId] + # Events[Id] -> Events_Hour/Day/Week/Month[EventId] -> Event_Summaries[MonitorId] # event_delete_trigger (BEFORE DELETE on Events) and event_update_trigger # (AFTER UPDATE on Events) both propagate into the bucket tables, whose # own triggers then UPDATE Event_Summaries — that's the canonical chain. @@ -474,36 +464,15 @@ sub delete { $ZoneMinder::Database::dbh->begin_work(); } + # Order: Stats -> Event_Data -> Frames -> Events (least to greatest reference depth) my $err = 0; my $errstr = ''; - my $reclaimed = 0; - - # Reclaim the disk usage FIRST, so the shared Storage row is locked ahead - # of the per-monitor rows the deletes below touch. Doing it afterwards - # meant a batch could hold Event_Summaries[MonitorId] while waiting on - # Storage, while a concurrent batch held Storage and waited on - # Event_Summaries. Reclaiming here also puts it inside the transaction, - # so it rolls back with the deletes rather than being applied after them. - # See ZoneMinder::Storage::adjust_diskspace for why this is a relative - # single statement rather than a read-modify-write. - if ($reclaim and $storage->Id()) { - $storage->adjust_diskspace(-$reclaim); - $err = $ZoneMinder::Database::dbh->err() // 0; - if ($err) { - $errstr = $ZoneMinder::Database::dbh->errstr() // ''; - } else { - $reclaimed = 1; - } - } - - # Order: Stats -> Event_Data -> Frames -> Events (least to greatest reference depth) foreach my $sql ( 'DELETE FROM Stats WHERE EventId=?', 'DELETE FROM Event_Data WHERE EventId=?', 'DELETE FROM Frames WHERE EventId=?', 'DELETE FROM Events WHERE Id=?', ) { - last if $err; ZoneMinder::Database::zmDbDo($sql, $$event{Id}); $err = $ZoneMinder::Database::dbh->err() // 0; if ($err) { @@ -513,22 +482,23 @@ sub delete { } } + if (!$err and !$in_transaction and $reclaim) { + # Reclaim inside our own transaction, after the deletes succeed, so it + # commits or rolls back with them and is retried on deadlock. A relative + # single statement, see ZoneMinder::Storage::adjust_diskspace. + $storage->adjust_diskspace(-$reclaim); + $err = $ZoneMinder::Database::dbh->err() // 0; + if ($err) { + $errstr = $ZoneMinder::Database::dbh->errstr() // ''; + } + } + if (!$err) { $ZoneMinder::Database::dbh->commit() if !$in_transaction; last; } $ZoneMinder::Database::dbh->rollback() if !$in_transaction; - - # That rollback undoes the reclaim when we own the transaction. When the - # caller owns it we cannot roll back, and zmfilter ignores what delete() - # returns and commits regardless (scripts/zmfilter.pl.in), so a reclaim - # left standing would commit a DiskSpace decrement for an event that is - # still there. Put it back. - if ($reclaimed and $in_transaction) { - $storage->adjust_diskspace($reclaim); - } - if ($in_transaction or $err != 1213 or $attempt >= $max_attempts) { # 1213 = ER_LOCK_DEADLOCK # Surface the final failure ourselves — zmDbDo suppresses its Error # log on 1213 inside a caller-managed TX (we own the retry), and the @@ -540,6 +510,13 @@ sub delete { Debug("Deadlock deleting event $$event{Id} attempt $attempt/$max_attempts, retrying"); select(undef, undef, undef, 0.05 * (1 << $attempt) + rand(0.05)); } + + # Relative, single-statement adjustment. A lock_and_load + save here would + # be a read-modify-write whose FOR UPDATE lock is dropped the moment the + # SELECT autocommits, so the absolute value it then writes clobbers any + # adjustment zmc or another filter made in between. + # See ZoneMinder::Storage::adjust_diskspace. + $storage->adjust_diskspace(-$reclaim) if $in_transaction and $reclaim; } if ( $event->Storage()->DoDelete() ) { diff --git a/scripts/ZoneMinder/t/event_delete_lock_order.t b/scripts/ZoneMinder/t/event_delete_lock_order.t deleted file mode 100644 index 751c05c36a..0000000000 --- a/scripts/ZoneMinder/t/event_delete_lock_order.t +++ /dev/null @@ -1,138 +0,0 @@ -use strict; -use warnings; -use Test::More; -use File::Temp qw(tempdir); - -eval { require ZoneMinder::Event; 1 } or plan skip_all => "cannot load ZoneMinder::Event: $@"; -require ZoneMinder::Database; -plan tests => 15; - -# Storage is shared across monitors; Event_Summaries is per-monitor. delete() -# has to take the coarse Storage row before the deletes cascade into the fine -# per-monitor rows, otherwise two concurrent batches on different monitors -# deadlock (issue #4964). Nothing here needs a database: we record the order -# statements are issued in. - -my $storage_dir = tempdir(CLEANUP => 1); - -{ - package Test::Storage; - sub new { my ($class, $id, $path) = @_; return bless {Id => $id, Path => $path, DiskSpace => 1_000_000}, $class } - sub Id { return $_[0]{Id} } - sub Path { return $_[0]{Path} } - sub DoDelete { return 0 } # keep delete() out of the filesystem - # Mirrors ZoneMinder::Storage::adjust_diskspace, which is what delete() calls - # now. It has to go through zmDbDo so the statement shows up in the recorded - # order, which is the whole point of this test. - sub adjust_diskspace { - my ($self, $delta) = @_; - return if !$$self{Id} or !$delta; - return ZoneMinder::Database::zmDbDo( - 'UPDATE Storage SET DiskSpace=GREATEST(COALESCE(DiskSpace,0)+?,0) WHERE Id=?', - $delta, $$self{Id}); - } - - # The pre-fix code reclaimed disk space through these rather than through - # zmDbDo. They are here so that path runs to completion and the ordering - # assertions below are what fail, rather than a missing method. - sub lock_and_load { return 1 } - sub DiskSpace { return $_[0]{DiskSpace} } - sub save { return '' } -} - -{ - package Test::STH; - # Just enough statement handle for ZoneMinder::Logger's INSERT INTO Logs. - sub new { return bless {}, shift } - sub execute { return 1 } - sub finish { return 1 } - sub errstr { return '' } -} - -{ - package Test::DBH; - # AutoCommit off means "caller is managing the transaction", which is the - # batch path where the deadlock actually bites. - sub new { return bless {AutoCommit => 0, err => 0}, shift } - sub ping { return 1 } - sub err { return $_[0]{err} } - sub errstr { return $_[0]{err} ? 'mock failure' : '' } - sub begin_work { return 1 } - sub commit { return 1 } - sub rollback { return 1 } - sub do { return 1 } - sub prepare { return Test::STH->new() } - sub prepare_cached { return Test::STH->new() } - sub selectrow_hashref { return undef } - sub quote { return $_[1] } -} - -my @issued; -my $fail_on = ''; -{ - no warnings 'redefine', 'once'; - *ZoneMinder::Database::zmDbDo = sub { - push @issued, [@_]; - # $fail_on lets a test make one statement fail, so the compensating path runs. - if ($fail_on and $_[0] =~ /\Q$fail_on\E/) { - $ZoneMinder::Database::dbh->{err} = 1205; # lock wait timeout, not a deadlock - } - return 1; - }; -} - -sub run_delete { - my ($diskspace) = @_; - @issued = (); - no warnings "once"; - $ZoneMinder::Database::dbh = Test::DBH->new(); - - my $event = new ZoneMinder::Event(); - $$event{Id} = 42; - $$event{MonitorId} = 8; - $$event{StartDateTime} = '2026-01-01 00:00:00'; - $$event{Storage} = Test::Storage->new(2, $storage_dir); - $$event{StorageId} = 2; - $$event{Path} = $storage_dir; - $event->DiskSpace($diskspace); - - $event->delete(); - return map { $_->[0] } @issued; -} - -my @sql = run_delete(4096); - -is(scalar(@sql), 5, 'one Storage update plus the four deletes'); -like($sql[0], qr/^UPDATE Storage /, 'Storage is locked first, before any delete'); -like($sql[0], qr/GREATEST/, 'DiskSpace is clamped so it cannot go negative'); -is_deeply([$issued[0][1], $issued[0][2]], [-4096, 2], - 'Storage update is parameterised by the negative reclaim and the storage id'); - -my ($storage_at) = grep { $sql[$_] =~ /^UPDATE Storage / } 0 .. $#sql; -my ($events_at) = grep { $sql[$_] =~ /DELETE FROM Events / } 0 .. $#sql; -ok(defined($storage_at) && defined($events_at) && $storage_at < $events_at, - 'Storage precedes the Events delete that cascades into Event_Summaries'); - -is($sql[1], 'DELETE FROM Stats WHERE EventId=?', 'Stats deleted first of the event rows'); -is($sql[2], 'DELETE FROM Event_Data WHERE EventId=?', 'then Event_Data'); -is($sql[3], 'DELETE FROM Frames WHERE EventId=?', 'then Frames'); -is($sql[4], 'DELETE FROM Events WHERE Id=?', 'Events last, so its triggers run after its dependants are gone'); - -# A failed delete inside a caller-managed transaction must not leave the reclaim -# standing. delete() cannot roll back a transaction it does not own, and zmfilter -# ignores what delete() returns and commits anyway, so a decrement left in place -# would be committed against an event that still exists. -$fail_on = 'DELETE FROM Stats'; -my @failed = run_delete(4096); -$fail_on = ''; - -my @storage_stmts = grep { $_->[0] =~ /^UPDATE Storage/ } @issued; -is(scalar(@storage_stmts), 2, 'the reclaim is followed by a compensating adjustment'); -is($storage_stmts[0][1], -4096, 'first takes the space off'); -is($storage_stmts[1][1], 4096, 'second puts it back'); -is($storage_stmts[0][2], $storage_stmts[1][2], 'both target the same storage area'); - -# With nothing to reclaim there is no reason to touch the shared row at all. -my @no_reclaim = run_delete(0); -is(scalar(@no_reclaim), 4, 'no Storage update when the event has no disk usage'); -unlike($no_reclaim[0], qr/^UPDATE Storage /, 'first statement is a delete when there is nothing to reclaim'); diff --git a/scripts/ZoneMinder/t/event_delete_reclaim.t b/scripts/ZoneMinder/t/event_delete_reclaim.t new file mode 100644 index 0000000000..9d8c7acd0c --- /dev/null +++ b/scripts/ZoneMinder/t/event_delete_reclaim.t @@ -0,0 +1,268 @@ +use strict; +use warnings; +use Test::More; +use File::Temp qw(tempdir); + +eval { require ZoneMinder::Event; 1 } or plan skip_all => "cannot load ZoneMinder::Event: $@"; +require ZoneMinder::Database; + +# Event::delete() owns the transaction when AutoCommit is on: the four event +# deletes and the Storage DiskSpace reclaim commit together, so a database +# error from the reclaim (or a deadlock on any statement) rolls the whole lot +# back. When the caller owns the transaction delete() must not begin, commit or +# rollback, and it reclaims once after the deletes. +# +# Nothing here needs a real database: the fake dbh records statements and +# transaction calls in order, and the fake storage records its reclaim calls. + +my $storage_dir = tempdir(CLEANUP => 1); + +my @calls; + +{ + package Test::Storage; + sub new { + my ($class, $id, $path) = @_; + return bless { Id => $id, Path => $path, DiskSpace => 1_000_000 }, $class; + } + sub Id { return $_[0]{Id} } + sub Path { return $_[0]{Path} } + sub DiskSpace { return $_[0]{DiskSpace} } + sub DoDelete { return 0 } # keep delete() out of the filesystem + + # Records the reclaim and, when asked, leaves a db error on the handle so + # delete() treats the reclaim like any other statement in its transaction. + sub adjust_diskspace { + my ($self, $delta) = @_; + push @calls, ['adjust_diskspace', $delta]; + $$self{reclaims}++; + my $dbh = $ZoneMinder::Database::dbh; + if ($$self{db_error}) { + $dbh->{err} = $$self{db_error}; + $dbh->{errstr} = 'mock adjust_diskspace failure'; + } else { + $dbh->{err} = 0; + $dbh->{errstr} = ''; + } + return 1; + } +} + +{ + package Test::STH; + # Just enough statement handle for ZoneMinder::Logger's INSERT INTO Logs. + sub new { return bless {}, shift } + sub execute { return 1 } + sub finish { return 1 } + sub errstr { return '' } +} + +{ + package Test::DBH; + # DBI's begin_work turns AutoCommit off for the duration of the transaction + # and commit/rollback turn it back on. That is what makes zmDbDo stop doing + # its own retries once delete() owns the transaction. + sub new { + my ($class, %args) = @_; + return bless { + AutoCommit => exists $args{AutoCommit} ? $args{AutoCommit} : 1, + err => 0, + errstr => '', + fail_sql => $args{fail_sql}, + fail_err => $args{fail_err}, + fail_times => $args{fail_times}, + }, $class; + } + sub ping { return 1 } + sub err { return $_[0]{err} } + sub errstr { return $_[0]{err} ? ($_[0]{errstr} || 'mock failure') : '' } + sub _ok { + my $self = shift; + $self->{err} = 0; + $self->{errstr} = ''; + } + sub do { + my ($self, $sql) = @_; + push @calls, ['do', $sql]; + $self->_ok; + + my $fail = 0; + if (defined $self->{fail_sql} and $sql =~ $self->{fail_sql}) { + if (!defined $self->{fail_times}) { + $fail = 1; + } elsif ($self->{fail_times} > 0) { + $self->{fail_times}--; + $fail = 1; + } + } + if ($fail) { + $self->{err} = $self->{fail_err} || 1205; + $self->{errstr} = 'mock statement failure'; + return; + } + return 1; + } + sub begin_work { + my $self = shift; + push @calls, ['begin_work']; + $self->{AutoCommit} = 0; + $self->_ok; + return 1; + } + sub commit { + my $self = shift; + push @calls, ['commit']; + $self->{AutoCommit} = 1; + $self->_ok; + return 1; + } + sub rollback { + my $self = shift; + push @calls, ['rollback']; + $self->{AutoCommit} = 1; + $self->_ok; + return 1; + } + sub prepare { return Test::STH->new() } + sub prepare_cached { return Test::STH->new() } + sub selectrow_hashref { return undef } + sub quote { return $_[1] } +} + +my @delete_sql = ( + 'DELETE FROM Stats WHERE EventId=?', + 'DELETE FROM Event_Data WHERE EventId=?', + 'DELETE FROM Frames WHERE EventId=?', + 'DELETE FROM Events WHERE Id=?', +); + +sub run_delete { + my (%opts) = @_; + @calls = (); + + my $dbh = Test::DBH->new( + AutoCommit => exists $opts{AutoCommit} ? $opts{AutoCommit} : 1, + fail_sql => $opts{fail_sql}, + fail_err => $opts{fail_err}, + fail_times => $opts{fail_times}, + ); + $ZoneMinder::Database::dbh = $dbh; + + my $event = new ZoneMinder::Event(); + $$event{Id} = 42; + $$event{MonitorId} = 8; + $$event{StartDateTime} = '2026-01-01 00:00:00'; + + my $storage = Test::Storage->new(2, $storage_dir); + $$storage{db_error} = $opts{adjust_error} if $opts{adjust_error}; + $$event{Storage} = $storage; + $$event{StorageId} = 2; + $$event{Path} = $storage_dir; + + $event->DiskSpace(exists $opts{DiskSpace} ? $opts{DiskSpace} : 4096); + + my $ret = $event->delete(); + return ($ret, [@calls], $storage); +} + +sub delete_sqls { + my ($calls) = @_; + return map { $_->[1] } grep { $_->[0] eq 'do' and $_->[1] =~ /^DELETE / } @$calls; +} + +sub adjust_deltas { + my ($calls) = @_; + return map { $_->[1] } grep { $_->[0] eq 'adjust_diskspace' } @$calls; +} + +sub call_count { + my ($calls, $type) = @_; + return scalar grep { $_->[0] eq $type } @$calls; +} + +# The deletes, reclaims, commits and rollbacks, in issue order. Transaction +# plumbing (SET TRANSACTION, begin_work) is checked through call_count(). +sub reclaim_sequence { + my ($calls) = @_; + my @sequence; + foreach my $call (@$calls) { + my ($kind, $arg) = @$call; + if ($kind eq 'do') { + push @sequence, 'delete' if $arg =~ /^DELETE /; + } elsif ($kind ne 'begin_work') { + push @sequence, $kind; + } + } + return @sequence; +} + +# 1. Owned, success: deletes, reclaim, commit in that order. +my ($ret, $calls, $storage) = run_delete(DiskSpace => 4096); +is_deeply([delete_sqls($calls)], \@delete_sql, + 'owned success: the four event deletes run in dependency order'); +is_deeply([reclaim_sequence($calls)], + [('delete') x 4, 'adjust_diskspace', 'commit'], + 'owned success: the reclaim happens after the deletes and before the commit'); +is(call_count($calls, 'adjust_diskspace'), 1, 'owned success: reclaims exactly once'); +is_deeply([adjust_deltas($calls)], [-4096], + 'owned success: reclaim is the negative of the event disk space'); +is(call_count($calls, 'begin_work'), 1, 'owned success: delete() begins its own transaction'); + +# 2. Owned, a DELETE fails with a non-deadlock error. +($ret, $calls, $storage) = run_delete( + DiskSpace => 4096, + fail_sql => qr/^DELETE FROM Stats /, + fail_err => 1205, # lock wait timeout, not a deadlock +); +ok(!defined $ret, 'owned failure: delete() returns failure'); +is_deeply([reclaim_sequence($calls)], ['delete', 'rollback'], + 'owned failure: rolls back after the failed delete'); +is(call_count($calls, 'adjust_diskspace'), 0, + 'owned failure: the reclaim is never attempted after a failed delete'); +is(call_count($calls, 'commit'), 0, 'owned failure: never commits'); + +# 3. Owned, deadlock 1213 on the first attempt then success. +($ret, $calls, $storage) = run_delete( + DiskSpace => 4096, + fail_sql => qr/^DELETE FROM Stats /, + fail_err => 1213, # ER_LOCK_DEADLOCK + fail_times => 1, +); +is_deeply([reclaim_sequence($calls)], + ['delete', 'rollback', ('delete') x 4, 'adjust_diskspace', 'commit'], + 'owned deadlock: rollback, retry, reclaim, then commit'); +is(call_count($calls, 'rollback'), 1, 'owned deadlock: rolls back the first attempt once'); +is(call_count($calls, 'begin_work'), 2, 'owned deadlock: retries in a fresh transaction'); +is(call_count($calls, 'adjust_diskspace'), 1, + 'owned deadlock: reclaim is applied only once in total'); +is(call_count($calls, 'commit'), 1, 'owned deadlock: commits the successful retry'); + +# 4. Owned, adjust_diskspace sets a db error. +($ret, $calls, $storage) = run_delete( + DiskSpace => 4096, + adjust_error => 1205, # non-deadlock failure from the reclaim statement +); +ok(!defined $ret, 'owned reclaim failure: delete() returns failure'); +is_deeply([reclaim_sequence($calls)], + [('delete') x 4, 'adjust_diskspace', 'rollback'], + 'owned reclaim failure: the reclaim error rolls back the deletes'); +is(call_count($calls, 'commit'), 0, 'owned reclaim failure: does not commit'); +is(call_count($calls, 'rollback'), 1, 'owned reclaim failure: rolls back once'); + +# 5. Caller-owned: delete() must leave transaction control with the caller. +($ret, $calls, $storage) = run_delete(DiskSpace => 4096, AutoCommit => 0); +is_deeply([reclaim_sequence($calls)], [('delete') x 4, 'adjust_diskspace'], + 'caller-owned: deletes then a single reclaim'); +is(call_count($calls, 'adjust_diskspace'), 1, 'caller-owned: reclaims exactly once'); +is(call_count($calls, 'begin_work'), 0, 'caller-owned: delete() does not begin a transaction'); +is(call_count($calls, 'commit'), 0, 'caller-owned: delete() does not commit'); +is(call_count($calls, 'rollback'), 0, 'caller-owned: delete() does not roll back'); + +# 6. Nothing to reclaim. +($ret, $calls, $storage) = run_delete(DiskSpace => 0); +is_deeply([reclaim_sequence($calls)], [('delete') x 4, 'commit'], + 'zero DiskSpace: deletes and commits without a reclaim'); +is(call_count($calls, 'adjust_diskspace'), 0, + 'zero DiskSpace: never calls adjust_diskspace'); + +done_testing(); From c8cd976cd467d4dab626145ad73d1f67cb6d59dd Mon Sep 17 00:00:00 2001 From: Jash Date: Mon, 16 Nov 2026 08:48:38 +0530 Subject: [PATCH 5/5] docs: note that only a caller-managed transaction reclaims after the loop refs #4964 --- scripts/ZoneMinder/lib/ZoneMinder/Event.pm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm index 15db103563..02cf249779 100644 --- a/scripts/ZoneMinder/lib/ZoneMinder/Event.pm +++ b/scripts/ZoneMinder/lib/ZoneMinder/Event.pm @@ -516,6 +516,8 @@ sub delete { # SELECT autocommits, so the absolute value it then writes clobbers any # adjustment zmc or another filter made in between. # See ZoneMinder::Storage::adjust_diskspace. + # When delete() owns the transaction the reclaim already ran inside it, + # above; only a caller-managed transaction reclaims here, once. $storage->adjust_diskspace(-$reclaim) if $in_transaction and $reclaim; }