Search by

kamal-abouzayed / recommend-kit

Kamal-Abouzayed

Self-hosted catalog recommendations for Laravel using CPU implicit ALS.

Package info

github.com/Kamal-Abouzayed/recommend-kit

pkg:composer/kamal-abouzayed/recommend-kit

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-12-02 16:25 UTC

This package is auto-updated.

Last update: 2026-12-02 16:30:22 UTC


README

RecommendKit provides personalized product and service recommendations for Laravel. Record interactions in your application's MySQL transaction, then request ranked item IDs by user and catalog. Laravel Scheduler queues training when enough data accumulates. The Python CPU ALS trainer runs on a dedicated worker. Web requests only need MySQL.

Installation

The Composer name is kamal-abouzayed/recommend-kit. Once the release is available on Packagist, install it in your Laravel application:

composer require "kamal-abouzayed/recommend-kit:^0.1"
php artisan vendor:publish --tag=recommend-kit
php artisan migrate

For a local checkout before publication, use these Composer commands in place of the first command:

composer config repositories.recommend-kit path /absolute/path/to/recommend-kit
composer require "kamal-abouzayed/recommend-kit:@dev"

Laravel discovers the service provider automatically. Configure the application's default database as MySQL with InnoDB before migrating. Use the same primary database for recording, training and serving.

Component Verified versions
Laravel 12.75.0 and 13.45.0
PHP 8.4.28 with PDO MySQL (Composer accepts PHP 8.4.x)
MySQL Community Server 8.4.8
Training worker CPython 3.11.18, implicit 0.7.2, Windows 11 x64

Configure the training worker

On Linux:

python3.11 -m venv /opt/recommendkit/venv
/opt/recommendkit/venv/bin/python -m pip install -r vendor/kamal-abouzayed/recommend-kit/python/requirements.txt

On Windows:

py -3.11 -m venv C:\RecommendKit\venv
C:\RecommendKit\venv\Scripts\python.exe -m pip install -r vendor/kamal-abouzayed/recommend-kit/python/requirements.txt

Set the absolute interpreter path in the worker environment. A database-backed queue and lock store can use the following Laravel settings:

RECOMMENDKIT_PYTHON=/opt/recommendkit/venv/bin/python
RECOMMENDKIT_QUEUE_CONNECTION=database
DB_QUEUE_RETRY_AFTER=1020
CACHE_STORE=database

Use the Windows interpreter path on Windows. Apply the queue and cache settings to the scheduler and workers. All workers need the same atomic lock store and application-specific cache prefix. Ensure Laravel's queue and cache tables exist and that the worker can write to storage/app/private.

Run php artisan schedule:run every minute using the host scheduler. For local testing, run php artisan schedule:work in one terminal and the dedicated worker in another:

php artisan queue:work database --queue=recommend-kit --timeout=900 --tries=2

The default process timeout is 600 seconds, job timeout 900 seconds, lock lifetime 960 seconds and database queue retry interval in the example 1,020 seconds. Use a Linux worker with pcntl for enforceable job timeouts. Restart workers after configuration changes.

First publication

Every five minutes, the readiness check looks for a catalog with at least six events, two distinct users and three distinct items in the last 90 days. After publication it requires five fresh events. Adjust the thresholds, training window, cron expression, event weights and top K in config/recommend-kit.php.

Before the first publication, forUser() returns an empty list. Check the active batch and the last published event sequence with:

SELECT CAST(catalog AS CHAR) AS catalog_name, active, checkpoint
FROM rk_catalogs;

A non-null active means a complete batch is available. If the catalog meets the thresholds and still has no batch, check php artisan schedule:list, confirm a worker consumes the recommend-kit queue, and inspect php artisan queue:failed. Training failures identify the catalog, run and stage. Check the configured interpreter, dependency imports, free RAM and private storage permissions. A failed run leaves the catalog eligible for retry.

Host integration

Use the same default MySQL connection and transaction for the business change and its event. Derive catalog names server-side from tenant and item type. Give each logical catalog a collision-free identity. Include tenant authorization and availability constraints when loading items.

use RecommendKit\RecommendKit;
use Illuminate\Support\Facades\DB;

DB::transaction(function () use ($orderLine, $user, $product, $tenant) {
    $orderLine->save();
    RecommendKit::record((string) $user->getKey(), (string) $product->getKey(),
        'purchase', "tenant-{$tenant->id}/products", "order-line:{$orderLine->id}");
});

DB::transaction(function () use ($booking, $tenant) {
    $booking->update(['status' => 'completed']);
    RecommendKit::record((string) $booking->user_id, (string) $booking->service_id,
        'booking_completed', "tenant-{$tenant->id}/services", "completed:{$booking->id}");
});

