Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix cascade SQL cache remove loops forever on cyclic references #6137

Merged
merged 1 commit into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,19 @@ class SqlNormalizedCache internal constructor(
/**
* Assume an enclosing transaction
*/
private fun internalDeleteRecord(key: String, cascade: Boolean): Boolean {
private fun internalDeleteRecord(key: String, cascade: Boolean, visited: MutableSet<String> = mutableSetOf()): Boolean {
if (cascade) {
// If we've already visited this key, return to prevent infinite loop
if (key in visited) return false
visited.add(key)

recordDatabase.select(key)
?.referencedFields()
?.forEach {
internalDeleteRecord(
key = it.key,
cascade = true,
visited = visited
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,59 @@ class SqlNormalizedCacheTest {
assertEquals("bad cache", throwable!!.cause!!.message)
}

@Test
fun testCascadeDeleteWithSelfReference() {
// Creating a self-referencing record
cache.merge(
record = Record(
key = "selfRefKey",
fields = mapOf(
"field1" to "value1",
"selfRef" to CacheKey("selfRefKey"),
),
),
cacheHeaders = CacheHeaders.NONE,
)

val result = cache.remove(cacheKey = CacheKey("selfRefKey"), cascade = true)

assertTrue(result)
val record = cache.loadRecord("selfRefKey", CacheHeaders.NONE)
assertNull(record)
}

@Test
fun testCascadeDeleteWithCyclicReferences() {
// Creating two records that reference each other
cache.merge(
record = Record(
key = "key1",
fields = mapOf(
"field1" to "value1",
"refToKey2" to CacheKey("key2"),
),
),
cacheHeaders = CacheHeaders.NONE,
)

cache.merge(
record = Record(
key = "key2",
fields = mapOf(
"field1" to "value2",
"refToKey1" to CacheKey("key1"),
),
),
cacheHeaders = CacheHeaders.NONE,
)

val result = cache.remove(cacheKey = CacheKey("key1"), cascade = true)

assertTrue(result)
assertNull(cache.loadRecord("key1", CacheHeaders.NONE))
assertNull(cache.loadRecord("key2", CacheHeaders.NONE))
}
Comment on lines +359 to +410
Copy link
Contributor

Choose a reason for hiding this comment

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

Very cool tests 👍


private fun createRecord(key: String) {
cache.merge(
record = Record(
Expand Down
Loading