Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

mypy plugin to check @cached return types #14911

Merged
merged 44 commits into from
Oct 2, 2023
Merged
Changes from 1 commit
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
eb24cdb
WIP mypy plugin to check `@cached` return types
Jan 25, 2023
d2cbac3
Whoops, Sequence is immutable
Jan 31, 2023
90631ac
WIP
Jan 31, 2023
4eb7de9
Merge remote-tracking branch 'origin/develop' into dmr/mypy-check-at-…
clokep Sep 12, 2023
ad1c28a
Update comments.
clokep Sep 12, 2023
88323dd
Simplify code due to other knowledge.
clokep Sep 12, 2023
676c858
Treat containers more similarly.
clokep Sep 12, 2023
008ef3f
cachedList wraps Mapping
clokep Sep 12, 2023
8aa4e87
Fix-up errors in tests.
clokep Sep 13, 2023
0f3c036
Ignore a few calls which purposefully (?) return mutable objects.
clokep Sep 13, 2023
9c94574
Data exfilitration is read-only and update admin APIs.
clokep Sep 13, 2023
f5fec7f
Update account_data & tags methods to be immutable.
clokep Sep 13, 2023
9a62053
FIx-up push related caching.
clokep Sep 13, 2023
cc61862
Update filtering to return immutable objects.
clokep Sep 13, 2023
a27a67f
Update relations with immutable.
clokep Sep 13, 2023
8f7f4d7
Update receipts code.
clokep Sep 13, 2023
9fdc5a1
Update e2e keys & devices.
clokep Sep 13, 2023
d8cce5b
Update appservice stuff.
clokep Sep 13, 2023
ef61f3d
Ensure current hosts is immutable.
clokep Sep 13, 2023
96faa34
Properly check attrs for frozen-ness.
clokep Sep 13, 2023
2f75929
Kick CI
clokep Sep 14, 2023
7849b26
Merge remote-tracking branch 'origin/develop' into dmr/mypy-check-at-…
clokep Sep 14, 2023
8b1b15b
Fix-up return value of get_latest_event_ids_in_room.
clokep Sep 14, 2023
451c9b1
Revert "Kick CI"
clokep Sep 14, 2023
d52e30c
Newsfragment
clokep Sep 14, 2023
47b7ba7
FIx-up sync changes.
clokep Sep 14, 2023
ee77d82
Merge remote-tracking branch 'origin/develop' into dmr/mypy-check-at-…
clokep Sep 18, 2023
0f02ad1
Merge remote-tracking branch 'origin/develop' into dmr/mypy-check-at-…
clokep Sep 19, 2023
51a1a5f
Merge remote-tracking branch 'origin/develop' into dmr/mypy-check-at-…
clokep Sep 20, 2023
07c4531
Merge branch 'develop' into dmr/mypy-check-at-cached
clokep Sep 25, 2023
745ad61
Correct context
erikjohnston Sep 29, 2023
03b0e40
Remove ignores for call-sites.
clokep Sep 29, 2023
2c07b1f
Merge remote-tracking branch 'origin/develop' into dmr/mypy-check-at-…
clokep Sep 29, 2023
460ed3c
Add ignores at definition sites.
clokep Sep 29, 2023
fbecb56
Actually check cachedList.
clokep Sep 29, 2023
dba8e72
Fix incorrect generic.
clokep Sep 29, 2023
4f06d85
Lint
clokep Sep 29, 2023
3875662
Abstract shared code.
clokep Sep 29, 2023
fb4ff5d
ServerAclEvaluator is immutable.
clokep Sep 29, 2023
06ddf65
Update comments.
clokep Sep 29, 2023
9b7ee03
Lint
clokep Sep 29, 2023
e2f599d
Update comments and remove unnecessary argument.
clokep Oct 2, 2023
da377cf
Merge remote-tracking branch 'origin/develop' into dmr/mypy-check-at-…
clokep Oct 2, 2023
a2956a6
Fix duplicate word.
clokep Oct 2, 2023
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
139 changes: 136 additions & 3 deletions scripts-dev/mypy_synapse_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,22 @@
can crop up, e.g the cache descriptors.
"""

from typing import Callable, Optional, Type
from typing import Callable, Optional, Tuple, Type

import mypy.types
from mypy.errorcodes import ErrorCode
from mypy.nodes import ARG_NAMED_OPT
from mypy.plugin import MethodSigContext, Plugin
from mypy.typeops import bind_self
from mypy.types import CallableType, NoneType, UnionType
from mypy.types import (
AnyType,
CallableType,
Instance,
NoneType,
TupleType,
TypeAliasType,
UnionType,
)


class SynapsePlugin(Plugin):
Expand All @@ -48,7 +58,7 @@ def cached_function_method_signature(ctx: MethodSigContext) -> CallableType:
"""

