Skip to content

Fix library UDF edge cases - #17871

Open
Caideyipi wants to merge 34 commits into
apache:masterfrom
Caideyipi:fix/library-udf-edge-cases
Open

Caideyipi wants to merge 34 commits into
apache:masterfrom
Caideyipi:fix/library-udf-edge-cases

Conversation

@Caideyipi

@Caideyipi Caideyipi commented Jun 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Fix validation, empty-input handling, invalid values, and instance-reuse state leaks across library UDF/UDAF implementations.
  • Preserve MAD aggregation/null semantics and sampled INT64 values when input Row objects are reused.
  • Correct DWT level handling and numerical/timestamp edge cases in Histogram, MinMax, Spline, AR, and moving averages.
  • Fix extreme-value median/MAD calculations and DTW aggregate-state merging, including interleaved partial states.
  • Defer merged DTW match rebuilding until final output and use rolling rows for DTW scratch space.
  • Add regression coverage with test fixtures that model reused input objects and valid access-window sizes.

Examples

  • Spline input timestamps and values 0,1,2,3,4 with points=4 previously emitted timestamps [0,1,3,4] but values approximately [0,1.3333,2.6667,4]. Values now use the emitted timestamps, producing [0,1,3,4]; the terminal value is also preserved when extreme timestamps share a double coordinate. With points=10 over the same timestamp range, it emits each of the five available timestamps once.
  • Histogram with min=0, max=100, and count=100 assigns input 29 to bucket 29. For the subnormal range 0..5*Double.MIN_VALUE with two buckets, inputs 2*Double.MIN_VALUE and 3*Double.MIN_VALUE now produce counts [1,1].
  • A moving average with window=2 and values [Double.MAX_VALUE,Double.MAX_VALUE,0,2,4] skips the overflowing window and recovers with values [Double.MAX_VALUE/2,1,3]. Compensated summation also preserves the average 1 once the large values leave [1e16,1e16,1,1].
  • Two Integer.MAX_VALUE or Double.MAX_VALUE samples return the correct finite median. The median of [Long.MIN_VALUE,Long.MAX_VALUE] is -0.5; adjacent large INT64 values retain MAD 0.5 by subtracting before conversion to double.
  • DTW pattern [1,2,3] over values [1,2,3,1,2,3], split after the first value, returns both windows [1,3] and [4,6]. Matches survive interleaved/reversed/grouped state merges and serialization. Merges accumulate input; final output rebuilds chronological matches when required.
  • Series-mode LOF with method=series, window=1, and k=2 over [0,0.1,100,100,0.2], split across access windows after the fourth value, previously returned 1.0 for the final value because only the latest k vectors were candidates. It now returns 0.875 using the previous up-to-2k vectors plus the current vector.

Validation

  • mvn -o spotless:apply -P with-integration-tests -pl library-udf: passed.
  • mvn -o clean test -pl library-udf -am: 139 tests passed, no failures/errors/skips.
  • mvn -o clean test-compile -pl library-udf -am -P with-zh-locale -DskipTests: passed.
  • Lifecycle Checkstyle and git diff --check: passed.
  • Four numerical regressions were reproduced before their production fixes. All newly added tests were run locally.

Both clean reactors rebuilt the required IoTDB source dependency closure with local and remote build caches disabled (-Ddevelocity.cache.local.enabled=false -Ddevelocity.cache.remote.enabled=false). Validation used a local offline fallback because remote Maven plugin downloads were blocked. No full-project build or performance benchmark was run. Remote CI was not waited on or polled.

DTW retains effective input points to support arbitrary temporal merge ordering/interleaving. State memory and serialized state grow with input count plus matches. Merges no longer repeatedly recalculate historical windows; a pending chronological rebuild runs at final output. DTW scratch memory is linear in pattern length, while each window still requires quadratic computation in pattern length.

Caideyipi added 9 commits June 9, 2026 09:46
…rary-udf-edge-cases

# Conflicts:
#	library-udf/src/main/java/org/apache/iotdb/library/anomaly/UDTFKSigma.java
#	library-udf/src/main/java/org/apache/iotdb/library/anomaly/UDTFRange.java
#	library-udf/src/main/java/org/apache/iotdb/library/dprofile/UDAFPercentile.java
#	library-udf/src/main/java/org/apache/iotdb/library/dprofile/UDAFQuantile.java
#	library-udf/src/main/java/org/apache/iotdb/library/dprofile/UDAFSpread.java
#	library-udf/src/main/java/org/apache/iotdb/library/dprofile/UDTFDistinct.java
#	library-udf/src/main/java/org/apache/iotdb/library/dprofile/UDTFSample.java
#	library-udf/src/main/java/org/apache/iotdb/library/drepair/UDTFTimestampRepair.java
#	library-udf/src/main/java/org/apache/iotdb/library/drepair/UDTFValueFill.java
#	library-udf/src/main/java/org/apache/iotdb/library/drepair/UDTFValueRepair.java
#	library-udf/src/main/java/org/apache/iotdb/library/frequency/UDFEnvelopeAnalysis.java
#	library-udf/src/main/java/org/apache/iotdb/library/match/UDAFDTWMatch.java
#	library-udf/src/main/java/org/apache/iotdb/library/match/UDAFPatternMatch.java
@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Self-reviewed this PR. Fixed the quantile floating-point ordering issue involving negative zero; I did not find any other issues.

Resolve UDF validation conflicts while preserving edge-case checks and upstream localized messages.
@Caideyipi
Caideyipi marked this pull request as draft November 13, 2026 03:02
@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Independent re-review completed for 1b94fa945b8ae6c7f71db515177888e3aa664767 against master baseline cca1dbbde6d0dffa38495c92c92a48b2626d2f99, covering the full 84-file diff and relevant context.

Fixed in 063697ab5b89817786a987034b92d718f97e6d18:

  • P1 — Reused rows in isometric sampling: RowIterator.next() reuses one Row. Retaining those objects repeated the final row, or read a final null row. Sampling now retains indexes and reads each selected row immediately; the test iterator now follows the API's reuse contract. UDTFSample.java:182
  • P2 — INT64 precision in triangle sampling: endpoint/all-points branches converted unchanged values through double, e.g. 9007199254740993 became 9007199254740992. These branches now preserve typed values. UDTFSample.java:168
  • P2 — Excess DWT layers: Java's shift-distance masking made layer=33 reconstruct the wrong signal. Inversion now derives the actual forward levels from the signal and filter lengths. DWTUtil.java:247
  • P2 — Spline timestamp precision: converting absolute timestamps to double before subtraction collapsed nearby nanosecond timestamps and caused a non-monotonic-sequence exception. The integer difference is now calculated first. UDTFSpline.java:86
  • P2 — Pattern-test false positives: the result-builder stub fabricated a non-null position even without a write. Tests now use BinaryColumnBuilder and assert exactly one output position. UDAFPatternTest.java:281

The UDAFMad conflict resolution correctly preserves the upstream exception for degenerate sketch results, null/non-finite filtering, and empty-input handling. The UDAFMadTest proxy's isNull response is effective; both MAD tests pass. No further MAD changes were needed.

