Skip to content

fix(importer): ZIP silently empty, clobbered delimiter, skipped-record resurrection, XML sibling carryover, long-text typed LONG (#6810 #6811 #6812 #6813 #6814) - #6865

Merged
lvca merged 2 commits into
mainfrom
fix/6810-6814-importer-batch
Aug 28, 2026
Merged

lvca merged 2 commits into
mainfrom
fix/6810-6814-importer-batch

Conversation

@lvca

@lvca lvca commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

Fixes #6810, fixes #6811, fixes #6812, fixes #6813, fixes #6814.

Five independent defects in the importer module, all of which either drop or corrupt imported data without the import ever reporting a failure. Each one has a regression test that was verified to fail against main before the fix.

#6810 - any ZIP source imports as 0 records, reported as success

Both reset callbacks in SourceDiscovery called getNextEntry() on the old, already closed ZipInputStream instead of the freshly created one, so the new stream was left with no current entry. A ZipInputStream with no current entry reads as an empty file rather than throwing, and the reset path runs on every import (Importer.loadFromSource, SourceDiscovery.getSchema, CSVImporterFormat.analyze). Source.reset() only logged the resulting Stream closed at SEVERE, so the run finished with Total documents: 0 and no error.

Beyond the suggested fix in the issue:

  • the new stream is positioned through the same seek the initial open uses, extracted as seekZipEntry/positionZipStream, so the :::<resource> entry is honoured on reset too (it never was - reset landed on the first entry of the archive regardless of what the user asked for);
  • Source.reset() propagates instead of swallowing, so a broken re-open can never again be mistaken for an empty input;
  • the remote reset callback closes the old stream before disconnecting the connection it belongs to. The local callback already did; the URL one leaked it, and on a ZIP source it then went on to advance that leaked stream instead of the new one, which is the defect itself;
  • the local reset now re-opens through the same file-then-classpath resolution the first open used. It previously hard-coded new FileInputStream(file), which cannot work for the classpath fallback - a latent second way for reset to fail, and one that the newly propagating reset() would have turned into a hard error.

#6811 - the user's delimiter is overwritten with null for every CSV source

analyzeSourceContent() unconditionally wrote knownDelimiter into settings.options, but left it null for EntityType.DATABASE. Since -delimiter / WITH delimiter = ';' lands in that same map (ImporterSettings.parseParameter), it was destroyed for every CSV source, and IMPORT DATABASE file://data.csv WITH delimiter = ';' parsed the whole line as one column - producing a property literally named id;name;age, and reporting success.

The put is now guarded, and case DATABASE reads the generic option back from settings.options (falling back to -documentsDelimiter). The guard also means a generic -delimiter now survives for the -documents/-vertices/-edges forms when no per-entity delimiter is set, instead of being cleared.

One addition beyond the issue: ; joins the isSeparator() candidate set. Without it a semicolon-separated file whose extension is not .csv produced no candidate at all and the import died with Cannot determine the file type; ; is no more ambiguous than the - and _ already in that set, and the best-candidate-by-frequency logic is unchanged.

#6812 - a record logged as skipped is saved as an anonymous Document

createRecord() used the same return signal for two opposite outcomes: no mapping, save this anonymously and this record is rejected or deduplicated, drop it. parseRecord() collapsed both into attributes.map, and parseRecordsArray() then materialized it into settings.documentTypeName. A duplicate @id without "@strategy": "merge", or a mapping object missing @cat/@type - both of which log will be skipped and increment context.errors - ended up saved anyway.

Rather than a sentinel return value, the two cases are separated where the information already exists:

  • parseRecordsArray() anonymously saves only when mappingObject == null. That is the one case the anonymous path is meant for, and it deliberately keeps working for the nested "@cat":"e" object, which returns its attribute map on purpose so convertMap() can turn it into an edge during the mapping phase. Returning a sentinel from createRecord() would have broken exactly that path.
  • a deduplicated @id now hands the existing record back, so a caller links to it instead of re-materializing the skipped attributes.

That second change also fixes a latent ClassCastException on the same code path: convertMap() cast the destination vertex to MutableVertex, which an existing (immutable) record from the dedup branch could never satisfy. It now goes through modify(), a no-op on a MutableVertex.

#6813 - an empty or self-closing XML sub-element inherits the previous sibling's value

lastContent was cleared only when a new record started, never when a new sub-element started, so <rows><row><a>1</a><b></b></row></rows> imported as {a: "1", b: "1"}, in both load() and analyze(). This is the sub-element twin of #2759, whose regression test uses attributes exclusively.

State is cleared on the sub-element boundary, but only there: the clear at END_ELEMENT is conditioned on closing the property element itself (nestLevel == objectNestLevel + 2), so a deeper descendant's text still feeds the property and <a><x>1</x><y>2</y></a> keeps its existing last-wins result. The #2759 whitespace fix is untouched - whitespace between elements still cannot erase the content of the element currently being read. An element opened and closed with no character content becomes an empty property, which is its XML text content, rather than a missing or null one.

#6814 - a long text value is treated as no evidence, so the column is typed LONG

AnalyzedProperty.setLastContent() treated a value longer than 100 chars as stop sampling and as no evidence about the type, returning before the numeric probes and - because collectingSamples was now permanently false - making every subsequent value for that column a no-op too. A column whose first value looked numeric was declared LONG and created as such in the schema, and the import then died on the long value it never examined with Cannot convert type 'java.lang.String' to 'LONG' (or, under -onRowError skip, silently dropped every long-text row).

Type refutation now runs on every value, independently of sample collection, which covers the maxValueSampling short-circuit the issue also flagged. Sample collection still stops exactly where it did.

Tests

  • Issue6810ZipSourceTest - single-entry and multi-entry (:::nodes.csv) archives.
  • Issue6811CsvDelimiterOptionTest - SQL WITH delimiter, CLI -delimiter, ; auto-detection, plus a guard that a plain comma file still imports with no delimiter set.
  • Issue6812JsonSkippedRecordTest - duplicate @id, missing @cat, plus a guard that the legitimate anonymous path still saves.
  • Issue6813XmlEmptySubElementTest - empty and self-closing siblings, plus a guard for nested sub-elements.
  • Issue6814AnalyzedPropertyLongTextTest - unit-level refutation, values after the cut-off, end-to-end CSV import, plus guards that genuinely numeric columns are still typed LONG/DOUBLE.

Full integration module green: 181 unit + 118 integration tests, including CSVImporterIT, JSONImporterIT, XMLImporterIT, JsonLImporterIT, Neo4jImporterIT, OrientDBImporterIT and XMLImporterFormatTest (the #2759 regression).

🤖 Generated with Claude Code

https://claude.ai/code/session_01QF6LJaiD6ZRr6oA9WZxVBK

Summary by CodeRabbit

  • Bug Fixes

    • Improved ZIP, local, and remote source reopening, including reliable archive-entry selection.
    • CSV imports now honor configured delimiters and detect semicolon-separated files.
    • Fixed JSON handling for skipped, duplicate, and mapped records.
    • Corrected XML imports so empty or self-closing elements do not inherit previous values.
    • Improved type detection for long text and numeric-looking data.
    • Source reset failures are now reported correctly.
  • Tests

    • Added coverage for ZIP, CSV, JSON, XML, and long-text import scenarios.

#6810 - importing any ZIP source silently yielded 0 records. Both reset
callbacks in SourceDiscovery called getNextEntry() on the OLD, already
closed ZipInputStream instead of the freshly created one, so the new
stream was left with no current entry - and a ZipInputStream with no
current entry reads as an empty file rather than failing. The reset path
runs on every import, and Source.reset() only logged the resulting
"Stream closed" IOException, so the import reported success. The new
stream is now positioned through the same seek the initial open uses
(including the :::<resource> entry, which reset never honoured), and
Source.reset() propagates instead of swallowing, so a broken re-open can
never again be mistaken for an empty input. The local reset also re-opens
through the same file-then-classpath resolution as the first open.

#6811 - analyzeSourceContent() unconditionally wrote knownDelimiter into
settings.options, but left it null for EntityType.DATABASE. The user's
-delimiter / WITH delimiter = ';' lands in that same map, so it was
destroyed for every CSV source and the whole line was parsed as a single
column, with a property literally named "id;name;age". The put is now
guarded, DATABASE reads the generic option back (falling back to
-documentsDelimiter), and ';' joins the auto-detection candidate set so a
semicolon file without a .csv extension is recognised instead of dying
with "Cannot determine the file type".

#6812 - createRecord() used one return signal for two opposite outcomes:
"no mapping, save this anonymously" and "rejected or deduplicated, drop
it". A record the importer had just logged as skipped (duplicate @id
without "@strategy": "merge", missing @cat/@type) was therefore saved as
an anonymous Document. The anonymous save now happens only when there was
no mapping object at all, and a deduplicated @id hands back the existing
record so callers link to it. That also removes a latent
ClassCastException in convertMap(), which cast an existing (immutable)
destination vertex to MutableVertex.

#6813 - in the XML importer lastContent was cleared only when a new
record started, never when a new sub-element started, so an empty or
self-closing sub-element inherited the previous sibling's text, in both
the import and the schema-analysis pass. This is the sub-element twin of
2759, which XMLImporterFormatTest fixed for attributes only. State is now
cleared on the sub-element boundary; deeper descendants still contribute
their text to the property, and an element with no character content
becomes an empty property rather than a missing or null one.

#6814 - AnalyzedProperty.setLastContent() treated a value longer than 100
chars as "stop sampling" AND as "no evidence about the type", returning
before the numeric probes and permanently disabling further analysis of
the column. A column whose first value looked numeric was declared LONG,
and the import then died converting the very value that should have
disproved it. Type refutation now runs on every value, independently of
sample collection.
@lvca lvca added this to the 26.9.1 milestone Aug 28, 2026
@lvca lvca self-assigned this Aug 28, 2026
@mergify

mergify Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@codacy-production

codacy-production Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 8 complexity

Metric Results
Complexity 8

View in Codacy

🟢 Coverage 83.15% diff coverage · -6.44% coverage variation

Metric Results
Coverage variation ✅ -6.44% coverage variation
Diff coverage ✅ 83.15% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (b7c6c80) 167722 134769 80.35%
Head commit (dd4c70e) 200138 (+32416) 147922 (+13153) 73.91% (-6.44%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#6865) 89 74 83.15%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@coderabbitai

coderabbitai Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 23fa1bdb-3a59-4534-b987-42b4c2a00269

📥 Commits

Reviewing files that changed from the base of the PR and between a7291a5 and dd4c70e.

📒 Files selected for processing (1)
  • integration/src/main/java/com/arcadedb/integration/importer/Source.java

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The importer now propagates reset failures, reopens and selects source streams correctly, preserves CSV delimiters, filters skipped JSON records, handles empty XML elements, and maintains type-analysis accuracy after sampling limits. Integration tests cover ZIP, CSV, JSON, XML, and long-text scenarios.

Changes

Importer regression fixes

Layer / File(s) Summary
Source reopening and delimiter handling
integration/src/main/java/com/arcadedb/integration/importer/Source.java, integration/src/main/java/com/arcadedb/integration/importer/SourceDiscovery.java, integration/src/test/java/com/arcadedb/integration/importer/Issue6810ZipSourceTest.java, integration/src/test/java/com/arcadedb/integration/importer/Issue6811CsvDelimiterOptionTest.java
Source resets now propagate callback failures, reopen local and remote streams, select requested ZIP entries, support classpath resources, and preserve or detect CSV delimiters.
JSON record filtering and vertex reuse
integration/src/main/java/com/arcadedb/integration/importer/format/JSONImporterFormat.java, integration/src/test/java/com/arcadedb/integration/importer/Issue6812JsonSkippedRecordTest.java
Mapped records rejected or deduplicated by createRecord() are no longer saved as anonymous documents. Destination vertices are validated and made mutable before modification.
XML empty-element state handling
integration/src/main/java/com/arcadedb/integration/importer/format/XMLImporterFormat.java, integration/src/test/java/com/arcadedb/integration/importer/Issue6813XmlEmptySubElementTest.java
XML loading and schema analysis clear per-element state and convert missing content to empty strings, preventing sibling-value inheritance.
Property type inference after sampling limits
integration/src/main/java/com/arcadedb/integration/importer/AnalyzedProperty.java, integration/src/test/java/com/arcadedb/integration/importer/Issue6814AnalyzedPropertyLongTextTest.java
Numeric candidacy is evaluated before sample collection stops. Oversized and later non-numeric values can refute numeric inference.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to dd4c7

The importer fixes are merge-ready after normal checks and review; no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 46 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address the coding objectives for all linked issues: ZIP stream reset and entry selection, delimiter preservation and semicolon detection, skipped JSON record handling, XML sibling state c…
Out of Scope Changes check ✅ Passed The implementation changes and added regression tests are directly related to issues #6810 through #6814. No unrelated code changes are identified.
Title check ✅ Passed The title clearly identifies the importer fixes for ZIP sources, delimiters, JSON records, XML values, and long-text type inference. It is specific and related to the main changes.
Description check ✅ Passed The description explains the five defects, motivations, related issues, implementation details, and regression tests. It omits the template headings and checklist, but it is otherwise substantially co…
Full details: Linked Issues check

Explanation

The changes address the coding objectives for all linked issues: ZIP stream reset and entry selection, delimiter preservation and semicolon detection, skipped JSON record handling, XML sibling state clearing, and numeric type refutation after sampling limits.

Full details: Description check

Explanation

The description explains the five defects, motivations, related issues, implementation details, and regression tests. It omits the template headings and checklist, but it is otherwise substantially complete.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/6810-6814-importer-batch

Comment @coderabbitai help to get the list of available commands.

com.arcadedb.utility.Callable.call() declares no checked exception, so
the IOException branch was unreachable: both reset callbacks in
SourceDiscovery already wrap their IOException into an ImportException.
Catching RuntimeException directly says so, and drops the instanceof
checks on the caught exception that ErrorProne flagged.
@claude

claude Bot commented Aug 28, 2026

Copy link
Copy Markdown

Review of PR #6865

Went through both commits (a7291a5 and dd4c70e) plus the five regression tests. Overall this is a solid, well-documented set of fixes - each defect has a clear root-cause explanation, a targeted fix, and a regression test described as verified-failing against main first. A few notes below, nothing blocking.

Correctness - traced through carefully, looks right

Minor observations (non-blocking)

  • Perf note on AnalyzedProperty treats a value longer than 100 chars as no evidence instead of disproving LONG/DOUBLE, so the column is typed numeric and the import then fails on that value #6814: fixing the early-return means a column that stays a numeric candidate for the whole file now pays Long.parseLong/Double.parseDouble attempts on every row instead of stopping once sampling is disabled. That's an inherent, justified cost of the correctness fix (unbounded parsing was exactly the bug), but worth knowing if a future profiling pass on very large imports flags AnalyzedProperty.setLastContent.
  • getSourceFromURL reset callback: the added source.inputStream.close() before connection.disconnect() looks like a good incidental fix (the local-file reset callback already closed its old stream first; the URL one didn't) but isn't called out in the PR description - might be worth a one-line mention so it doesn't look like an unexplained side effect during future archaeology.
  • Second commit (dd4c70e): good catch tightening Source.reset()'s catch clause to RuntimeException now that the IOException branch is provably dead (Callable.call() declares no checked exception) - confirmed by reading com.arcadedb.utility.Callable. Clean ErrorProne-driven cleanup.

Test coverage

Five new test classes, each isolated, each with try/finally cleanup (db.drop(), temp file .delete()) and TestHelper.checkActiveDatabases() at the end - consistent with the existing style in this test package (e.g. JSONImporterIT, XMLImporterIT use the same static-call pattern rather than extending TestHelper). Issue #6812's "without a mapping object the anonymous save still happens" test is a nice touch - it pins the intentional behavior so the fix can't be over-tightened later. Issue #6813's nested-descendant test similarly guards against a regression in the opposite direction.

Security / dependencies

No new dependencies. No System.out debug leftovers. The XXE/DTD hardening in XMLImporterFormat is untouched by this change.

Nice work - the "same signal used for two different outcomes" root-cause pattern in #6812 and the "early-return doubles as two different meanings" pattern in #6814 are exactly the kind of thing that's easy to introduce and hard to spot without a failing repro, and the fixes address the actual defect rather than papering over symptoms.

@claude

claude Bot commented Aug 28, 2026

Copy link
Copy Markdown

Review

Went through all five fixes in detail against the surrounding code (not just the diff), traced the data flow for each, and cross-checked the new regression tests against that logic.

Correctness

All five fixes hold up:

Minor/nit

  • Source.reset() still declares throws IOException, but the body now only ever catches/rethrows RuntimeException (the comment explains why a checked exception can't reach it, given com.arcadedb.utility.Callable.call() declares none). The throws IOException is effectively vestigial at this point - harmless since it's a widening declaration, but worth a second look if a future refactor is tempted to rely on it actually being thrown.
  • AnalyzedProperty.setLastContent()'s numeric-refutation cost is now paid on every value for the lifetime of a column scan (previously it stopped once collectingSamples went false). That's the correct tradeoff for the bug being fixed, and it's cheap once both candidate flags flip false (short-circuited boolean checks), so no real performance concern.

Test coverage

The five new test classes are well targeted: each pins the specific bug with a guard test for the previously-working path so the fix can't be "tightened" back into a regression, e.g. withoutAMappingObjectTheRecordIsStillSavedAsAnAnonymousDocument and nestedSubElementsStillContributeTheirTextToTheProperty. Good use of regression-test-first per repo convention. I didn't spot missing coverage for the described scenarios.

Security

No concerns - no new external input handling, no new dependencies, and the remote-source reset path already goes through ImportSecurityValidator.openRemoteConnection (unchanged by this PR other than adding a missing close() before disconnecting, which is a small resource-leak fix, not a security change).

Nice work - clear root-cause explanations, minimal targeted diffs, and tests that would have failed on main before the fix per the PR description.

@lvca

lvca commented Aug 28, 2026

Copy link
Copy Markdown
Member Author

CI note: the integration-tests lane failure on this PR is pre-existing on main and unrelated to these changes.

It fails on RemoteConsoleIT.userMgmt (console module, line 174 - create user albert identified by einstein grand connect on db1 is expected to raise a syntax error and no longer does). The same lane fails identically on main at b7c6c800d, which is the exact commit this branch is based on: run 33135270998 reports the same Tests run: 16, Failures: 1 on the same test, with none of this PR's changes present.

The lane went red on main somewhere around #6853, which rewrote ~249 lines of Console.java plus TerminalParser; the last completed main run whose integration-tests passed predates that merge. Worth its own issue - it is not something this PR can fix.

Everything this PR does touch is green: all 22 integration-module ITs passed in that same job, including CSVImporterIT, JSONImporterIT, XMLImporterIT, JsonLImporterIT, Neo4jImporterIT, OrientDBImporterIT and SQLRemoteImporterIT. vector-unit-tests is likewise red on main at the same commit.

@codecov

codecov Bot commented Aug 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 74.15730% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.74%. Comparing base (b7c6c80) to head (dd4c70e).
⚠️ Report is 32 commits behind head on main.

Files with missing lines Patch % Lines
...arcadedb/integration/importer/SourceDiscovery.java 68.42% 8 Missing and 4 partials ⚠️
...java/com/arcadedb/integration/importer/Source.java 28.57% 4 Missing and 1 partial ⚠️
...ntegration/importer/format/JSONImporterFormat.java 62.50% 1 Missing and 2 partials ⚠️
...integration/importer/format/XMLImporterFormat.java 88.88% 2 Missing ⚠️
...rcadedb/integration/importer/AnalyzedProperty.java 94.44% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6865      +/-   ##
==========================================
+ Coverage   71.73%   71.74%   +0.01%     
==========================================
  Files        1878     1878              
  Lines      167722   167751      +29     
  Branches    35543    35546       +3     
==========================================
+ Hits       120314   120360      +46     
+ Misses      32992    32987       -5     
+ Partials    14416    14404      -12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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