Skip to content
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
4 changes: 2 additions & 2 deletions .gemini/skills/pr-polisher/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ This skill is designed to evolve. If a human code reviewer (or presubmit hook) p
## Workflow Execution Steps

1. **Sync, Rebase, and Run the Automated Analysis Script**
First, fetch the latest `upstream/master` (`git fetch upstream master`) and rebase onto it (`git rebase upstream/master`) whenever creating or updating a PR branch—including in-flight code reviews—so the PR merges cleanly onto `master`. Then execute the packaged Python diff-checker script from the repository root. This script automatically checks commit messages, working tree status, `package-lock.json` modifications, copyright years on new files, missing tests across all tested modules, the 2-PR database schema split (Flyway scripts must not ship with Java or `db-schema.sql.generated` changes), Valkey Protostuff-cached entity field edits, state-machine anti-patterns (`TimedTransitionProperty.fromValueMap`, ordinal `Enum.compareTo`, Angular `setTimeout`/`GlobalLoaderService`/multi-boolean state flags), internal-only links or paths leaking into this public repository, whether the branch is rebased onto `upstream/master` and `FETCH_HEAD` freshness, and a litany of anti-patterns using regex (e.g., fully-qualified names, incorrect clock injections, generic exception catching).
First, fetch the latest `upstream/master` (`git fetch upstream master`) and rebase onto it (`git rebase upstream/master`) whenever creating or updating a PR branch—including in-flight code reviews—so the PR merges cleanly onto `master`. Then execute the packaged Python diff-checker script from the repository root. This script automatically checks commit messages, working tree status, `package-lock.json` modifications, copyright years on new files, missing tests across all tested modules, the 2-PR database schema split (Flyway scripts must not ship with Java or `db-schema.sql.generated` changes), Valkey Protostuff-cached entity field edits, GKE `requests.memory` sizing against `-XX:MaxRAMPercentage`, single-read `ServletInputStream` dual-injection hazards, state-machine anti-patterns (`TimedTransitionProperty.fromValueMap`, ordinal `Enum.compareTo`, Angular `setTimeout`/`GlobalLoaderService`/multi-boolean state flags), internal-only links or paths leaking into this public repository, whether the branch is rebased onto `upstream/master` and `FETCH_HEAD` freshness, and a litany of anti-patterns using regex (e.g., fully-qualified names, incorrect clock injections, generic exception catching).

```bash
python3 .gemini/skills/pr-polisher/scripts/check_diff.py
Expand Down Expand Up @@ -90,4 +90,4 @@ This skill is designed to evolve. If a human code reviewer (or presubmit hook) p
git add -u
git commit --amend # Or git commit --amend --no-edit if only files changed
```
**CRITICAL:** You must loop back to Step 1 and run `python3 .gemini/skills/pr-polisher/scripts/check_diff.py` again. Continue this loop of checking and amending until the script definitively returns `0 ERRORS`, the build/presubmits pass, and the working directory is perfectly clean. Do not assume your fixes worked without re-running the check.
**CRITICAL:** You must loop back to Step 1 and run `python3 .gemini/skills/pr-polisher/scripts/check_diff.py` again. Continue this loop of checking and amending until the script definitively returns `0 ERRORS`, the build/presubmits pass, and the working directory is perfectly clean. Do not assume your fixes worked without re-running the check.
322 changes: 322 additions & 0 deletions .gemini/skills/pr-polisher/scripts/check_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,39 @@
"core/src/main/java/google/registry/persistence/converter/TimedTransitionBaseUserType.java",
))

K8S_MEMORY_UNITS = {
"": 1,
"Ki": 1024,
"Mi": 1024**2,
"Gi": 1024**3,
"Ti": 1024**4,
"Pi": 1024**5,
"Ei": 1024**6,
"k": 1000,
"K": 1000,
"M": 1000**2,
"G": 1000**3,
"T": 1000**4,
"P": 1000**5,
"E": 1000**6,
}
K8S_MEMORY_QUANTITY_PATTERN = re.compile(
r'^"?([0-9]+(?:\.[0-9]+)?)(Ki|Mi|Gi|Ti|Pi|Ei|k|K|M|G|T|P|E)?"?$'
)
MAX_RAM_PERCENTAGE_PATTERN = re.compile(r'-XX:MaxRAMPercentage=([0-9]+(?:\.[0-9]+)?)')
DEFAULT_NOMULUS_MAX_RAM_PERCENTAGE = 50.0
DEFAULT_JDK_MAX_RAM_PERCENTAGE = 25.0

DIRECT_PAYLOAD_ANNOTATION_PATTERN = re.compile(r'@(OptionalJsonPayload|JsonPayload|Payload)\b')
PARAMETER_ANNOTATION_PATTERN = re.compile(r'@Parameter\s*\(\s*"([^"]+)"\s*\)')
PAYLOAD_BINDING_PATTERN = re.compile(
r'@(OptionalJsonPayload|JsonPayload|Payload)\b|@Parameter\s*\(\s*"([^"]+)"\s*\)'
)
PROVIDES_METHOD_PATTERN = re.compile(
r'@Provides\b(.*?)\{',
re.DOTALL,
)