Validation:

  • All four behavioral regressions were reproduced before their fixes.
  • Offline clean reactor test (library-udf -am, build-cache reuse disabled): 111 passed, 0 failures, 0 errors, 0 skipped. All newly added tests were run locally.
  • Offline clean Chinese-locale reactor test-compile: passed.
  • Spotless apply with with-integration-tests, lifecycle Checkstyle, English compilation, en/zh message-key and format-specifier parity, and PR-diff whitespace checks: passed.

Final local commit, confirmed source-branch head, and confirmed PR head are all 063697ab5b89817786a987034b92d718f97e6d18. The update is complete and the PR remains Draft because this round found behavioral/test-logic issues; a fresh independent re-review is required. No CI waiting or polling was performed.

@Caideyipi

Caideyipi commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Independent re-review of PR #17871

Reviewed the requested starting head 063697ab5b89817786a987034b92d718f97e6d18 against baseline cca1dbbde6d0dffa38495c92c92a48b2626d2f99. I inspected the complete 84-file diff and relevant context, including MAD state merging and isNull, sampling object reuse and INT64 precision, DWT level calculations, spline timestamp handling, and test doubles.

Confirmed behavior issues found and fixed during this round in commits df4183ead2c54fa27c59420554da7e889f524ab6 and a8e5d9e1f70c240a74c67a7f9135cc5bbc3fb25b:

  • P2 — Triangle sampling lost INT64 precision for selected interior points. The selected value now goes through the typed value writer instead of double. UDTFSample.java:216
  • P2 — Histogram bucket placement was inaccurate for adjacent large bounds and unsafe across extreme or subnormal ranges. The normalized calculation now avoids loss of boundary precision and range overflow/underflow. UDTFHistogram.java:82
  • P2 — MinMax normalization could produce an incorrect result when finite endpoints made max - min overflow. A scaled fallback now preserves normalization across the double range. UDTFMinMax.java:130
  • P2 — Spline timestamp arithmetic could overflow or collapse distinct timestamps into the same double coordinate over a wide range; endpoint evaluation could also produce non-finite output. Coordinates and output timestamps now use overflow-safe arithmetic, and endpoint results are handled explicitly. UDTFSpline.java:94 UDTFSpline.java:134

Validation: the offline clean library-udf source-reactor test passed all 117 tests; Spotless, Checkstyle, clean English and Chinese test-compiles, message-constant/placeholder parity, and git diff --check passed. All added tests were run locally. Remote Maven resolution was blocked while downloading a Central plugin, so verification used the local offline fallback. CI was not polled.

Final local commit, source branch head, and PR head are a8e5d9e1f70c240a74c67a7f9135cc5bbc3fb25b. The PR remains Draft because this round found behavior issues; a fresh independent re-review is required.

@Caideyipi

Caideyipi commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Independent re-review: fixes completed, Draft retained

Completed one review round of the full diff and relevant context, including MAD merge/isNull, sampling Row reuse and INT64 precision, DWT levels, Histogram/MinMax extremes, Spline timestamps/coordinates/endpoints, and test fixtures.

  • Reviewed head: a8e5d9e1f70c240a74c67a7f9135cc5bbc3fb25b
  • Comparison base: cca1dbbde6d0dffa38495c92c92a48b2626d2f99
  • Final local commit: 033b55d1474c978dd1b4ee07138f337809ede990
  • Confirmed source branch and PR head: 033b55d1474c978dd1b4ee07138f337809ede990

Six behavior issues and one test-fixture issue were found and fixed:

  1. Spline output coordinates: for t=y=0..4, points=4, rounded timestamps [0,1,3,4] previously carried values [0,1.3333,2.6667,4]. Interpolation now evaluates at the emitted timestamps.
  2. Spline terminal coordinate collisions: timestamps near Long.MAX_VALUE can share a double coordinate across the full long range. The final input value is now retained instead of being discarded.
  3. AR small-amplitude inputs: the absolute epsilon cutoff suppressed valid coefficients, e.g. [1e-8,2e-8,3e-8] should yield 6/7. The guard now rejects only zero or non-finite denominators.
  4. DTW pattern validation: comma-only patterns could pass validation because split discarded empty elements. Empty elements, including trailing commas, are now rejected.
  5. Histogram boundaries: with [0,100] and 100 buckets, input 29 could fall into bucket 28. Division by bucket width now preserves this exact boundary, with the existing extreme-range scaling and a fallback when width underflows.
  6. Moving-average recovery: an overflowing sum permanently poisoned later finite windows. A non-finite sum is now rebuilt from the current window; non-finite results are skipped and subsequent finite windows recover.
  7. RowWindow fixture: getRow() returned independent objects despite the intended reuse coverage. It now exposes a shared mutable Row and actual data types, and sampling tests explicitly assert object reuse.

Additional baseline fixes included

The two baseline observations identified during the completed round are now repaired in 033b55d1474c978dd1b4ee07138f337809ede990, following the initial review fixes in c1b81b14a3041e5cdb8cce797ee5cd3e9c835d1f. This implementation follow-up did not start another independent review round.

  • Extreme medians and MAD: two Integer.MAX_VALUE or Long.MAX_VALUE samples previously produced median -1, and two maximal finite floating-point values produced infinity. INT32/FLOAT addition is widened, INT64 values are summed exactly before conversion, and DOUBLE operands are halved only when their sum overflows. Opposite long extremes produce -0.5, and subnormal medians retain their precision.
  • DTW aggregate merging: replaying only the source's final buffer lost historical and boundary matches and could manufacture windows across discarded input. States now retain effective timestamp/value pairs, merge chronologically, and rebuild matching windows without duplicating partial results. Serialization preserves the required input; deserialization initializes/replaces fresh or reused states. Regressions cover historical/boundary matches, false windows, interleaved/reversed/grouped merges, continued input, source immutability, and state round trips.

Resource impact: DTW state memory now grows with accepted input count plus matches, and each combine recalculates windows. This supports arbitrary temporal ordering/interleaving of partial states. No performance benchmark was run.

Validation: all ten additional regressions failed before the production fixes (nine assertion failures and one deserialization NPE), then passed after repair. The earlier six behavior regressions also reproduced before their fixes. Spotless, Checkstyle (0 violations), and git diff --check passed. The final English clean source reactor passed all 133 tests (0 failures/errors/skips); the final Chinese clean source reactor passed test compilation. Both reactors included the required IoTDB source dependencies and disabled local build-cache reuse. A local offline fallback was used because remote Maven plugin downloads were blocked. All newly added tests were run locally. This was focused library-udf verification, not a full-project fresh-dependency build.

The source branch had not changed before either push. The final local commit, source branch, and PR head all match 033b55d1474c978dd1b4ee07138f337809ede990. The PR remains Draft and requires a fresh full-diff review before Ready. No remote CI waiting or polling was performed. This edits the existing single round summary; no additional top-level summary was posted.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Independent re-review: one complete round

