Repository navigation
[#172] Diff sync() against a copy of the CSV file and keep that copy as the next snapshot - #193
Conversation
… 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>.
… to the copy taken before the diff
…t mode and the unreadable CSV file of sync(), and log the copy a pass fails to read
vharseko
left a comment
There was a problem hiding this comment.
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.
…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.
|
Re review 5515753375: fixed in 2aa8447.
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 |
vharseko
left a comment
There was a problem hiding this comment.
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.
|
Re review 5535943732: the wording is fixed in f1f2df9. The comment at
|
vharseko
left a comment
There was a problem hiding this comment.
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.
… 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.
…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.
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.getLatestSyncTokenkeep running until a writer in this JVM queues behind the sync: the lock is a non-fairReentrantReadWriteLock, 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.copyCsvFile()writes the copy to a<csv>.<digits>.tmpfile fromcreateRewriteFile(), 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 withConnectorIOException"File … does not exist" when the CSV file is missing.<csv>.<mtime>withFiles.movewithout 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.copies.clear()after a handled delta ([#171] Skip CSV snapshot rows without a uid and delete the snapshots a failed sync copied #183);nulltoken;Trade-offs:
nullor 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 withConnectorException"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.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 withConnectorException"Unable to copy CSV file for sync operation", as a sync without a token already did. Before, these wereConnectorIOException"File … does not exist" and "Error reading from file …".Files.movechecks 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 inhandleResult, 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.<csv>.<digits>.tmpfiles by hand while no connector is running against the CSV file.<csv>.<mtime>whose content differs from the live file at that mtime (CSVFile connector: sync() never deletes old snapshots, and fails or keeps the old token when the current file already has a snapshot #174);false(CSVFile connector: sync() keeps offering deltas after the handler returns false and moves the token past the deltas it did not accept #175).Test strength
CSVFileConnector.java:635the create/update pass reads the copyrowCreatedDuringSyncIsReportedByTheNextSyncOnlyCSVFileConnector.java:680the copy becomes the next snapshotrowDeletedDuringSyncIsReportedByTheNextSyncCSVFileConnector.java:676same, once a delta is acceptedrowDeletedDuringSyncIsReportedByTheNextSync,rowCreatedDuringSyncIsReportedByTheNextSyncOnly,acceptedDeltaAdvancesTheTokenCSVFileConnector.java:550the index pass reads the copycsvFileChangedAfterItsCopyIsReportedByTheNextSync(overridescopyCsvFile()to rewrite the live file once the copy is taken)CSVFileConnector.java:515the mtime is read before the copycopyCsvFile()CSVFileConnector.java:517the 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 notcopyOfTheCsvFileBlocksWritersButNotReaders(overridescopyCsvFile()to callgetLatestSyncToken, thendelete, on another thread)CSVFileConnector.java:680an existing snapshot is not replacedexistingSnapshotOfTheCopiedMtimeKeepsTheTokenREPLACE_EXISTINGCSVFileConnector.java:685FileAlreadyExistsExceptionkeeps the tokenCSVFileConnector.java:707the copy is deleted when the sync endsexistingSnapshotOfTheCopiedMtimeKeepsTheToken,successfulSyncKeepsTheSnapshotItCopiedand 6 moreCSVFileConnector.java:1313copyCsvFile()deletes its file when the copy failsmissingCsvFileFailsSync,unreadableCsvFileFailsSyncCSVFileConnector.java:688a copy that cannot be moved to the next snapshot fails the syncsnapshotThatCannotBeMovedInFailsSync(POSIX, non-root)CSVFileConnector.java:1309the copy, and so the next snapshot, takes the mode of the CSV filesnapshotTakesTheModeOfTheCsvFile(POSIX, skipped when the umask gives the CSV file rw-------)createTempFilefile in place, which keeps rw-------CSVFileConnector.java:521an unreadable CSV file fails the copy with "Unable to copy…"unreadableCsvFileFailsSync(POSIX, non-root)AccessDeniedExceptionsent to theConnectorIOExceptionarmCSVFileConnector.java:566,:661a pass that cannot read the copy names the CSV file in its exception and the copy in its logcopyDeletedBeforeTheIndexPassFailsSyncNamingTheCsvFile,copyDeletedBeforeTheCreateUpdatePassFailsSyncNamingTheCsvFileCSVFileConnector.java:682next = nullafter the move.tmpfile thatcreateTempFilegave the freed name; a test cannot make it hand out that namemvn -pl OpenICF-csvfile-connector test: 132 run, 0 failures, 0 skipped (122 at 78c1e16).