Skip to content

fix(migration): import CSV values exactly or fail before writing - #15516

Open
HarshMN2345 wants to merge 7 commits into
mainfrom
fix-14333-csv-import-values
Open

HarshMN2345 wants to merge 7 commits into
mainfrom
fix-14333-csv-import-values

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Fixes #14333.

Changed in packages/migration:

  • Sources/CSV.php
    • A quote-aware reader keeps each cell's quoting: an unquoted null is NULL, a quoted "null" is the string, and quoted values are not trimmed.
    • Every row is checked before the first batch is written. A bad row fails the import with its row number, and nothing is stored. Before, the earlier batches stayed written.
    • A value its column cannot hold is rejected: integers that are not whole or are out of range, floats, booleans, relative dates (yesterday), out-of-range dates (31.02.2026), JSON, strings longer than the column size, enum/email/url/ip values, column min/max, and array elements.
    • Empty cells import as NULL for every column except plain strings; enum, email, url and ip used to get '' and reject the batch.
    • A UTF-8 BOM is stripped from the header, and a row with invalid UTF-8 is an error instead of a silent drop.
  • Destinations/CSV.php: exports quote "null", "" and padded strings, so an export imports back unchanged.
  • Destinations/Appwrite.php: buffered rows are counted only after their batch is written. If the write fails, every row in the batch is counted as an error, not just the last one. The last row of a batch also writes the buffer when it was skipped itself.

Tested on the local stack, with a throwaway e2e test that imports each case from the issue and reads the table back:

Case Before After
"null", " pad " NULL / pad null / pad
1.7, abc, 9999…, maybe, 31.02.2026, yesterday, [1,"x",3] stored cast or NULL failed, CSV row 2: invalid … value for column '…'
empty enum/email batch rejected row stored with NULL
value too long in row 200 of 300 partial import, success: 297 with 0 stored failed, nothing stored
wrong column count on line 251 200 rows stored failed, nothing stored
duplicate $id in a batch success: 2, error: 1 success: 0, error: 3
BOM $id ignored $id used
Latin-1 byte silent drop failed, CSV row 2 is not valid UTF-8.

The export → import round trip of null, "null", "", padded, quoted and multi-line values was checked locally. Migrations e2e (testCreateCSV*, testAppwriteMigrationDatabasesRow, testAppwriteMigrationRowsOnDuplicate, DocumentsDB/VectorsDB documents) pass. bin/monorepo check migration passes. In bin/monorepo test migration, only AppwriteSdkCoverageTest::testEveryProjectSettingIsMigratedOrSkipped fails, and it is unrelated to this change.

Behaviour change: CSV files that used to import with silently changed values (1.0 into an integer, yesterday into a datetime) now fail with the row number.

…type

Strip a UTF-8 BOM from the header, reject invalid UTF-8 rows, report
the row number, and treat empty enum/email/url/ip cells as null.
@luxor-code-review

luxor-code-review Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 2 medium

💬 Inline comments (3)

  • 🟠 parseValue rejects valid JSON array elements — CSV.php:344
  • 🟡 formatKeys never populated: is_array guard fails on Document columns — CSV.php:231
  • 🟡 Array string items silently trimmed, breaking round-trip — CSV.php:345
🧹 Nitpicks (3) — 🟢 3 low
  • 🟢 Stray doubled blank line in phpstan baseline (phpstan-baseline.neon:5396) — Deleting the is_string() baseline entry left two consecutive blank lines in the neon list (packages/migration/phpstan-baseline.neon:5396-5397), breaking the single-blank-line separation used between every other entry.
  • 🟢 New mb_check_encoding use missing ext-mbstring requirement (composer.json:31) — The new UTF-8 validation at packages/migration/src/Sources/CSV.php:290 calls mb_check_encoding, but packages/migration/composer.json declares no ext-mbstring requirement.
  • 🟢 Per-cell mb_check_encoding scan on every CSV row (CSV.php:289) — The new UTF-8 guard calls mb_check_encoding($cell, 'UTF-8') for every string cell of every row inside the streaming import loop (packages/migration/src/Sources/CSV.php:289-293).