Reviewed the complete 86-file diff from baseline cca1dbbde6d0dffa38495c92c92a48b2626d2f99 to 033b55d1474c978dd1b4ee07138f337809ede990, plus relevant implementation/API/test context.

The review covered MAD merge/null semantics, sampling Row reuse and INT64 precision, DWT levels, Histogram/MinMax extremes, Spline timestamps/coordinates/endpoints and test fixtures, AR/DTW validation, moving-average recovery, ExactOrderStatistics extreme-value median/MAD, and DTW history, cross-partition matching, interleaved/reversed/multilevel merges and serialization.

Outcome: six actionable findings were fixed in 111fd493b7a. The final local commit, remote source branch Caideyipi/iotdb:fix/library-udf-edge-cases, and PR head were all confirmed as 111fd493b7a4ab63437394e50beaa09ae72b7c94. The source head was checked immediately before pushing and had no concurrent update. Draft status is retained because this round found behavioral and test-logic issues; a fresh independent re-review is required.

Findings and repairs

Locations below refer to the reviewed commit.

  1. [P2] INT64 MAD loses small deviations at large offsets: ExactOrderStatistics.java:181. Converting samples/median to double before subtraction makes the MAD of adjacent large INT64 values zero instead of 0.5. The fix calculates twice the median and doubled absolute deviations with BigInteger before conversion. Added odd/even and extreme-offset regressions.

  2. [P2] A nonzero subnormal histogram width can still misclassify buckets: UDTFHistogram.java:90. For range 0..5*Double.MIN_VALUE, two buckets, and inputs 2*MIN_VALUE,3*MIN_VALUE, rounded division by the bucket width produces [0,2] instead of [1,1]. The fix uses the normalized ratio for subnormal widths; tests cover positive and negative bounds.

  3. [P2] Spline can emit duplicate timestamps: UDTFSpline.java:119. Input timestamps/values 0..4 with points=10 generate repeated timestamps, violating the PointCollector requirement for strictly increasing output. The fix caps the output count to the available integer timestamps and uses that count for spacing and endpoint selection. The collector regression enforces increasing timestamps and verifies values.

  4. [P2] Moving averages lose finite small values after large samples leave: UDTFMvAvg.java:75. With window=2 and values [1e16,1e16,1,1], the final average is 0.5 rather than 1. Recovery triggered only by nonfinite sums misses this cancellation. The fix uses compensated additions/removals and resets compensation when rebuilding after overflow. Regressions also cover positive/negative maximum doubles and subsequent windows.

  5. [P2] DTW merge repeatedly recalculates all historical windows: UDAFDTWMatch.java:143. Each combine copied the complete accumulated input and recomputed every window. Sequentially combining many small partitions therefore makes matching work quadratic in partition count for a fixed pattern. The fix accumulates incoming points and defers a required chronological rebuild to final output, persists the pending-rebuild flag through serialization, and uses two rolling DTW rows. Tests cover repeated small interleaved merges, serialization before output, continuation, repeated output, source immutability, and nonzero-distance threshold boundaries.

  6. [P2] The LOF series regression used an impossible access window: UDFWindowAndQueueTest.java:279. It configured a two-row window but supplied six rows, so the asserted result could not arise under the configured engine access strategy. The corrected test uses the default access window and embedding size five, with nine input rows including two invalid values, preserving the expected three output timestamps.

Verification

  • Four numerical regressions failed against their pre-fix implementations, then passed after repair.
  • mvn -o spotless:apply -P with-integration-tests -pl library-udf: passed.
  • mvn -o clean test -pl library-udf -am: 139 tests, zero failures/errors/skips.
  • mvn -o clean test-compile -pl library-udf -am -P with-zh-locale -DskipTests: passed.
  • Lifecycle Checkstyle and git diff --check: passed.
  • Both clean source reactors disabled local and remote build caches using -Ddevelocity.cache.local.enabled=false -Ddevelocity.cache.remote.enabled=false. Required IoTDB source dependencies were rebuilt.
  • All newly added tests were run locally. Validation used the local offline fallback because remote Maven plugin downloads were blocked.
  • No full-project build or performance benchmark was run. Remote CI was neither waited on nor polled.

DTW resource limits

The retained ordered input remains O(N + R) in state memory and serialized size, where N is the effective input count and R the match count; arbitrary temporal interleaving still requires the historical input. The merge repair removes repeated historical DTW recalculation during combines. A pending rebuild at final output still costs O(N * L^2) for pattern length L, with O(L) DTW scratch space. This is an algorithmic assessment, not a measured performance result.

This session completed one review round and its repairs; it did not conduct another review after the update.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Independent re-review completed: one full round of the 86-file diff and relevant implementation, API, and test context.

  • Reviewed head: 111fd493b7a4ab63437394e50beaa09ae72b7c94
  • Comparison base: cca1dbbde6d0dffa38495c92c92a48b2626d2f99
  • Final local commit, confirmed source branch head, and confirmed PR head: 32f25d9cedd8af43529c3c0ea26487b2b7344c6a

Two behavioral issues were found and fixed in this round. Locations below refer to the reviewed head.

  1. [P2] DTW raw and continued input did not invalidate cached matches when timestamps went backwards or an earlier value was replaced. DTWState.java:108. With pattern 1,2,3 and threshold 0, feeding timestamps 6,5,4,3,2,1 with corresponding values 3,2,1,3,2,1 missed both chronological matches. Likewise, after merging and observing times 1,3,4, inserting time 2 did not rebuild the historical windows. Updating an earlier value could leave an obsolete match. Non-increasing timestamps now mark the state for the same deferred chronological rebuild used by merges. Regressions cover batches, late continuation after output, historical replacement, serialization before rebuilding, and repeated output.

  2. [P2] Moving-average compensation could itself lose small values permanently. UDTFMvAvg.java:97. For window=3 and input [1e300,1e150,1,1,1], the final window [1,1,1] returned 0 instead of 1; all sums remained finite, so overflow recovery did not help. The fix detects lost compensation bits or overflowing additions, reconstructs the active window sum exactly once, and then updates that exact sum incrementally. The regression covers both signs, subsequent windows, and resetting the function for another run.

The review also covered MAD null handling and INT64 extremes, sampling Row reuse and typed INT64 output, DWT levels, Histogram normal/subnormal/extreme ranges, MinMax extremes, Spline timestamps/coordinates/endpoints/duplicate timestamps and fixtures, AR/DTW validation, LOF valid-window coverage, and DTW history, cross-partition matches, interleaved/reversed/multilevel merges, serialization, continuation, and repeated output.

Validation:

  • All three new regressions failed against the reviewed production implementation, then passed after repair.
  • Local offline mvn -o clean test -pl library-udf -am: 142 tests, zero failures/errors/skips.
  • Local offline Chinese clean test-compile -pl library-udf -am -P with-zh-locale -DskipTests: passed.
  • Spotless with with-integration-tests, lifecycle Checkstyle (zero violations), and git diff --check: passed.
  • Required IoTDB dependencies were rebuilt from clean source; both clean reactors disabled local and remote build caches. All newly added tests were run locally. The local offline fallback retained the previously established remote Maven plugin-download limitation; no new external dependencies were introduced.
  • No full-project build or performance benchmark was run. CI was neither waited on nor polled.

