diff --git a/lib/IMAP/Threading/ThreadBuilder.php b/lib/IMAP/Threading/ThreadBuilder.php
index 84bcc8cb3e7df98074f1dea75c22b0efdc496371..2b3c18f821ed278270cb834981092b917771e77f 100644
--- a/lib/IMAP/Threading/ThreadBuilder.php
+++ b/lib/IMAP/Threading/ThreadBuilder.php
@@ -114,7 +114,7 @@ class ThreadBuilder {
 			// Step 1.C
 			//$parentId = $message->getReferences()[count($message->getReferences()) - 1] ?? null;
 			//$container->setParent($idTable[$parentId] ?? null);
-			if ($parent === null || !$parent->hasAncestor($container)) {
+			if (($parent === null || !$parent->hasAncestor($container)) && $container !== $parent) {
 				$container->setParent($parent);
 			}
 		}
diff --git a/tests/Unit/IMAP/Threading/ThreadBuilderTest.php b/tests/Unit/IMAP/Threading/ThreadBuilderTest.php
index 23c1ed86849c16892fc3846ba165baefe0e5be5e..2e9959ee0d36ca05c9cdbf25d1da9e9831edc0ce 100644
--- a/tests/Unit/IMAP/Threading/ThreadBuilderTest.php
+++ b/tests/Unit/IMAP/Threading/ThreadBuilderTest.php
@@ -256,6 +256,33 @@ class ThreadBuilderTest extends TestCase {
 		);
 	}
 
+	public function testBuildTwoWithLoop(): void {
+		// 1 (but also points to itself)
+		// |
+		// 2
+		$messages = [
+			new Message('s1', 'id1', ['id1']),
+			new Message('s2', 'id2', ['id1']),
+		];
+
+		$result = $this->builder->build($messages, $this->logger);
+
+		$this->assertEquals(
+			[
+				[
+					'id' => 'id1',
+					'children' => [
+						[
+							'id' => 'id2',
+							'children' => [],
+						],
+					],
+				],
+			],
+			$this->abstract($result)
+		);
+	}
+
 	public function testBuildTree(): void {
 		//        1
 		//      /   \