feat(places): record which search result was picked, on this instance only

The corpus behind "is our own index good enough to replace Nominatim".
When somebody searches and then picks a result, the client posts the query,
the rank and the pick. Nothing else: no user, no trip, no session, and
coordinates only to three decimals.

Deliberately decoupled from the search endpoint. Correlating a response
with a later pick would mean handing out a ticket on POST /api/maps/search
and threading it through all fifteen call sites; the client already holds
everything the row needs at the moment of the pick.

Evaluation happens offline afterwards: export the corpus, run it against a
candidate index, count how often the pick came back in the top five. That
is why collection can start before such an index exists, which is the whole
point, because the corpus needs weeks of real use and the index needs a
server, and those two waits should not be serial.

Off unless an admin switches it on, and it reads === 'true' rather than
!== 'false'. The three older places switches fail open because a migration
backfilled a row for installs already using them; nothing uses this one, so
an instance that upgrades and never visits the admin panel logs nothing.

Reading is admin only, retention is 180 days, and the switch state is on the
unauthenticated app-config endpoint on purpose: whether an instance records
what its users search for is something a visitor may know before logging in.
This commit is contained in:
Maurice
2026-09-05 23:15:51 +02:00
committed by Maurice
parent 0a2fa32fc1
commit b3d69aa760
49 changed files with 1385 additions and 16 deletions
+35
View File
@@ -4257,6 +4257,41 @@ function runMigrations(db: Database.Database): void {
db.exec('ALTER TABLE journey_entries ADD COLUMN stats_excluded INTEGER NOT NULL DEFAULT 0');
}
},
/**
* Place shadow log: which search result a user actually picked.
*
* The corpus behind "would our own index have found that too". No user id,
* no trip, no session and no result list — the evaluation compares a query
* against a pick, and anything beyond that would be collecting for its own
* sake on an instance that promises not to.
*
* The table is created regardless of the switch: the switch decides whether
* rows are written, and a schema that appears only when a feature is
* enabled is a schema that differs between installs.
*
* Appended LAST: the array is index-addressed against schema_version.
*/
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS place_shadow_picks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
query TEXT NOT NULL,
lang TEXT,
bias_lat REAL,
bias_lng REAL,
source TEXT NOT NULL,
live_rank INTEGER NOT NULL,
live_count INTEGER NOT NULL,
picked_name TEXT NOT NULL,
picked_lat REAL NOT NULL,
picked_lng REAL NOT NULL,
picked_place_id TEXT
)
`);
// Retention deletes by age, the export pages by id.
db.exec('CREATE INDEX IF NOT EXISTS idx_place_shadow_created ON place_shadow_picks(created_at)');
},
];
if (currentVersion < migrations.length) {
+10
View File
@@ -186,6 +186,16 @@ export class AddonsService {
getPlacesDetails() { return this.readFlag('places_details_enabled'); }
updatePlacesDetails(enabled: boolean) { return this.writeFlag('places_details_enabled', enabled); }
/**
* The shadow log, fail-CLOSED like the three above but for the opposite
* reason: they read `=== 'true'` because a migration backfilled a row for
* installs that were already using the feature. Nothing is using this one,
* so there is nothing to backfill and an absent row correctly means off.
* PlaceShadowService.enabled() reads the same key the same way.
*/
getPlaceShadow() { return this.readFlag('place_shadow_enabled'); }
updatePlaceShadow(enabled: boolean) { return this.writeFlag('place_shadow_enabled', enabled); }
/**
* Enrichment reads fail-OPEN, unlike the three switches above.
*
+10
View File
@@ -233,6 +233,16 @@ export class AdminController {
return result;
}
@Get('place-shadow')
getPlaceShadow() { return this.addons.getPlaceShadow(); }
@Put('place-shadow')
updatePlaceShadow(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = this.addons.updatePlaceShadow(body.enabled);
this.audit.writeAudit({ userId: user.id, action: 'admin.place_shadow', ip: getClientIp(req), details: { enabled: result.enabled } });
return result;
}
@Get('places-enrich')
getPlacesEnrich() { return this.addons.getPlacesEnrich(); }
+2 -1
View File
@@ -20,6 +20,7 @@ import { ManagedExtModule } from './managed/managed-ext.module';
import { MapsModule } from './maps/maps.module';
import { GeoModule } from './geo/geo.module';
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
import { PlaceShadowModule } from './place-shadow/place-shadow.module';
import { CategoriesModule } from './categories/categories.module';
import { TagsModule } from './tags/tags.module';
import { NotificationsModule } from './notifications/notifications.module';
@@ -76,7 +77,7 @@ import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
* migrated.
*/
@Module({
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, PublicApiModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, PublicApiModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, PlaceShadowModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
providers: [
// Default-deny: a route is authenticated unless it carries @Public() or
// @OptionalAuth(), or declares its own @UseGuards chain. Protection used to
+6
View File
@@ -285,6 +285,11 @@ export class AuthService {
const placesDetailsEnabled = placesDetailsSetting !== 'false';
const placesEnrichSetting = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'places_enrich_enabled'")?.value;
const placesEnrichEnabled = placesEnrichSetting !== 'false';
// Fail-closed, and deliberately on this unauthenticated endpoint: whether an
// instance records what its users search for is something a visitor is
// entitled to know before logging in, not a detail to keep behind the door.
const placeShadowSetting = this.db.get<{ value: string }>("SELECT value FROM app_settings WHERE key = 'place_shadow_enabled'")?.value;
const placeShadowEnabled = placeShadowSetting === 'true';
const setupComplete = userCount > 0 && !this.db.get("SELECT id FROM users WHERE role = 'admin' AND must_change_password = 1 LIMIT 1");
return {
@@ -333,6 +338,7 @@ export class AuthService {
places_autocomplete_enabled: placesAutocompleteEnabled,
places_details_enabled: placesDetailsEnabled,
places_enrich_enabled: placesEnrichEnabled,
place_shadow_enabled: placeShadowEnabled,
permissions: authenticatedUser ? this.permissions.getAllPermissions() : undefined,
// Case-sensitive on purpose (legacy parity).
dev_mode: readEnv().app.nodeEnv === 'development',
@@ -0,0 +1,54 @@
import { Body, Controller, Delete, Get, HttpCode, Post, Query, UseGuards } from '@nestjs/common';
import type {
PlaceShadowExportResult,
PlaceShadowPickResult,
PlaceShadowSummaryResult,
} from '@trek/shared';
import { AdminGuard } from '../auth/admin.guard';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { PlaceShadowPickDto } from './place-shadow.dto';
import { PlaceShadowService } from './place-shadow.service';
/**
* /api/place-shadow — the local corpus of "what was searched, what was picked".
*
* Writing is open to any signed-in user because any signed-in user is the one
* doing the picking; reading is admin only, because the corpus is everybody's
* searches and the person entitled to see that is the person running the
* instance. Nothing here leaves the instance on its own.
*/
@Controller('api/place-shadow')
@UseGuards(JwtAuthGuard)
export class PlaceShadowController {
constructor(private readonly shadow: PlaceShadowService) {}
/**
* 200 with `{ recorded: false }` when the log is off, rather than a 403.
* The client posts this and moves on; a rejection would be a permanent error
* in the console of every install that never switched the log on.
*/
@Post('pick')
@HttpCode(200)
pick(@Body() body: PlaceShadowPickDto): PlaceShadowPickResult {
return { recorded: this.shadow.record(body) };
}
@Get('summary')
@UseGuards(JwtAuthGuard, AdminGuard)
summary(): PlaceShadowSummaryResult {
return this.shadow.summary();
}
@Get('export')
@UseGuards(JwtAuthGuard, AdminGuard)
export(@Query('after') after?: string): PlaceShadowExportResult {
const parsed = Number(after);
return this.shadow.export(Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined);
}
@Delete()
@UseGuards(JwtAuthGuard, AdminGuard)
clear(): { removed: number } {
return { removed: this.shadow.clear() };
}
}
@@ -0,0 +1,9 @@
import { createZodDto } from 'nestjs-zod';
import { placeShadowPickRequestSchema } from '@trek/shared';
/**
* Zod-pipe wrapper for the shadow log body. Same pattern as every other write
* endpoint: the contract lives in @trek/shared, the class exists so a
* controller parameter can be typed with it.
*/
export class PlaceShadowPickDto extends createZodDto(placeShadowPickRequestSchema) {}
@@ -0,0 +1,37 @@
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { logError, logInfo } from '../audit/audit-log.logger';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { PlaceShadowService } from './place-shadow.service';
/**
* Nightly retention for the shadow corpus.
*
* Runs even when the log is switched off, on purpose: switching it off should
* also let what it already collected age out, rather than freezing the rows in
* place until somebody remembers to press the wipe button.
*
* 3:40 AM keeps it clear of the 3:00 idempotency purge and the backup window.
*/
@Injectable()
export class PlaceShadowRetentionJob implements OnApplicationBootstrap {
constructor(
private readonly shadow: PlaceShadowService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
this.registrar.register('place-shadow-retention', '40 3 * * *', () => this.tick());
}
tick(): void {
try {
const removed = this.shadow.purgeExpired();
if (removed > 0) {
logInfo(`Place shadow retention: removed ${removed} expired row(s)`);
}
} catch (err: unknown) {
logError(`Place shadow retention: ${err instanceof Error ? err.message : err}`);
}
}
}
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { PlaceShadowController } from './place-shadow.controller';
import { PlaceShadowRetentionJob } from './place-shadow.job';
import { PlaceShadowService } from './place-shadow.service';
/**
* Place shadow log. Registered in AppModule; exports the service so the admin
* surface can read the summary without going through HTTP.
*/
@Module({
imports: [SchedulingModule],
controllers: [PlaceShadowController],
providers: [PlaceShadowService, PlaceShadowRetentionJob],
exports: [PlaceShadowService],
})
export class PlaceShadowModule {}
@@ -0,0 +1,196 @@
import { Injectable } from '@nestjs/common';
import type {
PlaceShadowExportResult,
PlaceShadowPickRequest,
PlaceShadowRow,
PlaceShadowSummaryResult,
} from '@trek/shared';
import { DatabaseService } from '../database/database.service';
/** Rows older than this are removed nightly. */
export const RETENTION_DAYS = 180;
/** Cap on one export page, so a large corpus cannot be pulled in one response. */
export const EXPORT_PAGE_SIZE = 2000;
/**
* Coordinates are stored at three decimals, matching what the client sends for
* the bias. That is about 100 m, which is far finer than any ranking decision
* and far coarser than a home address.
*/
const COORD_DECIMALS = 3;
function round(value: number, decimals = COORD_DECIMALS): number {
const f = 10 ** decimals;
return Math.round(value * f) / f;
}
interface DbRow {
id: number;
created_at: string;
query: string;
lang: string | null;
bias_lat: number | null;
bias_lng: number | null;
source: string;
live_rank: number;
live_count: number;
picked_name: string;
picked_lat: number;
picked_lng: number;
picked_place_id: string | null;
}
function toRow(r: DbRow): PlaceShadowRow {
return {
id: r.id,
createdAt: r.created_at,
query: r.query,
lang: r.lang,
biasLat: r.bias_lat,
biasLng: r.bias_lng,
source: r.source,
liveRank: r.live_rank,
liveCount: r.live_count,
pickedName: r.picked_name,
pickedLat: r.picked_lat,
pickedLng: r.picked_lng,
pickedPlaceId: r.picked_place_id,
};
}
/**
* Records which search result a user actually picked, so a different index can
* be judged against real queries later.
*
* Off unless an admin switches it on, and it reads `=== 'true'` rather than
* `!== 'false'`: an absent row means off. That is the opposite of the three
* older places switches, which had to fail open because installs were already
* using those features when the switches arrived. Nothing is using this one, so
* the safe default is the silent one — an instance that upgrades and never
* visits the admin panel logs nothing.
*/
@Injectable()
export class PlaceShadowService {
constructor(private readonly db: DatabaseService) {}
enabled(): boolean {
const row = this.db.get<{ value: string }>(
"SELECT value FROM app_settings WHERE key = 'place_shadow_enabled'",
);
return row?.value === 'true';
}
/**
* Returns whether the row was written. A disabled log is not an error: the
* client fires this and forgets it, and a 403 in the console every time
* somebody adds a place would be noise about a feature that is off on
* purpose.
*/
record(pick: PlaceShadowPickRequest): boolean {
if (!this.enabled()) return false;
// A rank outside the returned list means the client and the server disagree
// about what was on screen. Storing it would poison the very number the
// corpus exists to produce, so the row is dropped instead.
if (pick.liveRank >= pick.liveCount) return false;
this.db.run(
`INSERT INTO place_shadow_picks
(query, lang, bias_lat, bias_lng, source, live_rank, live_count,
picked_name, picked_lat, picked_lng, picked_place_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
pick.query,
pick.lang ?? null,
pick.biasLat === undefined ? null : round(pick.biasLat),
pick.biasLng === undefined ? null : round(pick.biasLng),
pick.source,
pick.liveRank,
pick.liveCount,
pick.pickedName,
round(pick.pickedLat),
round(pick.pickedLng),
pick.pickedPlaceId ?? null,
);
return true;
}
/**
* One page of the corpus, oldest first. `after` is the last id of the
* previous page; paging by id rather than by offset keeps the pages stable
* while new rows arrive underneath.
*/
export(after?: number, limit = EXPORT_PAGE_SIZE): PlaceShadowExportResult {
const size = Math.min(Math.max(1, limit), EXPORT_PAGE_SIZE);
const rows = this.db.all<DbRow>(
`SELECT * FROM place_shadow_picks
WHERE id > ?
ORDER BY id
LIMIT ?`,
after ?? 0,
size + 1,
);
const page = rows.slice(0, size);
return {
version: 1,
generatedAt: new Date().toISOString(),
rows: page.map(toRow),
nextAfter: rows.length > size && page.length > 0 ? page[page.length - 1].id : null,
};
}
summary(): PlaceShadowSummaryResult {
const enabled = this.enabled();
const totals = this.db.get<{ total: number; oldest: string | null; newest: string | null }>(
'SELECT COUNT(*) AS total, MIN(created_at) AS oldest, MAX(created_at) AS newest FROM place_shadow_picks',
);
const total = totals?.total ?? 0;
const bySource = this.db.all<{ source: string; count: number }>(
`SELECT source, COUNT(*) AS count FROM place_shadow_picks
GROUP BY source ORDER BY count DESC`,
);
// Buckets rather than a mean: the question is "did the user find it near
// the top", and an average rank is dragged around by the rare query that
// scrolled to result 40.
const ranks = this.db.all<{ live_rank: number; count: number }>(
'SELECT live_rank, COUNT(*) AS count FROM place_shadow_picks GROUP BY live_rank',
);
const counted = (test: (rank: number) => boolean): number =>
ranks.filter(r => test(r.live_rank)).reduce((sum, r) => sum + r.count, 0);
const topOne = counted(r => r === 0);
const topFive = counted(r => r < 5);
return {
enabled,
total,
oldest: totals?.oldest ?? null,
newest: totals?.newest ?? null,
retentionDays: RETENTION_DAYS,
bySource,
liveRankBuckets: [
{ bucket: '1', count: topOne },
{ bucket: '2-5', count: counted(r => r >= 1 && r < 5) },
{ bucket: '6-10', count: counted(r => r >= 5 && r < 10) },
{ bucket: '11+', count: counted(r => r >= 10) },
],
liveTopOneShare: total ? topOne / total : 0,
liveTopFiveShare: total ? topFive / total : 0,
};
}
/** Admin wipe. Returns how many rows went. */
clear(): number {
return this.db.run('DELETE FROM place_shadow_picks').changes;
}
/** Nightly retention. Returns how many rows went. */
purgeExpired(retentionDays = RETENTION_DAYS): number {
return this.db.run(
`DELETE FROM place_shadow_picks
WHERE created_at < datetime('now', ?)`,
`-${retentionDays} days`,
).changes;
}
}