From ed1f46c57cbb64e1692eea04e9c9271eca82f402 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Thu, 3 Dec 2026 14:58:21 +0100 Subject: [PATCH 1/2] fix: Offer to reset a local database that a crash left unable to start. A new project on Windows stopped being able to start its server: Postgres refused postgresql.conf on every start ("syntax error ... line 1, near token """), and Try Again failed the same way each time. That message is what Postgres prints for a configuration file that starts with NUL bytes. The Serverpod CLI creates the cluster with initdb --no-sync and rewrites the file unflushed, so a computer that crashes or loses power soon after a project's first start can come back with it zero-filled, and the CLI never recreates the cluster. - After any failed start or runner exit, findDamagedDatabases reads the cluster's text files under .serverpod//pgdata and reports a data directory when one of them holds a NUL byte. - The status then reads "Database error", the log explains what happened, and Reset Database takes Try Again's place. It asks first, deletes what EmbeddedPostgres.reset() deletes, and starts the server, which creates the database again and applies the migrations. The damage is looked for again at that moment, so an intact database is never deleted. - A stopped status message is capped at what the actions' icon form leaves, so a longer one ellipsizes instead of overflowing the toolbar. - specs/embedded_postgres_zeroed_conf_report.md has the analysis and the report for Serverpod. Only the zero-filled postgresql.conf was reproduced, with the bundled Postgres parsing a test file; that the affected machine's file is zero-filled is inferred from its error message. The reset was tested against files in a scratch project, not against a real cluster and runner. The process-tagged controller tests were not run on the Windows dev laptop. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 37 ++++ lib/process/database_repair_view.dart | 24 +++ lib/process/serverpod_process.dart | 101 ++++++++- lib/runner/runner_postgres.dart | 103 ++++++++- lib/ui/reset_database_dialog.dart | 53 +++++ lib/ui/server_status_bar.dart | 104 ++++++--- lib/ui/studio_shell.dart | 1 + lib/ui/studio_toolbar.dart | 6 + specs/embedded_postgres_zeroed_conf_report.md | 199 ++++++++++++++++++ test/process/database_reset_test.dart | 174 +++++++++++++++ test/runner/runner_postgres_test.dart | 102 +++++++++ test/ui/studio_toolbar_test.dart | 71 +++++++ widgetbook/fakes/project.dart | 19 ++ widgetbook/studio_window.dart | 4 + widgetbook/use_cases/project.dart | 28 +++ 15 files changed, 989 insertions(+), 37 deletions(-) create mode 100644 lib/process/database_repair_view.dart create mode 100644 lib/ui/reset_database_dialog.dart create mode 100644 specs/embedded_postgres_zeroed_conf_report.md create mode 100644 test/process/database_reset_test.dart diff --git a/AGENTS.md b/AGENTS.md index 9fded2c..3c6bbf6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -203,6 +203,38 @@ 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 +`/.serverpod//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 for Serverpod. + +- **`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 @@ -365,6 +397,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 diff --git a/lib/process/database_repair_view.dart b/lib/process/database_repair_view.dart new file mode 100644 index 0000000..5a47516 --- /dev/null +++ b/lib/process/database_repair_view.dart @@ -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 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.'; diff --git a/lib/process/serverpod_process.dart b/lib/process/serverpod_process.dart index 324062d..0d9790c 100644 --- a/lib/process/serverpod_process.dart +++ b/lib/process/serverpod_process.dart @@ -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'; @@ -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, @@ -134,6 +139,11 @@ class ServerpodProcessController extends ChangeNotifier Completer? _stopDone; String? _error; + /// The local databases the last failure found damaged + /// ([findDamagedDatabases]), until the next start or stop. + List _damagedDatabases = const []; + bool _resettingDatabase = false; + String? _serverDir; RunnerLaunch? _launch; RunnerClient? _client; @@ -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); @@ -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; @@ -402,6 +424,7 @@ class ServerpodProcessController extends ChangeNotifier _stopWatching(); _starting = true; _error = null; + _damagedDatabases = const []; _registrationCode = null; _launchRequested = false; _runnerLaunchesApps = false; @@ -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 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 @@ -812,6 +881,7 @@ class ServerpodProcessController extends ChangeNotifier } finally { _resetRunner(); _error = null; + _damagedDatabases = const []; _stopping = false; notifyListeners(); done.complete(); @@ -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 _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 diff --git a/lib/runner/runner_postgres.dart b/lib/runner/runner_postgres.dart index 81b95e3..25208ca 100644 --- a/lib/runner/runner_postgres.dart +++ b/lib/runner/runner_postgres.dart @@ -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\\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. /// @@ -27,7 +31,7 @@ Future 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(); @@ -46,16 +50,107 @@ Future 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> findDamagedDatabases(String serverDir) async { + final damaged = []; + 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> 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 _holdsNul(File file) async { + try { + return (await file.readAsBytes()).contains(0); + } on FileSystemException { + return false; + } +} + /// `\.serverpod\\pgdata` for every mode a runner has used — -/// `development` in today's template, `dev` in older ones. -Future> _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> _dataDirectories( + String serverDir, { + bool running = false, +}) async { final root = Directory(p.join(serverDir, '.serverpod')); if (!await root.exists()) return const []; final found = []; 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; } diff --git a/lib/ui/reset_database_dialog.dart b/lib/ui/reset_database_dialog.dart new file mode 100644 index 0000000..808cd6f --- /dev/null +++ b/lib/ui/reset_database_dialog.dart @@ -0,0 +1,53 @@ +import 'package:flutter/material.dart'; +import 'package:shad/shad.dart'; + +import '../process/database_repair_view.dart'; +import '../widgets/app_dialog.dart'; +import '../widgets/dialog_body.dart'; + +/// Asks, then resets the project's damaged local database +/// ([DatabaseRepairView.resetDatabase]). Nothing is deleted on a cancel. +Future confirmDatabaseReset( + BuildContext context, + DatabaseRepairView database, +) async { + final confirmed = await showAppDialog( + context: context, + builder: (context) => const ResetDatabaseDialog(), + ); + if (!(confirmed ?? false)) return; + await database.resetDatabase(); +} + +/// Asks before deleting a local database that can no longer start. +/// +/// It says what happened and what the reset costs. There is no way to keep +/// the data — the files that hold it are the damaged ones — so the choice is +/// only whether to do it now. +class ResetDatabaseDialog extends StatelessWidget { + const ResetDatabaseDialog({super.key}); + + @override + Widget build(BuildContext context) { + return ShadDialog.alert( + title: const Text('Reset the local database?'), + description: const Text( + '$kDatabaseDamagedExplanation\n\n' + 'Resetting deletes it and creates a new, empty one when the server ' + 'starts. Any data stored in it is lost. Your code and migrations are ' + 'not changed.', + ), + actions: [ + ShadButton.outline( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + ShadButton.destructive( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Reset Database'), + ), + ], + child: const DialogBody(), + ); + } +} diff --git a/lib/ui/server_status_bar.dart b/lib/ui/server_status_bar.dart index 5e0a50e..7975501 100644 --- a/lib/ui/server_status_bar.dart +++ b/lib/ui/server_status_bar.dart @@ -1,12 +1,15 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:shad/shad.dart'; +import '../process/database_repair_view.dart'; import '../process/full_restart_view.dart'; import '../runner/server_status.dart'; import '../theme/app_theme.dart'; import '../widgets/first_that_fits.dart'; +import 'reset_database_dialog.dart'; import 'server_status_indicator.dart'; /// The toolbar's status, with a way out beside it while the server is down: @@ -18,6 +21,11 @@ import 'server_status_indicator.dart'; /// then are why, and another go. Both already existed (Logs → Show Logs, the /// Full Restart icon), but neither says so next to the red square. /// +/// **Reset Database takes Try Again's place when the local database is +/// damaged** ([DatabaseRepairView]): another go would fail the same way, and +/// the reset — behind a confirmation, since it deletes the data — is the go +/// that can work. +/// /// The buttons fold to icons when the status area is too narrow for their /// labels, so they fit in the [StudioToolbar.minStatusWidth] the toolbar keeps /// for the status in every state. The stopped messages are all short, which @@ -27,11 +35,13 @@ class ServerStatusBar extends StatelessWidget { super.key, required this.status, required this.process, + required this.database, required this.onViewLogs, }); final ServerStatusView status; final FullRestartView process; + final DatabaseRepairView database; final VoidCallback onViewLogs; @override @@ -39,56 +49,86 @@ class ServerStatusBar extends StatelessWidget { final indicator = ServerStatusIndicator(status: status); return ListenableBuilder( - listenable: Listenable.merge([status, process]), + listenable: Listenable.merge([status, process, database]), builder: (context, _) { final stopped = status.serverStatus.kind == ServerStatusKind.stopped && !process.isTransitioning; - final onTryAgain = - process.canRestart ? () => unawaited(process.restart()) : null; + final damaged = database.databaseIsDamaged; + final retry = damaged + ? () => unawaited(confirmDatabaseReset(context, database)) + : () => unawaited(process.restart()); + final onRetry = process.canRestart ? retry : null; + final retryLabel = damaged ? 'Reset Database' : 'Try Again'; + final retryIcon = + damaged ? LucideIcons.databaseBackup : LucideIcons.rotateCcw; - return Row( - mainAxisSize: MainAxisSize.min, - children: [ - // Always the same slot, so the indicator keeps its state when the - // actions come and go. Flexible while alone, so a long busy - // message ellipsizes; sized to itself beside the actions, which - // take whatever is left — the stopped messages are all short. - Flexible(flex: stopped ? 0 : 1, child: indicator), - if (stopped) ...[ - const SizedBox(width: 12), + return LayoutBuilder( + builder: (context, constraints) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + // Always the same slot, so the indicator keeps its state when the + // actions come and go. Flexible while alone, so a long busy + // message ellipsizes; sized to itself beside the actions, which + // take whatever is left — the stopped messages are all short. The + // longest, "Database error", still ellipsizes rather than push + // the actions' icon form out of the status's minimum width. Flexible( - child: FirstThatFits( - children: [ - _RecoveryActions( - onViewLogs: onViewLogs, - onTryAgain: onTryAgain, - compact: false, - ), - _RecoveryActions( - onViewLogs: onViewLogs, - onTryAgain: onTryAgain, - compact: true, - ), - ], + flex: stopped ? 0 : 1, + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: stopped + ? math.max( + 0, + constraints.maxWidth - 12 - _compactActionsWidth, + ) + : double.infinity, + ), + child: indicator, ), ), + if (stopped) ...[ + const SizedBox(width: 12), + Flexible( + child: FirstThatFits( + children: [ + for (final compact in const [false, true]) + _RecoveryActions( + onViewLogs: onViewLogs, + onRetry: onRetry, + retryLabel: retryLabel, + retryIcon: retryIcon, + compact: compact, + ), + ], + ), + ), + ], ], - ], + ), ); }, ); } + + /// The two actions as icon buttons, and the gap between them. + static const _compactActionsWidth = 2 * kToolbarIconButtonSize + 8; } class _RecoveryActions extends StatelessWidget { const _RecoveryActions({ required this.onViewLogs, - required this.onTryAgain, + required this.onRetry, + required this.retryLabel, + required this.retryIcon, required this.compact, }); final VoidCallback onViewLogs; - final VoidCallback? onTryAgain; + + /// Try Again, or Reset Database when a retry cannot work. + final VoidCallback? onRetry; + final String retryLabel; + final IconData retryIcon; final bool compact; @override @@ -104,10 +144,10 @@ class _RecoveryActions extends StatelessWidget { ), const SizedBox(width: 8), _action( - label: 'Try Again', - icon: LucideIcons.rotateCcw, + label: retryLabel, + icon: retryIcon, primary: true, - onPressed: onTryAgain, + onPressed: onRetry, ), ], ); diff --git a/lib/ui/studio_shell.dart b/lib/ui/studio_shell.dart index 0965dcd..0748de9 100644 --- a/lib/ui/studio_shell.dart +++ b/lib/ui/studio_shell.dart @@ -163,6 +163,7 @@ class _StudioShellState extends State { tools: widget.toolchains, onManageTools: _openManageTools, process: widget.process, + database: widget.process, actions: widget.process, editors: widget.editors, publisher: widget.cloud, diff --git a/lib/ui/studio_toolbar.dart b/lib/ui/studio_toolbar.dart index 40c6629..de6e9bf 100644 --- a/lib/ui/studio_toolbar.dart +++ b/lib/ui/studio_toolbar.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:shad/shad.dart'; import '../cloud/cloud_publish.dart'; +import '../process/database_repair_view.dart'; import '../process/full_restart_view.dart'; import '../runner/runner_actions_view.dart'; import '../runner/server_status.dart'; @@ -30,6 +31,7 @@ class StudioToolbar extends StatelessWidget { required this.status, required this.tools, required this.process, + required this.database, required this.actions, required this.editors, required this.publisher, @@ -41,6 +43,9 @@ class StudioToolbar extends StatelessWidget { final ServerStatusView status; final ToolsView tools; final FullRestartView process; + + /// Offers a reset beside the status when the local database is damaged. + final DatabaseRepairView database; final RunnerActionsView actions; final ExternalEditorsView editors; final CloudPublisher publisher; @@ -99,6 +104,7 @@ class StudioToolbar extends StatelessWidget { child: ServerStatusBar( status: status, process: process, + database: database, onViewLogs: onViewLogs, ), ), diff --git a/specs/embedded_postgres_zeroed_conf_report.md b/specs/embedded_postgres_zeroed_conf_report.md new file mode 100644 index 0000000..2854429 --- /dev/null +++ b/specs/embedded_postgres_zeroed_conf_report.md @@ -0,0 +1,199 @@ +# Embedded Postgres: a zero-filled `postgresql.conf` — report + +Status: drafted 2026-12-03, **not filed yet**. One report for Serverpod +(GitHub, `serverpod/serverpod`), laid out as the fields of its bug report +form. App Studio's own mitigation is described at the end. + +What is established and what is inferred: + +- **Established:** the error text, from two photos of the failing machine + (2026-12-01); that the bundled Postgres prints exactly that text for a + configuration file whose first byte is NUL, and different text for a BOM or + a UTF-16 file (run on the dev laptop, see *Reproducing the message*); and + what `serverpod_embedded_postgres` 4.1.0 does when it creates and rewrites + the file (read from the package source). +- **Inferred:** that the file was zero-filled by an unclean shutdown. Nobody + has looked at the file's bytes on that machine or confirmed that it + crashed. `Format-Hex -Path \postgresql.conf | Select-Object -First 4` + there would settle it: leading `00` bytes. +- **It has happened before.** serverpod/serverpod#5996 (2026-11-11) is the + same message: Windows, App Studio 0.3.0, a brand-new project on the + Desktop. It was closed by its reporter with no root cause. The hex dump + posted there afterwards starts with `max_connections = 100` and CRLF line + ends, which is not what `initdb` writes (its file starts with a comment + header), so the file had been replaced by then and says nothing about + what was in it when it failed. +- **A suspect for the unclean shutdown: `afunix.sys`.** Two reports, both + new projects on Windows, is a lot for coincidental power cuts. The embedded + Postgres is reached over an AF_UNIX socket by default, on Windows too, and + a process that exits holding a connected AF_UNIX socket can blue-screen + Windows (`specs/windows_afunix_bsod_report.md`). A blue screen in the first + minutes of a new project is exactly the window in which nothing `initdb` + wrote has reached the disk. Unconfirmed: ask whether the machine restarted + by itself or showed a blue screen. + +--- + +## Serverpod — GitHub issue (Bug Report form) + +**Title** + +> Embedded Postgres never starts again once `postgresql.conf` holds NUL bytes (`syntax error … line 1, near token ""`) + +**Describe the bug** + +> On Windows, a new Serverpod 4.1 project can end up with a local (embedded) +> database that never starts again. Every start ends with: +> +> ``` +> The local database did not start successfully. +> +> To use Docker instead, remove `database.dataPath` from the relevant file in `config/`, then try again. +> +> Yikes! It is possible that this error is caused by an internal issue with the Serverpod tooling. […] +> +> CrashedException: postgres exited with code 1 before becoming ready. +> --- postgres log tail (2 lines) --- +> 2026-12-01 13:25:03.042 GMT [9608] LOG: syntax error in file "C:/Users//Desktop/testapp/testapp_server/.serverpod/development/pgdata/postgresql.conf" line 1, near token "" +> 2026-12-01 13:25:03.044 GMT [9608] FATAL: configuration file "C:/Users//Desktop/testapp/testapp_server/.serverpod/development/pgdata/postgresql.conf" contains errors +> --- end log tail --- +> #0 _waitForReady (package:serverpod_embedded_postgres/src/supervisor/supervisor.dart:296:7) +> #1 Supervisor.start (package:serverpod_embedded_postgres/src/supervisor/supervisor.dart:180:7) +> #2 _startSupervisorWithPortRetry (package:serverpod_embedded_postgres/src/embedded_postgres_impl.dart:552:12) +> #3 EmbeddedPostgresImpl._startLocked (package:serverpod_embedded_postgres/src/embedded_postgres_impl.dart:327:22) +> ``` +> +> Retrying never helps. The only way out is to delete +> `.serverpod/development/pgdata` by hand, which nothing in the message +> suggests. This is the second report of this message: #5996 was the same +> (Windows, a brand-new project) and was closed without a root cause. +> +> **What the message means** +> +> `near token ""` on line 1 is what Postgres's configuration lexer prints +> when the file starts with a NUL byte: the token it rejects is `\0`, which +> prints as an empty string. I checked this against the bundled binaries +> (`pg-binaries/16.13.0-r1/windows-x64`) with +> `postgres.exe -D -C port`: +> +> | `postgresql.conf` | Output | +> |---|---| +> | 4096 NUL bytes | `syntax error … line 1, near token ""`, then `contains errors` — identical to the report | +> | 4096 NUL bytes, then a valid block of settings | the same two lines | +> | UTF-8 BOM, then valid text | `syntax error … line 1, near end of line` | +> | UTF-16 LE with BOM | `line 1, near end of line`, then `near token ""` for lines 2, 3, 4… | +> | valid text | prints the port | +> +> So it is not an encoding problem or a hand edit. The two-line log fits a +> file that is NUL bytes followed by valid settings — what +> `reconcilePostgresConf` produces when the file it reads is all zeros (see +> below). A file at its full length and filled with zeros is what NTFS gives +> back when the file's metadata reached the disk and its data did not: after +> a crash, a blue screen, a forced power-off. +> +> **What I could not establish** +> +> I have not seen the file's bytes from the affected machine, and nobody has +> confirmed that it crashed or lost power, so the zero-fill and its cause are +> inferred from the message. If there was no unclean shutdown, something else +> puts NUL bytes at the start of the file and I do not know what. (The hex +> dump posted in #5996 after it was closed starts with +> `max_connections = 100` and CRLF, which is not what `initdb` writes, so the +> file had been replaced by then.) +> +> One candidate for an unclean shutdown on Windows specifically: a process +> that exits while holding a connected AF_UNIX socket can bugcheck in +> `afunix.sys` (0xD1), and the embedded Postgres is reached over an AF_UNIX +> socket by default. A blue screen in the first minutes of a new project +> would leave exactly this state. Not confirmed on either machine. +> +> **Why the cluster is exposed, and why it never recovers** +> +> In `serverpod_embedded_postgres` 4.1.0: +> +> - `ClusterStore.ensureInitialized` runs `initdb` with `--no-sync`, so +> nothing `initdb` writes is flushed. +> - `ClusterStore.reconcilePostgresConf` rewrites `postgresql.conf` with +> `File.writeAsStringSync`, also unflushed, on every start. Postgres's own +> `fsync = on` covers its data files and WAL, not these. +> - `isInitialized` only checks that `PG_VERSION` exists, so `initdb` is not +> run again for a damaged cluster. +> - `reconcilePostgresConf` reads the zeros, finds no managed block and +> appends one. The file is then zeros followed by a valid block, and +> Postgres rejects it at line 1 on every start. + +**To reproduce** + +> Without waiting for a crash: +> +> 1. Create a project and start it once, so +> `/.serverpod/development/pgdata` exists. Stop it. +> 2. Overwrite `pgdata/postgresql.conf` with NUL bytes, e.g. +> `head -c 30000 /dev/zero > postgresql.conf`. +> 3. Start again: the failure above, on this and every later start. + +**Expected behavior** + +> A cluster whose configuration is unreadable is repaired or recreated, or +> at least the error says how to get going again. Some options: +> +> 1. *Make creation durable.* Drop `--no-sync`, or run `initdb --sync-only` +> once after it, and write `postgresql.conf` through a temporary file that +> is flushed and renamed into place. +> 2. *Heal the configuration.* When the text outside the managed block holds +> a NUL, `reconcilePostgresConf` could rebuild the file from the bundle's +> `share/postgresql/postgresql.conf.sample` instead of appending to it. +> 3. *Recreate a cluster that has never worked.* When start fails on a +> cluster that never became ready (no `embedded_postgres_state.json`), so +> holds no data, `reset()` it and try once more. +> 4. *Say what to do.* For a failure whose log tail has +> `postgresql.conf" contains errors`, the "Yikes! … internal issue" text +> and the Docker hint point the wrong way. Naming the data directory and +> saying that deleting it recreates the database would unblock the user. + +**Library version** + +> Serverpod 4.1.0 (`serverpod_embedded_postgres` 4.1.0, going by the line +> numbers in the stack trace), bundled PostgreSQL 16.13 +> (`16.13.0-r1/windows-x64`). The Dart version on the affected machine is +> not known; the lexer check above ran with Dart 3.13.7. + +**Platform information** + +> Windows, x64. The project was created and started from Serverpod App +> Studio, as in #5996. + +**Additional context** + +> App Studio is getting a mitigation: after a failed start it looks for NUL +> bytes in the cluster's text files and offers to reset the local database +> (serverpod/appstudio, branch `fix/damaged-local-database`). + +--- + +## Reproducing the message + +Run on the dev laptop, 2026-12-03, with the bundled +`%LOCALAPPDATA%\serverpod\Cache\pg-binaries\16.13.0-r1\windows-x64\bin\postgres.exe`. +`-C port` only parses the configuration and prints one setting: no server is +started and no socket is opened, so it is safe there. The directory needs +nothing but the `postgresql.conf` under test. A directory named `nul` does +not work on Windows — it is a device name. + +## What App Studio does about it + +`lib/runner/runner_postgres.dart`, `ServerpodProcessController` and +`ui/server_status_bar.dart`: + +- After any failed start or runner exit, `findDamagedDatabases` reads the + cluster's text files (`PG_VERSION`, `postgresql.conf`, `pg_hba.conf`, + `pg_ident.conf`) under `/.serverpod/*/pgdata` and reports a data + directory when one of them holds a NUL byte. +- The status then reads **Database error**, the log gets a plain + explanation, and **Reset Database** takes Try Again's place. It asks first, + then deletes what `EmbeddedPostgres.reset()` deletes and starts the server. +- Only `postgresql.conf` is covered by the test above. The other three files + are included because a NUL in them is damage of the same kind, not because + each failure was reproduced. +- A project whose `database.dataPath` points outside `.serverpod/` is + not covered: App Studio does not read the project's config for it. diff --git a/test/process/database_reset_test.dart b/test/process/database_reset_test.dart new file mode 100644 index 0000000..0c3ea89 --- /dev/null +++ b/test/process/database_reset_test.dart @@ -0,0 +1,174 @@ +import 'dart:io'; + +import 'package:appstudio/preview/preview_phase.dart'; +import 'package:appstudio/process/database_repair_view.dart'; +import 'package:appstudio/process/serverpod_process.dart'; +import 'package:appstudio/runner/runner_ownership.dart'; +import 'package:appstudio/runner/runner_protocol.dart'; +import 'package:appstudio/runner/server_status.dart'; +import 'package:appstudio/session/project_session.dart'; +import 'package:appstudio/toolchain/toolchain.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../support/fake_runner.dart'; +import '../support/toolchain_support.dart'; + +/// The controller's side of a local database a crash left unable to start: +/// noticing it after a failure, saying so, and resetting it. +/// +/// Not tagged `process`, unlike the rest of the controller's tests: every +/// start here fails before a runner exists, so no process is started and no +/// socket is opened — only files in a scratch project. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late ProjectSession session; + late ServerpodProcessController process; + late Directory scratch; + late Directory project; + var launches = 0; + + /// `serverpod runner start` failing the way it does when the server cannot + /// come up: a non-zero exit and no runner answering. + Future launcher({ + required Toolchain toolchain, + required String serverDir, + }) async { + launches++; + return RunnerLaunch( + output: Stream.fromIterable(['The local database did not start.']), + exitCode: Future.value(1), + kill: () {}, + ); + } + + Future until(bool Function() condition, {String? reason}) async { + final deadline = DateTime.now().add(const Duration(seconds: 5)); + while (!condition()) { + if (DateTime.now().isAfter(deadline)) { + fail('Timed out waiting for ${reason ?? 'condition'}'); + } + await Future.delayed(const Duration(milliseconds: 10)); + } + } + + String dataDir() => p.join( + FakeRunner.serverDirOf(project), + '.serverpod', + 'development', + 'pgdata', + ); + + /// The project's cluster, with its configuration zero-filled if [damaged]. + void seedDatabase({required bool damaged}) { + Directory(dataDir()).createSync(recursive: true); + File(p.join(dataDir(), 'PG_VERSION')).writeAsStringSync('16\n'); + File(p.join(dataDir(), 'postgresql.conf')).writeAsBytesSync( + damaged ? List.filled(4096, 0) : 'port = 8090\n'.codeUnits, + ); + } + + Iterable logged() => process.log.serverItems + .whereType() + .map((record) => record.message); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + scratch = await Directory.systemTemp.createTemp('appstudio_database'); + ownedRunnerRecordPathOverride = p.join(scratch.path, 'runner.json'); + project = await FakeRunner.createProject(); + launches = 0; + session = ProjectSession(); + process = ServerpodProcessController( + toolchains: await emptyToolchainController(), + session: session, + launcher: launcher, + dependencies: (_, _, _) async {}, + // Nothing comes up for it to find; kept slow so it stays out of the way. + runnerWatchInterval: const Duration(minutes: 1), + ); + }); + + tearDown(() async { + await process.stop(); + process.dispose(); + ownedRunnerRecordPathOverride = null; + await project.delete(recursive: true); + await scratch.delete(recursive: true); + }); + + test('a failure over a damaged database says so, in place of "Stopped"', + () async { + seedDatabase(damaged: true); + + await session.openPath(project.path); + await until(() => process.databaseIsDamaged, reason: 'the damage'); + + final status = process.serverStatus(); + expect(status.kind, ServerStatusKind.stopped); + expect(status.message, 'Database error'); + expect(status.detail, kDatabaseDamagedExplanation); + expect(logged(), contains(startsWith(kDatabaseDamagedExplanation))); + // Still a failed start as far as everything else is concerned. + expect(process.phase, PreviewPhase.failed); + expect(process.canRestart, isTrue); + }); + + test('a failure with an intact database is an ordinary one', () async { + seedDatabase(damaged: false); + + await session.openPath(project.path); + await until(() => process.phase == PreviewPhase.failed); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(process.databaseIsDamaged, isFalse); + expect(process.serverStatus().message, 'Stopped'); + }); + + test('a reset deletes the database and starts the server again', () async { + seedDatabase(damaged: true); + await session.openPath(project.path); + await until(() => process.databaseIsDamaged, reason: 'the damage'); + expect(launches, 1); + + await process.resetDatabase(); + + expect(Directory(dataDir()).existsSync(), isFalse); + expect(launches, 2); + // The start it led to fails here too, but no longer over the database. + await Future.delayed(const Duration(milliseconds: 100)); + expect(process.databaseIsDamaged, isFalse); + expect(process.isRestarting, isFalse); + expect(process.serverStatus().message, 'Stopped'); + }); + + test('a reset is refused while the database is intact', () async { + seedDatabase(damaged: false); + await session.openPath(project.path); + await until(() => process.phase == PreviewPhase.failed); + + await process.resetDatabase(); + + expect(Directory(dataDir()).existsSync(), isTrue); + expect(launches, 1); + }); + + test('another start forgets the damage until it fails again', () async { + seedDatabase(damaged: true); + await session.openPath(project.path); + await until(() => process.databaseIsDamaged, reason: 'the damage'); + + final restart = process.restart(); + expect(process.databaseIsDamaged, isFalse); + await restart; + + await until(() => process.databaseIsDamaged, reason: 'the damage, again'); + // Said once per failure, not once per look. + expect( + logged().where((m) => m.startsWith(kDatabaseDamagedExplanation)), + hasLength(1), + ); + }); +} diff --git a/test/runner/runner_postgres_test.dart b/test/runner/runner_postgres_test.dart index 37731c2..f30a1ed 100644 --- a/test/runner/runner_postgres_test.dart +++ b/test/runner/runner_postgres_test.dart @@ -102,4 +102,106 @@ void main() { ); expect(runs, isEmpty); }); + + // What a crash or a power cut soon after the first start leaves on Windows: + // files at their full length, filled with zeros. + group('a database a crash left damaged', () { + const managedBlock = '\n# >>> serverpod_embedded_postgres BEGIN - DO NOT ' + 'EDIT\nport = 8090\n# <<< serverpod_embedded_postgres END\n'; + + /// An initialised cluster for [mode], as `initdb` and the CLI leave it. + String seedCluster(String mode) { + final root = Directory(p.join(serverDir.path, '.serverpod', mode)); + final data = Directory(p.join(root.path, 'pgdata')) + ..createSync(recursive: true); + File(p.join(data.path, 'PG_VERSION')).writeAsStringSync('16\n'); + File(p.join(data.path, 'postgresql.conf')) + .writeAsStringSync('# PostgreSQL configuration file\n$managedBlock'); + File(p.join(data.path, 'pg_hba.conf')) + .writeAsStringSync('local all all trust\n'); + File(p.join(data.path, 'pg_ident.conf')).writeAsStringSync('# none\n'); + Directory(p.join(data.path, 'base')).createSync(); + Directory(p.join(root.path, 'run')).createSync(); + for (final name in const [ + 'postgres.log', + 'postgres.password', + 'embedded_postgres_state.json', + ]) { + File(p.join(root.path, name)).writeAsStringSync('x'); + } + return data.path; + } + + /// [name] as the crash left it, with the block the CLI then appended on + /// the next start — which is how the file reads when Postgres refuses it. + void zeroFill(String data, String name) { + File(p.join(data, name)).writeAsBytesSync([ + ...List.filled(4096, 0), + ...managedBlock.codeUnits, + ]); + } + + test('is found by its zero-filled configuration', () async { + final data = seedCluster('development'); + zeroFill(data, 'postgresql.conf'); + + expect(await findDamagedDatabases(serverDir.path), [data]); + }); + + test('is found by any of its text files', () async { + for (final name in const ['PG_VERSION', 'pg_hba.conf', 'pg_ident.conf']) { + final data = seedCluster(name.replaceAll('.', '_')); + zeroFill(data, name); + } + + expect(await findDamagedDatabases(serverDir.path), hasLength(3)); + }); + + test('an intact database is not damaged, nor is a project without one', + () async { + expect(await findDamagedDatabases(serverDir.path), isEmpty); + + seedCluster('development'); + expect(await findDamagedDatabases(serverDir.path), isEmpty); + }); + + test('a reset deletes it, with what the CLI keeps beside it', () async { + final data = seedCluster('development'); + zeroFill(data, 'postgresql.conf'); + final root = p.dirname(data); + // Not the cluster's, so not App Studio's to delete. + final other = File(p.join(root, 'notes.txt'))..writeAsStringSync('mine'); + + expect(await resetDamagedDatabases(serverDir.path), [data]); + + expect(Directory(data).existsSync(), isFalse); + expect(Directory(p.join(root, 'run')).existsSync(), isFalse); + expect( + Directory(root).listSync().map((e) => p.basename(e.path)), + ['notes.txt'], + ); + expect(other.readAsStringSync(), 'mine'); + expect(await findDamagedDatabases(serverDir.path), isEmpty); + }); + + test('a reset leaves an intact database alone', () async { + final damaged = seedCluster('development'); + zeroFill(damaged, 'postgresql.conf'); + final intact = seedCluster('dev'); + + expect(await resetDamagedDatabases(serverDir.path), [damaged]); + + expect(Directory(damaged).existsSync(), isFalse); + expect(File(p.join(intact, 'PG_VERSION')).readAsStringSync(), '16\n'); + expect(File(p.join(p.dirname(intact), 'postgres.log')).existsSync(), + isTrue); + }); + + test('a reset with nothing damaged deletes nothing', () async { + final data = seedCluster('development'); + + expect(await resetDamagedDatabases(serverDir.path), isEmpty); + expect(Directory(data).existsSync(), isTrue); + }); + }); } diff --git a/test/ui/studio_toolbar_test.dart b/test/ui/studio_toolbar_test.dart index d17e683..4917876 100644 --- a/test/ui/studio_toolbar_test.dart +++ b/test/ui/studio_toolbar_test.dart @@ -16,6 +16,7 @@ void main() { double width, { ServerStatus status = const ServerStatus.running(), FakeFullRestart? process, + FakeDatabaseRepair? database, VoidCallback? onBack, VoidCallback? onViewLogs, }) async { @@ -31,6 +32,7 @@ void main() { status: FakeServerStatus(status), tools: FakeToolsView(inventory: completeInventory), process: process ?? FakeFullRestart(), + database: database ?? FakeDatabaseRepair(), actions: FakeRunnerActions(), editors: FakeExternalEditors( editors: const [cursorEditor, claudeEditor], @@ -117,4 +119,73 @@ void main() { expect(find.bySemanticsLabel('View Logs'), findsOneWidget); expect(tester.takeException(), isNull); }); + + group('a damaged local database', () { + const damaged = ServerStatus.stopped('Database error', detail: 'why'); + + testWidgets('offers Reset Database in place of Try Again, and asks first', + (tester) async { + final process = FakeFullRestart(isStopped: true); + final database = FakeDatabaseRepair(databaseIsDamaged: true); + await pumpAt( + tester, + 1800, + status: damaged, + process: process, + database: database, + ); + + expect(find.text('View Logs'), findsOneWidget); + expect(find.text('Try Again'), findsNothing); + + await tester.tap(find.text('Reset Database')); + await tester.pumpAndSettle(); + // Nothing is deleted until the user has read what it costs. + expect(find.text('Reset the local database?'), findsOneWidget); + expect(database.resets, 0); + + await tester.tap(find.text('Reset Database').last); + await tester.pumpAndSettle(); + expect(database.resets, 1); + expect(process.isTransitioning, isFalse); + // Mended, so the ordinary retry is back. + expect(find.text('Try Again'), findsOneWidget); + }); + + testWidgets('is left alone on a cancel', (tester) async { + final database = FakeDatabaseRepair(databaseIsDamaged: true); + await pumpAt( + tester, + 1800, + status: damaged, + process: FakeFullRestart(isStopped: true), + database: database, + ); + + await tester.tap(find.text('Reset Database')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(database.resets, 0); + expect(database.databaseIsDamaged, isTrue); + expect(find.text('Reset Database'), findsOneWidget); + }); + + testWidgets('folds to an icon in the narrowest window, without overflow', + (tester) async { + await pumpAt( + tester, + 670, + status: damaged, + process: FakeFullRestart(isStopped: true), + database: FakeDatabaseRepair(databaseIsDamaged: true), + ); + + expect(find.text('Reset Database'), findsNothing); + expect(find.bySemanticsLabel('Reset Database'), findsOneWidget); + expect(find.bySemanticsLabel('View Logs'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + }); } diff --git a/widgetbook/fakes/project.dart b/widgetbook/fakes/project.dart index cf1a58e..3d21856 100644 --- a/widgetbook/fakes/project.dart +++ b/widgetbook/fakes/project.dart @@ -4,6 +4,7 @@ library; import 'dart:async'; +import 'package:appstudio/process/database_repair_view.dart'; import 'package:appstudio/process/full_restart_view.dart'; import 'package:appstudio/process/new_project_view.dart'; import 'package:appstudio/process/project_creator.dart'; @@ -202,6 +203,24 @@ class FakeFullRestart extends ChangeNotifier implements FullRestartView { } } +/// A local database that is damaged or not, and counts the resets it is asked +/// for. A reset mends it. +class FakeDatabaseRepair extends ChangeNotifier implements DatabaseRepairView { + FakeDatabaseRepair({this.databaseIsDamaged = false}); + + @override + bool databaseIsDamaged; + + int resets = 0; + + @override + Future resetDatabase() async { + resets++; + databaseIsDamaged = false; + notifyListeners(); + } +} + class FakeExternalEditors extends ChangeNotifier implements ExternalEditorsView { FakeExternalEditors({this.editors = const [], this.canOpen = true}); diff --git a/widgetbook/studio_window.dart b/widgetbook/studio_window.dart index 94aade0..13e94da 100644 --- a/widgetbook/studio_window.dart +++ b/widgetbook/studio_window.dart @@ -11,6 +11,7 @@ import 'package:appstudio/preview/preview_phase.dart'; import 'package:appstudio/preview/preview_status_overlay.dart'; import 'package:appstudio/preview/preview_theme.dart'; import 'package:appstudio/preview/registration_code_toast.dart'; +import 'package:appstudio/process/database_repair_view.dart'; import 'package:appstudio/process/full_restart_view.dart'; import 'package:appstudio/session/external_editors_view.dart'; import 'package:appstudio/theme/app_theme.dart'; @@ -39,6 +40,7 @@ class StudioWindowMock extends StatelessWidget { this.tools, this.editors, this.process, + this.database, this.registrationCode, this.viewMode = PreviewViewMode.phonePortrait, this.log, @@ -53,6 +55,7 @@ class StudioWindowMock extends StatelessWidget { final ToolsView? tools; final ExternalEditorsView? editors; final FullRestartView? process; + final DatabaseRepairView? database; final String? registrationCode; final PreviewViewMode viewMode; @@ -114,6 +117,7 @@ class StudioWindowMock extends StatelessWidget { status: FakeServerStatus(_status), tools: tools ?? FakeToolsView(inventory: completeInventory), process: process ?? FakeFullRestart(), + database: database ?? FakeDatabaseRepair(), actions: actions, editors: editors ?? diff --git a/widgetbook/use_cases/project.dart b/widgetbook/use_cases/project.dart index 99b1b3e..aebf586 100644 --- a/widgetbook/use_cases/project.dart +++ b/widgetbook/use_cases/project.dart @@ -2,6 +2,7 @@ import 'package:appstudio/cloud/cloud_publish.dart'; import 'package:appstudio/preview/preview_device.dart'; import 'package:appstudio/preview/preview_phase.dart'; import 'package:appstudio/preview/registration_code_toast.dart'; +import 'package:appstudio/process/database_repair_view.dart'; import 'package:appstudio/toolchain/tool_status.dart'; import 'package:appstudio/runner/runner_actions_view.dart'; import 'package:appstudio/runner/server_status.dart'; @@ -13,6 +14,7 @@ import 'package:appstudio/ui/preview_header_bars.dart'; import 'package:appstudio/ui/project_started_dialog.dart'; import 'package:appstudio/ui/project_startup_dialog.dart'; import 'package:appstudio/ui/publish_to_cloud_button.dart'; +import 'package:appstudio/ui/reset_database_dialog.dart'; import 'package:flutter/material.dart'; import 'package:widgetbook/widgetbook.dart'; @@ -71,6 +73,20 @@ final projectFolder = WidgetbookFolder( ), ), ), + WidgetbookUseCase( + name: 'Database damaged', + builder: (_) => screen( + StudioWindowMock( + phase: PreviewPhase.failed, + status: const ServerStatus.stopped( + 'Database error', + detail: kDatabaseDamagedExplanation, + ), + process: FakeFullRestart(isStopped: true), + database: FakeDatabaseRepair(databaseIsDamaged: true), + ), + ), + ), WidgetbookUseCase( name: 'App log tab', builder: (_) => screen( @@ -196,6 +212,18 @@ final projectFolder = WidgetbookFolder( ), ], ), + WidgetbookComponent( + name: 'Reset the local database?', + useCases: [ + WidgetbookUseCase( + name: 'Default', + builder: (_) => _overStudio( + const ResetDatabaseDialog(), + phase: PreviewPhase.failed, + ), + ), + ], + ), WidgetbookComponent( name: 'Hot restart', useCases: [ From 1197996c3b682940f2487f2645bf939068ef9cee Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Thu, 3 Dec 2026 15:20:15 +0100 Subject: [PATCH 2/2] docs: Record the upstream report for the zero-filled postgresql.conf (serverpod/serverpod#6081). Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 3 ++- specs/embedded_postgres_zeroed_conf_report.md | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3c6bbf6..1bf8195 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -213,7 +213,8 @@ 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 for Serverpod. +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 diff --git a/specs/embedded_postgres_zeroed_conf_report.md b/specs/embedded_postgres_zeroed_conf_report.md index 2854429..311d28a 100644 --- a/specs/embedded_postgres_zeroed_conf_report.md +++ b/specs/embedded_postgres_zeroed_conf_report.md @@ -1,8 +1,9 @@ # Embedded Postgres: a zero-filled `postgresql.conf` — report -Status: drafted 2026-12-03, **not filed yet**. One report for Serverpod -(GitHub, `serverpod/serverpod`), laid out as the fields of its bug report -form. App Studio's own mitigation is described at the end. +Status: **filed 2026-12-03 as +[serverpod/serverpod#6081](https://github.com/serverpod/serverpod/issues/6081)**, +with the text below, laid out as the fields of Serverpod's bug report form. +App Studio's own mitigation is described at the end. What is established and what is inferred: