Skip to content

Support tags and attributes in tree-model schema export/import - #19150

Open
CritasWang wants to merge 8 commits into
apache:masterfrom
CritasWang:feat/schema-export-tags-attributes
Open

CritasWang wants to merge 8 commits into
apache:masterfrom
CritasWang:feat/schema-export-tags-attributes

Conversation

@CritasWang

@CritasWang CritasWang commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Tree-model export-schema dropped tags and attributes entirely, and import-schema had no way to restore them even though createMultiTimeseries / createAlignedTimeseries accept both. This PR makes a full export → import cycle preserve them exactly, including every special character.

It is four commits:

Commit Scope
bcaec8a3 [Server] Render tags and attributes as valid JSON in SHOW TIMESERIES prerequisite defect fix
01cf3c46 [Tools] Export and import tags and attributes in tree-model schema files the feature
ead56995 [IT] Cover the tags and attributes round trip integration coverage
f6d3e51f [Tools] Exit non-zero when import-schema connection retries are exhausted error reporting

Example

Create two time series whose metadata contains the characters that used to break the format:

CREATE TIMESERIES root.e2e.d1.s1 WITH DATATYPE=INT64, ENCODING=TS_2DIFF, COMPRESSION=SNAPPY,
  TAGS(room='101', type='sensor'), ATTRIBUTES(owner='team a', note='a"b');
CREATE TIMESERIES root.e2e.d1.s2 WITH DATATYPE=INT64, ENCODING=TS_2DIFF, COMPRESSION=SNAPPY,
  ALIAS=aliasA, TAGS(desc='a,b', p='a\b');

SHOW TIMESERIES root.e2e.** now renders both metadata columns as valid JSON:

Series Tags Attributes
root.e2e.d1.s1 {"room":"101","type":"sensor"} {"note":"a"b","owner":"team a"}
root.e2e.d1.s2 {"desc":"a,b","p":"a\\b"} (empty)

Export:

$ tools/schema/export-schema.sh -sql_dialect tree -t /tmp/out -pfn schema \
    -path "root.e2e.**" -h 127.0.0.1 -p 6667 -u root -pw root
$ cat /tmp/out/schema0_0.csv
Timeseries,Alias,DataType,Encoding,Compression,Tags,Attributes
root.e2e.d1.s1,,INT64,TS_2DIFF,SNAPPY,"{""room"":""101"",""type"":""sensor""}","{""note"":""a""b"",""owner"":""team a""}"
root.e2e.d1.s2,aliasA,INT64,TS_2DIFF,SNAPPY,"{""desc"":""a,b"",""p"":""a\\b""}",

Drop the database, import the same file into the empty database, and SHOW TIMESERIES gives back the values above, with the alias, data type, encoding and compression intact:

$ tools/schema/import-schema.sh -sql_dialect tree -s /tmp/out/schema0_0.csv \
    -db root.e2e -h 127.0.0.1 -p 6667 -u root -pw root
schema0_0.csv : Import completely successful!

Error path — when the connection cannot be re-established, the rows land in schema0_0.csv.failed and the command no longer reports success:

$ tools/schema/import-schema.sh -sql_dialect tree -s /tmp/out/schema0_0.csv -db root.e2e ...
Import schema fail: root.e2e.d1.s1: Could not reconnect to the server
$ echo $?
1
$ cat /tmp/out/schema0_0.csv.failed
root.e2e.d1.s1,,INT64,TS_2DIFF,SNAPPY,"{""room"":""101"",""type"":""sensor""}","{""note"":""a""b"",""owner"":""team a""}"

1. Why the server change is required

The client has no API that returns tags as a Map — Session/SessionPool only accept tagsList on write. Reading them is only possible through the Tags / Attributes columns of SHOW TIMESERIES, and TimeSeriesSchemaSource.mapToString concatenated keys and values without escaping, so that column was not parseable data:

tag value before consequence
a"b {"k":"a"b"} invalid JSON, parse fails
a\b {"k":"a�"} parses "successfully" but yields a<backspace> — silent corruption
a<TAB>b {"k":"a<TAB>b"} raw control character, invalid JSON

The fix escapes per RFC 8259 and keeps non-ASCII characters readable; it also removes the duplicate implementation in LogicalViewSchemaSource. Output is byte-identical for values that need no escaping, so ordinary schemas are unaffected.

2. File format

Export now writes seven columns:

Timeseries,Alias,DataType,Encoding,Compression,Tags,Attributes
root.t.d1.s1,,INT64,TS_2DIFF,SNAPPY,"{""room"":""101"",""type"":""sensor""}","{""owner"":""team a"",""note"":""a""b""}"
root.t.d1.s2,aliasA,INT64,TS_2DIFF,SNAPPY,"{""desc"":""a,b"",""p"":""a\\b""}",
root.t.d1.s3,,INT64,TS_2DIFF,SNAPPY,"{""q"":""`x`"",""multi"":""[  C  ]""}",
root.t.d1.s4,,INT64,TS_2DIFF,SNAPPY,,
  • Tags / Attributes are compact JSON objects with sorted keys and HTML escaping disabled; an absent set is an empty cell.
  • The CSV layer uses RFC4180 (quote ", no escape character, LF). JSON cells are therefore quoted with their inner quotes doubled, which is what makes them round-trip.

3. Compatibility

  • Files with the previous five-column header are still read with the legacy settings (quote='', escape=''`), so existing exports keep importing unchanged.
  • The new format is detected from the header (Tags or Attributes present, leading and trailing spaces ignored), and such a header is rejected unless all seven expected columns are there.
  • The metadata cells are read with a strict reader: a JSON array of pairs, an unquoted token, a duplicate key or trailing content is rejected instead of silently accepted.
  • User-visible change to note in release notes: tag/attribute values containing ", \ or control characters are now rendered escaped in SHOW TIMESERIES (previously the output was not valid JSON at all). Values without such characters are unchanged.
  • External scripts that split that column on "," would need adjusting.

4. Testing

Unit tests (real classes, no mocks except the session pool):

  • TimeSeriesSchemaSourceMapToStringTest (18 tests): every escaping case, and byte-identity with the old algorithm for values that need no escaping.
  • SchemaTagsFidelityTest (18) and SchemaTagsImportTest (19): JSON cell encoding (sorted keys, no HTML escaping, empty cell), RFC4180 bytes, CSV round-trip for " \ , tab newline CJK backtick, header normalisation, legacy detection, the create-call arguments for both the normal and the aligned path, and the connection-retry failure. The batch test was validated by reverting the fix and observing it fail (expected:<4> but was:<2>).

Full local runs: mvn test -pl iotdb-client/cli → 125/125; datanode test for the escaping change → 18/18; both locales (-P with-zh-locale) compile; dependency:analyze-only -DfailOnWarning=true clean.

End-to-end on a real standalone cluster (built from this branch): created 18 time series covering ", \, a literal \n, tab, newline, CJK+emoji, literal null, empty string, double spaces, backtick, a key with a space, multiple tags, attributes-only, neither, and an alias; exported, dropped the database, imported, and compared the server's rendering field by field — 18/18 identical. Editing one tag in the exported file with a spreadsheet tool and re-importing also worked, leaving the other rows untouched.

SchemaTagsRoundTripIT covers the same scenario in CI (three test methods: the round trip, an aligned import through the CLI, and isolation of invalid metadata rows). It could not be executed in this environment (the integration-test assembly references iotdb-core/ainode/dist/ainode/, absent here), but it compiles, is spotless-clean, passes the repository's IT-selection check, and the Simple (17) shard that owns its category is green on CI.

5. Not addressed here

Logical views, schema templates and device alignment are still not exported (they need different creation statements or device-level information); the import batch fix above is included because misaligned tags would otherwise corrupt exactly this feature's data.

@CritasWang
CritasWang force-pushed the feat/schema-export-tags-attributes branch from 3ffe671 to 087ed76 Compare November 9, 2026 07:58
} else {
builder.setQuote('`').setEscape('\\');
}
return builder.build().parse(new InputStreamReader(new FileInputStream(path)));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] Use an explicit UTF-8 charset for schema CSV I/O. The V2 format carries arbitrary tag and attribute text, but this reader uses the platform default charset. The exporter also opens new PrintWriter(filePath) with the platform default. On supported JDK 17 Windows, values such as 中文😀 may be replaced during export; files exchanged across platforms can also be decoded incorrectly on import. The new round-trip test reads the file as UTF-8, so this can fail there too. Please use UTF-8 consistently for writing, parsing, and header detection.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 610e1a2 — thanks, and you were right on all three points.\n\nAll schema I/O is now pinned to (11 call sites):\n\n| File | Site |\n| --- | --- |\n| | 3 × in (export, and the failed-records files) |\n| | parse stream, and (header detection) |\n| | 3 × (table-model SQL output) |\n| | and the failed-file |\n\nI also fixed the table-model sites in the same package: same defect, and leaving them would have produced the same review comment on the next PR.\n\nTwo regression tests in :\n- — writes through the real writer and compares the bytes on disk against the expected UTF-8 encoding.\n- — writes the file as UTF-8 bytes directly (so only the reader's charset can change the outcome) and reads it back through and .\n\nBoth are charset-sensitive rather than merely passing on a UTF-8 default: with the writer test fails before the fix ( — the character is replaced) and passes after it. Full suite: 102 tests, 0 failures; test-compile green; clean.

@HTHou HTHou left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Comments on the tree-model schema import path.

paths.add(0, path.substring(deviceId.length() + 1));
if (v2) {
// keep the maps aligned with the measurements list, whose head now holds this one
tags.add(0, recordTags);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Exercise aligned import through the CLI and server

The CLI rejects -aligned true with Unrecognized option. The new test sets aligned directly and expects the request to contain both s1 and root.sg.d.s1 alongside one data type. The server rejects the full path because each measurement must be a single node name.

Please register the CLI option and send one measurement with matching type, encoding, compression, alias, tags, and attributes per row. An end-to-end test would catch both failures.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 49d8409.

import-schema now registers -aligned / --use_aligned. Each valid aligned row sends exactly one measurement and one corresponding entry for type, encoding, compression, alias, tags, and attributes. MeasurementPath preserves quoted measurement names containing dots. The existing incorrect mock expectation has been corrected.

Added alignedImportThroughCliPreservesEveryRow, which runs the actual import script against the server for both v2 and legacy CSV files. It covers aliases, missing metadata, multiple measurements/devices, and a quoted measurement name, compares every schema field read back from the server, and checks that the devices are aligned.

Passed with both SimpleIT (1C1D) and ClusterIT (1C3D).

if (trimmed.isEmpty() || "null".equals(trimmed)) {
return null;
}
Map<String, String> parsed = JSON_GSON.fromJson(trimmed, JSON_CELL_TYPE);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Reject null metadata values before batching

Gson accepts a cell such as {"room":null} as a map containing a null value. Thrift then throws NullPointerException in writeString while serializing the map, so the entire createMultiTimeseries batch fails, including valid rows.

Please validate that each value in Tags and Attributes is a JSON string before adding the row to the batch. The existing failed-records path can then capture the invalid row.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 49d8409.

Metadata values are now decoded as JsonElement and checked to be strings before a row enters either import path. JSON nulls, numbers, booleans, arrays, and objects are rejected through the existing failed-records path. Empty metadata cells/objects and string values such as "null" remain supported, and duplicate-key rejection is preserved.

Added unit coverage for batch isolation and invalidMetadataIsIsolatedFromValidRowsThroughCli for the real script/server path. The latter checks all five invalid value types in both Tags and Attributes, verifies the exact 10 rows written to the failed file, and confirms that valid rows, including an aliased row, are created correctly.

Passed with both SimpleIT (1C1D) and ClusterIT (1C3D).

try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) {
String headerLine = reader.readLine();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P3] Use consistent header handling for format detection and parsing

The probe reads the first physical line. CSVParser skips leading empty lines, so a leading blank line sends a V2 file through the legacy parser and splits quoted Tags JSON containing a comma. A UTF-8 BOM also becomes part of the Timeseries header and causes validation to reject the file.

Please apply the same rules for leading blank lines and an optional BOM during detection and parsing.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 49d8409.

Format detection and CSV parsing now share the same UTF-8 reader, which strips an optional BOM at the start of the file. Detection skips leading empty lines consistently with the parser's ignoreEmptyLines setting. The separate RFC4180 and legacy backtick/backslash settings are retained.

Regression coverage includes LF/CRLF prefixes, BOM with and without leading empty lines, quoted/unquoted v2 headers, Tags JSON containing a comma, and legacy escaping. The real CLI/server tests also import files with a BOM and leading empty lines; all three integration cases passed in both 1C1D and 1C3D environments.

@CritasWang

Copy link
Copy Markdown
Collaborator Author

Pushed 49d8409 to address the three review comments:

  • Register the aligned import option and keep all measurement-indexed arguments paired, including aliases and metadata.
  • Reject non-string Tags/Attributes values before batching and record only the invalid rows in the failed file.
  • Handle an optional UTF-8 BOM and leading empty lines consistently during format detection and parsing, while retaining legacy CSV settings.

Local validation on macOS with Microsoft OpenJDK 21:

  • mvn -o clean test -pl iotdb-client/cli: 108 tests, 0 failures/errors/skips.
  • Full-reactor mvn -o test-compile -DskipTests, both with the default English locale and with -P with-zh-locale: passed.
  • SchemaTagsRoundTripIT through the real CLI scripts and server, using SimpleIT (1C1D) and ClusterIT (1C3D): 3 tests per profile, 0 failures/errors/skips. This includes the existing export/import round trip and the new aligned-import and invalid-metadata cases.
  • Spotless, Checkstyle, integration-test selection, and English/Chinese message-key and placeholder parity checks passed.

The integration runs used -Drat.skip=true: RAT was blocked by 263 pre-existing untracked local documentation files with unknown licenses. Those files were excluded from the commit, and all eight modified Java files retain their Apache license headers. Native Windows execution was not performed.

@HTHou HTHou left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The targeted CLI tests passed, and SchemaTagsRoundTripIT passed in both local 1C1D and 1C3D runs. The inline comments cover five additional cases reproduced with the CLI.

tagsList,
attributesList,
--retryTime);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Report aligned import failures when connection retries are exhausted

I ran import-schema -aligned true with a valid seven-column CSV and an unused local port. After exhausting its retries, the CLI printed Import completely successful!, exited with code 0, and produced no failed-record file. The last IoTDBConnectionException falls through this branch and the row is cleared.

Please propagate the final connection error to the command exit status and preserve the failed row for retry.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 686cf2f. Both create paths now return the failure instead of swallowing it: when the retries are exhausted, the affected rows are written to the failed-record file and throws, so exits non-zero and prints the failure (the message names the device or first path plus the last ).\n\nReproduced your scenario in a unit test: a mocked pool that always throws now makes the run throw and leaves in the failed file — for both the batch path and the aligned path (, ).

dataTypes.clear();
encodings.clear();
compressors.clear();
pathsWithAlias.clear();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Record failures from the aliased batch before clearing it

With -batch 2 and three aliased rows, an alias of bad.alias on the second row made the server reject the first two rows. The catch block reads paths, which is empty for an all-aliased batch. Only the third time series was created, but the CLI reported complete success and wrote no failed-record file.

Please capture the failed rows from the aliased batch, including their alias and metadata, before clearing its buffers.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 686cf2f. The aliased flush recorded from (empty for an all-aliased batch) instead of ; both the batch-boundary and the final flush now record the aliased rows, and each entry carries path, alias, type, encoding, compression, tags and attributes so the failed file is usable for a retry.\n\nCovered by : with two aliased rows and a pool that rejects the batch leaves both paths and both aliases in the failed file.

}

