Skip to content

[#171] Skip CSV snapshot rows without a uid and delete the snapshots a failed sync copied - #183

Merged
maximthomas merged 5 commits into
OpenIdentityPlatform:masterfrom
maximthomas:issues/171-csv-uidless-snapshot
Oct 13, 2026
Merged

maximthomas merged 5 commits into
OpenIdentityPlatform:masterfrom
maximthomas:issues/171-csv-uidless-snapshot

Conversation

@maximthomas

@maximthomas maximthomas commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #171.

CSVFileConnector.sync() no longer fails on a snapshot row without a uid, and a failed sync no longer leaves behind the snapshots it copied.

  • The delete pass skips a snapshot row whose uid cell is empty or blank and logs a warning with the line and the file. Such a row was never reported: a live row without a uid fails the sync before any delta. A sync from a snapshot that has one now reaches handleResult. The token moves with the next change; until then every poll logs the warning again.
  • sync() copies the live file before the diff when the token is null or names a missing snapshot, and again after the diff when it reports changes. When the sync fails before the handler accepts the token, it now deletes the copies it made, under the write lock. A kept copy could be returned by getLatestSyncToken, and it stopped a retry on the unchanged live file: sync(null) failed with "Unable to copy CSV file for sync operation", and a sync from the old snapshot reported the same changes again without moving the token. A snapshot named by the caller's token is never deleted, and neither is the copy made before the diff once the handler has returned from a delta: every delta carries that copy's token, and a consumer that stores the token of each handled delta resumes from it.

getLatestSyncToken takes only the read lock, so a call that overlaps the failing sync can still return a copy's token before the copy is deleted. A sync from that token then starts over from the live file, as it does for any token without a snapshot, and never reports the changes made since that token. A sync from that token that takes the write lock before the copy is deleted runs from the copy, but if it reports no change it hands back the same token, and the sync after it starts over.

Test strength

arm case mutant killed red at
CSVFileConnector.java:577 delete pass, null uid → skip snapshotRowWithoutUidIsSkipped[",Jane,Doe,pw1"] no guard ccb33e9
same, blank uid snapshotRowWithoutUidIsSkipped["\" \",Jane,Doe,pw1"] uid == null instead of StringUtil.isBlank ccb33e9
same, warning skippedSnapshotRowIsLogged warning removed ccb33e9
CSVFileConnector.java:681 finally deletes the copy failedSyncDeletesTheSnapshotItCopied no cleanup ac832fe
CSVFileConnector.java:497 same when the sync fails before it holds the read lock syncThatCannotListItsSnapshotsDeletesTheSnapshotItCopied (POSIX, non-root) no cleanup in the write-locked block cb7965d
keep: token's snapshot failedSyncKeepsTheSnapshotOfItsToken deletes syncOrigin that mutant only (green at ac832fe)
keep: completed sync successfulSyncKeepsTheSnapshotItCopied no !completed that mutant only (green at ac832fe)
completed after handleResult syncWhoseTokenIsNotDeliveredDeletesTheSnapshotItCopied completed set before the token block ac832fe
CSVFileConnector.java:670 the copy made after the diff is tracked syncWhoseTokenIsNotDeliveredDeletesTheSnapshotItCopiedAfterTheDiff that copy not added to copies ac832fe
CSVFileConnector.java:638 a handled delta keeps the copy failedSyncKeepsTheSnapshotOfADeltaItHandled no copies.clear() 0390dc5
same, only after handle returns syncWhoseFirstDeltaFailsDeletesTheSnapshotItCopied copies.clear() before handle that mutant only (green at 0390dc5)
CSVFileConnector.java:588 same in the delete pass failedSyncKeepsTheSnapshotOfADeleteItHandled (relies on the header cached at init: the live columns are permuted after it) no copies.clear() 0390dc5
deleteSnapshot warning snapshotThatCannotBeDeletedIsLogged (POSIX, non-root) result of delete() ignored ac832fe
deleteSnapshot write lock — unpinnable by construction: another sync in this JVM can enter its read section only between readLock().unlock() and writeLock().lock(), a window a test cannot open or hold without the private static lock map. The lock keeps a copy from being deleted while another sync reads it; it does not stop getLatestSyncToken from returning the copy's token earlier —

…e sync delete pass

A snapshot row without a uid was never reported, because a live row without one fails the sync before any delta. The delete pass now skips it with a warning instead of failing after earlier DELETEs were sent, so a sync from such a snapshot reaches handleResult and the token moves.
sync() copies the live file before the diff when the token is null or names a missing snapshot, and again after the diff when it reports changes. When the sync fails before the handler accepts the token, it now deletes the copies it made, under the write lock. A kept copy could be returned by getLatestSyncToken, and it stopped a retry on the unchanged live file: sync(null) failed to copy over it, and a sync from the old snapshot reported the same changes again without moving the token. A snapshot named by the caller's token is never deleted.

getLatestSyncToken takes only the read lock, so a call that overlaps the failing sync can still return a copy's token before the copy is deleted. A sync from that token then starts over from the live file, as it does for any token without a snapshot.
…ng its token was handled

Every delta of a sync carries the token of the snapshot copied before the diff. A consumer that stores the token of each handled delta resumes from that snapshot after a failure, so deleting it made the next sync start over from the live file and silently skip the changes in between. The copy is now kept as soon as the handler returns from a delta; it is still deleted when the handler fails on the first one.
@maximthomas
maximthomas marked this pull request as draft October 12, 2026 10:43
@maximthomas maximthomas added bug Something isn't working connector:csvfile CSV file connector java Pull requests that update java code tests Test additions or fixes labels Oct 12, 2026
…efore its read section

scrubSyncFiles() runs after the pre-diff copy, still under the write lock,
while the cleanup that deletes a failed sync's copies belongs to the read
section after it. When it threw (File.list() returns null on an I/O error),
the copy stayed, and the next sync(null) on the unchanged file failed with
"Unable to copy CSV file for sync operation".

Also pin the delete-pass copies.clear(): a live file whose columns are
permuted after init yields DELETEs from a fresh copy, because the connector
reads the live file with the header cached at init.
@maximthomas
maximthomas marked this pull request as ready for review October 12, 2026 11:29
@maximthomas
maximthomas requested a review from vharseko October 12, 2026 11:30

@vharseko vharseko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit (non-blocking): SyncOpDiffTest.java:337 — syncThatCannotListItsSnapshotsDeletesTheSnapshotItCopied expects exactly NullPointerException, which is what the unchecked dataDir.list() in scrubSyncFiles happens to throw today. The test is about the cleanup, not the exception type: once #174 reworks scrubSyncFiles (e.g. a ConnectorIOException on an unlistable directory), this test goes red although the copy is still deleted. expectThrows(RuntimeException.class, ...) would keep it pinned to the cleanup only.

Not raised here, as they are already tracked: the start-copy collision and the token kept when <csv>.<mtime> exists (#174), snapshot retention (#174), the handler-stop semantics (#175), and the external-writer race (#172).

…le-directory sync test

syncThatCannotListItsSnapshotsDeletesTheSnapshotItCopied expected the
NullPointerException that scrubSyncFiles() happens to throw on an unlistable
directory, so a rework of that method (OpenIdentityPlatform#174) would turn it red although the
copy is still deleted. It now accepts any RuntimeException.

A RuntimeException alone also accepts a sync that fails before the copy is
made, where the empty directory proves nothing. The test sets the
directory's mtime to 0 before the sync and asserts that it moved, which only
creating or deleting an entry does.
@maximthomas

Copy link
Copy Markdown
Contributor Author

Re review 5493443471: agreed, the test is about the cleanup and the NPE is incidental. Changing only the expected type would open another gap, though: RuntimeException also matches the ConnectorException("Unable to copy CSV file for sync operation") that a sync throws before any copy exists, and the empty-directory assertion then holds with nothing to clean up.

535f9c4 widens the expectation to RuntimeException and adds a witness that the copy was made. Before the sync the test sets the directory's mtime to 0; afterwards it asserts that the mtime moved. Only creating or deleting an entry in the directory moves it.

syncThatCannotListItsSnapshotsDeletesTheSnapshotItCopied, run alone on macOS against four mutants of CSVFileConnector (green = the mutant survives):

expectation no cleanup in the write-locked block copy fails first directory listed before the copy ConnectorIOException on an unlistable directory (#174-like)
NullPointerException (8bbbe4c) red red green red
RuntimeException only red green green green
RuntimeException + mtime witness (535f9c4) red red red green

Without mutants the test is green, and so is the whole module (122 tests, 0 skipped). The "red at cb7965d" cell in the description still holds: at cb7965d the test fails on the leftover copy.

@vharseko vharseko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re 6140592007: thanks — the mtime witness closes the gap I missed in my own suggestion; RuntimeException alone would indeed have accepted the pre-copy ConnectorException with nothing to clean up.

Checked 535f9c4 locally (macOS, JDK 21):

  • SyncOpDiffTest: 34 tests, 0 failures, 0 skipped (the POSIX test ran).
  • ConnectorException thrown before Files.copy ("copy fails first"): red, on the new assertion The sync failed before it copied the CSV file.
  • ConnectorIOException on an unlistable directory in scrubSyncFiles (#174-like): green.

Both match your table. No further findings.

@maximthomas
maximthomas merged commit 659e8b0 into OpenIdentityPlatform:master Oct 13, 2026
15 of 26 checks passed
@maximthomas
maximthomas deleted the issues/171-csv-uidless-snapshot branch October 13, 2026 08:19
vharseko added a commit that referenced this pull request Oct 14, 2026
Fixes four open CodeQL alerts.

### `java/unreleased-lock` — `CSVFileConnector.java:494` (#1889, medium)

Raised on master by #183. `sync()` takes the write lock, copies the live
file when needed, and downgrades to the read lock. #183 added cleanup of
those copies to the `finally`, guarded by a `downgraded` flag:

```java
rwLock.readLock().lock();
downgraded = true;
} finally {
    if (!downgraded) { for (File copy : copies) deleteRewriteFile(copy); }
    rwLock.writeLock().unlock();
}
```

At runtime the read lock was never leaked: when `downgraded` is true the
loop does not run. But CodeQL does not tie the flag to the lock, so it
sees a path where the read lock is held and `deleteRewriteFile` throws
out of the method.

The copies are now deleted in a `catch (RuntimeException | Error e)`
that rethrows, and the flag is gone. `readLock().lock()` is the last
statement of the `try`, so once it returns nothing can reach the
`catch`. Behaviour is unchanged, with one improvement: if a deletion
throws, the `finally` still releases the write lock, which the old code
skipped.

The #183 tests for this path pass, among them
`syncThatCannotListItsSnapshotsDeletesTheSnapshotItCopied` (cleanup
inside the write-locked block), `failedSyncDeletesTheSnapshotItCopied`,
`failedSyncKeepsTheSnapshotOfItsToken` and
`successfulSyncKeepsTheSnapshotItCopied`. I have no CodeQL CLI locally,
so this PR's CodeQL check is what confirms the alert closes.

### `java/unused-parameter` — `CSVFileConnector.java:282`, `:1063`
(#1875, #1874)

`testCredentials` and `doCreate` are private and never read `options`;
the parameter is dropped and the four call sites are updated.

### `java/non-static-nested-class` — `TstConnector.java:443` (#1877)

`BatchUseCase3Processor` uses only its own fields and static helpers, so
it is now `static`, like `BatchUseCase2Processor` next to it.

### Not changed here

The other three open notes repeat alerts that were already dismissed;
only their line numbers moved by one:
- #1873 `java/deprecated-call` `MessagesUtil.java:650` — the same
`deserializeLegacy` wire-format calls as #143–#150 (won't fix)
- #1870 `AbstractRemoteOperationRequestFactory.java:110` — as #1590
(false positive: abstract method signature)
- #1869 `LocalOperationProcessor.java:51` — as #1588 (false positive:
abstract method signature)

They should be dismissed with the same reasons rather than fixed in
code.

### Tests

`csvfile-connector`: 122 tests, 0 failures.
`connector-framework-internal` (uses `TstConnector` batch use cases):
178 tests, 0 failures, 2 skipped.
maximthomas added a commit that referenced this pull request Oct 20, 2026
…as the next snapshot (#193)

Fixes #172.

`CSVFileConnector.sync()` now copies the CSV file under the read lock
before the diff, diffs the token's snapshot against that copy, and keeps
the copy as the next snapshot. A change that an external writer makes
while a sync is running is now reported by the next sync instead of
being lost.

Before this change, the index pass and the create/update pass read the
live file. After the diff, if a delta had been accepted, the live file
was copied to `<csv>.<lastModified>` as the next snapshot. External
writers take no lock. A row deleted after the index pass was therefore
in neither the diff nor the next snapshot, and no sync ever reported its
DELETE.

- The mtime is read before the copy is made, and it names the next
snapshot. If the copy were named after a later mtime, it could miss a
change, and it would then be kept instead of the fresh copy of that
mtime. Every sync would then report the change again.
- The copy is taken at the start of the read-locked section. The read
lock keeps every writer in this JVM out of the copy, as the write lock
would. Searches, gets and `getLatestSyncToken` keep running until a
writer in this JVM queues behind the sync: the lock is a non-fair
`ReentrantReadWriteLock`, which still makes a reader that starts after
that wait behind the writer, for the rest of the copy and for the diff.
Readers already wait this way during the diff.
- The new package-private `copyCsvFile()` writes the copy to a
`<csv>.<digits>.tmp` file from `createRewriteFile()`, and deletes that
file if the copy fails. The copy gets the mode of the CSV file, as
snapshots do. Exception messages still name the CSV file, and the error
log of a pass that reads the copy names the copy as well. A sync from a
token still fails with `ConnectorIOException` "File … does not exist"
when the CSV file is missing.
- If a delta was accepted, the copy is moved to `<csv>.<mtime>` with
`Files.move` without options. If that snapshot already exists, the
existing snapshot and the token stay, as before. In every other case the
copy is deleted when the sync ends, whether it succeeded or failed.
- Unchanged:
  - the write-locked section, and the read lock during the diff;
  - the origin's token on every delta;
  - the `copies.clear()` after a handled delta (#183);
  - the copy of the live file as the origin for a `null` token;
  - snapshot names;
  - exception texts, apart from an unreadable CSV file (see Trade-offs).

Trade-offs:
- Every sync copies the whole CSV file, even when nothing has changed,
and needs free disk space for the copy. A sync with a `null` or stale
token copies it twice: to its origin, as before, and for the diff.
Writers in this JVM wait for the copy, as they wait for the diff. A
search waits for the copy only if it starts after a writer has queued
behind the sync, as it then waits for the diff. A sync of an unchanged
file now fails with `ConnectorException` "Unable to copy CSV file for
sync operation" if the connector cannot write to the directory or the
disk is full. Before, such a sync returned no delta and failed only at
the first change.
- A sync from a token now reads the CSV file first when it copies it,
and only a missing file still fails with `ConnectorIOException` "File …
does not exist". A CSV file that exists but cannot be read, or an I/O
error while it is read, now fails with `ConnectorException` "Unable to
copy CSV file for sync operation", as a sync without a token already
did. Before, these were `ConnectorIOException` "File … does not exist"
and "Error reading from file …".
- A copy can still be taken in the middle of a write by an external
writer that does not write atomically.
- On POSIX, `Files.move` checks the target first and then renames, so it
does not arbitrate between two syncs that reach the move with the same
mtime: both can pass the check, and the second sync then replaces the
first one's snapshot. Both copies were taken from the file at that
mtime. If the second sync then fails in `handleResult`, it deletes the
snapshot that the first sync handed out. This takes two syncs of one CSV
file that do not share a lock: in two JVMs, or in one JVM through two
absolute paths of the file, such as a symlink. Two syncs of one path in
one JVM run one after another, because each starts with the write lock,
which waits for the read lock of the other.
- A copy left behind by a killed process is not removed automatically,
the same as for rewrites. Delete `<csv>.<digits>.tmp` files by hand
while no connector is running against the CSV file.
- Out of scope:
- an existing `<csv>.<mtime>` whose content differs from the live file
at that mtime (#174);
  - a handler that stops the sync by returning `false` (#175).

## Test strength

| arm | case | mutant killed | red at |
|---|---|---|---|
| `CSVFileConnector.java:635` the create/update pass reads the copy |
`rowCreatedDuringSyncIsReportedByTheNextSyncOnly` | pass reads the live
file | 78c1e16 |
| `CSVFileConnector.java:680` the copy becomes the next snapshot |
`rowDeletedDuringSyncIsReportedByTheNextSync` | live file copied after
the diff, as before | 78c1e16 |
| `CSVFileConnector.java:676` same, once a delta is accepted |
`rowDeletedDuringSyncIsReportedByTheNextSync`,
`rowCreatedDuringSyncIsReportedByTheNextSyncOnly`,
`acceptedDeltaAdvancesTheToken` | no move | 78c1e16 (the first two) |
| `CSVFileConnector.java:550` the index pass reads the copy |
`csvFileChangedAfterItsCopyIsReportedByTheNextSync` (overrides
`copyCsvFile()` to rewrite the live file once the copy is taken) | pass
reads the live file | that mutant only (the seam is new) |
| `CSVFileConnector.java:515` the mtime is read before the copy | same |
mtime read after `copyCsvFile()` | that mutant only (the seam is new) |
| `CSVFileConnector.java:517` the copy is taken under the read lock, so
writers in this JVM wait for it, and a reader that starts before any
writer queues does not | `copyOfTheCsvFileBlocksWritersButNotReaders`
(overrides `copyCsvFile()` to call `getLatestSyncToken`, then `delete`,
on another thread) | per mutant: the copy under the write lock, as at
4cffb1c (the reader times out after 10 s); the read lock released
around the copy (the writer does not wait) | 4cffb1c (the first mutant)
|
| `CSVFileConnector.java:680` an existing snapshot is not replaced |
`existingSnapshotOfTheCopiedMtimeKeepsTheToken` | `REPLACE_EXISTING` |
that mutant only (green at 78c1e16) |
| `CSVFileConnector.java:685` `FileAlreadyExistsException` keeps the
token | same | no catch | that mutant only (green at 78c1e16) |
| `CSVFileConnector.java:707` the copy is deleted when the sync ends |
`existingSnapshotOfTheCopiedMtimeKeepsTheToken`,
`successfulSyncKeepsTheSnapshotItCopied` and 6 more | no delete | that
mutant only |
| `CSVFileConnector.java:1313` `copyCsvFile()` deletes its file when the
copy fails | `missingCsvFileFailsSync`, `unreadableCsvFileFailsSync` |
no delete | that mutant only (green at 78c1e16) |
| `CSVFileConnector.java:688` a copy that cannot be moved to the next
snapshot fails the sync | `snapshotThatCannotBeMovedInFailsSync` (POSIX,
non-root) | no throw, so the old token is handed out | that mutant only
(green at 78c1e16) |
| `CSVFileConnector.java:1309` the copy, and so the next snapshot, takes
the mode of the CSV file | `snapshotTakesTheModeOfTheCsvFile` (POSIX,
skipped when the umask gives the CSV file rw-------) | copy into the
`createTempFile` file in place, which keeps rw------- | that mutant only
(green at 78c1e16) |
| `CSVFileConnector.java:521` an unreadable CSV file fails the copy with
"Unable to copy…" | `unreadableCsvFileFailsSync` (POSIX, non-root) |
`AccessDeniedException` sent to the `ConnectorIOException` arm |
78c1e16 (the old exception) |
| `CSVFileConnector.java:566`, `:661` a pass that cannot read the copy
names the CSV file in its exception and the copy in its log |
`copyDeletedBeforeTheIndexPassFailsSyncNamingTheCsvFile`,
`copyDeletedBeforeTheCreateUpdatePassFailsSyncNamingTheCsvFile` | per
pass: the exception names the copy; the log names only the CSV file |
that mutant only (the seam is new) |
| `CSVFileConnector.java:682` `next = null` after the move | — | not
pinned: without it, the delete after the read lock is released could
remove a writer's `.tmp` file that `createTempFile` gave the freed name;
a test cannot make it hand out that name | — |

`mvn -pl OpenICF-csvfile-connector test`: 132 run, 0 failures, 0 skipped
(122 at 78c1e16).
maximthomas added a commit that referenced this pull request Oct 27, 2026
… of the same mtime and fail sync() on a token without a snapshot (#200)

Fixes #174.

`CSVFileConnector.sync()` now deletes the snapshots beyond
`syncFileRetentionCount`, reuses an existing snapshot of the CSV file's
current mtime instead of failing, advances the token to such a snapshot
when it holds the bytes the sync read, matches snapshot names exactly,
and fails on a token whose snapshot is gone instead of silently taking a
new baseline. `getLatestSyncToken` takes a snapshot when none exists, so
the first sync from its token reports every change made after the call.

- Snapshots `<csv>.<13-digit mtime>` are listed by one helper,
`listSnapshots()`, with `Pattern.quote(name) + "\\.([0-9]{13})"` and
`Matcher.matches()`. The old pattern, `"(" + name + ")(\\.[0-9]{13})$"`
with `find()`, also matched the snapshots of `old_data.csv` and
`dataXcsv`, never matched those of `data(1).csv`, and threw
`PatternSyntaxException` for `data[1.csv`. A directory that cannot be
listed now fails with `ConnectorIOException` "Unable to list the files
of <dir>" instead of a `NullPointerException`. The listing uses the
directory of the absolute CSV file, and one helper, `snapshotFile()`,
names every snapshot from the absolute CSV file. So a CSV file named
without a directory (`csvFile=data.csv`) no longer fails every sync and
`getLatestSyncToken` with a `NullPointerException`, and the scrub still
recognises the snapshot the sync reads.
- `scrubSyncFiles` now deletes files. At the start of every sync, under
the write lock, it deletes the snapshots taken first until
`syncFileRetentionCount` remain, but never the snapshot the sync is
about to read. Snapshots are ordered by their own mtime, the time of
their copy: each copy is given that mtime before it is renamed into
place, because `Files.copy` gives it only on Linux and macOS, while on
Windows its `CopyFileEx` keeps the mtime of the CSV file. A copy whose
mtime cannot be set is logged as WARN "Could not set the mtime of copy
<copy> of <csv> to the time of the copy" and used as it is. Snapshots of
one own mtime keep the order of their names. The mtime in a name gives
that order only while the mtime of the CSV file never moves back: after
a restore from a backup, `cp -p` or `rsync -t`, the next scrub of
another consumer deleted the snapshot just handed out as a token. A
snapshot that cannot be deleted is logged as WARN "Could not delete
<file>" and kept. A count of 0 or below keeps only the snapshot the sync
reads; a negative count used to throw `ArrayIndexOutOfBoundsException`.
The `syncFileRetentionCount` help text now says what is kept.
- A snapshot is taken as a complete copy renamed into place
(`takeSnapshot`). If a snapshot of that mtime already exists, or another
process takes it during the copy, it is reused as the baseline of a sync
without a token. At the end of a sync, an existing snapshot of the
copied mtime becomes the new token only if it holds the same bytes as
the sync's copy. Every snapshot is named after the mtime read before its
copy, so one taken in another JVM may also hold a later write that this
sync has not reported. Then the token stays, and the next sync reports
these changes again instead of never reporting that write. A snapshot
that cannot be read, or that is gone by the time of the comparison, is
logged as WARN "Could not compare <snapshot> with <copy>" and is not
adopted. Before, the start copy failed with `ConnectorException` "Unable
to copy CSV file for sync operation", and the end always kept the old
token, so a second consumer of the same changes got them again on every
sync. A failed sync deletes only the snapshots it made, never one it
reused.
- A sync from a token whose snapshot does not exist now fails with
`ConnectorException` "Snapshot <file> of sync token <token> does not
exist, so the changes since that token cannot be reported; reset the
sync token". Before, it copied the live file as the baseline and so
silently skipped every delete since the token.
- `getLatestSyncToken` without any snapshot takes one of the CSV file
and returns its mtime. Before, it returned the current time without a
snapshot, so the first sync from that token copied the live file as its
baseline and lost every change made in between. With snapshots, it
returns the token of the one taken last, which the scrub keeps longest,
instead of the token of the newest name.
- A failed sync now deletes the snapshots it made before it releases the
read lock, not afterwards under the write lock. The read lock keeps
every other sync in this JVM out just as well, because each sync starts
with the write lock. Between the two locks, a sync queued on the write
lock could reuse such a snapshot and hand out its token; the delete then
left that token without a snapshot. The read lock is released in a
`finally` block of its own, so a delete that throws, such as with an
`Error`, does not leave it held.
- Unchanged:
  - snapshot names;
  - the write-locked start and the read-locked diff;
  - the origin's token on every delta;
  - the `copies.clear()` after a handled delta (#183);
  - the copy for the diff (#193);
  - `syncFileRetentionCount` is not validated.

Trade-offs:
- Upgrade: the first sync after the upgrade deletes every snapshot
accumulated beyond `syncFileRetentionCount`, under the write lock, so
searches and writes on that CSV file in this JVM wait for it.
- Upgrade: a stored token without a snapshot now fails once and needs a
reset. That covers tokens the old `getLatestSyncToken` returned when no
snapshot existed (the current time) that were never synced, and tokens
whose snapshot a cleanup job deleted. Such cleanup jobs should be
dropped: retention now does their work.
- A consumer's stored token also loses its snapshot when other consumers
of the same CSV file take more than `syncFileRetentionCount` snapshots
after it, or when the count is 0 or below and the file has several
consumers. Its next sync then fails instead of silently skipping
deletes.
- Up to `syncFileRetentionCount + 1` snapshots stay on disk between
syncs, or `+ 2` when the snapshot a sync read was taken before the kept
ones.
- Other JVMs are not excluded. A scrub can delete a snapshot that a sync
in another JVM is reading. On POSIX, `Files.move` without options checks
the target and then renames, so two JVMs can replace each other's
snapshot of the same mtime. An existing snapshot of the copied mtime
becomes the token only if its bytes match, so a later write in it is
reported by the next sync instead of lost. In one JVM the bytes differ
only when the file changed without its mtime changing, such as a write
within the same mtime tick as an earlier sync's copy; that consumer then
gets these changes again until the mtime moves.
- `getLatestSyncToken` takes only the read lock, so it can return the
snapshot of a sync that is failing at the same moment, which that sync
then deletes. That needs a second consumer of the CSV file in this JVM;
its next sync then fails and its token has to be reset.
- A sync that finds the snapshot name of its copy taken reads that
snapshot and its copy once more to compare them.
- A snapshot reused by its name, as the baseline of a sync without a
token or as the new token at the end of a sync, keeps the time of its
first copy. Only when the mtime of the CSV file moves back to that of an
existing snapshot does that time differ from when its token is handed
out; the scrub can then delete that snapshot before the ones taken after
its first copy.
- On Windows, snapshots taken before this change carry the mtime the CSV
file had when they were copied, so among themselves they keep the order
of their names. That differs from the order they were taken only if the
CSV file's mtime moved back before the upgrade.
- The scrub and `getLatestSyncToken` take the order of the snapshots
from their own mtimes, so anything that rewrites those mtimes reorders
them: a copy of the data directory without its file times (`cp -r`, `scp
-r` without `-p`, `rsync` without `-t`), a `touch`, or a restore that
does not keep times. With several consumers of the CSV file, the scrub
can then delete another consumer's token although fewer than
`syncFileRetentionCount` snapshots were taken after it; that consumer's
next sync fails and its token has to be reset. `getLatestSyncToken` can
then return an older snapshot, so a new consumer gets some changes
twice, but none are lost. A single consumer is not affected. Copying the
directory with its times (`cp -p`, `rsync -t`) avoids this.
- The scrub and `getLatestSyncToken` read the mtime of every snapshot of
the CSV file to order them, and every snapshot copy sets its own.
- Snapshot names keep the unpadded mtime, while the listing matches
exactly 13 digits, as before. A CSV file with an mtime before
2001-09-09, such as an epoch-dated file from a reproducible-build image,
gets snapshots that retention never lists or deletes, one per such
mtime. Sync stays correct, because a token's snapshot is looked up by
name. Matching any number of digits would let the scrub delete unrelated
files such as a `data.csv.1` backup, and zero-padded names would break
the stored tokens of such mtimes.
- `<csv>.<digits>.tmp` files left by a killed process are still not
removed automatically.
- `SyncOpTest#syncTestSuccessive` now syncs from the snapshot that
`getLatestSyncToken` takes, no longer through the re-copy for a missing
snapshot.
-
`SyncOpDiffTest#syncOfAFileNamedWithoutADirectoryKeepsTheSnapshotItReads`
creates a temporary CSV file in the surefire working directory, the
module directory, and deletes it and its snapshots in a `finally` block.
A killed test run leaves `csv-sync-*.csv*` files there.

## Test strength

All cases are in `SyncOpDiffTest` unless named. "Red at <commit>" means
that the case fails when this PR's tests run against the
`CSVFileConnector` of that commit: 95c8375 is master, and 2c0760a,
b542f0d, a2acb12 and 2ada596 are earlier commits of this PR.

| arm | case | mutant killed | red at |
|---|---|---|---|
| `CSVFileConnector.java:1073`, `:1077` snapshot names are quoted and
matched whole | `latestSyncTokenIgnoresSnapshotsOfOtherFiles`
(`old_data.csv`, `dataXcsv`),
`latestSyncTokenFindsTheSnapshotsOfAFileWithRegexMetacharactersInItsName`
(`data(1).csv`, `data[1.csv`),
`syncOfAFileWhoseNameIsAnInvalidRegexReportsItsChanges` | the old
pattern with `find()` | 95c8375 |
| `:1071` an unlistable directory fails with `ConnectorIOException` |
`latestSyncTokenOfAnUnlistableDirectoryFails` (POSIX, non-root) | no
null check | 95c8375 (`NullPointerException`) |
| `:1054`-`:1055`, `:1068` snapshot paths and the listing use the
absolute CSV file |
`syncOfAFileNamedWithoutADirectoryKeepsTheSnapshotItReads` (a temporary
CSV file in the working directory, count 1) | the relative parent; an
absolute listing with relative snapshot paths, whose scrub deletes the
snapshot the sync reads (the sync then fails with "File … does not
exist") | 95c8375, b542f0d (`NullPointerException`) |
| `:739` the snapshot taken last is the latest token |
`SyncOpTest#syncTestSuccessive`;
`latestSyncTokenIsThatOfTheSnapshotTakenLast` (a snapshot of an older
mtime taken after one of a newer mtime) | the first listed snapshot; the
newest name, as at a2acb12, also with the scrub in the order taken |
95c8375, a2acb12 (the newest name) |
| `:1384` an existing snapshot is reused, not copied again |
`secondSyncWithoutATokenOfAnUnchangedFileReusesItsSnapshot` | no
`exists()` check (4 copies instead of 3) | 95c8375 |
| `:493` only a snapshot this call made goes into `copies` |
`failedSyncKeepsTheSnapshotItReused` | always added | 95c8375 |
| `:1392`, `:1395` a snapshot taken meanwhile by another process is
kept, and the losing copy is deleted |
`snapshotTakenMeanwhileByAnotherProcessIsKept` (overrides
`copyCsvFile()` to write the snapshot) | the losing copy kept | 95c8375
(the other process's snapshot is deleted) |
| `:694`-`:695` an existing snapshot at the end with the same bytes
advances the token | `existingSnapshotOfTheCopiedMtimeAdvancesTheToken`,
`secondConsumerOfTheSameChangesGetsTheNewTokenToo` | the token kept, as
before | 95c8375 |
| `:694`, `:1407`-`:1422` an existing snapshot at the end with other
bytes keeps the token and is not replaced |
`existingSnapshotOfTheCopiedMtimeWithOtherBytesKeepsTheToken` (a row
added; a change of the same length past the first 8 KiB) | always
adopted, as at b542f0d; only the lengths compared; only the first 8 KiB
compared | b542f0d only (green at 95c8375) |
| `:1425` an existing snapshot that cannot be read is logged and keeps
the token |
`existingSnapshotOfTheCopiedMtimeThatCannotBeReadKeepsTheToken` (POSIX,
non-root) | adopted on a failed read | b542f0d; 95c8375 (no WARN) |
| `:689` an existing snapshot at the end is not added to `copies` |
`failedSyncKeepsTheExistingSnapshotOfTheCopiedMtime` |
`copies.add(syncOrigin)` in the arm | that mutant only (green at
95c8375) |
| `:1081`-`:1087` the scrub deletes snapshots in the order they were
taken, by their own mtime |
`syncKeepsTheTokenOfAnotherConsumerWhenTheCsvFileMtimeMovesBack` (count
2, the CSV file's mtime set back below both tokens) | the name order, as
at a2acb12; the order reversed | a2acb12 only (green at 95c8375,
whose scrub deletes nothing) |
| `:522`, `:1387`, `:1369` a snapshot copy gets the time of its copy as
its mtime, also where `Files.copy` keeps the CSV file's mtime, as
`CopyFileEx` does on Windows | `[true]` of
`syncKeepsTheTokenOfAnotherConsumerWhenTheCsvFileMtimeMovesBack` (the
copy for the next token) and of
`latestSyncTokenIsThatOfABaselineTakenAfterTheCsvFileMtimeMovesBack`
(the baseline of a sync without a token, then the latest token);
`[true]` overrides `copyCsvFile()` to keep the CSV file's mtime |
`copyCsvFile()` instead at `:522`, and at `:1387`, each killed by its
own case | 2ada596 (`[true]` of both); 95c8375 (both variants of the
second case) |
| `:1370`-`:1372` a copy whose mtime cannot be set is logged and used as
it is | `copyDeletedBeforeItsMtimeIsSetLogsAWarning`,
`copyDeletedBeforeTheIndexPassFailsSyncNamingTheCsvFile` (the copy
deleted at once) | rethrown, which fails the sync as if the CSV file
were gone; no WARN | 2ada596, 95c8375 (the first case: no WARN) |
| `:1087` snapshots of one own mtime keep the order of their names |
`snapshotsTakenInOneTickAreScrubbedInTheOrderOfTheirNames` (three
snapshots of one own mtime, count 2) | ties broken by descending name |
95c8375 (nothing deleted) |
| `:1098` the configured count is used |
`syncDeletesTheSnapshotsBeyondTheRetentionCount` (count 2) | constant 3
| 95c8375 |
| `:1098`, `:1103` a count of 0 or below keeps only the snapshot the
sync reads | `syncFromATokenKeepsOnlyTheSnapshotItReads`,
`syncWithoutATokenKeepsOnlyItsBaseline` (counts 0 and -1) | an early
return for a count below 1; `scrubSyncFiles(copies.isEmpty() ?
syncOrigin : null)`, which spares only a reused origin | 95c8375
(nothing deleted at 0, `ArrayIndexOutOfBoundsException` at -1) |
| `:1103` the snapshot the sync reads is spared |
`syncKeepsTheSnapshotItReadsWhenItIsTheOldest` (count 1) | no check |
95c8375 |
| `:1097` the scrub lists only this file's snapshots |
`syncKeepsTheSnapshotsOfOtherFiles` (count 1) | the old pattern with
`find()` | that mutant only (green at 95c8375) |
| `:1104` a snapshot that cannot be deleted is logged and kept |
`snapshotThatCannotBeScrubbedIsLogged` (POSIX, non-root) | nothing
deleted, as before | 95c8375 |
| `:481` a token without a snapshot fails |
`syncFromATokenWhoseSnapshotIsGoneFails` | the old re-copy | 95c8375 |
| `:744` `getLatestSyncToken` takes a snapshot when there is none |
`latestSyncTokenWithoutASnapshotTakesOne` | no snapshot taken | 95c8375
|
| `:713`, `:717` a failed sync deletes its snapshots before it releases
the read lock | `syncQueuedBehindAFailingSyncGetsATokenWithASnapshot`
(swaps a lock into `fileNameToLockMap` by reflection whose read-lock
release waits until the queued sync has taken its baseline) | the delete
after the release with no lock held; the delete after the release under
the write lock, as at 2c0760a; with the case repeated 20 times, each
failed all 20 invocations (the first in 3 such runs), and a2acb12
passed all 20 (2 runs); with the release in its own `finally` block, the
delete with no lock held still fails it | 2c0760a (the token's snapshot
is gone); 95c8375 (the queued sync fails with "Unable to copy…") |
| `:717` the read lock is released even if a delete of a failed sync
throws | `failedSyncReleasesTheReadLockWhenItsCleanupFails` (POSIX,
non-root: a read-only directory, and `System.out` swapped for a stream
that throws, so the WARN "Could not delete" throws) | the release after
the delete loop outside a `finally` block, as at a2acb12 | a2acb12
only (green at 95c8375, which released the lock first) |
| `:745`-`:746` a failed copy in `getLatestSyncToken` fails the call | —
| not pinned: `catch (IOException e) { }` survives, and the next sync
would then fail with "Snapshot … does not exist" | — |
| `:1408`-`:1410` a snapshot gone by the time of the comparison is
logged | `existingSnapshotOfTheCopiedMtimeDeletedMeanwhileIsLogged` (a
symbolic link to no file holds the snapshot name; skipped where links
cannot be created) | the `File.length()` check before the `try`, as at
a2acb12, which returns 0 for a missing file | 95c8375, a2acb12 (no
WARN) |
| `:1410` the size check before the byte comparison | — | not pinned:
without it the comparison gives the same result, so it is only a
shortcut | — |
| `:1077` the name must end after the 13 digits | — | not pinned:
`matches()` → `lookingAt()` survives, and would list
`<csv>.<digits>.tmp` files whose random part has 13 or more digits | — |

`mvn -pl OpenICF-csvfile-connector test`: 167 run, 0 failures, 0 skipped
(132 at 95c8375). Of the 79 `SyncOpDiffTest` cases, 29 are red at
95c8375.
maximthomas added a commit that referenced this pull request Oct 29, 2026
…en of the offered deltas (#206)

Fixes #175.

`CSVFileConnector.sync()` now ends at the first `false` from the
handler. It offers no further delta in any pass, takes no snapshot, and
passes to `handleResult` the token that the offered deltas carry: the
caller's token, or for a sync without a token the token of its start
copy. The next sync from that token offers every delta of the stopped
sync again, the ones the handler accepted too.

- Delete pass: a `false` ends the pass at once. Before, the pass stopped
offering DELETEs but kept reading the snapshot for the fingerprints of
the next pass, and that pass still offered CREATEs and UPDATEs to a
handler that had asked to stop. In the sequence of the issue, the first
sync now offers `DELETE d1` and `DELETE d2` and returns the starting
token, and the next one offers `DELETE d1`, `DELETE d2`, `DELETE d3` and
`CREATE c1`.
- Create/update pass: skipped after a stop in the delete pass. The
snapshot rows that the delete pass did not read have no fingerprint, so
this pass would report them as CREATEs. Because nothing is read after
the stop, a malformed snapshot row past the stop point no longer fails
the stopped sync.
- End of the sync: the copy of the live file taken before the diff
becomes the next snapshot, and its mtime the token, only when the
handler accepted a delta and never returned `false`. Before, one
accepted delta was enough, so a `false` in either pass moved the token
past the deltas the handler had not accepted, and no later sync offered
them. This also covers a sync without a token whose live file changed
between its start copy and the copy for the diff: the token now stays at
the start copy, whose snapshot exists, instead of moving to the later
mtime.
- `SyncOpTest.syncTestHandlerStopped` expected the extra offer in the
second pass. It now expects exactly `DELETE vilo` and an unchanged
token, both from `handleResult` and from `getLatestSyncToken`.
- The create/update pass moved into `if (!stopped) { ... }`, so most of
its diff is indentation; `git diff -w` shows the rest. Besides the
guard, that is `stopped = true` before its `break` and one `log.error`
call wrapped to stay within 120 columns.
- Unchanged:
  - a sync whose handler accepts every delta;
- `copies.clear()` right after every `handle()` (#183), so a
`handleResult` that throws after a stop still leaves the snapshot that
the offered tokens name;
  - every delta carries the sync's starting token;
- the copy for the diff (#193), and the snapshot reuse and retention
(#200).

Trade-offs:
- A sync with a `false` makes no progress, even when the `false` comes
on its last delta. The connector has no resume point inside a snapshot:
every delta carries the starting token. A consumer that uses `false` as
a page limit ("stop after N deltas") gets the same first N deltas from
every sync of N or more changes and never gets past them. Before, it
moved on but lost the deltas after its limit. Such a consumer has to
accept every delta of a sync.
- After a `false`, the next sync offers again the deltas the handler
accepted before it. It offers an accepted delta again only if its change
is still in the file: an accepted delta that the source reverts before
that sync, such as a DELETE whose row is put back, is never undone.
OpenIDM already got the accepted deltas again, and had the same gap: on
a retry it keeps the token of its last accepted delta, which here is the
starting token. What changes for OpenIDM is that it is no longer
offered, and so no longer applies, the deltas after its `false`.

All cases are in `SyncOpDiffTest` unless named. "Red at <commit>" means
that the case fails when this PR's tests run against the
`CSVFileConnector` of that commit: 1cf81d2 is master, and 65e85b7 is
the first commit of this PR.

| arm | case | mutant killed | red at |
|---|---|---|---|
| `CSVFileConnector.java:613`-`:614` a `false` in the delete pass ends
the sync | `handlerStopInTheDeletePassEndsTheSync` (the sequence of the
issue: the handler accepts `DELETE d1` only),
`handlerStopEndsTheDeletePass`, `SyncOpTest#syncTestHandlerStopped` |
`stopped = true; break;` removed, so the `false` is ignored | 1cf81d2,
65e85b7 (`handlerStopEndsTheDeletePass`: that mutant only) |
| `:614` nothing more is read after the stop |
`handlerStopInTheDeletePassLeavesTheRestOfTheSnapshotUnread` (a
two-column row after the stop point) | `continue` instead of `break`,
with no delta offered after the stop: the pass reads on as on master |
1cf81d2, 65e85b7 (both `SuperCsvException` from that row) |
| `:640` the create/update pass is skipped after a stop |
`handlerStopInTheDeletePassEndsTheSync`, `handlerStopEndsTheDeletePass`,
`SyncOpTest#syncTestHandlerStopped` | `if (true)` | 1cf81d2, 65e85b7
(`handlerStopEndsTheDeletePass`: that mutant only) |
| `:664` a `false` in the create/update pass stops the sync |
`handlerStopInTheCreateUpdatePassKeepsTheToken` (the handler accepts
`CREATE c1` only, of three) | `stopped = true` removed | 1cf81d2 (the
token is the CSV file's mtime) |
| `:689` a stopped sync takes no snapshot and keeps the token |
`handlerStopInTheCreateUpdatePassKeepsTheToken`,
`handlerStopInTheDeletePassEndsTheSync` | `if (changesProcessed)` |
1cf81d2 |
| `:610` the start copy stays when a DELETE is rejected and
`handleResult` throws | `rejectedDeleteKeepsTheSnapshotItsTokenNames`
(sync without a token; the header cached at init makes the fresh copy
report DELETEs) | `copies.clear()` after the `false` check | that mutant
only (green at 1cf81d2) |
| `:662` the same for a rejected UPDATE |
`rejectedUpdateKeepsTheSnapshotItsTokenNames` (duplicate uids make the
fresh copy report UPDATEs) | the same | that mutant only (green at
1cf81d2) |

`mvn -pl OpenICF-csvfile-connector test`: 172 run, 0 failures, 0 skipped
(167 at 1cf81d2). Of the 84 `SyncOpDiffTest` cases, 3 are red at
1cf81d2, and `SyncOpTest#syncTestHandlerStopped` is red there too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working connector:csvfile CSV file connector java Pull requests that update java code tests Test additions or fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CSVFile connector: a snapshot row without a uid fails sync() after DELETEs were sent, and a leftover snapshot can leave the sync token stuck

2 participants