Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app/Actions/Photo/Pipes/Duplicate/SaveIfDirty.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@

use App\Contracts\PhotoCreate\DuplicatePipe;
use App\DTO\PhotoCreate\DuplicateDTO;
use App\Services\MonthDayKey;
use Illuminate\Support\Facades\Log;

class SaveIfDirty implements DuplicatePipe
{
public function handle(DuplicateDTO $state, \Closure $next): DuplicateDTO
{
// FR-106-03: HydrateMetadata may have rewritten `taken_at`.
$state->photo->month_day_key = MonthDayKey::of($state->photo->taken_at, $state->photo->created_at);

// Adopt settings of duplicated photo acc. to target album
if ($state->photo->isDirty()) {
Log::notice(__METHOD__ . ':' . __LINE__ . ' Updating metadata of existing photo.');
Expand Down
4 changes: 4 additions & 0 deletions app/Actions/Photo/Pipes/Shared/Save.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use App\Contracts\PhotoCreate\PhotoDTO;
use App\Contracts\PhotoCreate\PhotoPipe;
use App\Services\BucketKeys;
use App\Services\MonthDayKey;
use App\Services\TitleSplitter;

/**
Expand All @@ -25,6 +26,9 @@ public function handle(PhotoDTO $state, \Closure $next): PhotoDTO
$state->getPhoto()->title_index = $title_split->index;
// FR-092-02: assigned at every write of `title`.
$state->getPhoto()->title_date_key = BucketKeys::titleDateKey($state->getPhoto()->title ?? '');
// FR-106-03: assigned at every write of `taken_at` or `created_at`; a
// new photo is stamped with the current time by save().
$state->getPhoto()->month_day_key = MonthDayKey::of($state->getPhoto()->taken_at, $state->getPhoto()->created_at ?? now());

$state->getPhoto()->save();
$state->getPhoto()->tags()->sync($state->getTags()->pluck('id')->all());
Expand Down
3 changes: 3 additions & 0 deletions app/Console/Commands/ImageProcessing/Takedate.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use App\Metadata\Extractor;
use App\Models\Photo;
use App\Services\BucketKeys;
use App\Services\MonthDayKey;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
Expand Down Expand Up @@ -230,6 +231,8 @@ public function handle(): int
// FR-092-01, FR-092-10: assigned at every write of `taken_at`,
// then every `photo_album` key of the photo is recomputed.
$photo->taken_key = BucketKeys::takenKey($photo->taken_at);
// FR-106-03: follows `taken_at` and `created_at` alike.
$photo->month_day_key = MonthDayKey::of($photo->taken_at, $photo->created_at);
$photo->save();
RecomputePhotoBucketsJob::dispatchIf($photo->wasChanged(['taken_at', 'taken_key', 'created_at']), $photo->id);
}
Expand Down
3 changes: 3 additions & 0 deletions app/Http/Controllers/Gallery/PhotoController.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
use App\Policies\PhotoPolicy;
use App\Repositories\ConfigManager;
use App\Services\BucketKeys;
use App\Services\MonthDayKey;
use App\Services\Telemetry\TraceService;
use App\Services\TitleSplitter;
use Illuminate\Routing\Controller;
Expand Down Expand Up @@ -232,6 +233,8 @@ public function update(EditPhotoRequest $request): PhotoResource
// if the request takenAt is null, then we set the initial value back.
$photo->taken_at = $request->takenAt() ?? $photo->initial_taken_at;
$photo->taken_key = BucketKeys::takenKey($photo->taken_at);
// FR-106-03: follows the taken date, else the upload date set above.
$photo->month_day_key = MonthDayKey::of($photo->taken_at, $photo->created_at);

// Feature 082: the manual 360° flag, left untouched when not sent (v7).
$photo->is_360 = $request->is360() ?? $photo->is_360;
Expand Down
1 change: 1 addition & 0 deletions app/Models/Photo.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
* @property int $title_index
* @property string|null $title_date_key Leading date of the title as `Y-m-d` (FR-092-02).
* @property string|null $taken_key `taken_at` in `taken_at_orig_tz` as `Y-m-d-H` (FR-092-01).
* @property int|null $month_day_key Month × 100 + day of `taken_key`, else of `created_at` (FR-106-01).
* @property string|null $description
* @property Collection<int,Tag> $tags
* @property int $owner_id
Expand Down
33 changes: 33 additions & 0 deletions app/Services/MonthDayKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2026 LycheeOrg.
*/

namespace App\Services;

/**
* `photos.month_day_key` (FR-106-01): month × 100 + day, read by the On This
* Day smart album through `photos_month_day_key_index`.
*/
final class MonthDayKey
{
/**
* The day of a cast `taken_at`, which is in the zone the photo was taken
* in (the date of `photos.taken_key`), else of `created_at` as stored.
*/
public static function of(?\DateTimeInterface $taken_at, \DateTimeInterface $created_at): int
{
return self::ofDate($taken_at ?? $created_at);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/**
* The day of `$date` in its own zone.
*/
public static function ofDate(\DateTimeInterface $date): int
{
return (int) $date->format('n') * 100 + (int) $date->format('j');
}
}
16 changes: 8 additions & 8 deletions app/SmartAlbums/OnThisDayAlbum.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use App\Enum\SmartAlbumType;
use App\Exceptions\ConfigurationKeyMissingException;
use App\Exceptions\Internal\FrameworkException;
use App\Services\MonthDayKey;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\Exceptions\InvalidTimeZoneException;
use Illuminate\Database\Eloquent\Builder;
Expand All @@ -32,15 +33,14 @@ protected function __construct()

parent::__construct(
id: SmartAlbumType::ON_THIS_DAY,
// `month_day_key` is the day where the photo was taken, else its
// upload day (FR-106-01), read through its index; an upload of
// this year does not count.
smart_condition: function (Builder $query) use ($today): void {
$query->where(fn (Builder $q) => $q
->whereMonth('photos.taken_at', '=', $today->month)
->whereDay('photos.taken_at', '=', $today->day))
->orWhere(fn (Builder $q) => $q
->whereNull('photos.taken_at')
->whereYear('photos.created_at', '<', $today->year)
->whereMonth('photos.created_at', '=', $today->month)
->whereDay('photos.created_at', '=', $today->day));
$query->where('photos.month_day_key', '=', MonthDayKey::ofDate($today))
->where(fn (Builder $q) => $q
->whereNotNull('photos.taken_at')
->orWhere('photos.created_at', '<', $today->year . '-01-01 00:00:00'));
}
);
}
Expand Down
6 changes: 4 additions & 2 deletions database/factories/PhotoFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use App\Models\Statistics;
use App\Models\Tag;
use App\Services\BucketKeys;
use App\Services\MonthDayKey;
use Database\Factories\Traits\OwnedBy;
use Illuminate\Database\Eloquent\Factories\Factory;

Expand Down Expand Up @@ -195,10 +196,11 @@ public function with_title(string $title): self
public function configure(): self
{
return $this->afterMaking(function (Photo $photo) {
// Row-intrinsic bucket keys (FR-092-01, FR-092-02), as every
// write path assigns them.
// Row-intrinsic bucket keys (FR-092-01, FR-092-02) and the On
// This Day key (FR-106-01), as every write path assigns them.
$photo->taken_key = BucketKeys::takenKey($photo->taken_at);
$photo->title_date_key = BucketKeys::titleDateKey($photo->title);
$photo->month_day_key = MonthDayKey::of($photo->taken_at, $photo->created_at ?? now());
})->afterCreating(function (Photo $photo) {
Statistics::factory()->with_photo($photo->id)->create();
$photo->fresh();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2026 LycheeOrg.
*/

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

require_once 'TemporaryModels/OptimizeTables.php';

/**
* Feature 106 (FR-106-01, FR-106-04): `photos.month_day_key`, month × 100 +
* day of `taken_key` (the local day where the photo was taken), else of
* `created_at`, indexed for the On This Day smart album. Filled in two
* statements, only on rows without a key.
*/
return new class() extends Migration {
private OptimizeTables $optimize;

public function __construct()
{
$this->optimize = new OptimizeTables();
}

/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('photos', function (Blueprint $table) {
$this->optimize->dropIndexIfExists($table, 'photos_month_day_key_index');
});

Schema::table('photos', function (Blueprint $table) {
if (!Schema::hasColumn('photos', 'month_day_key')) {
$table->unsignedSmallInteger('month_day_key')->nullable()->default(null)->after('taken_key');
}
});

[$from_taken_key, $from_created_at] = match (DB::getDriverName()) {
'sqlite' => [
'CAST(SUBSTR(taken_key, 6, 2) || SUBSTR(taken_key, 9, 2) AS INTEGER)',
"CAST(strftime('%m%d', created_at) AS INTEGER)",
],
'pgsql' => [
'CAST(SUBSTR(taken_key, 6, 2) || SUBSTR(taken_key, 9, 2) AS INTEGER)',
"CAST(to_char(created_at, 'MMDD') AS INTEGER)",
],
'mysql', 'mariadb' => [
'CAST(CONCAT(SUBSTR(taken_key, 6, 2), SUBSTR(taken_key, 9, 2)) AS UNSIGNED)',
"CAST(DATE_FORMAT(created_at, '%m%d') AS UNSIGNED)",
],
default => throw new \RuntimeException('Unsupported database driver'),
};

DB::table('photos')
->whereNull('month_day_key')
->whereNotNull('taken_key')
->update(['month_day_key' => DB::raw($from_taken_key)]);

DB::table('photos')
->whereNull('month_day_key')
->whereNull('taken_key')
->update(['month_day_key' => DB::raw($from_created_at)]);

Schema::table('photos', function (Blueprint $table) {
$table->index('month_day_key', 'photos_month_day_key_index');
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('photos', function (Blueprint $table) {
$this->optimize->dropIndexIfExists($table, 'photos_month_day_key_index');
});

Schema::table('photos', function (Blueprint $table) {
$table->dropColumn('month_day_key');
});
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Open Questions – Feature 106

Open questions for [Feature 106](spec.md). Log every high- and medium-impact question here (table row + Question Details entry) before asking the user; see [open-questions-format.md](../../spec-guidelines/open-questions-format.md). Once answered, fold the outcome into [spec.md](spec.md) (and an ADR when architecturally significant), then mark the entry resolved.

## Active Questions

| Question ID | Feature | Priority | Summary | Status | Opened | Updated |
|-------------|---------|----------|---------|--------|--------|---------|
| ~~Q-106-01~~ | 106 | Medium | Day of a photo with a taken date: A local day where it was taken (as `taken_key`, Timeline), B UTC day as stored (today's result) | Resolved (A, FR-106-01, S-106-05) | 2026-11-01 | 2026-11-01 |

## Question Details

### ~~Q-106-01~~ · Which day a photo with a taken date belongs to

**Status:** Resolved (A, owner, 2026-11-01): the key holds the local day where the photo was taken (FR-106-01, S-106-05).
**Preferred option:** A – the local day where the photo was taken

**Question**
`taken_at` is stored in UTC with the zone it was taken in (`taken_at_orig_tz`). On This Day matches the month and day of the stored UTC value, while `taken_key` (Timeline, Feature 092) uses the local date where the photo was taken. For a photo taken near midnight away from UTC the two days differ: a photo taken at 00:30 on 2 November in Paris is stored as 1 November 23:30 UTC and is shown On This Day on 1 November. Which day does the key hold?

**Option A (recommended) – the local day where it was taken**
- Idea: key = month and day of `taken_key` (`Y-m-d-H` in `taken_at_orig_tz`); the backfill reads it from the stored `taken_key`.
- Pros: the day the photographer sees on the photo and in the Timeline; one rule across Lychee; the backfill needs no time-zone arithmetic in SQL.
- Cons: photos taken near midnight away from UTC move to the neighbouring day compared with today.

**Option B – the UTC day as stored**
- Idea: key = month and day of the stored `taken_at`, as the current query.
- Pros: exactly today's members.
- Cons: keeps the off-by-one day for photos taken near midnight; differs from the Timeline.
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Feature Plan 106 – On This Day Index

_Linked specification:_ [spec.md](spec.md)
_Linked tasks:_ [tasks.md](tasks.md)
_Status:_ Implemented
_Last updated:_ 2026-11-01

> Guardrail: Keep this plan traceable back to the governing spec. Reference FR/NFR/Scenario IDs from `spec.md` where relevant, log any new high- or medium-impact questions in the feature's [open-questions.md](open-questions.md), and assume clarifications are resolved only when the spec’s normative sections (requirements/NFR/behaviour/telemetry) and, where applicable, ADRs under `docs/specs/6-decisions/` have been updated.

## Vision & Success Criteria
On This Day reads only the photos of the day through `photos_month_day_key_index` (FR-106-01, FR-106-02, NFR-106-01). Every date write keeps the key current (FR-106-03), the migration fills it for existing photos (FR-106-04). Success: S-106-01 … 08 green, the SQLite plan names the index, and the scratch instance (50,000 photos) shows `Album::head?album_id=on_this_day` and the On This Day cover no longer scanning `photos`.

## Scope Alignment
- **In scope:** `App\Services\MonthDayKey`, migration (column, index, backfill), `OnThisDayAlbum`, the four write sites, `PhotoFactory`, `Photo` docblock, knowledge map.
- **Out of scope:** spec Non-Goals (Recent, random header pick, smart-album cover cache).

## Dependencies & Interfaces
- `photos.taken_key` (Feature 092): the backfill reads the local day where the photo was taken from it; `BucketKeys::takenKey()` formats the same cast `taken_at` the new helper reads.
- `Shared\Save`, `Duplicate\SaveIfDirty`, `PhotoController::update`, `lychee:takedate`: the places that already assign `taken_key`.
- `OptimizeTables::dropIndexIfExists()` for the index, as in `2026_10_12_000001_add_bucket_keys_to_photos`.

## Assumptions & Risks
- **Assumptions:** `taken_key` is set for every photo with a `taken_at` (assigned at every write since Feature 092, backfilled by its migration). The cast `taken_at` is in `taken_at_orig_tz`; `created_at` and `Carbon::today()` are in the application time zone.
- **Risks / Mitigations:** a single-column index misleading the MySQL planner (2022 migration) — the column is only compared for equality, never sorted on (NFR-106-02). A new photo has no `created_at` before `save()` — the `Save` pipe passes `now()` for a photo without one, the time Eloquent stamps it with.

## Implementation Drift Gate
2026-11-01, agent, after T-106-08 (all tasks checked, gate green).

| Requirement | Code | Tests / evidence |
|-------------|------|------------------|
| FR-106-01 | `App\Services\MonthDayKey`, `photos.month_day_key` + `photos_month_day_key_index` | `MonthDayKeyTest` 4/4 (red first) |
| FR-106-02 | `OnThisDayAlbum` smart condition | `OnThisDayAlbumTest` 5/5 (S-106-05 red first); `AlbumCategoryV3Test` 20/20, `AlbumHeadEndpointTest` 15/15 |
| FR-106-03 | `Shared\Save`, `Duplicate\SaveIfDirty`, `PhotoController::update()`, `Takedate`, `PhotoFactory` | `PhotoKeysWriteTest` 12/12 (6 new cases red first), `TakeDateTest` 2/2, `ImportFromServerTest` 6/6 |
| FR-106-04 | `2026_11_01_000001_add_month_day_key_to_photos` | Scratch copy, 50,000 photos (2,000 without taken date, 2,000 taken in Europe/Paris at 23:30 UTC): migration 84 ms, 0 rows without key, 0 keys differing from `MonthDayKey`, the 2,000 Paris photos on their local day |
| NFR-106-01 | – | SQLite plan: `SEARCH photos USING INDEX photos_month_day_key_index (month_day_key=?)`. Same data, old vs new condition: header `count` 20.8 → 3.8 ms, `OFFSET` 12.7 → 2.9 ms, `exists` 2.3 → 1.4 ms; `Album::head?album_id=on_this_day` 37–47 → 17–21 ms (SQL 22–35 → 6 ms); On This Day queries of `Albums/smart` 0.2–1 ms |
| NFR-106-02 | no `orderBy` on the column | code review |
| NFR-106-03 | per-driver backfill expressions (SQLite, PostgreSQL, MySQL/MariaDB) | SQLite run locally; PostgreSQL and MySQL/MariaDB through CI |

Commands rerun: `php artisan test --filter=` `MonthDayKeyTest`, `OnThisDayAlbumTest`, `AlbumCategoryV3Test`, `AlbumHeadEndpointTest`, `OverridePermissionsTest`, `CoverageTest`, `SmartAlbumTypeTest`, `RecomputeAlbumUserThumbsJobTest`, `AlbumFactoryTest`, `SetSmartProtectionPolicyTest`, `PhotoKeysWriteTest`, `TakeDateTest`, `ImportFromServerTest`, `Photo360UploadTest`, `Photo360EditTest`, `PhotoTitleSyncTest`, `PhotoSortingBucketDispatchTest`, `TimelineAlbumTest` (all green); `php-cs-fixer` on the 13 touched files (0 fixed); `make phpstan` (no errors). Scratch scripts: `onthisday/prepare.php`, `verify.php`, `ab.php`; `cachecheck/head.php`, `smart.php`.

Findings: `AlbumCategoryV3Test` fixtures moved `taken_at` with raw SQL and now set `taken_key` and `month_day_key` with it. The remaining cold cost of `Albums/smart` on the scratch data is Untagged (128 ms), Recent (120 ms) and Unsorted (53 ms), each scanning `photos` (Non-Goals, follow-up below).

## Increment Map
1. **I1 – Key helper** (T-106-01, T-106-02)
- _Steps:_ failing `MonthDayKeyTest`, then `App\Services\MonthDayKey`.
- _Commands:_ `php artisan test --filter=MonthDayKeyTest`, `make phpstan`.
- _Exit:_ green, phpstan clean.
2. **I2 – Schema** (T-106-03)
- _Steps:_ migration (column, index, two backfill `UPDATE`s per driver), `PhotoFactory` `afterMaking`, `Photo` docblock.
- _Commands:_ `php artisan test --filter=PhotoKeysWriteTest` (migrates the test database), `make phpstan`.
- _Exit:_ test database migrated, existing tests green.
3. **I3 – On This Day query** (T-106-04, T-106-05)
- _Steps:_ failing `OnThisDayAlbumTest` (S-106-05 fails on the current UTC-day query), then `OnThisDayAlbum` on `month_day_key`.
- _Commands:_ `php artisan test --filter=OnThisDayAlbumTest`, `php artisan test --filter=AlbumHeadEndpointTest`, `php artisan test --filter=AlbumCategoryV3Test`.
- _Exit:_ green.
4. **I4 – Write sites** (T-106-06, T-106-07)
- _Steps:_ failing `PhotoKeysWriteTest` cases (upload, edit taken date, reset, edit upload date, takedate), then the four write sites.
- _Commands:_ `php artisan test --filter=PhotoKeysWriteTest`, `php artisan test --filter=TakeDateTest`, `vendor/bin/php-cs-fixer fix`, `make phpstan`.
- _Exit:_ green.
5. **I5 – Verification and docs** (T-106-08)
- _Steps:_ knowledge map, roadmap; scratch instance: migrate a copy, `EXPLAIN QUERY PLAN`, timings before/after.
- _Exit:_ index used, timings recorded in the drift gate.

## Scenario Tracking

| Scenario ID | Increment / Task reference | Notes |
|-------------|---------------------------|-------|
| S-106-01 … 05 | I3 / T-106-04, T-106-05 | `OnThisDayAlbumTest` (time frozen) |
| S-106-06 | I4 / T-106-06, T-106-07 | `PhotoKeysWriteTest` upload |
| S-106-07 | I4 / T-106-06, T-106-07 | `PhotoKeysWriteTest` edit |
| S-106-08 | I4 / T-106-06, T-106-07 | `PhotoKeysWriteTest` takedate |

## Analysis Gate
2026-11-01, agent:
- Specification completeness: pass — FR-106-01 … 04, NFR-106-01 … 03, S-106-01 … 08; no UI change (no mock-up).
- Open questions: pass — Q-106-01 resolved A; no ADR (one derived column, same pattern as `taken_key`).
- Plan alignment: pass — success criteria match the Goals.
- Tasks coverage: pass — every FR has a task, tests staged before code (T-106-01, 04, 06).
- Working agreements: pass — explicit writes, no model events; migration approved by the owner (option C); no dependency; no migration test (backfill checked on the scratch instance).
- Tooling: pass — commands per increment.

## Follow-ups / Backlog
- Untagged, Recent and Unsorted still scan `photos` for their cover and header (`Albums/smart` cold, `Album::head`); empty smart albums recompute their cover on every request (`CachesAlbumUserThumb` caches only a photo).

## Exit Criteria
- T-106-01 … 08 checked; listed test classes green; `php-cs-fixer`, `make phpstan` clean.
- Knowledge map and roadmap updated, drift gate recorded.
Loading
Loading