static boolean checkHeader(List<String> headerNames) {
if (isV2Format(headerNames)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Keep format detection and header validation consistent

A seven-column CSV with headers named Tags and Attributes is detected as V2 because the probe trims the names. The parser preserves the leading spaces, so validation and writeScheme treat the same file as legacy and silently discard both metadata columns. I verified that the CLI reported success and created the time series without its metadata.

Please use the same normalized headers throughout, or explicitly reject the file when a V2 header fails validation.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 686cf2f. Format detection, header validation and column lookup now share one pass, so a header like / is v2 consistently and the metadata columns are no longer dropped. also reports the seven-column format for such a file if a column is missing.\n\nCovered by : the padded header imports and the tags map reaches .

compressors.add(compressionType);
measurementAlias.add(StringUtils.isBlank(alias) ? null : alias);
if (v2) {
tags.add(recordTags);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P3] Omit metadata parameters for aligned rows with empty metadata

For aligned rows with both cells empty, the lists still contain a null entry. Session converts the entries to empty maps for Thrift, so the server writes a tag log record for each row. Importing the same 12 aligned measurements left tlog.txt at 0 bytes with the five-column CSV and wrote 8,400 bytes with the seven-column CSV.

Please omit both metadata lists when the aligned row has neither tags nor attributes.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 686cf2f. The aligned writer now calls the shorter overload when every metadata entry of the row is null, so no tag log record is written for a row without tags and attributes.\n\nCovered by , which snapshots the invocation and asserts only six arguments were passed; was extended to capture both overloads.

if (trimmed.isEmpty() || "null".equals(trimmed)) {
return null;
}
Map<String, JsonElement> parsed = JSON_GSON.fromJson(trimmed, JSON_CELL_TYPE);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P3] Require a JSON object with strict JSON syntax

The Gson map adapter accepts [["room","101"]], and the default parser accepts {"room":yes}. I verified that both cells import successfully, even though the format specifies a JSON object with string values.

Please check the root token and use strict JSON parsing while preserving duplicate-key rejection and the supported empty-cell behavior.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 686cf2f. Metadata cells are parsed with a strict () driven explicitly: the document must be an object, every value must be a JSON string token, trailing content is rejected and duplicate keys are rejected. The empty-cell and literal behaviours are unchanged.\n\nCovered by — , , and trailing garbage are all rejected while , empty and still work — and by .\n\nVerification for the whole batch: 115 tests pass, test-compile green, clean.

@CritasWang
CritasWang force-pushed the feat/schema-export-tags-attributes branch from 7a21e9f to 73daa4c Compare November 27, 2026 07:33
The tree-model schema source joined the tags and attributes maps into a JSON
object without escaping, so a value containing a quote, a backslash or a
control character produced a document that no JSON reader accepts. Escape the
string values the way RFC 8259 requires, leave printable non-ASCII characters
raw, and share the implementation with the logical view source instead of
keeping a second copy of it.
Extend the seven-column version 2 CSV with a Tags and an Attributes column so
that a tree-model schema exports and imports without losing metadata. The
columns hold a compact JSON object, written and read with the gson that ships
inside ratis-thirdparty-misc: the reader is strict, so a JSON array of pairs,
an unquoted token and a duplicate key are rejected instead of silently
accepted. A five-column file is still imported as before, the header alone
decides which format is in use, and every read and write pins UTF-8 so that a
non-ASCII tag survives a platform with a different default charset.

A rejected batch now reports its rows together with their alias and metadata
instead of dropping them, an exhausted connection retry reaches the exit
status instead of looking like success, and an aligned row without metadata
no longer passes all-null lists that make the server write a tag log record.
Export a schema that carries awkward tag values, aliases and every data type,
import it into an empty cluster and compare the result with what was exported.
The cases cover the presence combinations of tags and attributes and mixed
devices, and read a NULL alias back as null instead of the literal text.
@CritasWang
CritasWang force-pushed the feat/schema-export-tags-attributes branch from 73daa4c to ead5699 Compare November 27, 2026 07:35
@CritasWang

CritasWang commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

The branch is now rebased onto the current master and the history is rewritten into three commits, so the earlier per-comment commit hashes no longer exist. The working tree is byte-identical to the previous push.\n\n\n\nAll five review points are contained in :\n\n- an exhausted connection retry is recorded, its rows go to the failed-record file and the command exits non-zero;\n- a rejected aliased batch is recorded with its alias and metadata;\n- header names are normalised once, for detection, validation and column lookup;\n- an aligned row without metadata omits the metadata parameters;\n- the metadata cells are read with a strict reader that rejects a JSON array of pairs, an unquoted token, a duplicate key and trailing content.\n\nVerification on this revision: 35 schema tests pass, is clean, and [INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for Apache IoTDB Project Parent POM 2.0.13-SNAPSHOT:
[INFO]
[INFO] Apache IoTDB Project Parent POM .................... SUCCESS [ 2.237 s]
[INFO] IoTDB: API ......................................... SUCCESS [ 0.201 s]
[INFO] IoTDB: API: External API ........................... SUCCESS [ 0.503 s]
[INFO] IoTDB: API: External Service API ................... SUCCESS [ 0.257 s]
[INFO] IoTDB: API: Pipe API ............................... SUCCESS [ 1.080 s]
[INFO] IoTDB: API: Trigger API ............................ SUCCESS [ 0.277 s]
[INFO] IoTDB: API: UDF API ................................ SUCCESS [ 0.602 s]
[INFO] IoTDB: Protocol .................................... SUCCESS [ 0.270 s]
[INFO] IoTDB: Protocol: Thrift Commons .................... SUCCESS [ 0.853 s]
[INFO] IoTDB: Protocol: Thrift Data Node .................. SUCCESS [ 3.244 s]
[INFO] IoTDB: Client ...................................... SUCCESS [ 0.198 s]
[INFO] IoTDB: Client: Service-RPC ......................... SUCCESS [ 1.376 s]
[INFO] IoTDB: Client: isession ............................ SUCCESS [ 0.502 s]
[INFO] IoTDB: Client: Session ............................. SUCCESS [ 2.238 s]
[INFO] IoTDB: Client: Subscription ........................ SUCCESS [ 1.689 s]
[INFO] IoTDB: Client: Jdbc ................................ SUCCESS [ 1.418 s]
[INFO] IoTDB: Core ........................................ SUCCESS [ 0.329 s]
[INFO] IoTDB: Core: Antlr-Parser .......................... SUCCESS [ 0.415 s]
[INFO] IoTDB: Core: Relational-Antlr-Parser ............... SUCCESS [ 0.393 s]
[INFO] IoTDB: Protocol: Thrift Config Node ................ SUCCESS [ 1.784 s]
[INFO] IoTDB: Protocol: Thrift AI Node .................... SUCCESS [ 0.464 s]
[INFO] IoTDB: Protocol: Thrift Consensus .................. SUCCESS [ 0.548 s]
[INFO] IoTDB: Core: Metrics ............................... SUCCESS [ 0.151 s]
[INFO] IoTDB: Core: Metrics: Metrics API .................. SUCCESS [ 0.780 s]
[INFO] IoTDB: Core: Metrics: API Impl ..................... SUCCESS [ 0.578 s]
[INFO] IoTDB: Core: Node Commons .......................... SUCCESS [ 8.881 s]
[INFO] IoTDB: Core: Consensus ............................. SUCCESS [ 1.398 s]
[INFO] IoTDB: Core: Calc Commons .......................... SUCCESS [ 4.654 s]
[INFO] IoTDB: Core: Data-Node (Server) .................... SUCCESS [ 41.879 s]
[INFO] IoTDB: Client: CLI ................................. SUCCESS [ 2.061 s]
[INFO] IoTDB: Core: ConfigNode ............................ SUCCESS [ 5.785 s]
[INFO] IoTDB: UDF ......................................... SUCCESS [ 1.263 s]
[INFO] IoTDB: External-Service-Impl ....................... SUCCESS [ 0.157 s]
[INFO] IoTDB: External-Service-Impl: MQTT ................. SUCCESS [ 1.294 s]
[INFO] IoTDB: External-Service-Impl: Rest-OpenAPI ......... SUCCESS [ 1.325 s]
[INFO] IoTDB: External-Service-Impl: Rest ................. SUCCESS [ 1.613 s]
[INFO] IoTDB: Integration-Test ............................ SUCCESS [ 6.082 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:41 min
[INFO] Finished at: 2026-11-27T15:36:48+08:00
[INFO] ------------------------------------------------------------------------
[INFO] 567 goals, 567 executed succeeds.

…sted

The connection failure was already reported to the console and the
failed rows were written to the failed-record file, but writeScheme
threw IllegalStateException after all of that work was done and the
calling importSchemaFromCsvFile only caught IOException /
IllegalPathException, so the exception was swallowed by the generic
run() handler and importFromTargetPath returned CODE_OK (0).

Add a connectionFailed flag in AbstractSchemaTool. The
IllegalStateException that writeScheme raises on retry exhaustion is
now caught separately in importSchemaFromCsvFile, which sets the flag
instead of re-throwing. importFromTargetPath reads the flag after all
files are processed and returns CODE_ERROR when it is set.

Verified: import against an unreachable port now exits 1 for both
aligned and non-aligned paths, the failed-record file is still
written, and all 35 cli schema unit tests pass on both en and
zh-locale compile.
@CritasWang
CritasWang force-pushed the feat/schema-export-tags-attributes branch from 09f87bc to f6d3e51 Compare November 27, 2026 08:43
Conflicts were limited to the table-model schema tools, where master replaced
the line-based SQL splitting of import-schema with a lexer based stream:

- ExportSchemaTable: keep master's Path based target directory handling and
  this branch's UTF-8 FileWriter.
- ImportSchemaTable: adopt master's statement stream and re-apply the UTF-8
  reader and failed-record writer.
- ImportSchema: keep the status code returned by importFiles() and still exit
  non-zero when a file ran out of connection retries.

@HTHou HTHou left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I reproduced the four cases below with the CLI. I recommend fixing the three P2 issues before merging because they affect recovery from incomplete imports. The P3 JSON strictness issue can be addressed in a follow-up.

--retryTime);
}
for (String measurement : measurements) {
failedRecords.add(Collections.singletonList(deviceId + "." + measurement));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Preserve the full aligned row when connection retries fail

I confirmed that import-schema -aligned true now exits with code 1 when the server is unreachable. The .failed_0 file contains only the path. It drops the alias, data type, encoding, compression, tags, and attributes. Importing that record under the seven-column header fails with Index 1 out of bounds for length 1.

Please preserve the complete row in the failed file before clearing the aligned batch.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d224bad. The exhausted-retry branch of the aligned import now records the whole row of every measurement of the batch before the batch is cleared: path, alias, data type, encoding, compression, tags and attributes.

Covered by SchemaTagsImportTest#exhaustedAlignedConnectionRetriesKeepTheWholeRow, which asserts the seven cells and that the failed file is importable under the seven-column header.

row.add(i < dataTypes.size() ? dataTypes.get(i).name() : "");
row.add(i < encodings.size() ? encodings.get(i).name() : "");
row.add(i < compressors.size() ? compressors.get(i).name() : "");
row.add(tagsList != null && i < tagsList.size() ? toJsonCell(tagsList.get(i)) : "");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Keep failed CSV rows in one column order

With a valid header ending in Attributes,Tags, the rows rejected by CSV validation are saved in source order, while rows rejected by the RPC are saved in Tags,Attributes order. I reproduced both in a single .failed_0 file. When I restored the source header and retried, the RPC-failed row was imported with its owner attribute in Tags and its room tag in Attributes.

Please use one column order for every row in the failed file and write the corresponding header.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d224bad. Every rejected row is now kept in one canonical order (Timeseries, Alias, DataType, Encoding, Compression, Tags, Attributes) and projected onto the columns of the imported file only when the failed file is written, whose first line is that header. A header ending in Attributes,Tags therefore yields an Attributes,Tags failed file, and a legacy five-column file stays five columns. Rows rejected by the CSV validation copy their cells verbatim, so a rejected JSON cell is retried exactly as it was read instead of being re-serialized.

Covered by SchemaTagsImportTest#failedFileUsesOneColumnOrderForValidationAndRpcRejections: one validation rejection plus one RPC rejection end up in a single failed file under the source header, and re-importing that file puts owner back into Attributes and room back into Tags. #legacyFileFailsIntoAFiveColumnFileWithItsOwnHeader guards the legacy layout, and the integration test invalidMetadataIsIsolatedFromValidRowsThroughCli now asserts the header line as well.

String.valueOf(e.getMessage()));
} catch (StatementExecutionException e) {
ioTPrinter.println(Constants.INSERT_CSV_MEET_ERROR_MSG + e.getMessage());
System.exit(1);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Preserve failed records and continue after an aligned create rejection

With -aligned true, I imported a file containing an invalid metadata row, a valid row, a row with the alias bad.alias, and a final valid row. The server rejected the alias. Only the first valid row was created, and there was no failed file for the earlier validation error. System.exit(1) terminates the JVM before the failed rows are written and also stops other import workers.

Please record the server-rejected row, let the workers finish, and report the failure at the entry point.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d224bad. System.exit(1) is gone. A rejected aligned create now prints the server message, records the rejected rows, and returns the failure without aborting the remaining records of the file; at the end of the file the existing ConnectionRetriesExhaustedException path marks the run failed and ImportSchema returns CODE_ERROR, so the workers finish and the entry point reports the failure.

SchemaTagsImportTest#serverRejectedAlignedRowIsRecordedAndTheRestIsStillImported reproduces your file (invalid metadata row, valid row, bad.alias, final valid row): no JVM exit, both valid rows created, both rejected rows in the failed file, and the run reported as failed. The same flow is exercised end to end by SchemaTagsRoundTripIT against a real import-schema process.


private static Map<String, String> parseStrictJsonObject(String text) {
JsonReader reader = new JsonReader(new StringReader(text));
reader.setLenient(false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P3] Use strict JSON parsing for metadata cells

In the bundled Gson, setLenient(false) selects LEGACY_STRICT. I verified that the CLI still imports metadata strings containing a literal tab or the invalid escape \'.

reader.setStrictness(Strictness.STRICT) enforces JSON syntax. The duplicate-key and empty-cell handling can stay as implemented. This can be addressed in a follow-up.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 2d3001a rather than deferred. parseStrictJsonObject now calls reader.setStrictness(Strictness.STRICT); duplicate-key rejection, trailing-token rejection and the empty-cell/null behaviour are unchanged.

Covered by SchemaTagsFidelityTest#jsonSyntaxIsStrictlyEnforced: a raw tab and the escape \' are rejected, while \t and a plain apostrophe are still accepted.

The failed-record file mixed two column orders: the rows rejected by the CSV
validation kept the order of the imported file while the rows rejected by the
RPC were written in Tags,Attributes order, so restoring the header of a failed
file could put a tag into the attribute column. Every failed row is now kept in
one canonical order and projected onto the columns of the imported file when the
failed file is written, whose first line is the header its rows follow.

An exhausted connection retry on an aligned import kept the path only, which is
not importable, and a create the server rejected called System.exit, which lost
the rejected row and stopped the other import workers. Both paths now record the
whole row and let the file finish; the entry point reports the failure through
the existing status code.
setLenient(false) only selects LEGACY_STRICT, which still accepts a raw control
character inside a string and the invalid escape \'. The reader now uses
Strictness.STRICT, so a Tags or Attributes cell that is not JSON is rejected.
@CritasWang

Copy link
Copy Markdown
Collaborator Author

Pushed d224bad and 2d3001a to address all four points; the three P2 issues are fixed and the P3 JSON strictness is included rather than deferred.

  • d224bad makes the failed-record file retryable: every row is kept in one canonical order and projected onto the imported file's own header, which is written as the first line, and cells of rows rejected by the validation are copied verbatim. The aligned import now keeps the whole row both when the retries are exhausted and when the server rejects the create, and System.exit is gone, so the file finishes and the command reports the failure through the existing status code.
  • 2d3001a reads the metadata cells with Strictness.STRICT.

Local validation on macOS (Microsoft OpenJDK 17):

  • mvn -pl iotdb-client/cli -am test -Dtest=SchemaTagsImportTest,SchemaTagsFidelityTest,ImportSchemaTableTest,ImportSchemaTableStatusTest: 54 tests, 0 failures/errors (SchemaTagsImportTest 19 -> 23, SchemaTagsFidelityTest 18 -> 19).
  • mvn -pl iotdb-client/cli -am test-compile -P with-zh-locale -DskipTests: BUILD SUCCESS.
  • mvn verify -DskipUTs -Dit.test=SchemaTagsRoundTripIT -pl integration-test -am -P with-integration-tests: BUILD SUCCESS, failsafe reports 3/3, including the cases that drive a real import-schema process.
  • python3 .github/scripts/check-it-selection.py: passes.

One intentional format change: a .failed file now starts with the header line its rows follow. That header is what makes a file whose columns are not in canonical order safe to retry, and the chunking behaviour is unchanged.

@HTHou HTHou left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I verified the four earlier fixes with the CLI. The 42 focused unit tests and all three local 1C1D integration cases passed. I recommend fixing the two remaining failed-file retry issues before merging.

for (List<Object> failedRow : failedRecords.subList(from, from + step)) {
failureFileRecords.add(projectFailedRow(failedRow, columns));
}
writeCsvFile(failureFileRecords, failedFilePath + "_" + fileIndex++);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Make the generated failed files importable through the CLI

I passed a generated schema.csv.failed_0 to import-schema -s against a running server. The CLI printed that the filename must end in csv, skipped the file, and exited with code 0. Renaming that same seven-column file to .csv restored the row and its metadata.

The current retry test calls importSchemaFromCsvFile directly, so it bypasses the filename check. Please make the generated file usable through -s and exercise the original filename in the retry test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 969d6c2. The generated chunks are now named <stem>.failed_<n>.csv (schema.csv -> schema.failed_0.csv, same name under -d <failed dir>), so the dispatcher's suffix check selects them and a failed file can be passed to -s exactly as it was written; chunking by linesPerFile is unchanged and the table dialect's statements.sql.failed naming is untouched.

SchemaTagsRoundTripIT#invalidMetadataIsIsolatedFromValidRowsThroughCli now takes the generated file and feeds it back to import-schema -s <generated file>: it asserts the CLI does not print the must-end-with-csv message for it and does process its rows. The unit retry tests import the generated file itself instead of a renamed copy.

One consequence worth flagging: because the failed files are *.csv now, a directory import (-s <dir>) also re-attempts files a previous run left there. That is what makes them usable through -s, but it is a behaviour change for directory imports - tell me if you would rather keep those untouched.

.setEscape('\\')
.setQuoteMode(QuoteMode.NONE)
.build();
this.csvFormat = createRfc4180CsvFormat().setHeader().setSkipHeaderRecord(true).build();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Preserve legacy CSV escaping in five-column failed files

A valid five-column source can contain a path whose measurement is sensor,1, with the comma escaped as \, in the source. After a connection failure, the failed file keeps the five-column header but quotes the path using RFC 4180. On retry, that header selects the legacy parser, which splits the path at the comma and shifts the remaining cells.

I verified that the original source creates the series. Renaming the generated failed file to .csv and importing it creates zero series. Please use compatible CSV rules when writing and reading five-column failed files, and include an escaped comma in the retry test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 969d6c2. The failed-record writer now picks the dialect from the columns it actually writes: a five-column file is written with the legacy escaped-delimiter layout (a comma inside a cell becomes \,, no quote char, matching what readCsvFile selects for a header without Tags and Attributes), while a seven-column file keeps RFC4180.

Covered by SchemaTagsImportTest#legacyFailedFileKeepsItsEscapedCommaAndCanBeImportedAgain: a source row whose path is root.sg.d.sensor\,1 runs out of connection retries, the generated file contains exactly root.sg.d.sensor\,1,aliasA,INT64,TS_2DIFF,SNAPPY and no " at all, and importing that generated file creates the series under root.sg.d.sensor,1 with alias, datatype, encoding and compression still in their own columns. On the pre-fix code the same row is written as "root.sg.d.sensor,1",aliasA,... and re-reads as six cells, which is the shift you reported.

A five-column failed file was written with RFC4180 quoting while the reader
selects the legacy dialect for a header without Tags and Attributes, so a path
carrying an escaped comma was quoted and then split at that comma on retry,
shifting every cell that followed it and creating no series. The failed-record
writer now picks the dialect from the columns it writes: the legacy escaped
delimiter for five columns, RFC4180 for seven.

The generated chunks are also named <stem>.failed_<n>.csv, so import-schema
selects them by suffix and a failed file can be fed back through -s exactly as
it was written instead of being renamed first.
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.

3 participants