Resource assessment: DTW still retains O(N + R) state and serialized data for N effective input points and R matches. A pending final rebuild costs O(N * L^2) for pattern length L, with O(L) DTW scratch space. Combines insert incoming points without recalculating all historical DTW windows; serialization and multilevel transfer still traverse retained input. This is an algorithmic assessment, not a measured performance result. The moving-average exact fallback retains the active window and an incremental sum, with a one-time window reconstruction.

The source branch was checked immediately before pushing and had no concurrent update. The source branch and PR head were both confirmed at the final SHA above, and the PR remains Draft because this round found behavioral issues. A fresh independent full-diff re-review is required before Ready. No second review round was started after these repairs.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Independent re-review

  • Reviewed SHA: 32f25d9cedd8af43529c3c0ea26487b2b7344c6a.
  • Fixed comparison baseline: cca1dbbde6d0dffa38495c92c92a48b2626d2f99.
  • Final local SHA, confirmed source-branch SHA, and confirmed PR-head SHA: 8c37cb0e5e083759420ae840558064b500db35ab.
  • Source: Caideyipi/iotdb:fix/library-udf-edge-cases. The source and PR heads matched the reviewed SHA immediately before the update; the push used an explicit expected-SHA lease and was a fast-forward. The PR is confirmed Draft.

Finding and fix

P2 — Subnormal Histogram widths misclassify exact bucket boundaries (reviewed UDTFHistogram.java:90). With min=0, max=22*Double.MIN_VALUE, and count=22, an input of 15*Double.MIN_VALUE enters bucket 14 instead of bucket 15: (15.0/22)*22 rounds to 14.999999999999998. This changes the reported histogram counts.

Commit 8c37cb0e5e083759420ae840558064b500db35ab computes the subnormal-width bucket index from exact binary-double values using an integral decimal quotient and clamps endpoints before indexing. The new regression enumerates representable points in positive and negative subnormal ranges, including widths rounded to a nonzero subnormal and widths underflowing to zero; expected bucket counts use an independent integer oracle. The regression reproduced the failure before the production fix.

Review coverage and resource costs

The review covered the complete fixed-base diff and relevant context, including MAD merge/null handling and INT64 extremes; sampled Row reuse and INT64 precision; DWT levels; Histogram/MinMax extremes; Spline timestamps, coordinates, endpoints, duplicates and test doubles; AR/DTW validation; moving-average overflow and compensated-sum recovery; LOF valid-window tests; and DTW history, cross-partition/interleaved/reverse/multilevel merges, deferred rebuild, serialization, continued input and repeated output. No further in-scope actionable issue was confirmed in this round.

For DTW, with N retained input points, R matches and pattern length p, static inspection gives O(N+R+p) retained state and 9 + 16N + 20R serialized bytes. A merge copies retained input, with ordinary map insertion cost O(M log(N+M)) for M source points, and defers DTW replay. Dirty finalization costs approximately O(N*p^2), with O(p) scratch space; multilevel merges repeatedly copy inputs. These are static costs, not measured performance results.

Validation

  • The new regression failed on the reviewed implementation before the fix (one failure, no errors or skips).
  • Local offline clean test -pl library-udf -am: 143 tests, zero failures, errors or skips. Required IoTDB dependencies were rebuilt from clean source, with both local and remote build caches disabled. All newly added tests ran locally.
  • Chinese-profile offline clean source-reactor test-compile, Spotless apply, lifecycle Checkstyle and git diff --check passed.
  • Local verification used the previously established fallback for blocked remote Maven plugin downloads. No full-project build or performance benchmark was run. CI was neither awaited nor polled.

This round found and fixed a behavioral issue, so the PR remains Draft pending a complete independent re-review in a fresh session. No second review round was started in this session.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Independent re-review round: Apache IoTDB PR #17871

  • Reviewed PR head: fec98a0610a61235e8b0250ade51a06e4ef338c3; previous review SHA: 39aed757e38cd3f7cda69aa7c0c3a78bd18df08c; fixed base: cca1dbbde6d0dffa38495c92c92a48b2626d2f99.
  • Confirmed test-logic finding and fix: the two Spline extreme-value tests used a fixed 1e292 absolute tolerance, which allowed arbitrarily incorrect results for expected values near zero through four. The assertions now check output length and use a relative tolerance with a small absolute floor.
  • Rechecked Integral and IntegralAvg exact area accumulation, long timestamp spans, extreme finite values and unit normalization; nanosecond hour/day scales; LOF series window/k thresholds, cross-batch context and final partial batches; Resampler interpolation and timestamp boundaries; and the LOF, ZScore and Spline fixes. No additional actionable behavior or test-logic issue was confirmed.
  • Validation: local clean library-udf test run passed 161 tests with zero failures, errors or skips; clean with-zh-locale test-compile passed; Spotless and git diff --check passed. The TsFile clean install passed from source commit 8f665d113dbb5257b901c528c31c8bc24da2a018, and its output JAR hashes match the installed copies. No CI was queried or polled.
  • Final local commit, confirmed source branch SHA and confirmed PR head: d9c4c1a2fb5531e7ad539418f10cef82bc6c61e9. The PR remains OPEN Draft because this round found and fixed a test-logic issue; a fresh independent re-review is required before marking it ready. No update step remains incomplete.

@Caideyipi
Caideyipi marked this pull request as ready for review November 17, 2026 03:29
@shuwenwei

Copy link
Copy Markdown
Member

Static review at d9c4c1a2fb5531e7ad539418f10cef82bc6c61e9

I reviewed the effective diff against cca1dbbde6d0dffa38495c92c92a48b2626d2f99. The PR covers the intended edge cases broadly, but I do not think it is ready to merge yet because of the following correctness and performance risks.

Blocking concerns

  1. [P1] UDTFLOF still implements the wrong LOF formula and has cubic worst-case behavior.

    getLOF() loops over all length vectors but divides by multipleK, and getLocDens() also sums over all vectors while dividing by k. For a dataset where all local densities are equal, every ratio is 1, so the result should be approximately 1; the current code returns length / k.

    The implementation also recomputes getLocDens(knn, x, length) for every iteration and allocates a new Double[length][2] in every findKthPoint() call. With a batch of V vectors this is approximately O(V^3), which is not viable for the default access window of 10,000.

    Suggested direction: find the k nearest neighbors once per vector, compute each local reachability density once, iterate only over the k neighbors as defined by LOF, and use primitive/cached distance storage. Numeric assertions for a simple dataset and a performance smoke test for the typical series window would also help.

  2. [P1] UDAFDTWMatch introduces an unbounded per-query state.

    DTWState now retains every effective input point in a boxed TreeMap<Long, Double> and also retains every match result. Serialization includes both collections, so state memory and state transfer grow as O(N). Final output then rebuilds all windows in O(N * patternLength^2).

    This may be acceptable as an explicitly bounded trade-off, but the current implementation has no limit or failure policy. A long series, or a UDAFPatternMatch fallback that duplicates the input into DTW state, can consume excessive heap or fail during state serialization. Please consider primitive arrays/sorted chunks, retaining only the required boundary context, or enforcing a documented maximum with a clear error.