This PR refactors the CSV migration source's value parsing: cells now flow through a shared parseValue with per-format handling, per-cell UTF-8 validation, and stricter scalar casting, and the matching phpstan baseline entry is dropped. The refactor introduces a high-severity regression where array column elements are parsed through the scalar path and valid JSON array elements are rejected, plus a medium bug where the formatKeys guard never fires for Document-backed columns and a round-trip change that trims array item strings. Low-severity items cover the baseline formatting, the un-declared ext-mbstring dependency, and the per-row encoding-scan cost.

Files Change
packages/migration/src/Sources/CSV.php Rewrites cell parsing with a parseValue pipeline, UTF-8 validation per cell, strict int/number casting, and formatKeys-driven default handling; array element handling regresses.
packages/migration/phpstan-baseline.neon Removes the baseline entry resolved by the CSV.php refactor, but leaves a stray doubled blank line.
packages/migration/composer.json Uses mb_check_encoding in the new parse path without declaring the ext-mbstring requirement.

Reviewed commit: 190f0dc

@HarshMN2345
HarshMN2345 force-pushed the fix-14333-csv-import-values branch from 190f0dc to 471ee86 Compare November 12, 2026 07:26
@appwrite

appwrite Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

Limited by an open minor finding: Accept decimal integers with leading zeros

CSV migration imports now preserve quoted values, strip a UTF-8 BOM, validate typed cells with row context, and preflight records before sending batches. CSV exports distinguish null from literal null and quote empty or whitespace-padded strings. Appwrite destination imports defer row counters until buffered batches are written and mark batch resources together when a write fails.

Latest changes: The newest commits add a full CSV validation pass before callbacks, improve quoting and null round-tripping in CSV exports, and defer Appwrite row status counters until each buffered batch has been written.

Verdict New comments Fixed Still open
💬 Commented 1 0 2

Note

Not approving while a bug finding is open: Accept decimal integers with leading zeros

Finding Where
🟡 Add regression coverage for CSV source imports packages/migration/src/Sources/CSV.php:275
Fix with agent prompt
### Issue 1
packages/migration/src/Sources/CSV.php:275-276
**Add regression coverage for CSV source imports**

The existing `CSVTest` exercises export and delimiter detection but does not drive `Sources\CSV` through this new parser or preflight pass. A focused import test should assert the parsed row values and that an invalid row prevents callbacks, so regressions in the custom quoted-record parsing are observable.

### Issue 2
packages/migration/src/Sources/CSV.php:421
**Accept decimal integers with leading zeros**

`FILTER_VALIDATE_INT` rejects decimal strings such as `0012` (confirmed with a direct `php -r` check), even though they are valid whole numbers and the previous `is_numeric`/cast path imported them as `12`. A CSV with such a cell now aborts the import.

### Issue 3
packages/migration/src/Sources/CSV.php:422
**Reject float values that overflow to infinity**

`is_numeric('1e9999')` is true, but casting it to float produces `INF` (confirmed with a direct `php -r` check), so this path accepts a value that cannot be represented as a finite double. It then reaches destination serialization or validation instead of failing here with the row-specific parsing error.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 4
File Change
packages/migration/phpstan-baseline.neon Removes resolved CSV PHPStan baseline entries.
packages/migration/src/Destinations/Appwrite.php Tracks buffered row resources and updates their statuses and counters after each batch write.
packages/migration/src/Destinations/CSV.php Writes null distinctly from literal null and quotes empty or whitespace-padded values for round-tripping.
packages/migration/src/Sources/CSV.php Builds a typed column schema, parses quoted CSV records, validates all rows before callbacks, and reports row-specific errors.
⏳ Still open from earlier reviews · 2
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Clear buffered rows when timestamp normalization fails Verifier: The throw-before-flush pattern is the same as the base code. It is hard to reach from a CSV import. $createdAt and $updatedAt values from the CSV are not normalized when they are non-empty. Otherwise the source supplies an empty createdAt, so normalizeDateTime falls back to now and does not throw. It could only throw for a schema column literally named created_at or updated_at that holds garbage.

Merged main (46b5230); no changes to this PR's code since 5b8dae6 · Details · Comment @appwrite review to re-run, or mention @appwrite with a question.

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

}

