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
38 changes: 38 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,39 @@ migrations are commands on the same connection.
rebuilds the shell, and a busy server logs many times a second; the log pane
listens to `RunnerLog` for the rest. A test pins this.

### A local database a crash left damaged

The CLI's bundled Postgres keeps the project's database in
`<server>/.serverpod/<mode>/pgdata`. It is created with `initdb --no-sync` and
its `postgresql.conf` is rewritten unflushed on every start, so a computer
that crashes or loses power soon after a project's first start can come back
with those files at full length and filled with zeros. Postgres then refuses
the configuration on every start (`syntax error … line 1, near token ""`) and
the CLI never recreates the cluster. First seen on a Windows machine,
2026-12-01; `specs/embedded_postgres_zeroed_conf_report.md` has the analysis
and the report filed with Serverpod (serverpod/serverpod#6081; #5996 there is
an earlier case).

- **`findDamagedDatabases` (`runner/runner_postgres.dart`) runs after every
failure** (`_fail`), whatever failed: a data directory is damaged when one
of its text files (`PG_VERSION`, `postgresql.conf`, `pg_hba.conf`,
`pg_ident.conf`) holds a NUL byte. It reads the disk, not the log, so it does
not depend on the CLI's wording.
- **The status then reads "Database error" and Reset Database replaces Try
Again** (`DatabaseRepairView`, `ui/server_status_bar.dart`): a retry would
fail the same way. `ResetDatabaseDialog` asks first — the data is lost.
- **`resetDatabase()` deletes what `EmbeddedPostgres.reset()` deletes** — the
data directory, `run` beside it, and the pid, log, state and password files
— then starts the server, which runs `initdb` and applies the migrations.
The damage is looked for again at that moment, so an intact database is
never deleted. The next start or stop forgets the damage; a failure finds
it again.
- Only the conventional location is covered. A `database.dataPath` pointing
elsewhere is not read.
- `test/process/database_reset_test.dart` is the controller's side and is
**not** tagged `process`: every start in it fails before a runner exists, so
it opens no socket and runs on the Windows dev laptop.

### The preview URL comes from the runner

- **No fixed port.** `flutter run -d web-server` picks a free one and the runner
Expand Down Expand Up @@ -365,6 +398,11 @@ toggle that used to lead the bar is Logs → Show/Hide Logs.
is `retryStart`, like the icon. They hide while the restart is in flight.
They fold to icon buttons (`FirstThatFits`) rather than claim more than
`minStatusWidth`: the stopped messages are short, which is what leaves room.
The message is capped at what the icon form leaves and ellipsizes past it —
"Database error" is the longest, and overflowed by 8 px in the test font
before the cap.
- **With a damaged local database, Try Again is Reset Database** — see *A
local database a crash left damaged*.

- **It is the only place an operation in flight is shown.** The log's pinned
footer of running operations was dropped once the status named them: the log
Expand Down
24 changes: 24 additions & 0 deletions lib/process/database_repair_view.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import 'package:flutter/foundation.dart';

/// What the toolbar needs to offer a way out of a local database that can no
/// longer start, and nothing that touches a file.
///
/// `ServerpodProcessController` implements this directly, like
/// `FullRestartView`; the status bar imports only this file, so the offer can
/// be drawn and tested without a damaged database on disk.
abstract interface class DatabaseRepairView implements Listenable {
/// The server is stopped and the project's local database is why: its files
/// came back from a crash filled with zeros, so no retry can start it.
bool get databaseIsDamaged;

/// Deletes the damaged local database and starts the server, which creates
/// a new, empty one. Whatever the database held is lost — ask first.
Future<void> resetDatabase();
}

/// Why the database cannot start and what a reset costs, for the status
/// tooltip, the server log and the confirmation.
const kDatabaseDamagedExplanation =
"This project's local database is damaged and cannot start. Its files "
'were not fully saved to disk, which happens when the computer crashes or '
'loses power while the database is being set up.';
101 changes: 100 additions & 1 deletion lib/process/serverpod_process.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart';