Other correctness issues

  1. [P2] Exact Median/MAD/Percentile still accept NaN and Infinity.

    The exact branches in UDAFMedian, UDAFMad, and UDAFPercentile only check row.isNull(0) before calling statistics.insert(row). The approximate branches correctly check Double.isFinite(...), but the exact path can insert non-finite float/double values and produce NaN or an incorrect ordered statistic. The current regression coverage checks null rows but does not exercise actual NaN/Inf values on these exact paths.

  2. [P2] UDAFSpread still overflows for integer extrema.

    intMax - intMin and longMax - longMin can overflow. For example, the full INT32 range reports -1, and the full INT64 range also reports -1. Since this PR explicitly targets extreme values, the output policy needs to be defined: widening, saturation, or an explicit error.

  3. [P2] Pearson/Covariance and K-Sigma retain unstable variance formulas.

    UDAFPearson and UDAFCov still use count * sumXX - sumX * sumX. With large common offsets and small variation, cancellation can produce zero or negative variance, causing the function to emit no result. UDTFKSigma has the same sumX2 / n - mean^2 pattern and can miss anomalies. Welford/co-moment or a stable two-pass window calculation would avoid this class of failure.

  4. [P2] BigDecimal is now on a per-row hot path without performance evidence.

    UDAFIntegral creates several BigDecimal objects for every finite input point. UDTFMvAvg permanently switches to BigDecimal after one compensation loss. This improves extreme-value handling, but the PR does not include a benchmark or allocation test. A fast compensated path with BigDecimal only as an overflow/underflow fallback, plus a large-series benchmark, would reduce the risk of a significant regression.

Minor input-handling issue

UDTFRegexMatch checks matcher.groupCount() >= group, but an optional group can exist while not participating in the match. In that case matcher.group(group) is null and the scalar/column paths can NPE. The returned group value should be checked before writing.

CI status

The current checks show 35 successful jobs and two failures:

Codecov and Sonar are skipped. The failures need to be investigated or rerun before merge.

Static checks only: I did not run compilation or tests. git diff --check passes, and the en/zh message files are in key and format-specifier parity.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

@shuwenwei Thanks for the detailed review. I addressed the actionable findings in fb0ea8444e842b7cc146e396aed97773f50c4471:

  • LOF: corrected the k-neighbor density and ratio calculations, cached primitive neighbor data, and added a numeric regression plus coverage at the 10,000-point default window.
  • DTW: bounded retained distinct timestamps at 100,000, including state merges, with a localized UDFException when exceeded. Serialized state now contains input points only; matches are rebuilt after merge or out-of-order input.
  • Exact Median/MAD/Percentile: the exact-order path already filters non-finite values; added NaN/Infinity regression cases for these exact paths.
  • Spread: integer range overflow now fails with a clear UDFException instead of wrapping.
  • Pearson/Covariance/K-Sigma: replaced cancellation-prone sum formulas with centered online statistics and added large-offset regressions.
  • Regex: a non-participating optional group now produces null/no output rather than throwing.
  • BigDecimal performance: left the exact arithmetic unchanged because the review identifies a potential allocation risk but no measured regression. I did not run a benchmark, so I am not claiming a performance result; a fast-path change should be guided by representative measurements.

Validation passed: Spotless apply; clean library-udf -am tests with 168 tests, 0 failures, 0 errors, and 0 skipped; full-reactor English and Chinese test-compile; and git diff --check.

I investigated the failures on the previous head. The AINode job ended during its IT step after runner loss without a test result. The dual-tree shard failed in IoTDBPipeLifeCycleIT.testReceiverRestartWhenTransferring, outside the changed UDF code. New checks for fb0ea8444e842b7cc146e396aed97773f50c4471 are pending; I have not waited for them.

The PR remains open, and I have left the discussion unresolved.

@shuwenwei

Copy link
Copy Markdown
Member

Re-review at fb0ea8444e842b7cc146e396aed97773f50c4471

I reviewed the incremental changes after d9c4c1a2fb5531e7ad539418f10cef82bc6c61e9 against the same base cca1dbbde6d0dffa38495c92c92a48b2626d2f99.

The substantive fixes look directionally correct:

  • LOF now computes k-neighbor local reachability density and the average neighbor density ratio instead of iterating over every point.
  • DTW now has a 100,000-distinct-timestamp limit and serializes only the effective input; matches are rebuilt after deserialization.
  • UDAFSpread now reports integer overflow instead of wrapping.
  • Pearson/Covariance use centered online statistics.
  • Optional unmatched regex groups no longer cause an NPE.
  • I withdraw the earlier exact-order-statistics finding: ExactOrderStatistics already filters non-finite FLOAT/DOUBLE values in its type-specific insert operations, and the added tests cover that path.

P1: integration tests still assert the old LOF behavior

The current implementation changes LOF results as intended, but integration-test/src/test/java/org/apache/iotdb/libudf/it/anomaly/AnomalyIT.java still contains the old expectations at lines 1121, 1157, 1193, and 1229.

Both Ubuntu and Windows fail identically:

AnomalyIT.testLOF1..4
expected: 3.8274824267668244
but was:  1.108194187554388

The first value returned by the current standard LOF calculation is consistent with an independent k=3 calculation. The remaining expected values for the data generated in AnomalyIT are approximately:

1.108194187554388
0.934912618041455
1.072129458369592
0.934912618041455
0.934912618041455
1.072129458369592
0.934912618041455
1.487500164460059

Please update all four LOF integration tests, not only the first assertion. A focused k=3 unit regression with a known reference value would also strengthen the current coverage, which only checks a k=1 uniform sequence.

Because this is a user-visible result change, the PR description should also include a before/after LOF example showing the old result and the corrected standard-LOF result.

Remaining non-blocking risks

  • UDAFPearson.java:71: centered online statistics still compute x - meanX directly. For finite endpoints such as -Double.MAX_VALUE and Double.MAX_VALUE, this becomes infinity and prevents a valid correlation from being emitted. A scaled fallback would make the fix complete for the full finite double range.
  • UDAFIntegral still performs multiple BigDecimal operations per row, and UDTFMvAvg permanently switches to BigDecimal after compensation loss. This is a performance risk rather than a proven defect; a representative throughput/allocation benchmark is still needed.
  • The new 10,000-point LOF test covers default mode with k=1 and one dimension. The heavier series mode (window=5, k=3, multi-dimensional input) still has O(V^2) distance work and should have a benchmark or measured elapsed-time record.

CI

At the time of this review:

  • 27 checks passed.
  • Ubuntu and Windows both failed the four LOF AnomalyIT tests above.
  • 7 checks were in progress, AINode was queued, and Sonar/Codecov were skipped.

Static review only; I did not run compilation or tests. git diff --check passes, and the en/zh message files have matching keys and format specifiers.