# Internal-only references that must never land in this public repository.
# Buganizer references (b/123, http://b/123) are allowed and do not match.
INTERNAL_LEAK_PATTERNS = (
Expand Down Expand Up @@ -571,6 +604,293 @@ def check_db_schema_split():
else:
log_success("No database schema or JPA entity changes found.")

def parse_k8s_memory_bytes(raw_value):
match = K8S_MEMORY_QUANTITY_PATTERN.match(raw_value.strip())
if not match:
return None
amount = float(match.group(1))
unit = match.group(2) or ""
return int(amount * K8S_MEMORY_UNITS[unit])

def parse_max_ram_percentage(text):
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith('#'):
continue
match = MAX_RAM_PERCENTAGE_PATTERN.search(stripped)
if match:
return float(match.group(1))
return None

def extract_k8s_containers(yaml_text):
containers = []
for doc in re.split(r'(?m)^---\s*$', yaml_text):
lines = doc.splitlines()
in_containers = False
containers_indent = -1
current = None
container_indent = -1
section = None
section_indent = -1
env_name = None
env_indent = -1

for raw_line in lines:
stripped = raw_line.strip()
if not stripped or stripped.startswith('#'):
continue
indent = len(raw_line) - len(raw_line.lstrip(' '))

if not in_containers:
if stripped == 'containers:':
in_containers = True
containers_indent = indent
continue

if indent <= containers_indent and not stripped.startswith('- '):
in_containers = False
current = None
continue

if stripped.startswith('- name:') and (
container_indent == -1 or indent <= container_indent
):
container_indent = indent
current = {
'name': stripped.split(':', 1)[1].strip().strip('"\''),
'image': '',
'requests_memory': None,
'limits_memory': None,
'jdk_java_options': '',
}
containers.append(current)
section = None
section_indent = -1
env_name = None
env_indent = -1
continue

if current is None:
continue

if section is not None and (
indent < section_indent
or (indent == section_indent and not (section == 'env' and stripped.startswith('- ')))
):
section = None
section_indent = -1
if env_name is not None and indent <= env_indent:
env_name = None
env_indent = -1

if stripped.startswith('image:') and section is None:
current['image'] = stripped.split(':', 1)[1].strip().strip('"\'')
elif stripped == 'requests:':
section = 'requests'
section_indent = indent
elif stripped == 'limits:':
section = 'limits'
section_indent = indent
elif stripped == 'env:':
section = 'env'
section_indent = indent
elif section == 'requests' and stripped.startswith('memory:'):
current['requests_memory'] = stripped.split(':', 1)[1].strip()
elif section == 'limits' and stripped.startswith('memory:'):
current['limits_memory'] = stripped.split(':', 1)[1].strip()
elif section == 'env' and stripped.startswith('- name:'):
env_name = stripped.split(':', 1)[1].strip().strip('"\'')
env_indent = indent
elif section == 'env' and env_name == 'JDK_JAVA_OPTIONS' and stripped.startswith('value:'):
current['jdk_java_options'] = stripped.split(':', 1)[1].strip().strip('"\'')

return containers

def find_gke_memory_issues(yaml_path, yaml_text, default_nomulus_max_ram_pct=DEFAULT_NOMULUS_MAX_RAM_PERCENTAGE):
issues = []
for container in extract_k8s_containers(yaml_text):
req_raw = container['requests_memory']
lim_raw = container['limits_memory']
if not req_raw or not lim_raw:
continue
req_bytes = parse_k8s_memory_bytes(req_raw)
lim_bytes = parse_k8s_memory_bytes(lim_raw)
if req_bytes is None or lim_bytes is None:
continue

max_ram_pct = parse_max_ram_percentage(container['jdk_java_options'])
if max_ram_pct is None:
image = container['image']
if re.search(r'/nomulus(?:[:@]|$)', image):
max_ram_pct = default_nomulus_max_ram_pct
elif re.search(r'/proxy(?:[:@]|$)', image):
max_ram_pct = DEFAULT_JDK_MAX_RAM_PERCENTAGE
else:
continue

max_heap_bytes = lim_bytes * (max_ram_pct / 100.0)
if req_bytes <= max_heap_bytes:
max_heap_mib = max_heap_bytes / (1024 * 1024)
req_mib = req_bytes / (1024 * 1024)
issues.append(
f"[{yaml_path}] Container '{container['name']}' has requests.memory={req_raw.strip('\"')}"
f" ({req_mib:.0f} MiB) <= {max_ram_pct:g}% of limits.memory={lim_raw.strip('\"')}"
f" ({max_heap_mib:.0f} MiB max JVM heap). -XX:MaxRAMPercentage scales off"
" limits.memory, not requests.memory; size requests.memory strictly above max"
" heap plus non-heap footprint to prevent kubelet evictions."
)
return issues

def check_gke_memory_requests(diff_files=None, root_dir="."):
print("\n--- Checking GKE Memory Requests vs -XX:MaxRAMPercentage ---")
if diff_files is None:
diff_files = get_diff_files()

k8s_files = []
if "jetty/start.sh" in diff_files:
k8s_dir = os.path.join(root_dir, "jetty", "kubernetes")
if os.path.isdir(k8s_dir):
for name in sorted(os.listdir(k8s_dir)):
if name.endswith(".yaml"):
k8s_files.append(f"jetty/kubernetes/{name}")

for path in diff_files:
if (
(path.startswith("jetty/kubernetes/") or path.startswith("proxy/kubernetes/"))
and path.endswith(".yaml")
and path not in k8s_files
):
k8s_files.append(path)

if not k8s_files:
log_success("No GKE manifest or JVM heap flag changes found.")
return

default_nomulus_pct = DEFAULT_NOMULUS_MAX_RAM_PERCENTAGE
start_sh_path = os.path.join(root_dir, "jetty", "start.sh")
if os.path.isfile(start_sh_path):
with open(start_sh_path, "r", encoding="utf-8") as f:
parsed_pct = parse_max_ram_percentage(f.read())
if parsed_pct is not None:
default_nomulus_pct = parsed_pct

found_any = False
for rel_path in k8s_files:
full_path = os.path.join(root_dir, rel_path)
if not os.path.isfile(full_path):
continue
with open(full_path, "r", encoding="utf-8") as f:
issues = find_gke_memory_issues(rel_path, f.read(), default_nomulus_pct)
for issue in issues:
found_any = True
log_warning(issue)

if not found_any:
log_success("GKE requests.memory exceeds configured JVM max heap across touched manifests.")

def strip_java_comments(java_text):
without_block = re.sub(r'/\*.*?\*/', ' ', java_text, flags=re.DOTALL)
return re.sub(r'//[^\n]*', '', without_block)

def discover_payload_backed_parameters(root_dir="."):
payload_params = set()
src_root = os.path.join(root_dir, "core", "src", "main", "java")
if not os.path.isdir(src_root):
return frozenset()
for dirpath, _, filenames in os.walk(src_root):
for filename in filenames:
if not filename.endswith("Module.java"):
continue
full_path = os.path.join(dirpath, filename)
with open(full_path, "r", encoding="utf-8") as f:
text = strip_java_comments(f.read())
for match in PROVIDES_METHOD_PATTERN.finditer(text):
header = match.group(1)
if not DIRECT_PAYLOAD_ANNOTATION_PATTERN.search(header):
continue
for param_match in PARAMETER_ANNOTATION_PATTERN.finditer(header):
payload_params.add(param_match.group(1))
return frozenset(payload_params)

def extract_inject_segments(cleaned_java):
segments = []
n = len(cleaned_java)
for match in re.finditer(r'@Inject\b', cleaned_java):
i = match.end()
paren_depth = 0
saw_param_list = False
while i < n:
ch = cleaned_java[i]
if ch == '"':
i += 1
while i < n and cleaned_java[i] != '"':
if cleaned_java[i] == '\\':
i += 1
i += 1
elif ch == '(':
paren_depth += 1
# Distinguish annotation args (@Foo(...)) from constructor/method param list.
prefix = cleaned_java[match.end():i].rstrip()
if paren_depth == 1 and not re.search(r'@[A-Za-z0-9_.]+\s*$', prefix):
saw_param_list = True
elif ch == ')':
paren_depth = max(0, paren_depth - 1)
if paren_depth == 0 and saw_param_list:
i += 1
break
elif paren_depth == 0 and ch in (';', '=', '{'):
break
i += 1
segments.append(cleaned_java[match.start():i])
return segments

def find_servlet_stream_dual_injections(java_text, payload_backed_params):
cleaned = strip_java_comments(java_text)
if re.search(r'@Module\b', cleaned):
return []

bindings = []
for segment in extract_inject_segments(cleaned):
for match in PAYLOAD_BINDING_PATTERN.finditer(segment):
if match.group(1):
bindings.append(f"@{match.group(1)}")
elif match.group(2) in payload_backed_params:
bindings.append(f'@Parameter("{match.group(2)}")')
return bindings if len(bindings) >= 2 else []

def check_servlet_input_stream_dual_injection(diff_files=None, root_dir="."):
print("\n--- Checking Single-Read ServletInputStream Invariant ---")
if diff_files is None:
diff_files = get_diff_files()

java_files = [
f for f in diff_files if f.startswith("core/src/main/") and f.endswith(".java")
]
if not java_files:
log_success("No core production Java files changed.")
return

payload_backed_params = discover_payload_backed_parameters(root_dir)
found_any = False
for rel_path in java_files:
full_path = os.path.join(root_dir, rel_path)
if not os.path.isfile(full_path):
continue
with open(full_path, "r", encoding="utf-8") as f:
bindings = find_servlet_stream_dual_injections(f.read(), payload_backed_params)
if bindings:
found_any = True
log_error(
f"[{rel_path}] Injects multiple ServletInputStream-reading bindings"
f" ({', '.join(bindings)}). RequestModule payload providers are intentionally"
" unscoped and Jetty's ServletInputStream drains on the first read, leaving"
" subsequent reads empty. Inject @OptionalJsonPayload once and deserialize"
" inside the action with Gson."
)

if not found_any:
log_success("No dual ServletInputStream injections detected.")

def check_missing_tests():
print("\n--- Checking for Missing Tests ---")
diff_files = get_diff_files()
Expand All @@ -597,6 +917,8 @@ def main():
check_missing_tests()
check_db_schema_split()
check_protostuff_cached_entities()
check_gke_memory_requests()
check_servlet_input_stream_dual_injection()
check_upstream_freshness()
check_formatting()
check_package_lock()
Expand Down
Loading
Loading