diff --git a/.github/public-behavior/CliContracts.java b/.github/public-behavior/CliContracts.java new file mode 100644 index 0000000000000..8ce2f1c3234d8 --- /dev/null +++ b/.github/public-behavior/CliContracts.java @@ -0,0 +1,198 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import com.sun.source.util.TreeScanner; +import java.nio.file.Path; +import java.util.*; +import java.util.function.Consumer; +import javax.lang.model.element.Modifier; + +class CliContracts { + static void compare(Path file, ClassTree before, ClassTree after, Consumer output) { + // Moving declarations to another class may preserve the CLI. + if (before == null || after == null) + return; + + String name = file.getFileName().toString(); + if (name.equals("CommandHandler.java")) { + compareExitCodes(before, after, output); + return; + } + + boolean commands = name.equals("IgniteCommandRegistry.java"); + if (!commands && !name.equals("ArgumentParser.java")) + return; + Registrations old = registrations(before, commands); + Registrations now = registrations(after, commands); + if (old == null || now == null || !old.otherStatements().equals(now.otherStatements())) + return; + String label = commands ? "CLI command " : "CLI option "; + old.options().forEach((nameBefore, type) -> { + if (!now.options().containsKey(nameBefore)) + output.accept("Removed " + label + nameBefore); + }); + now.options().forEach((nameAfter, type) -> { + if (!old.options().containsKey(nameAfter)) + output.accept("Added " + label + nameAfter); + else if (type != null && old.options().get(nameAfter) != null && !type.equals(old.options().get(nameAfter))) + output.accept("Changed CLI option " + nameAfter + " type from " + old.options().get(nameAfter) + " to " + type); + }); + } + + private record Registration(String name, String type) {} + private record Registrations(Map options, List otherStatements) {} + + private static Registrations registrations(ClassTree cls, boolean commands) { + List constructors = cls.getMembers().stream().filter(MethodTree.class::isInstance) + .map(MethodTree.class::cast).filter(m -> m.getReturnType() == null).toList(); + if (constructors.size() != 1 || constructors.get(0).getBody() == null) + return null; + Map constants = constants(cls); + Map options = new TreeMap<>(); + List other = new ArrayList<>(); + boolean found = false; + for (StatementTree stmt : constructors.get(0).getBody().getStatements()) { + List args = null; + if (stmt instanceof ExpressionStatementTree expr && expr.getExpression() instanceof MethodInvocationTree call) { + if (commands && call.getMethodSelect().toString().equals("super")) + args = call.getArguments(); + else if (!commands && call.getMethodSelect().toString().equals("common.addAll") + && call.getArguments().size() == 1 && call.getArguments().get(0) instanceof MethodInvocationTree list + && Set.of("List.of", "java.util.List.of").contains(list.getMethodSelect().toString())) + args = list.getArguments(); + } + if (args == null) { + // A helper can register the same names that were removed from the list. + other.add(stmt.toString()); + continue; + } + if (found) + return null; + found = true; + for (ExpressionTree arg : args) { + Registration registration = commands ? command(arg) : option(arg, constants); + if (registration == null) + return null; + options.put(registration.name(), registration.type()); + } + } + return found ? new Registrations(options, other) : null; + } + + private static Registration command(ExpressionTree arg) { + if (!(arg instanceof NewClassTree cmd) || cmd.getClassBody() != null) + return null; + String name = cmd.getIdentifier().toString(); + name = name.substring(name.lastIndexOf('.') + 1); + if (!name.matches("[A-Z][a-zA-Z]*Command")) + return null; + // CommandUtils inserts a dash before each uppercase letter after the first one. + String stem = name.substring(0, name.length() - "Command".length()); + return new Registration("--" + stem.replaceAll("(? constants) { + while (expr instanceof MethodInvocationTree call) { + String method = call.getMethodSelect().toString(); + if (Set.of("argument", "optionalArgument").contains(method) && call.getArguments().size() == 2) { + ExpressionTree arg = call.getArguments().get(0); + Object name = arg instanceof LiteralTree lit ? lit.getValue() : constants.get(arg.toString()); + if (!(name instanceof String option) || !option.matches("--[a-z0-9-]+")) + return null; + return new Registration(option, optionType(call.getArguments().get(1))); + } + if (!(call.getMethodSelect() instanceof MemberSelectTree chain)) + break; + expr = chain.getExpression(); + } + return null; + } + + private static String optionType(ExpressionTree type) { + if (!(type instanceof MemberSelectTree selected) || !selected.getIdentifier().contentEquals("class")) + return null; + // CommandUtils parses primitive and boxed options alike. A password is read as one string. + String name = selected.getExpression().toString(); + if (name.startsWith("java.lang.")) + name = name.substring("java.lang.".length()); + return switch (name) { + case "Boolean", "boolean" -> "boolean"; + case "Integer", "int" -> "int"; + case "Long", "long" -> "long"; + case "Float", "float" -> "float"; + case "Double", "double" -> "double"; + case "String", "char[]" -> "string"; + case "String[]" -> "string list"; + default -> null; + }; + } + + private static Map constants(ClassTree cls) { + Map values = new HashMap<>(); + for (Tree member : cls.getMembers()) { + if (member instanceof VariableTree field && field.getInitializer() instanceof LiteralTree literal + && field.getModifiers().getFlags().containsAll(Set.of(Modifier.STATIC, Modifier.FINAL))) + values.put(field.getName().toString(), literal.getValue()); + } + return values; + } + + private static MethodTree execute(ClassTree cls) { + for (Tree member : cls.getMembers()) { + if (member instanceof MethodTree method && method.getName().contentEquals("execute") + && "int".equals(String.valueOf(method.getReturnType())) && method.getParameters().size() == 1 + && Set.of("List", "java.util.List").contains(method.getParameters().get(0).getType().toString())) + return method; + } + return null; + } + + private static void compareExitCodes(ClassTree before, ClassTree after, Consumer output) { + MethodTree old = execute(before); + MethodTree now = execute(after); + // If the dispatch changed, a different return statement may still give callers the same code. + if (old == null || now == null || old.getBody() == null || now.getBody() == null + || !old.getBody().toString().equals(now.getBody().toString())) + return; + Set returned = new TreeSet<>(); + Set locals = new HashSet<>(); + new TreeScanner() { + @Override public Void visitVariable(VariableTree var, Void p) { + locals.add(var.getName().toString()); + return super.visitVariable(var, p); + } + + @Override public Void visitReturn(ReturnTree ret, Void p) { + if (ret.getExpression() instanceof IdentifierTree id) + returned.add(id.getName().toString()); + return null; + } + + @Override public Void visitLambdaExpression(LambdaExpressionTree lambda, Void p) { return null; } + @Override public Void visitClass(ClassTree nested, Void p) { return null; } + }.scan(old.getBody(), null); + returned.removeAll(locals); + Map oldValues = constants(before); + Map newValues = constants(after); + for (String status : returned) { + if (oldValues.get(status) instanceof Integer from && newValues.get(status) instanceof Integer to + && !from.equals(to)) + output.accept("Changed CLI exit code for " + status + " from " + from + " to " + to); + } + } +} diff --git a/.github/public-behavior/ErrorMapping.java b/.github/public-behavior/ErrorMapping.java new file mode 100644 index 0000000000000..cea3172622bb4 --- /dev/null +++ b/.github/public-behavior/ErrorMapping.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import java.nio.file.Path; +import java.util.*; +import java.util.function.BiConsumer; +import javax.lang.model.element.Modifier; + +/** SQLState returned for a numeric Ignite error by the JDBC error mapping. */ +class ErrorMapping { + private static final Path ROOT = Path.of("modules/core/src/main/java/org/apache/ignite/internal/processors"); + private static final Path ERRORS = ROOT.resolve("cache/query/IgniteQueryErrorCode.java"); + private static final Path STATES = ROOT.resolve("odbc/SqlStateCode.java"); + + static void compare(Map before, Map after, BiConsumer output) { + Map old = mapping(before); + for (var entry : mapping(after).entrySet()) { + String from = old.get(entry.getKey()); + if (from != null && !from.equals(entry.getValue())) + output.accept(ERRORS, "Changed SQLState for error " + entry.getKey() + " from " + from + " to " + entry.getValue()); + } + } + + private static Map mapping(Map types) { + ClassTree errors = types.get(ERRORS); + ClassTree states = types.get(STATES); + if (errors == null || states == null) + return Map.of(); + Map values = new HashMap<>(); + for (Tree member : states.getMembers()) { + if (member instanceof VariableTree field && JavaContracts.literal(field.getInitializer()) instanceof String value) + values.put(field.getName().toString(), value); + } + Map codes = new HashMap<>(); + for (Tree member : errors.getMembers()) { + if (member instanceof VariableTree field && field.getType().toString().equals("int") + && field.getModifiers().getFlags().containsAll(Set.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)) + && JavaContracts.literal(field.getInitializer()) instanceof Integer value) + codes.put(field.getName().toString(), value); + } + for (Tree member : errors.getMembers()) { + if (member instanceof MethodTree method && method.getName().contentEquals("codeToSqlState") + && method.getParameters().size() == 1 && method.getParameters().get(0).getType().toString().equals("int") + && method.getBody() != null && method.getBody().getStatements().size() == 1 + && method.getBody().getStatements().get(0) instanceof SwitchTree sw) { + ExpressionTree selector = sw.getExpression(); + while (selector instanceof ParenthesizedTree parens) + selector = parens.getExpression(); + if (selector instanceof IdentifierTree id && id.getName().equals(method.getParameters().get(0).getName())) + return switchValues(sw, codes, values); + } + } + return Map.of(); + } + + private static Map switchValues(SwitchTree sw, Map codes, Map states) { + Map result = new TreeMap<>(); + List pending = new ArrayList<>(); + boolean defaultFallsThrough = false; + String fallback = null; + for (CaseTree branch : sw.getCases()) { + if (branch.getCaseKind() != CaseTree.CaseKind.STATEMENT) + return Map.of(); + if (branch.getExpressions().isEmpty()) + defaultFallsThrough = true; + for (ExpressionTree key : branch.getExpressions()) { + if (!(key instanceof IdentifierTree id) || !codes.containsKey(id.getName().toString())) + return Map.of(); + pending.add(codes.get(id.getName().toString())); + } + var statements = branch.getStatements(); + if (statements.isEmpty()) + continue; + if (statements.size() != 1 || !(statements.get(0) instanceof ReturnTree ret)) + return Map.of(); + ExpressionTree expr = ret.getExpression(); + String state = null; + if (JavaContracts.literal(expr) instanceof String literal) + state = literal; + else if (expr instanceof MemberSelectTree ref && ref.getExpression().toString().equals("SqlStateCode")) + state = states.get(ref.getIdentifier().toString()); + if (state == null) + return Map.of(); + for (Integer code : pending) + result.put(code, state); + if (defaultFallsThrough) { + fallback = state; + defaultFallsThrough = false; + } + pending.clear(); + } + if (fallback != null) { + for (Integer code : codes.values()) + result.putIfAbsent(code, fallback); + } + return result; + } +} diff --git a/.github/public-behavior/FormatContracts.java b/.github/public-behavior/FormatContracts.java new file mode 100644 index 0000000000000..bd2ad7e63b4b0 --- /dev/null +++ b/.github/public-behavior/FormatContracts.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import java.util.*; +import java.util.function.Consumer; + +/** Literal values used to write external binary objects and persistent files. */ +class FormatContracts { + private static final String STORAGE = "org.apache.ignite.internal.processors.cache.persistence."; + private static final Set BINARY_TAGS = Set.of( + "BYTE", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE", "CHAR", "BOOLEAN", "DECIMAL", "STRING", "UUID", "DATE", + "BYTE_ARR", "SHORT_ARR", "INT_ARR", "LONG_ARR", "FLOAT_ARR", "DOUBLE_ARR", "CHAR_ARR", "BOOLEAN_ARR", + "DECIMAL_ARR", "STRING_ARR", "UUID_ARR", "DATE_ARR", "OBJ_ARR", "COL", "MAP", "BINARY_OBJ", "ENUM", "ENUM_ARR", + "TIMESTAMP", "TIMESTAMP_ARR", "TIME", "TIME_ARR", "NULL", "HANDLE", "OBJ"); + + static void compare(String owner, ClassTree before, ClassTree after, Consumer output) { + Map old = fields(owner, before); + for (var field : fields(owner, after).entrySet()) { + Number from = old.get(field.getKey()); + if (from != null && !from.equals(field.getValue())) + output.accept("Changed " + field.getKey() + " from " + from + " to " + field.getValue()); + } + } + + private static Map fields(String owner, ClassTree cls) { + Map values = new TreeMap<>(); + for (Tree member : cls.getMembers()) { + if (owner.equals("org.apache.ignite.internal.pagemem.wal.record.WALRecord") + && member instanceof ClassTree nested && nested.getKind() == Tree.Kind.ENUM + && nested.getSimpleName().contentEquals("RecordType")) { + for (Tree item : nested.getMembers()) { + if (item instanceof VariableTree entry && entry.getType().toString().equals("RecordType") + && entry.getInitializer() instanceof NewClassTree init && !init.getArguments().isEmpty() + && !entry.getName().toString().startsWith("RESERVED") + && JavaContracts.literal(init.getArguments().get(0)) instanceof Integer index) + values.put("WAL record index for " + entry.getName(), index); + } + continue; + } + if (!(member instanceof VariableTree field) + || !field.getModifiers().getFlags().containsAll(Set.of(javax.lang.model.element.Modifier.STATIC, + javax.lang.model.element.Modifier.FINAL))) + continue; + String name = field.getName().toString(); + String subject = switch (owner) { + case "org.apache.ignite.internal.binary.GridBinaryMarshaller" -> + BINARY_TAGS.contains(name) ? "binary type code for " + name : + name.equals("PROTO_VER") ? "binary object protocol version" : null; + case STORAGE + "file.FilePageStore", STORAGE + "file.FilePageStoreV2" -> + Set.of("SIGNATURE", "VERSION").contains(name) ? cls.getSimpleName() + " header " + name : null; + case STORAGE + "snapshot.SnapshotMetadata", STORAGE + "snapshot.IncrementalSnapshotMetadata" -> + name.equals("serialVersionUID") ? cls.getSimpleName() + " serialization version" : null; + default -> null; + }; + if (subject == null) + continue; + ExpressionTree expr = field.getInitializer(); + if (expr instanceof TypeCastTree cast && cast.getType().toString().equals("byte") + && JavaContracts.literal(cast.getExpression()) instanceof Integer n) + values.put(subject, (long)n.byteValue()); + else if (JavaContracts.literal(expr) instanceof Number n && (n instanceof Long || n instanceof Integer)) + values.put(subject, n.longValue()); + } + return values; + } +} diff --git a/.github/public-behavior/JavaContracts.java b/.github/public-behavior/JavaContracts.java new file mode 100644 index 0000000000000..8c572d37a0615 --- /dev/null +++ b/.github/public-behavior/JavaContracts.java @@ -0,0 +1,355 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import com.sun.source.util.JavacTask; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import javax.lang.model.element.Modifier; +import javax.tools.*; + +class JavaContracts { + private record Entry(Path file, String owner, String subject, String signature, boolean couldBeInherited, boolean deprecated) {} + + private static final Set OBJECT_METHODS = Set.of("equals", "hashCode", "toString", "getClass", "clone", + "finalize", "notify", "notifyAll", "wait"); + + private static final Map WIRE_TYPES = Map.of( + "org.apache.ignite.internal.processors.odbc.SqlStateCode", "SQLState", + "org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode", "SQL error code", + "org.apache.ignite.internal.client.thin.ClientOperation", "client operation ID", + "org.apache.ignite.internal.processors.platform.client.ClientBitmaskFeature", "client feature ID"); + + private final Map> declarations = new TreeMap<>(); + private final Map> wireValues = new TreeMap<>(); + private final Map wireFiles = new HashMap<>(); + private final Map units = new TreeMap<>(); + private final Map internalTypes = new TreeMap<>(); + private final Set typesWithParents = new HashSet<>(); + + private static boolean exported(ModifiersTree mods, boolean implicitPublic) { + Set flags = mods.getFlags(); + return !flags.contains(Modifier.PRIVATE) && (implicitPublic || flags.contains(Modifier.PUBLIC) + || flags.contains(Modifier.PROTECTED)); + } + + static Object literal(ExpressionTree expr) { + if (expr instanceof ParenthesizedTree parens) + return literal(parens.getExpression()); + if (expr instanceof LiteralTree lit && lit.getValue() != null) + return lit.getValue(); + if (expr instanceof UnaryTree unary && unary.getKind() == Tree.Kind.UNARY_MINUS + && unary.getExpression() instanceof LiteralTree lit && lit.getValue() instanceof Number) + return switch (lit.getKind()) { + case INT_LITERAL -> -((Integer)lit.getValue()); + case LONG_LITERAL -> -((Long)lit.getValue()); + case FLOAT_LITERAL -> -((Float)lit.getValue()); + case DOUBLE_LITERAL -> -((Double)lit.getValue()); + default -> null; + }; + return null; + } + + private static String constantValue(VariableTree field) { + Object value = literal(field.getInitializer()); + if (value == null) + return null; + String type = field.getType().toString(); + if (Set.of("String", "java.lang.String").contains(type) && value instanceof String text) + return text; + if (type.equals("boolean") && value instanceof Boolean flag) + return flag.toString(); + if (value instanceof Character ch) + value = (int)ch; + if (!(value instanceof Number number)) + return null; + return switch (type) { + case "double" -> Double.toString(number.doubleValue()); + case "float" -> Float.toString(number.floatValue()); + case "byte", "short", "char", "int", "long" -> number instanceof Integer || number instanceof Long + ? Long.toString(number.longValue()) : null; + default -> null; + }; + } + + // Qualified and imported spellings of the same type share its simple name. A change of imports alone + // is outside this comparison. Generic type variables need attribution, so leave their signatures unknown. + private static String type(Tree type, Set variables) { + if (type instanceof AnnotatedTypeTree annotated) + return type(annotated.getUnderlyingType(), variables); + if (type instanceof ParameterizedTypeTree parameterized) + return type(parameterized.getType(), variables); + if (type instanceof ArrayTypeTree array) { + String element = type(array.getType(), variables); + return element == null ? null : element + "[]"; + } + if (type instanceof PrimitiveTypeTree primitive) + return primitive.getPrimitiveTypeKind().toString().toLowerCase(Locale.ROOT); + if (type instanceof MemberSelectTree member) + return member.getIdentifier().toString(); + if (type instanceof IdentifierTree id && !variables.contains(id.getName().toString())) + return id.getName().toString(); + return null; + } + + private static boolean annotated(ModifiersTree mods, String type) { + return mods.getAnnotations().stream().map(a -> a.getAnnotationType().toString()) + .anyMatch(name -> name.equals(type) || name.equals("java.lang." + type)); + } + + private static String visibility(ModifiersTree mods) { + return mods.getFlags().contains(Modifier.PROTECTED) ? "protected" : "public"; + } + + private void add(String key, Entry entry) { + declarations.computeIfAbsent(key, ignored -> new ArrayList<>()).add(entry); + } + + private void readType(Path file, String owner, ClassTree cls, boolean implicitPublic, boolean ownerDeprecated, + Set outerVariables) { + String name = owner.isEmpty() ? cls.getSimpleName().toString() : owner + "." + cls.getSimpleName(); + if (name.contains(".internal.") && file.endsWith(name.replace('.', '/') + ".java")) + internalTypes.put(file, cls); + if (WIRE_TYPES.containsKey(name)) { + readWireValues(file, name, cls); + return; + } + boolean restExtension = name.equals("org.apache.ignite.internal.processors.rest.protocols.http.jetty.IgniteRestExtension"); + if ((name.contains(".internal.") && !restExtension) || !exported(cls.getModifiers(), implicitPublic)) + return; + + boolean iface = cls.getKind() == Tree.Kind.INTERFACE || cls.getKind() == Tree.Kind.ANNOTATION_TYPE; + boolean hasParents = cls.getExtendsClause() != null || !cls.getImplementsClause().isEmpty(); + if (hasParents) + typesWithParents.add(name); + Set variables = new HashSet<>(outerVariables); + cls.getTypeParameters().forEach(t -> variables.add(t.getName().toString())); + boolean deprecated = ownerDeprecated || annotated(cls.getModifiers(), "Deprecated"); + String kind = cls.getKind().toString().toLowerCase(Locale.ROOT); + String modifiers = visibility(cls.getModifiers()); + if (cls.getKind() == Tree.Kind.CLASS) { + if (cls.getModifiers().getFlags().contains(Modifier.FINAL)) + modifiers += " final"; + if (cls.getModifiers().getFlags().contains(Modifier.ABSTRACT)) + modifiers += " abstract"; + } + add(name, new Entry(file, owner, "API type " + name, modifiers + " " + kind, false, deprecated)); + + for (Tree member : cls.getMembers()) { + if (member instanceof ClassTree nested) + readType(file, name, nested, iface, deprecated, variables); + else if (member instanceof MethodTree method && (method.getReturnType() != null + || cls.getKind() == Tree.Kind.CLASS && !method.getParameters().isEmpty()) + && cls.getKind() != Tree.Kind.RECORD && exported(method.getModifiers(), iface)) { + String methodName = method.getName().toString(); + boolean constructor = method.getReturnType() == null; + boolean inherited = !constructor && (hasParents || OBJECT_METHODS.contains(methodName) + || cls.getKind() == Tree.Kind.ENUM || annotated(method.getModifiers(), "Override")); + Set methodVars = new HashSet<>(variables); + method.getTypeParameters().forEach(t -> methodVars.add(t.getName().toString())); + List params = new ArrayList<>(); + for (VariableTree param : method.getParameters()) + params.add(type(param.getType(), methodVars)); + String returns = constructor ? "" : type(method.getReturnType(), methodVars); + String access = visibility(method.getModifiers()); + if (method.getModifiers().getFlags().contains(Modifier.STATIC)) + access += " static"; + String signature = returns == null || params.contains(null) ? "?" : + access + " (" + String.join(", ", params) + ")" + (constructor ? "" : " -> " + returns); + String key = name + "." + methodName + "/" + params.size(); + String arity = params.size() + (params.size() == 1 ? " parameter" : " parameters"); + String subject = constructor ? "API constructor " + name : "API method " + name + "." + methodName; + add(key, new Entry(file, name, subject + " (" + arity + ")", signature, + inherited, deprecated || annotated(method.getModifiers(), "Deprecated"))); + } + else if (cls.getKind() == Tree.Kind.ENUM && member instanceof VariableTree entry + && entry.getInitializer() instanceof NewClassTree && entry.getType().toString().equals(cls.getSimpleName().toString())) { + String key = name + "." + entry.getName(); + add(key + " enum", new Entry(file, name, "API enum value " + key, "enum", false, + deprecated || annotated(entry.getModifiers(), "Deprecated"))); + } + else if (member instanceof VariableTree var && exported(var.getModifiers(), iface) + && (iface || var.getModifiers().getFlags().containsAll(Set.of(Modifier.FINAL, Modifier.STATIC)))) { + String key = name + "." + var.getName(); + add(key + " field", new Entry(file, name, "API constant " + key, constantValue(var), false, + deprecated || annotated(var.getModifiers(), "Deprecated"))); + } + } + } + + private void readWireValues(Path path, String name, ClassTree cls) { + Map values = new TreeMap<>(); + wireFiles.put(name, path); + wireValues.put(name, values); + for (Tree member : cls.getMembers()) { + if (!(member instanceof VariableTree var)) + continue; + String value; + if (cls.getKind() == Tree.Kind.ENUM) { + // Enum constants carry their wire ID in the constructor arguments. + if (!(var.getInitializer() instanceof NewClassTree init) + || !var.getType().toString().equals(cls.getSimpleName().toString())) + continue; + Object id = init.getArguments().size() == 1 ? literal(init.getArguments().get(0)) : null; + value = id instanceof Integer n ? n.toString() : null; + } + else { + boolean sqlState = name.endsWith(".SqlStateCode"); + String fieldType = var.getType().toString(); + if (!var.getModifiers().getFlags().containsAll(Set.of(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)) + || (sqlState ? !Set.of("String", "java.lang.String").contains(fieldType) : !fieldType.equals("int"))) + continue; + value = constantValue(var); + } + // An expression can have the same value as a literal in the other revision. + values.put(var.getName().toString(), value); + } + } + + private static JavaContracts read(Path root, Set invalidFiles) throws Exception { + JavaContracts snapshot = new JavaContracts(); + List paths; + try (var walk = Files.walk(root)) { + paths = walk.filter(p -> p.toString().endsWith(".java")).sorted().toList(); + } + if (paths.isEmpty()) + return snapshot; + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector problems = new DiagnosticCollector<>(); + try (var fs = compiler.getStandardFileManager(problems, Locale.ROOT, StandardCharsets.UTF_8)) { + JavacTask task = (JavacTask)compiler.getTask(null, fs, problems, List.of("-proc:none"), null, + fs.getJavaFileObjectsFromPaths(paths)); + Iterable units = task.parse(); + for (var diagnostic : problems.getDiagnostics()) { + if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { + if (diagnostic.getSource() == null) + throw new IllegalStateException("Could not parse the Java snapshots."); + String file = Path.of(diagnostic.getSource().toUri()).getFileName().toString(); + invalidFiles.add(file); + } + } + for (CompilationUnitTree unit : units) { + Path path = root.relativize(Path.of(unit.getSourceFile().toUri())); + if (invalidFiles.contains(path.getFileName().toString())) + continue; + snapshot.units.put(path, unit); + String pkg = unit.getPackageName() == null ? "" : unit.getPackageName().toString(); + for (Tree top : unit.getTypeDecls()) { + if (top instanceof ClassTree cls) + snapshot.readType(path, pkg, cls, false, false, Set.of()); + } + } + } + return snapshot; + } + + private static void emit(Path path, String text) { + // A TSV row must keep its file and message on the same line. + if (path.toString().chars().noneMatch(c -> Character.isISOControl(c) || c == 0x2028 || c == 0x2029)) + System.out.println(path + "\t" + text.replaceAll("[\\p{Cc}\\p{Zl}\\p{Zp}]", " ")); + } + + private static void compareWire(String name, JavaContracts before, JavaContracts after, Set invalid) { + Path path = after.wireFiles.getOrDefault(name, before.wireFiles.get(name)); + if (invalid.contains(path.getFileName().toString())) + return; + Map old = before.wireValues.getOrDefault(name, Map.of()); + Map now = after.wireValues.getOrDefault(name, Map.of()); + Set removed = new TreeSet<>(); + Set added = new TreeSet<>(); + // Unknown expressions may supply a value missing from the other revision's list of literals. + if (now.values().stream().noneMatch(Objects::isNull)) + old.values().stream().filter(v -> v != null && !now.containsValue(v)).forEach(removed::add); + if (old.values().stream().noneMatch(Objects::isNull)) + now.values().stream().filter(v -> v != null && !old.containsValue(v)).forEach(added::add); + String subject = WIRE_TYPES.get(name); + for (var entry : now.entrySet()) { + String from = old.get(entry.getKey()); + if (from != null && entry.getValue() != null && !from.equals(entry.getValue())) { + emit(path, "Changed " + subject + " for " + entry.getKey() + " from " + from + " to " + entry.getValue()); + removed.remove(from); + added.remove(entry.getValue()); + } + } + removed.forEach(v -> emit(path, "Removed " + subject + " " + v)); + added.forEach(v -> emit(path, "Added " + subject + " " + v)); + } + + public static void main(String[] args) throws Exception { + Set invalid = new HashSet<>(); + JavaContracts before = read(Path.of(args[0]).toAbsolutePath(), invalid); + JavaContracts after = read(Path.of(args[1]).toAbsolutePath(), invalid); + Set keys = new TreeSet<>(before.declarations.keySet()); + keys.addAll(after.declarations.keySet()); + for (String key : keys) { + List old = before.declarations.getOrDefault(key, List.of()); + List now = after.declarations.getOrDefault(key, List.of()); + List both = new ArrayList<>(old); + both.addAll(now); + if (both.stream().anyMatch(e -> invalid.contains(e.file.getFileName().toString()) + || e.signature == null || e.couldBeInherited)) + continue; + Entry item = now.isEmpty() ? old.get(0) : now.get(0); + if (old.size() != now.size() && !key.contains("./") && !key.endsWith(" enum") + && (before.typesWithParents.contains(item.owner) || after.typesWithParents.contains(item.owner))) + continue; + if (old.size() < now.size()) + emit(item.file, "Added " + item.subject); + else if (old.size() > now.size()) { + // Previously deprecated APIs may be removed under the project's release rules. + if (old.stream().filter(e -> !e.deprecated).count() > now.size()) + emit(item.file, "Removed " + item.subject); + } + else if (both.stream().noneMatch(e -> e.signature.equals("?"))) { + List from = old.stream().map(Entry::signature).sorted().toList(); + List to = now.stream().map(Entry::signature).sorted().toList(); + if (!from.equals(to)) + emit(item.file, "Changed " + item.subject + " from " + String.join(", ", from) + " to " + String.join(", ", to)); + } + } + before.internalTypes.keySet().removeIf(path -> invalid.contains(path.getFileName().toString())); + after.internalTypes.keySet().removeIf(path -> invalid.contains(path.getFileName().toString())); + RestContracts.compare(before.internalTypes, after.internalTypes, JavaContracts::emit); + Set options = Set.copyOf(Arrays.asList(args).subList(2, args.length)); + before.units.keySet().removeIf(path -> invalid.contains(path.getFileName().toString())); + after.units.keySet().removeIf(path -> invalid.contains(path.getFileName().toString())); + if (!options.contains("--skip-cli-arguments")) + SubcommandArguments.compare(before.units, after.units, JavaContracts::emit); + if (!options.contains("--skip-view-columns")) + SystemViewColumns.compare(before.units, after.units, JavaContracts::emit); + for (var entry : before.internalTypes.entrySet()) { + Path file = entry.getKey(); + ClassTree old = entry.getValue(); + ClassTree now = after.internalTypes.get(file); + if (now == null) + continue; + var output = (java.util.function.Consumer)(text -> emit(file, text)); + String owner = file.toString().replaceFirst("^.*/src/main/java/", "").replace('/', '.').replaceFirst("\\.java$", ""); + CliContracts.compare(file, old, now, output); + if (options.contains(file.toString())) + RegisteredContracts.compare(old, now, output); + FormatContracts.compare(owner, old, now, output); + } + ErrorMapping.compare(before.internalTypes, after.internalTypes, JavaContracts::emit); + Set wireTypes = new TreeSet<>(before.wireValues.keySet()); + wireTypes.addAll(after.wireValues.keySet()); + for (String name : wireTypes) + compareWire(name, before, after, invalid); + } +} diff --git a/.github/public-behavior/README.md b/.github/public-behavior/README.md new file mode 100644 index 0000000000000..c256b93fd9ed1 --- /dev/null +++ b/.github/public-behavior/README.md @@ -0,0 +1,56 @@ + + +# Public behavior changes + +The check compares source declarations at the PR head and its merge base. It reports changes it can identify from those declarations. The [public contract](../../rfcs/IGNITE-29219-public-api-and-compatibility.md) defines what Ignite supports. The [RFC process](../../rfcs/IGNITE-29220-rfc-development-process.md) defines when a proposal and a vote are required. + +## Results + +- **No action.** If the check finds no public contract change, it passes without checking RFC files. An RFC-only PR or a change to diagnostic log wording normally takes this path. +- **RFC needed.** If the check finds a contract change, add or update an RFC file in the PR. If an approved RFC already covers the change, open its file in the target branch and paste the GitHub URL into the PR description. +- **Review the change.** Once the check finds an RFC, it passes with a warning. Checks and the bot comment link to the RFC file and list the declarations or values that changed. The reviewer checks that the RFC covers the changes, reviews compatibility tests and checks any required vote on dev@. + +Use `rfcs/IGNITE--.md` for a new RFC. To update a plan under a new ticket, keep its original filename. If an RFC in the current PR has an invalid name, the check asks the author to fix it. + +The bot replaces its comment when the result changes and confirms when earlier issues are resolved. + +## What the check compares + +| Area | The check reports | The reviewer checks | +| --- | --- | --- | +| Programming APIs and extensions | Java type and method declarations, constructors with parameters, enum members and literal constants in supported packages. This includes the REST extension SPI. It also compares named Windows ODBC exports. | Inherited and generic signatures that need type resolution, other C++ and .NET APIs, callback order and side effects. Check deprecated removals against the release rules. | +| SQL and errors | Keywords in Ignite's native SQL parser, literal names of selected Calcite functions, SQL error codes, SQLState values and direct error-to-SQLState mappings. | Grammar, accepted types, query results and the conditions that cause an error. | +| REST and CLI | The built-in HTTP endpoint and commands. For `control.sh`, the check compares top-level commands, common options, exit codes and arguments of built-in subcommands with known registrations. | HTTP parameters and JSON output, dynamic command registrations, command output and when an error is returned. | +| Configuration | Public Java setting constants and literal defaults. The check also compares selected distributed property registrations and literal defaults, and parts of the shipped .NET XML schemas. | Defaults that depend on other settings, script environment variables, and how Ignite uses the settings. | +| Monitoring | Names in selected metric and system view registrations. For known built-in views with a generated walker, the check reports when an existing column changes position. Java API rules cover JMX declarations and event constants. | Metric meaning and units, custom views, and the events that Ignite emits. | +| Client protocols and stored data | Client operation and feature IDs, existing binary type codes, the binary object version, existing WAL record indices, page store signatures and versions, and snapshot metadata serialization versions. | Message and record layout, version negotiation, and whether an old client or an existing snapshot still works. | +| Distribution and runtime | Maven coordinates, entries in the Ignite BOM, literal NuGet package metadata, the Maven compiler release and the minimum Java version enforced by known launchers. | Supported combinations of JDKs and operating systems, upgrade paths and runtime compatibility. | + +For a subcommand such as `--cache list`, the check compares option names, known types and whether an option is required. It also checks prompts for missing string values and rules such as “choose one of these options.” It counts positional arguments. For a single positional argument it also compares its type and whether it is required. Reviewers check custom validation and the order of multiple positional arguments. + +For a system view, the report names the first existing column that moves and shows its old and new positions. Inserting a column before it counts. Appending a column or renumbering `@Order` while keeping all positions the same passes this rule. Reviewers check column order when the walker or its ordering rules cannot be resolved. + +Each rule compares the specific declarations it understands. For example, changing the numeric index of a WAL record produces a finding. A change to how recovery replays the same record needs review even when the check passes. Reviewers also check transactions, ordering, retries, cancellation and calls to user code. + +## Enabling the check on master + +1. Merge the public contract and process RFCs and the template, then merge the workflows. +2. On a fork PR, add a public method to a supported Java type. Verify that the check fails and names the method. Add a correctly named RFC file or put a direct link to an existing RFC file in the PR description. Verify that the check shows a review warning and that the file opens from the report. +3. Require trusted review for the workflow and checker files. Add `Public behavior changes` to the required checks for `master` in [`.asf.yaml`](../../.asf.yaml). Remove that status from the required checks to stop blocking merges. + +To run the tests locally, use `python3 -m unittest discover -s tests` from `.github/public-behavior` with JDK 17 or later on PATH. diff --git a/.github/public-behavior/RegisteredContracts.java b/.github/public-behavior/RegisteredContracts.java new file mode 100644 index 0000000000000..973be8f5ac48c --- /dev/null +++ b/.github/public-behavior/RegisteredContracts.java @@ -0,0 +1,273 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import com.sun.source.util.TreeScanner; +import java.util.*; +import java.util.function.Consumer; +import javax.lang.model.element.Modifier; + +/** Compare registrations whose public values are explicit in both revisions. */ +class RegisteredContracts extends TreeScanner { + private record Slot(String kind, String binding) {} + private final Map values = new HashMap<>(); + private final Map fields = new HashMap<>(); + private Set shadowed = new HashSet<>(); + private int registrationCalls; + private boolean allSettingsKnown = true; + private final Map defaults = new HashMap<>(); + private Map variableTypes = new HashMap<>(); + private static final Set PROPERTY_FACTORIES = Set.of("detachedBooleanProperty", + "detachedLongProperty", "detachedIntegerProperty", "detachedDoubleProperty"); + private static final Set METRIC_FACTORIES = Set.of("longMetric", "longAdderMetric", "intMetric", + "doubleMetric", "booleanMetric", "objectMetric", "hitRateMetric", "histogram"); + + static void compare(ClassTree before, ClassTree after, Consumer output) { + if (before == null || after == null) + return; + if (before.getSimpleName().contentEquals("SqlKeyword")) { + compareKeywords(before, after, output); + return; + } + var old = new RegisteredContracts(before); + var now = new RegisteredContracts(after); + Set messages = new TreeSet<>(); + old.values.forEach((slot, from) -> { + String to = now.values.get(slot); + if (from != null && to != null && !from.equals(to) + && !(old.contains(slot.kind(), to) && now.contains(slot.kind(), from))) + messages.add("Changed " + slot.kind() + " from " + from + " to " + to); + }); + // A private property may already exist when someone exposes it through the dispatcher. + // Require the same dispatcher calls and the same field definition on both sides. + if (old.allSettingsKnown && now.allSettingsKnown && old.registrationCalls > 0 + && old.registrationCalls == now.registrationCalls) { + for (String field : old.fields.keySet()) { + String key = old.propertyKey(field); + if (key == null || !key.equals(now.propertyKey(field))) + continue; + boolean wasRegistered = old.contains("distributed setting name", key); + boolean isRegistered = now.contains("distributed setting name", key); + if (isRegistered != wasRegistered) + messages.add((isRegistered ? "Added" : "Removed") + " distributed setting registration for " + key); + } + } + messages.forEach(output); + } + + private record Keywords(Set names, List loader) {} + + private static void compareKeywords(ClassTree before, ClassTree after, Consumer output) { + Keywords old = keywords(before); + Keywords now = keywords(after); + if (old == null || now == null || !old.loader.equals(now.loader)) + return; + old.names.stream().filter(name -> !now.names.contains(name)) + .forEach(name -> output.accept("Removed Ignite SQL parser keyword " + name)); + now.names.stream().filter(name -> !old.names.contains(name)) + .forEach(name -> output.accept("Added Ignite SQL parser keyword " + name)); + } + + private static Keywords keywords(ClassTree cls) { + Set names = new TreeSet<>(); + List loader = new ArrayList<>(); + boolean readsStringFields = false; + boolean checksMembership = false; + for (Tree member : cls.getMembers()) { + if (member instanceof VariableTree field && Set.of("String", "java.lang.String").contains(field.getType().toString())) { + if (!field.getModifiers().getFlags().containsAll(Set.of(Modifier.STATIC, Modifier.FINAL)) + || !(field.getInitializer() instanceof LiteralTree literal) || !(literal.getValue() instanceof String value)) + return null; + // Unquoted identifiers in the native SQL parser use these uppercase spellings. + if (value.matches("[A-Z_][A-Z0-9_]*")) + names.add(value); + } + else { + loader.add(member.toString()); + if (member instanceof BlockTree block && block.isStatic() && block.getStatements().size() == 2 + && block.getStatements().get(0).toString().equals("KEYWORDS = new HashSet<>();") + && block.getStatements().get(1) instanceof TryTree attempt && attempt.getFinallyBlock() == null + && attempt.getBlock().getStatements().size() == 1 + && attempt.getBlock().getStatements().get(0) instanceof EnhancedForLoopTree loop) { + readsStringFields = collectsKeywordValues(loop); + } + if (member instanceof MethodTree method && method.getName().contentEquals("isKeyword") + && method.getParameters().size() == 1 && method.getBody() != null + && method.getBody().getStatements().size() == 1 + && method.getBody().getStatements().get(0) instanceof ReturnTree ret) + checksMembership = ("KEYWORDS.contains(" + method.getParameters().get(0).getName() + ")") + .equals(ret.getExpression().toString()); + } + } + return readsStringFields && checksMembership ? new Keywords(names, loader) : null; + } + + private static boolean collectsKeywordValues(EnhancedForLoopTree loop) { + if (!loop.getExpression().toString().equals("SqlKeyword.class.getDeclaredFields()") + || !(loop.getStatement() instanceof BlockTree body) || body.getStatements().size() != 1 + || !(body.getStatements().get(0) instanceof IfTree guard) || guard.getElseStatement() != null + || !(guard.getThenStatement() instanceof BlockTree selected) || selected.getStatements().size() != 2 + || !(selected.getStatements().get(0) instanceof VariableTree value) || value.getInitializer() == null) + return false; + String field = loop.getVariable().getName().toString(); + return guard.getCondition().toString().equals("(Objects.equals(String.class, " + field + ".getType()))") + && value.getInitializer().toString().equals("(String)" + field + ".get(null)") + && selected.getStatements().get(1).toString().equals("KEYWORDS.add(" + value.getName() + ");"); + } + + private boolean contains(String kind, String value) { + return values.entrySet().stream().anyMatch(e -> e.getKey().kind().equals(kind) && value.equals(e.getValue())); + } + + private void record(String kind, String binding, String value) { + if (value == null) + return; + Slot slot = new Slot(kind, binding); + if (values.containsKey(slot) && !value.equals(values.get(slot))) + values.put(slot, null); + else + values.put(slot, value); + } + + private RegisteredContracts(ClassTree cls) { + for (Tree member : cls.getMembers()) { + if (member instanceof VariableTree field) { + fields.put(field.getName().toString(), field); + if (field.getType() != null) + variableTypes.put(field.getName().toString(), field.getType().toString()); + } + } + if (cls.getSimpleName().contentEquals("IgniteOwnSqlOperatorTable")) { + for (VariableTree field : fields.values()) { + if (field.getModifiers().getFlags().containsAll(Set.of(Modifier.PUBLIC, Modifier.STATIC)) + && field.getInitializer() instanceof NewClassTree init && init.getIdentifier().toString().equals("SqlFunction") + && !init.getArguments().isEmpty()) { + String name = text(init.getArguments().get(0)); + if (name != null && !name.startsWith("$")) + record("Calcite SQL function name", field.getName().toString(), name.toUpperCase(Locale.ROOT)); + } + } + } + scan(cls, null); + defaults.forEach((field, value) -> { + String key = values.get(new Slot("distributed setting name", field)); + if (key != null && !value.isEmpty()) + record("default for distributed setting " + key, key, value); + }); + } + + private String text(ExpressionTree expr) { + if (expr instanceof IdentifierTree id) { + VariableTree field = fields.get(id.getName().toString()); + if (field == null || shadowed.contains(id.getName().toString()) + || !field.getModifiers().getFlags().containsAll(Set.of(Modifier.FINAL, Modifier.STATIC))) + return null; + expr = field.getInitializer(); + } + return expr instanceof LiteralTree lit && lit.getValue() instanceof String s ? s : null; + } + + private String propertyKey(String id) { + VariableTree field = fields.get(id); + if (field == null || !field.getModifiers().getFlags().contains(Modifier.PRIVATE) + || !(field.getInitializer() instanceof MethodInvocationTree factory) + || !PROPERTY_FACTORIES.contains(method(factory)) || factory.getArguments().isEmpty()) + return null; + return text(factory.getArguments().get(0)); + } + + private static String method(MethodInvocationTree call) { + return call.getMethodSelect() instanceof MemberSelectTree member + ? member.getIdentifier().toString() : call.getMethodSelect().toString(); + } + + @Override public Void visitMethodInvocation(MethodInvocationTree call, Void unused) { + String name = method(call); + var args = call.getArguments(); + if (call.getMethodSelect() instanceof MemberSelectTree member) { + String receiver = member.getExpression().toString(); + if (Set.of("registerProperty", "registerProperties").contains(name) + && "DistributedPropertyDispatcher".equals(variableTypes.get(receiver))) { + registrationCalls++; + for (ExpressionTree arg : args) { + String id = arg.toString(); + String key = shadowed.contains(id) ? null : propertyKey(id); + if (key == null) { + allSettingsKnown = false; + continue; + } + record("distributed setting name", id, key); + var factory = (MethodInvocationTree)fields.get(id).getInitializer(); + String type = method(factory).replace("detached", "").replace("Property", ""); + record("type of distributed setting " + key, key, type); + } + } + else if (member.getExpression() instanceof MethodInvocationTree registry && method(registry).equals("systemView") + && Set.of("registerView", "registerFiltrableView", "registerInnerCollectionView").contains(name) + && args.size() >= 3 && args.get(2) instanceof NewClassTree walker) { + record("system view name", walker.getIdentifier().toString(), text(args.get(0))); + } + } + if (name.equals("setDefaultValue") && args.size() == 3 && args.get(0) instanceof IdentifierTree id + && args.get(1) instanceof LiteralTree literal && literal.getValue() != null) { + String value = literal.getValue().toString(); + String field = id.getName().toString(); + defaults.merge(field, value, (a, b) -> a.equals(b) ? a : ""); + } + return super.visitMethodInvocation(call, unused); + } + + @Override public Void visitAssignment(AssignmentTree assignment, Void unused) { + String field = assignment.getVariable().toString(); + if (field.startsWith("this.")) + field = field.substring(5); + else if (shadowed.contains(field)) + return super.visitAssignment(assignment, unused); + if (fields.containsKey(field) && assignment.getExpression() instanceof MethodInvocationTree call + && METRIC_FACTORIES.contains(method(call)) && call.getMethodSelect() instanceof MemberSelectTree member + && "MetricRegistryImpl".equals(variableTypes.get(member.getExpression().toString())) + && !call.getArguments().isEmpty()) + record("metric name", field, text(call.getArguments().get(0))); + return super.visitAssignment(assignment, unused); + } + + @Override public Void visitMethod(MethodTree method, Void unused) { + var outerTypes = variableTypes; + var outerShadowed = shadowed; + variableTypes = new HashMap<>(outerTypes); + shadowed = new HashSet<>(outerShadowed); + super.visitMethod(method, unused); + variableTypes = outerTypes; + shadowed = outerShadowed; + return null; + } + + @Override public Void visitVariable(VariableTree var, Void unused) { + String id = var.getName().toString(); + if (var.getType() != null && fields.get(id) != var) { + variableTypes.put(id, var.getType().toString()); + if (fields.containsKey(id)) + shadowed.add(id); + } + if (var.getType() != null && var.getType().toString().equals("MetricRegistryImpl") + && var.getInitializer() instanceof MethodInvocationTree call && call.getMethodSelect() instanceof MemberSelectTree member + && "GridMetricManager".equals(variableTypes.get(member.getExpression().toString())) + && method(call).equals("registry") && call.getArguments().size() == 1) + record("metric registry name", var.getName().toString(), text(call.getArguments().get(0))); + return super.visitVariable(var, unused); + } +} diff --git a/.github/public-behavior/RestContracts.java b/.github/public-behavior/RestContracts.java new file mode 100644 index 0000000000000..64ec8dedf6c91 --- /dev/null +++ b/.github/public-behavior/RestContracts.java @@ -0,0 +1,246 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import java.nio.file.Path; +import java.util.*; +import java.util.function.BiConsumer; +import javax.lang.model.element.Modifier; + +/** Compares the cmd values accepted by the HTTP REST handler. */ +class RestContracts { + private static final Path COMMANDS = Path.of("modules/core/src/main/java/org/apache/ignite/internal/" + + "processors/rest/GridRestCommand.java"); + private static final Path HANDLER = Path.of("modules/rest-http/src/main/java/org/apache/ignite/internal/" + + "processors/rest/protocols/http/jetty/GridJettyRestHandler.java"); + private static final Path PROTOCOL = HANDLER.resolveSibling("GridJettyRestProtocol.java"); + + private static String mapping(ExpressionTree expr, String commandPath) { + if (expr instanceof LiteralTree literal && literal.getValue() instanceof String value) + return value; + if (Set.of("IGNITE_CMD_PATH", "GridJettyRestHandler.IGNITE_CMD_PATH").contains(expr.toString())) + return commandPath; + if (expr instanceof BinaryTree concat && concat.getKind() == Tree.Kind.PLUS) { + String prefix = mapping(concat.getLeftOperand(), commandPath); + String suffix = mapping(concat.getRightOperand(), commandPath); + return prefix == null || suffix == null ? null : prefix + suffix; + } + return null; + } + + private record Endpoint(String path, String context, String registration) {} + + private static Endpoint endpoint(Map files) { + ClassTree protocol = files.get(PROTOCOL); + ClassTree handler = files.get(HANDLER); + if (protocol == null || handler == null) + return null; + // An unqualified reference can otherwise resolve to a field on the protocol itself. + if (protocol.getMembers().stream().anyMatch(member -> + member instanceof VariableTree field && field.getName().contentEquals("IGNITE_CMD_PATH"))) + return null; + boolean hasRestHandler = protocol.getMembers().stream().anyMatch(member -> + member instanceof VariableTree field && field.getName().contentEquals("jettyHnd") + && field.getType().toString().equals("GridJettyRestHandler")); + if (!hasRestHandler) + return null; + String commandPath = null; + for (Tree member : handler.getMembers()) { + if (member instanceof VariableTree field && field.getName().contentEquals("IGNITE_CMD_PATH") + && field.getModifiers().getFlags().containsAll(Set.of(Modifier.STATIC, Modifier.FINAL)) + && field.getInitializer() instanceof LiteralTree literal && literal.getValue() instanceof String value) + commandPath = value; + } + for (Tree member : protocol.getMembers()) { + if (!(member instanceof MethodTree method) || !method.getName().contentEquals("loadJettyConfiguration") + || method.getBody() == null) + continue; + String context = null; + String path = null; + String registration = null; + boolean registered = false; + boolean mainContext = false; + for (StatementTree stmt : method.getBody().getStatements()) { + if (stmt instanceof VariableTree var && var.getName().contentEquals("IGNITE_CMD_PATH")) + return null; + if (stmt instanceof VariableTree variable && variable.getName().contentEquals("mainCtx") + && variable.getInitializer() instanceof NewClassTree init + && init.getIdentifier().toString().equals("ServletContextHandler")) { + mainContext = true; + continue; + } + if (!(stmt instanceof ExpressionStatementTree expr) || !(expr.getExpression() instanceof MethodInvocationTree call)) { + if (stmt.toString().contains("mainCtx")) + return null; + continue; + } + var args = call.getArguments(); + switch (call.getMethodSelect().toString()) { + case "mainCtx.setContextPath" -> { + if (context != null || args.size() != 1 || !(args.get(0) instanceof LiteralTree literal) + || !(literal.getValue() instanceof String value)) + return null; + context = value; + } + case "mainCtx.addServlet" -> { + if (args.size() != 2 || !(args.get(0) instanceof NewClassTree holder) + || !holder.getIdentifier().toString().equals("ServletHolder") || holder.getArguments().size() != 1) + return null; + var servlet = holder.getArguments().get(0); + if (servlet instanceof NewClassTree other && other.getIdentifier().toString().equals("WelcomeHandler")) + continue; + if (path != null || !servlet.toString().equals("jettyHnd")) + return null; + path = mapping(args.get(1), commandPath); + if (path == null) + return null; + registration = args.get(1).toString(); + } + case "hnds.addHandler" -> registered |= args.size() == 1 && args.get(0).toString().equals("mainCtx"); + default -> { + if (call.toString().contains("mainCtx")) + return null; + } + } + } + if (mainContext && registered && context != null && context.startsWith("/") && path != null && path.startsWith("/")) + return new Endpoint((context.equals("/") ? "" : context) + path, context, registration); + } + return null; + } + + private static Set caseNames(SwitchTree dispatch) { + Set commands = new HashSet<>(); + Set pending = new HashSet<>(); + boolean rejectsUnknown = false; + for (CaseTree branch : dispatch.getCases()) { + List body = branch.getStatements(); + if (body == null) + return null; + if (body.size() == 1 && body.get(0) instanceof BlockTree block) + body = block.getStatements(); + if (branch.getExpressions().isEmpty()) { + rejectsUnknown = body.size() == 1 && body.get(0) instanceof ThrowTree; + pending.clear(); + continue; + } + for (ExpressionTree label : branch.getExpressions()) { + if (!(label instanceof IdentifierTree command)) + return null; + pending.add(command.getName().toString()); + } + // Several cmd values can share a handler. An empty case takes the next case's body. + if (body.isEmpty()) + continue; + StatementTree last = body.get(body.size() - 1); + if (last instanceof ReturnTree ret && (ret.getExpression() == null + || ret.getExpression().getKind() == Tree.Kind.NULL_LITERAL)) + return null; + if (last instanceof BreakTree || last instanceof ReturnTree) + commands.addAll(pending); + else if (!(last instanceof ThrowTree)) + return null; + pending.clear(); + } + return rejectsUnknown ? commands : null; + } + + // Some GridRestCommand values have no HTTP handler. Read the switch that builds REST requests. + private static Set handledCommands(ClassTree handler) { + for (Tree member : handler.getMembers()) { + if (!(member instanceof MethodTree method) || !method.getName().contentEquals("createRequest") + || method.getBody() == null) + continue; + for (StatementTree statement : method.getBody().getStatements()) { + if (statement instanceof VariableTree var && var.getInitializer() == null) + continue; + if (!(statement instanceof SwitchTree dispatch)) + return null; + ExpressionTree selector = dispatch.getExpression(); + while (selector instanceof ParenthesizedTree parens) + selector = parens.getExpression(); + if (!(selector instanceof IdentifierTree id) || method.getParameters().stream().noneMatch(param -> + param.getName().contentEquals(id.getName()) && param.getType().toString().equals("GridRestCommand"))) + return null; + return caseNames(dispatch); + } + } + return null; + } + + private record Snapshot(Set declared, Map handled, List lookup) {} + + private static Snapshot read(Map files) { + ClassTree commands = files.get(COMMANDS); + ClassTree handler = files.get(HANDLER); + if (commands == null || handler == null || commands.getKind() != Tree.Kind.ENUM) + return null; + Set cases = handledCommands(handler); + if (cases == null) + return null; + Set declared = new HashSet<>(); + Map handled = new TreeMap<>(); + List lookup = new ArrayList<>(); + for (Tree member : commands.getMembers()) { + if (!(member instanceof VariableTree var) || !(var.getInitializer() instanceof NewClassTree init) + || !var.getType().toString().equals(commands.getSimpleName().toString())) { + lookup.add(member.toString()); + continue; + } + if (init.getArguments().size() != 1 || !(init.getArguments().get(0) instanceof LiteralTree literal) + || !(literal.getValue() instanceof String key)) + return null; + if (!declared.add(key)) + return null; + if (cases.remove(var.getName().toString())) { + boolean deprecated = var.getModifiers().getAnnotations().stream().anyMatch(annotation -> + Set.of("Deprecated", "java.lang.Deprecated").contains(annotation.getAnnotationType().toString())); + // The HTTP lookup converts the cmd parameter to lowercase before looking up the enum key. + if (key.equals(key.toLowerCase(Locale.ROOT))) + handled.put(key, deprecated); + } + } + for (Tree member : handler.getMembers()) { + if (member instanceof MethodTree method && method.getName().contentEquals("command")) + lookup.add(method.toString()); + } + return cases.isEmpty() ? new Snapshot(declared, handled, lookup) : null; + } + + static void compare(Map before, Map after, BiConsumer emit) { + Endpoint previous = endpoint(before); + Endpoint current = endpoint(after); + if (previous != null && current != null && !previous.path.equals(current.path)) { + boolean sameRegistration = previous.registration.equals(current.registration) && previous.context.equals(current.context); + emit.accept(sameRegistration ? HANDLER : PROTOCOL, + "Changed REST endpoint mapping from " + previous.path + " to " + current.path); + } + Snapshot old = read(before); + Snapshot now = read(after); + // A change in the lookup can introduce an alias that keeps the old cmd working. + if (old == null || now == null || !old.lookup.equals(now.lookup)) + return; + old.handled.forEach((key, deprecated) -> { + if (!deprecated && !now.handled.containsKey(key)) + emit.accept(now.declared.contains(key) ? HANDLER : COMMANDS, "Removed REST command cmd=" + key); + }); + for (String key : now.handled.keySet()) { + if (!old.handled.containsKey(key)) + emit.accept(old.declared.contains(key) ? HANDLER : COMMANDS, "Added REST command cmd=" + key); + } + } +} diff --git a/.github/public-behavior/SubcommandArguments.java b/.github/public-behavior/SubcommandArguments.java new file mode 100644 index 0000000000000..92d364e515d51 --- /dev/null +++ b/.github/public-behavior/SubcommandArguments.java @@ -0,0 +1,375 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import java.nio.file.Path; +import java.util.*; +import java.util.function.BiConsumer; + +/** Arguments of executable commands reached through the built-in control.sh registries. */ +class SubcommandArguments { + private static final String MANAGEMENT = "org.apache.ignite.internal.management."; + private static final String API = MANAGEMENT + "api."; + private static final String DTO = "org.apache.ignite.internal.dto.IgniteDataTransferObject"; + private static final Set EXECUTABLE = Set.of(API + "ComputeCommand", API + "NativeCommand", + API + "BeforeNodeStartCommand", API + "HelpCommand", API + "OfflineCommand"); + + private record Source(Path path, String pkg, Map imports, ClassTree cls) { + String resolve(Tree type) { + if (type instanceof ParameterizedTypeTree generic) + return resolve(generic.getType()); + if (type == null) + return ""; + String name = type.toString(); + return name.contains(".") ? name : imports.getOrDefault(name, pkg + "." + name); + } + + boolean annotated(ModifiersTree mods, String name) { + return mods.getAnnotations().stream().anyMatch(a -> resolve(a.getAnnotationType()).equals(API + name)); + } + } + + private record Argument(Path path, String type, Boolean required, Boolean sensitive, boolean deprecated) {} + private record Group(Boolean optional, Boolean exclusive) {} + private record Binding(Source dto, Path method) {} + private record Arguments(Path command, Path binding, Path dto, Map named, + List positional, Map, Group> groups) { + Group rule(List options) { + Group group = groups.get(options); + if (group != null) + return group; + // Separate optional options accept both an empty set and more than one value. + return options.stream().allMatch(key -> named.containsKey(key) && Boolean.FALSE.equals(named.get(key).required)) + ? new Group(true, false) : null; + } + } + + static void compare(Map before, Map after, + BiConsumer emit) { + Map old = commands(before); + commands(after).forEach((name, now) -> { + Arguments was = old.get(name); + if (was == null || !was.command.equals(now.command)) + return; + // A command can select a different existing DTO without editing either DTO. + boolean switched = !was.dto.equals(now.dto); + BiConsumer report = (path, fact) -> { + if (changed(path, before, after)) + emit.accept(path, fact); + else if (changed(now.dto, before, after)) + emit.accept(now.dto, fact); + else if (changed(now.binding, before, after)) + emit.accept(now.binding, fact); + else if (changed(now.command, before, after)) + emit.accept(now.command, fact); + }; + for (var entry : was.named.entrySet()) { + if (!entry.getValue().deprecated && !now.named.containsKey(entry.getKey())) + report.accept(switched ? now.command : entry.getValue().path, "Removed CLI option " + name + " " + entry.getKey()); + } + now.named.forEach((option, arg) -> { + Path path = switched ? now.command : arg.path; + String subject = "CLI option " + name + " " + option; + Argument prior = was.named.get(option); + if (prior == null) + report.accept(path, "Added " + subject); + else { + compareArgument(prior, arg, subject, path, report); + if (option.startsWith("--") && "string".equals(prior.type) && "string".equals(arg.type) + && prior.sensitive != null && arg.sensitive != null && !arg.sensitive.equals(prior.sensitive)) + report.accept(path, subject + (arg.sensitive ? " now prompts for a missing value on an interactive console" + : " now requires a value on the command line")); + } + }); + int oldCount = was.positional.size(); + int count = now.positional.size(); + if (count > oldCount || was.positional.stream().filter(a -> !a.deprecated).count() > count) { + Map counts = new TreeMap<>(); + now.positional.forEach(arg -> counts.merge(arg.path, 1, Integer::sum)); + was.positional.forEach(arg -> counts.merge(arg.path, -1, Integer::sum)); + Path origin = counts.entrySet().stream().filter(e -> e.getValue() != 0 && changed(e.getKey(), before, after)) + .map(Map.Entry::getKey).findFirst().orElse(now.dto); + report.accept(switched ? now.command : origin, + "Changed positional argument count for " + name + " from " + oldCount + " to " + count); + } + else if (oldCount == 1 && count == 1) + compareArgument(was.positional.get(0), now.positional.get(0), "CLI positional argument for " + name, + switched ? now.command : now.positional.get(0).path, report); + Set> allGroups = new LinkedHashSet<>(was.groups.keySet()); + allGroups.addAll(now.groups.keySet()); + for (List options : allGroups) { + Group oldGroup = was.rule(options); + Group group = now.rule(options); + if (group == null || oldGroup == null) + continue; + Path origin = switched ? now.command : now.dto; + String names = String.join(", ", options); + if (group.optional != null && oldGroup.optional != null && !group.optional.equals(oldGroup.optional)) + report.accept(origin, group.optional ? name + " now allows omitting " + names + : name + " now requires at least one of " + names); + if (group.exclusive != null && oldGroup.exclusive != null && !group.exclusive.equals(oldGroup.exclusive)) + report.accept(origin, group.exclusive ? name + " now accepts at most one of " + names + : name + " now allows combining " + names); + } + }); + } + + private static boolean changed(Path path, Map before, Map after) { + return before.get(path) == null || after.get(path) == null || !before.get(path).toString().equals(after.get(path).toString()); + } + + private static void compareArgument(Argument old, Argument now, String subject, Path path, BiConsumer emit) { + if (old.type != null && now.type != null && !old.type.equals(now.type)) + emit.accept(path, "Changed " + subject + " type from " + old.type + " to " + now.type); + if (old.required != null && now.required != null && !old.required.equals(now.required)) + emit.accept(path, subject + " is now " + (now.required ? "required" : "optional")); + } + + private static Map commands(Map units) { + if (units.keySet().stream().noneMatch(path -> path.endsWith("management/IgniteCommandRegistry.java"))) + return Map.of(); + Map types = new HashMap<>(); + units.forEach((path, unit) -> { + if (unit.getPackageName() == null) + return; + String pkg = unit.getPackageName().toString(); + Map imports = new HashMap<>(); + for (ImportTree item : unit.getImports()) { + String name = item.getQualifiedIdentifier().toString(); + // Without attribution a wildcard can refer to a different annotation, DTO or command. + if (name.endsWith(".*") && !item.isStatic()) + return; + if (!item.isStatic()) + imports.put(name.substring(name.lastIndexOf('.') + 1), name); + } + for (Tree member : unit.getTypeDecls()) { + if (member instanceof ClassTree cls && path.getFileName().toString().equals(cls.getSimpleName() + ".java")) { + String name = pkg + "." + cls.getSimpleName(); + for (Tree child : cls.getMembers()) { + if (child instanceof ClassTree nested) { + String nestedName = name + "." + nested.getSimpleName(); + imports.put(nested.getSimpleName().toString(), nestedName); + types.put(nestedName, new Source(path, pkg, imports, nested)); + } + } + types.put(name, new Source(path, pkg, imports, cls)); + } + } + }); + Map result = new TreeMap<>(); + Source root = types.get(MANAGEMENT + "IgniteCommandRegistry"); + if (root != null) + visitRegistry(root, "", types, result, new HashSet<>()); + return result; + } + + private static void visitRegistry(Source registry, String parent, Map types, + Map result, Set visiting) { + if (!registry.resolve(registry.cls.getExtendsClause()).equals(API + "CommandRegistryImpl") || !visiting.add(registry.path)) + return; + MethodTree constructor = null; + for (Tree member : registry.cls.getMembers()) { + if (!(member instanceof MethodTree method)) + continue; + if (method.getName().contentEquals("command")) + return; + if (method.getName().contentEquals("register") && (method.getBody() == null || method.getParameters().size() != 1 + || !method.getBody().getStatements().toString().equals("super.register(" + method.getParameters().get(0).getName() + ");"))) + return; + if (method.getReturnType() == null && method.getParameters().isEmpty()) + constructor = method; + } + if (constructor == null || constructor.getBody() == null || constructor.getBody().getStatements().isEmpty() + || !(constructor.getBody().getStatements().get(0) instanceof ExpressionStatementTree first) + || !(first.getExpression() instanceof MethodInvocationTree registration) || !registration.getMethodSelect().toString().equals("super")) + return; + String prefix = parent.isEmpty() ? "" : stem(registry.cls.getSimpleName().toString()); + boolean dashes = parent.isEmpty() || registry.annotated(registry.cls.getModifiers(), "CliSubcommandsWithPrefix"); + for (ExpressionTree arg : registration.getArguments()) { + if (!(arg instanceof NewClassTree init) || init.getClassBody() != null) + continue; + Source child = types.get(registry.resolve(init.getIdentifier())); + if (child == null) + continue; + String key = stem(child.cls.getSimpleName().toString()); + if (key == null || prefix == null || !key.startsWith(prefix) || key.length() == prefix.length()) + continue; + String word = formatted(key.substring(prefix.length()), dashes ? '-' : '_'); + String name = (parent.isEmpty() ? "" : parent + " ") + (dashes ? "--" : "") + word; + if (!parent.isEmpty()) { + Binding binding = argumentClass(child, types); + if (binding != null) { + Arguments options = arguments(child, binding, types); + if (options != null) + result.put(name, options); + } + } + visitRegistry(child, name, types, result, visiting); + } + visiting.remove(registry.path); + } + + private static String stem(String name) { + return name.matches("[A-Za-z][A-Za-z0-9]*Command") ? name.substring(0, name.length() - "Command".length()) : null; + } + + private static Binding argumentClass(Source command, Map types) { + boolean executable = false; + Binding binding = null; + Set seen = new HashSet<>(); + for (Source source = command; source != null && seen.add(source.cls); source = types.get(source.resolve(source.cls.getExtendsClause()))) { + executable |= source.cls.getImplementsClause().stream().map(source::resolve).anyMatch(EXECUTABLE::contains); + for (Tree member : source.cls.getMembers()) { + if (binding != null || !(member instanceof MethodTree method) || !method.getName().contentEquals("argClass") + || !method.getParameters().isEmpty()) + continue; + if (method.getBody() == null || method.getBody().getStatements().size() != 1 + || !(method.getBody().getStatements().get(0) instanceof ReturnTree ret) + || !(ret.getExpression() instanceof MemberSelectTree type) || !type.getIdentifier().contentEquals("class")) + return null; + Source dto = types.get(source.resolve(type.getExpression())); + if (dto == null) + return null; + binding = new Binding(dto, source.path); + } + if (executable && binding != null) + return binding; + } + return null; + } + + private static Arguments arguments(Source command, Binding binding, Map types) { + Source dto = binding.dto; + Set grouped = new HashSet<>(); + Map, Group> restrictions = new LinkedHashMap<>(); + for (AnnotationTree annotation : dto.cls.getModifiers().getAnnotations()) { + String type = dto.resolve(annotation.getAnnotationType()); + if (type.equals(API + "ArgumentGroupsHolder")) + return null; + if (type.equals(API + "ArgumentGroup")) { + ExpressionTree value = attribute(annotation, "value"); + if (value == null) + return null; + List members = value instanceof NewArrayTree array ? array.getInitializers() : List.of(value); + if (members == null) + return null; + List fields = new ArrayList<>(); + for (ExpressionTree entry : members) { + if (!(entry instanceof LiteralTree lit) || !(lit.getValue() instanceof String name) || !grouped.add(name)) + return null; + fields.add(name); + } + restrictions.put(fields, new Group(flag(annotation, "optional"), flag(annotation, "onlyOneOf"))); + } + } + Map named = new TreeMap<>(); + Map externalNames = new HashMap<>(); + List positional = new ArrayList<>(); + Set seen = new HashSet<>(); + for (Source source = dto; source != null && seen.add(source.cls); source = types.get(source.resolve(source.cls.getExtendsClause()))) { + for (Tree member : source.cls.getMembers()) { + if (!(member instanceof VariableTree field)) + continue; + for (AnnotationTree arg : field.getModifiers().getAnnotations()) { + if (!source.resolve(arg.getAnnotationType()).equals(API + "Argument")) + continue; + String id = field.getName().toString(); + Boolean optional = flag(arg, "optional"); + Boolean required = optional == null || grouped.contains(id) ? null : !optional; + ExpressionTree description = attribute(arg, "description"); + String help = description instanceof LiteralTree lit && lit.getValue() instanceof String text + ? text.strip().toLowerCase(Locale.ROOT) : ""; + boolean deprecated = field.getModifiers().getAnnotations().stream().anyMatch(a -> + Set.of("Deprecated", "java.lang.Deprecated").contains(a.getAnnotationType().toString())) + || help.startsWith("deprecated.") + || id.equals("nodeId") && help.endsWith("(deprecated. use --node-ids or --all-nodes instead)"); + Argument option = new Argument(source.path, inputType(field.getType(), source), required, flag(arg, "sensitive"), deprecated); + if (source.annotated(field.getModifiers(), "Positional")) + positional.add(option); + else { + Boolean noPrefix = flag(arg, "withoutPrefix"); + Boolean javaStyle = flag(arg, "javaStyleName"); + if (noPrefix == null || javaStyle == null) + return null; + String name = (noPrefix ? "" : "--") + (javaStyle ? id.toLowerCase(Locale.ROOT) : formatted(id, '-')); + externalNames.put(id, name); + if (named.put(name, option) != null) + return null; + } + } + } + if (source.resolve(source.cls.getExtendsClause()).equals(DTO)) { + Map, Group> groups = new LinkedHashMap<>(); + restrictions.forEach((ids, rule) -> { + if (ids.size() >= 2 && externalNames.keySet().containsAll(ids)) { + List options = ids.stream().map(externalNames::get).sorted().toList(); + groups.put(options, rule); + } + }); + return new Arguments(command.path, binding.method, dto.path, named, positional, groups); + } + } + return null; + } + + private static String formatted(String id, char delimiter) { + StringBuilder name = new StringBuilder(); + for (int i = 0; i < id.length(); i++) { + if (i > 0 && !Character.isLowerCase(id.charAt(i))) + name.append(delimiter); + name.append(Character.toLowerCase(id.charAt(i))); + } + return name.toString(); + } + + private static ExpressionTree attribute(AnnotationTree annotation, String name) { + for (ExpressionTree arg : annotation.getArguments()) { + if (arg instanceof AssignmentTree assignment && assignment.getVariable().toString().equals(name)) + return assignment.getExpression(); + } + return null; + } + + private static Boolean flag(AnnotationTree annotation, String name) { + ExpressionTree expr = attribute(annotation, name); + if (expr == null) + return false; + return expr instanceof LiteralTree lit && lit.getValue() instanceof Boolean b ? b : null; + } + + private static String inputType(Tree type, Source source) { + if (type instanceof ArrayTypeTree array) { + if (array.getType().toString().equals("char")) + return "string"; + String element = inputType(array.getType(), source); + return element == null ? null : element + " list"; + } + String raw = type.toString(); + String name = source.imports.getOrDefault(raw, raw); + return switch (name) { + case "boolean", "Boolean", "java.lang.Boolean" -> "boolean"; + case "int", "Integer", "java.lang.Integer" -> "int"; + case "long", "Long", "java.lang.Long" -> "long"; + case "float", "Float", "java.lang.Float" -> "float"; + case "double", "Double", "java.lang.Double" -> "double"; + case "String", "java.lang.String" -> "string"; + case "java.util.UUID" -> "UUID"; + case "org.apache.ignite.lang.IgniteUuid" -> "IgniteUuid"; + default -> null; + }; + } +} diff --git a/.github/public-behavior/SystemViewColumns.java b/.github/public-behavior/SystemViewColumns.java new file mode 100644 index 0000000000000..84c8e4e52b20e --- /dev/null +++ b/.github/public-behavior/SystemViewColumns.java @@ -0,0 +1,304 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.sun.source.tree.*; +import com.sun.source.util.TreeScanner; +import java.nio.file.Path; +import java.util.*; +import java.util.function.BiConsumer; +import javax.lang.model.element.Modifier; + +/** Compare the indexed columns exposed by registered, generated system view walkers. */ +class SystemViewColumns { + private static final String GENERATOR = "org.apache.ignite.internal.systemview."; + private static final String ROWS = "org.apache.ignite.spi.systemview.view."; + private static final String MANAGERS = "org.apache.ignite.internal.managers.systemview."; + private static final Path MANAGER_PATH = Path.of("modules/core/src/main/java/org/apache/ignite/internal/managers/systemview"); + private static final String STATS = "org.apache.ignite.internal.processors.query.stat.view."; + private static final String CODEGEN = "modules/codegen/src/main/java/org/apache/ignite/internal/systemview/"; + private static final Set REGISTRATIONS = Set.of("registerView", "registerFiltrableView", "registerInnerCollectionView"); + + private record Row(Path file, CompilationUnitTree unit, ClassTree type) {} + private record Column(String name, Integer order, Path file) {} + + private static boolean imported(CompilationUnitTree unit, String name) { + return unit.getImports().stream().anyMatch(i -> i.getQualifiedIdentifier().toString().equals(name)); + } + + private static boolean named(CompilationUnitTree unit, Tree ref, String name) { + return ref.toString().equals(name) || ref.toString().equals(name.substring(name.lastIndexOf('.') + 1)) && imported(unit, name); + } + + private static Map rows(Map units) { + Map rows = new HashMap<>(); + units.forEach((path, unit) -> { + String pkg = unit.getPackageName() + "."; + if (pkg.startsWith(ROWS) || pkg.equals(STATS)) { + for (Tree declaration : unit.getTypeDecls()) { + if (declaration instanceof ClassTree cls && cls.getKind() == Tree.Kind.CLASS + && path.endsWith((pkg + cls.getSimpleName()).replace('.', '/') + ".java")) + rows.put(pkg + cls.getSimpleName(), new Row(path, unit, cls)); + } + } + }); + return rows; + } + + private static String parent(Row row) { + Tree ref = row.type.getExtendsClause(); + if (ref == null) + return "java.lang.Object"; + if (ref instanceof ParameterizedTypeTree generic) + ref = generic.getType(); + String name = ref.toString(); + if (name.contains(".") || name.equals("Object")) + return name.equals("Object") ? "java.lang.Object" : name; + for (ImportTree use : row.unit.getImports()) { + String type = use.getQualifiedIdentifier().toString(); + if (!use.isStatic() && type.endsWith("." + name)) + return type; + } + return row.unit.getPackageName() + "." + name; + } + + private static List columns(Map rows, String name) { + List result = new ArrayList<>(); + Set visited = new HashSet<>(); + Set names = new HashSet<>(); + Set orders = new HashSet<>(); + boolean descriptor = false; + while (!name.equals("java.lang.Object")) { + Row row = rows.get(name); + if (row == null || !visited.add(name)) + return List.of(); + descriptor |= row.type.getModifiers().getAnnotations().stream() + .anyMatch(a -> named(row.unit, a.getAnnotationType(), GENERATOR + "SystemViewDescriptor")); + for (Tree member : row.type.getMembers()) { + if (!(member instanceof MethodTree method) || method.getReturnType() == null + || method.getReturnType().toString().equals("void")) + continue; + Set flags = method.getModifiers().getFlags(); + if (!flags.contains(Modifier.PUBLIC) || flags.contains(Modifier.STATIC)) + continue; + String column = method.getName().toString(); + if (!method.getParameters().isEmpty() || !names.add(column)) + return List.of(); + Integer order = null; + for (AnnotationTree annotation : method.getModifiers().getAnnotations()) { + Tree annotationType = annotation.getAnnotationType(); + if (!named(row.unit, annotationType, GENERATOR + "Order")) { + if (annotationType.toString().equals("Order")) + return List.of(); + continue; + } + var args = annotation.getArguments(); + if (args.isEmpty()) + order = 0; + else if (args.size() == 1) { + var value = args.get(0); + if (value instanceof AssignmentTree assignment && assignment.getVariable().toString().equals("value")) + value = assignment.getExpression(); + if (JavaContracts.literal(value) instanceof Integer rank) + order = rank; + } + // Ambiguous ranks rely on the order in which javac enumerates members. + if (order == null || !orders.add(order)) + return List.of(); + } + result.add(new Column(column, order, row.file)); + } + name = parent(row); + } + result.sort(Comparator.comparing(Column::order, Comparator.nullsLast(Integer::compareTo)).thenComparing(Column::name)); + return descriptor ? result : List.of(); + } + + private static String viewName(ExpressionTree expr, ClassTree cls, MethodTree method, CompilationUnitTree unit, Map rows) { + if (expr instanceof IdentifierTree id) { + Set locals = new HashSet<>(); + new TreeScanner() { + @Override public Void visitVariable(VariableTree var, Void unused) { + locals.add(var.getName().toString()); + return super.visitVariable(var, unused); + } + }.scan(method, null); + if (locals.contains(id.getName().toString())) + return null; + for (ImportTree use : unit.getImports()) { + String imported = use.getQualifiedIdentifier().toString(); + if (use.isStatic() && imported.endsWith("." + id.getName())) { + Row row = rows.get(imported.substring(0, imported.lastIndexOf('.'))); + if (row == null || cls.getMembers().stream().anyMatch(m -> + m instanceof VariableTree field && field.getName().equals(id.getName()))) + return null; + cls = row.type; + unit = row.unit; + break; + } + } + for (Tree member : cls.getMembers()) { + if (member instanceof VariableTree field && id.getName().equals(field.getName()) + && field.getModifiers().getFlags().containsAll(Set.of(Modifier.STATIC, Modifier.FINAL))) { + expr = field.getInitializer(); + break; + } + } + } + if (expr instanceof LiteralTree literal && literal.getValue() instanceof String value) + return value; + if (expr instanceof MethodInvocationTree call && (named(unit, call.getMethodSelect(), + "org.apache.ignite.internal.processors.metric.impl.MetricUtils.metricName") + || call.getMethodSelect() instanceof MemberSelectTree selected && selected.getIdentifier().contentEquals("metricName") + && named(unit, selected.getExpression(), "org.apache.ignite.internal.processors.metric.impl.MetricUtils"))) { + List parts = new ArrayList<>(); + for (ExpressionTree arg : call.getArguments()) { + if (!(arg instanceof LiteralTree literal) || !(literal.getValue() instanceof String part)) + return null; + parts.add(part); + } + return parts.isEmpty() ? null : String.join(".", parts); + } + return null; + } + + // The scan view passes its name and generated walker to AbstractSystemView's constructor. + private static String scanViewName(Map units, Map rows) { + Path wrapper = MANAGER_PATH.resolve("ScanQuerySystemView.java"); + CompilationUnitTree unit = units.get(wrapper); + if (unit == null || !(unit.getPackageName() + ".").equals(MANAGERS) || unit.getTypeDecls().size() != 1 + || !(unit.getTypeDecls().get(0) instanceof ClassTree cls) || !cls.getSimpleName().contentEquals("ScanQuerySystemView") + || !parent(new Row(wrapper, unit, cls)).equals(MANAGERS + "AbstractSystemView")) + return null; + String result = null; + for (Tree member : cls.getMembers()) { + if (!(member instanceof MethodTree method)) + continue; + if (Set.of("name", "walker").contains(method.getName().toString())) + return null; + if (method.getReturnType() != null) + continue; + if (result != null || method.getBody() == null || method.getBody().getStatements().isEmpty() + || !(method.getBody().getStatements().get(0) instanceof ExpressionStatementTree first) + || !(first.getExpression() instanceof MethodInvocationTree call) || !call.getMethodSelect().toString().equals("super") + || call.getArguments().size() != 3 || !(call.getArguments().get(2) instanceof NewClassTree walker) + || walker.getClassBody() != null || !named(unit, walker.getIdentifier(), GENERATOR + "ScanQueryViewWalker")) + return null; + result = viewName(call.getArguments().get(0), cls, method, unit, rows); + if (result == null) + return null; + } + return result; + } + + private static Map> registrations(Map units, Map rows) { + Map> views = new HashMap<>(); + String scan = units.containsKey(MANAGER_PATH.resolve("AbstractSystemView.java")) ? null : scanViewName(units, rows); + for (CompilationUnitTree unit : units.values()) { + if (!unit.getImports().stream().anyMatch(i -> i.getQualifiedIdentifier().toString().startsWith(GENERATOR) + && i.getQualifiedIdentifier().toString().endsWith("Walker")) + && !(scan != null && imported(unit, MANAGERS + "ScanQuerySystemView"))) + continue; + for (Tree decl : unit.getTypeDecls()) { + if (!(decl instanceof ClassTree cls)) + continue; + for (Tree member : cls.getMembers()) { + if (!(member instanceof MethodTree method)) + continue; + new TreeScanner() { + @Override public Void visitMethodInvocation(MethodInvocationTree call, Void unused) { + var args = call.getArguments(); + if (call.getMethodSelect() instanceof MemberSelectTree select + && REGISTRATIONS.contains(select.getIdentifier().toString()) && args.size() >= 3 + && args.get(2) instanceof NewClassTree walker && walker.getClassBody() == null + && systemViewManager(select.getExpression(), method, unit)) { + String type = walker.getIdentifier().toString(); + String shortName = type.substring(type.lastIndexOf('.') + 1); + String name = viewName(args.get(0), cls, method, unit, rows); + if (name != null && shortName.endsWith("Walker") && named(unit, walker.getIdentifier(), GENERATOR + shortName)) + views.computeIfAbsent(shortName, ignored -> new TreeSet<>()).add(name); + } + if (scan != null && args.size() == 1 && call.getMethodSelect() instanceof MemberSelectTree select + && select.getIdentifier().contentEquals("registerView") && systemViewManager(select.getExpression(), method, unit) + && args.get(0) instanceof NewClassTree view && view.getClassBody() == null) { + Tree type = view.getIdentifier() instanceof ParameterizedTypeTree generic ? generic.getType() : view.getIdentifier(); + if (named(unit, type, MANAGERS + "ScanQuerySystemView")) + views.computeIfAbsent("ScanQueryViewWalker", ignored -> new TreeSet<>()).add(scan); + } + return super.visitMethodInvocation(call, unused); + } + }.scan(method.getBody(), null); + } + } + } + return views; + } + + private static boolean systemViewManager(ExpressionTree receiver, MethodTree method, CompilationUnitTree unit) { + if (receiver instanceof MethodInvocationTree get && get.getArguments().isEmpty() + && get.getMethodSelect() instanceof MemberSelectTree name && name.getIdentifier().contentEquals("systemView")) + return true; + return method.getParameters().stream().anyMatch(p -> p.getName().contentEquals(receiver.toString()) + && named(unit, p.getType(), "org.apache.ignite.internal.managers.systemview.GridSystemViewManager")); + } + + private static Path changedPrefix(List prefix, List other) { + for (Column col : prefix) { + if (!other.contains(col)) + return col.file; + } + return null; + } + + static void compare(Map before, Map after, + BiConsumer emit) { + if (before.keySet().stream().anyMatch(p -> p.startsWith(CODEGEN)) || after.keySet().stream().anyMatch(p -> p.startsWith(CODEGEN))) + return; + Map oldRows = rows(before); + Map newRows = rows(after); + if (oldRows.isEmpty() || newRows.isEmpty()) + return; + var oldViews = registrations(before, oldRows); + var newViews = registrations(after, newRows); + for (String type : new TreeSet<>(newRows.keySet())) { + Row row = newRows.get(type); + String walker = row.type.getSimpleName() + "Walker"; + Set views = new TreeSet<>(newViews.getOrDefault(walker, Set.of())); + views.retainAll(oldViews.getOrDefault(walker, Set.of())); + if (views.isEmpty() || row.type.getModifiers().getFlags().contains(Modifier.ABSTRACT)) + continue; + List old = columns(oldRows, type); + List now = columns(newRows, type); + List previousNames = old.stream().map(Column::name).toList(); + for (int i = 0; i < now.size(); i++) { + String column = now.get(i).name; + int previous = previousNames.indexOf(column); + if (previous < 0 || previous == i) + continue; + // A column moves if its rank or a preceding declaration changes, including in an ancestor. + Path source = changedPrefix(now.subList(0, i + 1), old); + if (source == null) + source = changedPrefix(old.subList(0, previous + 1), now); + if (source != null) { + for (String view : views) + emit.accept(source, "Changed column order in system view " + view + ": " + column + + " moved from position " + (previous + 1) + " to " + (i + 1)); + } + break; + } + } + } +} diff --git a/.github/public-behavior/check_pull_request.py b/.github/public-behavior/check_pull_request.py new file mode 100644 index 0000000000000..c2c898160608e --- /dev/null +++ b/.github/public-behavior/check_pull_request.py @@ -0,0 +1,217 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Check public behavior changes in a pull request from the trusted base checkout.""" +import json +import os +import re +import subprocess +import sys +from dataclasses import dataclass +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import quote, unquote + +from check_summary import report +from contract_diff import changed_contracts + +RFC_PATH = re.compile(r"rfcs/IGNITE-[0-9]+-[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*\.md") + + +@dataclass +class CheckResult: + reason: str + author: str + reviewer: str + paths: tuple = () + advisory: bool = False + changes: dict | None = None + rfc_links: tuple = () + + +class CheckError(ValueError): + def __init__(self, reason, author, reviewer, paths=(), changes=None): + super().__init__(reason) + self.result = CheckResult(reason, author, reviewer, paths, changes=changes) + + +def api(route, *, pages=False, raw=False, full=False, exists=False, optional=False, fields=None): + args = ["gh", "api"] + if exists: + args.extend(["--method", "HEAD", "--silent"]) + if pages: + args.extend(["--paginate", "--slurp"]) + if raw: + args.extend(["-H", "Accept: application/vnd.github.raw+json"]) + if full: + args.extend(["-H", "Accept: application/vnd.github.full+json"]) + args.append(route) + for key, value in (fields or {}).items(): + args.extend(["-f", key + "=" + value]) + try: + response = subprocess.check_output(args, stderr=subprocess.PIPE) + if exists: + return True + if raw: + return response.decode("utf-8") + data = json.loads(response) + return [item for page in data for item in page] if pages else data + except (OSError, subprocess.CalledProcessError, ValueError, TypeError) as exc: + detail = str(exc) + if isinstance(exc, subprocess.CalledProcessError) and exc.stderr: + detail = exc.stderr.decode(errors="replace").strip() + if (exists or optional) and re.search(r"\bHTTP 404\b", detail): + return False if exists else None + raise CheckError( + f"Could not read the GitHub API response for {route}. {detail}", + "Check that the repository and revision are available, then rerun the job.", + "Check the failed request in the job log and confirm the workflow has read access.", + ) from exc + + +def is_rfc_candidate(path): + filename = Path(path) + if not path.startswith("rfcs/") or filename.name.lower() in {"template.md", "readme.md"}: + return False + suffix = filename.suffix.lower() + if suffix == ".md": + return True + document_suffixes = {"", ".txt", ".markdown", ".mdown", ".mkd", ".adoc", ".asciidoc"} + return (filename.parent == Path("rfcs") and suffix in document_suffixes + and re.match(r"IGNITE-[0-9]+\b", filename.name) is not None) + + +class RFCFileLinks(HTMLParser): + """Read links to RFC files from GitHub's rendered PR description.""" + + def __init__(self, repository): + super().__init__() + self.pattern = re.compile(rf"(?ai:(?:https://github\.com)?/{re.escape(repository)})/blob/" + rf"([^?#]+?)/({RFC_PATH.pattern})(?:[?#].*)?") + self.targets = [] + + def handle_starttag(self, tag, attrs): + if tag == "a": + match = self.pattern.fullmatch(dict(attrs).get("href") or "") + if match: + self.targets.append((unquote(match[1]), match[2])) + + +def linked_rfcs(pr, files): + base = pr["base"] + repository = base["repo"]["full_name"] + parser = RFCFileLinks(repository) + parser.feed(pr["body_html"] or "") + removed = {f["filename"] for f in files if f["status"] == "removed"} + removed.update(f["previous_filename"] for f in files if f["status"] == "renamed") + + found = set() + request_error = None + for ref, path in dict.fromkeys(parser.targets): + if path in found or path in removed or not Path(path).is_file(): + continue + # The checkout proves the target-branch link exists. Other revisions need a metadata check. + if ref not in {base["ref"], base["sha"]}: + try: + if not api(f"repos/{repository}/contents/{path}?ref={quote(ref, safe='')}", exists=True): + continue + except CheckError as error: + request_error = error + continue + found.add(path) + if request_error and not found: + raise request_error + return sorted(found) + + +def check(files, changes, pr): + if not changes: + return CheckResult("No change was found by the static contract checks.", "", "") + + docs = sorted(f["filename"] for f in files if f["status"] != "removed" and is_rfc_candidate(f["filename"])) + paths = (*docs, *changes) + for path in docs: + if not RFC_PATH.fullmatch(path): + raise CheckError( + f"Invalid RFC filename: {path}.", + "Use rfcs/IGNITE--.md, for example rfcs/IGNITE-12345-cache-timeout.md.", + "Check that the filename contains the proposal's Jira ticket number.", paths, changes, + ) + + if docs: + revision = pr["head"]["sha"] + reason = "This PR changes a public contract and adds or updates an RFC." + review = ("Compare the changes below and their compatibility tests with the RFC. " + "For a new or revised plan, check its vote on dev@ and any unresolved objections.") + else: + docs = linked_rfcs(pr, files) + if not docs: + raise CheckError( + "Public API and other public contract changes require an RFC.", + "Add a new RFC from rfcs/TEMPLATE.md or update an existing RFC in this PR. " + "If an approved RFC covers the change, open its file on the target branch and " + "paste its GitHub URL into the PR description.", + "Check the detected changes and their effect on existing users.", paths, changes, + ) + revision = pr["base"]["sha"] + reason = "The PR description links to an existing RFC." + review = ("Check that the linked RFC covers the changes below and their compatibility tests. " + "Check any required vote on dev@.") + + repository = pr["base"]["repo"]["full_name"] + links = tuple((path, f"https://github.com/{repository}/blob/{revision}/{path}") for path in docs) + return CheckResult(reason, "", review, tuple(changes), advisory=True, changes=changes, rfc_links=links) + + +def main(): + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())["pull_request"] + route = f"repos/{os.environ['GITHUB_REPOSITORY']}/pulls/{event['number']}" + pr = api(route, full=True) + if ((pr["head"]["sha"], pr["base"]["sha"]) != (event["head"]["sha"], event["base"]["sha"]) + or (pr.get("body") or "") != (event.get("body") or "")): + raise CheckError( + "This run is stale. The PR revision or description has changed.", + "Open the check for the current PR revision. Update the PR if it needs a new run.", + "Use the result attached to the current revision before merging.", + ) + files = api(route + "/files?per_page=100", pages=True) + if len(files) != pr["changed_files"]: + raise CheckError( + f"GitHub returned an incomplete file list ({len(files)} of {pr['changed_files']}).", + "Split PRs that exceed GitHub's limit of 3,000 files. For a smaller PR, rerun the job.", + "Wait for a complete file list before assessing public-contract impact.", + ) + repository = os.environ["GITHUB_REPOSITORY"] + changes = changed_contracts(files, repository, pr["base"]["sha"], pr["head"]["sha"], api) + return check(files, changes, pr) + + +if __name__ == "__main__": + try: + outcome = main() + passed = True + except CheckError as error: + outcome = error.result + passed = False + except (OSError, KeyError, TypeError, ValueError, subprocess.SubprocessError) as error: + outcome = CheckResult( + f"The public contract check could not finish. {error}", + "Rerun the job for the current PR revision.", + "If the error recurs, check the workflow event and GitHub API response in the job log.", + ) + passed = False + report(passed, outcome.reason, outcome.author, outcome.reviewer, outcome.paths, + advisory=outcome.advisory, changes=outcome.changes, rfc_links=outcome.rfc_links) + sys.exit(0 if passed else 1) diff --git a/.github/public-behavior/check_summary.py b/.github/public-behavior/check_summary.py new file mode 100644 index 0000000000000..4319de532a9b8 --- /dev/null +++ b/.github/public-behavior/check_summary.py @@ -0,0 +1,102 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from html import escape +import os +from pathlib import Path +import sys + + +def _one_line(text, limit=1000): + line = "".join(c if c.isprintable() else ascii(c)[1:-1] for c in text[:limit + 1]) + return line[:limit - 1] + "…" if len(line) > limit else line + + +def report_title(passed, advisory=False): + if passed and advisory: + return "Public behavior to review" + return "Public behavior check passed" if passed else "Public behavior check failed" + + +def rules_reference(): + project = "https://github.com/apache/ignite" + scope = f"{project}/blob/master/rfcs/IGNITE-29219-public-api-and-compatibility.md" + process_doc = Path("rfcs/IGNITE-29220-rfc-development-process.md") + if os.environ.get("GITHUB_REPOSITORY") == "apache/ignite" and process_doc.is_file(): + process = f"{project}/blob/master/{process_doc.as_posix()}" + else: + process = f"{project}/pull/13760/files#diff-964c536dd887c02e46887244405c46d2d8b5e15dc7a4480eb3a33fb64844b15a" + return ( + f"See [Ignite's public contracts]({scope}) for the scope of compatibility review. " + f"The [RFC process]({process}) describes the review rules." + ) + + +def report(passed, reason, author, reviewer, paths=(), *, advisory=False, changes=None, rfc_links=()): + title = report_title(passed, advisory) + reason, author, reviewer = _one_line(reason), _one_line(author), _one_line(reviewer, limit=3000) + status = "🟡 Reviewer action needed. " if passed and advisory else "" + log = [f"{title}: {reason}"] + summary = [f"## {title}", f"

{status}{escape(reason, quote=False)}

"] + for role, task in (("author", author), ("reviewer", reviewer)): + if task: + log.append(f"For the {role}: {task}") + summary.extend([f"### For the {role}", f"

{escape(task, quote=False)}

"]) + + if rfc_links: + summary.append("### RFC files") + for path, file_url in rfc_links[:8]: + summary.append(f"[{path}]({file_url})") + log.append(f"RFC: {file_url}") + if len(rfc_links) > 8: + summary.append(f"{len(rfc_links) - 8} more RFC files are listed in the PR.") + + if paths: + items = [] + log.append("Files to review:") + for path in paths[:8]: + name = _one_line(path) + log.append(" - " + name) + facts = (changes or {}).get(path, ()) + lines = [_one_line(fact, limit=320) for fact in facts[:6]] + if len(facts) > len(lines): + lines.append(f"{len(facts) - len(lines)} more changes in this file.") + log.extend(" - " + line for line in lines) + details = "".join(f"
  • {escape(line, quote=False)}
  • " for line in lines) + listing = f"
      {details}
    " if details else "" + items.append(f"
  • {escape(name, quote=False)}{listing}
  • ") + summary.extend(["### Files to review", "
      \n" + "\n".join(items) + "\n
    "]) + if len(paths) > 8: + more = f"See {len(paths) - 8} more in the PR diff." + log.append(more) + summary.append(more) + + if not passed or advisory: + rules = rules_reference() + summary.append(rules) + log.append(rules) + + # GitHub also accepts the older ##[command] syntax inside log lines. + print("\n".join(log).replace("##[", r"##\["), file=sys.stdout if passed else sys.stderr) + if passed and advisory and os.environ.get("PUBLIC_BEHAVIOR_REVIEW_WARNING") == "true": + print("::warning title=Public behavior review::Review the RFC, any required dev@ vote, " + "and the files listed in the check summary.") + destination = os.environ.get("GITHUB_STEP_SUMMARY") + if destination: + try: + with open(destination, "a", encoding="utf-8") as out: + out.write("\n\n".join(summary) + "\n\n") + except OSError: + print("Could not write the GitHub job summary. See the result in this log.", file=sys.stderr) diff --git a/.github/public-behavior/cli_sources.py b/.github/public-behavior/cli_sources.py new file mode 100644 index 0000000000000..d532b6911c0cb --- /dev/null +++ b/.github/public-behavior/cli_sources.py @@ -0,0 +1,79 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Read the command and argument declarations for the affected control.sh command families.""" + +from pathlib import PurePosixPath +import re + + +MANAGEMENT = "modules/core/src/main/java/org/apache/ignite/internal/management" +ROOT_REGISTRY = MANAGEMENT + "/IgniteCommandRegistry.java" +NO_ARG = MANAGEMENT + "/api/NoArg.java" +COMMANDLINE = "modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/" +CLI_RULE_SOURCES = {COMMANDLINE + "ArgumentParser.java", + COMMANDLINE + "argument/parser/CLIArgumentParser.java", + COMMANDLINE + "argument/parser/CLIArgument.java"} +CLI_RULE_SOURCES.update(MANAGEMENT + "/api/" + name + ".java" for name in ( + "Argument", "ArgumentGroup", "ArgumentGroupsHolder", "Positional", "CommandUtils", + "Command", "CommandRegistryImpl", "CliSubcommandsWithPrefix", "CommandsRegistry", +)) + +# The tree belongs to a single Java package. One request supplies its commands, argument DTOs and base classes. +_PACKAGE_QUERY = """query($owner:String!, $repo:String!, $path:String!) { + repository(owner:$owner, name:$repo) { + object(expression:$path) { ... on Tree { entries { name type object { ... on Blob { text isTruncated } } } } } + } +}""" + + +def cli_package(path): + if not path.startswith(MANAGEMENT + "/"): + return None + relative = path[len(MANAGEMENT) + 1:] + if relative.startswith("api/") or not re.fullmatch(r"(?:[a-z][a-z0-9]*/)*[A-Z][A-Za-z0-9]*(?:Command|Arg)\.java", relative): + return None + return str(PurePosixPath(path).parent) + + +def cli_packages(paths): + packages = set() + for path in paths: + package = cli_package(path) + if package: + packages.add(package) + # A nested subcommand may be registered in its enclosing package. + for parent in PurePosixPath(package).parents: + if not str(parent).startswith(MANAGEMENT + "/"): + break + packages.add(str(parent)) + return packages + + +def cli_package_sources(repository, revision, package, api): + owner, repo = repository.split("/") + data = api("graphql", fields={"query": _PACKAGE_QUERY, "owner": owner, "repo": repo, "path": revision + ":" + package}) + tree = data["data"]["repository"]["object"] + if not tree: + return {} + sources = {} + for entry in tree["entries"]: + path = package + "/" + entry["name"] + if entry["type"] != "blob" or not (cli_package(path) == package or path == ROOT_REGISTRY): + continue + blob = entry["object"] + if blob and isinstance(blob.get("text"), str) and not blob.get("isTruncated", True): + sources[path] = blob["text"] + return sources diff --git a/.github/public-behavior/contract_diff.py b/.github/public-behavior/contract_diff.py new file mode 100644 index 0000000000000..eb6e15869bb35 --- /dev/null +++ b/.github/public-behavior/contract_diff.py @@ -0,0 +1,144 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Compare the contract declarations on the two sides of a pull request.""" + +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path, PurePosixPath +import subprocess +from tempfile import TemporaryDirectory +from urllib.parse import quote + +from cli_sources import CLI_RULE_SOURCES, MANAGEMENT, NO_ARG, ROOT_REGISTRY, cli_packages, cli_package_sources +from view_sources import VIEW_RULE_SOURCES, view_companions, supports_view_source +from contract_paths import REST_SOURCES, SQL_ERRORS, SQL_STATES, java_contract_source +from launcher_contracts import launcher_changes, supports_launcher +from registered_contracts import supports_registered_contracts +from contract_values import contract_values, supports_values, value_changes + + +def _candidate(path): + if not path or path.startswith("/") or ".." in PurePosixPath(path).parts: + return False + return java_contract_source(path) or supports_values(path) or supports_launcher(path) + + +def changed_contracts(files, repository, base, head, api): + touched = {name for item in files for name in (item["filename"], item.get("previous_filename")) if name} + view_sources = view_companions(touched) + pairs = [] + for item in files: + path = item["filename"] + old = None if item["status"] in {"added", "copied"} else item.get("previous_filename", path) + new = None if item["status"] == "removed" else path + # We can compare a rename only when both locations are in a supported contract. + if all(_candidate(name) or name in view_sources for name in (old, new) if name): + pairs.append((old, new)) + if not pairs: + return {} + + old_paths = {old for old, _ in pairs if old} + new_paths = {new for _, new in pairs if new} + skip_cli = bool(touched & CLI_RULE_SOURCES) + skip_views = bool(touched & VIEW_RULE_SOURCES) + # An argument change needs a registered command on both sides. New files are + # already in the PR diff and cannot establish a previous binding on their own. + packages = set() if skip_cli else cli_packages(old_paths) & cli_packages(new_paths) + companions = view_sources - touched + if packages: + if NO_ARG not in touched: + companions.add(NO_ARG) + if MANAGEMENT not in packages and ROOT_REGISTRY not in touched: + companions.add(ROOT_REGISTRY) + if REST_SOURCES & (old_paths | new_paths): + companions.update(REST_SOURCES - touched) + if SQL_ERRORS in old_paths & new_paths and SQL_STATES not in touched: + companions.add(SQL_STATES) + revisions = {"after": head} + if old_paths: + # Compare against the PR's branch point. The base branch can move independently. + comparison = api(f"repos/{repository}/compare/{base}...{head}?per_page=1") + revisions["before"] = comparison["merge_base_commit"]["sha"] + + def read(item): + side, path = item + route = f"repos/{repository}/contents/{quote(path)}?ref={revisions[side]}" + if path in companions: + return item, api(route, raw=True, optional=True) + return item, api(route, raw=True) + + jobs = [("before", path) for path in sorted(old_paths)] + [("after", path) for path in sorted(new_paths | companions)] + with ThreadPoolExecutor(max_workers=4) as pool: + sources = dict(pool.map(read, jobs)) + for path in companions: + contents = sources.pop(("after", path)) + if contents is not None: + sources["before", path] = sources["after", path] = contents + # Unchanged files have the same contents on both sides of the PR. Read each package once, + # even if several of its subcommands or argument DTOs changed. + for package in sorted(packages): + for path, source in cli_package_sources(repository, revisions["before"], package, api).items(): + if path not in touched: + sources["before", path] = sources["after", path] = source + return compare_sources(pairs, sources, skip_cli=skip_cli, skip_views=skip_views) + + +def compare_sources(pairs, sources, *, skip_cli=False, skip_views=False): + changes = defaultdict(list) + java = [(key, text) for key, text in sources.items() if java_contract_source(key[1]) or supports_view_source(key[1])] + for path, fact in java_changes(java, skip_cli=skip_cli, skip_views=skip_views): + changes[path].append(fact) + + for old, new in pairs: + if old == new and supports_launcher(new): + findings = launcher_changes(new, sources["before", old], sources["after", new]) + if findings: + changes[new].extend(findings) + if old and new and supports_values(old) and supports_values(new): + before = contract_values(old, sources["before", old]) + after = contract_values(new, sources["after", new]) + for key in sorted(before.keys() & after.keys()): + findings = value_changes(key, before[key], after[key]) + if findings: + changes[new].extend(findings) + return dict(sorted(changes.items())) + + +def java_changes(java, *, skip_cli=False, skip_views=False): + if not java: + return [] + # Only the trusted analyzer is executed. The two directories contain PR sources as data. + with TemporaryDirectory() as directory: + root = Path(directory) + for side in ("before", "after"): + (root / side).mkdir() + for (side, path), text in java: + target = root / side / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + checker = Path(__file__).resolve().parent + compiled = root / "checker" + compiled.mkdir() + subprocess.run(["javac", "-proc:none", "-d", str(compiled), *map(str, sorted(checker.glob("*.java")))], + check=True) + options = sorted({path for (_, path), _ in java if supports_registered_contracts(path)}) + if skip_cli: + options.append("--skip-cli-arguments") + if skip_views: + options.append("--skip-view-columns") + run = subprocess.run(["java", "-cp", str(compiled), "JavaContracts", str(root / "before"), str(root / "after"), *options], + text=True, stdout=subprocess.PIPE, check=True) + return [line.split("\t", 1) for line in run.stdout.splitlines()] diff --git a/.github/public-behavior/contract_paths.py b/.github/public-behavior/contract_paths.py new file mode 100644 index 0000000000000..fc47e968d7103 --- /dev/null +++ b/.github/public-behavior/contract_paths.py @@ -0,0 +1,69 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Select source files for the static checks. A path match by itself is not a finding.""" + +from cli_sources import cli_package +from registered_contracts import supports_registered_contracts + + +JAVA_MODULES = { + "binary/api", "binary/impl", "calcite", "commons", "compress", "control-utility", "core", "direct-io", + "indexing", "jcl", "json", "jta", "kubernetes", "log4j2", "nio", "numa-allocator", + "opencensus", "rest-http", "schedule", "slf4j", "spring", "thin-client/api", + "thin-client/impl", "urideploy", "web", "zookeeper", +} + +_CORE = "modules/core/src/main/java/org/apache/ignite/internal/" +_REST = "processors/rest/" +REST_SOURCES = { + _CORE + _REST + "GridRestCommand.java", + "modules/rest-http/src/main/java/org/apache/ignite/internal/" + _REST + "protocols/http/jetty/GridJettyRestProtocol.java", + "modules/rest-http/src/main/java/org/apache/ignite/internal/" + _REST + "protocols/http/jetty/GridJettyRestHandler.java", +} +SQL_ERRORS = _CORE + "processors/cache/query/IgniteQueryErrorCode.java" +SQL_STATES = _CORE + "processors/odbc/SqlStateCode.java" + +_INTERNAL_SOURCES = { + "internal/processors/cache/query/IgniteQueryErrorCode.java", + "internal/processors/odbc/SqlStateCode.java", + "internal/processors/platform/client/ClientBitmaskFeature.java", + "internal/client/thin/ClientOperation.java", + "internal/processors/rest/protocols/http/jetty/IgniteRestExtension.java", + "internal/commandline/ArgumentParser.java", + "internal/commandline/CommandHandler.java", + "internal/management/IgniteCommandRegistry.java", + "internal/management/api/NoArg.java", + "internal/binary/GridBinaryMarshaller.java", + "internal/pagemem/wal/record/WALRecord.java", + "internal/processors/cache/persistence/file/FilePageStore.java", + "internal/processors/cache/persistence/file/FilePageStoreV2.java", + "internal/processors/cache/persistence/snapshot/SnapshotMetadata.java", + "internal/processors/cache/persistence/snapshot/IncrementalSnapshotMetadata.java", +} + + +def java_contract_source(path): + if cli_package(path): + return True + module, source_root, java = path.partition("/src/main/java/org/apache/ignite/") + if not source_root or not module.startswith("modules/") or not java.endswith(".java"): + return False + if module.removeprefix("modules/") not in JAVA_MODULES: + return False + if java in _INTERNAL_SOURCES or path in REST_SOURCES or supports_registered_contracts(path): + return True + return not (java.startswith(("internal/", "spi/discovery/tcp/messages/", "spi/communication/tcp/messages/")) + or "/internal/" in java or java.endswith("package-info.java")) diff --git a/.github/public-behavior/contract_values.py b/.github/public-behavior/contract_values.py new file mode 100644 index 0000000000000..72411976ec630 --- /dev/null +++ b/.github/public-behavior/contract_values.py @@ -0,0 +1,169 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Read values from published manifests and configuration schemas.""" + +import re +from xml.etree import ElementTree + +from contract_paths import JAVA_MODULES + + +# modules/bom/pom.xml lists the published artifacts covered here. +_MODULES = (JAVA_MODULES - {"jcl", "numa-allocator"}) | {"bom"} +_POMS = {f"modules/{module}/pom.xml" for module in _MODULES} +_NAMESPACE = "{http://maven.apache.org/POM/4.0.0}" + + +_PLATFORMS = "modules/platforms/" +_ODBC = _PLATFORMS + "cpp/odbc/module.def" +_DOTNET = _PLATFORMS + "dotnet/Apache.Ignite." +_NUGET = {_DOTNET + name + "/Apache.Ignite." + name + ".csproj" + for name in ("Core", "EntityFramework", "AspNet", "Linq", "NLog", "Log4Net", "Schema")} +_SCHEMAS = {_DOTNET + "Core/" + name + ".xsd" for name in ("IgniteClientConfigurationSection", "IgniteConfigurationSection")} +_XS = "{http://www.w3.org/2001/XMLSchema}" +_PARENT = "parent/pom.xml" +_BOM = "modules/bom/pom.xml" + + +def supports_values(path): + return path in _POMS or path in _NUGET or path in _SCHEMAS or path in {_PARENT, _ODBC} + + +def _odbc_exports(source): + lines = [line.partition(";")[0].strip() for line in source.splitlines()] + lines = [line for line in lines if line] + if len(lines) < 2 or not lines[0].startswith("LIBRARY ") or lines[1] != "EXPORTS": + return None + exports = set() + for entry in lines[2:]: + match = re.fullmatch(r"([a-zA-Z_]\w*)(?:\s*=\s*[a-zA-Z_]\w*)?", entry, re.ASCII) + if not match: + return None + exports.add(match[1]) + return exports + + +def _schema_values(schema): + if schema.tag != _XS + "schema": + return {} + values = {"XML configuration namespace": schema.get("targetNamespace")} + for typ in schema.findall(_XS + "simpleType"): + restriction = typ.find(_XS + "restriction") + if restriction is None or not typ.get("name"): + continue + choices = {node.get("value") for node in restriction.findall(_XS + "enumeration")} + if None not in choices and choices and restriction.get("base") == "xs:string": + values["XML configuration values for " + typ.get("name")] = choices + groups = {_XS + group for group in ("complexType", "all", "sequence", "choice")} + + # Only compare attributes in inline element declarations with the same external path. + def attributes(node, path): + for child in node: + if child.tag == _XS + "element" and child.get("name"): + attributes(child, path + "/" + child.get("name")) + elif child.tag in groups and not child.get("name"): + attributes(child, path) + elif child.tag == _XS + "attribute" and child.get("name") and path: + key = "XML configuration " + path + "/@" + child.get("name") + values[key + " use"] = child.get("use", "optional") + default = child.get("default") + kind = child.get("type") + if default is not None: + if kind == "xs:string": + values[key + " string default"] = default + elif kind == "xs:boolean": + value = {"0": "false", "false": "false", "1": "true", "true": "true"}.get(default.strip()) + values[key + " boolean default"] = value + attributes(schema, "") + return {key: val for key, val in values.items() if val is not None} + + +def _nuget_values(project): + if project.tag != "Project" or project.get("Sdk") != "Microsoft.NET.Sdk": + return {} + values = {} + for field, label in (("PackageId", "NuGet package ID"), ("TargetFramework", ".NET target framework"), + ("AssemblyName", ".NET assembly name"), ("IsPackable", "packable")): + all_nodes = project.findall(".//" + field) + groups = project.findall("PropertyGroup") + literal = [node for group in groups if not group.attrib for node in group.findall(field) if not node.attrib] + if len(all_nodes) == len(literal) == 1 and re.fullmatch(r"[a-zA-Z0-9_.-]+", literal[0].text or ""): + values[label] = literal[0].text + elif field == "IsPackable" and all_nodes: + return {} + return values if values.pop("packable", "true").lower() == "true" else {} + + +def value_changes(label, before, after): + if label in {"NuGet package ID", ".NET target framework"} and before.casefold() == after.casefold(): + return [] + if isinstance(before, set): + return ([f"Removed {label}: {name}" for name in sorted(before - after)] + + [f"Added {label}: {name}" for name in sorted(after - before)]) + return [f"{label} changed from {before} to {after}."] if before != after else [] + + +def contract_values(path, source): + if not supports_values(path): + return {} + if path == _ODBC: + exports = _odbc_exports(source) + return {} if exports is None else {"Windows ODBC export": exports} + try: + project = ElementTree.fromstring(source) + except (ElementTree.ParseError, ValueError): + return {} + if path in _SCHEMAS: + return _schema_values(project) + if path in _NUGET: + return _nuget_values(project) + if project.tag not in {"project", _NAMESPACE + "project"}: + return {} + namespace = _NAMESPACE if project.tag.startswith("{") else "" + if path == _PARENT: + release = project.findtext(f"{namespace}properties/{namespace}maven.compiler.release", "") + return {"Java release for compiled artifacts": release} if re.fullmatch(r"[1-9][0-9]*", release) else {} + values = {} + for field in ("groupId", "artifactId"): + nodes = project.findall(namespace + field) + if field == "groupId" and not nodes: + nodes = project.findall(f"{namespace}parent/{namespace}groupId") + if len(nodes) != 1 or len(nodes[0]): + continue + value = (nodes[0].text or "").strip() + if re.fullmatch(r"[A-Za-z0-9_.-]+", value): + values["Maven " + field] = value + if path == _BOM: + dependencies = project.find(f"{namespace}dependencyManagement/{namespace}dependencies") + if dependencies is not None: + managed = set() + for dependency in dependencies.findall(namespace + "dependency"): + kind = dependency.findtext(namespace + "type", "jar").strip() + scope = dependency.findtext(namespace + "scope", "compile").strip() + if kind == "pom" and scope == "import": + break + if kind != "jar" or dependency.find(namespace + "classifier") is not None or scope != "compile": + continue + artifact = dependency.findtext(namespace + "artifactId", "").strip() + group = dependency.findtext(namespace + "groupId", "").strip() + if group == "${project.groupId}": + group = values.get("Maven groupId", "") + if not all(re.fullmatch(r"[A-Za-z0-9_.-]+", part) for part in (group, artifact)): + break + managed.add(group + ":" + artifact) + else: + values["Maven BOM dependency"] = managed + return values diff --git a/.github/public-behavior/launcher_contracts.py b/.github/public-behavior/launcher_contracts.py new file mode 100644 index 0000000000000..8f66873563512 --- /dev/null +++ b/.github/public-behavior/launcher_contracts.py @@ -0,0 +1,67 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Read the minimum Java version enforced by the distribution launchers.""" + +import re + + +_UNIX = "bin/include/functions.sh" +_WINDOWS = {"bin/ignite.bat", "bin/control.bat", "bin/index-reader.bat"} +_UNIX_GATE = re.compile( + r'^ +javaMajorVersion "\$JAVA"\n\s*if \[ \$version -lt (?P[1-9][0-9]*) \]; then\n' + r'(?:[ \t]+echo [^\n]*\n)*[ \t]+exit 1\n[ \t]+fi\n}$', re.MULTILINE) +_WINDOWS_GATE = re.compile( + r'^if %MAJOR_JAVA_VER% == 1 set MAJOR_JAVA_VER=%MINOR_JAVA_VER%\n\s*' + r'if %MAJOR_JAVA_VER% LSS (?P[1-9][0-9]*) \(\n' + r'(?:[ \t]+echo [^\n]*\n)*[ \t]+goto error_finish\n\)$', re.MULTILINE | re.IGNORECASE) +_WINDOWS_ERROR_EXIT = re.compile(r'^:error_finish\n\s*(?:if not "%NO_PAUSE%" == "1" pause\n\s*)?goto :eof$', + re.MULTILINE | re.IGNORECASE) +# The same installation advice also appears in the branches for a missing java executable. +_JDK_ADVICE = re.compile(r'^[ \t]*echo "?[a-zA-Z0-9 _.,:/-]*\bJDK\b[a-zA-Z0-9 _.,:/-]*"?$', + re.MULTILINE | re.IGNORECASE) + + +def supports_launcher(path): + return path == _UNIX or path in _WINDOWS + + +def launcher_changes(path, before, after): + if not supports_launcher(path): + return [] + gate = _UNIX_GATE if path == _UNIX else _WINDOWS_GATE + versions = [] + scripts = [] + for source in (before, after): + script = source.replace("\r\n", "\n") + matches = list(gate.finditer(script)) + if len(matches) != 1: + return [] + match = matches[0] + if path == _UNIX: + # The rejection must be in checkJava, which the Unix launchers call. + prefix = script[:match.start()].rsplit("\n}", 1)[-1] + if not re.search(r"^checkJava\(\) \{$", prefix, re.MULTILINE): + return [] + elif not (re.search(r"^:checkJdkVersion$", script[:match.start()], re.MULTILINE | re.IGNORECASE) + and _WINDOWS_ERROR_EXIT.search(script, match.end())): + return [] + versions.append(match["minimum"]) + start, end = match.span("minimum") + scripts.append(_JDK_ADVICE.sub("", script[:start] + "" + script[end:])) + # If the control flow also changed, the numeric threshold alone cannot establish the effect. + if scripts[0] == scripts[1] and versions[0] != versions[1]: + return [f"Changed minimum Java version accepted by the launcher from {versions[0]} to {versions[1]}."] + return [] diff --git a/.github/public-behavior/post_pr_comment.py b/.github/public-behavior/post_pr_comment.py new file mode 100644 index 0000000000000..8b24c0710af3c --- /dev/null +++ b/.github/public-behavior/post_pr_comment.py @@ -0,0 +1,210 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Report public behavior changes from a trusted workflow run on the current pull request.""" + +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys + +from check_pull_request import api +from check_summary import report_title, rules_reference + + +MARKER = re.compile( + r"^\n" +) +JOB_CONCLUSIONS = {"success", "failure", "timed_out"} +RESOLVED = f"## {report_title(True)}\n\nThe check passed. There is nothing left to flag in this PR." +RERUN = ( + "## Public behavior changes need a fresh check\n\n" + "GitHub still shows a failed job. The current PR passed when the reporter checked again.\n\n" + "### For the author\n\nRe-run the failed job or ask a maintainer to re-run it.\n\n" + "### For the reviewer\n\nWait for **Public behavior changes** to pass on this commit." +) +TIMEOUT = ( + "## Public behavior check timed out\n\n" + "GitHub stopped the check before it could verify the change.\n\n" + "### For the author\n\nCheck the job log for the stalled step and update the PR to start a fresh check.\n\n" + "### For the reviewer\n\nWait for **Public behavior changes** to finish on this commit." +) + + +def eligible(run, repo): + return ( + run["repository"]["full_name"] == repo and run["path"] == ".github/workflows/check-public-behavior.yml" + and run["event"] == "pull_request" + and run["status"] == "completed" and run["conclusion"] in JOB_CONCLUSIONS + and run["head_repository"] and run["head_branch"] + and re.fullmatch(r"[0-9a-f]{40}", run["head_sha"]) + ) + + +def matches(pr, run, repo): + source = run["head_repository"]["full_name"] + head = pr["head"] + return ( + run.get("display_title") == f"Public behavior changes for PR #{pr['number']}" + and pr["state"] == "open" and pr["base"]["ref"] == "master" and pr["base"]["repo"]["full_name"] == repo + and head["repo"] and head["repo"]["full_name"] == source + and head["ref"] == run["head_branch"] and head["sha"] == run["head_sha"] + and (not run["pull_requests"] or any(link["number"] == pr["number"] for link in run["pull_requests"])) + ) + + +def recorded_job(root, run): + attempt = f"{root}/actions/runs/{int(run['id'])}/attempts/{int(run['run_attempt'])}" + jobs = [job for job in api(f"{attempt}/jobs?per_page=100")["jobs"] if job["name"] == "Public behavior changes"] + return jobs[0]["conclusion"] if len(jobs) == 1 else None + + +def newer_run(repo, run, pr): + root = f"repos/{repo}" + route = f"{root}/actions/workflows/check-public-behavior.yml/runs?head_sha={run['head_sha']}&status=completed&per_page=100" + page = 1 + while True: + response = api(f"{route}&page={page}") + for other in response["workflow_runs"]: + if ((other["id"], other["run_attempt"]) <= (run["id"], run["run_attempt"]) + or not eligible(other, repo) or not matches(pr, other, repo)): + continue + if recorded_job(root, other) in JOB_CONCLUSIONS: + return True + if page * 100 >= response["total_count"]: + return False + # GitHub returns up to 1,000 filtered runs. Keep the existing comment if the list is incomplete. + if not response["workflow_runs"] or page == 10: + return True + page += 1 + + +def prepare(repo, run, destination): + if not eligible(run, repo): + return + root = f"repos/{repo}" + conclusion = recorded_job(root, run) + if conclusion not in JOB_CONCLUSIONS: + return + + # Fork events can omit workflow_run.pull_requests. Verify the run's PR number against the live head. + title = re.fullmatch(r"Public behavior changes for PR #([1-9][0-9]*)", run.get("display_title") or "") + if not title: + return + pr = api(f"{root}/pulls/{title[1]}") + if not matches(pr, run, repo): + return + event = {"number": pr["number"], "head": {"sha": pr["head"]["sha"]}, "base": {"sha": pr["base"]["sha"]}, + "body": pr.get("body") or ""} + context = {"pull_request": event, "source_conclusion": conclusion} + destination.write_text(json.dumps(context), encoding="utf-8") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as out: + print(f"pr_number={int(pr['number'])}", f"base_sha={pr['base']['sha']}", f"conclusion={conclusion}", sep="\n", file=out) + + +def update(method, route, body=None): + args = ["gh", "api", "--method", method, "--silent", route] + if body is not None: + args.extend(["--input", "-"]) + subprocess.run(args, input=json.dumps({"body": body}) if body is not None else None, text=True, check=True) + + +def comment_body(summary_file, original, outcome): + if original == outcome == "timed_out": + return TIMEOUT + "\n\n" + rules_reference() + if outcome not in {"success", "failure"} or original == "timed_out": + raise ValueError("The public behavior check returned inconsistent conclusions.") + summary = summary_file.read_text(encoding="utf-8").strip() + heading, _, content = summary.partition("\n") + passed = outcome == "success" + headings = {"## " + report_title(passed), "## " + report_title(passed, advisory=True)} + if not content or heading not in headings or len(summary) > 63000: + raise ValueError("The public behavior check did not produce a complete job summary.") + if passed: + if original != "success": + return RERUN + "\n\n" + rules_reference() + if heading == "## " + report_title(True, advisory=True): + return summary + return RESOLVED + if original == "success": + summary += "\n\nThe original job passed. Update the PR to start a fresh **Public behavior changes** check." + return summary + + +def publish(repo, run, context, summary_file, outcome): + if not eligible(run, repo) or outcome not in JOB_CONCLUSIONS: + return + root = f"repos/{repo}" + number = int(context["pull_request"]["number"]) + route = f"{root}/pulls/{number}" + comments = [] + for comment in api(f"{root}/issues/{number}/comments?per_page=100", pages=True): + user = comment.get("user") or {} + marker = MARKER.match(comment["body"] or "") + if user.get("login") == "github-actions[bot]" and user.get("type") == "Bot" and marker: + comments.append((comment["id"], marker)) + + source = int(run["id"]), int(run["run_attempt"]) + if any((int(m["run"]), int(m["attempt"])) > source for _, m in comments): + return + original = context["source_conclusion"] + passed = original == outcome == "success" + body = comment_body(summary_file, original, outcome) + advisory = body.startswith("## " + report_title(True, advisory=True) + "\n") + if passed and not advisory and not comments: + return + outcome = "success" if passed else "failure" + # Avoid notifications from @mentions in file names or diagnostic text. + body = re.sub(r"(?" + if advisory and comments and latest["outcome"] == "failure": + body += "\n\nThe issues from the previous check are resolved." + details = f"https://github.com/{repo}/pull/{number}/checks" + update("POST", f"{root}/issues/{number}/comments", f"{marker}\n{body}\n\n[Open PR checks]({details})") + for cid, _ in comments: + if cid != retained: + update("DELETE", f"{root}/issues/comments/{cid}") + + +if __name__ == "__main__": + event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text()) + repo = os.environ["GITHUB_REPOSITORY"] + if event["action"] == "completed": + if sys.argv[1] == "prepare": + prepare(repo, event["workflow_run"], Path(sys.argv[2])) + elif sys.argv[1] == "publish": + context = json.loads(Path(sys.argv[2]).read_text()) + publish(repo, event["workflow_run"], context, Path(sys.argv[3]), sys.argv[4]) diff --git a/.github/public-behavior/registered_contracts.py b/.github/public-behavior/registered_contracts.py new file mode 100644 index 0000000000000..cad9a5c0c40d2 --- /dev/null +++ b/.github/public-behavior/registered_contracts.py @@ -0,0 +1,46 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Java sources that register settings, metrics, system views, and SQL functions.""" + +SOURCE_ROOT = "/src/main/java/org/apache/ignite/internal/" +REGISTERED_SOURCES = { + "core": { + "sql/SqlKeyword", + "cluster/DistributedBaselineConfiguration", + "cluster/DistributedTransactionConfiguration", + "processors/configuration/distributed/DistributedThinClientConfiguration", + "processors/cache/CacheMetricsImpl", + "processors/cache/CacheGroupMetricsImpl", + "processors/cache/persistence/DataRegionMetricsImpl", + "processors/cache/persistence/DataStorageMetricsImpl", + "processors/cache/transactions/TransactionMetricsAdapter", + "processors/query/QueryParserMetricsHolder", + "managers/discovery/GridDiscoveryManager", + "processors/cache/ClusterCachesInfo", + "processors/cluster/GridClusterStateProcessor", + "processors/datastructures/DataStructuresProcessor", + "processors/query/schema/management/SchemaManager", + }, + "calcite": {"processors/query/calcite/sql/fun/IgniteOwnSqlOperatorTable"}, + "indexing": {"processors/query/h2/DistributedIndexingConfiguration"}, +} + +REGISTERED_PATHS = {f"modules/{module}{SOURCE_ROOT}{name}.java" + for module, classes in REGISTERED_SOURCES.items() for name in classes} + + +def supports_registered_contracts(path): + return path in REGISTERED_PATHS diff --git a/.github/public-behavior/tests/test_check_command.py b/.github/public-behavior/tests/test_check_command.py new file mode 100644 index 0000000000000..7536d8fce811c --- /dev/null +++ b/.github/public-behavior/tests/test_check_command.py @@ -0,0 +1,212 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import os +from pathlib import Path +import subprocess +import sys +from tempfile import TemporaryDirectory +import unittest + + +CHECKER = Path(__file__).resolve().parents[1] / "check_pull_request.py" +PUBLIC_API = "modules/core/src/main/java/org/apache/ignite/IgniteCache.java" +HEAD = "a" * 40 +BASE = "b" * 40 +PLAN = "rfcs/IGNITE-123-timeout.md" +PLAN_LINK = f"https://github.com/apache/ignite/blob/master/{PLAN}" + + +def run_checker(file_pages, *, sources=None, changed_files=None, title="", link="", base_rfc=None, earlier_revision=None): + """Run the workflow command with a fork PR event and GitHub responses for its list of files.""" + repo = "apache/ignite" + pull = f"repos/{repo}/pulls/42" + pr = { + "number": 42, "title": title, "body": link, + "head": {"repo": {"full_name": "contributor/ignite"}, "sha": HEAD}, + "base": {"repo": {"full_name": repo}, "ref": "master", "sha": BASE}, + "changed_files": sum(map(len, file_pages)) if changed_files is None else changed_files, + } + paged = "api --paginate --slurp" + responses = { + f"api -H Accept: application/vnd.github.full+json {pull}": + dict(pr, body_html=f'

    {link}

    ' if link else ""), + f"{paged} {pull}/files?per_page=100": file_pages, + } + if earlier_revision: + responses[f"api --method HEAD --silent repos/{repo}/contents/{base_rfc}?ref={earlier_revision}"] = "" + merge_base = "c" * 40 + responses[f"api repos/{repo}/compare/{pr['base']['sha']}...{HEAD}?per_page=1"] = { + "merge_base_commit": {"sha": merge_base} + } + for (side, path), source in (sources or {}).items(): + rev = merge_base if side == "before" else HEAD + responses[f"api -H Accept: application/vnd.github.raw+json repos/{repo}/contents/{path}?ref={rev}"] = source + with TemporaryDirectory() as directory: + work = Path(directory) + if base_rfc: + plan = work / base_rfc + plan.parent.mkdir() + plan.write_text("# Accepted plan\n") + event = work / "event.json" + event.write_text(json.dumps({"pull_request": pr})) + (work / "responses.json").write_text(json.dumps(responses)) + gh = work / "gh" + gh.write_text( + "#!/usr/bin/env python3\n" + "import json, sys\n" + "from pathlib import Path\n" + "responses = json.loads(Path('responses.json').read_text())\n" + "value = responses[' '.join(sys.argv[1:])]\n" + "sys.stdout.write(value if isinstance(value, str) else json.dumps(value))\n" + ) + gh.chmod(0o755) + summary = work / "summary.md" + env = { + "PATH": os.pathsep.join((directory, str(Path(sys.executable).parent), os.environ["PATH"])), + "GITHUB_EVENT_PATH": str(event), "GITHUB_REPOSITORY": repo, + "GITHUB_STEP_SUMMARY": str(summary), + } + result = subprocess.run([sys.executable, str(CHECKER)], cwd=work, env=env, capture_output=True, text=True) + return result, summary.read_text() + + +def run_artifact_rename(*rfc_files, **fixture): + """Run the workflow on a public artifact rename and the RFC files supplied by the test.""" + pom = "modules/core/pom.xml" + before = "ignite-core" + sources = {("before", pom): before, ("after", pom): before.replace("ignite-core", "ignite-runtime")} + return run_checker([[{"filename": pom, "status": "modified"}, *rfc_files]], sources=sources, **fixture) + + +class CheckCommandTest(unittest.TestCase): + def test_new_public_method_is_reported_on_page_two(self): + first_page = [{"filename": f"docs/page-{i}.md", "status": "modified"} for i in range(100)] + pages = [first_page, [{"filename": PUBLIC_API, "status": "modified"}]] + original = "package org.apache.ignite; public interface IgniteCache {}" + sources = {("before", PUBLIC_API): original, + ("after", PUBLIC_API): original.replace("{}", "{ int cacheTimeout(); }")} + result, summary = run_checker(pages, sources=sources) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("require an RFC", summary) + self.assertIn(PUBLIC_API, summary) + self.assertIn("cacheTimeout", summary) + self.assertIn("rfcs/TEMPLATE.md", summary) + added_rfc = {"filename": PLAN, "status": "added"} + result, summary = run_checker([first_page, [*pages[1], added_rfc]], sources=sources) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("🟡 Reviewer action needed", summary) + self.assertIn("cacheTimeout", summary) + self.assertIn("vote on dev@", summary) + + def test_follow_up_pr_links_the_existing_rfc_file(self): + """A link to an RFC on the base branch puts its checked revision in the review report.""" + result, summary = run_artifact_rename(link=PLAN_LINK, base_rfc=PLAN) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("🟡 Reviewer action needed", summary) + self.assertIn(f"[{PLAN}](https://github.com/apache/ignite/blob/{BASE}/{PLAN})", summary) + self.assertIn("Maven artifactId changed from ignite-core to ignite-runtime", summary) + + def test_link_to_an_earlier_revision_shows_the_rfc_on_the_target_branch(self): + """A permalink identifies an existing RFC. The reviewer sees the version on the target branch.""" + revision = "d" * 40 + result, summary = run_artifact_rename(link=f"https://github.com/apache/ignite/blob/{revision}/{PLAN}", + base_rfc=PLAN, earlier_revision=revision) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn(f"[{PLAN}](https://github.com/apache/ignite/blob/{BASE}/{PLAN})", summary) + + def test_link_must_point_to_an_rfc_file_in_this_repository(self): + """An unrelated link leaves the change without an RFC even when the base contains a plan.""" + for link, base_rfc in (("https://github.com/apache/ignite/pull/17", PLAN), + (PLAN_LINK.replace("apache/ignite", "other/ignite"), PLAN), + (PLAN_LINK.replace(PLAN, "rfcs/timeout.md"), "rfcs/timeout.md")): + with self.subTest(link=link): + result, summary = run_artifact_rename(link=link, base_rfc=base_rfc) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("rfcs/TEMPLATE.md", summary) + self.assertIn("Maven artifactId changed", summary) + + def test_linked_plan_must_still_exist_after_the_change(self): + """The link must still point to an RFC on the base branch after this PR's changes.""" + removed = {"filename": PLAN, "status": "removed"} + moved = {"filename": "docs/archive.md", "status": "renamed", "previous_filename": PLAN} + for base_rfc, edits in ((None, []), (PLAN, [removed]), (PLAN, [moved])): + with self.subTest(base_rfc=base_rfc, edits=edits): + result, summary = run_artifact_rename(*edits, link=PLAN_LINK, base_rfc=base_rfc) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("Maven artifactId changed", summary) + self.assertIn("rfcs/TEMPLATE.md", summary) + + def test_direct_rfc_link_does_not_hide_an_invalid_local_name(self): + """A PR adds a misnamed RFC and links a valid file. The author must still fix the name.""" + local = {"filename": "rfcs/timeout.md", "status": "added"} + result, summary = run_artifact_rename(local, link=PLAN_LINK, base_rfc=PLAN) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("Invalid RFC filename: rfcs/timeout.md", summary) + + def test_method_body_change_skips_rfc_checks(self): + """A PR edits a method body and adds a misnamed RFC. The check reports no contract change.""" + source = "package org.apache.ignite; public class IgniteCache { public int size() { return 1; } }" + edit = {"filename": PUBLIC_API, "status": "modified"} + rfc = {"filename": "rfcs/cache-timeout.md", "status": "added"} + sources = {("before", PUBLIC_API): source, ("after", PUBLIC_API): source.replace("return 1", "return 2")} + result, summary = run_checker([[edit, rfc]], sources=sources) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("No change was found by the static contract checks", summary) + self.assertNotIn("Reviewer action needed", summary) + + def test_empty_correctly_named_rfc_needs_no_action(self): + file = {"filename": "rfcs/IGNITE-123-cache-timeout.md", "status": "modified"} + result, summary = run_checker([[file]], title="IGNITE-456 Amend an existing RFC") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("Reviewer action needed", summary) + + def test_rfc_only_pr_passes_with_an_invalid_filename(self): + """When only an RFC changes, its filename does not affect the result.""" + file = {"filename": "rfcs/cache-timeout.md", "status": "added"} + result, summary = run_checker([[file]]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("No change was found by the static contract checks", summary) + self.assertNotIn("rfcs/cache-timeout.md", summary) + + def test_incomplete_file_list_requires_a_complete_pr(self): + """Given an API file count mismatch, the job stops before review and explains GitHub's limit.""" + result, summary = run_checker([[{"filename": PUBLIC_API, "status": "modified"}]], changed_files=3001) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("incomplete file list (1 of 3001)", result.stderr) + self.assertIn("3,000 files", summary) + + def test_changed_jdbc_mapping_loads_the_unchanged_sqlstate_file(self): + """A PR edits only the error mapping. The report shows the values a client receives.""" + core = "modules/core/src/main/java/org/apache/ignite/internal/processors/" + errors = core + "cache/query/IgniteQueryErrorCode.java" + states = core + "odbc/SqlStateCode.java" + expr = """package org.apache.ignite.internal.processors.cache.query; + class IgniteQueryErrorCode { + public static final int DUPLICATE_KEY = 4001; + static String codeToSqlState(int code) { + switch (code) { case DUPLICATE_KEY: return SqlStateCode.CONSTRAINT; + default: return SqlStateCode.INVALID; } + } + }""" + sources = {("before", errors): expr, + ("after", errors): expr.replace("return SqlStateCode.CONSTRAINT", "return SqlStateCode.INVALID"), + ("after", states): """package org.apache.ignite.internal.processors.odbc; + class SqlStateCode { static final String CONSTRAINT="23000", INVALID="22000"; }"""} + result, summary = run_checker([[{"filename": errors, "status": "modified"}]], sources=sources) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("require an RFC", summary) + self.assertIn("SQLState for error 4001 from 23000 to 22000", summary) diff --git a/.github/public-behavior/tests/test_check_pull_request.py b/.github/public-behavior/tests/test_check_pull_request.py new file mode 100644 index 0000000000000..562a7a3b3dfaa --- /dev/null +++ b/.github/public-behavior/tests/test_check_pull_request.py @@ -0,0 +1,107 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from contextlib import chdir +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch + +import check_pull_request as ci + + +DOC = "rfcs/IGNITE-123-sql.md" +PR = {"number": 42, "head": {"sha": "a" * 40}, "base": {"repo": {"full_name": "apache/ignite"}, "ref": "master", "sha": "b" * 40}, + "body_html": ""} +API = "modules/core/src/main/java/org/apache/ignite/IgniteCache.java" + + +def file(name, status="modified", **kwargs): + return dict(filename=name, status=status, **kwargs) + + +class CheckPullRequestTest(unittest.TestCase): + def test_only_actual_links_to_project_rfc_files_count(self): + """A link label, code sample, or file in a fork cannot identify the RFC.""" + parser = ci.RFCFileLinks("apache/ignite") + plan = f"https://github.com/apache/ignite/blob/master/{DOC}" + parser.feed(f'{plan}{plan}' + f'fork' + f'plan') + self.assertEqual(parser.targets, [("master", DOC)]) + + def test_an_unavailable_permalink_does_not_hide_a_working_link(self): + """A second link to the target branch identifies the plan even if a metadata request fails.""" + project = "https://github.com/apache/ignite" + old = "c" * 40 + body = f'old current' + failure = ci.CheckError("GitHub is unavailable.", "Re-run the check.", "") + with TemporaryDirectory() as root, chdir(root), patch.object(ci, "api", side_effect=failure) as request: + Path(DOC).parent.mkdir() + Path(DOC).touch() + result = ci.check([file(API)], {API: ["Added API method cacheTimeout"]}, dict(PR, body_html=body)) + self.assertTrue(result.advisory) + self.assertEqual(result.rfc_links, ((DOC, f"{project}/blob/{PR['base']['sha']}/{DOC}"),)) + request.assert_called_once_with(f"repos/apache/ignite/contents/{DOC}?ref={old}", exists=True) + + def test_implementation_only_and_standalone_rfc_pass_quietly(self): + for files in ([file(API)], [file(DOC)], [file("rfcs/TEMPLATE.md")]): + with self.subTest(files=files): + result = ci.check(files, {}, PR) + self.assertFalse(result.advisory) + self.assertEqual((result.author, result.reviewer, result.paths), ("", "", ())) + + def test_public_change_requires_a_proposal(self): + changes = {API: ["Added API method cacheTimeout"]} + with self.assertRaises(ci.CheckError) as caught: + ci.check([file(API)], changes, PR) + result = caught.exception.result + self.assertIn("require an RFC", result.reason) + self.assertIn("rfcs/TEMPLATE.md", result.author) + self.assertEqual(result.changes, changes) + + def test_removing_an_rfc_does_not_cover_a_public_change(self): + """Removing or moving a plan out of rfcs leaves the PR without an RFC file.""" + changes = {API: ["Added API method cacheTimeout"]} + for edit in (file(DOC, "removed"), file("docs/archive.md", "renamed", previous_filename=DOC)): + with self.subTest(edit=edit), self.assertRaises(ci.CheckError) as caught: + ci.check([file(API), edit], changes, PR) + self.assertIn("require an RFC", caught.exception.result.reason) + + def test_public_change_with_rfc_goes_to_review(self): + changes = {API: ["Added API method cacheTimeout"]} + for status in ("added", "modified"): + with self.subTest(status=status): + result = ci.check([file(API), file(DOC, status)], changes, PR) + self.assertTrue(result.advisory) + self.assertEqual(result.paths, (API,)) + self.assertEqual(result.rfc_links, ((DOC, f"https://github.com/apache/ignite/blob/{PR['head']['sha']}/{DOC}"),)) + self.assertEqual(result.changes, changes) + self.assertIn("vote on dev@", result.reviewer) + + def test_invalid_rfc_name_with_public_change(self): + """When a public method is added, a misnamed RFC fails with the path and an example.""" + changes = {API: ["Added API method cacheTimeout"]} + for name in ["rfcs/cache-timeout.md", "rfcs/IGNITE-timeout.md", "rfcs/IGNITE-42-.md", + "rfcs/IGNITE-42 two.md", "rfcs/IGNITE-42-timeout.txt", "rfcs/IGNITE-42-timeout", + "rfcs/IGNITE-42-timeout.markdown", "rfcs/IGNITE-42-timeout.adoc"]: + with self.subTest(name=name): + with self.assertRaises(ci.CheckError) as caught: + ci.check([file(API), file(name, "added")], changes, PR) + result = caught.exception.result + self.assertIn(f"Invalid RFC filename: {name}", result.reason) + self.assertIn("rfcs/IGNITE-12345-cache-timeout.md", result.author) + self.assertEqual(result.paths, (name, API)) + self.assertEqual(result.changes, changes) diff --git a/.github/public-behavior/tests/test_check_summary.py b/.github/public-behavior/tests/test_check_summary.py new file mode 100644 index 0000000000000..995ca16165cab --- /dev/null +++ b/.github/public-behavior/tests/test_check_summary.py @@ -0,0 +1,89 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from contextlib import chdir, redirect_stderr, redirect_stdout +from io import StringIO +import os +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch + +from check_summary import report, rules_reference + + +class CheckSummaryTest(unittest.TestCase): + def test_summary_lists_actions_and_displays_file_names_as_text(self): + """Given a flagged PR, report each role's next step and quote file names safely.""" + paths = ["a\n##[warning]"] + [f"public/path{i}" for i in range(8)] + with TemporaryDirectory() as directory: + summary = Path(directory) / "summary.md" + with patch.dict(os.environ, GITHUB_STEP_SUMMARY=str(summary), PUBLIC_BEHAVIOR_REVIEW_WARNING="true"), \ + redirect_stderr(StringIO()) as log, redirect_stdout(StringIO()) as annotations: + report(False, "Invalid RFC filename.", "Rename the file.", "Check the migration plan.", paths) + rendered = summary.read_text() + + self.assertIn("## Public behavior check failed", rendered) + self.assertIn(rules_reference(), rendered) + self.assertIn("### For the author\n\n

    Rename the file.

    ", rendered) + self.assertIn("### For the reviewer\n\n

    Check the migration plan.

    ", rendered) + self.assertIn("a</code>\\n##[warning]", rendered) + self.assertIn("See 1 more in the PR diff.", rendered) + self.assertNotIn("public/path7", rendered) + self.assertNotIn("##[warning]", log.getvalue()) + self.assertEqual(annotations.getvalue(), "") + + def test_passing_check_shows_what_to_review(self): + """When an RFC needs review, the main job warns once and the summary names the review task.""" + with TemporaryDirectory() as directory: + summary = Path(directory) / "summary.md" + with patch.dict(os.environ, GITHUB_STEP_SUMMARY=str(summary), PUBLIC_BEHAVIOR_REVIEW_WARNING="true"), \ + redirect_stdout(StringIO()) as log: + report(True, "A client protocol file changed.", "", "Check old clients.", advisory=True) + rendered = summary.read_text() + + self.assertTrue(rendered.startswith("## Public behavior to review\n")) + self.assertIn("🟡 Reviewer action needed", rendered) + self.assertIn("Check old clients.", rendered) + self.assertNotIn("For the author", rendered) + self.assertEqual(sum(line.startswith("::warning ") for line in log.getvalue().splitlines()), 1) + + def test_clean_check_reports_no_tasks_or_warnings(self): + """When the check finds no change, its only output is the result.""" + with patch.dict(os.environ, GITHUB_STEP_SUMMARY="", PUBLIC_BEHAVIOR_REVIEW_WARNING="true"), \ + redirect_stdout(StringIO()) as log: + report(True, "No contract changes found.", "", "") + + self.assertEqual(log.getvalue().strip(), "Public behavior check passed: No contract changes found.") + + def test_comment_reporter_does_not_repeat_warning(self): + """When the reporter checks the PR again, it renders the marker without a second annotation.""" + with patch.dict(os.environ, GITHUB_STEP_SUMMARY="", PUBLIC_BEHAVIOR_REVIEW_WARNING=""), \ + redirect_stdout(StringIO()) as log: + report(True, "An RFC was added.", "", "Review the API.", advisory=True) + self.assertNotIn("::warning", log.getvalue()) + + def test_links_to_the_process_document_available_on_apache(self): + """Use the PR until the process has landed in the trusted Ignite checkout.""" + with TemporaryDirectory() as directory, chdir(directory), patch.dict(os.environ, GITHUB_REPOSITORY="apache/ignite"): + self.assertIn("github.com/apache/ignite/pull/13760/files#diff-", rules_reference()) + path = Path("rfcs/IGNITE-29220-rfc-development-process.md") + path.parent.mkdir() + path.touch() + links = rules_reference() + self.assertIn("github.com/apache/ignite/blob/master/rfcs/IGNITE-29219-public-api-and-compatibility.md", links) + self.assertIn("github.com/apache/ignite/blob/master/rfcs/IGNITE-29220-rfc-development-process.md", links) + with patch.dict(os.environ, GITHUB_REPOSITORY="contributor/validation"): + self.assertIn("github.com/apache/ignite/pull/13760/files#diff-", rules_reference()) diff --git a/.github/public-behavior/tests/test_cli_contracts.py b/.github/public-behavior/tests/test_cli_contracts.py new file mode 100644 index 0000000000000..980c66a8167a9 --- /dev/null +++ b/.github/public-behavior/tests/test_cli_contracts.py @@ -0,0 +1,92 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from test_java_contracts import compare + + +CLI_DIR = "modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/" +MANAGEMENT = "modules/core/src/main/java/org/apache/ignite/internal/management/" +REGISTRY = MANAGEMENT + "IgniteCommandRegistry.java" +PARSER = CLI_DIR + "ArgumentParser.java" +HANDLER = CLI_DIR + "CommandHandler.java" + + +class CliContractsTest(unittest.TestCase): + def test_registered_commands_and_common_options(self): + registry = """package org.apache.ignite.internal.management; + class IgniteCommandRegistry extends CommandRegistryImpl { + IgniteCommandRegistry() { super(new StateCommand(), new SystemViewCommand()); } + }""" + parser = """package org.apache.ignite.internal.commandline; + class ArgumentParser { + static final String PORT = "--port"; + static final String UNUSED = "--unused"; + ArgumentParser() { + common.addAll(List.of(optionalArgument(PORT, Integer.class).withUsage("PORT").build(), + optionalArgument("--yes", boolean.class).build())); + } + }""" + before = {REGISTRY: registry, PARSER: parser} + after = {REGISTRY: registry.replace("new SystemViewCommand()", "new SetStateCommand()"), + PARSER: parser.replace('"--port"', '"--tcp-port"')} + self.assertCountEqual(compare(before, after), [ + f"{REGISTRY}\tRemoved CLI command --system-view", f"{REGISTRY}\tAdded CLI command --set-state", + f"{PARSER}\tRemoved CLI option --port", f"{PARSER}\tAdded CLI option --tcp-port", + ]) + + same_names = { + REGISTRY: registry.replace("new StateCommand(), new SystemViewCommand()", + "new commands.SystemViewCommand(), new StateCommand()"), + PARSER: parser.replace("PORT", "CONNECTION_PORT").replace("--unused", "--other") + .replace("Integer.class", "int.class"), + } + self.assertEqual(compare(before, same_names), []) + + self.assertEqual(compare({PARSER: parser}, {PARSER: parser.replace("Integer.class", "Long.class")}), + [f"{PARSER}\tChanged CLI option --port type from int to long"]) + self.assertEqual(compare({PARSER: parser}, {PARSER: parser.replace("Integer.class", "portType()")}), []) + + delegated = {REGISTRY: registry.replace("new SystemViewCommand()", "systemView()"), + PARSER: parser.replace('"--port"', 'Prefix.CLI + "port"')} + self.assertEqual(compare(before, delegated), []) + moved = {REGISTRY: registry.replace(", new SystemViewCommand()", "") + .replace("StateCommand());", "StateCommand()); registerSystemView();")} + self.assertEqual(compare({REGISTRY: registry}, moved), []) + + def test_exit_codes_returned_by_the_control_utility(self): + src = """package org.apache.ignite.internal.commandline; + class CommandHandler { + static final int EXIT_CODE_INVALID_ARGUMENTS = 1; + static final int UNUSED = 2; + int execute(List args) { + IntSupplier helper = () -> { return UNUSED; }; + return EXIT_CODE_INVALID_ARGUMENTS; + } + }""" + edited = src.replace("UNUSED = 2", "UNUSED = 4").replace("ARGUMENTS = 1", "ARGUMENTS = 6") + self.assertEqual(compare({HANDLER: src}, {HANDLER: edited}), + [f"{HANDLER}\tChanged CLI exit code for EXIT_CODE_INVALID_ARGUMENTS from 1 to 6"]) + for status in (src.replace("EXIT_CODE_INVALID_ARGUMENTS", "INVALID"), + src.replace("ARGUMENTS = 1", "ARGUMENTS = Defaults.INVALID")): + with self.subTest(status=status): + self.assertEqual(compare({HANDLER: src}, {HANDLER: status}), []) + + # Swapping two field names and their uses preserves both return values. + both = src.replace("return EXIT_CODE_INVALID_ARGUMENTS;", + "if (args.isEmpty()) return UNUSED; return EXIT_CODE_INVALID_ARGUMENTS;") + swapped = both.replace("UNUSED", "TMP").replace("EXIT_CODE_INVALID_ARGUMENTS", "UNUSED") + self.assertEqual(compare({HANDLER: both}, {HANDLER: swapped.replace("TMP", "EXIT_CODE_INVALID_ARGUMENTS")}), []) diff --git a/.github/public-behavior/tests/test_contract_context.py b/.github/public-behavior/tests/test_contract_context.py new file mode 100644 index 0000000000000..4198a3bda4c4a --- /dev/null +++ b/.github/public-behavior/tests/test_contract_context.py @@ -0,0 +1,78 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from pathlib import PurePosixPath +import unittest + +from cli_sources import CLI_RULE_SOURCES, ROOT_REGISTRY, cli_packages +from contract_diff import changed_contracts +from test_subcommand_arguments import builtin, DTO +from test_system_view_columns import CACHES, REGISTRY, REGISTER, ROW +from view_sources import VIEW_RULE_SOURCES + + +def pr_changes(base, edits): + """Run a PR diff with unchanged registrations supplied by GitHub at the requested revision.""" + def api(route, *, raw=False, fields=None, optional=False): + if "/compare/" in route: + return {"merge_base_commit": {"sha": "branch-point"}} + if route == "graphql": + revision, package = fields["path"].split(":") + assert revision == "branch-point" + entries = [{"type": "blob", "name": PurePosixPath(path).name, "object": {"text": src, "isTruncated": False}} + for path, src in base.items() if str(PurePosixPath(path).parent) == package] + return {"data": {"repository": {"object": {"entries": entries}}}} + assert raw + path, rev = route.split("/contents/")[1].split("?ref=") + assert rev in {"branch-point", "head"} + if rev == "head" and path in edits: + return edits[path] + if optional: + return base.get(path) + return base[path] + + files = [{"filename": path, "status": "modified" if path in base else "added"} for path in edits] + return changed_contracts(files, "apache/ignite", "target-tip", "head", api) + + +class ContractContextTest(unittest.TestCase): + def test_cli_arguments_use_the_snapshot_of_the_registered_family(self): + """A DTO changes alone. The command and its unchanged registries still prove which flag changed.""" + before = builtin("@Argument(optional=true) boolean groups;") + renamed = before[DTO].replace("boolean groups", "boolean showGroups") + self.assertCountEqual(pr_changes(before, {DTO: renamed})[DTO], + ["Removed CLI option --cache list --groups", "Added CLI option --cache list --show-groups"]) + parser = next(path for path in CLI_RULE_SOURCES if path.endswith("/CommandUtils.java")) + self.assertEqual(pr_changes(before, {DTO: renamed, parser: "// different argument naming rules"}), {}) + self.assertEqual(pr_changes({k: v for k, v in before.items() if k != ROOT_REGISTRY}, {DTO: renamed}), {}) + + def test_new_dto_alone_cannot_change_an_existing_binding(self): + self.assertEqual(pr_changes({}, {DTO: builtin("@Argument boolean groups;")[DTO]}), {}) + + def test_nested_cli_packages_include_the_parent_registry(self): + """A DTO under cache/scan uses both that package and the cache registry.""" + nested = DTO.replace("/cache/", "/cache/scan/") + self.assertEqual(cli_packages([nested]), {str(PurePosixPath(nested).parent), str(PurePosixPath(DTO).parent)}) + + def test_view_order_uses_the_registration_at_the_pr_revision(self): + """A changed row produces a finding only when the registration and generator still support the inference.""" + before = {CACHES: ROW, REGISTRY: REGISTER} + reordered = ROW.replace("@Order(1)", "@Order(-1)") + findings = pr_changes(before, {CACHES: reordered})[CACHES] + self.assertTrue(any("cacheId moved from position 2 to 1" in finding for finding in findings), findings) + generator = next(path for path in VIEW_RULE_SOURCES if path.endswith("/SystemViewRowAttributeWalkerGenerator.java")) + for also_changed in ({REGISTRY: REGISTER.replace("new CacheViewWalker()", "custom")}, + {generator: "// new generator rules"}): + self.assertEqual(pr_changes(before, {CACHES: reordered, **also_changed}), {}) diff --git a/.github/public-behavior/tests/test_contract_paths.py b/.github/public-behavior/tests/test_contract_paths.py new file mode 100644 index 0000000000000..6e9474336d286 --- /dev/null +++ b/.github/public-behavior/tests/test_contract_paths.py @@ -0,0 +1,30 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from contract_paths import java_contract_source + + +class ContractPathsTest(unittest.TestCase): + def test_only_supported_java_sources_are_parsed(self): + core = "modules/core/src/main/java/org/apache/ignite/" + self.assertTrue(java_contract_source(core + "IgniteCache.java")) + self.assertTrue(java_contract_source(core + "internal/processors/odbc/SqlStateCode.java")) + for path in ("rfcs/TEMPLATE.md", "modules/core/pom.xml", core + "internal/IgniteKernal.java", + core + "spi/discovery/tcp/messages/TcpDiscoveryPingRequest.java", + "modules/core/src/test/java/org/apache/ignite/CacheTest.java"): + with self.subTest(path=path): + self.assertFalse(java_contract_source(path)) diff --git a/.github/public-behavior/tests/test_contract_values.py b/.github/public-behavior/tests/test_contract_values.py new file mode 100644 index 0000000000000..bed7658136f14 --- /dev/null +++ b/.github/public-behavior/tests/test_contract_values.py @@ -0,0 +1,59 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from contract_values import contract_values, supports_values + + +CORE = "modules/core/pom.xml" +CORE_POM = """ + org.apache.igniteignite-parent-internal + ignite-core + ${revision} + cache-api + +""" + + +class ContractValuesTest(unittest.TestCase): + def test_coordinates_can_use_the_parent_group(self): + """The core module declares its own artifactId and inherits its group's literal name.""" + expected = {"Maven groupId": "org.apache.ignite", "Maven artifactId": "ignite-core"} + self.assertEqual(contract_values(CORE, CORE_POM), expected) + edited = CORE_POM.replace("ignite-core", "ignite-runtime") + self.assertEqual(contract_values(CORE, edited), {**expected, "Maven artifactId": "ignite-runtime"}) + + def test_unrelated_changes_preserve_the_coordinates(self): + """Updating a version, dependency, or comment leaves both published coordinates unchanged.""" + edited = (CORE_POM.replace("${revision}", "2.19.0").replace("cache-api", "cache-api-next") + .replace("documentation example", "other-example")) + self.assertEqual(contract_values(CORE, edited), contract_values(CORE, CORE_POM)) + + def test_explicit_group_overrides_the_parent(self): + """An explicit group wins over its parent even when its value cannot be resolved.""" + edited = CORE_POM.replace("ignite-core", "org.newignite-core") + self.assertEqual(contract_values(CORE, edited)["Maven groupId"], "org.new") + self.assertEqual(contract_values(CORE, edited.replace("org.new", "${ignite.group}")), + {"Maven artifactId": "ignite-core"}) + + def test_incomplete_documents_and_unrelated_paths_produce_no_values(self): + """A missing model or an unrelated file provides no evidence of an artifact rename.""" + self.assertTrue(supports_values("modules/bom/pom.xml")) + self.assertFalse(supports_values("examples/pom.xml")) + self.assertEqual(contract_values("examples/pom.xml", CORE_POM), {}) + for source in ("x", ""): + with self.subTest(source=source): + self.assertEqual(contract_values(CORE, source), {}) diff --git a/.github/public-behavior/tests/test_format_and_package_contracts.py b/.github/public-behavior/tests/test_format_and_package_contracts.py new file mode 100644 index 0000000000000..4ed76a58c10f2 --- /dev/null +++ b/.github/public-behavior/tests/test_format_and_package_contracts.py @@ -0,0 +1,126 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from contract_diff import compare_sources + + +def changes(before, after): + sources = {(side, path): src for side, snapshot in (("before", before), ("after", after)) + for path, src in snapshot.items()} + return compare_sources([(path, path) for path in before], sources) + + +CORE = "modules/core/src/main/java/org/apache/ignite/internal/" +WAL = CORE + "pagemem/wal/record/WALRecord.java" +PAGE = CORE + "processors/cache/persistence/file/FilePageStore.java" +META = CORE + "processors/cache/persistence/snapshot/SnapshotMetadata.java" +BINARY = "modules/binary/api/src/main/java/org/apache/ignite/internal/binary/GridBinaryMarshaller.java" +ODBC = "modules/platforms/cpp/odbc/module.def" +NUGET = "modules/platforms/dotnet/Apache.Ignite.Core/Apache.Ignite.Core.csproj" +XSD = NUGET.rsplit("/", 1)[0] + "/IgniteConfigurationSection.xsd" +BOM = "modules/bom/pom.xml" + + +class FormatAndPackageContractsTest(unittest.TestCase): + def test_persisted_numbers_and_wire_tags(self): + """Changing a literal used in a stored file or binary object identifies that format.""" + before = { + WAL: "package org.apache.ignite.internal.pagemem.wal.record; class WALRecord { enum RecordType {" + "PAGE_RECORD(1, PHYSICAL), RESERVED(9); RecordType(int i, Object... p) {} } }", + PAGE: "package org.apache.ignite.internal.processors.cache.persistence.file; class FilePageStore {" + "private static final long SIGNATURE = 0xABCDL; static final int DFLT_BUFFER = 42; }", + META: "package org.apache.ignite.internal.processors.cache.persistence.snapshot; class SnapshotMetadata {" + "private static final long serialVersionUID = 0L; }", + BINARY: "package org.apache.ignite.internal.binary; class GridBinaryMarshaller {" + "public static final byte STRING=9, OBJ=(byte)103; }", + } + after = {WAL: before[WAL].replace("(1,", "(8,").replace("(9)", "(10)"), + PAGE: before[PAGE].replace("0xABCD", "0xABCE").replace("42", "53"), + META: before[META].replace("0L", "1L"), BINARY: before[BINARY].replace("=9,", "=17,")} + self.assertEqual(changes(before, after), { + WAL: ["Changed WAL record index for PAGE_RECORD from 1 to 8"], + PAGE: ["Changed FilePageStore header SIGNATURE from 43981 to 43982"], + META: ["Changed SnapshotMetadata serialization version from 0 to 1"], + BINARY: ["Changed binary type code for STRING from 9 to 17"], + }) + after = {WAL: before[WAL].replace("PAGE_RECORD", "PAGE"), META: before[META], + PAGE: before[PAGE].replace("0xABCDL", "43981L"), BINARY: before[BINARY].replace("(byte)103", "103")} + self.assertEqual(changes(before, after), {}) + + def test_sqlstate_mapping_resolves_both_constants(self): + """JDBC returns a different SQLState for the same numeric Ignite error.""" + errors = CORE + "processors/cache/query/IgniteQueryErrorCode.java" + states = CORE + "processors/odbc/SqlStateCode.java" + before = {errors: """package org.apache.ignite.internal.processors.cache.query; + class IgniteQueryErrorCode { public static final int DUPLICATE_KEY = 4001; + static String codeToSqlState(int code) { + switch (code) { case DUPLICATE_KEY: return SqlStateCode.CONSTRAINT; + default: return SqlStateCode.INVALID; } + } }""", states: """package org.apache.ignite.internal.processors.odbc; + class SqlStateCode { public static final String CONSTRAINT="23000", INVALID="22000"; }"""} + after = dict(before, **{errors: before[errors].replace("SqlStateCode.CONSTRAINT", "SqlStateCode.INVALID")}) + self.assertEqual(changes(before, after), {errors: ["Changed SQLState for error 4001 from 23000 to 22000"]}) + fallback = before[errors].replace("case DUPLICATE_KEY: return SqlStateCode.CONSTRAINT;", "") + self.assertEqual(changes(before, {**before, errors: fallback}), + {errors: ["Changed SQLState for error 4001 from 23000 to 22000"]}) + after = {k: v.replace("CONSTRAINT", "CONSTRAINT_VIOLATION") for k, v in before.items()} + self.assertEqual(changes(before, after), {}) + + def test_published_manifest_entries(self): + """A public package, exported ODBC name or managed dependency changes in its manifest.""" + before = {ODBC: "LIBRARY ignite.odbc.dll\nEXPORTS\nSQLAllocConnect\nSQLDisconnect\n", + NUGET: 'Apache.Ignite' + 'netstandard2.0', + "parent/pom.xml": "17" + "", + BOM: "org.apache.ignite" + "${project.groupId}ignite-core" + ""} + after = {ODBC: before[ODBC].replace("SQLAllocConnect\n", ""), NUGET: before[NUGET].replace("Apache.Ignite", "Ignite"), + "parent/pom.xml": before["parent/pom.xml"].replace("17", "21"), + BOM: before[BOM].replace("ignite-core", "ignite-new")} + self.assertEqual(changes(before, after), { + ODBC: ["Removed Windows ODBC export: SQLAllocConnect"], NUGET: ["NuGet package ID changed from Apache.Ignite to Ignite."], + BOM: ["Removed Maven BOM dependency: org.apache.ignite:ignite-core", + "Added Maven BOM dependency: org.apache.ignite:ignite-new"], + "parent/pom.xml": ["Java release for compiled artifacts changed from 17 to 21."], + }) + same = before[BOM].replace("", " jar compile ") + self.assertEqual(changes({BOM: before[BOM]}, {BOM: same}), {}) + imported = before[BOM].replace("", "pomimport") + self.assertEqual(changes({BOM: before[BOM]}, {BOM: imported}), {}) + self.assertEqual(changes({ODBC: before[ODBC]}, {ODBC: before[ODBC].replace("SQLDisconnect", "SQLDisconnect=impl")}), {}) + + def test_dotnet_configuration_schema(self): + """A configuration file accepts different enum values or requires a previously optional attribute.""" + schema = ('' + '' + '' + '') + self.assertEqual(changes({XSD: schema}, {XSD: schema.replace("Atomic", "Local").replace("optional", "required")}), + {XSD: ["XML configuration /config/@host use changed from optional to required.", + "Removed XML configuration values for cacheMode: Atomic", + "Added XML configuration values for cacheMode: Local"]}) + + def test_equivalent_values_in_shipped_manifests(self): + """Configuration booleans and NuGet IDs have equivalent external spellings.""" + schema = ('' + '' + '') + project = 'Apache.Ignite' + self.assertEqual(changes({XSD: schema, NUGET: project}, + {XSD: schema.replace('"false"', '"0"'), NUGET: project.replace("Apache.Ignite", "apache.ignite")}), {}) diff --git a/.github/public-behavior/tests/test_java_contracts.py b/.github/public-behavior/tests/test_java_contracts.py new file mode 100644 index 0000000000000..0a0e51230428b --- /dev/null +++ b/.github/public-behavior/tests/test_java_contracts.py @@ -0,0 +1,140 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import unittest + +from contract_diff import java_changes + + +def compare(before, after): + """Run the workflow's JDK parser on both snapshots.""" + sources = [((side, path), source) for side, files in (("before", before), ("after", after)) + for path, source in files.items()] + return ["\t".join(row) for row in java_changes(sources)] + + +class JavaContractsTest(unittest.TestCase): + def test_reports_api_declarations_and_literal_values(self): + before = {"api/Client.java": """package api; +public interface Client { int TIMEOUT = 3; int read(String key); void remove(); }"""} + after = {"api/Client.java": """package api; +public interface Client { int TIMEOUT = 5; long read(String key); void put(int key); }"""} + self.assertEqual(compare(before, after), [ + "api/Client.java\tChanged API constant api.Client.TIMEOUT from 3 to 5", + "api/Client.java\tAdded API method api.Client.put (1 parameter)", + "api/Client.java\tChanged API method api.Client.read (1 parameter) from public (String) -> int to public (String) -> long", + "api/Client.java\tRemoved API method api.Client.remove (0 parameters)", + ]) + + def test_preserves_contract_across_source_only_edits(self): + before = {"old/Client.java": """package api; +import java.util.List; +public class Client { + public List list(String key) { throw new UnsupportedOperationException(); } + private class Helper { public void foo() {} } +}"""} + after = {"new/Client.java": """package api; +public class Client { + private class Helper { public void bar() {} } + @Override public String toString() { return "client"; } + public java.util.List list(String name) { + class Local { public int unrelated() { return 1; } } + return new java.util.ArrayList<>(); + } +}"""} + self.assertEqual(compare(before, after), []) + + def test_ignores_inherited_methods_without_type_information(self): + before = {"api/Child.java": "package api; public class Child extends Parent {}"} + after = {"api/Child.java": "package api; public class Child extends Parent { public void inherited() {} }"} + self.assertEqual(compare(before, after), []) + + def test_equal_literal_values_after_field_conversion(self): + before = {"Settings.java": 'public class Settings { public static final double RATE = 1;' + " public static final int CODE = 'A'; }"} + after = {"Settings.java": "public class Settings { public static final double RATE = 1.0;" + " public static final int CODE = 65; }"} + self.assertEqual(compare(before, after), []) + + def test_members_can_move_to_an_unknown_parent(self): + own = {"Settings.java": "public class Settings { public int timeout() { return 1; }" + " public static final int DEFAULT = 1; }"} + inherited = {"Settings.java": "public class Settings extends Base {}"} + self.assertEqual(compare(own, inherited), []) + self.assertEqual(compare(inherited, own), []) + + def test_removed_deprecated_api_is_left_to_review(self): + before = {"Api.java": """public interface Api { + @java.lang.Deprecated void oldMethod(); + @Deprecated int OLD_SETTING = 5; + @Deprecated class Legacy { public void read() {} } + }"""} + after = {"Api.java": "public interface Api { void newMethod(); }"} + self.assertEqual(compare(before, after), ["Api.java\tAdded API method Api.newMethod (0 parameters)"]) + + def test_protocol_values_track_wire_ids_across_java_renames(self): + pkg = "package org.apache.ignite.internal.client.thin;" + before = {"ClientOperation.java": pkg + " enum ClientOperation { CACHE(1), READ(-1); ClientOperation(int n) {} }"} + after = {"ClientOperation.java": pkg + " enum ClientOperation { RENAMED(1), READ(3); ClientOperation(int n) {} }"} + self.assertEqual(compare(before, after), [ + "ClientOperation.java\tChanged client operation ID for READ from -1 to 3"]) + + def test_swapping_existing_wire_ids_reports_both_operations(self): + pkg = "package org.apache.ignite.internal.client.thin;" + before = {"ClientOperation.java": pkg + " enum ClientOperation { A(1), B(2); ClientOperation(int n) {} }"} + after = {"ClientOperation.java": pkg + " enum ClientOperation { B(1), A(2); ClientOperation(int n) {} }"} + self.assertEqual(compare(before, after), [ + "ClientOperation.java\tChanged client operation ID for A from 1 to 2", + "ClientOperation.java\tChanged client operation ID for B from 2 to 1"]) + + def test_added_wire_file_lists_its_known_values(self): + after = {"ClientBitmaskFeature.java": "package org.apache.ignite.internal.processors.platform.client;" + " enum ClientBitmaskFeature { A(1); ClientBitmaskFeature(int n) {} }"} + self.assertEqual(compare({}, after), ["ClientBitmaskFeature.java\tAdded client feature ID 1"]) + self.assertEqual(compare(after, {}), ["ClientBitmaskFeature.java\tRemoved client feature ID 1"]) + + def test_sql_states_are_values_even_with_duplicate_names(self): + pkg = "package org.apache.ignite.internal.processors.odbc;" + before = {"SqlStateCode.java": pkg + ' class SqlStateCode { public static final String E="02000", F="01000"; }'} + after = {"SqlStateCode.java": pkg + ' class SqlStateCode { public static final String A="02000", B="02000", F="22000"; }'} + self.assertEqual(compare(before, after), [ + "SqlStateCode.java\tChanged SQLState for F from 01000 to 22000"]) + + def test_sql_error_codes_use_the_declared_integer_value(self): + pkg = "package org.apache.ignite.internal.processors.cache.query;" + before = {"IgniteQueryErrorCode.java": pkg + " class IgniteQueryErrorCode { public static final int E='A'; }"} + after = {"IgniteQueryErrorCode.java": pkg + " class IgniteQueryErrorCode { public static final int E=65;" + ' public static final String DESCRIPTION="example"; }'} + self.assertEqual(compare(before, after), []) + + def test_parse_error_does_not_report_a_removal_or_hide_other_files(self): + src = "package api; public class Valid { public void newSetting() {} }" + before = {"api/Bad.java": "package api; public class Bad { public int run() { return 1; } }"} + after = {"api/Bad.java": "package api; public class Bad { public int }", "api/Valid.java": src} + rows = compare(before, after) + self.assertTrue(any("Added API method api.Valid.newSetting" in row for row in rows), rows) + self.assertFalse(any("Bad" in row for row in rows), rows) + + def test_constructors_of_derived_classes_and_public_enum_members(self): + """A new constructor needs no inherited-method resolution. Enum members keep their source names.""" + before = {"Client.java": "public class Client extends Base { public Client(String s) {} }", + "Mode.java": "public enum Mode implements Marker { FIRST, SECOND }"} + after = {"Client.java": before["Client.java"].replace("String s", "long value"), + "Mode.java": before["Mode.java"].replace("SECOND", "THIRD")} + self.assertCountEqual(compare(before, after), [ + "Client.java\tChanged API constructor Client (1 parameter) from public (String) to public (long)", + "Mode.java\tRemoved API enum value Mode.SECOND", "Mode.java\tAdded API enum value Mode.THIRD"]) + self.assertEqual(compare(before, {**before, "Mode.java": before["Mode.java"].replace("FIRST, SECOND", "SECOND, FIRST")}), []) diff --git a/.github/public-behavior/tests/test_launcher_contracts.py b/.github/public-behavior/tests/test_launcher_contracts.py new file mode 100644 index 0000000000000..f9b270821bad4 --- /dev/null +++ b/.github/public-behavior/tests/test_launcher_contracts.py @@ -0,0 +1,64 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest + +from launcher_contracts import launcher_changes, supports_launcher + + +UNIX = '''checkJava() { + javaMajorVersion "$JAVA" + + if [ $version -lt 17 ]; then + echo "Please point JAVA_HOME variable to installation of JDK 17 or later." + exit 1 + fi +} +''' +WINDOWS = '''if exist "%JAVA_HOME%\\bin\\java.exe" goto checkJdkVersion +:checkJdkVersion +if %MAJOR_JAVA_VER% == 1 set MAJOR_JAVA_VER=%MINOR_JAVA_VER% + +if %MAJOR_JAVA_VER% LSS 17 ( + echo Please point JAVA_HOME variable to installation of JDK 17 or later. + goto error_finish +) +:error_finish +goto :eof +''' + + +class LauncherContractsTest(unittest.TestCase): + def test_launcher_rejects_a_different_java_version(self): + for path, script in (("bin/include/functions.sh", UNIX), ("bin/ignite.bat", WINDOWS), + ("bin/index-reader.bat", WINDOWS), ("bin/control.bat", WINDOWS.replace("\n", "\r\n"))): + with self.subTest(path=path): + self.assertTrue(supports_launcher(path)) + self.assertEqual(launcher_changes(path, script, script.replace("17", "21")), + ["Changed minimum Java version accepted by the launcher from 17 to 21."]) + + def test_message_or_another_version_check_is_not_a_startup_requirement(self): + self.assertFalse(supports_launcher("tools/test.bat")) + self.assertEqual(launcher_changes("tools/test.bat", WINDOWS, WINDOWS.replace("17", "21")), []) + self.assertEqual(launcher_changes("bin/include/functions.sh", UNIX, UNIX.replace("JDK 17", "JDK 21")), []) + for old, new in (("exit 1", "exit 0"), ("exit 1", "return"), ("-lt", "-eq"), + ("checkJava()", "printExample()")): + with self.subTest(edit=new): + edited = UNIX.replace(old, new).replace("17", "21") + self.assertEqual(launcher_changes("bin/include/functions.sh", UNIX, edited), []) + self.assertEqual(launcher_changes("bin/control.bat", WINDOWS, + WINDOWS.replace("17", "21").replace("goto error_finish", "echo error")), []) + continues = WINDOWS.replace("goto :eof", "goto launch") + self.assertEqual(launcher_changes("bin/control.bat", continues, continues.replace("17", "21")), []) diff --git a/.github/public-behavior/tests/test_post_pr_comment.py b/.github/public-behavior/tests/test_post_pr_comment.py new file mode 100644 index 0000000000000..550557ea1ab77 --- /dev/null +++ b/.github/public-behavior/tests/test_post_pr_comment.py @@ -0,0 +1,306 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from contextlib import redirect_stdout +from copy import deepcopy +from io import StringIO +import json +import os +from pathlib import Path +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch + +import post_pr_comment as rc +from check_summary import report + + +REPO = "apache/ignite" +FORK = {"full_name": "contributor/ignite"} +RUN = {"status": "completed", "conclusion": "failure", "event": "pull_request", + "repository": {"full_name": REPO}, "head_repository": FORK, "head_sha": "a" * 40, + "head_branch": "proposal", "path": ".github/workflows/check-public-behavior.yml", "id": 12, "run_attempt": 1, + "pull_requests": [], "display_title": "Public behavior changes for PR #42"} +PR = {"state": "open", "number": 42, "head": {"ref": "proposal", "sha": RUN["head_sha"], "repo": FORK}, + "base": {"ref": "master", "sha": "b" * 40, "repo": RUN["repository"]}, + "title": "IGNITE-123 Proposal", "body": ""} +BOT = {"login": "github-actions[bot]", "type": "Bot"} +ADVISORY_TITLE = "Public behavior to review" +CHECKS_LINK = f"[Open PR checks](https://github.com/{REPO}/pull/42/checks)" + + +class PostPrCommentTest(unittest.TestCase): + def setUp(self): + """Expose a fork PR, its workflow runs and its comments through a local GitHub API fixture.""" + self.pr = deepcopy(PR) + self.comments = [] + self.writes = [] + self.runs = [RUN] + self.jobs = [{"name": "Public behavior changes", "conclusion": "failure"}] + directory = TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.enterContext(patch.dict(os.environ, GITHUB_OUTPUT=str(self.root / "output"))) + self.enterContext(patch.object(rc, "api", self.read)) + self.enterContext(patch.object(rc, "update", self.write)) + + def read(self, route, *, pages=False): + prefix = f"repos/{REPO}" + if route == f"{prefix}/actions/runs/12/attempts/1/jobs?per_page=100": + return {"jobs": self.jobs} + if route == f"{prefix}/actions/runs/13/attempts/1/jobs?per_page=100": + return {"jobs": [{"name": "Public behavior changes", "conclusion": "success"}]} + if route == (f"{prefix}/actions/workflows/check-public-behavior.yml/runs?head_sha={RUN['head_sha']}" + "&status=completed&per_page=100&page=1"): + return {"total_count": len(self.runs), "workflow_runs": self.runs} + if route == f"{prefix}/pulls/42": + return self.pr + if route == f"{prefix}/issues/42/comments?per_page=100": + self.assertTrue(pages) + return self.comments + self.fail(f"Unexpected request to {route}") + + def write(self, method, route, body=None): + self.writes.append(method) + if method == "POST": + self.assertEqual(route, f"repos/{REPO}/issues/42/comments") + self.comments.append({"id": self.next_id, "body": body, "user": BOT}) + elif method == "DELETE": + self.comments = [c for c in self.comments if route != f"repos/{REPO}/issues/comments/{c['id']}"] + else: + self.fail(f"Unexpected request {method}") + + @property + def next_id(self): + return max([0] + [c["id"] for c in self.comments]) + 1 + + def prepare(self): + """Capture the current PR for the trusted checker.""" + filename = self.root / "pr.json" + rc.prepare(REPO, RUN, filename) + return json.loads(filename.read_text()) + + def publish(self, context, outcome, text="", *, original=None, title=None): + """Write the trusted summary and pair it with the original job outcome.""" + summary = self.root / "summary.md" + if title is None: + title = "Public behavior check passed" if outcome == "success" else "Public behavior check failed" + summary.write_text(f"## {title}\n\n{text}\n\n{rc.rules_reference()}\n") + rc.publish(REPO, RUN, dict(context, source_conclusion=original or outcome), summary, outcome) + + def test_prepare_resolves_fork_and_skips_an_unrelated_job(self): + """Given a fork run without a PR number, resolve its current PR only for the public behavior job.""" + self.jobs[0]["name"] = "Public behavior check tests" + rc.prepare(REPO, RUN, self.root / "pr.json") + self.assertFalse((self.root / "output").exists()) + self.jobs[0]["name"] = "Public behavior changes" + self.pr["body"] = "See https://github.com/apache/ignite/blob/master/rfcs/IGNITE-123-sql.md" + context = self.prepare() + self.assertEqual(context["pull_request"], + {"number": 42, "head": {"sha": PR["head"]["sha"]}, "base": {"sha": PR["base"]["sha"]}, + "body": self.pr["body"]}) + self.assertEqual(context["source_conclusion"], "failure") + self.assertIn(f"pr_number=42\nbase_sha={PR['base']['sha']}\n", (self.root / "output").read_text()) + + def test_skips_review_events(self): + """When a review triggers a workflow on a fork, leave the PR alone.""" + dest = self.root / "pr.json" + rc.prepare(REPO, dict(RUN, event="pull_request_review"), dest) + self.assertFalse(dest.exists()) + + def test_run_must_match_the_head_repository_and_pr(self): + """When the same commit is reported for another repository or PR, skip the report.""" + dest = self.root / "pr.json" + for details in ({"head_repository": {"full_name": REPO}}, {"pull_requests": [{"number": 17}]}): + with self.subTest(details=details): + rc.prepare(REPO, dict(RUN, **details), dest) + self.assertFalse(dest.exists()) + + def test_run_title_alone_cannot_select_a_different_pr(self): + """Given a run title from a fork, require the exact template and matching live head before checking.""" + dest = self.root / "pr.json" + rc.prepare(REPO, dict(RUN, display_title="A reference to Public behavior changes for PR #42"), dest) + self.assertFalse(dest.exists()) + rc.prepare(REPO, dict(RUN, head_sha="9" * 40), dest) + self.assertFalse(dest.exists()) + rc.prepare(REPO, RUN, dest) + self.assertTrue(dest.exists()) + + def test_posts_changed_guidance_and_a_single_resolution(self): + """Given repeated runs, post new guidance and a resolution only when the situation changes.""" + context = self.prepare() + self.publish(context, "success", "No matching paths.") + self.assertEqual(self.writes, []) + self.publish(context, "failure", "Use the required RFC filename.") + self.assertEqual(self.writes, ["POST"]) + self.publish(context, "failure", "Use the required RFC filename.") + self.assertEqual(self.writes, ["POST"]) + + copied_marker = {**self.comments[0], "id": 98, "user": {"login": "contributor", "type": "User"}} + self.comments.append(copied_marker) + self.publish(context, "failure", "Include the Jira number in the filename.") + self.assertEqual(self.writes[-2:], ["POST", "DELETE"]) + self.assertIn("Include the Jira number in the filename.", self.comments[-1]["body"]) + self.publish(context, "success", "RFC filename checked.") + self.assertEqual(self.writes, ["POST", "POST", "DELETE", "POST", "DELETE"]) + self.assertIn("The check passed. There is nothing left to flag in this PR.", self.comments[-1]["body"]) + self.assertNotIn(rc.rules_reference(), self.comments[-1]["body"]) + self.publish(context, "success", "No matching paths.") + self.assertEqual(len(self.writes), 5) + self.assertIn(copied_marker, self.comments) + + def test_posts_review_guidance_on_the_first_green_run(self): + """When the first check finds an RFC, publish its review marker even though the job passed.""" + self.jobs[0]["conclusion"] = "success" + summary = self.root / "summary.md" + path = "rfcs/IGNITE-123-sql.md" + file_url = f"https://github.com/{REPO}/blob/{PR['base']['sha']}/{path}" + with patch.dict(os.environ, GITHUB_STEP_SUMMARY=str(summary)), redirect_stdout(StringIO()): + report(True, "This PR links to an existing RFC.", "", "Review the SQL result.", + advisory=True, rfc_links=((path, file_url),)) + rc.publish(REPO, RUN, self.prepare(), summary, "success") + self.assertEqual(self.writes, ["POST"]) + body = self.comments[0]["body"] + self.assertIn("## Public behavior to review", body) + self.assertIn("🟡 Reviewer action needed", body) + self.assertIn("Review the SQL result.", body) + self.assertIn(f"[{path}]({file_url})", body) + self.assertIn(CHECKS_LINK, body) + self.assertNotIn("resolved", body) + + def test_fixed_error_keeps_remaining_review_guidance(self): + """When an RFC error is fixed, confirm the fix and keep the advice until the affected code changes.""" + context = self.prepare() + self.publish(context, "failure", "Use the required RFC filename.") + self.publish(context, "success", "Review the SQL result.", title=ADVISORY_TITLE) + self.assertEqual(self.writes, ["POST", "POST", "DELETE"]) + self.assertEqual(len(self.comments), 1) + self.assertIn("The issues from the previous check are resolved.", self.comments[0]["body"]) + self.assertIn("Review the SQL result.", self.comments[0]["body"]) + + self.publish(context, "success", "Review the SQL result.", title=ADVISORY_TITLE) + self.assertEqual(self.writes, ["POST", "POST", "DELETE"]) + self.publish(context, "success", "No matching paths.") + self.assertEqual(self.writes[-2:], ["POST", "DELETE"]) + self.assertEqual(len(self.comments), 1) + self.assertIn("There is nothing left to flag in this PR.", self.comments[0]["body"]) + self.assertNotIn("issues", self.comments[0]["body"]) + self.publish(context, "success", "No matching paths.") + self.assertEqual(self.writes, ["POST", "POST", "DELETE", "POST", "DELETE"]) + + def test_replaces_only_its_own_comment_from_the_old_workflow(self): + """Given an old bot status, post the renamed status once and preserve comments from other authors.""" + context = self.prepare() + for verdict in ("failure", "success"): + with self.subTest(verdict=verdict): + self.comments.clear() + self.writes.clear() + self.publish(context, "failure", "Use the required RFC filename.") + if verdict == "success": + self.publish(context, "success", "RFC filename checked.") + old = self.comments[0] + old["body"] = old["body"].replace("