@Caideyipi
Caideyipi marked this pull request as draft November 18, 2026 04:23
@Caideyipi
Caideyipi marked this pull request as ready for review November 18, 2026 06:00
@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Additional local performance measurements for the remaining non-blocking risks (single run):

  • UDAFIntegral: 200,000 rows; 0.326 s; 612,840 rows/s; 3,788.1 B/row allocated.
  • UDTFMvAvg BigDecimal fallback: 200,000 rows; 0.457 s; 437,901 rows/s; 4,402.2 B/row allocated.
  • UDTFLOF series mode: 10,000 points; 5-dimensional embeddings; k=3; 1.403 s; 7,127 vectors/s; 466.3 B/vector allocated.

Environment: Windows 11 x64, Oracle JDK 17.0.15, Maven 3.8.8. Measurements came from a temporary local test fixture that has been removed and is not part of the PR diff. This was one local run, not a JMH benchmark; it has no warm-up/repeated statistical samples or comparison against the prior implementation. These figures provide elapsed-time and allocation data points only; they do not establish a regression or improvement, and the LOF measurement does not remove its O(V^2) distance-work risk.

@Caideyipi
Caideyipi marked this pull request as draft November 18, 2026 08:11
@Caideyipi
Caideyipi marked this pull request as ready for review November 18, 2026 08:16
@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Review round summary for commit bed525549fa4e05d1fbb6f67703c6dca63a42465:

  • Reviewed the full diff against base cca1dbbde6d0dffa38495c92c92a48b2626d2f99; no confirmed defects were found.
  • Added scale-aware Pearson accumulation and finite-double endpoint coverage. git diff --check passed; Maven tests were not run.
  • The endpoint test covers two-point perfect correlations; multi-row mixed-scale, cancellation, and non-finite-pair coverage remains limited.
  • No performance improvement is claimed from the prior single-run samples. LOF series mode still performs O(V^2) pairwise-distance work.
  • GitHub reports PR head bed525549fa4e05d1fbb6f67703c6dca63a42465. The PR remains Draft pending a fresh independent review of this update.

@shuwenwei

Copy link
Copy Markdown
Member

Independent review at bed525549fa4e05d1fbb6f67703c6dca63a42465

Reviewed the full effective diff against base cca1dbbde6d0dffa38495c92c92a48b2626d2f99, including the latest Pearson scaling and LOF IT expectation updates. The earlier LOF expected-value failure is resolved. I found the following remaining correctness/performance concerns.

Findings

  1. [P1] Series-mode LOF drops historical candidates by timestamp, not by distance.

    In UDTFLOF.transform() the previous candidate set is replaced with the final k entries in timestamp order (seriesNeighbors, around lines 313-317). At the next access-window batch, new vectors are compared only with those recent vectors plus the current batch. LOF's neighbors are selected in value/vector distance space, so an older vector can still be one of the true nearest neighbors even when many later vectors have arrived. The computed result therefore depends on access-window partition boundaries and can differ from LOF over the input series.

    Please either preserve/search the intended historical candidate population with a distance-based index, or explicitly define a bounded temporal neighborhood as the series method's contract and add a cross-batch regression where a new vector's nearest prior vectors are not the most recent k vectors. The existing tail test only asserts that outputs are finite/present, not that their LOF values use the correct neighbors.

  2. [P1] A legal k can allocate over 1 GiB for one LOF window.

    Validation only requires k > 0; the default access window is 10,000. With k=9999 and 10,000 valid rows, calculateLOFs() allocates int[10000][9999] and double[10000][9999], about 1.2 billion bytes of array payload (~1.12 GiB), before row/vector data and JVM overhead. This can OOM a DataNode for a valid query. The algorithm also performs pairwise distance work, with heap updates up to O(N^2 log k).

    Please bound k/window based on a defensible memory budget or use a representation whose memory does not grow as N*k; add a validation or allocation-boundary regression. The current 10,000-point test uses k=1, so it does not cover the high-k case.

  3. [P2] Covariance still overflows on finite inputs even when the true covariance is finite.

    UDAFCov.transform() computes deltaX = x - meanX without scaling. For two rows x=[-Double.MAX_VALUE, Double.MAX_VALUE], y=[-Double.MIN_VALUE, Double.MIN_VALUE], the second deltaX becomes infinity and coMoment becomes non-finite, so terminate() emits no result. The population covariance is finite, approximately 8.88e-16. Pearson received exponent scaling in the latest commit; Covariance needs equivalent scaled accumulation or a fallback. Please add this mixed-range regression.

  4. [P2] K-Sigma's centered update still overflows for finite extreme windows.

    With window=3, k=0.5, and values [Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE], value - mean overflows during the second insertion; the running mean/M2 become infinite/NaN and the function emits no outliers. A scaled window statistic can represent the comparisons: the sample deviation exceeds Double.MAX_VALUE, but k * deviation is finite and each sample's deviation from the mean exceeds that threshold. Please scale the window statistics or explicitly reject this range, and cover it in a regression.

PR description and validation

The PR changes user-visible LOF results, but its Examples section still has no LOF before/after example. Please add one concrete input/output example, as required for behavior changes.

Current CI: 36 checks pass; AINode fails in AINodeSharedClusterIT.concurrentForecastTest at AINodeTestUtils.concurrentInference (outside the changed files); Sonar/Codecov are skipped. That failure does not point to this UDF diff, but a clean CI result or confirmed infrastructure explanation is still needed before merge.

Static checks only: I did not run compilation or tests. git diff --check passes, and the EN/ZH message keys and format placeholders match. The author's single-run throughput/allocation figures are useful data points, but without a baseline they do not establish whether the BigDecimal paths regress performance.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

@shuwenwei Thanks for the detailed review. I addressed the findings in 37cb49358085d6e601eec98fdac55422aebadb2f:

  • method=series LOF now retains a bounded temporal neighborhood of up to the preceding 2k vectors plus the current vector. A cross-access-window regression with [0,0.1,100,100,0.2] verifies that the final score changes from 1.0 to 0.875; the PR description now includes this example. This is an explicit bounded temporal contract, not a full-history nearest-neighbor search.
  • The LOF neighbor graph uses flat arrays with a 64 MiB pre-allocation limit. The k=9999, 10,000-row case now fails with a localized UDFException instead of attempting the oversized graph.
  • Covariance switches to scaled accumulation when finite-input intermediate arithmetic overflows, including the mixed Double.MAX_VALUE/Double.MIN_VALUE regression.
  • K-Sigma uses normalized window statistics for extreme finite values; [Double.MAX_VALUE, -Double.MAX_VALUE, Double.MAX_VALUE] with window=3 and k=0.5 is covered.

Validation:

  • mvn -o clean test -pl library-udf -am -Dtest=UDFWindowAndQueueTest -Dsurefire.failIfNoSpecifiedTests=false: 127 tests passed.
  • Full-reactor mvn test-compile -DskipTests and mvn test-compile -P with-zh-locale -DskipTests: passed.
  • Spotless and git diff --check: passed.