# First we mark this as a bound function signature.
signature = bind_self(ctx.default_signature)
signature: CallableType = bind_self(ctx.default_signature)

# Secondly, we remove any "cache_context" args.
#
Expand Down Expand Up @@ -98,9 +108,132 @@ def cached_function_method_signature(ctx: MethodSigContext) -> CallableType:
arg_kinds=arg_kinds,
)

# 4. Complain loudly if we are returning something mutable
check_is_cacheable(signature, ctx)

return signature


def clean_message(value: str) -> str:
return value.replace("builtins.", "").replace("typing.", "")


def unwrap_awaitable_types(t: mypy.types.Type) -> mypy.types.Type:
if isinstance(t, Instance):
if t.type.fullname == "typing.Coroutine":
# We're assuming this is Awaitable[R]m aka Coroutine[None, None, R].
# TODO: assert yield type and send type are None
# Extract the `R` type from `Coroutine[Y, S, R]`, and reinspect
t = t.args[2]
elif t.type.fullname == "twisted.internet.defer.Deferred":
t = t.args[0]

return mypy.types.get_proper_type(t)


def check_is_cacheable(signature: CallableType, ctx: MethodSigContext) -> None:
return_type = unwrap_awaitable_types(signature.ret_type)
verbose = ctx.api.options.verbosity >= 1
ok, note = is_cacheable(return_type, signature, verbose)

if ok:
message = f"function {signature.name} is @cached, returning {return_type}"
else:
message = f"function {signature.name} is @cached, but has mutable return value {return_type}"

if note:
message += f" ({note})"
message = clean_message(message)

if ok and note:
ctx.api.note(message, ctx.context) # type: ignore[attr-defined]
elif not ok:
ctx.api.fail(message, ctx.context, code=AT_CACHED_MUTABLE_RETURN)


IMMUTABLE_BUILTIN_VALUE_TYPES = {
"builtins.bool",
"builtins.int",
"builtins.float",
"builtins.str",
"builtins.bytes",
}

IMMUTABLE_BUILTIN_CONTAINER_TYPES = {
clokep marked this conversation as resolved.
Show resolved Hide resolved
"builtins.frozenset",
"typing.AbstractSet",
}

MUTABLE_BUILTIN_CONTAINER_TYPES = {
clokep marked this conversation as resolved.
Show resolved Hide resolved
"builtins.set",
"builtins.list",
"builtins.dict",
"typing.Sequence",
}

AT_CACHED_MUTABLE_RETURN = ErrorCode(
"synapse-@cached-mutable",
"@cached() should have an immutable return type",
"General",
)


def is_cacheable(
rt: mypy.types.Type, signature: CallableType, verbose: bool
) -> Tuple[bool, Optional[str]]:
"""
Returns: a 2-tuple (cacheable, message).
- cachable: False means the type is definitely not cacheable;
true means anything else.
- Optional message.
"""

# This should probably be done via a TypeVisitor. Apologies to the reader!
if isinstance(rt, AnyType):
return True, ("may be mutable" if verbose else None)

elif isinstance(rt, Instance):
if rt.type.fullname in IMMUTABLE_BUILTIN_VALUE_TYPES:
return True, None

elif rt.type.fullname == "typing.Mapping":
return is_cacheable(rt.args[1], signature, verbose)

elif rt.type.fullname in IMMUTABLE_BUILTIN_CONTAINER_TYPES:
return is_cacheable(rt.args[0], signature, verbose)

elif rt.type.fullname in MUTABLE_BUILTIN_CONTAINER_TYPES:
return False, None

elif "attrs" in rt.type.metadata:
frozen = rt.type.metadata["attrs"].get("frozen", False)
if frozen:
# TODO: should really check that all of the fields are also cacheable
return True, None
else:
return False, "non-frozen attrs class"

else:
return False, f"Don't know how to handle {rt.type.fullname}"

elif isinstance(rt, NoneType):
return True, None

elif isinstance(rt, (TupleType, UnionType)):
for item in rt.items:
ok, note = is_cacheable(item, signature, verbose)
if not ok:
return False, note
# This discards notes but that's probably fine
return True, None

elif isinstance(rt, TypeAliasType):
return is_cacheable(mypy.types.get_proper_type(rt), signature, verbose)

else:
return False, f"Don't know how to handle {type(rt).__qualname__} return type"


def plugin(version: str) -> Type[SynapsePlugin]:
# This is the entry point of the plugin, and lets us deal with the fact
# that the mypy plugin interface is *not* stable by looking at the version
Expand Down