From af92def494bbad0b90e6687f241e2fe027c23e6e Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:51:17 +0000 Subject: [PATCH 1/5] Preserve causer decisions made by activity callbacks When a custom activity model supplies a causer, treat that choice as resolved before invoking tap. Clearing it in the callback must leave an anonymous activity, even when the current user is authenticated. Reconcile the logger tests with Spatie's late-resolution and backed-enum cases. Exercise placeholders and hooks on a log call without a preceding tap, and keep the stronger facade and lifecycle assertions in the corresponding upstream cases. Use the upstream parameter name for isResolvable so subclasses can call it with a named argument. Compared with spatie/laravel-activitylog at 741ce06abfb91a96d2ee056706a6564ae8a3a71f. --- .../src/Support/ActivityLogger.php | 12 +- .../src/Support/CauserResolver.php | 10 +- tests/ActivityLog/ActivityLogManagerTest.php | 70 ------- tests/ActivityLog/Models/User.php | 2 +- .../Support/ActivityLoggerTest.php | 177 ++++++++++++++++-- .../Support/CauserResolverTest.php | 2 +- 6 files changed, 181 insertions(+), 92 deletions(-) diff --git a/src/activity-log/src/Support/ActivityLogger.php b/src/activity-log/src/Support/ActivityLogger.php index bc9d14954..73087e967 100644 --- a/src/activity-log/src/Support/ActivityLogger.php +++ b/src/activity-log/src/Support/ActivityLogger.php @@ -296,14 +296,18 @@ protected function getActivity(): ActivityContract&Model */ protected function useDefaultCauserIfNoneWasGiven(): void { - if ($this->causerResolved || $this->getActivity()->getAttribute('causer_id') !== null) { + if ($this->causerResolved) { return; } - $causer = $this->causerResolver->resolve(); + $activity = $this->getActivity(); + + if ($activity->getAttribute('causer_id') === null) { + $causer = $this->causerResolver->resolve(); - if ($causer !== null) { - $this->getActivity()->causer()->associate($causer); + if ($causer !== null) { + $activity->causer()->associate($causer); + } } $this->causerResolved = true; diff --git a/src/activity-log/src/Support/CauserResolver.php b/src/activity-log/src/Support/CauserResolver.php index 623d3401b..79a4f844e 100644 --- a/src/activity-log/src/Support/CauserResolver.php +++ b/src/activity-log/src/Support/CauserResolver.php @@ -168,12 +168,12 @@ public function withCauser(Model|int|string|null $causer, Closure $callback): mi /** * Determine whether a resolver result can identify a causer. */ - protected function isResolvable(mixed $causer): bool + protected function isResolvable(mixed $model): bool { - return $causer instanceof Model - || is_int($causer) - || is_string($causer) - || $causer === null; + return $model instanceof Model + || is_int($model) + || is_string($model) + || $model === null; } /** diff --git a/tests/ActivityLog/ActivityLogManagerTest.php b/tests/ActivityLog/ActivityLogManagerTest.php index 16f1e80a1..cc3817a4c 100644 --- a/tests/ActivityLog/ActivityLogManagerTest.php +++ b/tests/ActivityLog/ActivityLogManagerTest.php @@ -4,7 +4,6 @@ namespace Hypervel\Tests\ActivityLog; -use Hypervel\ActivityLog\Actions\LogActivityAction; use Hypervel\ActivityLog\ActivityLogManager; use Hypervel\ActivityLog\Exceptions\CouldNotLogActivity; use Hypervel\ActivityLog\Facades\ActivityLog; @@ -18,7 +17,6 @@ use JMac\Testing\Double; use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JMac\Testing\Matching\Argument; -use RuntimeException; class ActivityLogManagerTest extends TestCase { @@ -76,74 +74,6 @@ function (string $marker): ActivityLogger { $this->assertFalse(ActivityLog::hasMacro('marked')); } - public function testBootRegistrarsDoNotResolveScopedServicesOrLoggers(): void - { - $this->app->bind( - ActivityLogger::class, - static fn (): never => throw new RuntimeException('logger resolved'), - ); - $this->app->scoped( - CauserResolver::class, - static fn (): never => throw new RuntimeException('resolver resolved'), - ); - - ActivityLog::macro('registered_only', static fn (): null => null); - ActivityLog::beforeLogging(static function (): void { - }); - - $this->assertTrue(ActivityLog::hasMacro('registered_only')); - } - - public function testDefaultCauserIsVisibleToEveryLoggingHook(): void - { - $causer = User::query()->firstOrFail(); - $subject = new class extends Article { - /** - * Modify the activity before it is logged. - */ - public function beforeActivityLogged(Activity $activity, string $eventName): void - { - $activity->setAttribute( - 'properties', - $activity->properties->put( - 'subject_hook_causer', - $activity->causer?->getKey(), - ), - ); - } - }; - $this->app->make(CauserResolver::class)->setCauser($causer); - LogActivityAction::beforeLogging(function (Activity $activity): void { - $activity->setAttribute( - 'properties', - $activity->properties->put( - 'global_callback_causer', - $activity->causer?->getKey(), - ), - ); - }); - - activity() - ->performedOn($subject) - ->tap(function (Activity $activity): void { - $activity->setAttribute( - 'properties', - $activity->properties->put( - 'tap_causer', - $activity->causer?->getKey(), - ), - ); - }) - ->log('Causer :causer.name'); - - $activity = Activity::query()->firstOrFail(); - - $this->assertSame('Causer name 1', $activity->description); - $this->assertSame($causer->getKey(), $activity->getProperty('tap_causer')); - $this->assertSame($causer->getKey(), $activity->getProperty('subject_hook_causer')); - $this->assertSame($causer->getKey(), $activity->getProperty('global_callback_causer')); - } - public function testAnonymousCauserDissociatesAnAlreadyResolvedDefault(): void { $causer = User::query()->firstOrFail(); diff --git a/tests/ActivityLog/Models/User.php b/tests/ActivityLog/Models/User.php index 33f3c49ae..29e71e950 100644 --- a/tests/ActivityLog/Models/User.php +++ b/tests/ActivityLog/Models/User.php @@ -49,7 +49,7 @@ public function getAuthPasswordName(): string */ public function getAuthPassword(): ?string { - return $this->getAttribute('password'); + return $this->getAttribute($this->getAuthPasswordName()); } /** diff --git a/tests/ActivityLog/Support/ActivityLoggerTest.php b/tests/ActivityLog/Support/ActivityLoggerTest.php index 62f0cd067..3b81fe697 100644 --- a/tests/ActivityLog/Support/ActivityLoggerTest.php +++ b/tests/ActivityLog/Support/ActivityLoggerTest.php @@ -11,6 +11,7 @@ use Hypervel\ActivityLog\Facades\ActivityLog as ActivityFacade; use Hypervel\ActivityLog\Models\Activity; use Hypervel\ActivityLog\Models\Concerns\LogsActivity; +use Hypervel\ActivityLog\Support\ActivityLogger; use Hypervel\ActivityLog\Support\CauserResolver; use Hypervel\ActivityLog\Support\LogOptions; use Hypervel\Database\Eloquent\JsonEncodingException; @@ -26,6 +27,7 @@ use Hypervel\Tests\ActivityLog\Models\User; use Hypervel\Tests\ActivityLog\TestCase; use InvalidArgumentException; +use RuntimeException; use stdClass; class ActivityLoggerTest extends TestCase @@ -174,7 +176,7 @@ public function testCanLogAnActivityWithACauserOtherThanUserModel(): void $this->assertSame($article->getKey(), $activity->causer?->getKey()); } - public function testCanLogAnActivityWithACauserSetFromAnotherContext(): void + public function testCanLogAnActivityWithACauserThatHasBeenSetFromOtherContext(): void { $causer = Article::query()->firstOrFail(); $this->app->make(CauserResolver::class)->setCauser($causer); @@ -215,12 +217,27 @@ public function testPreassignedCauserAndArrayPropertiesOnACustomActivity(): void $this->assertSame(1, $activity->causer_id); $this->assertSame('value', $activity->getProperty('key.nested')); + + $anonymous = activity()->tap(static fn (Activity $activity) => $activity->causer()->dissociate())->log('anonymous'); + $this->assertNull($anonymous->fresh()->causer_id); } - public function testBackedEnumLogNamesWorkAcrossLoggerOptionsAndQueryScopes(): void + public function testCanUseAStringBackedEnumAsLogName(): void { activity(StringBackedEnum::Published)->log('published'); - activity()->inLog(IntBackedEnum::Draft)->log('draft'); + + $this->assertSame('published', $this->lastActivity()->log_name); + } + + public function testCanUseAnIntBackedEnumAsLogName(): void + { + activity()->useLog(IntBackedEnum::Draft)->log('draft'); + + $this->assertSame('0', $this->lastActivity()->log_name); + } + + public function testCanUseABackedEnumAsLogNameInTheLogOptions(): void + { $article = new class extends Article { use LogsActivity; @@ -232,9 +249,25 @@ public function getActivityLogOptions(): LogOptions $article->name = 'example'; $article->save(); - $this->assertSame('0', Activity::inLog(IntBackedEnum::Draft)->sole()->log_name); + $this->assertSame('draft', $this->lastActivity()->log_name); + } + + public function testCanQueryByLogNameUsingABackedEnum(): void + { + activity(StringBackedEnum::Published)->log('published'); + activity()->inLog(IntBackedEnum::Draft)->log('draft'); + + $this->assertSame('draft', Activity::inLog(IntBackedEnum::Draft)->sole()->description); + } + + public function testCanQueryByLogNameUsingMultipleBackedEnums(): void + { + activity(StringBackedEnum::Published)->log('published'); + activity()->inLog(IntBackedEnum::Draft)->log('draft'); + activity('other')->log('other'); + $this->assertSame(['published', '0'], Activity::inLog(StringBackedEnum::Published, IntBackedEnum::Draft)->orderBy('id')->pluck('log_name')->all()); - $this->assertSame(['published', 'draft'], Activity::inLog([StringBackedEnum::Published, 'draft'])->orderBy('id')->pluck('log_name')->all()); + $this->assertSame(['published', 'other'], Activity::inLog([StringBackedEnum::Published, 'other'])->orderBy('id')->pluck('log_name')->all()); } public function testCanLogActivityWithProperties(): void @@ -313,17 +346,139 @@ public function testWillUseTheLoggedInUserAsTheCauserByDefault(): void $this->assertSame($user->getKey(), $activity->causer?->getKey()); } + public function testResolvesTheDefaultCauserWhenTheActivityIsLoggedNotWhenTheLoggerIsBuilt(): void + { + $logger = activity(); + Auth::login(User::query()->findOrFail(1)); + $logger->log('late login'); + + $this->assertInstanceOf(User::class, $this->lastActivity()->causer); + $this->assertSame(1, $this->lastActivity()->causer_id); + } + + public function testDoesNotResolveTheCauserWhenTheFacadeIsResolved(): void + { + $this->app->bind( + ActivityLogger::class, + static fn (): never => throw new RuntimeException('logger resolved'), + ); + $this->app->scoped( + CauserResolver::class, + static fn (): never => throw new RuntimeException('resolver resolved'), + ); + + ActivityFacade::macro('registered_only', static fn (): null => null); + ActivityFacade::beforeLogging(static function (): void { + }); + + $this->assertTrue(ActivityFacade::hasMacro('registered_only')); + } + + public function testPreservesAnExplicitlyResolvedAnonymousCauser(): void + { + $default = User::query()->findOrFail(1); + $this->app->make(CauserResolver::class)->resolveUsing(static fn ($subject) => $subject?->getKey() === 2 ? null : $default); + + activity()->causedBy(User::query()->findOrFail(2))->log('anonymous'); + + $this->assertNull($this->lastActivity()->causer_id); + $this->assertNull($this->lastActivity()->causer_type); + } + + public function testPreservesAnExplicitCauserWithoutAPrimaryKey(): void + { + Auth::login(User::query()->findOrFail(1)); + $causer = new User; + + $activity = activity()->causedBy($causer)->log('unsaved causer'); + + $this->assertSame($causer, $activity->causer); + $this->assertNull($activity->causer_id); + } + + public function testResolvesAFreshDefaultCauserWhenReusingALoggerAfterAnonymousLogging(): void + { + $logger = activity()->causedByAnonymous(); + Auth::login(User::query()->findOrFail(1)); + $this->assertNull($logger->log('anonymous')->causer_id); + + Auth::login(User::query()->findOrFail(2)); + $this->assertSame(2, $logger->log('authenticated')->causer_id); + } + + public function testPreservesACauserAssociatedThroughTap(): void + { + Auth::login(User::query()->findOrFail(1)); + activity()->tap(static fn (Activity $activity) => $activity->causer()->associate(User::query()->findOrFail(2)))->log('explicit'); + $this->assertSame(2, $this->lastActivity()->causer_id); + } + + public function testMakesTheDefaultCauserAvailableToTapAndPreservesItsChanges(): void + { + Auth::login(User::query()->findOrFail(1)); + activity()->tap(static function (Activity $activity): void { + $activity->properties = collect(['name' => $activity->causer->name]); + $activity->causer()->dissociate(); + })->log('anonymous'); + + $activity = $this->lastActivity(); + $this->assertSame('name 1', $activity->getProperty('name')); + $this->assertNull($activity->causer_id); + $this->assertNull($activity->causer_type); + } + + public function testMakesTheDefaultCauserAvailableToDescriptionPlaceholdersAndBeforeLoggingCallbacks(): void + { + $causer = User::query()->firstOrFail(); + $subject = new class extends Article { + /** + * Modify the activity before it is logged. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + $activity->setAttribute( + 'properties', + $activity->properties->put( + 'subject_hook_causer', + $activity->causer?->getKey(), + ), + ); + } + }; + $logger = activity(); + Auth::login($causer); + LogActivityAction::beforeLogging(function (Activity $activity): void { + $activity->setAttribute( + 'properties', + $activity->properties->put( + 'global_callback_causer', + $activity->causer?->getKey(), + ), + ); + }); + + $logger->performedOn($subject)->log('Causer :causer.name'); + + $activity = Activity::query()->firstOrFail(); + + $this->assertSame('Causer name 1', $activity->description); + $this->assertSame($causer->getKey(), $activity->getProperty('subject_hook_causer')); + $this->assertSame($causer->getKey(), $activity->getProperty('global_callback_causer')); + } + public function testCanLogActivityUsingAnAnonymousCauser(): void { - activity() + $activity = activity() + ->causedBy(User::query()->findOrFail(1)) ->causedByAnonymous() ->log('hello poetsvrouwman'); + $this->assertNull($activity->causer); $this->assertNull($this->lastActivity()->causer_id); $this->assertNull($this->lastActivity()->causer_type); } - public function testAnonymousCauserOverridesTheLoggedInUser(): void + public function testWillOverrideTheLoggedInUserAsTheCauserWhenAnAnonymousCauserIsSpecified(): void { Auth::login(User::query()->findOrFail(1)); @@ -352,7 +507,7 @@ public function testCanReplaceThePlaceholders(): void ); } - public function testCanReplacePlaceholdersWithObjectPropertiesAndAccessors(): void + public function testCanReplaceThePlaceholdersWithObjectPropertiesAndAccessors(): void { $article = Article::create([ 'name' => 'article name', @@ -395,7 +550,7 @@ public function testWillNotReplaceNonPlaceholders(): void $this->assertSame($description, $this->lastActivity()->description); } - public function testReturnsTheConfiguredCustomActivityModelAfterLogging(): void + public function testReturnsAnInstanceOfTheActivityLogAfterLoggingWhenUsingACustomModel(): void { $activityModel = new class extends Activity { }; @@ -566,7 +721,7 @@ public function testWillDisableLogsForACallbackWithoutAffectingPreviousState(): $this->assertSame('outer', $this->lastActivity()->description); } - public function testWillDisableLogsForACallbackWithoutAffectingDisabledState(): void + public function testWillDisableLogsForACallbackWithoutAffectingPreviousStateEvenWhenAlreadyDisabled(): void { activity()->disableLogging(); @@ -582,7 +737,7 @@ public function testWillDisableLogsForACallbackWithoutAffectingDisabledState(): $this->assertNull($this->getLastActivity()); } - public function testWillRestoreDisabledStateWhenTheCallbackThrows(): void + public function testWillDisableLogsForACallbackWithoutAffectingPreviousStateEvenWithException(): void { activity()->disableLogging(); diff --git a/tests/ActivityLog/Support/CauserResolverTest.php b/tests/ActivityLog/Support/CauserResolverTest.php index d3d30347a..345155e15 100644 --- a/tests/ActivityLog/Support/CauserResolverTest.php +++ b/tests/ActivityLog/Support/CauserResolverTest.php @@ -144,7 +144,7 @@ public function testRestoresThePreviousCauserAfterWithCauser(): void $this->assertSame($first->getKey(), $resolver->resolve()?->getKey()); } - public function testRestoresThePreviousCauserWhenWithCauserThrows(): void + public function testRestoresThePreviousCauserAfterWithCauserEvenWhenAnExceptionIsThrown(): void { $first = User::query()->firstOrFail(); $second = User::query()->findOrFail(2); From 53ae336e96a75b3cf4a8f2d4ee0269c85c25abe2 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:51:17 +0000 Subject: [PATCH 2/5] Reconcile activity transaction and buffer coverage Group savepoint, ordering, rollback and connection cases in the upstream transaction test class. Exercise immediate and buffered writes, verify that model events actually stage an activity before rollback, and retain the callback-order assertions for work promoted by nested commits. Cover optional insert columns, database defaults and models with renamed, missing, disabled or explicitly null timestamps. Document why the activity connection owns each buffered write and why a failed insert must not put an attempted batch back into the buffer. Compared with spatie/laravel-activitylog at 741ce06abfb91a96d2ee056706a6564ae8a3a71f. --- .../src/Actions/LogActivityAction.php | 3 + .../src/Support/ActivityBuffer.php | 6 +- .../Models/ActivityWithoutUpdatedAt.php | 12 + .../Support/ActivityBufferTest.php | 226 ++++------- .../Support/ActivityTransactionsTest.php | 368 ++++++++++++++++++ 5 files changed, 465 insertions(+), 150 deletions(-) create mode 100644 tests/ActivityLog/Models/ActivityWithoutUpdatedAt.php create mode 100644 tests/ActivityLog/Support/ActivityTransactionsTest.php diff --git a/src/activity-log/src/Actions/LogActivityAction.php b/src/activity-log/src/Actions/LogActivityAction.php index f7cb70669..15801f0e4 100644 --- a/src/activity-log/src/Actions/LogActivityAction.php +++ b/src/activity-log/src/Actions/LogActivityAction.php @@ -116,6 +116,9 @@ protected function beforeActivityLogged(ActivityContract&Model $activity): void */ protected function save(ActivityContract&Model $activity): void { + // REMOVED: Spatie defers to the subject's transaction across connections. + // Only the activity connection owns this write. Atomic audits share the + // subject's transaction; durable delivery to another database needs an outbox. if ($this->shouldBuffer()) { $this->container->make(ActivityBuffer::class)->add($activity); diff --git a/src/activity-log/src/Support/ActivityBuffer.php b/src/activity-log/src/Support/ActivityBuffer.php index 44e047fc6..efabbbc3e 100644 --- a/src/activity-log/src/Support/ActivityBuffer.php +++ b/src/activity-log/src/Support/ActivityBuffer.php @@ -210,8 +210,8 @@ protected function flushBatch(): void $firstStaged = array_key_first($this->staged); $records = []; - // Claim before writing: transaction callbacks and events may re-enter - // the buffer, and must never observe or insert this in-flight batch. + // Claim the batch before writing so reentrant callbacks cannot insert it again. + // Keep it removed on failure: if the commit outcome is unknown, a retry can duplicate rows. foreach (array_slice($this->pending, 0, $this->batchSize(), preserve_keys: true) as $sequence => $record) { if ($firstStaged !== null && $sequence >= $firstStaged) { break; @@ -363,6 +363,8 @@ protected function batchSize(): int /** * Ensure the activity still targets the configured connection and table. + * + * All rows in this buffer share an insert target and its transaction callbacks. */ protected function ensurePersistenceTargetWasNotChanged(ActivityContract&Model $activity): void { diff --git a/tests/ActivityLog/Models/ActivityWithoutUpdatedAt.php b/tests/ActivityLog/Models/ActivityWithoutUpdatedAt.php new file mode 100644 index 000000000..6f49b8e40 --- /dev/null +++ b/tests/ActivityLog/Models/ActivityWithoutUpdatedAt.php @@ -0,0 +1,12 @@ +assertSame(0, Activity::query()->count()); } - public function testTransactionRowsRemainStagedUntilTheOuterCommit(): void - { - $connection = $this->activityConnection(); - $connection->beginTransaction(); - - try { - activity()->log('staged activity'); - - $this->assertSame(0, Activity::query()->count()); - $this->assertSame(1, $this->buffer()->count()); - $this->assertFalse($this->buffer()->canFlush()); - } finally { - $connection->commit(); - } - - $this->assertSame(1, $this->buffer()->count()); - $this->assertTrue($this->buffer()->canFlush()); - - $this->buffer()->flush(); - - $this->assertSame(['staged activity'], Activity::query()->pluck('description')->all()); - } - - public function testNestedRollbackDiscardsOnlyTheSavepointRows(): void - { - $connection = $this->activityConnection(); - $connection->beginTransaction(); - - try { - activity()->log('outer activity'); - $connection->beginTransaction(); - activity()->log('savepoint activity'); - $connection->rollBack(); - - $this->assertSame(1, $connection->transactionLevel()); - $this->assertSame(1, $this->buffer()->count()); - } finally { - $connection->commit(); - } - - $this->buffer()->flush(); - - $this->assertSame(['outer activity'], Activity::query()->pluck('description')->all()); - } - - public function testForeignCommitCannotPromoteAnActivityTransactionRow(): void - { - $activityConnection = $this->activityConnection(); - $foreignConnection = $this->foreignConnection(); - $activityConnection->beginTransaction(); - - try { - activity()->log('rolled back activity'); - $foreignConnection->beginTransaction(); - $foreignConnection->commit(); - - $this->assertSame(1, $this->buffer()->count()); - } finally { - $activityConnection->rollBack(); - } - - $this->buffer()->flush(); - - $this->assertSame(0, Activity::query()->count()); - $this->assertSame(0, $this->buffer()->count()); - } - public function testForeignRollbackCannotDiscardAnActivityTransactionRow(): void { $activityConnection = $this->activityConnection(); @@ -434,40 +368,6 @@ public function testTransactionOnOnlyAnotherConnectionDoesNotStageTheRow(): void } } - public function testSequenceOrderSurvivesNestedTransactionResolution(): void - { - activity()->log('before transaction'); - $connection = $this->activityConnection(); - $connection->beginTransaction(); - - try { - activity()->log('outer before savepoint'); - $connection->beginTransaction(); - activity()->log('inside savepoint'); - $connection->afterCommit(function (): void { - $this->assertTrue($this->buffer()->canFlush()); - $this->buffer()->flush(); - $this->assertSame(['before transaction'], Activity::query()->pluck('description')->all()); - $this->assertFalse($this->buffer()->canFlush()); - }); - $connection->commit(); - activity()->log('outer after savepoint'); - } finally { - $connection->commit(); - } - - activity()->log('after transaction'); - $this->buffer()->flush(); - - $this->assertSame([ - 'before transaction', - 'outer before savepoint', - 'inside savepoint', - 'outer after savepoint', - 'after transaction', - ], Activity::query()->orderBy('id')->pluck('description')->all()); - } - public function testThresholdWaitsForEveryStagedOutcome(): void { config()->set('activity-log.buffer.batch_size', 2); @@ -646,7 +546,22 @@ public function testThresholdAndRemainderUseBoundedInsertStatements(): void $this->assertSame(0, $this->buffer()->count()); } - public function testAdjacentColumnShapesPreserveInsertionOrderAndDatabaseDefaults(): void + public function testFlushesActivitiesWithDifferentOptionalAttributes(): void + { + activity()->event('created')->log('first'); + activity()->log('second'); + activity()->event('updated')->log('third'); + + $this->buffer()->flush(); + + $this->assertSame([ + ['description' => 'first', 'event' => 'created'], + ['description' => 'second', 'event' => null], + ['description' => 'third', 'event' => 'updated'], + ], Activity::query()->orderBy('id')->get()->map->only(['description', 'event'])->all()); + } + + public function testPreservesDatabaseDefaultsForOmittedAttributes(): void { Schema::table('activity_log', static function (Blueprint $table): void { $table->string('extra')->default('database default'); @@ -691,34 +606,76 @@ public function testAdjacentColumnShapesPreserveInsertionOrderAndDatabaseDefault ], $rows->map(static fn (object $row): array => (array) $row)->all()); } - public function testModelsWithoutTimestampsDoNotGainBufferTimestamps(): void + public function testFlushesAnActivityModelThatHasNoUpdatedAtColumn(): void { - config()->set('activity-log.activity_model', ActivityLogWithoutTimestamps::class); + Schema::table('activity_log', static fn (Blueprint $table) => $table->dropColumn('updated_at')); + config()->set('activity-log.activity_model', ActivityWithoutUpdatedAt::class); + $time = $this->freezeTime(); - activity()->log('without timestamps'); + activity()->log('buffered'); $this->buffer()->flush(); - $row = Activity::query()->toBase()->first(); - $this->assertNotNull($row); - $this->assertNull($row->created_at); - $this->assertNull($row->updated_at); + $row = ActivityWithoutUpdatedAt::query()->sole(); + $this->assertSame('buffered', $row->description); + $this->assertSame($time->toDateTimeString(), $row->created_at->toDateTimeString()); } - public function testRenamedAndDisabledTimestampColumnsMatchImmediatePersistence(): void + public function testFlushesRenamedTimestampColumnsAndPreservesSuppliedTimestamps(): void { Schema::table('activity_log', static function (Blueprint $table): void { - $table->timestamp('logged_at')->nullable(); + $table->renameColumn('created_at', 'logged_at'); + $table->renameColumn('updated_at', 'modified_at'); }); - config()->set('activity-log.activity_model', ActivityLogCreatedAtOnly::class); + config()->set('activity-log.activity_model', ActivityLogRenamedTimestamps::class); + $time = $this->freezeTime(); + $createdAt = $time->subDays(5); + $updatedAt = $time->subDays(2); + + activity()->log('automatic'); + activity()->tap(static function (Activity $activity) use ($createdAt, $updatedAt): void { + $activity->setCreatedAt($createdAt); + $activity->setUpdatedAt($updatedAt); + })->log('supplied'); + $this->assertSame(0, Activity::query()->count()); - activity()->log('custom timestamps'); + $this->travel(1)->hour(); $this->buffer()->flush(); - $row = Activity::query()->toBase()->first(); - $this->assertNotNull($row); - $this->assertNotNull($row->logged_at); - $this->assertNull($row->created_at); - $this->assertNull($row->updated_at); + $this->assertSame([ + ['description' => 'automatic', 'logged_at' => $time->toDateTimeString(), 'modified_at' => $time->toDateTimeString()], + ['description' => 'supplied', 'logged_at' => $createdAt->toDateTimeString(), 'modified_at' => $updatedAt->toDateTimeString()], + ], ActivityLogRenamedTimestamps::query()->orderBy('id')->get(['description', 'logged_at', 'modified_at'])->map->getAttributes()->all()); + } + + public function testFlushesAnActivityModelWithTimestampsDisabledAndNoTimestampColumns(): void + { + config()->set('activity-log.activity_model', ActivityLogWithoutTimestamps::class); + Schema::table('activity_log', static function (Blueprint $table): void { + $table->dropIndex('activity_log_created_at_id_index'); + $table->dropIndex('activity_log_name_created_at_id_index'); + $table->dropTimestamps(); + }); + activity()->log('without timestamps'); + $this->assertSame(0, Activity::query()->count()); + + $this->buffer()->flush(); + $this->assertSame(['without timestamps'], Activity::query()->pluck('description')->all()); + $this->assertFalse($this->buffer()->hasPending()); + } + + public function testPreservesExplicitlyNullTimestampsWhenFlushing(): void + { + activity()->tap(static function (Activity $activity): void { + $activity->setCreatedAt(null); + $activity->setUpdatedAt(null); + })->log('null timestamps'); + $this->buffer()->flush(); + + $this->assertSame([ + 'description' => 'null timestamps', + 'created_at' => null, + 'updated_at' => null, + ], Activity::query()->sole()->only(['description', 'created_at', 'updated_at'])); } public function testFlushWritesToTheConnectionSelectedWhenBuffering(): void @@ -774,6 +731,7 @@ public function testChangingTheBufferedPersistenceTargetIsRejected(): void $this->assertSame(0, Activity::query()->count()); } + // REMOVED: Keeping the whole batch pending would let a later lifecycle flush retry an ambiguous write. public function testFailedInsertDiscardsTheAttemptedBatchAndPreservesLaterRows(): void { config()->set('activity-log.buffer.batch_size', 1); @@ -946,34 +904,6 @@ public function testThresholdReentryCannotReselectTheClaimedBatch(): void $this->assertSame(0, $this->buffer()->count()); } - public function testFailedPostCommitFlushLeavesDomainWorkCommitted(): void - { - $connection = $this->activityConnection(); - $connection->transaction(static function (): void { - Article::query()->create(['name' => 'committed domain row']); - activity()->log('post-commit failure'); - }); - $connection->statement(<<<'SQL' - CREATE TRIGGER fail_post_commit_activity - BEFORE INSERT ON activity_log - WHEN NEW.description = 'post-commit failure' - BEGIN - SELECT RAISE(FAIL, 'post-commit activity failed'); - END - SQL); - - try { - ActivityBuffer::finalizeCurrent(); - $this->fail('Expected the post-commit activity insert to fail.'); - } catch (QueryException $exception) { - $this->assertStringContainsString('post-commit activity failed', $exception->getMessage()); - } - - $this->assertSame(1, Article::query()->where('name', 'committed domain row')->count()); - $this->assertSame(0, Activity::query()->count()); - $this->assertSame(0, $this->buffer()->count()); - } - /** * Get the current scoped activity buffer. */ @@ -1004,11 +934,11 @@ class ActivityLogWithoutTimestamps extends Activity public bool $timestamps = false; } -class ActivityLogCreatedAtOnly extends Activity +class ActivityLogRenamedTimestamps extends Activity { public const ?string CREATED_AT = 'logged_at'; - public const ?string UPDATED_AT = null; + public const ?string UPDATED_AT = 'modified_at'; } class UuidActivityLog extends Activity diff --git a/tests/ActivityLog/Support/ActivityTransactionsTest.php b/tests/ActivityLog/Support/ActivityTransactionsTest.php new file mode 100644 index 000000000..950e63fee --- /dev/null +++ b/tests/ActivityLog/Support/ActivityTransactionsTest.php @@ -0,0 +1,368 @@ +set('activity-log.buffer.enabled', true); + DB::beginTransaction(); + $article = Article::create(['name' => 'rolled back']); + activity()->performedOn($article)->log('created'); + DB::rollBack(); + + ActivityBuffer::finalizeCurrent(); + $this->assertNull($article->fresh()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testBufferedActivityBecomesEligibleToFlushAfterTheOutermostActivityTransactionCommits(): void + { + config()->set('activity-log.buffer.enabled', true); + DB::beginTransaction(); + DB::beginTransaction(); + $article = Article::create(['name' => 'committed']); + $activity = activity()->performedOn($article)->log('created'); + DB::commit(); + + $buffer = $this->app->make(ActivityBuffer::class); + $this->assertSame(0, Activity::query()->count()); + $this->assertFalse($activity->exists); + $this->assertNull($activity->getKey()); + $this->assertSame(1, $buffer->count()); + $this->assertFalse($buffer->canFlush()); + + DB::commit(); + $this->assertSame(1, $buffer->count()); + $this->assertTrue($buffer->canFlush()); + $buffer->flush(); + + $saved = Activity::query()->sole(); + $this->assertSame('created', $saved->description); + $this->assertSame($article->getKey(), $saved->subject_id); + $this->assertSame('committed', $article->fresh()->name); + } + + public function testDiscardsACommittedSavepointWhenItsOuterTransactionRollsBack(): void + { + config()->set('activity-log.buffer.enabled', true); + DB::beginTransaction(); + DB::beginTransaction(); + $article = Article::create(['name' => 'rolled back']); + activity()->performedOn($article)->log('created'); + DB::commit(); + DB::rollBack(); + + ActivityBuffer::finalizeCurrent(); + $this->assertNull($article->fresh()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testDiscardsARolledBackSavepointWithoutDiscardingTheOuterActivity(): void + { + config()->set('activity-log.buffer.enabled', true); + $article = Article::query()->firstOrFail(); + DB::beginTransaction(); + $article->update(['name' => 'outer']); + activity()->performedOn($article)->log('outer'); + DB::beginTransaction(); + $article->update(['name' => 'inner']); + activity()->performedOn($article)->log('inner'); + DB::rollBack(); + + $this->assertSame(1, DB::transactionLevel()); + $this->assertSame(1, $this->app->make(ActivityBuffer::class)->count()); + DB::commit(); + ActivityBuffer::finalizeCurrent(); + + $this->assertSame('outer', $article->fresh()->name); + $this->assertSame('outer', Activity::query()->sole()->description); + } + + public function testDiscardsCommittedDescendantsOfARolledBackSavepoint(): void + { + config()->set('activity-log.buffer.enabled', true); + $article = Article::query()->firstOrFail(); + DB::beginTransaction(); + activity()->performedOn($article)->log('outer'); + DB::beginTransaction(); + DB::beginTransaction(); + activity()->performedOn($article)->log('inner'); + DB::commit(); + DB::rollBack(); + DB::commit(); + + ActivityBuffer::finalizeCurrent(); + $this->assertSame('outer', Activity::query()->sole()->description); + } + + public function testWaitsForTheActivityConnectionWhenAnotherConnectionCommitsFirst(): void + { + config()->set('activity-log.buffer.enabled', true); + $subject = Article::query()->firstOrFail(); + DB::beginTransaction(); + $other = DB::connection('custom_connection_name'); + $other->beginTransaction(); + activity()->performedOn($subject)->log('rolled back'); + $other->commit(); + + $buffer = $this->app->make(ActivityBuffer::class); + $this->assertSame(1, $buffer->count()); + $this->assertFalse($buffer->canFlush()); + DB::rollBack(); + $buffer->flush(); + $this->assertSame(0, $buffer->count()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testCanFlushAfterTheActivityConnectionCommitsWhileAnUnrelatedTransactionRemainsOpen(): void + { + config()->set('activity-log.buffer.enabled', true); + $subject = Article::query()->firstOrFail(); + DB::beginTransaction(); + $other = DB::connection('custom_connection_name'); + $other->beginTransaction(); + activity()->performedOn($subject)->log('committed'); + DB::commit(); + ActivityBuffer::finalizeCurrent(); + + $this->assertSame('committed', Activity::query()->sole()->description); + $other->rollBack(); + $this->assertSame(1, Activity::query()->count()); + } + + public function testUsesTheActivityConnectionWhenItIsNotTheDefaultConnection(): void + { + DB::usingConnection('custom_connection_name', fn () => $this->setUpDatabase()); + config()->set([ + 'activity-log.activity_model' => CustomDatabaseConnectionOnActivityModel::class, + 'activity-log.buffer.enabled' => true, + ]); + $article = Article::on('custom_connection_name')->firstOrFail(); + $connection = $article->getConnection(); + $connection->beginTransaction(); + $article->update(['name' => 'rolled back']); + activity()->performedOn($article)->log('updated'); + $connection->rollBack(); + + ActivityBuffer::finalizeCurrent(); + $this->assertNotSame('rolled back', $article->fresh()->name); + $this->assertSame(0, CustomDatabaseConnectionOnActivityModel::query()->count()); + } + + public function testKeepsUnbufferedActivitiesOnTheSameConnectionInsideTheSubjectTransaction(): void + { + DB::beginTransaction(); + $article = Article::create(['name' => 'rolled back']); + $activity = activity()->performedOn($article)->log('created'); + $this->assertTrue($activity->exists); + $this->assertSame(1, Activity::query()->count()); + DB::rollBack(); + + $this->assertNull($article->fresh()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testSavesImmediatelyWhenTheSubjectIsNotInATransaction(): void + { + $activity = activity()->performedOn(Article::query()->firstOrFail())->log('immediate'); + + $this->assertTrue($activity->exists); + $this->assertSame($activity->getKey(), Activity::query()->sole()->getKey()); + } + + // REMOVED: Spatie defers cross-connection writes until the subject commits. + // A subject transaction does not own Hypervel's activity connection or its savepoints. + #[TestWith([false])] + #[TestWith([true])] + public function testSeparateActivityConnectionIsIndependentOfTheSubjectTransaction(bool $buffered): void + { + DB::usingConnection('custom_connection_name', fn () => $this->migrateActivityLogTable()); + config()->set([ + 'activity-log.activity_model' => CustomDatabaseConnectionOnActivityModel::class, + 'activity-log.buffer.enabled' => $buffered, + ]); + + DB::beginTransaction(); + $article = Article::create(['name' => 'rolled back']); + activity()->performedOn($article)->log('with subject'); + ActivityBuffer::finalizeCurrent(); + DB::rollBack(); + + $this->assertNull($article->fresh()); + $this->assertSame('with subject', CustomDatabaseConnectionOnActivityModel::query()->sole()->description); + } + + public function testDoesNotInferASubjectTransactionForActivitiesWithoutASubject(): void + { + DB::usingConnection('custom_connection_name', fn () => $this->migrateActivityLogTable()); + config()->set('activity-log.activity_model', CustomDatabaseConnectionOnActivityModel::class); + DB::beginTransaction(); + $activity = activity()->log('attempted operation'); + DB::rollBack(); + + $this->assertTrue($activity->exists); + $this->assertSame('attempted operation', CustomDatabaseConnectionOnActivityModel::query()->sole()->description); + } + + #[TestWith([false])] + #[TestWith([true])] + public function testCapturesAttributesAndTimestampsAfterHooksRunInsteadOfAtCommitTime(bool $buffered): void + { + config()->set('activity-log.buffer.enabled', $buffered); + $now = $this->freezeTime(); + $calls = 0; + LogActivityAction::beforeLogging(static function (Activity $activity) use (&$calls): void { + ++$calls; + $activity->properties = $activity->properties->put('source', 'request'); + }); + DB::beginTransaction(); + $activity = activity()->performedOn(Article::query()->firstOrFail()) + ->withChanges(['attributes' => ['name' => 'original']])->log('original'); + $activity->description = 'mutated'; + $activity->properties = $activity->properties->put('source', 'mutated'); + $activity->attribute_changes = ['attributes' => ['name' => 'mutated']]; + $this->travel(1)->minute(); + DB::commit(); + ActivityBuffer::finalizeCurrent(); + + $saved = Activity::query()->sole(); + $this->assertSame('original', $saved->description); + $this->assertSame(['source' => 'request'], $saved->properties->all()); + $this->assertSame(['attributes' => ['name' => 'original']], $saved->attribute_changes->all()); + $this->assertSame($now->toDateTimeString(), $saved->created_at->toDateTimeString()); + $this->assertSame(1, $calls); + } + + #[TestWith(['created'])] + #[TestWith(['updated'])] + #[TestWith(['deleted'])] + public function testDiscardsAutomaticModelEventLogsAfterRollback(string $event): void + { + config()->set('activity-log.buffer.enabled', true); + $article = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logAll(); + } + }; + $article->disableLogging(); + $article->name = 'original'; + $article->save(); + $article->enableLogging(); + DB::beginTransaction(); + match ($event) { + 'created' => $article->replicate()->save(), + 'updated' => $article->update(['name' => 'updated']), + 'deleted' => $article->delete(), + }; + $this->assertSame(1, $this->app->make(ActivityBuffer::class)->count()); + DB::rollBack(); + ActivityBuffer::finalizeCurrent(); + + $this->assertSame('original', Article::query()->findOrFail($article->getKey())->name); + $this->assertSame(0, Activity::query()->count()); + } + + #[TestWith([false])] + #[TestWith([true])] + public function testPreservesLoggingOrderAcrossCommittedAndRolledBackSavepoints(bool $buffered): void + { + config()->set('activity-log.buffer.enabled', $buffered); + $buffer = $this->app->make(ActivityBuffer::class); + $article = Article::query()->firstOrFail(); + activity()->log('before transaction'); + $connection = DB::connection(); + $connection->beginTransaction(); + + try { + activity()->performedOn($article)->log('outer before savepoint'); + $connection->beginTransaction(); + activity()->performedOn($article)->log('inside savepoint'); + if ($buffered) { + $connection->afterCommit(function () use ($buffer): void { + $this->assertTrue($buffer->canFlush()); + $buffer->flush(); + $this->assertSame(['before transaction'], Activity::query()->pluck('description')->all()); + $this->assertFalse($buffer->canFlush()); + }); + } + $connection->commit(); + $connection->beginTransaction(); + activity()->performedOn($article)->log('discarded'); + $connection->rollBack(); + activity()->performedOn($article)->log('outer after savepoint'); + } finally { + $connection->commit(); + } + + activity()->log('after transaction'); + $buffer->flush(); + + $this->assertSame([ + 'before transaction', + 'outer before savepoint', + 'inside savepoint', + 'outer after savepoint', + 'after transaction', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + } + + public function testLeavesTheSubjectCommittedIfSavingToTheActivityDatabaseFails(): void + { + config()->set('activity-log.buffer.enabled', true); + $connection = DB::connection(); + $connection->transaction(static function (): void { + $article = Article::query()->create(['name' => 'committed domain row']); + activity()->performedOn($article)->log('post-commit failure'); + }); + $connection->statement(<<<'SQL' + CREATE TRIGGER fail_post_commit_activity + BEFORE INSERT ON activity_log + WHEN NEW.description = 'post-commit failure' + BEGIN + SELECT RAISE(FAIL, 'post-commit activity failed'); + END + SQL); + + try { + ActivityBuffer::finalizeCurrent(); + $this->fail('Expected the post-commit activity insert to fail.'); + } catch (QueryException $exception) { + $this->assertStringContainsString('post-commit activity failed', $exception->getMessage()); + } + + $this->assertSame(1, Article::query()->where('name', 'committed domain row')->count()); + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(0, $this->app->make(ActivityBuffer::class)->count()); + } + + public function testRespectsActivitiesWithTimestampsDisabled(): void + { + DB::beginTransaction(); + $activity = activity()->performedOn(Article::query()->firstOrFail()) + ->tap(static fn (Activity $activity) => $activity->timestamps = false)->log('without timestamps'); + DB::commit(); + + $this->assertSame($activity->getKey(), Activity::query()->sole()->getKey()); + $this->assertNull($activity->created_at); + $this->assertNull($activity->updated_at); + } +} From 84bdb0db6f2cffb0bd431ecf5da89347d366f0fb Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:51:17 +0000 Subject: [PATCH 3/5] Align activity cleanup, model and trait tests with Spatie Restore retention boundary inputs, command exit codes and validation messages to the clean command tests. Check default and custom model connections and table names alongside the existing persistence assertions. Explain why cleanup filters the log column directly when the configured model implements only the activity storage contract. Use the upstream test descriptions for model logging and change detection. Verify related values at creation as well as after an update in the cases that promise creation coverage. Compared with spatie/laravel-activitylog at 741ce06abfb91a96d2ee056706a6564ae8a3a71f. --- .../src/Actions/CleanActivityLogAction.php | 1 + .../Commands/CleanActivityLogCommandTest.php | 16 ++++--- ...tomDatabaseConnectionActivityModelTest.php | 7 +++- .../Models/CustomTableNameModelTest.php | 5 ++- .../ActivityLog/Traits/DetectsChangesTest.php | 42 ++++++++++--------- tests/ActivityLog/Traits/LogsActivityTest.php | 10 ++--- 6 files changed, 50 insertions(+), 31 deletions(-) diff --git a/src/activity-log/src/Actions/CleanActivityLogAction.php b/src/activity-log/src/Actions/CleanActivityLogAction.php index 3d0f895d0..f46fac956 100644 --- a/src/activity-log/src/Actions/CleanActivityLogAction.php +++ b/src/activity-log/src/Actions/CleanActivityLogAction.php @@ -108,6 +108,7 @@ private function newEligibleQuery( ->where($createdAtColumn, '<', $cutOffDate); if ($logName !== null) { + // Custom activity models implement the storage contract and may have no inLog scope. $query->where('log_name', $logName); } diff --git a/tests/ActivityLog/Commands/CleanActivityLogCommandTest.php b/tests/ActivityLog/Commands/CleanActivityLogCommandTest.php index 659646200..2c25ed360 100644 --- a/tests/ActivityLog/Commands/CleanActivityLogCommandTest.php +++ b/tests/ActivityLog/Commands/CleanActivityLogCommandTest.php @@ -9,6 +9,7 @@ use Hypervel\Support\Facades\Artisan; use Hypervel\Tests\ActivityLog\TestCase; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; class CleanActivityLogCommandTest extends TestCase { @@ -46,7 +47,7 @@ public function testCanCleanTheActivityLog(): void $this->assertCount(60, Activity::all()); - Artisan::call('activity-log:clean'); + $this->assertSame(0, Artisan::call('activity-log:clean')); $this->assertCount(31, Activity::all()); @@ -55,7 +56,9 @@ public function testCanCleanTheActivityLog(): void $this->assertCount(0, Activity::where('created_at', '<', $cutOffDate)->get()); } - public function testCanAcceptDaysAsOptionToOverrideConfigSetting(): void + #[TestWith([1])] + #[TestWith([7])] + public function testCanAcceptDaysAsOptionToOverrideConfigSetting(int $days): void { foreach (range(1, 60) as $index) { Activity::create([ @@ -66,11 +69,11 @@ public function testCanAcceptDaysAsOptionToOverrideConfigSetting(): void $this->assertCount(60, Activity::all()); - Artisan::call('activity-log:clean', ['--days' => 7]); + $this->assertSame(0, Artisan::call('activity-log:clean', ['--days' => $days])); - $this->assertCount(7, Activity::all()); + $this->assertCount($days, Activity::all()); - $cutOffDate = CarbonImmutable::now()->subDays(7)->format('Y-m-d H:i:s'); + $cutOffDate = CarbonImmutable::now()->subDays($days)->format('Y-m-d H:i:s'); $this->assertCount(0, Activity::where('created_at', '<', $cutOffDate)->get()); } @@ -137,6 +140,7 @@ public function testDoesNotCleanTheActivityLogWhenDaysOptionValueIsInvalid(mixed $exitCode = Artisan::call('activity-log:clean', ['--days' => $days]); $this->assertSame(1, $exitCode); + $this->assertStringContainsString('The days option must be a positive integer.', Artisan::output()); $this->assertCount(60, Activity::all()); } @@ -152,6 +156,8 @@ public static function invalidDays(): array 'non-numeric string' => ['abc'], 'fraction' => ['7.5'], 'empty string' => [''], + 'zero' => [0], + 'negative' => [-1], ]; } } diff --git a/tests/ActivityLog/Models/CustomDatabaseConnectionActivityModelTest.php b/tests/ActivityLog/Models/CustomDatabaseConnectionActivityModelTest.php index ad1bccd0b..21958a27d 100644 --- a/tests/ActivityLog/Models/CustomDatabaseConnectionActivityModelTest.php +++ b/tests/ActivityLog/Models/CustomDatabaseConnectionActivityModelTest.php @@ -44,7 +44,12 @@ static function (): void { } } - public function testUsesTheCustomConnectionForImmediateWrites(): void + public function testUsesTheDefaultDatabaseConnection(): void + { + $this->assertSame(DB::connection('sqlite'), (new DefaultActivity)->getConnection()); + } + + public function testUsesTheDatabaseConnectionFromACustomModel(): void { config()->set( 'activity-log.activity_model', diff --git a/tests/ActivityLog/Models/CustomTableNameModelTest.php b/tests/ActivityLog/Models/CustomTableNameModelTest.php index 6afb73744..ec3b1cceb 100644 --- a/tests/ActivityLog/Models/CustomTableNameModelTest.php +++ b/tests/ActivityLog/Models/CustomTableNameModelTest.php @@ -46,10 +46,13 @@ protected function tearDownInCoroutine(): void } } - public function testUsesTheCustomTableForImmediateQueriesAndCleanup(): void + public function testUsesActivityLogAsTheDefaultTableName(): void { $this->assertSame('activity_log', (new DefaultActivity)->getTable()); + } + public function testUsesTheTableNameFromACustomModel(): void + { config()->set( 'activity-log.activity_model', CustomTableNameOnActivityModel::class, diff --git a/tests/ActivityLog/Traits/DetectsChangesTest.php b/tests/ActivityLog/Traits/DetectsChangesTest.php index 4f348e90c..7dc6520a5 100644 --- a/tests/ActivityLog/Traits/DetectsChangesTest.php +++ b/tests/ActivityLog/Traits/DetectsChangesTest.php @@ -167,7 +167,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChangesForInterval, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanStoreTheRelationValuesWhenUpdatingAModel(): void + public function testCanStoreTheRelationValuesWhenCreatingAModel(): void { $articleClass = new class extends Article { use LogsActivity; @@ -189,6 +189,8 @@ public function getActivityLogOptions(): LogOptions 'user_id' => $user->id, ]); + $this->assertSame('user name', $this->lastActivity()->attribute_changes->get('attributes')['user.name']); + $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); @@ -209,7 +211,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanStoreAnEmptyRelationWhenUpdatingAModel(): void + public function testCanStoreEmptyRelationWhenCreatingAModel(): void { $articleClass = new class extends Article { use LogsActivity; @@ -230,6 +232,8 @@ public function getActivityLogOptions(): LogOptions 'text' => 'original text', ]); + $this->assertSame(null, $this->lastActivity()->attribute_changes->get('attributes')['user.name']); + $article->name = 'updated name'; $article->text = 'updated text'; $article->save(); @@ -566,7 +570,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanStoreTheChangesWhenSavingAMultilevelRelatedModel(): void + public function testCanStoreTheChangesWhenSavingIncludingMultiLevelRelatedModel(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1025,7 +1029,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanStoreTheChangesWhenABooleanFieldChangesFromFalseToNull(): void + public function testCanStoreTheChangesWhenABooleanFieldIsChangedFromFalseToNull(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1135,7 +1139,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testWillStoreNoChangesWithWildcardGuardAndLogUnguarded(): void + public function testWillStoreNoChangesWhenWildcardGuardAndLogUnguardedAttributes(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1157,7 +1161,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals([], $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanLogUnguardedAttributesWhenModelIsGloballyUnguarded(): void + public function testCanLogUnguardedAttributesWhenModelUnguardIsCalledGlobally(): void { // Model without explicit $fillable or $guarded $articleClass = new class extends Article { @@ -1225,7 +1229,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanUseOverloadedAttributesAsLoggableAttributes(): void + public function testCanUseOverloadedAsLoggableAttributes(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1272,7 +1276,7 @@ public function getDescriptionAttribute(): mixed $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanUseMutatedAttributesAsLoggableAttributes(): void + public function testCanUseMutatedAsLoggableAttributes(): void { $userClass = new class extends User { use LogsActivity; @@ -1332,7 +1336,7 @@ public function setNameAttribute(string $value): void $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanUseAccessorsAsLoggableAttributes(): void + public function testCanUseAccessorAsLoggableAttributes(): void { $userClass = new class extends User { use LogsActivity; @@ -1392,7 +1396,7 @@ public function getNameAttribute(string $value): string $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanUseEncryptedAttributesAsLoggableAttributes(): void + public function testCanUseEncryptedAsLoggableAttributes(): void { $userClass = new class extends User { use LogsActivity; @@ -1460,7 +1464,7 @@ public function setAttribute(string|int $key, mixed $value): mixed $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanUseCastedAttributesAsLoggableAttributes(): void + public function testCanUseCastedAsLoggableAttribute(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1512,7 +1516,7 @@ public function getActivityLogOptions(): LogOptions $this->assertIsFloat($changes['attributes']['price']); } - public function testCanUseNullableDatesAsLoggableAttributes(): void + public function testCanUseNullableDateAsLoggableAttributes(): void { $userClass = new class extends User { use LogsActivity; @@ -1552,7 +1556,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanUseCustomDateCastsAsLoggableAttributes(): void + public function testCanUseCustomDateCastAsLoggableAttributes(): void { $userClass = new class extends User { use LogsActivity; @@ -1589,7 +1593,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testCanUseCustomImmutableDateCastsAsLoggableAttributes(): void + public function testCanUseCustomImmutableDateCastAsLoggableAttributes(): void { $userClass = new class extends User { use LogsActivity; @@ -1702,7 +1706,7 @@ public function getActivityLogOptions(): LogOptions $this->assertSame($expectedChanges, $changes); } - public function testWillReturnNullForAMissingJsonAttribute(): void + public function testWillReturnNullForMissingJsonAttribute(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1753,7 +1757,7 @@ public function getActivityLogOptions(): LogOptions $this->assertSame($expectedChanges, $changes); } - public function testWillReturnAnArrayForASubkeyInAJsonAttribute(): void + public function testWillReturnAnArrayForSubKeyInJsonAttribute(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1820,7 +1824,7 @@ public function getActivityLogOptions(): LogOptions $this->assertSame($expectedChanges, $changes); } - public function testWillAccessBeyondLevelOneInAJsonAttribute(): void + public function testWillAccessFurtherThanLevelOneJsonAttribute(): void { $articleClass = new class extends Article { use LogsActivity; @@ -1884,7 +1888,7 @@ public function getActivityLogOptions(): LogOptions $this->assertSame($expectedChanges, $changes); } - public function testCanExcludeAttributesGloballyViaConfiguration(): void + public function testCanExcludeAttributesGloballyViaConfigDefaultExceptAttributes(): void { config()->set('activity-log.default_except_attributes', ['text']); @@ -1912,7 +1916,7 @@ public function getActivityLogOptions(): LogOptions $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); } - public function testMergesConfiguredDefaultExclusionsWithModelExclusions(): void + public function testMergesConfigDefaultExceptAttributesWithModelLogExcept(): void { config()->set('activity-log.default_except_attributes', ['text']); diff --git a/tests/ActivityLog/Traits/LogsActivityTest.php b/tests/ActivityLog/Traits/LogsActivityTest.php index 75a126244..53737c51a 100644 --- a/tests/ActivityLog/Traits/LogsActivityTest.php +++ b/tests/ActivityLog/Traits/LogsActivityTest.php @@ -109,7 +109,7 @@ public function testCanSkipLoggingIfAskedToForUpdateMethod(): void $this->assertNull($this->getLastActivity()); } - public function testCanExcludeSpecificEventsUsingDoNotRecordEvents(): void + public function testCanExcludeSpecificEventsFromBeingLoggedUsingDoNotRecordEvents(): void { $articleClass = new class extends Article { use LogsActivity; @@ -264,7 +264,7 @@ public function testCanFetchSoftDeletedModels(): void $this->assertSame('changed name', $activity->subject?->getAttribute('name')); } - public function testCanFetchSubjectWithoutSoftDeletesWhenConfigIsEnabled(): void + public function testCanFetchSubjectWhenModelDoesNotUseSoftDeletesAndConfigIsEnabled(): void { config()->set('activity-log.include_soft_deleted_subjects', true); @@ -311,7 +311,7 @@ public function getActivityLogOptions(): LogOptions $this->assertSame('custom_log', $this->lastActivity()->log_name); } - public function testWillNotLogAnUpdateIfOnlyIgnoredAttributesChanged(): void + public function testWillNotLogAnUpdateOfTheModelIfOnlyIgnoredAttributesAreChanged(): void { $articleClass = new class extends Article { use LogsActivity; @@ -340,7 +340,7 @@ public function getActivityLogOptions(): LogOptions $this->assertSame('created', $activity->event); } - public function testWillNotFailIfAskedToReplaceFromAnEmptyAttribute(): void + public function testWillNotFailIfAskedToReplaceFromEmptyAttribute(): void { $model = new class extends Article { use LogsActivity; @@ -371,7 +371,7 @@ public function getActivityLogOptions(): LogOptions $this->assertSame(':causer.name updated', $activities[1]->description); } - public function testCanLogActivityOnSubjectByTheSameCauser(): void + public function testCanLogActivityOnSubjectBySameCauser(): void { $user = $this->loginWithFakeUser(); $user->setAttribute('name', 'LogsActivity Name'); From 4673d3068510ef4740d1da6e37d527a0fa3388d2 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:51:17 +0000 Subject: [PATCH 4/5] Document the Activity Log reconciliation baseline and differences Explain how activity-connection ownership affects rollback guarantees when the audit and subject databases differ. Document failed-batch handling, worker-lifetime callbacks, fresh loggers and top-level configuration defaults. Show how to hydrate log names into an enum through the configured activity model. The source, test suite and applicable documentation were reconciled against spatie/laravel-activitylog main at 741ce06abfb91a96d2ee056706a6564ae8a3a71f. The Activity Log suite, MySQL, MariaDB and PostgreSQL integration checks, formatting and static analysis passed. --- src/activity-log/README.md | 30 ++++++++++++++++++++++++++---- src/docs/activity-log.md | 21 ++++++++++++++++++--- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/activity-log/README.md b/src/activity-log/README.md index e5537e5a4..ccac0f1ca 100644 --- a/src/activity-log/README.md +++ b/src/activity-log/README.md @@ -5,8 +5,9 @@ Documentation: https://hypervel.org/docs/activity-log ## Differences From Spatie Laravel Activity Log -- Public names use `ActivityLog` and `activity-log` casing. The global - `activity()` helper is retained. +- Use the `ActivityLog` facade in place of Spatie's `Activity` facade. The + config file and Artisan command prefix use `activity-log`, and environment + settings use `ACTIVITY_LOG_`. The global helper is `activity()`. - `activity(null)` selects the configured default. Empty string and `"0"` are distinct log names. `useLog(null)` and `inLog(null)` explicitly set a null name. - Automatic model logging uses the event's in-memory snapshot without another @@ -14,8 +15,29 @@ Documentation: https://hypervel.org/docs/activity-log transaction-only refresh for database-generated values. - Dotted relation attributes retain the configured key even when traversal resolves a snake-case, camel-case, or dynamic-relation alias. -- Optional buffering is coroutine-scoped, transaction-aware, and flushed in - bounded batches at Hypervel lifecycle boundaries. +- The activity model's connection owns the write. Spatie can defer a write + on another connection until the subject commits. Hypervel supports a + separate activity database, but a rollback on the subject connection does + not discard that activity. For atomic audit writes, disable buffering and + use the same connection and transaction. For durable cross-database + delivery, use an application outbox. +- Optional buffering is coroutine-scoped and flushes in bounded batches at + request and job boundaries. If an insert fails, its attempted batch is + discarded because retrying an ambiguous write can duplicate rows. + Unattempted rows remain eligible to flush. +- The facade resolves a stateless `ActivityLogManager`. Each fluent root + call gets a fresh logger, and reusing a logger after `log()` starts a new + activity even when the previous call failed or logging was disabled. +- Register callbacks and macros at worker boot. Resolve request-specific + values such as a batch UUID when the callback runs, since the same + registration serves later requests. See [Callbacks and Macros](https://hypervel.org/docs/activity-log#callbacks-and-macros). +- Hypervel reads package settings through `ActivityLogConfiguration`. Omitted + top-level settings use package defaults. If you supply a `buffer` group, + include both `enabled` and `batch_size`. Explicitly setting `activity_model` + or `enabled` to null is invalid. +- Cleanup uses the model's configured created-at column and primary key + to delete bounded batches. A custom model can record keyless activities, + but the built-in cleanup action requires a primary key. - `setLogStatus()` is replaced by `enableLogging()`, `disableLogging()`, and `withoutLogging()`. Tests reset callbacks through `flushState()` rather than the upstream test-only `clearBeforeLoggingCallbacks()` alias. diff --git a/src/docs/activity-log.md b/src/docs/activity-log.md index 2463ae4e7..cdb1436e5 100644 --- a/src/docs/activity-log.md +++ b/src/docs/activity-log.md @@ -208,6 +208,21 @@ The `createdAt()` method uses the activity model's configured created-at column. Use `activity('security')`, `useLog()`, or `inLog()` to select a log. These methods, `LogOptions::useLogName()`, and the `inLog` query scope also accept backed enums. Their backing values are stored as strings. Passing `null` to `activity()` selects `default_log_name`; empty string and `"0"` are valid, distinct log names. Calling `useLog(null)` or `inLog(null)` explicitly sets the pending activity's log name to `null`. +To read the log name back as an enum, register a custom activity model and add the cast to the model's existing casts: + +```php +use App\Enums\LogName; +use Hypervel\ActivityLog\Models\Activity as BaseActivity; + +class Activity extends BaseActivity +{ + protected function casts(): array + { + return [...parent::casts(), 'log_name' => LogName::class]; + } +} +``` + ### Placeholders @@ -612,9 +627,9 @@ A UUID/ULID key can therefore exist before the row is persisted. Do not treat a ### Transactions -An activity prepared while its own activity connection is transacting is staged against that exact connection. The outer commit makes it eligible for insertion; rollback discards it. Savepoint order is preserved, and a transaction on another connection does not decide its outcome. +A buffered activity prepared inside a transaction on the activity model's connection becomes eligible for insertion when the outer transaction commits. Rolling back discards it. Savepoint order is preserved. If the subject uses a different connection, its transaction does not control the activity write, even when the activity was recorded by a model event. -After the domain transaction commits, buffered activities are written in a new transaction. Activities from rolled-back transactions are discarded, but the later insert is not atomic with your domain changes. A crash between the two commits can lose the activity. +When the activity and domain models share a connection, buffered activities are written in a new transaction after the domain transaction commits. A crash between the two commits can lose the activity. On a separate connection, the activity can be written before the domain transaction finishes. If the activity must commit atomically with domain data, disable buffering and write it immediately using the same transaction and connection. For durable or cross-connection delivery, use an application outbox. @@ -741,7 +756,7 @@ Review custom models, actions, callbacks, and tests for these public differences - `activity()` selects the default log name only for `null`, not empty string or `"0"`; - automatic logging does not call `fresh()` unless `refreshBeforeLogging()` is enabled inside a transaction; - dotted relation keys retain the configured spelling; -- buffering is coroutine-scoped, bounded, and transaction-aware; +- buffering is coroutine-scoped and bounded; a transaction on a separate subject connection does not defer or discard an activity write; - `setLogStatus()` is replaced by `enableLogging()`, `disableLogging()`, and `withoutLogging()`; - Hypervel clears registered callbacks between tests. From 1928d4de48fcf9519d41806109d31605a1689465 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:07:17 +0000 Subject: [PATCH 5/5] Clarify activity causer callbacks and buffered delivery guarantees Document that log() preserves the causer selected or cleared inside tap(). Explain how consecutive rows with the same columns share an insert within a bounded batch and how omitted columns retain their database defaults. Distinguish the risk of losing buffered rows on a worker crash from the choice to write to a separate audit database. Describe the transactional outbox for applications that require reliable delivery for each committed domain change. Cross-checked all 16 Spatie PRs since the initial port through upstream 741ce06abfb91a96d2ee056706a6564ae8a3a71f, including the causer, buffer, and transaction changes in #1477, #1480, and #1476 respectively. The Activity Log suite and both separate-connection test modes pass. --- src/docs/activity-log.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/docs/activity-log.md b/src/docs/activity-log.md index cdb1436e5..ce680928f 100644 --- a/src/docs/activity-log.md +++ b/src/docs/activity-log.md @@ -248,7 +248,7 @@ activity() ->log('Invoice approved'); ``` -The default causer has already been associated when the tap runs. +The default causer is available when the tap runs. If the callback replaces or clears the causer, `log()` preserves that choice. ### Conditional Logging @@ -611,9 +611,9 @@ ACTIVITY_LOG_BUFFER_BATCH_SIZE=500 Buffered activities are kept in memory for the current coroutine and are never combined with activities from another request or job. The buffer is created only when the first activity needs it. > [!WARNING] -> Buffering is not a durable queue. If you need activities to survive a worker crash or to be delivered across database connections, use an application outbox or queue. +> A worker crash can lose activities still in memory. If those activities must survive a crash, use a durable queue or transactional outbox. -Buffered activities are written in call order. Custom columns, timestamp settings, and database defaults are preserved. +The buffer writes each bounded batch in one transaction. Consecutive activities with the same columns share an insert. This preserves logging order and lets the database apply defaults to omitted columns. The activity model controls its timestamps. Before enabling buffering, keep these differences in mind: @@ -631,7 +631,7 @@ A buffered activity prepared inside a transaction on the activity model's connec When the activity and domain models share a connection, buffered activities are written in a new transaction after the domain transaction commits. A crash between the two commits can lose the activity. On a separate connection, the activity can be written before the domain transaction finishes. -If the activity must commit atomically with domain data, disable buffering and write it immediately using the same transaction and connection. For durable or cross-connection delivery, use an application outbox. +If the activity must commit atomically with domain data, disable buffering and write it immediately using the same transaction and connection. If delivery to a separate audit database must be guaranteed for each committed domain change, write an outbox record in the domain transaction and have a worker deliver it to the audit database. Calling `ActivityBuffer::flush()` while the buffer has work and its activity connection has an open application transaction throws. It drains rows in call order and stops at the first activity whose transaction outcome is still pending.