import '../platform/host.dart';
import '../preview/preview_phase.dart';
import '../process/database_repair_view.dart';
import '../process/full_restart_view.dart';
import '../process/project_ready_view.dart';
import '../process/registration_code.dart';
Expand Down Expand Up @@ -83,7 +84,11 @@ final _runnerPid = RegExp(r'\(pid (\d+)\)');
/// to. [runnerWatchInterval] is how often App Studio looks for one then, and
/// it attaches as it would on opening the project.
class ServerpodProcessController extends ChangeNotifier
implements FullRestartView, ProjectReadyView, RunnerActionsView {
implements
DatabaseRepairView,
FullRestartView,
ProjectReadyView,
RunnerActionsView {
ServerpodProcessController({
required this.toolchains,
required this.session,
Expand Down Expand Up @@ -134,6 +139,11 @@ class ServerpodProcessController extends ChangeNotifier
Completer<void>? _stopDone;
String? _error;

/// The local databases the last failure found damaged
/// ([findDamagedDatabases]), until the next start or stop.
List<String> _damagedDatabases = const [];
bool _resettingDatabase = false;

String? _serverDir;
RunnerLaunch? _launch;
RunnerClient? _client;
Expand Down Expand Up @@ -172,6 +182,15 @@ class ServerpodProcessController extends ChangeNotifier
case ProcessState.stopping:
return const ServerStatus.busy('Stopping the server');
case ProcessState.idle:
if (_resettingDatabase) {
return const ServerStatus.busy('Resetting the database');
}
if (databaseIsDamaged) {
return const ServerStatus.stopped(
'Database error',
detail: kDatabaseDamagedExplanation,
);
}
return _error == null
? const ServerStatus.stopped('Stopped')
: ServerStatus.stopped('Stopped', detail: _error);
Expand Down Expand Up @@ -350,6 +369,9 @@ class ServerpodProcessController extends ChangeNotifier
@override
bool get isStopped => state == ProcessState.idle;

@override
bool get databaseIsDamaged => _damagedDatabases.isNotEmpty;

@override
bool get canHotRestart =>
_client != null && _stage == RunnerStage.running && !_stopping;
Expand Down Expand Up @@ -402,6 +424,7 @@ class ServerpodProcessController extends ChangeNotifier
_stopWatching();
_starting = true;
_error = null;
_damagedDatabases = const [];
_registrationCode = null;
_launchRequested = false;
_runnerLaunchesApps = false;
Expand Down Expand Up @@ -750,6 +773,52 @@ class ServerpodProcessController extends ChangeNotifier
}
}

/// Deletes the local database a crash left unable to start, then starts the
/// server, which creates it again and applies the project's migrations.
///
/// Only ever what [findDamagedDatabases] reports, and only while the server
/// is stopped. The caller has asked the user: the data is lost.
@override
Future<void> resetDatabase() async {
final projectPath = session.projectPath;
final serverDir = _serverDir;
if (projectPath == null ||
serverDir == null ||
!databaseIsDamaged ||
isTransitioning) {
return;
}

_restarting = true;
_resettingDatabase = true;
_stopWatching();
notifyListeners();
try {
// None should be running on a database that cannot start, but the
// Windows runner has left one behind before, and its files must not be
// deleted under it.
if (currentHost.isWindows) {
await stopOrphanedPostgres(
serverDir,
isAlive: const ProcessKiller().isAlive,
settle: Duration.zero,
);
}
await resetDamagedDatabases(serverDir);
_resettingDatabase = false;
if (session.projectPath != projectPath) return;
await start();
} catch (e) {
_resettingDatabase = false;
_fail('The local database could not be reset. $e');
_watchForRunner();
} finally {
_resettingDatabase = false;
_restarting = false;
notifyListeners();
}
}

/// Hard-reloads the CEF preview, ignoring its cache.
///
/// One reload path, and it is always the hard one — a plain navigation
Expand Down Expand Up @@ -812,6 +881,7 @@ class ServerpodProcessController extends ChangeNotifier
} finally {
_resetRunner();
_error = null;
_damagedDatabases = const [];
_stopping = false;
notifyListeners();
done.complete();
Expand Down Expand Up @@ -912,6 +982,35 @@ class ServerpodProcessController extends ChangeNotifier
_error = message;
log.addLocal(message, level: RunnerLogLevel.error);
notifyListeners();
unawaited(_lookForDatabaseDamage());
}

/// After a failure, checks whether the project's local database is beyond a
/// retry: the status then says so and offers a reset in place of Try Again,
/// which would only fail the same way.
///
/// Whatever failed, not only a start that names the database: a database in
/// this state cannot start, so it is the next failure if it is not this one.
Future<void> _lookForDatabaseDamage() async {
final serverDir = _serverDir;
if (serverDir == null) return;
final epoch = _epoch;
final damaged = await findDamagedDatabases(serverDir);
if (damaged.isEmpty ||
epoch != _epoch ||
serverDir != _serverDir ||
_error == null ||
listEquals(damaged, _damagedDatabases)) {
return;
}
_damagedDatabases = damaged;
log.addLocal(
'$kDatabaseDamagedExplanation Resetting it deletes it and creates a '
'new, empty one.',
level: RunnerLogLevel.error,
error: damaged.join('\n'),
);
notifyListeners();
}

/// Called by the preview pane once the Flutter app's `main()` is running in
Expand Down
103 changes: 99 additions & 4 deletions lib/runner/runner_postgres.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import 'dart:io';

import 'package:path/path.dart' as p;

// The project's own Postgres — the bundled one the Serverpod CLI runs on the
// server's `.serverpod\<mode>\pgdata` — where App Studio has to step in: one
// a Windows runner stop left running, and one a crash left unable to start.

/// Windows only: stops the project's own Postgres when the runner App Studio
/// just stopped left it running.
///
Expand All @@ -27,7 +31,7 @@ Future<void> stopOrphanedPostgres(
}) async {
final runner = run ?? (exe, args) => Process.run(exe, args);
try {
for (final dataDir in await _dataDirectories(serverDir)) {
for (final dataDir in await _dataDirectories(serverDir, running: true)) {
final pid = await _postmasterPid(dataDir);
if (pid == null) continue;
final waited = Stopwatch()..start();
Expand All @@ -46,16 +50,107 @@ Future<void> stopOrphanedPostgres(
}
}

/// The project's local databases that a crash left unable to start: every
/// data directory holding a text file with NUL bytes in it.
///
/// Serverpod creates the cluster with `initdb --no-sync` and then rewrites
/// `postgresql.conf` without flushing it. A computer that crashes or loses
/// power before the OS has written those files out comes back with them at
/// their full length and filled with zeros. Postgres then refuses the
/// configuration on every start — `syntax error in file "…/postgresql.conf"
/// line 1, near token ""` — so trying again cannot help: the cluster has to
/// be created again ([resetDamagedDatabases]). Seen on Windows after the
/// first start of a new project; specs/embedded_postgres_zeroed_conf_report.md.
///
/// Only files that are text, and so never hold a NUL while intact, are read.
/// Never throws: a directory that cannot be read is not reported.
Future<List<String>> findDamagedDatabases(String serverDir) async {
final damaged = <String>[];
try {
for (final dataDir in await _dataDirectories(serverDir)) {
for (final name in _clusterTextFiles) {
if (await _holdsNul(File(p.join(dataDir, name)))) {
damaged.add(dataDir);
break;
}
}
}
} on FileSystemException {
// Whatever was found before the listing failed still stands.
}
return damaged;
}

/// Deletes every damaged local database of [serverDir] and returns their data
/// directories. The next start creates each one again, empty, and applies the
/// project's migrations to it.
///
/// Removes what `EmbeddedPostgres.reset()` in `serverpod_embedded_postgres`
/// removes — the data directory, the `run` directory beside it, and the
/// cluster's pid, log, state and password files — and nothing else of the
/// mode's folder. An intact database is never touched: the damage is looked
/// for again here, not taken from an earlier look.
///
/// Call with the server stopped. Throws a [FileSystemException] when
/// something cannot be deleted.
Future<List<String>> resetDamagedDatabases(String serverDir) async {
final damaged = await findDamagedDatabases(serverDir);
for (final dataDir in damaged) {
final root = p.dirname(dataDir);
for (final path in [dataDir, p.join(root, 'run')]) {
final directory = Directory(path);
if (await directory.exists()) await directory.delete(recursive: true);
}
for (final name in _clusterSidecarFiles) {
final file = File(p.join(root, name));
if (await file.exists()) await file.delete();
}
}
return damaged;
}

/// Files of a cluster that are plain text.
const _clusterTextFiles = [
'PG_VERSION',
'postgresql.conf',
'pg_hba.conf',
'pg_ident.conf',
];

/// What `serverpod_embedded_postgres` keeps beside the data directory.
const _clusterSidecarFiles = [
'postgres.pid',
'postgres.log',
'postgres.log.1',
'embedded_postgres_state.json',
'postgres.password',
];

Future<bool> _holdsNul(File file) async {
try {
return (await file.readAsBytes()).contains(0);
} on FileSystemException {
return false;
}
}

/// `<server>\.serverpod\<mode>\pgdata` for every mode a runner has used —
/// `development` in today's template, `dev` in older ones.
Future<List<String>> _dataDirectories(String serverDir) async {
/// `development` in today's template, `dev` in older ones. With [running],
/// only those a postmaster has left its pid file in.
Future<List<String>> _dataDirectories(
String serverDir, {
bool running = false,
}) async {
final root = Directory(p.join(serverDir, '.serverpod'));
if (!await root.exists()) return const [];
final found = <String>[];
await for (final mode in root.list()) {
if (mode is! Directory) continue;
final data = p.join(mode.path, 'pgdata');
if (await File(p.join(data, 'postmaster.pid')).exists()) found.add(data);
final exists = running
? File(p.join(data, 'postmaster.pid')).exists()
: Directory(data).exists();
if (await exists) found.add(data);
}
return found;
}
Expand Down
Loading
Loading