The CI launched for this update is still pending. The previous completed run at bed525549fa4e05d1fbb6f67703c6dca63a42465 had the AINode job fail in AINodeSharedClusterIT.concurrentForecastTest at AINodeTestUtils.concurrentInference. I have not established that it was an infrastructure failure, so this remains a pre-merge check.

@shuwenwei

Copy link
Copy Markdown
Member

Independent re-review at 37cb49358085d6e601eec98fdac55422aebadb2f

Reviewed the new fixes against base cca1dbbde6d0dffa38495c92c92a48b2626d2f99, including LOF series history/memory, Covariance scaled fallback, and K-Sigma extreme-window handling. The previous high-k neighbor-graph allocation guard, mixed-range covariance fallback, and finite-extreme K-Sigma result now have direct changes/regressions. The bounded temporal LOF neighborhood is now documented in code and in the PR example; I treat that as the stated series-mode contract.

Findings

  1. [P1] LOF series mode can allocate hundreds of MiB and do billions of distance-coordinate operations for a valid embedding size.

    For method=series, window=10000, k=3, beforeStart() configures an access window of 10003 rows. The one-argument SlidingSizeWindowAccessStrategy uses a full-window step. On the second access batch, the retained 9999-row context plus 10003 new rows produces about 10003 new vectors. Lines 316-324 copy every vector into a separate double[10000] and retain all of them in pendingSeriesVectors before processing any of them: roughly 800,240,000 bytes (~763 MiB) for the raw doubles alone.

    The 64 MiB guard is inside calculateLOFs(), after this pending-vector allocation, and only accounts for the neighbor graph. It therefore does not protect this path. Processing those vectors also calls calculateLOFs() once per vector; with up to 7 candidates, each call evaluates 21 pairwise distances across 10000 coordinates, roughly 2.1 billion coordinate iterations per such batch.

    Please process newly generated vectors incrementally instead of materializing the whole batch, and enforce a working-memory/work limit that includes vector storage and distance computation. A regression or benchmark should cover a large embedding width across at least two access batches; the current LOF performance sample uses window=5, so it does not exercise this case.

  2. [P2] K-Sigma becomes O(window) per input row while scaled statistics are active.

    Once a value exceeds safeMomentMagnitude, usesScaledStatistics remains true while such values remain in the window. For every subsequent full-window row, removeValue() calls recomputeStatistics() after popping, and addValue() calls it again after pushing. Each recomputation scans the whole window to find its magnitude and then scans it again to rebuild moments. With the default window of 10000 and a sustained extreme-valued stream, this changes the steady-state path from O(1) updates to roughly four window passes per row.

    This is a plausible CPU regression in the exact extreme-value scenario the new branch handles. Please consider maintaining scaled add/remove moments incrementally (rescaling existing moments when the scale changes), or provide a representative sustained-extreme throughput comparison and a documented bound.

Review status

  • The prior LOF expected-value IT issue is resolved in the current tree.
  • Static git diff --check passes; EN/ZH message files have matching keys and format placeholders.
  • Current PR checks: 36 successful, AINode queued, Sonar/Codecov skipped.
  • I did not run local compilation or tests, per repository instructions. The author's single-run performance numbers are not a baseline and use a small LOF embedding width.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Addressed both findings in 8f7944e60f0179b6274a97ca200d7065b55472ad:

  • LOF series now preflights per-access memory and distance-coordinate budgets before allocating vectors or emitting results, then processes vectors incrementally. Added a two-batch large-embedding regression.
  • K-Sigma now maintains scaled moments incrementally and rescales them when the window magnitude changes. Added coverage for sustained extreme values and for those values leaving the window.

Validation: UDFWindowAndQueueTest (129 tests passed), full-reactor English and Chinese test-compile, and Spotless passed.

@shuwenwei

Copy link
Copy Markdown
Member

Independent re-review at 8f7944e60f0179b6274a97ca200d7065b55472ad

Reviewed the latest fixes against base cca1dbbde6d0dffa38495c92c92a48b2626d2f99, focusing on the LOF preflight/incremental path and K-Sigma scaled sliding updates. The previous series-batch vector accumulation and repeated full-window K-Sigma recomputation are addressed. I found these remaining issues/risks.

Findings

  1. [P1] Default-mode LOF bypasses the new distance-work limit, and the memory check runs after point vectors are allocated.

    MAX_LOF_DISTANCE_COORDINATE_OPERATIONS_PER_ACCESS is checked by validateSeriesBatchWork(), which is called only by the method=series branch. The default branch still builds all point vectors and calls calculateLOFs() directly. For the valid default configuration window=10000, k=3, and 700 input dimensions, the current memory estimate is about 57.6 MB including the neighbor graph, so the 64 MiB guard accepts it; however the pairwise distance loop executes about 10000*9999/2*700 ~= 35 billion coordinate operations. There is no corresponding work cap for this mode.

    Also, the default branch allocates double[dim] for every valid row before calculateLOFs() performs its 64 MiB check. For higher dimensions this can exceed the advertised working-memory limit before the query is rejected. Please preflight default-mode memory/work before constructing the vectors and apply an explicit distance-work budget (or a more scalable neighbor search).

  2. [P2] Scaled Covariance can lose a representable accumulated co-moment when one axis's scale later jumps.

    In UDAFCov.addScaledValue(), when scaleX grows, coMoment is multiplied by scaleX / absoluteX. That ratio can underflow to zero even though the prior covariance contribution is representable after rescaling back to the original units.

    Example finite inputs:

    x = [-Double.MIN_VALUE, Double.MIN_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE]
    y = [-Double.MAX_VALUE, Double.MAX_VALUE, 0, 0]
    

    The true population covariance is approximately 4.440892098500626e-16. The second row enters scaled mode with a non-zero co-moment; when x's scale then grows from Double.MIN_VALUE to Double.MAX_VALUE, the scale ratio underflows and clears that contribution. The current regression only checks a two-row mixed-range case, where no already-accumulated co-moment is rescaled. Please preserve the cross-moment with exponent-aware/extended scaling and add this sequence as an observable-output regression.

  3. [P2] Series-mode LOF's initialization emits scores using future vectors despite the documented past-only neighborhood.

    In processSeriesVector(), when the initial history first reaches k+1, the code calculates LOF for and emits every vector in that initial group. The earliest emitted vectors therefore use later timestamps as neighbors. This conflicts with the class contract that each new vector is evaluated using preceding vectors plus itself. Please either delay output until each point has the required prior context, or explicitly document the startup look-ahead exception and test it; the current cross-batch test asserts only the final vector's score.

Performance and test coverage

  • UDTFKSigma now updates a TreeMap<Double,Integer> on every accepted value and every eviction. This is O(log window) and can allocate/deallocate map nodes for high-cardinality values; it replaces the previous constant-time ordinary sliding update. No K-Sigma throughput/allocation comparison is reported. This is a performance risk to quantify, not a measured regression.
  • The new sustained-extreme K-Sigma test reflectively reads the private usesScaledStatistics field and only asserts that collected outputs are finite; that does not prove the expected user-visible output during rescaling or after extreme values leave the window. Please prefer assertions on output timestamps/values and avoid the reflective state assertion.

