Skip to content

[#172] Diff sync() against a copy of the CSV file and keep that copy as the next snapshot - #193

Merged
maximthomas merged 5 commits into
OpenIdentityPlatform:masterfrom
maximthomas:issues/172-csv-sync-copy-before-diff
Oct 20, 2026
Merged

maximthomas merged 5 commits into
OpenIdentityPlatform:masterfrom
maximthomas:issues/172-csv-sync-copy-before-diff

Conversation

@maximthomas

@maximthomas maximthomas commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

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:

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:

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).

… and keep that copy as the next snapshot

sync() copied the live file after the diff, so a row an external writer
deleted during the sync was in neither the diff nor the next snapshot and
was never reported. The copy is now taken under the write lock before the
diff, the index and create/update passes read it, and once a delta is
accepted it is moved to <csv>.<mtime read before the copy>.
@maximthomas maximthomas added bug Something isn't working java Pull requests that update java code tests Test additions or fixes connector:csvfile CSV file connector concurrency Races, locking and thread-safety fixes labels Oct 14, 2026
…t mode and the unreadable CSV file of sync(), and log the copy a pass fails to read
@maximthomas
maximthomas marked this pull request as ready for review October 14, 2026 08:47
@maximthomas
maximthomas requested a review from vharseko October 14, 2026 08:47

@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.

CSVFileConnector.java:500: the copy of the CSV file does not need the write lock

next is a private .tmp file. Every writer in this JVM takes the write lock, so the read lock already keeps them out while the copy is taken. Holding the write lock for the copy instead blocks every search, get, getLatestSyncToken and the start of other syncs for the whole copy. Before this PR, that happened only on a sync with a null or stale token. Now it happens on every sync, including one from a valid token on an unchanged file. That path used to hold the write lock only for an exists() check.

Taking nextTimestamp and copyCsvFile() at the start of the read-locked section would avoid this, and needs no new error path: the finally at :698-710 already deletes copies and next when the sync fails. It would also take the second full copy that a sync with a null or stale token now makes (:489, then :500) out of the write-locked section.

@vharseko vharseko added the data-loss Fixes or risks loss or corruption of stored data label Oct 14, 2026
…d lock instead of the write lock

The read lock keeps every writer in this JVM out of the copy, as the write
lock did, while searches, gets and getLatestSyncToken keep running. The
write-locked section is back to what it was before the copy was added.
copyOfTheCsvFileBlocksWritersButNotReaders pins both sides.
@maximthomas

Copy link
Copy Markdown
Contributor Author

Re review 5515753375: fixed in 2aa8447.

nextTimestamp and copyCsvFile() now run at the start of the read-locked section (CSVFileConnector.java:515-523). The write-locked section is the same as on master again: it picks the origin, copies the live file to it for a null or stale token, and calls scrubSyncFiles(). A failed copy needs no new cleanup: copyCsvFile() deletes its own file, and the finally of the read section deletes copies and next.

copyOfTheCsvFileBlocksWritersButNotReaders pins both sides of the lock. Its copyCsvFile() override calls getLatestSyncToken on another thread, which must return within 10 s. It then starts a delete there, which must still be waiting after 500 ms, and the next sync reports that delete. With the copy back under the write lock (the 4cffb1c code), the reader times out. With the read lock released around the copy, the delete does not wait. I re-ran the mutants of the rows the move touched: mtime read after the copy, no delete of next at the end, copyCsvFile() keeping its file, AccessDeniedException sent to the ConnectorIOException arm. The same tests still kill each of them. The module runs 132 tests, 0 failures, 0 skipped.

The move does not let another sync start earlier: it starts with the write lock, which waits for the read lock of the first sync until that sync ends. Following that through, the POSIX Files.move trade-off in the PR body over-claimed: two syncs of one path in one JVM never reach the move together. The body now says the race takes two syncs that do not share a lock, in two JVMs or through two absolute paths of the file in one JVM. Trade-offs now also list the second copy that a sync with a null or stale token makes, and the test-strength table has the new row and the line numbers at 2aa8447.

@maximthomas
maximthomas requested a review from vharseko October 15, 2026 07:50

@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 2aa8447: the copy now runs at the start of the read-locked section, and the write-locked section is back to what it is on master. A failed copy is cleaned up by copyCsvFile() itself, and the origin copy of a null or stale token by the finally of the read section. getLatestSyncToken, which can now run during the copy, does not pick up the .tmp file, because its pattern requires the name to end in 13 digits. copyOfTheCsvFileBlocksWritersButNotReaders kills both lock mutants. The corrected Files.move trade-off and the new table row match the code. The module passes locally: 132 tests, 0 failures, 0 skipped.

Non-blocking, wording only: the lock from fileNameToLockMap is a non-fair ReentrantReadWriteLock. Once a writer in this JVM queues behind the sync, a search that starts after it waits behind that writer: for the rest of the copy and for the diff. "Searches do not wait for the copy" therefore holds until a writer queues. The diff on master already behaves this way, so this is not a regression and needs no code change. The comment at :512 and the Trade-offs line could say so, if you want them exact.

…writer waits for the sync copy

The lock from fileNameToLockMap is a non-fair ReentrantReadWriteLock, which
still makes a new reader wait behind a queued writer. Once a writer in this
JVM queues behind the sync, a search that starts after it waits for the rest
of the copy and for the diff. Comment only; the line count is unchanged.
@maximthomas

Copy link
Copy Markdown
Contributor Author

Re review 5535943732: the wording is fixed in f1f2df9.

The comment at CSVFileConnector.java:512 now says that a reader which starts after a writer has queued also waits for the copy. The body says the same in three places: the bullet on the read-locked copy, the first Trade-offs line, and the :517 row of the table. I checked the lock behaviour on JDK 8, 11 and 26. While a read lock is held and a writer is queued, a new readLock().lock() blocks until both have released the lock.

copyOfTheCsvFileBlocksWritersButNotReaders is not affected: its reader finishes before the delete is submitted. The comment is still three lines long, so the line numbers in the body are unchanged. Only the comment changed, no code. The module passes locally: 132 tests, 0 failures, 0 skipped.

@maximthomas
maximthomas requested a review from vharseko October 20, 2026 11:00

@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 f1f2df9: the comment at CSVFileConnector.java:512-514 now says that a reader which starts after a writer has queued also waits for the copy. The body says the same in the read-lock bullet, in the first Trade-offs line and in the :517 row of the table. All three match the code. Every reader in the connector takes the lock with lock() (:367, :723, :869), not with the barging tryLock(), so the non-fair queue check applies to it. On JDK 21 I see the same behaviour as the reply describes: while a read lock is held and a writer is queued, a new readLock().lock() waits until both have released the lock, and a reader that arrives before the writer gets in at once.

The commit changes only the comment. Its three lines stay within 120 columns, and the line numbers in the body still point at the statements they name. copyOfTheCsvFileBlocksWritersButNotReaders still tests the case it names: it awaits its getLatestSyncToken before it submits the delete. The module passes locally at f1f2df9: 132 tests, 0 failures, 0 skipped. CI is green.

@maximthomas
maximthomas merged commit 6f54d68 into OpenIdentityPlatform:master Oct 20, 2026
15 checks passed
@maximthomas
maximthomas deleted the issues/172-csv-sync-copy-before-diff branch October 20, 2026 12:28
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 concurrency Races, locking and thread-safety fixes connector:csvfile CSV file connector data-loss Fixes or risks loss or corruption of stored data 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 row deleted by an external writer during sync() is never reported as DELETE

2 participants