$parsed = match ($type) {
Column::TYPE_INTEGER, Column::TYPE_BIG_INT => \filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accept decimal integers with leading zeros

FILTER_VALIDATE_INT rejects decimal strings such as 0012 (confirmed with a direct php -r check), even though they are valid whole numbers and the previous is_numeric/cast path imported them as 12. A CSV with such a cell now aborts the import.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/migration/src/Sources/CSV.php
Line: 421

Comment:
**Accept decimal integers with leading zeros**

`FILTER_VALIDATE_INT` rejects decimal strings such as `0012` (confirmed with a direct `php -r` check), even though they are valid whole numbers and the previous `is_numeric`/cast path imported them as `12`. A CSV with such a cell now aborts the import.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

Comment thread packages/migration/src/Sources/CSV.php Outdated

$parsed = match ($type) {
Column::TYPE_INTEGER, Column::TYPE_BIG_INT => \filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE),
Column::TYPE_FLOAT => \is_numeric($value) ? (float)$value : null,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reject float values that overflow to infinity

is_numeric('1e9999') is true, but casting it to float produces INF (confirmed with a direct php -r check), so this path accepts a value that cannot be represented as a finite double. It then reaches destination serialization or validation instead of failing here with the row-specific parsing error.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/migration/src/Sources/CSV.php
Line: 422

Comment:
**Reject float values that overflow to infinity**

`is_numeric('1e9999')` is true, but casting it to float produces `INF` (confirmed with a direct `php -r` check), so this path accepts a value that cannot be represented as a finite double. It then reaches destination serialization or validation instead of failing here with the row-specific parsing error.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · bug · Reply if this doesn't apply.

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reworks CSV migration value parsing with stricter validation but breaks valid JSON/structured array elements, leaving one formatKeys branch dead and adding two hygiene issues.

Key findings

  • 🟠 parseValue rejects valid JSON array elements — CSV.php:344
  • 🟡 formatKeys never populated: is_array guard fails on Document columns — CSV.php:231
  • 🟡 Array string items silently trimmed, breaking round-trip — CSV.php:345

Comment thread packages/migration/src/Sources/CSV.php Outdated
Comment on lines +344 to +347
$parsedData[$key] = \array_map(
fn ($item) => $this->parseValue(\is_string($item) ? \trim($item) : $item, \is_string($type) ? $type : '', $key, $line),
$arrayValues
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 bug · high

parseValue rejects valid JSON array elements

Array columns now route every element through parseValue (packages/migration/src/Sources/CSV.php:344-347). JSON false elements are stringified to "" and rejected by the boolean arm; JSON null, nested arrays, and objects are coerced to null and hit the invalid value throw (packages/migration/src/Sources/CSV.php:416-435). The removed mapper used default => $item and a raw filter_var call, so these payloads previously imported correctly. Importing a CSV whose array column contains e.g. [true,false] or ["a", null, "b"] now aborts the entire row with a validation error on values that are valid for the column.

📋 Prompt for AI Agents

In packages/migration/src/Sources/CSV.php around lines 344-347, change the array_map callback so it only invokes $this->parseValue(...) for scalar non-boolean items: booleans should be returned directly (they are valid for TYPE_BOOLEAN), and nested arrays, objects, and explicit JSON null elements should pass through unchanged — the behavior the removed default => $item mapping provided. Concretely: fn ($item) => \is_bool($item) ? $item : (\is_scalar($item) ? $this->parseValue(\is_string($item) ? $item : (string)$item, \is_string($type) ? $type : '', $key, $line) : $item). Without this, [true,false] throws (because (string)false === "" fails FILTER_VALIDATE_BOOLEAN) and [null] / nested JSON elements abort the whole row with a CODE_VALIDATION exception.

Comment thread packages/migration/src/Sources/CSV.php Outdated
foreach ($columns as $column) {
$key = $column['key'];
$type = $column['type'];
$format = \is_array($column) && \is_string($column['format'] ?? null) ? $column['format'] : '';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

formatKeys never populated: is_array guard fails on Document columns

The new format detection reads format only when \is_array($column) (packages/migration/src/Sources/CSV.php:231), but columns come from $this->database->listColumns(), which returns Utopia\Database\Document objects (an ArrayObject subclass, not PHP arrays) from find('attributes', ...) (packages/migration/src/Sources/Appwrite/Reader/Database.php:251). The sibling $key and $type reads at lines 229-230 use ArrayAccess with no is_array guard, confirming the runtime shape. As a result $format is always '', formatKeys stays empty, and the empty-cell-to-null rule for enum/email/url/ip columns at line 376 never activates in production.

📋 Prompt for AI Agents

In packages/migration/src/Sources/CSV.php line 231, replace \is_array($column) && \is_string($column['format'] ?? null) ? $column['format'] : '' with \is_string($column['format'] ?? null) ? $column['format'] : '', matching the ArrayAccess pattern used for $column['key'] and $column['type'] on lines 229-230. Columns arrive as Utopia\Database\Document objects (ArrayObject) from listColumns(), so the is_array guard always fails and the enum/email/url/ip empty-cell handling never runs; add a unit test with a Document-backed column so the format path is covered.

Comment thread packages/migration/src/Sources/CSV.php Outdated
};
}, $arrayValues);
$parsedData[$key] = \array_map(
fn ($item) => $this->parseValue(\is_string($item) ? \trim($item) : $item, \is_string($type) ? $type : '', $key, $line),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

Array string items silently trimmed, breaking round-trip

Every string item of an array column is now passed through trim() before storage (packages/migration/src/Sources/CSV.php:345). A JSON array cell such as [" padded ", "tail "] previously imported verbatim; leading/trailing whitespace inside string array elements is now silently discarded, corrupting data on export→import round-trips for values whose whitespace is meaningful (tokens, serialized blobs, text). The same trim also applies to $permissions entries routed through this path.

📋 Prompt for AI Agents

In packages/migration/src/Sources/CSV.php line 345, remove the \trim($item) call from the array_map callback and pass the raw string item to parseValue (fn ($item) => $this->parseValue(\is_string($item) ? $item : (string)$item, ...)). Trimming array elements silently deletes meaningful leading/trailing whitespace from imported data and breaks export→import round-trips; the whole-cell trim at line 303 already normalizes cell-level whitespace where intended.

@github-actions

github-actions Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-14333-csv-import-values (after).

Metric Before After Change
🚀 Requests/sec 186.18 178.62 ⚪ -4.1%
⏱️ Latency P50 93.95 ms 96.73 ms ⚪ +3%
⏱️ Latency P95 216.85 ms 229.08 ms 🔴 +5.6%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 96.73 229.08 11,400 178.62 +12.23
Account 184.64 338.65 600 10.15 +18.83
TablesDB 93.39 174.4 6,200 100.37 +9.53
Storage 89.24 214.02 3,000 50.2 +21.83
Functions 137.25 262.37 1,600 27.43 +4.75

Top API waits (after)

API request Max wait (ms)
account.name.update 585.87
functions.delete 535.18
tablesdb.rows.delete 521.49
functions.variables.create 495.68
storage.buckets.create 462.17

Read cells with their quoting, so a quoted "null" and quoted whitespace
are kept. Reject values a column cannot hold (integer range, relative or
out-of-range dates, string size, enum, email, url, ip) with the row number,
and check every row before the first batch is written.
A null exports as bare null, so the strings "null", "" and values with
surrounding whitespace are quoted to import back unchanged.
A failed batch write marks every row in it as failed, and the last row
of a batch flushes the buffer even when it was skipped itself.
@HarshMN2345 HarshMN2345 changed the title fix(migration): reject CSV import values that do not parse fix(migration): import CSV values exactly or fail before writing Nov 12, 2026

@appwrite appwrite Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

Comment on lines +275 to +276
// Check every row before any is written, so one bad row cannot leave the table half imported
foreach ($this->readRows($stream, $delimiter, $headers, $schema) as $_) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add regression coverage for CSV source imports

The existing CSVTest exercises export and delimiter detection but does not drive Sources\CSV through this new parser or preflight pass. A focused import test should assert the parsed row values and that an invalid row prevents callbacks, so regressions in the custom quoted-record parsing are observable.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/migration/src/Sources/CSV.php
Line: 275-276

Comment:
**Add regression coverage for CSV source imports**

The existing `CSVTest` exercises export and delimiter detection but does not drive `Sources\CSV` through this new parser or preflight pass. A focused import test should assert the parsed row values and that an invalid row prevents callbacks, so regressions in the custom quoted-record parsing are observable.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

🟡 Minor · testing · Reply if this doesn't apply.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug Report: CSV import silently changes, drops or partially imports rows

1 participant