$ids = RecommendKit::forUser((string) $user->getKey(), "tenant-{$tenant->id}/products", 20);
$query = $tenant->products()->where('available', true);
$items = (clone $query)->whereKey($ids)->get()->keyBy(fn ($p) => 'id:'.$p->getKey());
$ranked = collect($ids)->map(fn ($id) => $items->get('id:'.$id))->filter()->take(10)->values();
if ($ranked->count() < 10) {
    $ranked = $ranked->concat((clone $query)->whereNotIn('id', $ranked->pluck('id'))
        ->orderByDesc('sales_count')->orderBy('id')->limit(10 - $ranked->count())->get());
}

Use the same retrieval pattern with available services and booking count. Hosts with opaque primary keys should configure Eloquent string key types and matching binary comparisons. IDs and catalog names accept 1–128 UTF-8 bytes, compared verbatim including case, spaces and leading zeros. PHP uses strings, MySQL VARBINARY, Python Unicode without normalization. Identical replays retain their original weight. Conflicting payloads throw DomainException. Weights must be finite positive numbers at most one million. forUser returns a list of item ID strings in rank order, possibly empty, with limits 1–100.

Training and storage

The writer serializes sequence allocation with a per-catalog row lock held through the host commit. A lower sequence cannot commit after a higher sequence in that catalog. Keep host transactions short. A run freezes the time cutoff and committed upper sequence. It exports eligible immutable rows in chunks. Newly committed sequences remain eligible for the next successful run. Erasure invalidates every older snapshot.

Input NDJSON rows are [1,user,item,weight]. Output has one [1,user,[[item,score],...]] per user in bytewise user order, including empty lists, followed by [1,"end",userCount] and EOF. All rows require a newline. Rank is the one-based array position. K is capped at 100. Every item seen by that user in the window is excluded, for all event types. Ties sort by item bytes. The importer checks the expected users, item eligibility, list lengths, finite scores, uniqueness and order. A single transaction stages the new rows, checks generation and checkpoint under lock, publishes, and removes the old batch. InnoDB rolls back abandoned imports. A single indexed join serves the active batch. A custom Trainer binding can replace the local process.

The training window governs inclusion. Events persist for replay protection. To erase a user call RecommendKit::erase($userId,$catalog) for every applicable catalog and suppress upstream replays. Erasure clears the entire active batch because other predictions also depended on that user. Readers get empty results until retraining. Coordinate backup expiry separately. Normal exits remove private run directories. After a hard kill, stop the affected worker and remove its abandoned run directory after confirming the process exited.

PHP streams files. Python needs memory for unique pairs, dictionaries, the sparse matrix, user/item factors, and dense scores for 64 users times the item count. Exact ranking scans all catalog items. Size worker memory using representative load. A full publication occupies one DB transaction. Scale worker concurrency across catalogs; measure lock waits, ranking and import before adding alternative serving infrastructure.

Retention and cleanup

Window expiry affects subsequent training snapshots. The active batch stays available until replacement or erasure. Workers remove run files on normal exits. At the start of training, a worker checks its private run directories older than 24 hours and removes abandoned snapshots after acquiring a nonblocking file lock. An idle worker can retain crash files until its next run.

Publishing from GitHub

RecommendKit uses annotated Git tags for versioning, starting with v0.1.0. Packagist reads the version from the tag. For the first publication, confirm ownership of the Composer vendor, push the release commit and tag to your public GitHub repository, then submit that repository's HTTPS URL to Packagist and enable the GitHub integration for automatic updates.

Testing from a source checkout

With a disposable migrated MySQL host and RECOMMENDKIT_PYTHON set, run php tests/integration.php /path/to/host. This exercises the scheduler, two workers, publication, and concurrent transactions. The race checks require read access to MySQL Performance Schema. Run python tests/trainer_test.py in the training environment for the ALS tests.

The chronological fixture (python python/evaluate.py tests/fixture.ndjson --cutoff 7 --k 1) gave Hit Rate@1 of 3/3 for ALS and 1/3 for weighted popularity. One cold-start user was skipped.

Run php tests/benchmark.php /path/to/host 100 200 2000 to reproduce the synthetic benchmark. On Windows 11 with a Ryzen 5 3550H and the Laravel 13 stack above, 2,000 events produced 2,000 recommendations in 4.54 s. Readiness and export took 0.111 s, ALS fitting took 0.041 s, ranking and writing took 0.025 s, and import and publication took 1.935 s. Process startup and library loading accounted for most remaining time. Across 100 sequential reads, serving latency was 1.58 ms at p50 and 2.27 ms at p95. Peak PHP allocation was 24 MiB.

License

RecommendKit is distributed under the MIT license. License