diff --git a/CHANGES.md b/CHANGES.md
index e28730a..1d20a4c 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -11,6 +11,10 @@
 <!-- Changes that affect Black's stable style -->
 
 - Don't move comments along with delimiters, which could cause crashes (#4248)
+- Strengthen AST safety check to catch more unsafe changes to strings. Previous versions
+  of Black would incorrectly format the contents of certain unusual f-strings containing
+  nested strings with the same quote type. Now, Black will crash on such strings until
+  support for the new f-string syntax is implemented. (#4270)
 
 ### Preview style
 
diff --git a/src/black/__init__.py b/src/black/__init__.py
index f82b9fe..da884e6 100644
--- a/src/black/__init__.py
+++ b/src/black/__init__.py
@@ -77,8 +77,13 @@ from black.nodes import (
     syms,
 )
 from black.output import color_diff, diff, dump_to_file, err, ipynb_diff, out
-from black.parsing import InvalidInput  # noqa F401
-from black.parsing import lib2to3_parse, parse_ast, stringify_ast
+from black.parsing import (  # noqa F401
+    ASTSafetyError,
+    InvalidInput,
+    lib2to3_parse,
+    parse_ast,
+    stringify_ast,
+)
 from black.ranges import adjusted_lines, convert_unchanged_lines, parse_line_ranges
 from black.report import Changed, NothingChanged, Report
 from black.trans import iter_fexpr_spans
@@ -1511,7 +1516,7 @@ def assert_equivalent(src: str, dst: str) -> None:
     try:
         src_ast = parse_ast(src)
     except Exception as exc:
-        raise AssertionError(
+        raise ASTSafetyError(
             "cannot use --safe with this file; failed to parse source file AST: "
             f"{exc}\n"
             "This could be caused by running Black with an older Python version "
@@ -1522,7 +1527,7 @@ def assert_equivalent(src: str, dst: str) -> None:
         dst_ast = parse_ast(dst)
     except Exception as exc:
         log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
-        raise AssertionError(
+        raise ASTSafetyError(
             f"INTERNAL ERROR: Black produced invalid code: {exc}. "
             "Please report a bug on https://github.com/psf/black/issues.  "
             f"This invalid output might be helpful: {log}"
@@ -1532,7 +1537,7 @@ def assert_equivalent(src: str, dst: str) -> None:
     dst_ast_str = "\n".join(stringify_ast(dst_ast))
     if src_ast_str != dst_ast_str:
         log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
-        raise AssertionError(
+        raise ASTSafetyError(
             "INTERNAL ERROR: Black produced code that is not equivalent to the"
             " source.  Please report a bug on "
             f"https://github.com/psf/black/issues.  This diff might be helpful: {log}"
diff --git a/src/black/parsing.py b/src/black/parsing.py
index 63c5e71..aa97a8c 100644
--- a/src/black/parsing.py
+++ b/src/black/parsing.py
@@ -110,6 +110,10 @@ def lib2to3_unparse(node: Node) -> str:
     return code
 
 
+class ASTSafetyError(Exception):
+    """Raised when Black's generated code is not equivalent to the old AST."""
+
+
 def _parse_single_version(
     src: str, version: Tuple[int, int], *, type_comments: bool
 ) -> ast.AST:
@@ -154,9 +158,20 @@ def _normalize(lineend: str, value: str) -> str:
     return normalized.strip()
 
 
-def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
+def stringify_ast(node: ast.AST) -> Iterator[str]:
     """Simple visitor generating strings to compare ASTs by content."""
+    return _stringify_ast(node, [])
+
 
+def _stringify_ast_with_new_parent(
+    node: ast.AST, parent_stack: List[ast.AST], new_parent: ast.AST
+) -> Iterator[str]:
+    parent_stack.append(new_parent)
+    yield from _stringify_ast(node, parent_stack)
+    parent_stack.pop()
+
+
+def _stringify_ast(node: ast.AST, parent_stack: List[ast.AST]) -> Iterator[str]:
     if (
         isinstance(node, ast.Constant)
         and isinstance(node.value, str)
@@ -167,7 +182,7 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
         # over the kind
         node.kind = None
 
-    yield f"{'  ' * depth}{node.__class__.__name__}("
+    yield f"{'    ' * len(parent_stack)}{node.__class__.__name__}("
 
     for field in sorted(node._fields):  # noqa: F402
         # TypeIgnore has only one field 'lineno' which breaks this comparison
@@ -179,7 +194,7 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
         except AttributeError:
             continue
 
-        yield f"{'  ' * (depth + 1)}{field}="
+        yield f"{'    ' * (len(parent_stack) + 1)}{field}="
 
         if isinstance(value, list):
             for item in value:
@@ -191,13 +206,15 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
                     and isinstance(item, ast.Tuple)
                 ):
                     for elt in item.elts:
-                        yield from stringify_ast(elt, depth + 2)
+                        yield from _stringify_ast_with_new_parent(
+                            elt, parent_stack, node
+                        )
 
                 elif isinstance(item, ast.AST):
-                    yield from stringify_ast(item, depth + 2)
+                    yield from _stringify_ast_with_new_parent(item, parent_stack, node)
 
         elif isinstance(value, ast.AST):
-            yield from stringify_ast(value, depth + 2)
+            yield from _stringify_ast_with_new_parent(value, parent_stack, node)
 
         else:
             normalized: object
@@ -205,6 +222,12 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
                 isinstance(node, ast.Constant)
                 and field == "value"
                 and isinstance(value, str)
+                and len(parent_stack) >= 2
+                and isinstance(parent_stack[-1], ast.Expr)
+                and isinstance(
+                    parent_stack[-2],
+                    (ast.FunctionDef, ast.AsyncFunctionDef, ast.Module, ast.ClassDef),
+                )
             ):
                 # Constant strings may be indented across newlines, if they are
                 # docstrings; fold spaces after newlines when comparing. Similarly,
@@ -215,6 +238,9 @@ def stringify_ast(node: ast.AST, depth: int = 0) -> Iterator[str]:
                 normalized = value.rstrip()
             else:
                 normalized = value
-            yield f"{'  ' * (depth + 2)}{normalized!r},  # {value.__class__.__name__}"
+            yield (
+                f"{'    ' * (len(parent_stack) + 1)}{normalized!r},  #"
+                f" {value.__class__.__name__}"
+            )
 
-    yield f"{'  ' * depth})  # /{node.__class__.__name__}"
+    yield f"{'    ' * len(parent_stack)})  # /{node.__class__.__name__}"

diff --git a/tests/test_black.py b/tests/test_black.py
index 41f87cd..96f53d5 100644
--- a/tests/test_black.py
+++ b/tests/test_black.py
@@ -46,6 +46,7 @@ from black.cache import FileData, get_cache_dir, get_cache_file
 from black.debug import DebugVisitor
 from black.mode import Mode, Preview
 from black.output import color_diff, diff
+from black.parsing import ASTSafetyError
 from black.report import Report
 
 # Import other test classes
@@ -1473,10 +1474,6 @@ class BlackTestCase(BlackBaseTestCase):
                 ff(test_file, write_back=black.WriteBack.YES)
                 self.assertEqual(test_file.read_bytes(), expected)
 
-    def test_assert_equivalent_different_asts(self) -> None:
-        with self.assertRaises(AssertionError):
-            black.assert_equivalent("{}", "None")
-
     def test_root_logger_not_used_directly(self) -> None:
         def fail(*args: Any, **kwargs: Any) -> None:
             self.fail("Record created with root logger")
@@ -1962,16 +1959,6 @@ class BlackTestCase(BlackBaseTestCase):
 
         exc_info.match("Cannot parse: 2:0: EOF in multi-line statement")
 
-    def test_equivalency_ast_parse_failure_includes_error(self) -> None:
-        with pytest.raises(AssertionError) as err:
-            black.assert_equivalent("a«»a  = 1", "a«»a  = 1")
-
-        err.match("--safe")
-        # Unfortunately the SyntaxError message has changed in newer versions so we
-        # can't match it directly.
-        err.match("invalid character")
-        err.match(r"\(<unknown>, line 1\)")
-
     def test_line_ranges_with_code_option(self) -> None:
         code = textwrap.dedent("""\
             if  a  ==  b:
@@ -2822,6 +2809,113 @@ class TestDeFactoAPI:
             black.format_file_contents("x = 1\n", fast=True, mode=black.Mode())
 
 
+class TestASTSafety(BlackBaseTestCase):
+    def check_ast_equivalence(
+        self, source: str, dest: str, *, should_fail: bool = False
+    ) -> None:
+        # If we get a failure, make sure it's not because the code itself
+        # is invalid, since that will also cause assert_equivalent() to throw
+        # ASTSafetyError.
+        source = textwrap.dedent(source)
+        dest = textwrap.dedent(dest)
+        black.parse_ast(source)
+        black.parse_ast(dest)
+        if should_fail:
+            with self.assertRaises(ASTSafetyError):
+                black.assert_equivalent(source, dest)
+        else:
+            black.assert_equivalent(source, dest)
+
+    def test_assert_equivalent_basic(self) -> None:
+        self.check_ast_equivalence("{}", "None", should_fail=True)
+        self.check_ast_equivalence("1+2", "1    +   2")
+        self.check_ast_equivalence("hi # comment", "hi")
+
+    def test_assert_equivalent_del(self) -> None:
+        self.check_ast_equivalence("del (a, b)", "del a, b")
+
+    def test_assert_equivalent_strings(self) -> None:
+        self.check_ast_equivalence('x = "x"', 'x = " x "', should_fail=True)
+        self.check_ast_equivalence(
+            '''
+            """docstring  """
+            ''',
+            '''
+            """docstring"""
+            ''',
+        )
+        self.check_ast_equivalence(
+            '''
+            """docstring  """
+            ''',
+            '''
+            """ddocstring"""
+            ''',
+            should_fail=True,
+        )
+        self.check_ast_equivalence(
+            '''
+            class A:
+                """
+
+                docstring
+
+
+                """
+            ''',
+            '''
+            class A:
+                """docstring"""
+            ''',
+        )
+        self.check_ast_equivalence(
+            """
+            def f():
+                " docstring  "
+            """,
+            '''
+            def f():
+                """docstring"""
+            ''',
+        )
+        self.check_ast_equivalence(
+            """
+            async def f():
+                "   docstring  "
+            """,
+            '''
+            async def f():
+                """docstring"""
+            ''',
+        )
+
+    def test_assert_equivalent_fstring(self) -> None:
+        major, minor = sys.version_info[:2]
+        if major < 3 or (major == 3 and minor < 12):
+            pytest.skip("relies on 3.12+ syntax")
+        # https://github.com/psf/black/issues/4268
+        self.check_ast_equivalence(
+            """print(f"{"|".join([a,b,c])}")""",
+            """print(f"{" | ".join([a,b,c])}")""",
+            should_fail=True,
+        )
+        self.check_ast_equivalence(
+            """print(f"{"|".join(['a','b','c'])}")""",
+            """print(f"{" | ".join(['a','b','c'])}")""",
+            should_fail=True,
+        )
+
+    def test_equivalency_ast_parse_failure_includes_error(self) -> None:
+        with pytest.raises(ASTSafetyError) as err:
+            black.assert_equivalent("a«»a  = 1", "a«»a  = 1")
+
+        err.match("--safe")
+        # Unfortunately the SyntaxError message has changed in newer versions so we
+        # can't match it directly.
+        err.match("invalid character")
+        err.match(r"\(<unknown>, line 1\)")
+
+
 try:
     with open(black.__file__, "r", encoding="utf-8") as _bf:
         black_source_lines = _bf.readlines()

AST safety check fails to catch incorrect f-string change
**Describe the style change**

I wonder if f-strings should be formatted at all.

**Examples in the current _Black_ style**

```python
print(f"{"|".join(['a','b','c'])}")
```

**Desired style**

```python
print(f"{"|".join(['a','b','c'])}")
```

> [!NOTE]
> There's no change to the input here.

**Additional context**

Black formats the `"|"` to become `" | "` and that affects the output which cannot be desired.

Black formats the snippet like this currently:

```python
print(f"{" | ".join(['a','b','c'])}")
```

tests/test_black.py::BlackTestCase::test_assertFormatEqual_print_full_tree tests/test_black.py::BlackTestCase::test_assertFormatEqual_print_tree_diff tests/test_black.py::BlackTestCase::test_async_as_identifier tests/test_black.py::BlackTestCase::test_bpo_2142_workaround tests/test_black.py::BlackTestCase::test_bpo_33660_workaround tests/test_black.py::BlackTestCase::test_broken_symlink tests/test_black.py::BlackTestCase::test_check_diff_use_together tests/test_black.py::BlackTestCase::test_cli_unstable tests/test_black.py::BlackTestCase::test_code_option tests/test_black.py::BlackTestCase::test_code_option_changed tests/test_black.py::BlackTestCase::test_code_option_check tests/test_black.py::BlackTestCase::test_code_option_check_changed tests/test_black.py::BlackTestCase::test_code_option_color_diff tests/test_black.py::BlackTestCase::test_code_option_config tests/test_black.py::BlackTestCase::test_code_option_diff tests/test_black.py::BlackTestCase::test_code_option_fast tests/test_black.py::BlackTestCase::test_code_option_parent_config tests/test_black.py::BlackTestCase::test_code_option_safe tests/test_black.py::BlackTestCase::test_debug_visitor tests/test_black.py::BlackTestCase::test_detect_debug_f_strings tests/test_black.py::BlackTestCase::test_detect_pos_only_arguments tests/test_black.py::BlackTestCase::test_empty_ff tests/test_black.py::BlackTestCase::test_endmarker tests/test_black.py::BlackTestCase::test_expression_diff tests/test_black.py::BlackTestCase::test_expression_diff_with_color tests/test_black.py::BlackTestCase::test_expression_ff tests/test_black.py::BlackTestCase::test_false_positive_symlink_output_issue_3384 tests/test_black.py::BlackTestCase::test_find_project_root tests/test_black.py::BlackTestCase::test_find_pyproject_toml tests/test_black.py::BlackTestCase::test_find_user_pyproject_toml_linux tests/test_black.py::BlackTestCase::test_find_user_pyproject_toml_windows tests/test_black.py::BlackTestCase::test_for_handled_unexpected_eof_error tests/test_black.py::BlackTestCase::test_format_file_contents tests/test_black.py::BlackTestCase::test_get_features_used tests/test_black.py::BlackTestCase::test_get_features_used_decorator tests/test_black.py::BlackTestCase::test_get_features_used_for_future_flags tests/test_black.py::BlackTestCase::test_get_future_imports tests/test_black.py::BlackTestCase::test_infer_target_version tests/test_black.py::BlackTestCase::test_invalid_cli_regex tests/test_black.py::BlackTestCase::test_invalid_config_return_code tests/test_black.py::BlackTestCase::test_lib2to3_parse tests/test_black.py::BlackTestCase::test_line_ranges_in_pyproject_toml tests/test_black.py::BlackTestCase::test_line_ranges_with_code_option tests/test_black.py::BlackTestCase::test_line_ranges_with_ipynb tests/test_black.py::BlackTestCase::test_line_ranges_with_multiple_sources tests/test_black.py::BlackTestCase::test_line_ranges_with_source tests/test_black.py::BlackTestCase::test_line_ranges_with_stdin tests/test_black.py::BlackTestCase::test_multi_file_force_py36 tests/test_black.py::BlackTestCase::test_multi_file_force_pyi tests/test_black.py::BlackTestCase::test_newline_comment_interaction tests/test_black.py::BlackTestCase::test_no_src_fails tests/test_black.py::BlackTestCase::test_normalize_line_endings tests/test_black.py::BlackTestCase::test_normalize_path_ignore_windows_junctions_outside_of_root tests/test_black.py::BlackTestCase::test_one_empty_line tests/test_black.py::BlackTestCase::test_one_empty_line_ff tests/test_black.py::BlackTestCase::test_parse_pyproject_toml tests/test_black.py::BlackTestCase::test_parse_pyproject_toml_project_metadata tests/test_black.py::BlackTestCase::test_pep_572_version_detection tests/test_black.py::BlackTestCase::test_pep_695_version_detection tests/test_black.py::BlackTestCase::test_pipe_force_py36 tests/test_black.py::BlackTestCase::test_pipe_force_pyi tests/test_black.py::BlackTestCase::test_piping tests/test_black.py::BlackTestCase::test_piping_diff tests/test_black.py::BlackTestCase::test_piping_diff_with_color tests/test_black.py::BlackTestCase::test_preserves_line_endings tests/test_black.py::BlackTestCase::test_preserves_line_endings_via_stdin tests/test_black.py::BlackTestCase::test_python37 tests/test_black.py::BlackTestCase::test_read_pyproject_toml tests/test_black.py::BlackTestCase::test_read_pyproject_toml_from_stdin tests/test_black.py::BlackTestCase::test_reformat_one_with_stdin tests/test_black.py::BlackTestCase::test_reformat_one_with_stdin_and_existing_path tests/test_black.py::BlackTestCase::test_reformat_one_with_stdin_empty tests/test_black.py::BlackTestCase::test_reformat_one_with_stdin_filename tests/test_black.py::BlackTestCase::test_reformat_one_with_stdin_filename_ipynb tests/test_black.py::BlackTestCase::test_reformat_one_with_stdin_filename_pyi tests/test_black.py::BlackTestCase::test_report_normal tests/test_black.py::BlackTestCase::test_report_quiet tests/test_black.py::BlackTestCase::test_report_verbose tests/test_black.py::BlackTestCase::test_required_version_does_not_match_on_minor_version tests/test_black.py::BlackTestCase::test_required_version_does_not_match_version tests/test_black.py::BlackTestCase::test_required_version_matches_partial_version tests/test_black.py::BlackTestCase::test_required_version_matches_version tests/test_black.py::BlackTestCase::test_root_logger_not_used_directly tests/test_black.py::BlackTestCase::test_single_file_force_py36 tests/test_black.py::BlackTestCase::test_single_file_force_pyi tests/test_black.py::BlackTestCase::test_skip_magic_trailing_comma tests/test_black.py::BlackTestCase::test_skip_source_first_line tests/test_black.py::BlackTestCase::test_skip_source_first_line_when_mixing_newlines tests/test_black.py::BlackTestCase::test_spellcheck_pyproject_toml tests/test_black.py::BlackTestCase::test_src_and_code_fails tests/test_black.py::BlackTestCase::test_string_quotes tests/test_black.py::BlackTestCase::test_tab_comment_indentation tests/test_black.py::BlackTestCase::test_works_in_mono_process_only_environment tests/test_black.py::TestCaching::test_get_cache_dir tests/test_black.py::TestCaching::test_cache_file_length tests/test_black.py::TestCaching::test_cache_broken_file tests/test_black.py::TestCaching::test_cache_single_file_already_cached tests/test_black.py::TestCaching::test_cache_multiple_files tests/test_black.py::TestCaching::test_no_cache_when_writeback_diff[no-color] tests/test_black.py::TestCaching::test_no_cache_when_writeback_diff[with-color] tests/test_black.py::TestCaching::test_output_locking_when_writeback_diff[no-color] tests/test_black.py::TestCaching::test_output_locking_when_writeback_diff[with-color] tests/test_black.py::TestCaching::test_no_cache_when_stdin tests/test_black.py::TestCaching::test_read_cache_no_cachefile tests/test_black.py::TestCaching::test_write_cache_read_cache tests/test_black.py::TestCaching::test_filter_cached tests/test_black.py::TestCaching::test_filter_cached_hash tests/test_black.py::TestCaching::test_write_cache_creates_directory_if_needed tests/test_black.py::TestCaching::test_failed_formatting_does_not_get_cached tests/test_black.py::TestCaching::test_write_cache_write_fail tests/test_black.py::TestCaching::test_read_cache_line_lengths tests/test_black.py::TestFileCollection::test_include_exclude tests/test_black.py::TestFileCollection::test_gitignore_used_as_default tests/test_black.py::TestFileCollection::test_gitignore_used_on_multiple_sources tests/test_black.py::TestFileCollection::test_exclude_for_issue_1572 tests/test_black.py::TestFileCollection::test_gitignore_exclude tests/test_black.py::TestFileCollection::test_nested_gitignore tests/test_black.py::TestFileCollection::test_nested_gitignore_directly_in_source_directory tests/test_black.py::TestFileCollection::test_invalid_gitignore tests/test_black.py::TestFileCollection::test_invalid_nested_gitignore tests/test_black.py::TestFileCollection::test_gitignore_that_ignores_subfolders tests/test_black.py::TestFileCollection::test_empty_include tests/test_black.py::TestFileCollection::test_include_absolute_path tests/test_black.py::TestFileCollection::test_exclude_absolute_path tests/test_black.py::TestFileCollection::test_extend_exclude tests/test_black.py::TestFileCollection::test_symlinks tests/test_black.py::TestFileCollection::test_get_sources_symlink_and_force_exclude tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_symlink_outside_root tests/test_black.py::TestFileCollection::test_get_sources_with_stdin tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_filename tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_filename_and_exclude tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_filename_and_extend_exclude tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_filename_and_force_exclude tests/test_black.py::TestFileCollection::test_get_sources_with_stdin_filename_and_force_exclude_and_symlink tests/test_black.py::TestDeFactoAPI::test_format_str tests/test_black.py::TestDeFactoAPI::test_format_file_contents tests/test_black.py::TestASTSafety::test_assert_equivalent_basic tests/test_black.py::TestASTSafety::test_assert_equivalent_del tests/test_black.py::TestASTSafety::test_assert_equivalent_strings tests/test_black.py::TestASTSafety::test_equivalency_ast_parse_failure_includes_error