fix(cli): tolerate corrupt or unreadable command state file - #29609
Conversation
Summary by CodeRabbit
WalkthroughCommand-state loading now validates parsed JSON and 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
✨ Simplify code
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/cli/src/utils/commandState.ts`:
- Around line 35-39: The routine loadOrInitializeCommandState currently throws
if fs.promises.mkdir or fs.promises.writeFile fail; change it to best-effort
persistence: after building the in-memory state (state = {
firstCommandTimestamp: ... }), attempt to create the directory and write the
file but wrap mkdir/write logic in a try/catch that logs/debugs the error and
does not rethrow so the function still returns the in-memory state; additionally
perform the write atomically by writing JSON to a temp file (e.g., filePath +
".tmp" or similar) and then fs.promises.rename to the final file to avoid
truncated commands.json on interruption, catching and suppressing any errors
from both the temp write and rename so failures don’t prevent returning the
state.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 6972eb1c-5892-4d3c-8c74-8934dae78762
📒 Files selected for processing (2)
packages/cli/src/__tests__/commandState.test.tspackages/cli/src/utils/commandState.ts
A read failure other than ENOENT (e.g. EACCES, or EISDIR when the path is a directory) previously rejected out of loadOrInitializeCommandState, so callers skipped their command-state logic and the broken file was never repaired. Treat any read failure like a missing file: log it via debug and re-initialize the state. Also log JSON parse failures instead of swallowing them, and add tests for the unreadable-file and failed-persistence paths.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/cli/src/utils/commandState.ts (2)
32-34: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winValidate the timestamp value, not only its type.
Line [33] accepts values such as
"invalid"or""as valid state.daysSinceFirstCommandwill then returnNaN, and the corrupted file will not be repaired. Require a parseable timestamp and add a regression test for malformed timestamp strings.Proposed validation
- if (parsed && typeof parsed.firstCommandTimestamp === 'string') { + if ( + parsed && + typeof parsed.firstCommandTimestamp === 'string' && + !Number.isNaN(Date.parse(parsed.firstCommandTimestamp)) + ) { state = parsed }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/cli/src/utils/commandState.ts` around lines 32 - 34, Update the JSON state validation in commandState parsing so parsed.firstCommandTimestamp must be a non-empty, parseable timestamp rather than merely a string; otherwise leave the state invalid so the existing repair path runs. Add a regression test covering malformed timestamp strings such as "invalid" and asserting the corrupted state is repaired.
45-47: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftUse an isolated temporary path per command-state write.
commands.json.tmpis the same file for every Prisma CLI invocation, so concurrent invokes can collide onwriteFileor cross-rename another attempt’s temporary file. Use a unique temp path per attempt, serialize writes, and clean up failed temporary files.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/cli/src/utils/commandState.ts` around lines 45 - 47, Update the command-state write flow around tempFilePath to generate an isolated temporary filename for each attempt, serialize concurrent writes, and remove the temporary file when writing or renaming fails. Preserve the existing atomic write behavior by renaming only that attempt’s temporary file to filePath.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/cli/src/__tests__/commandState.test.ts`:
- Around line 107-112: Update the loadOrInitializeCommandState test to assert
that mockWrite was called with the temporary file path and the serialized state
before verifying mockRename was not called. Keep the existing returned-state
assertions unchanged.
---
Outside diff comments:
In `@packages/cli/src/utils/commandState.ts`:
- Around line 32-34: Update the JSON state validation in commandState parsing so
parsed.firstCommandTimestamp must be a non-empty, parseable timestamp rather
than merely a string; otherwise leave the state invalid so the existing repair
path runs. Add a regression test covering malformed timestamp strings such as
"invalid" and asserting the corrupted state is repaired.
- Around line 45-47: Update the command-state write flow around tempFilePath to
generate an isolated temporary filename for each attempt, serialize concurrent
writes, and remove the temporary file when writing or renaming fails. Preserve
the existing atomic write behavior by renaming only that attempt’s temporary
file to filePath.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: e845da61-0d8d-4b9a-96ef-340be0891633
📒 Files selected for processing (2)
packages/cli/src/__tests__/commandState.test.tspackages/cli/src/utils/commandState.ts
|
Pushed a follow-up on top of this branch:
Verified with |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/cli/src/__tests__/commandState.test.ts (1)
86-99: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winAssert the atomic rename for unreadable-file recovery.
This test verifies the temporary write but not
mkdiror the subsequentrename. A regression that leaves the state only in.tmpwould still pass and cause re-initialization on every invocation.Proposed assertions
expect(mockRead).toHaveBeenCalledTimes(1) + expect(mockMkdir).toHaveBeenCalledWith(expect.anything(), { recursive: true }) expect(mockWrite).toHaveBeenCalledWith(expect.stringContaining('.tmp'), JSON.stringify(state)) + expect(mockRename).toHaveBeenCalledWith(expect.stringContaining('.tmp'), expect.not.stringContaining('.tmp'))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/cli/src/__tests__/commandState.test.ts` around lines 86 - 99, Extend the test for loadOrInitializeCommandState to assert the recovery directory setup and atomic rename after an unreadable state file. Verify mockMkdir and mockRename are each called with the expected arguments, ensuring the initialized state is moved from the temporary file to the final state path rather than left in .tmp.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@packages/cli/src/__tests__/commandState.test.ts`:
- Around line 86-99: Extend the test for loadOrInitializeCommandState to assert
the recovery directory setup and atomic rename after an unreadable state file.
Verify mockMkdir and mockRename are each called with the expected arguments,
ensuring the initialized state is moved from the temporary file to the final
state path rather than left in .tmp.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: c3ae0b68-4424-4d81-9a0f-ec46bac62eba
📒 Files selected for processing (1)
packages/cli/src/__tests__/commandState.test.ts
…9609) ## Problem If the CLI's `commands.json` state file becomes corrupted (invalid or truncated JSON, wrong schema) or unreadable, loading the command state fails. A bare `JSON.parse` throws during CLI startup, so a corrupt state file breaks every subsequent Prisma CLI command. ## Solution Make `loadOrInitializeCommandState` fully best-effort: - Catch `JSON.parse` errors and schema mismatches, and fall back to a fresh initial state instead of throwing; the healthy state is written back to `commands.json`. - Treat any read failure (not just `ENOENT`) like a missing file, logging non-`ENOENT` errors via `debug`. - Write the state atomically (temp file + rename) so an interrupted write cannot leave a truncated `commands.json`, and make persistence failures non-fatal: the in-memory state is still returned when the config dir is not writable. ## Verification Unit tests in `packages/cli/src/__tests__/commandState.test.ts` cover re-initialization on invalid JSON, invalid schema, and unreadable file, plus returning the in-memory state when persisting fails (`pnpm --filter prisma test commandState`). --------- Co-authored-by: Alexey Orlenko's AI Agent <robot@aqrln.net>
This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [@prisma/adapter-pg](https://github.com/prisma/prisma) ([source](https://github.com/prisma/prisma/tree/HEAD/packages/adapter-pg)) | imports | minor | [`7.9.1` -> `7.10.0`](https://renovatebot.com/diffs/npm/@prisma%2fadapter-pg/7.9.1/7.10.0) | | [@prisma/client](https://www.prisma.io) ([source](https://github.com/prisma/prisma/tree/HEAD/packages/client)) | imports | minor | [`7.9.1` -> `7.10.0`](https://renovatebot.com/diffs/npm/@prisma%2fclient/7.9.1/7.10.0) | --- ### Release Notes <details> <summary>prisma/prisma (@​prisma/adapter-pg)</summary> ### [`v7.10.0`](https://github.com/prisma/orm/releases/tag/7.10.0) [Compare Source](prisma/orm@7.9.1...7.10.0) ##### Prisma ORM 7.10.0 Prisma ORM 7.10.0 introduces a compatibility package for running Prisma 7 alongside newer Prisma versions, secures Prisma Studio's local server, and includes fixes across Prisma Client and the PostgreSQL, MariaDB, Neon, SQLite, and Prisma Postgres Serverless adapters. ##### Highlights ##### Run Prisma 7 alongside Prisma 8 This release introduces `@prisma/prisma7`, a compatibility package that lets you retain a matching Prisma 7 CLI and configuration while installing Prisma 8 in the same project. Once 7.10.0 is released, a side-by-side installation can use: ```sh npm install --save-dev prisma@8 @prisma/prisma7@7.10.0 npm install @prisma/client@7.10.0 ``` Use `prisma` for the directly installed Prisma 8 CLI and `prisma7` for Prisma 7: ```sh npx prisma --version npx prisma7 --version npx prisma7 generate npx prisma7 migrate dev npx prisma7 db push ``` Prisma 7 now prefers version-specific configuration files, allowing its configuration to coexist with Prisma 8's `prisma.config.*` files: ```ts // prisma7.config.ts import { defineConfig } from '@prisma/prisma7/config' export default defineConfig({ schema: 'prisma/schema.prisma', migrations: { path: 'prisma/migrations', }, }) ``` Without an explicit `--config` option, Prisma 7 searches for: 1. Root-level `prisma7.config.*` files. 2. `.config/prisma7.*` files. 3. Existing `prisma.config.*` files as a backwards-compatible fallback. The supported extensions are `.js`, `.ts`, `.mjs`, `.cjs`, `.mts`, and `.cts`. An explicit config path always takes precedence: ```sh npx prisma7 generate --config ./custom/prisma7.config.ts ``` New projects initialized by the Prisma 7 CLI use `prisma7.config.ts`. Existing projects containing only `prisma.config.*` continue to work without migration or additional warnings. If a `prisma7.config.*` file exists but cannot be loaded, Prisma reports the error rather than silently falling back to another configuration. The `prisma7` identity is carried through CLI help, version output, shell completion, initialization, migration, database, and generation guidance. Stable Prisma concepts such as `schema.prisma`, Prisma Migrate, `@prisma/client`, and `PRISMA_*` environment variables remain unchanged. Together, the separate executable and configuration namespace make it possible to operate Prisma 7 and Prisma 8 side by side without command or config-file collisions. [#​29949](prisma/orm#29949), [#​29969](prisma/orm#29969), [#​29994](prisma/orm#29994), [#​30000](prisma/orm#30000), [#​30002](prisma/orm#30002), [#​30020](prisma/orm#30020) ##### Prisma Studio security hardening Prisma Studio's local HTTP server now: - Binds explicitly to `127.0.0.1` instead of all network interfaces. - Rejects browser requests from origins other than the active `localhost` or `127.0.0.1` Studio URL. - No longer returns wildcard CORS headers. - Applies the same protections across Node.js, Bun, and Deno. This prevents network clients or malicious websites from accessing Studio's database endpoints while Studio is running. [#​29890](prisma/orm#29890) ##### Prisma Client - Fixed `P2002` errors from nested writes so `meta.modelName` identifies the model where the unique constraint violation occurred, including models using `@@map` and `@@schema`. [#​29628](prisma/orm#29628) - Fixed automatically batched `findUniqueOrThrow()` calls so every missing record rejects with `P2025`; later misses no longer resolve to `undefined`. [#​29654](prisma/orm#29654) - Parameter-chunked statements are now executed atomically in a transaction and rolled back if a later chunk fails. [#​29771](prisma/orm#29771) - Improved interactive transaction cleanup during `$disconnect()`, including transactions whose driver-level startup is still in progress. [#​28768](prisma/orm#28768) - Prevented transaction cleanup failures after a timeout or backend termination from becoming unhandled promise rejections. [#​29611](prisma/orm#29611) - Fixed fluent relation queries when relation fields are literally named `select` or `include`. [#​29683](prisma/orm#29683) - Fixed handling of `Date` and `Uint8Array` values created in other JavaScript realms, such as iframes, jsdom, and Node.js `vm` contexts. [#​29177](prisma/orm#29177) - Invalid `Date` values passed to `$queryRaw` or `$executeRaw` now throw `PrismaClientValidationError` instead of a generic error. [#​29718](prisma/orm#29718) - Fixed `moduleFormat` inference for the `prisma-client` generator in TypeScript projects using `module: "node16"` or `"nodenext"`. Generated output now follows the nearest `package.json` `type`, defaulting to CommonJS when absent. [#​29712](prisma/orm#29712) - Deserialized `Bytes` values now own standalone `ArrayBuffer`s rather than exposing unrelated contents from Node.js's shared `Buffer` pool. This applies to both regular and raw query results. [#​29701](prisma/orm#29701) - Fixed an incorrect logging context in the remote executor, including Accelerate-backed query execution. [#​28892](prisma/orm#28892) ##### Client extensions and observability - Result-extension `compute` callbacks now receive the current model name as a typed second argument: ```ts compute(data, modelName) { // ... } ``` The model name is also preserved when multiple extensions compose the same computed field. [#​29782](prisma/orm#29782) - Improved OpenTelemetry context for remotely executed queries: - `$on('query')` callbacks run within the matching `db_query` span. - Events from one operation share the same trace. - Error events are recorded as span exceptions. - Log events continue to be emitted when tracing is disabled or their reported span is unavailable. [#​28892](prisma/orm#28892) ##### Driver adapters ##### MariaDB - `@prisma/adapter-mariadb` now accepts an existing `mariadb` pool. External pools remain caller-owned unless `disposeExternalPool: true` is supplied. [#​27992](prisma/orm#27992) - Fixed pooled connection leaks during commit, rollback, and failed transaction startup. Connections are now returned with `release()` and transaction-specific listeners are removed before reuse. [#​29612](prisma/orm#29612) - Added support for bracketed IPv6 addresses in both `mysql://` and `mariadb://` connection strings. [#​29026](prisma/orm#29026) - Prevented malformed connection strings from exposing embedded passwords in retained debug output and diagnostic reports. [#​27992](prisma/orm#27992) ##### PostgreSQL, Neon, and Prisma Postgres Serverless - PostgreSQL deadlocks using SQLSTATE `40P01` are now reported as `P2034` transaction write conflicts. [#​29717](prisma/orm#29717) - PostgreSQL `RESTRICT` violations using SQLSTATE `23001` are now reported as `P2003`, preserving an available field or constraint name. [#​29554](prisma/orm#29554) - `@prisma/adapter-pg` now preserves database constraint names when reporting unique constraint violations through `P2002`. [#​29587](prisma/orm#29587) - Prisma Postgres Serverless now prefers the named constraint for `P2002`, falling back to parsed field names when no constraint name is available. [#​29801](prisma/orm#29801) - Fixed Neon HTTP adapter serialization for typed parameters such as `Bytes` and `DateTime`. [#​29747](prisma/orm#29747) ##### SQLite - `@prisma/adapter-better-sqlite3` now converts previously unhandled SQLite result codes into typed database errors instead of exposing raw driver errors. - The complete `SQLITE_BUSY` family is now mapped to socket timeout errors, with numeric extended result codes preserved where available. [#​29794](prisma/orm#29794) ##### CLI and Migrate - `prisma generate` can now offer to install Prisma's agent skills. The opt-in prompt: - Is shown at most once per machine. - Is skipped in CI, containers, Git hooks, npm lifecycle scripts, and watch mode. - Is skipped when `--no-hints` is used or Prisma skills are already installed. - Times out after 30 seconds. - Never causes generation to fail if installation is unsuccessful. [#​29690](prisma/orm#29690) - A globally installed CLI now warns during `prisma generate` when its version differs from the project's local `prisma` or `@prisma/client`, and recommends running the local CLI. The check is best-effort and does not fail generation. [#​29593](prisma/orm#29593) - `prisma version` and `prisma version --json` now include the resolved Prisma CLI package path, making global-versus-local installation issues easier to diagnose. [#​29573](prisma/orm#29573) - Empty or generator-only schema files now report `Schema must contain a datasource block` from `db pull`, `db push`, and `migrate dev`, rather than reaching the schema engine and potentially producing inconsistent errors. [#​29657](prisma/orm#29657) - CLI commands now tolerate corrupt, unreadable, or unwritable command-state files. Invalid state is reinitialized, writes are atomic, and persistence failures fall back to in-memory state. [#​29609](prisma/orm#29609) - Studio now recognizes semicolon-delimited `sqlserver://` connection strings before reporting the existing explicit message that SQL Server is not supported by Studio. [#​29623](prisma/orm#29623) - The AI-agent safety checkpoint now also covers interactive `prisma db push` confirmations involving data-loss warnings, rather than only invocations using `--accept-data-loss`. [#​29793](prisma/orm#29793) ##### Performance and reliability - Optimized query-plan execution by eagerly evaluating plans with one unconditional database operation and synchronously interpreting the remaining pure plan. Cached plans remain immutable. [#​29004](prisma/orm#29004) - Prevented call-stack overflows when rendering very large parameter lists or combining chunked results containing hundreds of thousands of rows. [#​29751](prisma/orm#29751) - Reduced ordinary query setup overhead by constructing fluent-relation field maps lazily and in linear time. Non-fluent queries no longer build this map. [#​29752](prisma/orm#29752) ##### Dependencies - Updated the transitive `fast-uri` dependency to a patched release addressing production audit advisories affecting versions through `3.1.3`. [#​29758](prisma/orm#29758) </details> --- ### Configuration 📅 **Schedule**: (UTC) - Branch creation - At any time (no schedule defined) - Automerge - At any time (no schedule defined) 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about these updates again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4zMC4zIiwidXBkYXRlZEluVmVyIjoiNDQuMzAuMyIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==--> Reviewed-on: https://git.oirnoir.dev/OIRNOIR/YouTube-Helper-Server/pulls/41
Problem
If the CLI's
commands.jsonstate file becomes corrupted (invalid or truncated JSON, wrong schema) or unreadable, loading the command state fails. A bareJSON.parsethrows during CLI startup, so a corrupt state file breaks every subsequent Prisma CLI command.Solution
Make
loadOrInitializeCommandStatefully best-effort:JSON.parseerrors and schema mismatches, and fall back to a fresh initial state instead of throwing; the healthy state is written back tocommands.json.ENOENT) like a missing file, logging non-ENOENTerrors viadebug.commands.json, and make persistence failures non-fatal: the in-memory state is still returned when the config dir is not writable.Verification
Unit tests in
packages/cli/src/__tests__/commandState.test.tscover re-initialization on invalid JSON, invalid schema, and unreadable file, plus returning the in-memory state when persisting fails (pnpm --filter prisma test commandState).