Static checks only: I did not compile or run tests. The latest git diff --check is clean, and the EN/ZH message files have matching keys and format placeholders. Current CI has 19 successful checks, 17 in progress, AINode queued, and Sonar/Codecov skipped; no current completed CI failure is reported.

@Caideyipi

Caideyipi commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

@shuwenwei Thanks for the detailed review. I implemented the findings in 04c7b15b38df6fd036bbbff44e86ba6c95ce00db:

  • Default-mode LOF now preflights working memory and distance-coordinate work before allocating point vectors.
  • Covariance preserves the accumulated cross-moment across scale changes; the reported four-row extreme-range case now has output coverage.
  • Series-mode LOF delays its first score until k prior vectors are available and scores only the current vector.
  • K-Sigma uses an amortized O(1) monotonic maximum deque instead of the TreeMap hot path; regression assertions check exact timestamps and values after extreme values leave the window.

Validation: Spotless, git diff --check, and full-reactor English and Chinese test-compile runs passed. UDFWindowAndQueueTest had 131 passing tests in the full-class run; the corrected remaining K-Sigma assertion passed in a focused rerun, so all 132 test methods were exercised successfully across these runs. No throughput/allocation benchmark was run, so I am not claiming a measured performance delta.

The commit has now been pushed to Caideyipi/iotdb:fix/library-udf-edge-cases. I verified that both the source branch and PR #17871 head match 04c7b15b38df6fd036bbbff44e86ba6c95ce00db. The PR remains open, and I left the discussion unresolved.

@shuwenwei

Copy link
Copy Markdown
Member

Re-review at 04c7b15b38df6fd036bbbff44e86ba6c95ce00db

I reviewed the latest fixes against base cca1dbbde6d0dffa38495c92c92a48b2626d2f99. The prior findings are largely addressed: LOF default and series work are now preflighted, series processing is incremental and only emits the current vector after k prior vectors exist, Covariance preserves cross-moments across scale changes, and K-Sigma uses an amortized O(1) monotonic maximum deque with observable-output assertions.

Remaining concern

[P1] Series-mode LOF still allocates large boxed input/context lists before its 64 MiB preflight.

In UDTFLOF.transform() around lines 382-395, the function copies the whole RowWindow into ArrayList<Long> timestamps and ArrayList<Double> values, and only then calls validateSeriesBatchWork(). The method later copies the last window - 1 entries into the retained context lists as well.

A legal example is method=series, window=2_000_000, k=3. The access window is window + k, producing four embedding vectors. ensureLOFWorkingMemory(4, 2_000_000) estimates about 64,000,512 bytes and therefore remains below the 64 MiB limit. But before that check the method has already boxed roughly two million timestamps and two million values into two lists; the references plus wrapper objects alone are well over 100 MiB. It then creates four 2-million-double vectors (about 64 MB) and retains context for almost two million rows. Thus the stated working-memory guard does not bound the actual per-invocation/retained UDF memory and a valid large-window query can still exhaust heap.

Please preflight from rowWindow.windowSize() / configured parameters before building those lists, or use bounded/primitive storage and include both transient lists and retained context in the budget. The existing two-batch test uses window=10000, so it does not exercise this large-window path.

Performance evidence

The remaining implementation is improved structurally, but the extreme Covariance path switches to precision-700 BigDecimal arithmetic for every subsequent point once a floating-point intermediate overflows. There is no representative benchmark for that sustained scaled path. This is not a measured regression, but a high-range throughput/allocation comparison would help quantify the cost.

Validation state

  • git diff --check passes; EN/ZH messages have matching keys and format placeholders.
  • Latest checks: 22 successful, 14 in progress, AINode queued, Sonar/Codecov skipped; no completed failure currently reported.
  • Static review only. I did not run compilation or tests.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

Comment-handling review at 04c7b15b38df6fd036bbbff44e86ba6c95ce00db

Addressed the confirmed series-mode LOF memory-preflight issue:

  • The batch now budgets input/context memory and the maximum LOF working set before allocating boxed lists.
  • Added a regression for window=2,000,000, k=3, asserting rejection before row access or output.

Validation: Spotless with with-integration-tests, git diff --check, and UDFWindowAndQueueTest passed (133 tests, 0 failures, 0 errors, 0 skipped). No covariance benchmark was run; the covariance path is unchanged and no performance claim is made.

Reviewed SHA: 04c7b15b38df6fd036bbbff44e86ba6c95ce00db.
Final local commit, confirmed source-branch head, and confirmed PR head: f1721da1fce393d60b47321936e45b0ccd5b6673.
The PR remains open and non-draft; the discussion remains unresolved.

@Caideyipi

Copy link
Copy Markdown
Collaborator Author

@shuwenwei Thanks for catching this. The series-mode preflight now runs before either boxed list is created and combines a conservative budget for the RowWindow upper bound and retained context with the largest LOF/history working set. The window=2,000,000, k=3 case is covered by a regression that verifies rejection before row access or output.

Spotless and UDFWindowAndQueueTest passed (133 tests, 0 failures, errors, or skips). I did not run the suggested covariance benchmark: this patch does not change the covariance path, and I am making no performance claim.

@shuwenwei

Copy link
Copy Markdown
Member

Re-review at f1721da1fce393d60b47321936e45b0ccd5b6673

I reviewed the current head against base cca1dbbde6d0dffa38495c92c92a48b2626d2f99, including the latest series-mode LOF preflight change.

Correctness

The latest fix now performs the conservative memory preflight before reading/boxing the incoming series rows. The new 2,000,000-row proxy regression checks rejection before row access, which covers the specific false-allocation path from my last review. The default LOF path also preflights before allocating per-row value vectors. I found no new confirmed correctness defect in these changes. The earlier startup scoring, covariance scale-transition, and K-Sigma sliding-window issues have corresponding fixes/tests in the reviewed tree.

Remaining performance risk

[P2] LOF's 64 Mi distance-coordinate budget does not bound heap maintenance cost.

The new budget counts N*(N-1)/2 * dimensions, while calculateLOFs() also performs two bounded-heap updates per pair, each potentially O(log k). A valid default-mode example window=10000, k=500, dimensions=1 passes both current guards:

  • estimated memory: about 61.36 MB, below 64 MiB;
  • distance-coordinate count: about 49,995,000, below 64 Mi.

Yet it executes about 50 million pair distances and up to about 100 million heap insert/update attempts, with each update able to sift through a heap of up to 500 entries. The limit therefore caps distance arithmetic, not total CPU work. This is not a demonstrated regression, but the current 10,000-point test uses k=1; please add a representative high-k timing/benchmark or account for heap-update work in the budget.

Validation status

  • Static git diff --check passes; EN/ZH message keys and format placeholders match.
  • Current checks: 34 successful, 3 queued, 2 skipped; no completed failure is currently reported.
  • No local compilation or tests were run, per repository instructions. Author-reported local tests are not independently verified here.

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.

2 participants