Datasets:
Tasks:
Text Generation
Formats:
parquet
Sub-tasks:
language-modeling
Languages:
English
Size:
< 1K
License:
Update dataset (part 3)
Browse files- harbor/tasks/druid_lenient_script/instruction.md +18 -0
- harbor/tasks/druid_lenient_script/solution/reference.patch +795 -0
- harbor/tasks/druid_lenient_script/solution/solve.sh +801 -0
- harbor/tasks/druid_lenient_script/task.toml +28 -0
- harbor/tasks/druid_lenient_script/tests/Dockerfile +10 -0
- harbor/tasks/druid_lenient_script/tests/config.json +296 -0
- harbor/tasks/druid_lenient_script/tests/docker-compose.yaml +5 -0
- harbor/tasks/druid_lenient_script/tests/evidence.py +123 -0
- harbor/tasks/druid_lenient_script/tests/judge.py +178 -0
- harbor/tasks/druid_lenient_script/tests/test.sh +9 -0
- harbor/tasks/druid_lenient_script/tests/verify.py +235 -0
- harbor/tasks/help_defaults/environment/Dockerfile +15 -0
- harbor/tasks/help_defaults/environment/capture.py +28 -0
- harbor/tasks/help_defaults/environment/capture_submission.py +157 -0
- harbor/tasks/help_defaults/environment/docker-compose.yaml +11 -0
- harbor/tasks/help_defaults/environment/sanitize.py +25 -0
- harbor/tasks/help_defaults/instruction.md +9 -0
- harbor/tasks/help_defaults/solution/reference.patch +232 -0
- harbor/tasks/help_defaults/solution/solve.sh +238 -0
- harbor/tasks/help_defaults/task.toml +28 -0
- harbor/tasks/help_defaults/tests/Dockerfile +9 -0
- harbor/tasks/help_defaults/tests/config.json +152 -0
- harbor/tasks/help_defaults/tests/docker-compose.yaml +5 -0
- harbor/tasks/help_defaults/tests/evidence.py +123 -0
- harbor/tasks/help_defaults/tests/judge.py +178 -0
- harbor/tasks/help_defaults/tests/test.sh +3 -0
- harbor/tasks/help_defaults/tests/verify.py +235 -0
- harbor/tasks/manifest.json +5 -0
harbor/tasks/druid_lenient_script/instruction.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please make your changes directly in /workspace/repo.
|
| 2 |
+
|
| 3 |
+
A bad statement loses a whole SQL script at the first error.
|
| 4 |
+
|
| 5 |
+
Add a lenient whole script read:
|
| 6 |
+
|
| 7 |
+
- `SQLUtils.parseStatementsLenient(String sql, DbType dbType)` returns the statements in order. What the strict call reads comes back as today; the rest comes back as `SQLUnparsedStatement`, a new public statement class: `getSql()` is the statement's source text, `getError()` the message the strict call gives for that text on its own, with pos, line and column counted from the script start, `getLine()` and `getColumn()` those two numbers, and `toString()` the sql.
|
| 8 |
+
- An unparsed statement is the whole top level statement the error lies in. A compound statement is one statement with everything the strict parser puts inside it, branches and bodies included, and ends at the semicolon that ends it as a top level statement. Keywords used as names, functions, modifiers or transaction commands open and close nothing.
|
| 9 |
+
- The sql is the source exactly as written from the statement's first token to its last, whatever the text or line endings; delimiter, comments and whitespace around it are left out. When a string, quoted name or comment opened in a statement is never closed, it is unparsed and its text runs to the end of the input.
|
| 10 |
+
- What follows an unparsed statement parses exactly as the script without it.
|
| 11 |
+
- A script costs at most twice a strict parse of the same script with its unparsed statements removed, in tokens read, at 5,000 statements with 125 bad ones.
|
| 12 |
+
- The strict calls and their messages are unchanged.
|
| 13 |
+
|
| 14 |
+
Work in the core module. Build files and committed tests stay as they are and must keep passing; add no dependency; new tests go in new files.
|
| 15 |
+
|
| 16 |
+
When the requirements hold you are done: stop and report what you changed.
|
| 17 |
+
|
| 18 |
+
Finish with a final response when your changes are ready.
|
harbor/tasks/druid_lenient_script/solution/reference.patch
ADDED
|
@@ -0,0 +1,795 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java b/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
|
| 2 |
+
index 2ad08d6..1ebbe21 100644
|
| 3 |
+
--- a/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
|
| 4 |
+
+++ b/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
|
| 5 |
+
@@ -677,6 +677,14 @@ public class SQLUtils {
|
| 6 |
+
return parseStatements(sql, DbType.of(dbType), features);
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
+ /**
|
| 10 |
+
+ * Reads a whole script; statements the strict parser cannot read come back as
|
| 11 |
+
+ * {@link com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement} in place, the rest as today.
|
| 12 |
+
+ */
|
| 13 |
+
+ public static List<SQLStatement> parseStatementsLenient(String sql, DbType dbType) {
|
| 14 |
+
+ return new com.alibaba.druid.sql.parser.LenientScriptParser(sql, dbType).parse();
|
| 15 |
+
+ }
|
| 16 |
+
+
|
| 17 |
+
public static List<SQLStatement> parseStatements(String sql, DbType dbType, SQLParserFeature... features) {
|
| 18 |
+
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, features);
|
| 19 |
+
List<SQLStatement> stmtList = new ArrayList<SQLStatement>();
|
| 20 |
+
diff --git a/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java b/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java
|
| 21 |
+
new file mode 100644
|
| 22 |
+
index 0000000..336039b
|
| 23 |
+
--- /dev/null
|
| 24 |
+
+++ b/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java
|
| 25 |
+
@@ -0,0 +1,69 @@
|
| 26 |
+
+package com.alibaba.druid.sql.ast.statement;
|
| 27 |
+
+
|
| 28 |
+
+import com.alibaba.druid.DbType;
|
| 29 |
+
+import com.alibaba.druid.sql.ast.SQLStatementImpl;
|
| 30 |
+
+import com.alibaba.druid.sql.visitor.SQLASTVisitor;
|
| 31 |
+
+import com.alibaba.druid.sql.visitor.VisitorFeature;
|
| 32 |
+
+
|
| 33 |
+
+/**
|
| 34 |
+
+ * A statement the strict parser could not read, kept as its source text by the lenient script read.
|
| 35 |
+
+ */
|
| 36 |
+
+public class SQLUnparsedStatement extends SQLStatementImpl {
|
| 37 |
+
+ private final String sql;
|
| 38 |
+
+ private final String error;
|
| 39 |
+
+ private final int line;
|
| 40 |
+
+ private final int column;
|
| 41 |
+
+
|
| 42 |
+
+ public SQLUnparsedStatement(DbType dbType, String sql, String error, int line, int column) {
|
| 43 |
+
+ super(dbType);
|
| 44 |
+
+ this.sql = sql;
|
| 45 |
+
+ this.error = error;
|
| 46 |
+
+ this.line = line;
|
| 47 |
+
+ this.column = column;
|
| 48 |
+
+ }
|
| 49 |
+
+
|
| 50 |
+
+ /** The statement's source text, exactly as written, without its delimiter. */
|
| 51 |
+
+ public String getSql() {
|
| 52 |
+
+ return sql;
|
| 53 |
+
+ }
|
| 54 |
+
+
|
| 55 |
+
+ /** The strict parser's message for this text, positions counted from the start of the whole script. */
|
| 56 |
+
+ public String getError() {
|
| 57 |
+
+ return error;
|
| 58 |
+
+ }
|
| 59 |
+
+
|
| 60 |
+
+ public int getLine() {
|
| 61 |
+
+ return line;
|
| 62 |
+
+ }
|
| 63 |
+
+
|
| 64 |
+
+ public int getColumn() {
|
| 65 |
+
+ return column;
|
| 66 |
+
+ }
|
| 67 |
+
+
|
| 68 |
+
+ @Override
|
| 69 |
+
+ protected void accept0(SQLASTVisitor v) {
|
| 70 |
+
+ // nothing to visit
|
| 71 |
+
+ }
|
| 72 |
+
+
|
| 73 |
+
+ @Override
|
| 74 |
+
+ public void output(StringBuilder buf) {
|
| 75 |
+
+ buf.append(sql);
|
| 76 |
+
+ }
|
| 77 |
+
+
|
| 78 |
+
+ @Override
|
| 79 |
+
+ public String toString() {
|
| 80 |
+
+ return sql;
|
| 81 |
+
+ }
|
| 82 |
+
+
|
| 83 |
+
+ @Override
|
| 84 |
+
+ public String toString(VisitorFeature... features) {
|
| 85 |
+
+ return sql;
|
| 86 |
+
+ }
|
| 87 |
+
+
|
| 88 |
+
+ @Override
|
| 89 |
+
+ public SQLUnparsedStatement clone() {
|
| 90 |
+
+ SQLUnparsedStatement x = new SQLUnparsedStatement(dbType, sql, error, line, column);
|
| 91 |
+
+ x.setAfterSemi(afterSemi);
|
| 92 |
+
+ return x;
|
| 93 |
+
+ }
|
| 94 |
+
+}
|
| 95 |
+
diff --git a/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java b/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java
|
| 96 |
+
new file mode 100644
|
| 97 |
+
index 0000000..9fba816
|
| 98 |
+
--- /dev/null
|
| 99 |
+
+++ b/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java
|
| 100 |
+
@@ -0,0 +1,462 @@
|
| 101 |
+
+package com.alibaba.druid.sql.parser;
|
| 102 |
+
+
|
| 103 |
+
+import com.alibaba.druid.DbType;
|
| 104 |
+
+import com.alibaba.druid.sql.ast.SQLStatement;
|
| 105 |
+
+import com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement;
|
| 106 |
+
+
|
| 107 |
+
+import java.util.ArrayList;
|
| 108 |
+
+import java.util.List;
|
| 109 |
+
+
|
| 110 |
+
+/**
|
| 111 |
+
+ * Reads a whole script in one lexer pass. Every statement the strict parser reads is returned as today; every
|
| 112 |
+
+ * statement it cannot read is returned as {@link SQLUnparsedStatement} holding its exact source text and the strict
|
| 113 |
+
+ * parser's message for that text, with positions moved to the script. The extent of an unparsed statement is found
|
| 114 |
+
+ * by scanning its tokens with the dialect's block structure (a compound statement is one statement) up to the
|
| 115 |
+
+ * semicolon that ends it at the top level; a statement whose lexer never recovers runs to the end of the input.
|
| 116 |
+
+ */
|
| 117 |
+
+public class LenientScriptParser {
|
| 118 |
+
+ /** the script as handed in */
|
| 119 |
+
+ private final String sql;
|
| 120 |
+
+ /** the text the lexer reads: the parser factory rewrites CRLF to LF, so lexer positions refer to this one */
|
| 121 |
+
+ private final String text;
|
| 122 |
+
+ private final DbType dbType;
|
| 123 |
+
+ private final SQLStatementParser parser;
|
| 124 |
+
+ private final Lexer lexer;
|
| 125 |
+
+
|
| 126 |
+
+ public LenientScriptParser(String sql, DbType dbType) {
|
| 127 |
+
+ this.sql = sql;
|
| 128 |
+
+ this.dbType = dbType == null ? DbType.other : dbType;
|
| 129 |
+
+ this.parser = SQLParserUtils.createSQLStatementParser(sql, this.dbType, new SQLParserFeature[0]);
|
| 130 |
+
+ this.lexer = parser.getLexer();
|
| 131 |
+
+ this.text = lexer.text;
|
| 132 |
+
+ }
|
| 133 |
+
+
|
| 134 |
+
+ /** original offset of a normalized offset; end = true maps the exclusive end of a slice */
|
| 135 |
+
+ private int orig(int idx, boolean end) {
|
| 136 |
+
+ if (text.length() == sql.length()) {
|
| 137 |
+
+ return idx;
|
| 138 |
+
+ }
|
| 139 |
+
+ if (end) {
|
| 140 |
+
+ if (idx <= 0) {
|
| 141 |
+
+ return 0;
|
| 142 |
+
+ }
|
| 143 |
+
+ return orig(idx - 1, false) + 1;
|
| 144 |
+
+ }
|
| 145 |
+
+ // walk both strings: every "\r\n" of the original is one "\n" of the text
|
| 146 |
+
+ int j = 0;
|
| 147 |
+
+ for (int i = 0; i < idx && j < sql.length(); i++) {
|
| 148 |
+
+ if (sql.charAt(j) == '\r' && j + 1 < sql.length() && sql.charAt(j + 1) == '\n' && text.charAt(i) == '\n') {
|
| 149 |
+
+ j++;
|
| 150 |
+
+ }
|
| 151 |
+
+ j++;
|
| 152 |
+
+ }
|
| 153 |
+
+ if (idx < text.length() && j < sql.length() && sql.charAt(j) == '\r' && j + 1 < sql.length() && sql.charAt(j + 1) == '\n' && text.charAt(idx) == '\n') {
|
| 154 |
+
+ j++;
|
| 155 |
+
+ }
|
| 156 |
+
+ return j;
|
| 157 |
+
+ }
|
| 158 |
+
+
|
| 159 |
+
+ public List<SQLStatement> parse() {
|
| 160 |
+
+ List<SQLStatement> out = new ArrayList<SQLStatement>();
|
| 161 |
+
+ while (true) {
|
| 162 |
+
+ // delimiters and comment tokens between statements, handled as the dialect's own loop handles them: the
|
| 163 |
+
+ // base loop hands the comments after a delimiter to the previous statement, Oracle's loop leaves them for
|
| 164 |
+
+ // the next one
|
| 165 |
+
+ try {
|
| 166 |
+
+ while (true) {
|
| 167 |
+
+ while (lexer.token() == Token.MULTI_LINE_COMMENT || lexer.token() == Token.LINE_COMMENT) {
|
| 168 |
+
+ lexer.nextToken();
|
| 169 |
+
+ }
|
| 170 |
+
+ if (lexer.token() != Token.SEMI) {
|
| 171 |
+
+ break;
|
| 172 |
+
+ }
|
| 173 |
+
+ char ch = lexer.ch;
|
| 174 |
+
+ lexer.nextToken();
|
| 175 |
+
+ if (!out.isEmpty()) {
|
| 176 |
+
+ SQLStatement last = out.get(out.size() - 1);
|
| 177 |
+
+ last.setAfterSemi(true);
|
| 178 |
+
+ if (!isOracle() && lexer.isKeepComments()) {
|
| 179 |
+
+ if (ch == '\n' && lexer.getComments() != null && !lexer.getComments().isEmpty()
|
| 180 |
+
+ && !(last instanceof com.alibaba.druid.sql.ast.statement.SQLSetStatement)) {
|
| 181 |
+
+ lexer.getComments().add(0, new String("\n"));
|
| 182 |
+
+ }
|
| 183 |
+
+ last.addAfterComment(lexer.readAndResetComments());
|
| 184 |
+
+ }
|
| 185 |
+
+ }
|
| 186 |
+
+ }
|
| 187 |
+
+ } catch (RuntimeException e) {
|
| 188 |
+
+ // the lexer failed on the first token after a delimiter: that statement runs to the end of the input
|
| 189 |
+
+ addUnparsed(out, firstTokenStart(lexer.mark), text.length());
|
| 190 |
+
+ return out;
|
| 191 |
+
+ }
|
| 192 |
+
+ if (lexer.token() == Token.EOF) {
|
| 193 |
+
+ break;
|
| 194 |
+
+ }
|
| 195 |
+
+ Lexer.SavePoint sp = lexer.mark();
|
| 196 |
+
+ int before = out.size();
|
| 197 |
+
+ boolean ok;
|
| 198 |
+
+ try {
|
| 199 |
+
+ // one statement through the dialect's own loop, which also consumes delimiters and comments as today
|
| 200 |
+
+ parser.parseStatementList(out, before + 1, null);
|
| 201 |
+
+ // what the strict loop accepted as one statement is one statement; only delimiters and comments
|
| 202 |
+
+ // followed by the end of the input add nothing
|
| 203 |
+
+ ok = out.size() == before + 1 || (out.size() == before && lexer.token() == Token.EOF);
|
| 204 |
+
+ } catch (RuntimeException e) {
|
| 205 |
+
+ ok = false;
|
| 206 |
+
+ }
|
| 207 |
+
+ if (ok) {
|
| 208 |
+
+ if (out.size() == before) {
|
| 209 |
+
+ break;
|
| 210 |
+
+ }
|
| 211 |
+
+ continue;
|
| 212 |
+
+ }
|
| 213 |
+
+ while (out.size() > before) {
|
| 214 |
+
+ out.remove(out.size() - 1);
|
| 215 |
+
+ }
|
| 216 |
+
+ lexer.reset(sp);
|
| 217 |
+
+ int[] se = skipStatement();
|
| 218 |
+
+ addUnparsed(out, se[0], se[1]);
|
| 219 |
+
+ if (se[1] >= text.length()) {
|
| 220 |
+
+ return out;
|
| 221 |
+
+ }
|
| 222 |
+
+ // the lexer stands on the delimiter; the next round's strict loop consumes it as today
|
| 223 |
+
+ }
|
| 224 |
+
+ return out;
|
| 225 |
+
+ }
|
| 226 |
+
+
|
| 227 |
+
+ /**
|
| 228 |
+
+ * The lexer's startPos for a token that follows kept comments points at the first comment; the statement's text
|
| 229 |
+
+ * begins at its first token, so step over whitespace and comments from there (offsets in the lexer's text).
|
| 230 |
+
+ */
|
| 231 |
+
+ private int firstTokenStart(int from) {
|
| 232 |
+
+ int i = from < 0 ? 0 : from;
|
| 233 |
+
+ int n = text.length();
|
| 234 |
+
+ while (i < n) {
|
| 235 |
+
+ char c = text.charAt(i);
|
| 236 |
+
+ if (Character.isWhitespace(c)) {
|
| 237 |
+
+ i++;
|
| 238 |
+
+ } else if (c == '-' && i + 1 < n && text.charAt(i + 1) == '-') {
|
| 239 |
+
+ while (i < n && text.charAt(i) != '\n') {
|
| 240 |
+
+ i++;
|
| 241 |
+
+ }
|
| 242 |
+
+ } else if (c == '#' && isMySql()) {
|
| 243 |
+
+ while (i < n && text.charAt(i) != '\n') {
|
| 244 |
+
+ i++;
|
| 245 |
+
+ }
|
| 246 |
+
+ } else if (c == '/' && i + 1 < n && text.charAt(i + 1) == '*') {
|
| 247 |
+
+ int close = text.indexOf("*/", i + 2);
|
| 248 |
+
+ if (close < 0) {
|
| 249 |
+
+ return i;
|
| 250 |
+
+ }
|
| 251 |
+
+ i = close + 2;
|
| 252 |
+
+ } else {
|
| 253 |
+
+ break;
|
| 254 |
+
+ }
|
| 255 |
+
+ }
|
| 256 |
+
+ return i;
|
| 257 |
+
+ }
|
| 258 |
+
+
|
| 259 |
+
+ /** start and end are offsets in the lexer's text; the item keeps the original characters */
|
| 260 |
+
+ private void addUnparsed(List<SQLStatement> out, int start, int end) {
|
| 261 |
+
+ if (start < 0) {
|
| 262 |
+
+ start = 0;
|
| 263 |
+
+ }
|
| 264 |
+
+ if (end > text.length()) {
|
| 265 |
+
+ end = text.length();
|
| 266 |
+
+ }
|
| 267 |
+
+ if (end < start) {
|
| 268 |
+
+ end = start;
|
| 269 |
+
+ }
|
| 270 |
+
+ int oStart = orig(start, false);
|
| 271 |
+
+ int oEnd = end >= text.length() ? sql.length() : orig(end, true);
|
| 272 |
+
+ if (oEnd < oStart) {
|
| 273 |
+
+ oEnd = oStart;
|
| 274 |
+
+ }
|
| 275 |
+
+ start = oStart;
|
| 276 |
+
+ String item = sql.substring(oStart, oEnd);
|
| 277 |
+
+ String msg = strictMessage(item);
|
| 278 |
+
+ int line = 1, col = 1;
|
| 279 |
+
+ for (int i = 0; i < start; i++) {
|
| 280 |
+
+ if (sql.charAt(i) == '\n') {
|
| 281 |
+
+ line++;
|
| 282 |
+
+ col = 1;
|
| 283 |
+
+ } else {
|
| 284 |
+
+ col++;
|
| 285 |
+
+ }
|
| 286 |
+
+ }
|
| 287 |
+
+ String moved = move(msg, start, line, col);
|
| 288 |
+
+ int[] lc = lineCol(moved);
|
| 289 |
+
+ SQLUnparsedStatement u = new SQLUnparsedStatement(dbType, item, moved, lc[0], lc[1]);
|
| 290 |
+
+ out.add(u);
|
| 291 |
+
+ }
|
| 292 |
+
+
|
| 293 |
+
+ /** The strict parser's message for the text on its own. */
|
| 294 |
+
+ private String strictMessage(String text) {
|
| 295 |
+
+ try {
|
| 296 |
+
+ SQLStatementParser p = SQLParserUtils.createSQLStatementParser(text, dbType, new SQLParserFeature[0]);
|
| 297 |
+
+ List<SQLStatement> l = new ArrayList<SQLStatement>();
|
| 298 |
+
+ p.parseStatementList(l, -1, null);
|
| 299 |
+
+ if (p.getLexer().token() != Token.EOF) {
|
| 300 |
+
+ return "syntax error : " + p.getLexer().info();
|
| 301 |
+
+ }
|
| 302 |
+
+ return "syntax error";
|
| 303 |
+
+ } catch (RuntimeException e) {
|
| 304 |
+
+ return e.getMessage() == null ? e.toString() : e.getMessage();
|
| 305 |
+
+ }
|
| 306 |
+
+ }
|
| 307 |
+
+
|
| 308 |
+
+ // ------------------------------------------------------------------ extent
|
| 309 |
+
+
|
| 310 |
+
+ private boolean isMySql() {
|
| 311 |
+
+ return dbType == DbType.mysql || dbType == DbType.mariadb || dbType == DbType.tidb || dbType == DbType.oceanbase
|
| 312 |
+
+ || dbType == DbType.polardbx || dbType == DbType.drds || dbType == DbType.ads;
|
| 313 |
+
+ }
|
| 314 |
+
+
|
| 315 |
+
+ private boolean isOracle() {
|
| 316 |
+
+ return dbType == DbType.oracle || dbType == DbType.oceanbase_oracle || dbType == DbType.polardb2;
|
| 317 |
+
+ }
|
| 318 |
+
+
|
| 319 |
+
+ private boolean isSqlServer() {
|
| 320 |
+
+ return dbType == DbType.sqlserver || dbType == DbType.jtds;
|
| 321 |
+
+ }
|
| 322 |
+
+
|
| 323 |
+
+ private boolean isPg() {
|
| 324 |
+
+ return dbType == DbType.postgresql || dbType == DbType.edb || dbType == DbType.greenplum || dbType == DbType.gaussdb
|
| 325 |
+
+ || dbType == DbType.hologres || dbType == DbType.redshift;
|
| 326 |
+
+ }
|
| 327 |
+
+
|
| 328 |
+
+ /**
|
| 329 |
+
+ * From the first token of a statement, scan to the delimiter ending it as a top level statement. Returns the end
|
| 330 |
+
+ * offset (exclusive) of its last token and leaves the lexer on that delimiter (or EOF). When the lexer cannot read
|
| 331 |
+
+ * on, the statement runs to the end of the input.
|
| 332 |
+
+ */
|
| 333 |
+
+ private int[] skipStatement() {
|
| 334 |
+
+ // leading delimiters and comment tokens belong to no statement
|
| 335 |
+
+ try {
|
| 336 |
+
+ while (lexer.token() == Token.SEMI || lexer.token() == Token.MULTI_LINE_COMMENT || lexer.token() == Token.LINE_COMMENT) {
|
| 337 |
+
+ lexer.nextToken();
|
| 338 |
+
+ }
|
| 339 |
+
+ } catch (RuntimeException e) {
|
| 340 |
+
+ // the lexer failed on the first token: that statement runs to the end of the input
|
| 341 |
+
+ return new int[] {firstTokenStart(lexer.mark), text.length()};
|
| 342 |
+
+ }
|
| 343 |
+
+ int start = firstTokenStart(lexer.startPos);
|
| 344 |
+
+ if (lexer.token() == Token.EOF) {
|
| 345 |
+
+ return new int[] {start, start};
|
| 346 |
+
+ }
|
| 347 |
+
+ int depth = 0;
|
| 348 |
+
+ // per depth: whether the next BEGIN at this level is the body of an already opened block (DECLARE, IS/AS)
|
| 349 |
+
+ boolean[] absorb = new boolean[256];
|
| 350 |
+
+ int end = lexer.pos();
|
| 351 |
+
+ boolean stmtStart = true;
|
| 352 |
+
+ boolean afterEnd = false;
|
| 353 |
+
+ boolean routinePending = false;
|
| 354 |
+
+ Token prev = null;
|
| 355 |
+
+ while (true) {
|
| 356 |
+
+ Token t = lexer.token();
|
| 357 |
+
+ if (t == Token.EOF) {
|
| 358 |
+
+ return new int[] {start, end};
|
| 359 |
+
+ }
|
| 360 |
+
+ if (t == Token.ERROR) {
|
| 361 |
+
+ // a literal, quoted name or comment the lexer could not close runs to the end of the input;
|
| 362 |
+
+ // any other unreadable character is just a token of the statement
|
| 363 |
+
+ char c = lexer.startPos < text.length() ? text.charAt(lexer.startPos) : ' ';
|
| 364 |
+
+ if (lexer.pos() >= text.length() || c == '\'' || c == '"' || c == '`' || c == '[' || c == '/') {
|
| 365 |
+
+ return new int[] {start, text.length()};
|
| 366 |
+
+ }
|
| 367 |
+
+ }
|
| 368 |
+
+ if (t == Token.SEMI && depth == 0) {
|
| 369 |
+
+ if (isSqlServer()) {
|
| 370 |
+
+ // IF cond stmt; ELSE stmt; is one statement
|
| 371 |
+
+ Lexer.SavePoint sp = lexer.mark();
|
| 372 |
+
+ try {
|
| 373 |
+
+ lexer.nextToken();
|
| 374 |
+
+ } catch (RuntimeException e) {
|
| 375 |
+
+ return new int[] {start, text.length()};
|
| 376 |
+
+ }
|
| 377 |
+
+ if (lexer.token() == Token.ELSE) {
|
| 378 |
+
+ prev = Token.SEMI;
|
| 379 |
+
+ stmtStart = true;
|
| 380 |
+
+ // fall through to treat ELSE as an ordinary token
|
| 381 |
+
+ } else {
|
| 382 |
+
+ lexer.reset(sp);
|
| 383 |
+
+ return new int[] {start, end};
|
| 384 |
+
+ }
|
| 385 |
+
+ } else {
|
| 386 |
+
+ return new int[] {start, end};
|
| 387 |
+
+ }
|
| 388 |
+
+ }
|
| 389 |
+
+ t = lexer.token();
|
| 390 |
+
+ boolean startHere = stmtStart;
|
| 391 |
+
+ boolean opener = false;
|
| 392 |
+
+ boolean closerKeyword = false;
|
| 393 |
+
+ if (afterEnd) {
|
| 394 |
+
+ if (t == Token.IF || t == Token.LOOP || t == Token.CASE || t == Token.WHILE || t == Token.REPEAT
|
| 395 |
+
+ || lexer.identifierEquals("TRY") || lexer.identifierEquals("CATCH")) {
|
| 396 |
+
+ closerKeyword = true;
|
| 397 |
+
+ }
|
| 398 |
+
+ afterEnd = false;
|
| 399 |
+
+ }
|
| 400 |
+
+ if (!closerKeyword) {
|
| 401 |
+
+ if (t == Token.BEGIN) {
|
| 402 |
+
+ opener = beginOpensBlock();
|
| 403 |
+
+ if (opener && depth > 0 && absorb[depth]) {
|
| 404 |
+
+ opener = false;
|
| 405 |
+
+ absorb[depth] = false;
|
| 406 |
+
+ }
|
| 407 |
+
+ } else if (t == Token.CASE || t == Token.LOOP) {
|
| 408 |
+
+ opener = true;
|
| 409 |
+
+ } else if (t == Token.IF) {
|
| 410 |
+
+ opener = startHere && !isSqlServer();
|
| 411 |
+
+ } else if (t == Token.WHILE || t == Token.REPEAT) {
|
| 412 |
+
+ opener = startHere && isMySql();
|
| 413 |
+
+ } else if (t == Token.DECLARE) {
|
| 414 |
+
+ if (startHere && (isOracle() || isPg())) {
|
| 415 |
+
+ opener = true;
|
| 416 |
+
+ if (depth + 1 < absorb.length) {
|
| 417 |
+
+ absorb[depth + 1] = true;
|
| 418 |
+
+ }
|
| 419 |
+
+ }
|
| 420 |
+
+ } else if (t == Token.PROCEDURE || t == Token.FUNCTION || lexer.identifierEquals("PACKAGE")) {
|
| 421 |
+
+ if (isOracle() && (startHere || prev == Token.CREATE || prev == Token.REPLACE)) {
|
| 422 |
+
+ routinePending = true;
|
| 423 |
+
+ }
|
| 424 |
+
+ } else if ((t == Token.IS || t == Token.AS) && routinePending) {
|
| 425 |
+
+ routinePending = false;
|
| 426 |
+
+ opener = true;
|
| 427 |
+
+ if (depth + 1 < absorb.length) {
|
| 428 |
+
+ absorb[depth + 1] = true;
|
| 429 |
+
+ }
|
| 430 |
+
+ } else if (t == Token.END) {
|
| 431 |
+
+ if (depth > 0) {
|
| 432 |
+
+ absorb[depth] = false;
|
| 433 |
+
+ depth--;
|
| 434 |
+
+ }
|
| 435 |
+
+ afterEnd = true;
|
| 436 |
+
+ }
|
| 437 |
+
+ }
|
| 438 |
+
+ if (opener) {
|
| 439 |
+
+ depth++;
|
| 440 |
+
+ if (t == Token.BEGIN || t == Token.LOOP || t == Token.CASE || t == Token.IF || t == Token.WHILE || t == Token.REPEAT) {
|
| 441 |
+
+ // a fresh block: nothing pending to absorb at this level unless set above
|
| 442 |
+
+ if (t != Token.BEGIN && depth < absorb.length && !(t == Token.DECLARE)) {
|
| 443 |
+
+ absorb[depth] = absorb[depth] && false;
|
| 444 |
+
+ }
|
| 445 |
+
+ }
|
| 446 |
+
+ }
|
| 447 |
+
+ stmtStart = t == Token.SEMI || t == Token.BEGIN || t == Token.THEN || t == Token.ELSE || t == Token.DO
|
| 448 |
+
+ || t == Token.LOOP || t == Token.EXCEPTION || t == Token.ELSEIF
|
| 449 |
+
+ || (t == Token.VARIANT && lexer.stringVal() != null && lexer.stringVal().startsWith("$"))
|
| 450 |
+
+ || (t == Token.VARIANT && ":".equals(lexer.stringVal()))
|
| 451 |
+
+ || (t == Token.IS || t == Token.AS) && opener
|
| 452 |
+
+ || t == Token.GTGT;
|
| 453 |
+
+ prev = t;
|
| 454 |
+
+ end = lexer.pos();
|
| 455 |
+
+ try {
|
| 456 |
+
+ lexer.nextToken();
|
| 457 |
+
+ } catch (RuntimeException e) {
|
| 458 |
+
+ return new int[] {start, text.length()};
|
| 459 |
+
+ }
|
| 460 |
+
+ }
|
| 461 |
+
+ }
|
| 462 |
+
+
|
| 463 |
+
+ /** BEGIN opens a block unless the dialect reads it as a transaction command. Consumes nothing (peeks and resets). */
|
| 464 |
+
+ private boolean beginOpensBlock() {
|
| 465 |
+
+ if (isOracle()) {
|
| 466 |
+
+ return true;
|
| 467 |
+
+ }
|
| 468 |
+
+ Lexer.SavePoint sp = lexer.mark();
|
| 469 |
+
+ boolean block;
|
| 470 |
+
+ try {
|
| 471 |
+
+ lexer.nextToken();
|
| 472 |
+
+ Token n = lexer.token();
|
| 473 |
+
+ if (isMySql()) {
|
| 474 |
+
+ block = !(n == Token.SEMI || n == Token.EOF || n == Token.IDENTIFIER);
|
| 475 |
+
+ } else if (isSqlServer()) {
|
| 476 |
+
+ block = !(lexer.identifierEquals("TRANSACTION") || lexer.identifierEquals("TRAN") || lexer.identifierEquals("DISTRIBUTED"));
|
| 477 |
+
+ } else {
|
| 478 |
+
+ block = !(n == Token.SEMI || n == Token.EOF || lexer.identifierEquals("WORK") || lexer.identifierEquals("TRANSACTION")
|
| 479 |
+
+ || lexer.identifierEquals("ISOLATION") || lexer.identifierEquals("READ") || lexer.identifierEquals("DEFERRABLE")
|
| 480 |
+
+ || lexer.identifierEquals("NOT"));
|
| 481 |
+
+ }
|
| 482 |
+
+ } catch (RuntimeException e) {
|
| 483 |
+
+ block = true;
|
| 484 |
+
+ }
|
| 485 |
+
+ lexer.reset(sp);
|
| 486 |
+
+ return block;
|
| 487 |
+
+ }
|
| 488 |
+
+
|
| 489 |
+
+ // ------------------------------------------------------------------ positions
|
| 490 |
+
+
|
| 491 |
+
+ /** Rewrites every "pos N, line L, column C" in a message from the statement's frame to the script's. */
|
| 492 |
+
+ static String move(String m, int start, int sLine, int sCol) {
|
| 493 |
+
+ if (m == null) {
|
| 494 |
+
+ return null;
|
| 495 |
+
+ }
|
| 496 |
+
+ StringBuilder sb = new StringBuilder();
|
| 497 |
+
+ int i = 0;
|
| 498 |
+
+ while (true) {
|
| 499 |
+
+ int p = m.indexOf("pos ", i);
|
| 500 |
+
+ if (p < 0) {
|
| 501 |
+
+ sb.append(m.substring(i));
|
| 502 |
+
+ break;
|
| 503 |
+
+ }
|
| 504 |
+
+ int pe = p + 4;
|
| 505 |
+
+ while (pe < m.length() && Character.isDigit(m.charAt(pe))) {
|
| 506 |
+
+ pe++;
|
| 507 |
+
+ }
|
| 508 |
+
+ if (pe == p + 4 || !m.startsWith(", line ", pe)) {
|
| 509 |
+
+ sb.append(m, i, pe);
|
| 510 |
+
+ i = pe;
|
| 511 |
+
+ continue;
|
| 512 |
+
+ }
|
| 513 |
+
+ int le = pe + 7;
|
| 514 |
+
+ while (le < m.length() && Character.isDigit(m.charAt(le))) {
|
| 515 |
+
+ le++;
|
| 516 |
+
+ }
|
| 517 |
+
+ if (le == pe + 7 || !m.startsWith(", column ", le)) {
|
| 518 |
+
+ sb.append(m, i, le);
|
| 519 |
+
+ i = le;
|
| 520 |
+
+ continue;
|
| 521 |
+
+ }
|
| 522 |
+
+ int ce = le + 9;
|
| 523 |
+
+ while (ce < m.length() && Character.isDigit(m.charAt(ce))) {
|
| 524 |
+
+ ce++;
|
| 525 |
+
+ }
|
| 526 |
+
+ if (ce == le + 9) {
|
| 527 |
+
+ sb.append(m, i, ce);
|
| 528 |
+
+ i = ce;
|
| 529 |
+
+ continue;
|
| 530 |
+
+ }
|
| 531 |
+
+ int pos = Integer.parseInt(m.substring(p + 4, pe));
|
| 532 |
+
+ int line = Integer.parseInt(m.substring(pe + 7, le));
|
| 533 |
+
+ int col = Integer.parseInt(m.substring(le + 9, ce));
|
| 534 |
+
+ sb.append(m, i, p).append("pos ").append(pos + start).append(", line ").append(line + sLine - 1)
|
| 535 |
+
+ .append(", column ").append(line == 1 ? col + sCol - 1 : col);
|
| 536 |
+
+ i = ce;
|
| 537 |
+
+ }
|
| 538 |
+
+ return sb.toString();
|
| 539 |
+
+ }
|
| 540 |
+
+
|
| 541 |
+
+ static int[] lineCol(String m) {
|
| 542 |
+
+ if (m == null) {
|
| 543 |
+
+ return new int[] {-1, -1};
|
| 544 |
+
+ }
|
| 545 |
+
+ int li = m.indexOf(", line ");
|
| 546 |
+
+ if (li < 0) {
|
| 547 |
+
+ return new int[] {-1, -1};
|
| 548 |
+
+ }
|
| 549 |
+
+ int l = num(m, li + 7);
|
| 550 |
+
+ int ci = m.indexOf(", column ", li);
|
| 551 |
+
+ int c = ci < 0 ? -1 : num(m, ci + 9);
|
| 552 |
+
+ return new int[] {l, c};
|
| 553 |
+
+ }
|
| 554 |
+
+
|
| 555 |
+
+ static int num(String m, int j) {
|
| 556 |
+
+ int k = j;
|
| 557 |
+
+ while (k < m.length() && Character.isDigit(m.charAt(k))) {
|
| 558 |
+
+ k++;
|
| 559 |
+
+ }
|
| 560 |
+
+ return k == j ? -1 : Integer.parseInt(m.substring(j, k));
|
| 561 |
+
+ }
|
| 562 |
+
+}
|
| 563 |
+
diff --git a/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java b/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java
|
| 564 |
+
new file mode 100644
|
| 565 |
+
index 0000000..9bdc701
|
| 566 |
+
--- /dev/null
|
| 567 |
+
+++ b/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java
|
| 568 |
+
@@ -0,0 +1,227 @@
|
| 569 |
+
+package com.alibaba.druid.bvt.sql;
|
| 570 |
+
+
|
| 571 |
+
+import com.alibaba.druid.DbType;
|
| 572 |
+
+import com.alibaba.druid.sql.SQLUtils;
|
| 573 |
+
+import com.alibaba.druid.sql.ast.SQLStatement;
|
| 574 |
+
+import com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement;
|
| 575 |
+
+import org.junit.jupiter.api.Test;
|
| 576 |
+
+
|
| 577 |
+
+import java.util.ArrayList;
|
| 578 |
+
+import java.util.List;
|
| 579 |
+
+import java.util.regex.Matcher;
|
| 580 |
+
+import java.util.regex.Pattern;
|
| 581 |
+
+
|
| 582 |
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
|
| 583 |
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
|
| 584 |
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
|
| 585 |
+
+import static org.junit.jupiter.api.Assertions.fail;
|
| 586 |
+
+
|
| 587 |
+
+/**
|
| 588 |
+
+ * The lenient whole-script read: SQLUtils.parseStatementsLenient returns what the strict call reads as today and the
|
| 589 |
+
+ * rest as SQLUnparsedStatement carrying the statement's exact text and the strict message for that text on its own,
|
| 590 |
+
+ * with pos, line and column counted from the script start.
|
| 591 |
+
+ */
|
| 592 |
+
+public class LenientScriptReadTest {
|
| 593 |
+
+ private static final Pattern POS = Pattern.compile("pos (\\d+), line (\\d+), column (\\d+)");
|
| 594 |
+
+
|
| 595 |
+
+ private static List<SQLUnparsedStatement> unparsedOf(List<SQLStatement> list) {
|
| 596 |
+
+ List<SQLUnparsedStatement> out = new ArrayList<SQLUnparsedStatement>();
|
| 597 |
+
+ for (SQLStatement s : list) {
|
| 598 |
+
+ if (s instanceof SQLUnparsedStatement) {
|
| 599 |
+
+ out.add((SQLUnparsedStatement) s);
|
| 600 |
+
+ }
|
| 601 |
+
+ }
|
| 602 |
+
+ return out;
|
| 603 |
+
+ }
|
| 604 |
+
+
|
| 605 |
+
+ /** the message the strict call gives for a text on its own */
|
| 606 |
+
+ private static String strictMessage(String sql, DbType dbType) {
|
| 607 |
+
+ try {
|
| 608 |
+
+ SQLUtils.parseStatements(sql, dbType);
|
| 609 |
+
+ } catch (Exception e) {
|
| 610 |
+
+ return e.getMessage();
|
| 611 |
+
+ }
|
| 612 |
+
+ fail("the text should not parse on its own: " + sql);
|
| 613 |
+
+ return null;
|
| 614 |
+
+ }
|
| 615 |
+
+
|
| 616 |
+
+ /** the same message with pos, line and column counted from the script start, for a statement starting at (offset, line, column) */
|
| 617 |
+
+ private static String counted(String standalone, int offset, int line, int column) {
|
| 618 |
+
+ Matcher m = POS.matcher(standalone);
|
| 619 |
+
+ StringBuffer sb = new StringBuffer();
|
| 620 |
+
+ while (m.find()) {
|
| 621 |
+
+ int p = Integer.parseInt(m.group(1)), l = Integer.parseInt(m.group(2)), c = Integer.parseInt(m.group(3));
|
| 622 |
+
+ m.appendReplacement(sb, "pos " + (p + offset) + ", line " + (l + line - 1) + ", column " + (l == 1 ? c + column - 1 : c));
|
| 623 |
+
+ }
|
| 624 |
+
+ m.appendTail(sb);
|
| 625 |
+
+ return sb.toString();
|
| 626 |
+
+ }
|
| 627 |
+
+
|
| 628 |
+
+ private static int lineOf(String error) {
|
| 629 |
+
+ Matcher m = POS.matcher(error);
|
| 630 |
+
+ assertTrue(m.find(), error);
|
| 631 |
+
+ return Integer.parseInt(m.group(2));
|
| 632 |
+
+ }
|
| 633 |
+
+
|
| 634 |
+
+ private static int columnOf(String error) {
|
| 635 |
+
+ Matcher m = POS.matcher(error);
|
| 636 |
+
+ assertTrue(m.find(), error);
|
| 637 |
+
+ return Integer.parseInt(m.group(3));
|
| 638 |
+
+ }
|
| 639 |
+
+
|
| 640 |
+
+ @Test
|
| 641 |
+
+ public void allGoodComesBackAsStrict() {
|
| 642 |
+
+ String sql = "select id from t where x = 1; insert into t (a) values (2); update t set a = 3;";
|
| 643 |
+
+ List<SQLStatement> strict = SQLUtils.parseStatements(sql, DbType.mysql);
|
| 644 |
+
+ List<SQLStatement> lenient = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 645 |
+
+ assertEquals(strict.size(), lenient.size());
|
| 646 |
+
+ for (int i = 0; i < strict.size(); ++i) {
|
| 647 |
+
+ assertEquals(strict.get(i).toString(), lenient.get(i).toString());
|
| 648 |
+
+ }
|
| 649 |
+
+ assertTrue(unparsedOf(lenient).isEmpty());
|
| 650 |
+
+ }
|
| 651 |
+
+
|
| 652 |
+
+ @Test
|
| 653 |
+
+ public void badSimpleStatementBetweenGoodOnes() {
|
| 654 |
+
+ String bad = "select a from where a = 1";
|
| 655 |
+
+ String sql = "select 1; " + bad + "; select 3;";
|
| 656 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 657 |
+
+ assertEquals(3, list.size());
|
| 658 |
+
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
|
| 659 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 660 |
+
+
|
| 661 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 662 |
+
+ assertEquals(bad, u.getSql());
|
| 663 |
+
+ assertEquals(bad, u.toString());
|
| 664 |
+
+ String standalone = strictMessage(bad, DbType.mysql);
|
| 665 |
+
+ assertEquals(counted(standalone, 10, 1, 11), u.getError());
|
| 666 |
+
+ assertEquals(lineOf(u.getError()), u.getLine());
|
| 667 |
+
+ assertEquals(columnOf(u.getError()), u.getColumn());
|
| 668 |
+
+ }
|
| 669 |
+
+
|
| 670 |
+
+ @Test
|
| 671 |
+
+ public void errorLineCountedFromScriptStart() {
|
| 672 |
+
+ String sql = "select 1;\nselect * from t where a ==== 1;\nselect 3;";
|
| 673 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 674 |
+
+ assertEquals(3, list.size());
|
| 675 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 676 |
+
+ assertEquals("select * from t where a ==== 1", u.getSql());
|
| 677 |
+
+ assertEquals("ERROR. pos 38, line 2, column 27, token ==", u.getError());
|
| 678 |
+
+ assertEquals(2, u.getLine());
|
| 679 |
+
+ assertEquals(27, u.getColumn());
|
| 680 |
+
+ }
|
| 681 |
+
+
|
| 682 |
+
+ @Test
|
| 683 |
+
+ public void whatFollowsParsesAsTheScriptWithoutIt() {
|
| 684 |
+
+ String script = "select 1; nonsense here; select 2 from t; create table x (id bigint);";
|
| 685 |
+
+ String without = "select 1; select 2 from t; create table x (id bigint);";
|
| 686 |
+
+ List<SQLStatement> lenient = SQLUtils.parseStatementsLenient(script, DbType.mysql);
|
| 687 |
+
+ List<SQLStatement> strict = SQLUtils.parseStatements(without, DbType.mysql);
|
| 688 |
+
+ assertEquals(4, lenient.size());
|
| 689 |
+
+ assertTrue(lenient.get(1) instanceof SQLUnparsedStatement);
|
| 690 |
+
+ assertEquals(strict.get(0).toString(), lenient.get(0).toString());
|
| 691 |
+
+ assertEquals(strict.get(1).toString(), lenient.get(2).toString());
|
| 692 |
+
+ assertEquals(strict.get(2).toString(), lenient.get(3).toString());
|
| 693 |
+
+ }
|
| 694 |
+
+
|
| 695 |
+
+ @Test
|
| 696 |
+
+ public void compoundStatementIsOneStatement() {
|
| 697 |
+
+ String sql = "create procedure p() begin if x > 0 then begin select bad from; end; end if; end; select 7;";
|
| 698 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 699 |
+
+ assertEquals(2, list.size());
|
| 700 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(0);
|
| 701 |
+
+ assertEquals("create procedure p() begin if x > 0 then begin select bad from; end; end if; end", u.getSql());
|
| 702 |
+
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
|
| 703 |
+
+ }
|
| 704 |
+
+
|
| 705 |
+
+ @Test
|
| 706 |
+
+ public void compoundLoopsAreOneStatement() {
|
| 707 |
+
+ String sql = "create procedure p() begin while i < 10 do set i = i + + ; end while; end; select 7;";
|
| 708 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 709 |
+
+ assertEquals(2, list.size());
|
| 710 |
+
+ assertEquals("create procedure p() begin while i < 10 do set i = i + + ; end while; end",
|
| 711 |
+
+ ((SQLUnparsedStatement) list.get(0)).getSql());
|
| 712 |
+
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
|
| 713 |
+
+ }
|
| 714 |
+
+
|
| 715 |
+
+ @Test
|
| 716 |
+
+ public void oracleDeclareSectionBelongsToTheBlock() {
|
| 717 |
+
+ String sql = "begin null; end;\ndeclare x number; begin x := ; end;\nselect 1 from dual;";
|
| 718 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.oracle);
|
| 719 |
+
+ assertEquals(3, list.size());
|
| 720 |
+
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
|
| 721 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 722 |
+
+ assertEquals("declare x number; begin x := ; end", u.getSql());
|
| 723 |
+
+ assertEquals(2, u.getLine());
|
| 724 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 725 |
+
+ }
|
| 726 |
+
+
|
| 727 |
+
+ @Test
|
| 728 |
+
+ public void sqlServerIfElseBranchesAreOneStatement() {
|
| 729 |
+
+ String sql = "if 1 = 1 select bad from; else select 2;\nselect 3;";
|
| 730 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.sqlserver);
|
| 731 |
+
+ assertEquals(2, list.size());
|
| 732 |
+
+ assertEquals("if 1 = 1 select bad from; else select 2", ((SQLUnparsedStatement) list.get(0)).getSql());
|
| 733 |
+
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
|
| 734 |
+
+ }
|
| 735 |
+
+
|
| 736 |
+
+ @Test
|
| 737 |
+
+ public void keywordsAsNamesFunctionsModifiersAndTransactionsOpenNothing() {
|
| 738 |
+
+ String sql = "begin; select 1; commit; select if(a, 1, 2) from t; select `end` from t; drop table if exists t2;"
|
| 739 |
+
+ + " delete from where a = 1; select 4;";
|
| 740 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 741 |
+
+ List<SQLUnparsedStatement> bad = unparsedOf(list);
|
| 742 |
+
+ assertEquals(1, bad.size());
|
| 743 |
+
+ assertEquals("delete from where a = 1", bad.get(0).getSql());
|
| 744 |
+
+ assertEquals(8, list.size());
|
| 745 |
+
+ assertFalse(list.get(7) instanceof SQLUnparsedStatement);
|
| 746 |
+
+ }
|
| 747 |
+
+
|
| 748 |
+
+ @Test
|
| 749 |
+
+ public void unclosedStringRunsToTheEndOfTheInput() {
|
| 750 |
+
+ String tail = "select 'abc; select 3;";
|
| 751 |
+
+ String sql = "select 1; " + tail;
|
| 752 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 753 |
+
+ assertEquals(2, list.size());
|
| 754 |
+
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
|
| 755 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 756 |
+
+ assertEquals(tail, u.getSql());
|
| 757 |
+
+ assertEquals(counted(strictMessage(tail, DbType.mysql), 10, 1, 11), u.getError());
|
| 758 |
+
+ }
|
| 759 |
+
+
|
| 760 |
+
+ @Test
|
| 761 |
+
+ public void textIsExactUnderCrlf() {
|
| 762 |
+
+ String bad = "select a from where a = 1";
|
| 763 |
+
+ String sql = "select 1;\r\n" + bad + ";\r\nselect 3;";
|
| 764 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 765 |
+
+ assertEquals(3, list.size());
|
| 766 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 767 |
+
+ assertEquals(bad, u.getSql());
|
| 768 |
+
+ assertEquals(2, u.getLine());
|
| 769 |
+
+ assertEquals(counted(strictMessage(bad, DbType.mysql), 11, 2, 1), u.getError());
|
| 770 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 771 |
+
+ }
|
| 772 |
+
+
|
| 773 |
+
+ @Test
|
| 774 |
+
+ public void commentAheadOfABadStatementIsNotPartOfItsText() {
|
| 775 |
+
+ String bad = "select a from where a = 1";
|
| 776 |
+
+ String sql = "select 1;\n-- note\n" + bad + ";\n/* block */ select 3;";
|
| 777 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 778 |
+
+ assertEquals(3, list.size());
|
| 779 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 780 |
+
+ assertEquals(bad, u.getSql());
|
| 781 |
+
+ assertEquals(3, u.getLine());
|
| 782 |
+
+ assertEquals(counted(strictMessage(bad, DbType.mysql), 18, 3, 1), u.getError());
|
| 783 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 784 |
+
+ }
|
| 785 |
+
+
|
| 786 |
+
+ @Test
|
| 787 |
+
+ public void strictEntryPointsUnchanged() {
|
| 788 |
+
+ try {
|
| 789 |
+
+ SQLUtils.parseStatements("select 1; select a from where a = 1; select 3;", DbType.mysql);
|
| 790 |
+
+ fail("the strict call must still fail on a bad statement");
|
| 791 |
+
+ } catch (Exception e) {
|
| 792 |
+
+ assertTrue(e.getMessage().contains("pos "), e.getMessage());
|
| 793 |
+
+ }
|
| 794 |
+
+ }
|
| 795 |
+
+}
|
harbor/tasks/druid_lenient_script/solution/solve.sh
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -eu
|
| 3 |
+
cd /workspace/repo
|
| 4 |
+
git apply <<'REFERENCE_PATCH'
|
| 5 |
+
diff --git a/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java b/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
|
| 6 |
+
index 2ad08d6..1ebbe21 100644
|
| 7 |
+
--- a/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
|
| 8 |
+
+++ b/core/src/main/java/com/alibaba/druid/sql/SQLUtils.java
|
| 9 |
+
@@ -677,6 +677,14 @@ public class SQLUtils {
|
| 10 |
+
return parseStatements(sql, DbType.of(dbType), features);
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
+ /**
|
| 14 |
+
+ * Reads a whole script; statements the strict parser cannot read come back as
|
| 15 |
+
+ * {@link com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement} in place, the rest as today.
|
| 16 |
+
+ */
|
| 17 |
+
+ public static List<SQLStatement> parseStatementsLenient(String sql, DbType dbType) {
|
| 18 |
+
+ return new com.alibaba.druid.sql.parser.LenientScriptParser(sql, dbType).parse();
|
| 19 |
+
+ }
|
| 20 |
+
+
|
| 21 |
+
public static List<SQLStatement> parseStatements(String sql, DbType dbType, SQLParserFeature... features) {
|
| 22 |
+
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType, features);
|
| 23 |
+
List<SQLStatement> stmtList = new ArrayList<SQLStatement>();
|
| 24 |
+
diff --git a/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java b/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java
|
| 25 |
+
new file mode 100644
|
| 26 |
+
index 0000000..336039b
|
| 27 |
+
--- /dev/null
|
| 28 |
+
+++ b/core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLUnparsedStatement.java
|
| 29 |
+
@@ -0,0 +1,69 @@
|
| 30 |
+
+package com.alibaba.druid.sql.ast.statement;
|
| 31 |
+
+
|
| 32 |
+
+import com.alibaba.druid.DbType;
|
| 33 |
+
+import com.alibaba.druid.sql.ast.SQLStatementImpl;
|
| 34 |
+
+import com.alibaba.druid.sql.visitor.SQLASTVisitor;
|
| 35 |
+
+import com.alibaba.druid.sql.visitor.VisitorFeature;
|
| 36 |
+
+
|
| 37 |
+
+/**
|
| 38 |
+
+ * A statement the strict parser could not read, kept as its source text by the lenient script read.
|
| 39 |
+
+ */
|
| 40 |
+
+public class SQLUnparsedStatement extends SQLStatementImpl {
|
| 41 |
+
+ private final String sql;
|
| 42 |
+
+ private final String error;
|
| 43 |
+
+ private final int line;
|
| 44 |
+
+ private final int column;
|
| 45 |
+
+
|
| 46 |
+
+ public SQLUnparsedStatement(DbType dbType, String sql, String error, int line, int column) {
|
| 47 |
+
+ super(dbType);
|
| 48 |
+
+ this.sql = sql;
|
| 49 |
+
+ this.error = error;
|
| 50 |
+
+ this.line = line;
|
| 51 |
+
+ this.column = column;
|
| 52 |
+
+ }
|
| 53 |
+
+
|
| 54 |
+
+ /** The statement's source text, exactly as written, without its delimiter. */
|
| 55 |
+
+ public String getSql() {
|
| 56 |
+
+ return sql;
|
| 57 |
+
+ }
|
| 58 |
+
+
|
| 59 |
+
+ /** The strict parser's message for this text, positions counted from the start of the whole script. */
|
| 60 |
+
+ public String getError() {
|
| 61 |
+
+ return error;
|
| 62 |
+
+ }
|
| 63 |
+
+
|
| 64 |
+
+ public int getLine() {
|
| 65 |
+
+ return line;
|
| 66 |
+
+ }
|
| 67 |
+
+
|
| 68 |
+
+ public int getColumn() {
|
| 69 |
+
+ return column;
|
| 70 |
+
+ }
|
| 71 |
+
+
|
| 72 |
+
+ @Override
|
| 73 |
+
+ protected void accept0(SQLASTVisitor v) {
|
| 74 |
+
+ // nothing to visit
|
| 75 |
+
+ }
|
| 76 |
+
+
|
| 77 |
+
+ @Override
|
| 78 |
+
+ public void output(StringBuilder buf) {
|
| 79 |
+
+ buf.append(sql);
|
| 80 |
+
+ }
|
| 81 |
+
+
|
| 82 |
+
+ @Override
|
| 83 |
+
+ public String toString() {
|
| 84 |
+
+ return sql;
|
| 85 |
+
+ }
|
| 86 |
+
+
|
| 87 |
+
+ @Override
|
| 88 |
+
+ public String toString(VisitorFeature... features) {
|
| 89 |
+
+ return sql;
|
| 90 |
+
+ }
|
| 91 |
+
+
|
| 92 |
+
+ @Override
|
| 93 |
+
+ public SQLUnparsedStatement clone() {
|
| 94 |
+
+ SQLUnparsedStatement x = new SQLUnparsedStatement(dbType, sql, error, line, column);
|
| 95 |
+
+ x.setAfterSemi(afterSemi);
|
| 96 |
+
+ return x;
|
| 97 |
+
+ }
|
| 98 |
+
+}
|
| 99 |
+
diff --git a/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java b/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java
|
| 100 |
+
new file mode 100644
|
| 101 |
+
index 0000000..9fba816
|
| 102 |
+
--- /dev/null
|
| 103 |
+
+++ b/core/src/main/java/com/alibaba/druid/sql/parser/LenientScriptParser.java
|
| 104 |
+
@@ -0,0 +1,462 @@
|
| 105 |
+
+package com.alibaba.druid.sql.parser;
|
| 106 |
+
+
|
| 107 |
+
+import com.alibaba.druid.DbType;
|
| 108 |
+
+import com.alibaba.druid.sql.ast.SQLStatement;
|
| 109 |
+
+import com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement;
|
| 110 |
+
+
|
| 111 |
+
+import java.util.ArrayList;
|
| 112 |
+
+import java.util.List;
|
| 113 |
+
+
|
| 114 |
+
+/**
|
| 115 |
+
+ * Reads a whole script in one lexer pass. Every statement the strict parser reads is returned as today; every
|
| 116 |
+
+ * statement it cannot read is returned as {@link SQLUnparsedStatement} holding its exact source text and the strict
|
| 117 |
+
+ * parser's message for that text, with positions moved to the script. The extent of an unparsed statement is found
|
| 118 |
+
+ * by scanning its tokens with the dialect's block structure (a compound statement is one statement) up to the
|
| 119 |
+
+ * semicolon that ends it at the top level; a statement whose lexer never recovers runs to the end of the input.
|
| 120 |
+
+ */
|
| 121 |
+
+public class LenientScriptParser {
|
| 122 |
+
+ /** the script as handed in */
|
| 123 |
+
+ private final String sql;
|
| 124 |
+
+ /** the text the lexer reads: the parser factory rewrites CRLF to LF, so lexer positions refer to this one */
|
| 125 |
+
+ private final String text;
|
| 126 |
+
+ private final DbType dbType;
|
| 127 |
+
+ private final SQLStatementParser parser;
|
| 128 |
+
+ private final Lexer lexer;
|
| 129 |
+
+
|
| 130 |
+
+ public LenientScriptParser(String sql, DbType dbType) {
|
| 131 |
+
+ this.sql = sql;
|
| 132 |
+
+ this.dbType = dbType == null ? DbType.other : dbType;
|
| 133 |
+
+ this.parser = SQLParserUtils.createSQLStatementParser(sql, this.dbType, new SQLParserFeature[0]);
|
| 134 |
+
+ this.lexer = parser.getLexer();
|
| 135 |
+
+ this.text = lexer.text;
|
| 136 |
+
+ }
|
| 137 |
+
+
|
| 138 |
+
+ /** original offset of a normalized offset; end = true maps the exclusive end of a slice */
|
| 139 |
+
+ private int orig(int idx, boolean end) {
|
| 140 |
+
+ if (text.length() == sql.length()) {
|
| 141 |
+
+ return idx;
|
| 142 |
+
+ }
|
| 143 |
+
+ if (end) {
|
| 144 |
+
+ if (idx <= 0) {
|
| 145 |
+
+ return 0;
|
| 146 |
+
+ }
|
| 147 |
+
+ return orig(idx - 1, false) + 1;
|
| 148 |
+
+ }
|
| 149 |
+
+ // walk both strings: every "\r\n" of the original is one "\n" of the text
|
| 150 |
+
+ int j = 0;
|
| 151 |
+
+ for (int i = 0; i < idx && j < sql.length(); i++) {
|
| 152 |
+
+ if (sql.charAt(j) == '\r' && j + 1 < sql.length() && sql.charAt(j + 1) == '\n' && text.charAt(i) == '\n') {
|
| 153 |
+
+ j++;
|
| 154 |
+
+ }
|
| 155 |
+
+ j++;
|
| 156 |
+
+ }
|
| 157 |
+
+ if (idx < text.length() && j < sql.length() && sql.charAt(j) == '\r' && j + 1 < sql.length() && sql.charAt(j + 1) == '\n' && text.charAt(idx) == '\n') {
|
| 158 |
+
+ j++;
|
| 159 |
+
+ }
|
| 160 |
+
+ return j;
|
| 161 |
+
+ }
|
| 162 |
+
+
|
| 163 |
+
+ public List<SQLStatement> parse() {
|
| 164 |
+
+ List<SQLStatement> out = new ArrayList<SQLStatement>();
|
| 165 |
+
+ while (true) {
|
| 166 |
+
+ // delimiters and comment tokens between statements, handled as the dialect's own loop handles them: the
|
| 167 |
+
+ // base loop hands the comments after a delimiter to the previous statement, Oracle's loop leaves them for
|
| 168 |
+
+ // the next one
|
| 169 |
+
+ try {
|
| 170 |
+
+ while (true) {
|
| 171 |
+
+ while (lexer.token() == Token.MULTI_LINE_COMMENT || lexer.token() == Token.LINE_COMMENT) {
|
| 172 |
+
+ lexer.nextToken();
|
| 173 |
+
+ }
|
| 174 |
+
+ if (lexer.token() != Token.SEMI) {
|
| 175 |
+
+ break;
|
| 176 |
+
+ }
|
| 177 |
+
+ char ch = lexer.ch;
|
| 178 |
+
+ lexer.nextToken();
|
| 179 |
+
+ if (!out.isEmpty()) {
|
| 180 |
+
+ SQLStatement last = out.get(out.size() - 1);
|
| 181 |
+
+ last.setAfterSemi(true);
|
| 182 |
+
+ if (!isOracle() && lexer.isKeepComments()) {
|
| 183 |
+
+ if (ch == '\n' && lexer.getComments() != null && !lexer.getComments().isEmpty()
|
| 184 |
+
+ && !(last instanceof com.alibaba.druid.sql.ast.statement.SQLSetStatement)) {
|
| 185 |
+
+ lexer.getComments().add(0, new String("\n"));
|
| 186 |
+
+ }
|
| 187 |
+
+ last.addAfterComment(lexer.readAndResetComments());
|
| 188 |
+
+ }
|
| 189 |
+
+ }
|
| 190 |
+
+ }
|
| 191 |
+
+ } catch (RuntimeException e) {
|
| 192 |
+
+ // the lexer failed on the first token after a delimiter: that statement runs to the end of the input
|
| 193 |
+
+ addUnparsed(out, firstTokenStart(lexer.mark), text.length());
|
| 194 |
+
+ return out;
|
| 195 |
+
+ }
|
| 196 |
+
+ if (lexer.token() == Token.EOF) {
|
| 197 |
+
+ break;
|
| 198 |
+
+ }
|
| 199 |
+
+ Lexer.SavePoint sp = lexer.mark();
|
| 200 |
+
+ int before = out.size();
|
| 201 |
+
+ boolean ok;
|
| 202 |
+
+ try {
|
| 203 |
+
+ // one statement through the dialect's own loop, which also consumes delimiters and comments as today
|
| 204 |
+
+ parser.parseStatementList(out, before + 1, null);
|
| 205 |
+
+ // what the strict loop accepted as one statement is one statement; only delimiters and comments
|
| 206 |
+
+ // followed by the end of the input add nothing
|
| 207 |
+
+ ok = out.size() == before + 1 || (out.size() == before && lexer.token() == Token.EOF);
|
| 208 |
+
+ } catch (RuntimeException e) {
|
| 209 |
+
+ ok = false;
|
| 210 |
+
+ }
|
| 211 |
+
+ if (ok) {
|
| 212 |
+
+ if (out.size() == before) {
|
| 213 |
+
+ break;
|
| 214 |
+
+ }
|
| 215 |
+
+ continue;
|
| 216 |
+
+ }
|
| 217 |
+
+ while (out.size() > before) {
|
| 218 |
+
+ out.remove(out.size() - 1);
|
| 219 |
+
+ }
|
| 220 |
+
+ lexer.reset(sp);
|
| 221 |
+
+ int[] se = skipStatement();
|
| 222 |
+
+ addUnparsed(out, se[0], se[1]);
|
| 223 |
+
+ if (se[1] >= text.length()) {
|
| 224 |
+
+ return out;
|
| 225 |
+
+ }
|
| 226 |
+
+ // the lexer stands on the delimiter; the next round's strict loop consumes it as today
|
| 227 |
+
+ }
|
| 228 |
+
+ return out;
|
| 229 |
+
+ }
|
| 230 |
+
+
|
| 231 |
+
+ /**
|
| 232 |
+
+ * The lexer's startPos for a token that follows kept comments points at the first comment; the statement's text
|
| 233 |
+
+ * begins at its first token, so step over whitespace and comments from there (offsets in the lexer's text).
|
| 234 |
+
+ */
|
| 235 |
+
+ private int firstTokenStart(int from) {
|
| 236 |
+
+ int i = from < 0 ? 0 : from;
|
| 237 |
+
+ int n = text.length();
|
| 238 |
+
+ while (i < n) {
|
| 239 |
+
+ char c = text.charAt(i);
|
| 240 |
+
+ if (Character.isWhitespace(c)) {
|
| 241 |
+
+ i++;
|
| 242 |
+
+ } else if (c == '-' && i + 1 < n && text.charAt(i + 1) == '-') {
|
| 243 |
+
+ while (i < n && text.charAt(i) != '\n') {
|
| 244 |
+
+ i++;
|
| 245 |
+
+ }
|
| 246 |
+
+ } else if (c == '#' && isMySql()) {
|
| 247 |
+
+ while (i < n && text.charAt(i) != '\n') {
|
| 248 |
+
+ i++;
|
| 249 |
+
+ }
|
| 250 |
+
+ } else if (c == '/' && i + 1 < n && text.charAt(i + 1) == '*') {
|
| 251 |
+
+ int close = text.indexOf("*/", i + 2);
|
| 252 |
+
+ if (close < 0) {
|
| 253 |
+
+ return i;
|
| 254 |
+
+ }
|
| 255 |
+
+ i = close + 2;
|
| 256 |
+
+ } else {
|
| 257 |
+
+ break;
|
| 258 |
+
+ }
|
| 259 |
+
+ }
|
| 260 |
+
+ return i;
|
| 261 |
+
+ }
|
| 262 |
+
+
|
| 263 |
+
+ /** start and end are offsets in the lexer's text; the item keeps the original characters */
|
| 264 |
+
+ private void addUnparsed(List<SQLStatement> out, int start, int end) {
|
| 265 |
+
+ if (start < 0) {
|
| 266 |
+
+ start = 0;
|
| 267 |
+
+ }
|
| 268 |
+
+ if (end > text.length()) {
|
| 269 |
+
+ end = text.length();
|
| 270 |
+
+ }
|
| 271 |
+
+ if (end < start) {
|
| 272 |
+
+ end = start;
|
| 273 |
+
+ }
|
| 274 |
+
+ int oStart = orig(start, false);
|
| 275 |
+
+ int oEnd = end >= text.length() ? sql.length() : orig(end, true);
|
| 276 |
+
+ if (oEnd < oStart) {
|
| 277 |
+
+ oEnd = oStart;
|
| 278 |
+
+ }
|
| 279 |
+
+ start = oStart;
|
| 280 |
+
+ String item = sql.substring(oStart, oEnd);
|
| 281 |
+
+ String msg = strictMessage(item);
|
| 282 |
+
+ int line = 1, col = 1;
|
| 283 |
+
+ for (int i = 0; i < start; i++) {
|
| 284 |
+
+ if (sql.charAt(i) == '\n') {
|
| 285 |
+
+ line++;
|
| 286 |
+
+ col = 1;
|
| 287 |
+
+ } else {
|
| 288 |
+
+ col++;
|
| 289 |
+
+ }
|
| 290 |
+
+ }
|
| 291 |
+
+ String moved = move(msg, start, line, col);
|
| 292 |
+
+ int[] lc = lineCol(moved);
|
| 293 |
+
+ SQLUnparsedStatement u = new SQLUnparsedStatement(dbType, item, moved, lc[0], lc[1]);
|
| 294 |
+
+ out.add(u);
|
| 295 |
+
+ }
|
| 296 |
+
+
|
| 297 |
+
+ /** The strict parser's message for the text on its own. */
|
| 298 |
+
+ private String strictMessage(String text) {
|
| 299 |
+
+ try {
|
| 300 |
+
+ SQLStatementParser p = SQLParserUtils.createSQLStatementParser(text, dbType, new SQLParserFeature[0]);
|
| 301 |
+
+ List<SQLStatement> l = new ArrayList<SQLStatement>();
|
| 302 |
+
+ p.parseStatementList(l, -1, null);
|
| 303 |
+
+ if (p.getLexer().token() != Token.EOF) {
|
| 304 |
+
+ return "syntax error : " + p.getLexer().info();
|
| 305 |
+
+ }
|
| 306 |
+
+ return "syntax error";
|
| 307 |
+
+ } catch (RuntimeException e) {
|
| 308 |
+
+ return e.getMessage() == null ? e.toString() : e.getMessage();
|
| 309 |
+
+ }
|
| 310 |
+
+ }
|
| 311 |
+
+
|
| 312 |
+
+ // ------------------------------------------------------------------ extent
|
| 313 |
+
+
|
| 314 |
+
+ private boolean isMySql() {
|
| 315 |
+
+ return dbType == DbType.mysql || dbType == DbType.mariadb || dbType == DbType.tidb || dbType == DbType.oceanbase
|
| 316 |
+
+ || dbType == DbType.polardbx || dbType == DbType.drds || dbType == DbType.ads;
|
| 317 |
+
+ }
|
| 318 |
+
+
|
| 319 |
+
+ private boolean isOracle() {
|
| 320 |
+
+ return dbType == DbType.oracle || dbType == DbType.oceanbase_oracle || dbType == DbType.polardb2;
|
| 321 |
+
+ }
|
| 322 |
+
+
|
| 323 |
+
+ private boolean isSqlServer() {
|
| 324 |
+
+ return dbType == DbType.sqlserver || dbType == DbType.jtds;
|
| 325 |
+
+ }
|
| 326 |
+
+
|
| 327 |
+
+ private boolean isPg() {
|
| 328 |
+
+ return dbType == DbType.postgresql || dbType == DbType.edb || dbType == DbType.greenplum || dbType == DbType.gaussdb
|
| 329 |
+
+ || dbType == DbType.hologres || dbType == DbType.redshift;
|
| 330 |
+
+ }
|
| 331 |
+
+
|
| 332 |
+
+ /**
|
| 333 |
+
+ * From the first token of a statement, scan to the delimiter ending it as a top level statement. Returns the end
|
| 334 |
+
+ * offset (exclusive) of its last token and leaves the lexer on that delimiter (or EOF). When the lexer cannot read
|
| 335 |
+
+ * on, the statement runs to the end of the input.
|
| 336 |
+
+ */
|
| 337 |
+
+ private int[] skipStatement() {
|
| 338 |
+
+ // leading delimiters and comment tokens belong to no statement
|
| 339 |
+
+ try {
|
| 340 |
+
+ while (lexer.token() == Token.SEMI || lexer.token() == Token.MULTI_LINE_COMMENT || lexer.token() == Token.LINE_COMMENT) {
|
| 341 |
+
+ lexer.nextToken();
|
| 342 |
+
+ }
|
| 343 |
+
+ } catch (RuntimeException e) {
|
| 344 |
+
+ // the lexer failed on the first token: that statement runs to the end of the input
|
| 345 |
+
+ return new int[] {firstTokenStart(lexer.mark), text.length()};
|
| 346 |
+
+ }
|
| 347 |
+
+ int start = firstTokenStart(lexer.startPos);
|
| 348 |
+
+ if (lexer.token() == Token.EOF) {
|
| 349 |
+
+ return new int[] {start, start};
|
| 350 |
+
+ }
|
| 351 |
+
+ int depth = 0;
|
| 352 |
+
+ // per depth: whether the next BEGIN at this level is the body of an already opened block (DECLARE, IS/AS)
|
| 353 |
+
+ boolean[] absorb = new boolean[256];
|
| 354 |
+
+ int end = lexer.pos();
|
| 355 |
+
+ boolean stmtStart = true;
|
| 356 |
+
+ boolean afterEnd = false;
|
| 357 |
+
+ boolean routinePending = false;
|
| 358 |
+
+ Token prev = null;
|
| 359 |
+
+ while (true) {
|
| 360 |
+
+ Token t = lexer.token();
|
| 361 |
+
+ if (t == Token.EOF) {
|
| 362 |
+
+ return new int[] {start, end};
|
| 363 |
+
+ }
|
| 364 |
+
+ if (t == Token.ERROR) {
|
| 365 |
+
+ // a literal, quoted name or comment the lexer could not close runs to the end of the input;
|
| 366 |
+
+ // any other unreadable character is just a token of the statement
|
| 367 |
+
+ char c = lexer.startPos < text.length() ? text.charAt(lexer.startPos) : ' ';
|
| 368 |
+
+ if (lexer.pos() >= text.length() || c == '\'' || c == '"' || c == '`' || c == '[' || c == '/') {
|
| 369 |
+
+ return new int[] {start, text.length()};
|
| 370 |
+
+ }
|
| 371 |
+
+ }
|
| 372 |
+
+ if (t == Token.SEMI && depth == 0) {
|
| 373 |
+
+ if (isSqlServer()) {
|
| 374 |
+
+ // IF cond stmt; ELSE stmt; is one statement
|
| 375 |
+
+ Lexer.SavePoint sp = lexer.mark();
|
| 376 |
+
+ try {
|
| 377 |
+
+ lexer.nextToken();
|
| 378 |
+
+ } catch (RuntimeException e) {
|
| 379 |
+
+ return new int[] {start, text.length()};
|
| 380 |
+
+ }
|
| 381 |
+
+ if (lexer.token() == Token.ELSE) {
|
| 382 |
+
+ prev = Token.SEMI;
|
| 383 |
+
+ stmtStart = true;
|
| 384 |
+
+ // fall through to treat ELSE as an ordinary token
|
| 385 |
+
+ } else {
|
| 386 |
+
+ lexer.reset(sp);
|
| 387 |
+
+ return new int[] {start, end};
|
| 388 |
+
+ }
|
| 389 |
+
+ } else {
|
| 390 |
+
+ return new int[] {start, end};
|
| 391 |
+
+ }
|
| 392 |
+
+ }
|
| 393 |
+
+ t = lexer.token();
|
| 394 |
+
+ boolean startHere = stmtStart;
|
| 395 |
+
+ boolean opener = false;
|
| 396 |
+
+ boolean closerKeyword = false;
|
| 397 |
+
+ if (afterEnd) {
|
| 398 |
+
+ if (t == Token.IF || t == Token.LOOP || t == Token.CASE || t == Token.WHILE || t == Token.REPEAT
|
| 399 |
+
+ || lexer.identifierEquals("TRY") || lexer.identifierEquals("CATCH")) {
|
| 400 |
+
+ closerKeyword = true;
|
| 401 |
+
+ }
|
| 402 |
+
+ afterEnd = false;
|
| 403 |
+
+ }
|
| 404 |
+
+ if (!closerKeyword) {
|
| 405 |
+
+ if (t == Token.BEGIN) {
|
| 406 |
+
+ opener = beginOpensBlock();
|
| 407 |
+
+ if (opener && depth > 0 && absorb[depth]) {
|
| 408 |
+
+ opener = false;
|
| 409 |
+
+ absorb[depth] = false;
|
| 410 |
+
+ }
|
| 411 |
+
+ } else if (t == Token.CASE || t == Token.LOOP) {
|
| 412 |
+
+ opener = true;
|
| 413 |
+
+ } else if (t == Token.IF) {
|
| 414 |
+
+ opener = startHere && !isSqlServer();
|
| 415 |
+
+ } else if (t == Token.WHILE || t == Token.REPEAT) {
|
| 416 |
+
+ opener = startHere && isMySql();
|
| 417 |
+
+ } else if (t == Token.DECLARE) {
|
| 418 |
+
+ if (startHere && (isOracle() || isPg())) {
|
| 419 |
+
+ opener = true;
|
| 420 |
+
+ if (depth + 1 < absorb.length) {
|
| 421 |
+
+ absorb[depth + 1] = true;
|
| 422 |
+
+ }
|
| 423 |
+
+ }
|
| 424 |
+
+ } else if (t == Token.PROCEDURE || t == Token.FUNCTION || lexer.identifierEquals("PACKAGE")) {
|
| 425 |
+
+ if (isOracle() && (startHere || prev == Token.CREATE || prev == Token.REPLACE)) {
|
| 426 |
+
+ routinePending = true;
|
| 427 |
+
+ }
|
| 428 |
+
+ } else if ((t == Token.IS || t == Token.AS) && routinePending) {
|
| 429 |
+
+ routinePending = false;
|
| 430 |
+
+ opener = true;
|
| 431 |
+
+ if (depth + 1 < absorb.length) {
|
| 432 |
+
+ absorb[depth + 1] = true;
|
| 433 |
+
+ }
|
| 434 |
+
+ } else if (t == Token.END) {
|
| 435 |
+
+ if (depth > 0) {
|
| 436 |
+
+ absorb[depth] = false;
|
| 437 |
+
+ depth--;
|
| 438 |
+
+ }
|
| 439 |
+
+ afterEnd = true;
|
| 440 |
+
+ }
|
| 441 |
+
+ }
|
| 442 |
+
+ if (opener) {
|
| 443 |
+
+ depth++;
|
| 444 |
+
+ if (t == Token.BEGIN || t == Token.LOOP || t == Token.CASE || t == Token.IF || t == Token.WHILE || t == Token.REPEAT) {
|
| 445 |
+
+ // a fresh block: nothing pending to absorb at this level unless set above
|
| 446 |
+
+ if (t != Token.BEGIN && depth < absorb.length && !(t == Token.DECLARE)) {
|
| 447 |
+
+ absorb[depth] = absorb[depth] && false;
|
| 448 |
+
+ }
|
| 449 |
+
+ }
|
| 450 |
+
+ }
|
| 451 |
+
+ stmtStart = t == Token.SEMI || t == Token.BEGIN || t == Token.THEN || t == Token.ELSE || t == Token.DO
|
| 452 |
+
+ || t == Token.LOOP || t == Token.EXCEPTION || t == Token.ELSEIF
|
| 453 |
+
+ || (t == Token.VARIANT && lexer.stringVal() != null && lexer.stringVal().startsWith("$"))
|
| 454 |
+
+ || (t == Token.VARIANT && ":".equals(lexer.stringVal()))
|
| 455 |
+
+ || (t == Token.IS || t == Token.AS) && opener
|
| 456 |
+
+ || t == Token.GTGT;
|
| 457 |
+
+ prev = t;
|
| 458 |
+
+ end = lexer.pos();
|
| 459 |
+
+ try {
|
| 460 |
+
+ lexer.nextToken();
|
| 461 |
+
+ } catch (RuntimeException e) {
|
| 462 |
+
+ return new int[] {start, text.length()};
|
| 463 |
+
+ }
|
| 464 |
+
+ }
|
| 465 |
+
+ }
|
| 466 |
+
+
|
| 467 |
+
+ /** BEGIN opens a block unless the dialect reads it as a transaction command. Consumes nothing (peeks and resets). */
|
| 468 |
+
+ private boolean beginOpensBlock() {
|
| 469 |
+
+ if (isOracle()) {
|
| 470 |
+
+ return true;
|
| 471 |
+
+ }
|
| 472 |
+
+ Lexer.SavePoint sp = lexer.mark();
|
| 473 |
+
+ boolean block;
|
| 474 |
+
+ try {
|
| 475 |
+
+ lexer.nextToken();
|
| 476 |
+
+ Token n = lexer.token();
|
| 477 |
+
+ if (isMySql()) {
|
| 478 |
+
+ block = !(n == Token.SEMI || n == Token.EOF || n == Token.IDENTIFIER);
|
| 479 |
+
+ } else if (isSqlServer()) {
|
| 480 |
+
+ block = !(lexer.identifierEquals("TRANSACTION") || lexer.identifierEquals("TRAN") || lexer.identifierEquals("DISTRIBUTED"));
|
| 481 |
+
+ } else {
|
| 482 |
+
+ block = !(n == Token.SEMI || n == Token.EOF || lexer.identifierEquals("WORK") || lexer.identifierEquals("TRANSACTION")
|
| 483 |
+
+ || lexer.identifierEquals("ISOLATION") || lexer.identifierEquals("READ") || lexer.identifierEquals("DEFERRABLE")
|
| 484 |
+
+ || lexer.identifierEquals("NOT"));
|
| 485 |
+
+ }
|
| 486 |
+
+ } catch (RuntimeException e) {
|
| 487 |
+
+ block = true;
|
| 488 |
+
+ }
|
| 489 |
+
+ lexer.reset(sp);
|
| 490 |
+
+ return block;
|
| 491 |
+
+ }
|
| 492 |
+
+
|
| 493 |
+
+ // ------------------------------------------------------------------ positions
|
| 494 |
+
+
|
| 495 |
+
+ /** Rewrites every "pos N, line L, column C" in a message from the statement's frame to the script's. */
|
| 496 |
+
+ static String move(String m, int start, int sLine, int sCol) {
|
| 497 |
+
+ if (m == null) {
|
| 498 |
+
+ return null;
|
| 499 |
+
+ }
|
| 500 |
+
+ StringBuilder sb = new StringBuilder();
|
| 501 |
+
+ int i = 0;
|
| 502 |
+
+ while (true) {
|
| 503 |
+
+ int p = m.indexOf("pos ", i);
|
| 504 |
+
+ if (p < 0) {
|
| 505 |
+
+ sb.append(m.substring(i));
|
| 506 |
+
+ break;
|
| 507 |
+
+ }
|
| 508 |
+
+ int pe = p + 4;
|
| 509 |
+
+ while (pe < m.length() && Character.isDigit(m.charAt(pe))) {
|
| 510 |
+
+ pe++;
|
| 511 |
+
+ }
|
| 512 |
+
+ if (pe == p + 4 || !m.startsWith(", line ", pe)) {
|
| 513 |
+
+ sb.append(m, i, pe);
|
| 514 |
+
+ i = pe;
|
| 515 |
+
+ continue;
|
| 516 |
+
+ }
|
| 517 |
+
+ int le = pe + 7;
|
| 518 |
+
+ while (le < m.length() && Character.isDigit(m.charAt(le))) {
|
| 519 |
+
+ le++;
|
| 520 |
+
+ }
|
| 521 |
+
+ if (le == pe + 7 || !m.startsWith(", column ", le)) {
|
| 522 |
+
+ sb.append(m, i, le);
|
| 523 |
+
+ i = le;
|
| 524 |
+
+ continue;
|
| 525 |
+
+ }
|
| 526 |
+
+ int ce = le + 9;
|
| 527 |
+
+ while (ce < m.length() && Character.isDigit(m.charAt(ce))) {
|
| 528 |
+
+ ce++;
|
| 529 |
+
+ }
|
| 530 |
+
+ if (ce == le + 9) {
|
| 531 |
+
+ sb.append(m, i, ce);
|
| 532 |
+
+ i = ce;
|
| 533 |
+
+ continue;
|
| 534 |
+
+ }
|
| 535 |
+
+ int pos = Integer.parseInt(m.substring(p + 4, pe));
|
| 536 |
+
+ int line = Integer.parseInt(m.substring(pe + 7, le));
|
| 537 |
+
+ int col = Integer.parseInt(m.substring(le + 9, ce));
|
| 538 |
+
+ sb.append(m, i, p).append("pos ").append(pos + start).append(", line ").append(line + sLine - 1)
|
| 539 |
+
+ .append(", column ").append(line == 1 ? col + sCol - 1 : col);
|
| 540 |
+
+ i = ce;
|
| 541 |
+
+ }
|
| 542 |
+
+ return sb.toString();
|
| 543 |
+
+ }
|
| 544 |
+
+
|
| 545 |
+
+ static int[] lineCol(String m) {
|
| 546 |
+
+ if (m == null) {
|
| 547 |
+
+ return new int[] {-1, -1};
|
| 548 |
+
+ }
|
| 549 |
+
+ int li = m.indexOf(", line ");
|
| 550 |
+
+ if (li < 0) {
|
| 551 |
+
+ return new int[] {-1, -1};
|
| 552 |
+
+ }
|
| 553 |
+
+ int l = num(m, li + 7);
|
| 554 |
+
+ int ci = m.indexOf(", column ", li);
|
| 555 |
+
+ int c = ci < 0 ? -1 : num(m, ci + 9);
|
| 556 |
+
+ return new int[] {l, c};
|
| 557 |
+
+ }
|
| 558 |
+
+
|
| 559 |
+
+ static int num(String m, int j) {
|
| 560 |
+
+ int k = j;
|
| 561 |
+
+ while (k < m.length() && Character.isDigit(m.charAt(k))) {
|
| 562 |
+
+ k++;
|
| 563 |
+
+ }
|
| 564 |
+
+ return k == j ? -1 : Integer.parseInt(m.substring(j, k));
|
| 565 |
+
+ }
|
| 566 |
+
+}
|
| 567 |
+
diff --git a/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java b/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java
|
| 568 |
+
new file mode 100644
|
| 569 |
+
index 0000000..9bdc701
|
| 570 |
+
--- /dev/null
|
| 571 |
+
+++ b/core/src/test/java/com/alibaba/druid/bvt/sql/LenientScriptReadTest.java
|
| 572 |
+
@@ -0,0 +1,227 @@
|
| 573 |
+
+package com.alibaba.druid.bvt.sql;
|
| 574 |
+
+
|
| 575 |
+
+import com.alibaba.druid.DbType;
|
| 576 |
+
+import com.alibaba.druid.sql.SQLUtils;
|
| 577 |
+
+import com.alibaba.druid.sql.ast.SQLStatement;
|
| 578 |
+
+import com.alibaba.druid.sql.ast.statement.SQLUnparsedStatement;
|
| 579 |
+
+import org.junit.jupiter.api.Test;
|
| 580 |
+
+
|
| 581 |
+
+import java.util.ArrayList;
|
| 582 |
+
+import java.util.List;
|
| 583 |
+
+import java.util.regex.Matcher;
|
| 584 |
+
+import java.util.regex.Pattern;
|
| 585 |
+
+
|
| 586 |
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
|
| 587 |
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
|
| 588 |
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
|
| 589 |
+
+import static org.junit.jupiter.api.Assertions.fail;
|
| 590 |
+
+
|
| 591 |
+
+/**
|
| 592 |
+
+ * The lenient whole-script read: SQLUtils.parseStatementsLenient returns what the strict call reads as today and the
|
| 593 |
+
+ * rest as SQLUnparsedStatement carrying the statement's exact text and the strict message for that text on its own,
|
| 594 |
+
+ * with pos, line and column counted from the script start.
|
| 595 |
+
+ */
|
| 596 |
+
+public class LenientScriptReadTest {
|
| 597 |
+
+ private static final Pattern POS = Pattern.compile("pos (\\d+), line (\\d+), column (\\d+)");
|
| 598 |
+
+
|
| 599 |
+
+ private static List<SQLUnparsedStatement> unparsedOf(List<SQLStatement> list) {
|
| 600 |
+
+ List<SQLUnparsedStatement> out = new ArrayList<SQLUnparsedStatement>();
|
| 601 |
+
+ for (SQLStatement s : list) {
|
| 602 |
+
+ if (s instanceof SQLUnparsedStatement) {
|
| 603 |
+
+ out.add((SQLUnparsedStatement) s);
|
| 604 |
+
+ }
|
| 605 |
+
+ }
|
| 606 |
+
+ return out;
|
| 607 |
+
+ }
|
| 608 |
+
+
|
| 609 |
+
+ /** the message the strict call gives for a text on its own */
|
| 610 |
+
+ private static String strictMessage(String sql, DbType dbType) {
|
| 611 |
+
+ try {
|
| 612 |
+
+ SQLUtils.parseStatements(sql, dbType);
|
| 613 |
+
+ } catch (Exception e) {
|
| 614 |
+
+ return e.getMessage();
|
| 615 |
+
+ }
|
| 616 |
+
+ fail("the text should not parse on its own: " + sql);
|
| 617 |
+
+ return null;
|
| 618 |
+
+ }
|
| 619 |
+
+
|
| 620 |
+
+ /** the same message with pos, line and column counted from the script start, for a statement starting at (offset, line, column) */
|
| 621 |
+
+ private static String counted(String standalone, int offset, int line, int column) {
|
| 622 |
+
+ Matcher m = POS.matcher(standalone);
|
| 623 |
+
+ StringBuffer sb = new StringBuffer();
|
| 624 |
+
+ while (m.find()) {
|
| 625 |
+
+ int p = Integer.parseInt(m.group(1)), l = Integer.parseInt(m.group(2)), c = Integer.parseInt(m.group(3));
|
| 626 |
+
+ m.appendReplacement(sb, "pos " + (p + offset) + ", line " + (l + line - 1) + ", column " + (l == 1 ? c + column - 1 : c));
|
| 627 |
+
+ }
|
| 628 |
+
+ m.appendTail(sb);
|
| 629 |
+
+ return sb.toString();
|
| 630 |
+
+ }
|
| 631 |
+
+
|
| 632 |
+
+ private static int lineOf(String error) {
|
| 633 |
+
+ Matcher m = POS.matcher(error);
|
| 634 |
+
+ assertTrue(m.find(), error);
|
| 635 |
+
+ return Integer.parseInt(m.group(2));
|
| 636 |
+
+ }
|
| 637 |
+
+
|
| 638 |
+
+ private static int columnOf(String error) {
|
| 639 |
+
+ Matcher m = POS.matcher(error);
|
| 640 |
+
+ assertTrue(m.find(), error);
|
| 641 |
+
+ return Integer.parseInt(m.group(3));
|
| 642 |
+
+ }
|
| 643 |
+
+
|
| 644 |
+
+ @Test
|
| 645 |
+
+ public void allGoodComesBackAsStrict() {
|
| 646 |
+
+ String sql = "select id from t where x = 1; insert into t (a) values (2); update t set a = 3;";
|
| 647 |
+
+ List<SQLStatement> strict = SQLUtils.parseStatements(sql, DbType.mysql);
|
| 648 |
+
+ List<SQLStatement> lenient = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 649 |
+
+ assertEquals(strict.size(), lenient.size());
|
| 650 |
+
+ for (int i = 0; i < strict.size(); ++i) {
|
| 651 |
+
+ assertEquals(strict.get(i).toString(), lenient.get(i).toString());
|
| 652 |
+
+ }
|
| 653 |
+
+ assertTrue(unparsedOf(lenient).isEmpty());
|
| 654 |
+
+ }
|
| 655 |
+
+
|
| 656 |
+
+ @Test
|
| 657 |
+
+ public void badSimpleStatementBetweenGoodOnes() {
|
| 658 |
+
+ String bad = "select a from where a = 1";
|
| 659 |
+
+ String sql = "select 1; " + bad + "; select 3;";
|
| 660 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 661 |
+
+ assertEquals(3, list.size());
|
| 662 |
+
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
|
| 663 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 664 |
+
+
|
| 665 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 666 |
+
+ assertEquals(bad, u.getSql());
|
| 667 |
+
+ assertEquals(bad, u.toString());
|
| 668 |
+
+ String standalone = strictMessage(bad, DbType.mysql);
|
| 669 |
+
+ assertEquals(counted(standalone, 10, 1, 11), u.getError());
|
| 670 |
+
+ assertEquals(lineOf(u.getError()), u.getLine());
|
| 671 |
+
+ assertEquals(columnOf(u.getError()), u.getColumn());
|
| 672 |
+
+ }
|
| 673 |
+
+
|
| 674 |
+
+ @Test
|
| 675 |
+
+ public void errorLineCountedFromScriptStart() {
|
| 676 |
+
+ String sql = "select 1;\nselect * from t where a ==== 1;\nselect 3;";
|
| 677 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 678 |
+
+ assertEquals(3, list.size());
|
| 679 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 680 |
+
+ assertEquals("select * from t where a ==== 1", u.getSql());
|
| 681 |
+
+ assertEquals("ERROR. pos 38, line 2, column 27, token ==", u.getError());
|
| 682 |
+
+ assertEquals(2, u.getLine());
|
| 683 |
+
+ assertEquals(27, u.getColumn());
|
| 684 |
+
+ }
|
| 685 |
+
+
|
| 686 |
+
+ @Test
|
| 687 |
+
+ public void whatFollowsParsesAsTheScriptWithoutIt() {
|
| 688 |
+
+ String script = "select 1; nonsense here; select 2 from t; create table x (id bigint);";
|
| 689 |
+
+ String without = "select 1; select 2 from t; create table x (id bigint);";
|
| 690 |
+
+ List<SQLStatement> lenient = SQLUtils.parseStatementsLenient(script, DbType.mysql);
|
| 691 |
+
+ List<SQLStatement> strict = SQLUtils.parseStatements(without, DbType.mysql);
|
| 692 |
+
+ assertEquals(4, lenient.size());
|
| 693 |
+
+ assertTrue(lenient.get(1) instanceof SQLUnparsedStatement);
|
| 694 |
+
+ assertEquals(strict.get(0).toString(), lenient.get(0).toString());
|
| 695 |
+
+ assertEquals(strict.get(1).toString(), lenient.get(2).toString());
|
| 696 |
+
+ assertEquals(strict.get(2).toString(), lenient.get(3).toString());
|
| 697 |
+
+ }
|
| 698 |
+
+
|
| 699 |
+
+ @Test
|
| 700 |
+
+ public void compoundStatementIsOneStatement() {
|
| 701 |
+
+ String sql = "create procedure p() begin if x > 0 then begin select bad from; end; end if; end; select 7;";
|
| 702 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 703 |
+
+ assertEquals(2, list.size());
|
| 704 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(0);
|
| 705 |
+
+ assertEquals("create procedure p() begin if x > 0 then begin select bad from; end; end if; end", u.getSql());
|
| 706 |
+
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
|
| 707 |
+
+ }
|
| 708 |
+
+
|
| 709 |
+
+ @Test
|
| 710 |
+
+ public void compoundLoopsAreOneStatement() {
|
| 711 |
+
+ String sql = "create procedure p() begin while i < 10 do set i = i + + ; end while; end; select 7;";
|
| 712 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 713 |
+
+ assertEquals(2, list.size());
|
| 714 |
+
+ assertEquals("create procedure p() begin while i < 10 do set i = i + + ; end while; end",
|
| 715 |
+
+ ((SQLUnparsedStatement) list.get(0)).getSql());
|
| 716 |
+
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
|
| 717 |
+
+ }
|
| 718 |
+
+
|
| 719 |
+
+ @Test
|
| 720 |
+
+ public void oracleDeclareSectionBelongsToTheBlock() {
|
| 721 |
+
+ String sql = "begin null; end;\ndeclare x number; begin x := ; end;\nselect 1 from dual;";
|
| 722 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.oracle);
|
| 723 |
+
+ assertEquals(3, list.size());
|
| 724 |
+
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
|
| 725 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 726 |
+
+ assertEquals("declare x number; begin x := ; end", u.getSql());
|
| 727 |
+
+ assertEquals(2, u.getLine());
|
| 728 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 729 |
+
+ }
|
| 730 |
+
+
|
| 731 |
+
+ @Test
|
| 732 |
+
+ public void sqlServerIfElseBranchesAreOneStatement() {
|
| 733 |
+
+ String sql = "if 1 = 1 select bad from; else select 2;\nselect 3;";
|
| 734 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.sqlserver);
|
| 735 |
+
+ assertEquals(2, list.size());
|
| 736 |
+
+ assertEquals("if 1 = 1 select bad from; else select 2", ((SQLUnparsedStatement) list.get(0)).getSql());
|
| 737 |
+
+ assertFalse(list.get(1) instanceof SQLUnparsedStatement);
|
| 738 |
+
+ }
|
| 739 |
+
+
|
| 740 |
+
+ @Test
|
| 741 |
+
+ public void keywordsAsNamesFunctionsModifiersAndTransactionsOpenNothing() {
|
| 742 |
+
+ String sql = "begin; select 1; commit; select if(a, 1, 2) from t; select `end` from t; drop table if exists t2;"
|
| 743 |
+
+ + " delete from where a = 1; select 4;";
|
| 744 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 745 |
+
+ List<SQLUnparsedStatement> bad = unparsedOf(list);
|
| 746 |
+
+ assertEquals(1, bad.size());
|
| 747 |
+
+ assertEquals("delete from where a = 1", bad.get(0).getSql());
|
| 748 |
+
+ assertEquals(8, list.size());
|
| 749 |
+
+ assertFalse(list.get(7) instanceof SQLUnparsedStatement);
|
| 750 |
+
+ }
|
| 751 |
+
+
|
| 752 |
+
+ @Test
|
| 753 |
+
+ public void unclosedStringRunsToTheEndOfTheInput() {
|
| 754 |
+
+ String tail = "select 'abc; select 3;";
|
| 755 |
+
+ String sql = "select 1; " + tail;
|
| 756 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 757 |
+
+ assertEquals(2, list.size());
|
| 758 |
+
+ assertFalse(list.get(0) instanceof SQLUnparsedStatement);
|
| 759 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 760 |
+
+ assertEquals(tail, u.getSql());
|
| 761 |
+
+ assertEquals(counted(strictMessage(tail, DbType.mysql), 10, 1, 11), u.getError());
|
| 762 |
+
+ }
|
| 763 |
+
+
|
| 764 |
+
+ @Test
|
| 765 |
+
+ public void textIsExactUnderCrlf() {
|
| 766 |
+
+ String bad = "select a from where a = 1";
|
| 767 |
+
+ String sql = "select 1;\r\n" + bad + ";\r\nselect 3;";
|
| 768 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 769 |
+
+ assertEquals(3, list.size());
|
| 770 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 771 |
+
+ assertEquals(bad, u.getSql());
|
| 772 |
+
+ assertEquals(2, u.getLine());
|
| 773 |
+
+ assertEquals(counted(strictMessage(bad, DbType.mysql), 11, 2, 1), u.getError());
|
| 774 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 775 |
+
+ }
|
| 776 |
+
+
|
| 777 |
+
+ @Test
|
| 778 |
+
+ public void commentAheadOfABadStatementIsNotPartOfItsText() {
|
| 779 |
+
+ String bad = "select a from where a = 1";
|
| 780 |
+
+ String sql = "select 1;\n-- note\n" + bad + ";\n/* block */ select 3;";
|
| 781 |
+
+ List<SQLStatement> list = SQLUtils.parseStatementsLenient(sql, DbType.mysql);
|
| 782 |
+
+ assertEquals(3, list.size());
|
| 783 |
+
+ SQLUnparsedStatement u = (SQLUnparsedStatement) list.get(1);
|
| 784 |
+
+ assertEquals(bad, u.getSql());
|
| 785 |
+
+ assertEquals(3, u.getLine());
|
| 786 |
+
+ assertEquals(counted(strictMessage(bad, DbType.mysql), 18, 3, 1), u.getError());
|
| 787 |
+
+ assertFalse(list.get(2) instanceof SQLUnparsedStatement);
|
| 788 |
+
+ }
|
| 789 |
+
+
|
| 790 |
+
+ @Test
|
| 791 |
+
+ public void strictEntryPointsUnchanged() {
|
| 792 |
+
+ try {
|
| 793 |
+
+ SQLUtils.parseStatements("select 1; select a from where a = 1; select 3;", DbType.mysql);
|
| 794 |
+
+ fail("the strict call must still fail on a bad statement");
|
| 795 |
+
+ } catch (Exception e) {
|
| 796 |
+
+ assertTrue(e.getMessage().contains("pos "), e.getMessage());
|
| 797 |
+
+ }
|
| 798 |
+
+ }
|
| 799 |
+
+}
|
| 800 |
+
|
| 801 |
+
REFERENCE_PATCH
|
harbor/tasks/druid_lenient_script/task.toml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
artifacts = ["/workspace/submissions/submitted.patch"]
|
| 3 |
+
[metadata]
|
| 4 |
+
task = "druid_lenient_script"
|
| 5 |
+
validation_revision = "coding-rubric-v2"
|
| 6 |
+
[agent]
|
| 7 |
+
timeout_sec = 1800
|
| 8 |
+
user = "1000:1000"
|
| 9 |
+
[environment]
|
| 10 |
+
build_timeout_sec = 1800
|
| 11 |
+
cpus = 2
|
| 12 |
+
memory_mb = 8192
|
| 13 |
+
network_mode = "no-network"
|
| 14 |
+
[verifier]
|
| 15 |
+
timeout_sec = 7200
|
| 16 |
+
user = "0"
|
| 17 |
+
environment_mode = "separate"
|
| 18 |
+
env = { JUDGE_API_KEY = "${JUDGE_API_KEY:-}", JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://openrouter.ai/api/v1}", JUDGE_MODEL = "${JUDGE_MODEL:-anthropic/claude-sonnet-5.5}" }
|
| 19 |
+
[verifier.environment]
|
| 20 |
+
build_timeout_sec = 1800
|
| 21 |
+
cpus = 2
|
| 22 |
+
memory_mb = 8192
|
| 23 |
+
network_mode = "allowlist"
|
| 24 |
+
allowed_hosts = ["openrouter.ai"]
|
| 25 |
+
[[verifier.collect]]
|
| 26 |
+
command = "/opt/task-tools/python -I /opt/task-tools/capture.py"
|
| 27 |
+
user = "0"
|
| 28 |
+
timeout_sec = 900
|
harbor/tasks/druid_lenient_script/tests/Dockerfile
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-druid:source-v9
|
| 2 |
+
USER root
|
| 3 |
+
RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
|
| 4 |
+
RUN chown -R 1000:1000 /hud/grader-runner
|
| 5 |
+
ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
|
| 6 |
+
RUN rm -f /hud/gold.diff
|
| 7 |
+
COPY verify.py evidence.py judge.py config.json test.sh /tests/
|
| 8 |
+
RUN chmod 755 /tests/test.sh
|
| 9 |
+
WORKDIR /app
|
| 10 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/druid_lenient_script/tests/config.json
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"revision": "coding-rubric-v2",
|
| 3 |
+
"task_id": "druid_lenient_script",
|
| 4 |
+
"arguments": {},
|
| 5 |
+
"grader_version": "0.6.17",
|
| 6 |
+
"source_image": "ec-swe-druid:source-v9",
|
| 7 |
+
"source_image_id": "sha256:5f1b83c229945b6e5b8a1967c326e74451ba8dcc61fac88bb8afb7c5f6f3631d",
|
| 8 |
+
"provenance": {
|
| 9 |
+
"repository": "alibaba/druid",
|
| 10 |
+
"environment_id": "4fce1a24-1403-4334-bf16-4501cb4c1d65",
|
| 11 |
+
"build": 9,
|
| 12 |
+
"build_id": "4b38f7d2-3002-4aaf-b77d-d99b6013d8e8",
|
| 13 |
+
"hosted_task": "druid_lenient_script",
|
| 14 |
+
"task_version": 1,
|
| 15 |
+
"source_archive_sha256": "d600f5069d646a71e959d38c9d27873c2cc6fb253ca1491111f71bd28f45c7fc",
|
| 16 |
+
"hosted_revision_argument": "not recorded; the scenario does not read it"
|
| 17 |
+
},
|
| 18 |
+
"criteria": [
|
| 19 |
+
[
|
| 20 |
+
"clean_equals_strict",
|
| 21 |
+
0.0417,
|
| 22 |
+
false,
|
| 23 |
+
"bash",
|
| 24 |
+
1800
|
| 25 |
+
],
|
| 26 |
+
[
|
| 27 |
+
"simple_bad",
|
| 28 |
+
0.0417,
|
| 29 |
+
false,
|
| 30 |
+
"bash",
|
| 31 |
+
1800
|
| 32 |
+
],
|
| 33 |
+
[
|
| 34 |
+
"block_extent",
|
| 35 |
+
0.1761,
|
| 36 |
+
false,
|
| 37 |
+
"bash",
|
| 38 |
+
1800
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
"keyword_context",
|
| 42 |
+
0.1343,
|
| 43 |
+
false,
|
| 44 |
+
"bash",
|
| 45 |
+
1800
|
| 46 |
+
],
|
| 47 |
+
[
|
| 48 |
+
"lexer_tail",
|
| 49 |
+
0.0927,
|
| 50 |
+
false,
|
| 51 |
+
"bash",
|
| 52 |
+
1800
|
| 53 |
+
],
|
| 54 |
+
[
|
| 55 |
+
"error_identity",
|
| 56 |
+
0.0927,
|
| 57 |
+
false,
|
| 58 |
+
"bash",
|
| 59 |
+
1800
|
| 60 |
+
],
|
| 61 |
+
[
|
| 62 |
+
"mixed",
|
| 63 |
+
0.0833,
|
| 64 |
+
false,
|
| 65 |
+
"bash",
|
| 66 |
+
1800
|
| 67 |
+
],
|
| 68 |
+
[
|
| 69 |
+
"budget",
|
| 70 |
+
0.0833,
|
| 71 |
+
false,
|
| 72 |
+
"bash",
|
| 73 |
+
1800
|
| 74 |
+
],
|
| 75 |
+
[
|
| 76 |
+
"line_endings",
|
| 77 |
+
0.0671,
|
| 78 |
+
false,
|
| 79 |
+
"bash",
|
| 80 |
+
1800
|
| 81 |
+
],
|
| 82 |
+
[
|
| 83 |
+
"comments",
|
| 84 |
+
0.0671,
|
| 85 |
+
false,
|
| 86 |
+
"bash",
|
| 87 |
+
1800
|
| 88 |
+
],
|
| 89 |
+
[
|
| 90 |
+
"wall",
|
| 91 |
+
0.1,
|
| 92 |
+
true,
|
| 93 |
+
"bash",
|
| 94 |
+
3000
|
| 95 |
+
],
|
| 96 |
+
[
|
| 97 |
+
"maintainer_review",
|
| 98 |
+
0.02,
|
| 99 |
+
false,
|
| 100 |
+
"judge",
|
| 101 |
+
600
|
| 102 |
+
]
|
| 103 |
+
],
|
| 104 |
+
"gates": [],
|
| 105 |
+
"reward_rule": "authored",
|
| 106 |
+
"local_hostname": false,
|
| 107 |
+
"fault_exit": null,
|
| 108 |
+
"grader_readable": [],
|
| 109 |
+
"grader_writable": [
|
| 110 |
+
"/hud/grader-runner"
|
| 111 |
+
],
|
| 112 |
+
"blocker_cap": 0.6,
|
| 113 |
+
"empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 114 |
+
"verifier_files": {
|
| 115 |
+
"/app/tasks.py": "410424d675faa18b5da06b612d22b05fbdfe882c73ba41bbeb6eedd3b5b686c2",
|
| 116 |
+
"/app/env.py": "e77d13f90f806a82e710ce2df91341be5bab2ab83c477fa2fd178b8cc573cf64",
|
| 117 |
+
"/app/task/prompt.md": "196f1f60de0d46002f178a6540d15e71c2403c0aa69dd468fb770bd033939fc3",
|
| 118 |
+
"/hud/grader/maintainer_review.judge.json": "54c754dfc30eac8ed0fcc78ac988ae37f337b14ee2953b8470a4adf35f8f0413",
|
| 119 |
+
"/hud/grader/run_grading.sh": "b5595934139fff27473eb59ddfedbb4edf1891e93d3d1615784f893e7bd4d5f6",
|
| 120 |
+
"/hud/grader/lib/budget-agent.jar": "47e3e688e210baa701e90717544375ed2a1ecad2f3186cf0cd14840bb41165e5",
|
| 121 |
+
"/hud/grader/src/BudgetAgent.java": "ef84245cbbb4d8829f4305380db6733be919822744c294bc5813e353efee3ff4",
|
| 122 |
+
"/hud/grader/src/Hidden.java": "dc23fc5ee7be36101bd7bb717200333c8f667fc1394135111d268d13536e303e",
|
| 123 |
+
"/hud/grader/src/BudgetCounter.java": "b4d4ccae9a5fb774e10f49a9ca73256e065e582664dc444746d693b55269971f",
|
| 124 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.sqlserver.expected": "f5f880a13db1857e6035f9a708f56c8bbab040b1a1d22b84ac6c7bf0bb4a16aa",
|
| 125 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.postgresql.sql": "6f62d28b9294d904b2434b17ff3eb85f745f8e6522976e41df9d25a7094229b6",
|
| 126 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.postgresql.clean.sql": "e2bf00f083927874c1099cf1c801f63f1053cbc3784d402520fa482c0ea7016d",
|
| 127 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.postgresql.expected": "6445a61cfe16bb73565a9266fdf027f406fa775ab0308c26638b63ed9681ac6d",
|
| 128 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.oracle.clean.sql": "f32f8a69c2b3f5379ca883590b12cf11ccc050aa1f922b5b6719fe4cc866dab3",
|
| 129 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.sqlserver.sql": "2c296c6be24c3c7f4e468b4d887e4f2c067cd4664d48e5ab519714c8656226d4",
|
| 130 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.oracle.expected": "c4a4a53e96d685fcc0c0cb5ff255b5770a839247663e7a3d9b7cf94dadfffd6a",
|
| 131 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.sqlserver.clean.sql": "25f8b6e05eab128d43e1bd6c928df60c9a2278c2b12e13c0c8e76b88d8a71a03",
|
| 132 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.mysql.sql": "fe647603715bddb5de037e6f91993d0e0ea047b2dd7ba1a320bac2d6f039a32c",
|
| 133 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.oracle.sql": "450c5045a58ddd759c00f7af2c686412165dce75fa6997f7a832da7f913cba41",
|
| 134 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.mysql.clean.sql": "ba2f50c5beffae404d8403aa8ded5b5aa374d9fe1f97988b2ff0fc233e9a62b5",
|
| 135 |
+
"/hud/grader/fixtures/keyword_context/keyword_context.mysql.expected": "9027f7f6d80629950f100316952bd44f55ab9b935fd8a91ca9b689bb1c7d4917",
|
| 136 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.oracle.sql": "add4aedcaafe82f0f4e0864b120a7741ae29dc8109e4a5a27368e9740d48095e",
|
| 137 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.sqlserver.clean.sql": "3024ae747d620baf53e7184674fe499b05b490478b7fd04ac7fc24bac1681d5a",
|
| 138 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.postgresql.expected": "98b24706c0b955030ebd1dc296d30a43e7a4d1e1923fbabf955512ccde5e3d22",
|
| 139 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.oracle.expected": "36d091f8fb9ae38e4b4162da379d94f39c59b97c4e73d802cd2c05c6ef38e2a9",
|
| 140 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.postgresql.sql": "cca8796158ee25718a71251ad370f16c8626b2cf2ea572c86bdc14c214f6088a",
|
| 141 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.postgresql.clean.sql": "cca8796158ee25718a71251ad370f16c8626b2cf2ea572c86bdc14c214f6088a",
|
| 142 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.sqlserver.sql": "3024ae747d620baf53e7184674fe499b05b490478b7fd04ac7fc24bac1681d5a",
|
| 143 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.oracle.clean.sql": "add4aedcaafe82f0f4e0864b120a7741ae29dc8109e4a5a27368e9740d48095e",
|
| 144 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.mysql.sql": "16536841d0b038842cfed4fde2a1c176776a5f5d8cbe332fad25e32fcd4fdad5",
|
| 145 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.mysql.clean.sql": "16536841d0b038842cfed4fde2a1c176776a5f5d8cbe332fad25e32fcd4fdad5",
|
| 146 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.mysql.expected": "fb52855a3ab4ff82710595850f6d1ac2f15f01daffc3aacf71185002e439032f",
|
| 147 |
+
"/hud/grader/fixtures/clean_equals_strict/clean_equals_strict.sqlserver.expected": "96283d91327d3ec5d14f87a89abed4bc53f0ed5240814eae67dae5c1eb79a23e",
|
| 148 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.oracle.sql": "86358dbd104f2a5a8b4c9bb80b4e63b43ebd34053390b18430295ff966e2d9bf",
|
| 149 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.mysql.sql": "6a70eb2cfdfa29f43e7f93035be9f78d1b9ce0389cca1d877d448a9370b7a2d3",
|
| 150 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.mysql.clean.sql": "67acb13d238d6e9fe368fa48e5059a76730d5daf6ad61e36a011bf717949b9ef",
|
| 151 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.mysql.expected": "18fde8846a569793208e8c309a9c227a8eafa5875714356544ee8a1b6caeaec1",
|
| 152 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.postgresql.sql": "cf24f7a7d75b08e8e78eb15bae48bfbca56e10cc123b8e7a62f57c4f7d4e6075",
|
| 153 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.sqlserver.sql": "62d0676e1441d69034fb448877b8e881aeefff0686aaf684beabf5f224dbdd54",
|
| 154 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.oracle.clean.sql": "99fe329aaa67b3bfa078c8edaa83276cb2ee2881bbc353d1c3ed1df4461e9268",
|
| 155 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.sqlserver.clean.sql": "5ea4a602179735f1e56c2321d2a30bb3e8d3895ae45f307140d6dfb6348a501c",
|
| 156 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.postgresql.clean.sql": "cb7fb4adb4ba2e514ce005865f0ec564d38f13da6e9059ade8d424949b94ff8c",
|
| 157 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.sqlserver.expected": "bd924f7b9203b13ebf28d8512ee628ebdf8f35a7b8bf574989a15a2ab0457663",
|
| 158 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.postgresql.expected": "a206593ca02a891afdbf01599c9f7e23b33144a74812aed7a9c4f6ac4d0a0ac6",
|
| 159 |
+
"/hud/grader/fixtures/simple_bad/simple_bad.oracle.expected": "10e45104ab2e52edbb60e9e5574b212d16e331ce32440100240eef97e1ff162b",
|
| 160 |
+
"/hud/grader/fixtures/block_extent/block_extent.postgresql.clean.sql": "6f8b13dc632e53b8fbbc66bcc7a7e22fdf36d1232c999c9fef064e0283c66dbf",
|
| 161 |
+
"/hud/grader/fixtures/block_extent/block_extent.mysql.clean.sql": "cbb3164274f0e6503bca21365ae1fdcc4f2ef0a124d75f3a92519018fda561e5",
|
| 162 |
+
"/hud/grader/fixtures/block_extent/block_extent.sqlserver.clean.sql": "d6e205602e295dfa60ca69f7e116f59f10e2070b24b6fb6b67f590f56f3af3dd",
|
| 163 |
+
"/hud/grader/fixtures/block_extent/block_extent.mysql.expected": "99e412d825fe24e8ce588ea0057c9e82880941b51793c403f2b2bd6223b10dbf",
|
| 164 |
+
"/hud/grader/fixtures/block_extent/block_extent.oracle.clean.sql": "e0fea6bc9aa58e939107749ab20ac20b75903b5759a9b2a1a5675f5f4c50cb35",
|
| 165 |
+
"/hud/grader/fixtures/block_extent/block_extent.oracle.sql": "c4d57a411781daecf57849f6d54b978bcfdeabc44ee6c17447f7e602043e48a6",
|
| 166 |
+
"/hud/grader/fixtures/block_extent/block_extent.sqlserver.expected": "90effc22535965223f0bcc2f55d83fcf4a4ca0df28aefefc998d612e3711dfa2",
|
| 167 |
+
"/hud/grader/fixtures/block_extent/block_extent.sqlserver.sql": "34d0684ff39d1270f6c11e5d8b4dfeb4f03df12329855aabb7f9836c1e2abe25",
|
| 168 |
+
"/hud/grader/fixtures/block_extent/block_extent.postgresql.sql": "1cca12ebd07a55a5bb5ebf5f63492f13e26e984d902f4f07d10b9f4c6cdc115d",
|
| 169 |
+
"/hud/grader/fixtures/block_extent/block_extent.mysql.sql": "75f23ccd11e80b3abac102becda459f5bf47d455021c91b94f55f863ac5cf49b",
|
| 170 |
+
"/hud/grader/fixtures/block_extent/block_extent.oracle.expected": "9956862d75d073bb1726dfb75d86e10305faa0c808437b5e705b1fa7ba68bae7",
|
| 171 |
+
"/hud/grader/fixtures/block_extent/block_extent.postgresql.expected": "ea3cc5fba461b8c352709a0d0bad6c8a1b33a404e3fd8e4737c2fdb25d0d28ff",
|
| 172 |
+
"/hud/grader/fixtures/comments/comments.sqlserver.expected": "b8cb3759c77bee28897da159187068292f998248b171dd97dada5307dbcb30fa",
|
| 173 |
+
"/hud/grader/fixtures/comments/comments.oracle.sql": "1a785a5295f1e3f806432c50b29007df68a071b588153d77eb94925b198c841d",
|
| 174 |
+
"/hud/grader/fixtures/comments/comments.mysql.sql": "1134594012868337098e29e878cf59430b41863ca5335c621675ba0142bc664d",
|
| 175 |
+
"/hud/grader/fixtures/comments/comments.sqlserver.clean.sql": "f26f79f328556f06cdaedb6290a1381fb1b5759b35299f905148bb63a43e9cef",
|
| 176 |
+
"/hud/grader/fixtures/comments/comments.oracle.clean.sql": "b89de53897ff885921ce516d8bfcf6a3a7ea8798cb39405dbd9b1dff37257d28",
|
| 177 |
+
"/hud/grader/fixtures/comments/comments.postgresql.sql": "08c130beeb2cc5dd7e2eee5cdbde06ead2d7b440a6a584aabfea31cd12a02407",
|
| 178 |
+
"/hud/grader/fixtures/comments/comments.oracle.expected": "7df627031e262f805de6a64f527eeddecef21aeff528c02923a01fcae7b6a7cd",
|
| 179 |
+
"/hud/grader/fixtures/comments/comments.sqlserver.sql": "ba1f8d95cccc201951b570653d66006bedb5b06c6e360e3e1c1c9053bca89a1d",
|
| 180 |
+
"/hud/grader/fixtures/comments/comments.mysql.clean.sql": "45fc52e95ae5bd7550d32d74e746d4220001bce017e1c1d8c0e3a80ad95ed8d7",
|
| 181 |
+
"/hud/grader/fixtures/comments/comments.postgresql.expected": "51558f1629294fb591011c6448a3f5fa03d2e2066e2e9af49d94d16e018c9438",
|
| 182 |
+
"/hud/grader/fixtures/comments/comments.postgresql.clean.sql": "fcb10ef1200b2bc7137b4f48bbd4a9137cfa99b5abd89c86cf95d8ebf74ee2ac",
|
| 183 |
+
"/hud/grader/fixtures/comments/comments.mysql.expected": "2dcbf978e509c56b97413e67c67510b63c9f248ad90cb065bece413f0d346721",
|
| 184 |
+
"/hud/grader/fixtures/mixed/mixed.sqlserver.expected": "fdda2566bf1a83139556afd34de4c9a3ae41be6d121548a21133da6b555b64b0",
|
| 185 |
+
"/hud/grader/fixtures/mixed/mixed.postgresql.expected": "dec9256dd2bf0b428704ee9a125aabd3a82ce679e0b5e974fba9e4b43615d3fe",
|
| 186 |
+
"/hud/grader/fixtures/mixed/mixed.oracle.expected": "f464879018a173ca6fb0566fcbe0df8b313fcc28268cb2fa7c4e096e82b6b9af",
|
| 187 |
+
"/hud/grader/fixtures/mixed/mixed.oracle.clean.sql": "5289adca97630e277e9907107e688f394037bfd454351b8acc351151a47c7cd1",
|
| 188 |
+
"/hud/grader/fixtures/mixed/mixed.postgresql.sql": "1de6a80b44ba9e54f59db3c09cdd918d21ae55db4700bbf6a1ce087b908ed853",
|
| 189 |
+
"/hud/grader/fixtures/mixed/mixed.mysql.expected": "521e9e48bf4c433a1e0059386e6989fed46ba472eef3f0e18b1de26de59942fd",
|
| 190 |
+
"/hud/grader/fixtures/mixed/mixed.sqlserver.sql": "ab3769eb7bc2a620d60b010f41fa28ad0d872da1ace192dee72f07e62b34b318",
|
| 191 |
+
"/hud/grader/fixtures/mixed/mixed.mysql.sql": "3c797df67335c00fe2626aabff3b2d3cd50b0f45475f18d7715bf72a526d2244",
|
| 192 |
+
"/hud/grader/fixtures/mixed/mixed.mysql.clean.sql": "c78d52eca76b94e9ae695d2fa92b9d379d74e7e9aecf5cc8c89272c573197261",
|
| 193 |
+
"/hud/grader/fixtures/mixed/mixed.postgresql.clean.sql": "3773327c9207cd0bffc6c6cd6d358f525ea1621ad55e5c1579091ce6b00c374a",
|
| 194 |
+
"/hud/grader/fixtures/mixed/mixed.oracle.sql": "aea596b0f04354ca83de0f02f8a37f9ef2b25e3820189f1821f136f652255150",
|
| 195 |
+
"/hud/grader/fixtures/mixed/mixed.sqlserver.clean.sql": "9ae85b0a289df63f0199dc4dd5099b54128f3e849937f2dbe491d669ea771fe2",
|
| 196 |
+
"/hud/grader/fixtures/line_endings/line_endings.sqlserver.sql": "4883eee6a6b4e1cf88af74a0ebe3b4df469303d4625f48fc42c0a25b948748e9",
|
| 197 |
+
"/hud/grader/fixtures/line_endings/line_endings.oracle.expected": "fc17dae0db0fc422f6e81f3f494ab98046d95dca0736be46801551d65710f9a1",
|
| 198 |
+
"/hud/grader/fixtures/line_endings/line_endings.mysql.expected": "8353c892f4a71fe583785fad8b3d69e317c9cf96f53cb463688ec83ff7159809",
|
| 199 |
+
"/hud/grader/fixtures/line_endings/line_endings.mysql.sql": "c255b176ab699aa49f5076dba8a10acb3effdd378851f8dc7e119dce1edf3245",
|
| 200 |
+
"/hud/grader/fixtures/line_endings/line_endings.sqlserver.clean.sql": "6ae2ed9b17d696c17f06347cc11aa0fb077c64c0317d44a6e789dd94f806dd66",
|
| 201 |
+
"/hud/grader/fixtures/line_endings/line_endings.sqlserver.expected": "1b8b73744b5094824dc8a5ae9ae71910597adc0976763f6ef6c86622ae38ac9b",
|
| 202 |
+
"/hud/grader/fixtures/line_endings/line_endings.oracle.sql": "f2f9702f45f1762a4df9cee57db6082471fe5d86663cc11d7f785cde570f891b",
|
| 203 |
+
"/hud/grader/fixtures/line_endings/line_endings.oracle.clean.sql": "d0d639b46d555a409082de1d59de6d6ad0434b21f178a1546d6a99583865ef88",
|
| 204 |
+
"/hud/grader/fixtures/line_endings/line_endings.postgresql.expected": "df42466380c25e23f5becc0afa306693c74371442c6d1f2358452a8c3aa5f358",
|
| 205 |
+
"/hud/grader/fixtures/line_endings/line_endings.postgresql.sql": "86f23839b192a4f93179a2a1c2f0e1d24a1d7bae996c2418461c53a160d889c7",
|
| 206 |
+
"/hud/grader/fixtures/line_endings/line_endings.postgresql.clean.sql": "9e2b2cd3d197b12abeff88d8d6b9a5102c102f42ebb944e6caee1111e6fa1271",
|
| 207 |
+
"/hud/grader/fixtures/line_endings/line_endings.mysql.clean.sql": "94957946316a79fcb8045b3144ccae66773b060777cb2fad5a9bfd0aad62e67a",
|
| 208 |
+
"/hud/grader/fixtures/budget/budget.mysql.expected": "07bee126cc83afc0c1fec82d58b6ad59b7a49d8ad56468f1cd0e5eca3210a7e0",
|
| 209 |
+
"/hud/grader/fixtures/budget/budget.mysql.clean.sql": "01483a80afd6fda225e58b49f564ba613a503b96c1051b5d28b0ea254107ad80",
|
| 210 |
+
"/hud/grader/fixtures/budget/budget.sqlserver.expected": "78cae58e75584566a870943619c588eba3eda6a3a973e0ee51525c87fc4ff0d6",
|
| 211 |
+
"/hud/grader/fixtures/budget/budget.oracle.sql": "a41aa27b241dba9c7690b5b21e256ca792f1234b15e9b41931811e2abca917ca",
|
| 212 |
+
"/hud/grader/fixtures/budget/budget.oracle.expected": "5eeba8ce0d49158efd361221f9db2c361b4b8ef80003c8161e93026631a83bde",
|
| 213 |
+
"/hud/grader/fixtures/budget/budget.sqlserver.clean.sql": "0c6d2048c4f1557540fa0f42d5875e14736c737af3eccecc0b88e8a837033a78",
|
| 214 |
+
"/hud/grader/fixtures/budget/budget.oracle.clean.sql": "c3f0172d6242aeca2b2d645afedfe752eeedb1a217bb394b1093c1bf7911e5f5",
|
| 215 |
+
"/hud/grader/fixtures/budget/budget.postgresql.clean.sql": "1a4f79a991ed90f1501ff3b82ce0201f26e4ae35ccdfb480636996921fb50e7b",
|
| 216 |
+
"/hud/grader/fixtures/budget/budget.postgresql.expected": "735e667a43f1f812e347d67096fb75ee8a3c253748dc3240e8c2ffb5d3a306a8",
|
| 217 |
+
"/hud/grader/fixtures/budget/budget.mysql.sql": "030e8475d8fe10f149eab41f9fba8e88eaf06a02535779b28dbe88730c2aa808",
|
| 218 |
+
"/hud/grader/fixtures/budget/budget.sqlserver.sql": "ff32b9f21b84311fb197453c964f3f4f0b27731cc134ecc773e2a7d7ff5a296d",
|
| 219 |
+
"/hud/grader/fixtures/budget/budget.postgresql.sql": "15fcb623b46dc7ee8c690f0c2ecd513637029daa026563f63a6eb09b6bd27d27",
|
| 220 |
+
"/hud/grader/fixtures/error_identity/error_identity.mysql.expected": "351dd6eed1361178bb680195c697d31d8b6c9a8529bfb7d05e2b9275a3240b7a",
|
| 221 |
+
"/hud/grader/fixtures/error_identity/error_identity.mysql.clean.sql": "01f11cbe6d7a8a8f366c4cf429f3650c047fa6ac45a7bc53ebe45a54cad022bb",
|
| 222 |
+
"/hud/grader/fixtures/error_identity/error_identity.postgresql.expected": "04ea1305d691b9614e20c4fc5375b8cd0ab69958c1370a223337ac4c6f9e3630",
|
| 223 |
+
"/hud/grader/fixtures/error_identity/error_identity.oracle.sql": "7bd557c883d7c230e4022ce844d8fea3dd5a1a40f15f233bd6839f65f2e43df0",
|
| 224 |
+
"/hud/grader/fixtures/error_identity/error_identity.sqlserver.clean.sql": "f35c01e5395098279f255e5d44bf19fc5a161c043e6579cc667cf7313a506622",
|
| 225 |
+
"/hud/grader/fixtures/error_identity/error_identity.sqlserver.sql": "489097faa36bee380409a2d735fbcab9e4e4d16d8258263cf65ec93fd02aa06c",
|
| 226 |
+
"/hud/grader/fixtures/error_identity/error_identity.sqlserver.expected": "893ca3c638cef458c7fa0f16b8cd07f3afada1cc53c21d97fe96820fc9485e55",
|
| 227 |
+
"/hud/grader/fixtures/error_identity/error_identity.oracle.expected": "4a59b303bf1ad531f92769609241806a3c1c5b89009d312f5441bbca50d695ac",
|
| 228 |
+
"/hud/grader/fixtures/error_identity/error_identity.postgresql.clean.sql": "4ac4be1dc824fd808a871f947059fedbe87817066e3cd1cc89903ea9eb0e2443",
|
| 229 |
+
"/hud/grader/fixtures/error_identity/error_identity.oracle.clean.sql": "8c378b64659bf194a2339d37b2700898a36600fd96d0d5690b3885d4a9f2ec9a",
|
| 230 |
+
"/hud/grader/fixtures/error_identity/error_identity.postgresql.sql": "c796ea82da70469a67c654c484154145d24ccbb049400229eaf64eb278324a48",
|
| 231 |
+
"/hud/grader/fixtures/error_identity/error_identity.mysql.sql": "dfc8aab9881b345fcb24413be752d9f19590357fca757f0c12e708a3f0329832",
|
| 232 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.oracle.clean.sql": "b0ddb5ac8f574b1d1448bc02e6565333cafa377a618d6871b1767a8e12337f6d",
|
| 233 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.sqlserver.clean.sql": "262e93498b82d72ffda9dce3b133a988c24e8d7023a168c22ffc0e9cd077e9f1",
|
| 234 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.mysql.sql": "5900f2a965747f01dea3f54688f8fd6699efb87e07355dcc1bfb7d7f24271c88",
|
| 235 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.oracle.sql": "0a9ff16972a47bcbd5ea92ee1bba9afdb9a6ae9fb5b09cc86348388c57aa4b9f",
|
| 236 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.mysql.expected": "56d079ee888eb48f76ba1e6f21ea8654bf3c2aaf6c6d12ca00c0a889d78fc6c2",
|
| 237 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.postgresql.sql": "2ce8d455b4f960554dfe28f6d1abe2a45239229059558102f493315865293af6",
|
| 238 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.sqlserver.expected": "cfbfb6241a0aa89518ea2767ebd699735fc5df49eb190b6146c25e5a287a4328",
|
| 239 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.oracle.sql": "324cfd3e4a2915790b4301c85bea8c92a11e332da8e3729af2d2dbc69e541313",
|
| 240 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.postgresql.expected": "c4662ab2ccda5798c27a1bae6257ec43c338463ff9addf6d93d1fb5374e947a3",
|
| 241 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.oracle.sql": "3311b4605059b19774a3c1f30b3dbeb64f4e86a7607deea81930fd72e2cfed57",
|
| 242 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.mysql.sql": "e9038561f0478b143050d5a967cdb0662a51ea852b9cbfb36b0121cc66e49458",
|
| 243 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.postgresql.sql": "8b202fe0bde93e6e0f4c78395c646c914db85bb9cd8c2b48cd73cdbbfa25283e",
|
| 244 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.sqlserver.expected": "e06615849d50f44839a411a42b14d0d3b65b9262acbc09650b2e2b6838094fe0",
|
| 245 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.postgresql.clean.sql": "313faf7f26f862b5f52ed232b5c9bc78685f9c70b7ab03c2c10bca9fba7e7466",
|
| 246 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.sqlserver.expected": "b0ee43e8f7a55bd4d640fe9212252474ba48e5a6b60b1ad41c13de89d0f7b7f4",
|
| 247 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.postgresql.expected": "5c61e19384359cc984153ca22cda9ce92c352036cd5c7020eba4930d593c1e52",
|
| 248 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.oracle.expected": "5a5fad0fae2e6508047aefa831a92b4b41f5c2a66e3347169f5a8ae3a7e73df8",
|
| 249 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.mysql.expected": "fe47de4fd9a9a60adaa00415357a0537e89f2e29208c5f49319aa009e14c55f7",
|
| 250 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.sqlserver.clean.sql": "5e88795e075c5b40931ecdcef5c77ec37abadeb5f956370d1123c2aa3ff89361",
|
| 251 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.mysql.clean.sql": "faa67f8f5f5728e03bbe7f3b4ae78c20930ba6d243b4c3d657d2e73730e313af",
|
| 252 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.oracle.clean.sql": "8227d697b5f73f9bb736e6a53184059095f8167076bc16edb5f49e7fdfe83108",
|
| 253 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.postgresql.clean.sql": "33cb36b3ae9be7ea2586daa6585235926718255a14e347271072ec37d5818082",
|
| 254 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.sqlserver.sql": "913c7e50f0a2544dba2e52f578a27b5590bdd278c0787b657bf1294105562600",
|
| 255 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.mysql.clean.sql": "c579e5a660d6901305098ddd794f56cb3037119da2d017d19e21c44991868198",
|
| 256 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.postgresql.expected": "548df167b18e3a45276f3f33ed8ff15e854712eefc8eb43794176d43587e62ab",
|
| 257 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.mysql.clean.sql": "f84dd92f038eea6960970dbcb61219938d06a3ba2358d4afc8b0ae7d8439eed9",
|
| 258 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.oracle.expected": "6e4f011583a1233b72d1123dc702be492575acba49d2dcfa6a3cf9ebf740bc61",
|
| 259 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.oracle.clean.sql": "9a829badaab95515a91ca1160c0ffb0f572a7fdbeeb2f6bb0cad56821ea38bf6",
|
| 260 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.mysql.expected": "ed672295b2f2077c0c56125d5e3a92bfd4bab13b60d08fbbe09d6cbc841e79cb",
|
| 261 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.sqlserver.sql": "86ed93179159b614bb4b8ead77aa044c2147cfcd8590c43d9ed8abb16ab38234",
|
| 262 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-0.sqlserver.sql": "c49a90c5413c5d700148e92df86675be03ce5e6790c0a0f501ef1d187051a3d7",
|
| 263 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.postgresql.sql": "8bdd3ac12f059918cde60a0a62e67689c3c3b1cefa3f2dafb5343b29e7b46347",
|
| 264 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.oracle.expected": "1e4b77a64159dae00be3f085555cde8c5535716af092161711a9b928faee5e88",
|
| 265 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.postgresql.clean.sql": "ced74b5e59c88d84dec58419448a90fed2efd0d4d33a5de92ce1ee959a8a09cd",
|
| 266 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-1.sqlserver.clean.sql": "a98d78a2f6499fa7f7eac0ffe75d7faa67e5a3a1c9330c904e3048f7f21965d0",
|
| 267 |
+
"/hud/grader/fixtures/lexer_tail/lexer_tail-2.mysql.sql": "9d5e6977bfb3c88d15ccd708f1950c6cce9638e53d29e9e8a238b33201220621"
|
| 268 |
+
},
|
| 269 |
+
"preflight": [
|
| 270 |
+
[
|
| 271 |
+
"/bin/bash",
|
| 272 |
+
"--version"
|
| 273 |
+
],
|
| 274 |
+
[
|
| 275 |
+
"setpriv",
|
| 276 |
+
"--version"
|
| 277 |
+
],
|
| 278 |
+
[
|
| 279 |
+
"git",
|
| 280 |
+
"--version"
|
| 281 |
+
],
|
| 282 |
+
[
|
| 283 |
+
"bash",
|
| 284 |
+
"-c",
|
| 285 |
+
"bash -lc 'java -version' || java -version"
|
| 286 |
+
]
|
| 287 |
+
],
|
| 288 |
+
"judge": {
|
| 289 |
+
"base_url": "https://openrouter.ai/api/v1",
|
| 290 |
+
"model": "anthropic/claude-sonnet-5.5",
|
| 291 |
+
"criteria": [
|
| 292 |
+
"maintainer_review"
|
| 293 |
+
],
|
| 294 |
+
"fractional_rows": true
|
| 295 |
+
}
|
| 296 |
+
}
|
harbor/tasks/druid_lenient_script/tests/docker-compose.yaml
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
pids_limit: 512
|
| 4 |
+
security_opt:
|
| 5 |
+
- no-new-privileges:true
|
harbor/tasks/druid_lenient_script/tests/evidence.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate complete coding-rubric evidence without importing the grader library or Harbor."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
REVISION = "coding-rubric-v2"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _number(value: Any) -> float:
|
| 12 |
+
if isinstance(value, bool) or not isinstance(value, (float, int)):
|
| 13 |
+
raise ValueError("Expected numeric rubric evidence")
|
| 14 |
+
if not math.isfinite(value) or not 0 <= value <= 1:
|
| 15 |
+
raise ValueError("Rubric values must be finite and within [0, 1]")
|
| 16 |
+
return float(value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
|
| 20 |
+
"""Check provenance, criterion coverage, weights, caps and command outcomes.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
report, config : dict
|
| 25 |
+
Fresh verifier evidence and the trusted prepared task configuration.
|
| 26 |
+
digest : str
|
| 27 |
+
SHA-256 of the submission collected by Harbor.
|
| 28 |
+
|
| 29 |
+
Raises
|
| 30 |
+
------
|
| 31 |
+
ValueError
|
| 32 |
+
If evidence is missing, inconsistent or reports infrastructure failure.
|
| 33 |
+
"""
|
| 34 |
+
if (
|
| 35 |
+
report.get("revision") != REVISION
|
| 36 |
+
or report.get("task_id") != config["task_id"]
|
| 37 |
+
or report.get("patch_sha256") != digest
|
| 38 |
+
or report.get("grader_version") != config["grader_version"]
|
| 39 |
+
):
|
| 40 |
+
raise ValueError("Verifier evidence provenance mismatch")
|
| 41 |
+
result = report.get("result", {})
|
| 42 |
+
reward = _number(result.get("reward"))
|
| 43 |
+
# A rubric may flag its own result when a grader could not judge. That is
|
| 44 |
+
# admitted only together with proof, checked below, that the same grader
|
| 45 |
+
# reaches a verdict on the untouched repository.
|
| 46 |
+
fault_exit = config.get("fault_exit")
|
| 47 |
+
faults = {
|
| 48 |
+
row["name"]
|
| 49 |
+
for row in report.get("commands", [])
|
| 50 |
+
if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
|
| 51 |
+
}
|
| 52 |
+
flagged = result.get("isError", False)
|
| 53 |
+
if (flagged and not faults) or result.get("done", True) is not True:
|
| 54 |
+
raise ValueError("Grader returned an incomplete or failed evaluation")
|
| 55 |
+
status = report.get("status")
|
| 56 |
+
if status == "rejected_patch":
|
| 57 |
+
if reward != 0 or not report.get("patch_error") or result.get("subscores"):
|
| 58 |
+
raise ValueError("Invalid rejected-patch evidence")
|
| 59 |
+
return
|
| 60 |
+
if status == "empty_patch":
|
| 61 |
+
credited = any(_number(row["value"]) for row in result.get("subscores") or [])
|
| 62 |
+
if reward != 0 or digest != config["empty_sha256"] or report.get("commands") or credited:
|
| 63 |
+
raise ValueError("Invalid empty-patch evidence")
|
| 64 |
+
return
|
| 65 |
+
if status != "graded":
|
| 66 |
+
raise ValueError("Verifier did not complete")
|
| 67 |
+
scores = result.get("subscores")
|
| 68 |
+
expected = {row[0]: row for row in config["criteria"]}
|
| 69 |
+
if not isinstance(scores, list) or len(scores) != len(expected):
|
| 70 |
+
raise ValueError("Missing rubric criteria")
|
| 71 |
+
names = [row["name"] for row in scores]
|
| 72 |
+
if len(set(names)) != len(names) or set(names) != set(expected):
|
| 73 |
+
raise ValueError("Duplicate or unexpected rubric criteria")
|
| 74 |
+
raw = 0.0
|
| 75 |
+
values = {}
|
| 76 |
+
for score in scores:
|
| 77 |
+
name = score["name"]
|
| 78 |
+
value, weight = _number(score["value"]), _number(score["weight"])
|
| 79 |
+
if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
|
| 80 |
+
raise ValueError("Criterion weights changed")
|
| 81 |
+
raw += value * weight
|
| 82 |
+
values[name] = value
|
| 83 |
+
commands = report.get("commands", [])
|
| 84 |
+
command_names = [row["name"] for row in commands]
|
| 85 |
+
expected_commands = set(expected) | set(config["gates"])
|
| 86 |
+
if len(command_names) != len(set(command_names)) or set(command_names) != expected_commands:
|
| 87 |
+
raise ValueError("Missing or duplicate grader command evidence")
|
| 88 |
+
for command in commands:
|
| 89 |
+
info = command.get("info") or {}
|
| 90 |
+
code = info.get("exit_code")
|
| 91 |
+
verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
|
| 92 |
+
if not verdict or info.get("timed_out"):
|
| 93 |
+
raise ValueError("Grader command failed outside its verdict contract")
|
| 94 |
+
if _number(command["value"]) != float(code == 0):
|
| 95 |
+
raise ValueError("Command exit code disagrees with score")
|
| 96 |
+
probes = {row["name"]: row for row in report.get("fault_probes") or []}
|
| 97 |
+
if set(probes) != faults or any(
|
| 98 |
+
row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
|
| 99 |
+
):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"A grader could not judge and the untouched repository does not explain it"
|
| 102 |
+
)
|
| 103 |
+
if any(values.get(name, 0) for name in faults):
|
| 104 |
+
raise ValueError("A criterion its grader could not judge is credited")
|
| 105 |
+
info = result.get("info") or {}
|
| 106 |
+
if info.get("aggregate_mismatch") or info.get("git_apply"):
|
| 107 |
+
raise ValueError("Grader reported inconsistent grading")
|
| 108 |
+
if config.get("reward_rule") == "authored":
|
| 109 |
+
# The task's own function decides the reward. It may take credit away
|
| 110 |
+
# (a cap, a criterion that pays only with progress) but never add any.
|
| 111 |
+
passed = {row["name"]: row["value"] for row in commands}
|
| 112 |
+
if any(values[name] > passed[name] for name in expected):
|
| 113 |
+
raise ValueError("A criterion is credited although its command failed")
|
| 114 |
+
if reward > raw + 1e-9:
|
| 115 |
+
raise ValueError("Grader reward exceeds its weighted criteria")
|
| 116 |
+
return
|
| 117 |
+
failed = {name for name, row in expected.items() if row[2] and values[name] < 1}
|
| 118 |
+
gate_failed = {
|
| 119 |
+
row["name"] for row in commands if row["name"] in config["gates"] and row["value"] < 1
|
| 120 |
+
}
|
| 121 |
+
expected_reward = min(raw, config["blocker_cap"]) if failed or gate_failed else raw
|
| 122 |
+
if not math.isclose(reward, expected_reward, abs_tol=1e-9):
|
| 123 |
+
raise ValueError("Grader reward disagrees with original weights and blocker cap")
|
harbor/tasks/druid_lenient_script/tests/judge.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
"""Verifier entry for a coding rubric with criteria judged by a language model.
|
| 2 |
+
|
| 3 |
+
The packaged verifier (verify.py) grades offline. A rubric with a judged
|
| 4 |
+
criterion runs this file instead, which runs the same grading with three
|
| 5 |
+
differences:
|
| 6 |
+
|
| 7 |
+
- the verifier container reaches the judge's endpoint through Harbor's host
|
| 8 |
+
allowlist, and the judge's key, model and endpoint come from the verifier's
|
| 9 |
+
environment (``JUDGE_API_KEY``, ``JUDGE_MODEL``, ``JUDGE_BASE_URL``);
|
| 10 |
+
- the key is held by this process only. Grader commands run the submission's
|
| 11 |
+
code, so no environment they inherit carries it;
|
| 12 |
+
- the evidence check accepts a criterion the judge answered. A judge that does
|
| 13 |
+
not answer makes the attempt invalid: there is no reward, as for any grader
|
| 14 |
+
that cannot reach a verdict.
|
| 15 |
+
|
| 16 |
+
verify.py and evidence.py are unchanged; this file wraps them.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import importlib
|
| 22 |
+
import math
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
from typing import Any
|
| 26 |
+
from urllib.parse import urlsplit
|
| 27 |
+
|
| 28 |
+
# The key leaves the environment before anything can start a subprocess.
|
| 29 |
+
_KEY = os.environ.pop("JUDGE_API_KEY", "")
|
| 30 |
+
for _name in ("HUD_API_KEY", "OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"):
|
| 31 |
+
os.environ.pop(_name, None)
|
| 32 |
+
_BASE_URL = os.environ.get("JUDGE_BASE_URL") or "https://openrouter.ai/api/v1"
|
| 33 |
+
os.environ["JUDGE_MODEL"] = os.environ.get("JUDGE_MODEL") or "anthropic/claude-sonnet-5.5"
|
| 34 |
+
|
| 35 |
+
import evidence # noqa: E402
|
| 36 |
+
import verify # noqa: E402
|
| 37 |
+
|
| 38 |
+
_preflight = verify._preflight
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _scenario_grade(task: Any) -> Any:
|
| 42 |
+
# A task whose scenario both prompts and grades (druid): its second item is the result.
|
| 43 |
+
async def _grade(validate_mode: str | None) -> Any:
|
| 44 |
+
steps = task._scenario(validate_mode)
|
| 45 |
+
await steps.__anext__()
|
| 46 |
+
return await steps.__anext__()
|
| 47 |
+
|
| 48 |
+
return _grade
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _prepare_task(config: dict[str, Any]) -> None:
|
| 52 |
+
"""Check the verifier as verify.py does, then point the judge at its endpoint."""
|
| 53 |
+
_preflight(config)
|
| 54 |
+
from hud.settings import settings
|
| 55 |
+
|
| 56 |
+
# The judge's client reads these when it is built, from this process alone.
|
| 57 |
+
settings.api_key = _KEY or None
|
| 58 |
+
settings.hud_gateway_url = _BASE_URL
|
| 59 |
+
sys.path.insert(0, "/app")
|
| 60 |
+
task = importlib.import_module("tasks")
|
| 61 |
+
if not hasattr(task, "_setup"):
|
| 62 |
+
task._setup = importlib.import_module("env")._setup
|
| 63 |
+
if not hasattr(task, "_grade"):
|
| 64 |
+
task._grade = _scenario_grade(task)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _judge_error(score: dict[str, Any], result: dict[str, Any]) -> str | None:
|
| 68 |
+
for field in ("metadata", "info"):
|
| 69 |
+
error = (score.get(field) or {}).get("judge_error")
|
| 70 |
+
if error:
|
| 71 |
+
return str(error)
|
| 72 |
+
return ((result.get("info") or {}).get("judge_errors") or {}).get(score["name"])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def validate_judged_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
|
| 76 |
+
"""Check judged evidence as evidence.validate_report checks the rest.
|
| 77 |
+
|
| 78 |
+
Parameters
|
| 79 |
+
----------
|
| 80 |
+
report, config : dict
|
| 81 |
+
Fresh verifier evidence and the trusted prepared task configuration.
|
| 82 |
+
digest : str
|
| 83 |
+
SHA-256 of the submission collected by Harbor.
|
| 84 |
+
|
| 85 |
+
Raises
|
| 86 |
+
------
|
| 87 |
+
ValueError
|
| 88 |
+
If evidence is missing or inconsistent, or the judge did not answer.
|
| 89 |
+
|
| 90 |
+
Notes
|
| 91 |
+
-----
|
| 92 |
+
Judged criteria have no grader command. Every other criterion keeps the
|
| 93 |
+
checks of evidence.py, under its rule for a task's own reward function:
|
| 94 |
+
the reward stays within the weighted criteria, and a criterion whose
|
| 95 |
+
command failed earns nothing unless the task scores that criterion from
|
| 96 |
+
its command's output (``fractional_rows``).
|
| 97 |
+
"""
|
| 98 |
+
report["judge"] = {"model": os.environ["JUDGE_MODEL"], "endpoint": urlsplit(_BASE_URL).hostname}
|
| 99 |
+
if report.get("status") != "graded":
|
| 100 |
+
evidence.validate_report(report, config, digest)
|
| 101 |
+
return
|
| 102 |
+
if (
|
| 103 |
+
report.get("revision") != evidence.REVISION
|
| 104 |
+
or report.get("task_id") != config["task_id"]
|
| 105 |
+
or report.get("patch_sha256") != digest
|
| 106 |
+
or report.get("grader_version") != config["grader_version"]
|
| 107 |
+
):
|
| 108 |
+
raise ValueError("Verifier evidence provenance mismatch")
|
| 109 |
+
result = report.get("result", {})
|
| 110 |
+
reward = evidence._number(result.get("reward"))
|
| 111 |
+
commands = report.get("commands", [])
|
| 112 |
+
fault_exit = config.get("fault_exit")
|
| 113 |
+
faults = {
|
| 114 |
+
row["name"]
|
| 115 |
+
for row in commands
|
| 116 |
+
if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
|
| 117 |
+
}
|
| 118 |
+
if (result.get("isError", False) and not faults) or result.get("done", True) is not True:
|
| 119 |
+
raise ValueError("Grader returned an incomplete or failed evaluation")
|
| 120 |
+
scores = result.get("subscores")
|
| 121 |
+
expected = {row[0]: row for row in config["criteria"]}
|
| 122 |
+
judged = {name for name, row in expected.items() if row[3] == "judge"}
|
| 123 |
+
if not isinstance(scores, list) or len(scores) != len(expected):
|
| 124 |
+
raise ValueError("Missing rubric criteria")
|
| 125 |
+
names = [row["name"] for row in scores]
|
| 126 |
+
if len(set(names)) != len(names) or set(names) != set(expected):
|
| 127 |
+
raise ValueError("Duplicate or unexpected rubric criteria")
|
| 128 |
+
raw = 0.0
|
| 129 |
+
values = {}
|
| 130 |
+
for score in scores:
|
| 131 |
+
name = score["name"]
|
| 132 |
+
error = _judge_error(score, result) if name in judged else None
|
| 133 |
+
if error:
|
| 134 |
+
raise ValueError(f"The judge did not answer for {name}: {error}")
|
| 135 |
+
value, weight = evidence._number(score["value"]), evidence._number(score["weight"])
|
| 136 |
+
if name in judged and value > 0 and not score.get("children"):
|
| 137 |
+
raise ValueError(f"{name} is credited without the judge's verdicts")
|
| 138 |
+
if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
|
| 139 |
+
raise ValueError("Criterion weights changed")
|
| 140 |
+
raw += value * weight
|
| 141 |
+
values[name] = value
|
| 142 |
+
command_names = [row["name"] for row in commands]
|
| 143 |
+
if len(command_names) != len(set(command_names)) or set(command_names) != (
|
| 144 |
+
set(expected) - judged
|
| 145 |
+
) | set(config["gates"]):
|
| 146 |
+
raise ValueError("Missing or duplicate grader command evidence")
|
| 147 |
+
for command in commands:
|
| 148 |
+
info = command.get("info") or {}
|
| 149 |
+
code = info.get("exit_code")
|
| 150 |
+
verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
|
| 151 |
+
if not verdict or info.get("timed_out"):
|
| 152 |
+
raise ValueError("Grader command failed outside its verdict contract")
|
| 153 |
+
if evidence._number(command["value"]) != float(code == 0):
|
| 154 |
+
raise ValueError("Command exit code disagrees with score")
|
| 155 |
+
probes = {row["name"]: row for row in report.get("fault_probes") or []}
|
| 156 |
+
if set(probes) != faults or any(
|
| 157 |
+
row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
|
| 158 |
+
):
|
| 159 |
+
raise ValueError("A grader could not judge and the untouched repository does not explain it")
|
| 160 |
+
if any(values.get(name, 0) for name in faults):
|
| 161 |
+
raise ValueError("A criterion its grader could not judge is credited")
|
| 162 |
+
info = result.get("info") or {}
|
| 163 |
+
if info.get("aggregate_mismatch") or info.get("git_apply"):
|
| 164 |
+
raise ValueError("Grader reported inconsistent grading")
|
| 165 |
+
passed = {row["name"]: row["value"] for row in commands}
|
| 166 |
+
if not config["judge"]["fractional_rows"] and any(
|
| 167 |
+
values[name] > passed[name] for name in expected if name not in judged
|
| 168 |
+
):
|
| 169 |
+
raise ValueError("A criterion is credited although its command failed")
|
| 170 |
+
if reward > raw + 1e-9:
|
| 171 |
+
raise ValueError("Grader reward exceeds its weighted criteria")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
verify._preflight = _prepare_task
|
| 175 |
+
verify.validate_report = validate_judged_report
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
verify.main()
|
harbor/tasks/druid_lenient_script/tests/test.sh
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
mkdir -p /workspace/repo
|
| 4 |
+
git config --global gc.auto 0
|
| 5 |
+
chmod 711 /root
|
| 6 |
+
chmod -R a+rX /root/.m2
|
| 7 |
+
cp -a /root/.m2 /home/agent/.m2
|
| 8 |
+
chown -R 1000:1000 /home/agent/.m2
|
| 9 |
+
/opt/hudenv/bin/python /tests/judge.py
|
harbor/tasks/druid_lenient_script/tests/verify.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the original trusted coding rubric in a fresh, offline verifier container."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import hashlib
|
| 7 |
+
import importlib
|
| 8 |
+
import importlib.metadata
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shlex
|
| 12 |
+
import shutil
|
| 13 |
+
import signal
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
from evidence import REVISION, validate_report
|
| 20 |
+
|
| 21 |
+
OUT = Path("/logs/verifier")
|
| 22 |
+
PRIVATE = Path("/var/lib/task-evidence")
|
| 23 |
+
CONFIG = Path("/tests/config.json")
|
| 24 |
+
PATCH = Path("/workspace/submissions/submitted.patch")
|
| 25 |
+
GRADER_HOME = "/tmp/agent-home"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
|
| 29 |
+
return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _preflight(config: dict[str, Any]) -> None:
|
| 33 |
+
if importlib.metadata.version("hud") != config["grader_version"]:
|
| 34 |
+
raise RuntimeError("Grader library version does not match the task")
|
| 35 |
+
for filename, expected in config["verifier_files"].items():
|
| 36 |
+
if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
|
| 37 |
+
raise RuntimeError(f"Verifier source changed: {filename}")
|
| 38 |
+
for command in config["preflight"]:
|
| 39 |
+
completed = _run(command, cwd="/workspace/repo")
|
| 40 |
+
if completed.returncode:
|
| 41 |
+
raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _readable_mode(path: Path) -> int:
|
| 45 |
+
# World-readable, keeping what is executable so: a grader may ship tools.
|
| 46 |
+
return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _permissions() -> None:
|
| 50 |
+
# The orchestrator owns reports and rubric definitions. Grader commands,
|
| 51 |
+
# and so the candidate's code, run as uid 1000: the user the task installed
|
| 52 |
+
# its toolchain and caches for. They cannot read gold/vault or overwrite
|
| 53 |
+
# the rubric or the result files, which stay root's.
|
| 54 |
+
Path("/hud").chmod(0o711)
|
| 55 |
+
for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
|
| 56 |
+
if root.exists():
|
| 57 |
+
root.chmod(0o755)
|
| 58 |
+
for path in root.rglob("*"):
|
| 59 |
+
if not path.is_symlink():
|
| 60 |
+
path.chmod(_readable_mode(path))
|
| 61 |
+
home = Path(GRADER_HOME)
|
| 62 |
+
home.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
os.chown(home, 1000, 1000)
|
| 64 |
+
for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
|
| 65 |
+
path = Path(directory)
|
| 66 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
for item in (path, *path.rglob("*")):
|
| 68 |
+
if not item.is_symlink():
|
| 69 |
+
os.chown(item, 1000, 1000)
|
| 70 |
+
item.chmod(_readable_mode(item))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _hand_over_checkout() -> None:
|
| 74 |
+
# The original grader runs as root and may run the candidate's own suite in
|
| 75 |
+
# place, which writes into the tree. The rubric resets and re-applies the
|
| 76 |
+
# candidate as root, so give what root touched back to the grading user.
|
| 77 |
+
# Installed dependency trees are large and already that user's.
|
| 78 |
+
subprocess.run(
|
| 79 |
+
[
|
| 80 |
+
"find",
|
| 81 |
+
"/workspace/repo",
|
| 82 |
+
"-path",
|
| 83 |
+
"*/node_modules",
|
| 84 |
+
"-prune",
|
| 85 |
+
"-o",
|
| 86 |
+
"!",
|
| 87 |
+
"-user",
|
| 88 |
+
"1000",
|
| 89 |
+
"-exec",
|
| 90 |
+
"chown",
|
| 91 |
+
"-h",
|
| 92 |
+
"1000:1000",
|
| 93 |
+
"{}",
|
| 94 |
+
"+",
|
| 95 |
+
],
|
| 96 |
+
check=True,
|
| 97 |
+
capture_output=True,
|
| 98 |
+
timeout=3600,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
|
| 103 |
+
_preflight(config)
|
| 104 |
+
sys.path.insert(0, "/app")
|
| 105 |
+
task: Any = importlib.import_module("tasks")
|
| 106 |
+
await task._setup()
|
| 107 |
+
_permissions()
|
| 108 |
+
patch = PATCH.read_bytes()
|
| 109 |
+
if patch:
|
| 110 |
+
checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
|
| 111 |
+
if checked.returncode:
|
| 112 |
+
record.update(
|
| 113 |
+
status="rejected_patch",
|
| 114 |
+
patch_error=checked.stderr[-4000:],
|
| 115 |
+
result={"reward": 0.0, "subscores": None},
|
| 116 |
+
)
|
| 117 |
+
return
|
| 118 |
+
_run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
|
| 119 |
+
original = task.BashGrader
|
| 120 |
+
fault_exit = config.get("fault_exit")
|
| 121 |
+
faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []
|
| 122 |
+
|
| 123 |
+
class ObservedGrader:
|
| 124 |
+
@classmethod
|
| 125 |
+
async def grade(cls, *args: Any, **kwargs: Any) -> Any:
|
| 126 |
+
command = kwargs["command"]
|
| 127 |
+
_hand_over_checkout()
|
| 128 |
+
kwargs["command"] = (
|
| 129 |
+
"setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
|
| 130 |
+
f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
|
| 131 |
+
)
|
| 132 |
+
score = await original.grade(*args, **kwargs)
|
| 133 |
+
snapshot = score.model_dump(mode="json")
|
| 134 |
+
record["commands"].append(snapshot)
|
| 135 |
+
(PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
|
| 136 |
+
info = snapshot.get("info") or {}
|
| 137 |
+
if info.get("timed_out") or type(info.get("exit_code")) is not int:
|
| 138 |
+
raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
|
| 139 |
+
if fault_exit is not None and info["exit_code"] == fault_exit:
|
| 140 |
+
# The grader says it could not judge. Whether the submission or
|
| 141 |
+
# the environment is the reason is settled after grading.
|
| 142 |
+
faulted.append((args, dict(kwargs), snapshot["name"]))
|
| 143 |
+
elif info["exit_code"] not in (0, 1):
|
| 144 |
+
raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
|
| 145 |
+
return score
|
| 146 |
+
|
| 147 |
+
task.BashGrader = ObservedGrader
|
| 148 |
+
result = await task._grade(None)
|
| 149 |
+
if faulted:
|
| 150 |
+
# Ask the same commands about the untouched repository. A verdict there
|
| 151 |
+
# means the grader works here and the submission is what it could not
|
| 152 |
+
# judge, so the criterion stays unmet. No verdict there means the
|
| 153 |
+
# environment is at fault, and the attempt is invalid.
|
| 154 |
+
await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
|
| 155 |
+
await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
|
| 156 |
+
# Graders keep state between criteria, some of them a copy of the tree
|
| 157 |
+
# they judged. It describes the submission, so it goes too.
|
| 158 |
+
for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
|
| 159 |
+
if leftover.is_dir() and not leftover.is_symlink():
|
| 160 |
+
shutil.rmtree(leftover)
|
| 161 |
+
else:
|
| 162 |
+
leftover.unlink()
|
| 163 |
+
record["fault_probes"] = []
|
| 164 |
+
for args, kwargs, name in faulted:
|
| 165 |
+
_hand_over_checkout()
|
| 166 |
+
probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
|
| 167 |
+
info = probe.get("info") or {}
|
| 168 |
+
record["fault_probes"].append(
|
| 169 |
+
{
|
| 170 |
+
"name": name,
|
| 171 |
+
"exit_code": info.get("exit_code"),
|
| 172 |
+
"timed_out": info.get("timed_out"),
|
| 173 |
+
"stdout": (info.get("stdout") or "")[-2000:],
|
| 174 |
+
}
|
| 175 |
+
)
|
| 176 |
+
(PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
|
| 177 |
+
if info.get("timed_out") or info.get("exit_code") not in (0, 1):
|
| 178 |
+
raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
|
| 179 |
+
record["result"] = result.model_dump(mode="json")
|
| 180 |
+
# A rubric may answer an empty change without running any criterion.
|
| 181 |
+
record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _stop_candidate_processes() -> None:
|
| 185 |
+
# A candidate may fork. End its UID's processes before publishing evidence
|
| 186 |
+
# to a host bind mount, whose permissions may differ on Docker Desktop.
|
| 187 |
+
for directory in Path("/proc").iterdir():
|
| 188 |
+
if not directory.name.isdecimal():
|
| 189 |
+
continue
|
| 190 |
+
try:
|
| 191 |
+
status = (directory / "status").read_text()
|
| 192 |
+
uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
|
| 193 |
+
if uid == "1000":
|
| 194 |
+
os.kill(int(directory.name), signal.SIGKILL)
|
| 195 |
+
except (FileNotFoundError, ProcessLookupError):
|
| 196 |
+
pass
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def main() -> None:
|
| 200 |
+
"""Persist structured evidence and publish reward only after validation."""
|
| 201 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 203 |
+
PRIVATE.chmod(0o700)
|
| 204 |
+
reward_path = OUT / "reward.txt"
|
| 205 |
+
reward_path.unlink(missing_ok=True)
|
| 206 |
+
config = json.loads(CONFIG.read_text())
|
| 207 |
+
shutil.copy2(CONFIG, OUT / "config.json")
|
| 208 |
+
record: dict[str, Any] = {
|
| 209 |
+
"revision": REVISION,
|
| 210 |
+
"task_id": config["task_id"],
|
| 211 |
+
"grader_version": importlib.metadata.version("hud"),
|
| 212 |
+
"commands": [],
|
| 213 |
+
"status": "error",
|
| 214 |
+
}
|
| 215 |
+
try:
|
| 216 |
+
if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
|
| 217 |
+
raise ValueError("Missing, oversized or symlink submission")
|
| 218 |
+
record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
|
| 219 |
+
try:
|
| 220 |
+
asyncio.run(_grade(config, record))
|
| 221 |
+
finally:
|
| 222 |
+
_stop_candidate_processes()
|
| 223 |
+
reward_path.unlink(missing_ok=True)
|
| 224 |
+
validate_report(record, config, record["patch_sha256"])
|
| 225 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 226 |
+
reward_path.write_text(str(record["result"]["reward"]) + "\n")
|
| 227 |
+
except BaseException as error:
|
| 228 |
+
reward_path.unlink(missing_ok=True)
|
| 229 |
+
record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
|
| 230 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 231 |
+
raise
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|
harbor/tasks/help_defaults/environment/Dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-click:source-v9 AS sanitized
|
| 2 |
+
USER root
|
| 3 |
+
COPY sanitize.py capture.py capture_submission.py /opt/task-tools/
|
| 4 |
+
RUN HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 /opt/hudvenv/bin/python /opt/task-tools/sanitize.py
|
| 5 |
+
FROM scratch
|
| 6 |
+
COPY --from=sanitized / /
|
| 7 |
+
ENV PATH="/opt/agentvenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
|
| 8 |
+
ENV LANG="C.UTF-8"
|
| 9 |
+
ENV HOME="/tmp/agent-home"
|
| 10 |
+
ENV GOCACHE="/tmp/agent-home/.cache/go-build"
|
| 11 |
+
ENV HUD_TELEMETRY_ENABLED="false"
|
| 12 |
+
ENV HUD_CLI_ANALYTICS_ENABLED="0"
|
| 13 |
+
WORKDIR /workspace/repo
|
| 14 |
+
USER 1000:1000
|
| 15 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/help_defaults/environment/capture.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture a patch against protected baseline history inside the agent sandbox."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, "/opt/task-tools")
|
| 11 |
+
from capture_submission import capture_submission # noqa: E402
|
| 12 |
+
|
| 13 |
+
with tempfile.TemporaryDirectory(prefix="capture-") as directory:
|
| 14 |
+
git_dir = Path(directory) / "git"
|
| 15 |
+
shutil.copytree("/opt/task-tools/baseline.git", git_dir)
|
| 16 |
+
os.environ.update(
|
| 17 |
+
GIT_DIR=str(git_dir),
|
| 18 |
+
GIT_WORK_TREE="/workspace/repo",
|
| 19 |
+
GIT_CONFIG_NOSYSTEM="1",
|
| 20 |
+
GIT_CONFIG_GLOBAL="/dev/null",
|
| 21 |
+
)
|
| 22 |
+
print(
|
| 23 |
+
json.dumps(
|
| 24 |
+
capture_submission(
|
| 25 |
+
Path("/workspace/repo"), Path("/workspace/submissions/submitted.patch")
|
| 26 |
+
)
|
| 27 |
+
)
|
| 28 |
+
)
|
harbor/tasks/help_defaults/environment/capture_submission.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture tracked and new SWE files without changing the agent's Git index."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import shlex
|
| 8 |
+
import subprocess
|
| 9 |
+
import tempfile
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
MAX_SUBMISSION_BYTES = 32 * 1024 * 1024
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def capture_submission(
|
| 16 |
+
repository: Path, output: Path, *, max_bytes: int = MAX_SUBMISSION_BYTES
|
| 17 |
+
) -> dict[str, object]:
|
| 18 |
+
"""Write a bounded binary patch including nonignored new files.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
repository : Path
|
| 23 |
+
Git checkout root. HEAD must remain the task's initial commit.
|
| 24 |
+
output : Path
|
| 25 |
+
Submission path outside the checkout. Replaces any prior submission.
|
| 26 |
+
max_bytes : int, default: 33554432
|
| 27 |
+
Maximum emitted patch size. Oversized submissions fail without a patch.
|
| 28 |
+
|
| 29 |
+
Returns
|
| 30 |
+
-------
|
| 31 |
+
dict
|
| 32 |
+
Patch size, SHA-256, base commit and capture format for trial evidence.
|
| 33 |
+
|
| 34 |
+
Raises
|
| 35 |
+
------
|
| 36 |
+
ValueError
|
| 37 |
+
If paths or the limit are invalid, or the patch exceeds the limit.
|
| 38 |
+
OSError, subprocess.CalledProcessError, RuntimeError
|
| 39 |
+
If capture fails. No partial patch is published.
|
| 40 |
+
|
| 41 |
+
Notes
|
| 42 |
+
-----
|
| 43 |
+
Uses a temporary index to combine staged, unstaged and untracked changes.
|
| 44 |
+
Ignored untracked files are excluded. This is a capture bound, not a total
|
| 45 |
+
sandbox disk quota or a security boundary against a malicious Git runtime.
|
| 46 |
+
"""
|
| 47 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 48 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 49 |
+
repository = repository.resolve(strict=True)
|
| 50 |
+
if output.is_symlink():
|
| 51 |
+
raise ValueError("Submission output must not be a symlink")
|
| 52 |
+
output = output.resolve()
|
| 53 |
+
if output.is_relative_to(repository):
|
| 54 |
+
raise ValueError("Submission output must be outside the repository")
|
| 55 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
output.unlink(missing_ok=True)
|
| 57 |
+
root = subprocess.check_output(
|
| 58 |
+
["git", "rev-parse", "--show-toplevel"], cwd=repository, text=True
|
| 59 |
+
).strip()
|
| 60 |
+
if Path(root).resolve() != repository:
|
| 61 |
+
raise ValueError("repository must be the Git checkout root")
|
| 62 |
+
base = subprocess.check_output(
|
| 63 |
+
["git", "rev-parse", "--verify", "HEAD^{commit}"], cwd=repository, text=True
|
| 64 |
+
).strip()
|
| 65 |
+
with tempfile.TemporaryDirectory(prefix="submission-", dir=output.parent) as directory:
|
| 66 |
+
temporary = Path(directory)
|
| 67 |
+
env = {**os.environ, "GIT_INDEX_FILE": str(temporary / "index")}
|
| 68 |
+
for arguments in (["read-tree", base], ["add", "--all", "--", "."]):
|
| 69 |
+
subprocess.run(["git", *arguments], cwd=repository, env=env, check=True)
|
| 70 |
+
patch = temporary / "patch"
|
| 71 |
+
size = 0
|
| 72 |
+
digest = hashlib.sha256()
|
| 73 |
+
with (
|
| 74 |
+
patch.open("wb") as stream,
|
| 75 |
+
tempfile.TemporaryFile() as errors,
|
| 76 |
+
subprocess.Popen(
|
| 77 |
+
[
|
| 78 |
+
"git",
|
| 79 |
+
"diff",
|
| 80 |
+
"--cached",
|
| 81 |
+
"--binary",
|
| 82 |
+
"--full-index",
|
| 83 |
+
"--no-renames",
|
| 84 |
+
"--no-ext-diff",
|
| 85 |
+
"--no-textconv",
|
| 86 |
+
"--no-color",
|
| 87 |
+
"--src-prefix=a/",
|
| 88 |
+
"--dst-prefix=b/",
|
| 89 |
+
base,
|
| 90 |
+
],
|
| 91 |
+
cwd=repository,
|
| 92 |
+
env=env,
|
| 93 |
+
stdout=subprocess.PIPE,
|
| 94 |
+
stderr=errors,
|
| 95 |
+
) as process,
|
| 96 |
+
):
|
| 97 |
+
assert process.stdout is not None
|
| 98 |
+
try:
|
| 99 |
+
while chunk := process.stdout.read(65536):
|
| 100 |
+
size += len(chunk)
|
| 101 |
+
if size > max_bytes:
|
| 102 |
+
raise ValueError(f"Submission exceeds {max_bytes} bytes")
|
| 103 |
+
stream.write(chunk)
|
| 104 |
+
digest.update(chunk)
|
| 105 |
+
except BaseException:
|
| 106 |
+
process.kill()
|
| 107 |
+
process.wait()
|
| 108 |
+
raise
|
| 109 |
+
if process.wait():
|
| 110 |
+
errors.seek(0)
|
| 111 |
+
raise RuntimeError(
|
| 112 |
+
"Git patch capture failed: " + errors.read(4096).decode(errors="replace")
|
| 113 |
+
)
|
| 114 |
+
patch.replace(output)
|
| 115 |
+
return {
|
| 116 |
+
"bytes": size,
|
| 117 |
+
"sha256": digest.hexdigest(),
|
| 118 |
+
"base_commit": base,
|
| 119 |
+
"format": "git-binary-v1",
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def submission_command(*, max_bytes: int = MAX_SUBMISSION_BYTES) -> str:
|
| 124 |
+
"""Build the trusted command recorded before Harbor collects artifacts.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
----------
|
| 128 |
+
max_bytes : int, default: 33554432
|
| 129 |
+
Maximum emitted patch bytes.
|
| 130 |
+
|
| 131 |
+
Returns
|
| 132 |
+
-------
|
| 133 |
+
str
|
| 134 |
+
Shell command carrying this exact helper into the solver runtime.
|
| 135 |
+
|
| 136 |
+
Raises
|
| 137 |
+
------
|
| 138 |
+
ValueError
|
| 139 |
+
If the size limit is invalid.
|
| 140 |
+
"""
|
| 141 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 142 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 143 |
+
return "python -c " + shlex.quote(Path(__file__).read_text()) + f" --max-bytes {max_bytes}"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def main() -> None:
|
| 147 |
+
"""Capture the submission and print its identity as trial evidence."""
|
| 148 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 149 |
+
parser.add_argument("--repository", type=Path, default=Path("/testbed"))
|
| 150 |
+
parser.add_argument("--output", type=Path, default=Path("/workspace/submitted.patch"))
|
| 151 |
+
parser.add_argument("--max-bytes", type=int, default=MAX_SUBMISSION_BYTES)
|
| 152 |
+
args = parser.parse_args()
|
| 153 |
+
print(json.dumps(capture_submission(args.repository, args.output, max_bytes=args.max_bytes)))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
main()
|
harbor/tasks/help_defaults/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
pids_limit: 512
|
| 4 |
+
security_opt:
|
| 5 |
+
- no-new-privileges:true
|
| 6 |
+
volumes:
|
| 7 |
+
- type: tmpfs
|
| 8 |
+
target: /logs/verifier
|
| 9 |
+
tmpfs:
|
| 10 |
+
mode: 448
|
| 11 |
+
size: 1048576
|
harbor/tasks/help_defaults/environment/sanitize.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Remove private task assets and history when building the agent-only image."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, "/app")
|
| 10 |
+
from env import _setup # noqa: E402
|
| 11 |
+
|
| 12 |
+
asyncio.run(_setup())
|
| 13 |
+
# The new history contains only the public baseline. Preserve a root-owned
|
| 14 |
+
# copy so capture can ignore agent-controlled refs, hooks and Git configuration.
|
| 15 |
+
shutil.copytree("/workspace/repo/.git", "/opt/task-tools/baseline.git")
|
| 16 |
+
for path in Path("/opt/task-tools/baseline.git").rglob("*"):
|
| 17 |
+
os.chown(path, 0, 0)
|
| 18 |
+
path.chmod(0o755 if path.is_dir() else 0o644)
|
| 19 |
+
for name in ("/hud", "/app", "/root/.cache", "/root/.hud"):
|
| 20 |
+
if Path(name).exists():
|
| 21 |
+
shutil.rmtree(name)
|
| 22 |
+
# Capture runs on the base interpreter under one name, whatever the image calls it.
|
| 23 |
+
os.symlink(os.path.realpath(sys.executable), "/opt/task-tools/python")
|
| 24 |
+
Path("/workspace/submissions").mkdir()
|
| 25 |
+
os.chown("/workspace/submissions", 1000, 1000)
|
harbor/tasks/help_defaults/instruction.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please make your changes directly in /workspace/repo.
|
| 2 |
+
|
| 3 |
+
The [default: ...] text that an option's help shows is wrong for a multi-valued default. A single default is rendered by rules that make it readable and typeable: an Enum member is shown by its name, an empty string is shown as "", a callable is shown as (dynamic). When the option takes several values (multiple, or several values per occurrence), those rules are not applied: an Enum member shows as E.Foo, which is not a value the user can pass and does not match the metavar next to it, and an empty string shows as nothing at all.
|
| 4 |
+
|
| 5 |
+
Required behaviour: every value of a multi-valued default is rendered exactly as the same value would be rendered as a single default, and the rendered values are joined with ", " into one list. This holds at any nesting: when each occurrence takes several values, every value of every occurrence is rendered by the same rules and all of them appear in that one list. These rules apply wherever a default value or the accepted values are presented to the user, not only in the help text: whenever a prompt shows its default or lists its choices, whether it is an option asking for its value or the prompt function called directly, each is rendered as the help renders that value, so that what is shown is what the user can type back, and the value typed back that way is accepted. Typing a default back exactly as the prompt shows it, a single value or a whole list, gives the default itself, just as pressing Enter does; any other input is taken as typed. Nothing else observable changes: a show_default string is still shown verbatim in parentheses, in the help and in the prompt; single-valued defaults, numbers, strings, dynamic defaults, boolean flags, file defaults, plain string choices and the no-default case render exactly as before, in the help and in the prompt; a prompt that hides its choices keeps hiding them; and the public API is unchanged.
|
| 6 |
+
|
| 7 |
+
Add tests under tests/ in new files, do not edit any pre-existing test file, and keep the existing suite green. If a test fails, fix the code rather than weakening the test. Add an entry to the changelog under the unreleased version. Everything you need is already installed and works offline; do not download or install anything. Run tests with python -m pytest from the repository root; the whole suite takes a few seconds.
|
| 8 |
+
|
| 9 |
+
Finish with a final response when your changes are ready.
|
harbor/tasks/help_defaults/solution/reference.patch
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
| 1 |
+
diff --git a/CHANGES.md b/CHANGES.md
|
| 2 |
+
index 8853860..4976b6c 100644
|
| 3 |
+
--- a/CHANGES.md
|
| 4 |
+
+++ b/CHANGES.md
|
| 5 |
+
@@ -11,6 +11,10 @@ Unreleased
|
| 6 |
+
|
| 7 |
+
Unreleased
|
| 8 |
+
|
| 9 |
+
+- The `[default: ...]` shown in help for an option with `multiple=True`
|
| 10 |
+
+ renders each value the way a single value is rendered: `Enum` members by
|
| 11 |
+
+ name, empty strings as `""`. The prompt of an option lists its choices and
|
| 12 |
+
+ previews its default the same way, so what it shows can be typed back.
|
| 13 |
+
- Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`
|
| 14 |
+
- A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,
|
| 15 |
+
or while it exits, no longer escapes as an unhandled traceback. The command still
|
| 16 |
+
diff --git a/src/click/_utils.py b/src/click/_utils.py
|
| 17 |
+
index 2d4e8f2..e2811bb 100644
|
| 18 |
+
--- a/src/click/_utils.py
|
| 19 |
+
+++ b/src/click/_utils.py
|
| 20 |
+
@@ -1,7 +1,9 @@
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import enum
|
| 24 |
+
+import inspect
|
| 25 |
+
import typing as t
|
| 26 |
+
+from gettext import gettext as _
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Sentinel(enum.Enum):
|
| 30 |
+
@@ -43,3 +45,33 @@ T_UNSET: t.TypeAlias = t.Literal[Sentinel.UNSET]
|
| 31 |
+
|
| 32 |
+
T_FLAG_NEEDS_VALUE: t.TypeAlias = t.Literal[Sentinel.FLAG_NEEDS_VALUE]
|
| 33 |
+
"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
|
| 34 |
+
+
|
| 35 |
+
+
|
| 36 |
+
+def _format_default_value(value: t.Any) -> str:
|
| 37 |
+
+ """Render a value the way ``[default: ...]`` and prompts show it.
|
| 38 |
+
+
|
| 39 |
+
+ A list or tuple renders as its values, comma separated, each rendered by
|
| 40 |
+
+ the same rules as a single value: an Enum member by its name, an empty
|
| 41 |
+
+ string as ``""``, a plain function as ``(dynamic)``, anything else with
|
| 42 |
+
+ ``str()``.
|
| 43 |
+
+
|
| 44 |
+
+ :meta private:
|
| 45 |
+
+ """
|
| 46 |
+
+ if isinstance(value, (list, tuple)):
|
| 47 |
+
+ return ", ".join(_format_default_value(item) for item in value)
|
| 48 |
+
+ if isinstance(value, enum.Enum):
|
| 49 |
+
+ return value.name
|
| 50 |
+
+ if inspect.isfunction(value):
|
| 51 |
+
+ return _("(dynamic)")
|
| 52 |
+
+ if isinstance(value, str) and value == "":
|
| 53 |
+
+ return '""'
|
| 54 |
+
+ return str(value)
|
| 55 |
+
+
|
| 56 |
+
+
|
| 57 |
+
+def _format_choice(choice: t.Any) -> str:
|
| 58 |
+
+ """Render one choice the way prompts and help list it: an Enum member by
|
| 59 |
+
+ its name, anything else with ``str()``.
|
| 60 |
+
+
|
| 61 |
+
+ :meta private:
|
| 62 |
+
+ """
|
| 63 |
+
+ return choice.name if isinstance(choice, enum.Enum) else str(choice)
|
| 64 |
+
diff --git a/src/click/core.py b/src/click/core.py
|
| 65 |
+
index 1f9323a..e82eaa0 100644
|
| 66 |
+
--- a/src/click/core.py
|
| 67 |
+
+++ b/src/click/core.py
|
| 68 |
+
@@ -23,6 +23,7 @@ from types import TracebackType
|
| 69 |
+
|
| 70 |
+
from . import types
|
| 71 |
+
from ._utils import FLAG_NEEDS_VALUE
|
| 72 |
+
+from ._utils import _format_default_value
|
| 73 |
+
from ._utils import UNSET
|
| 74 |
+
from .exceptions import Abort
|
| 75 |
+
from .exceptions import BadParameter
|
| 76 |
+
@@ -3564,12 +3565,13 @@ class Option(Parameter):
|
| 77 |
+
):
|
| 78 |
+
if show_default_is_str:
|
| 79 |
+
default_string = f"({self.show_default})"
|
| 80 |
+
- elif isinstance(default_value, (list, tuple)):
|
| 81 |
+
- default_string = ", ".join(str(d) for d in default_value)
|
| 82 |
+
- elif isinstance(default_value, enum.Enum):
|
| 83 |
+
- default_string = default_value.name
|
| 84 |
+
- elif inspect.isfunction(default_value):
|
| 85 |
+
- default_string = _("(dynamic)")
|
| 86 |
+
+ elif isinstance(default_value, (list, tuple)) or (
|
| 87 |
+
+ isinstance(default_value, enum.Enum)
|
| 88 |
+
+ or inspect.isfunction(default_value)
|
| 89 |
+
+ ):
|
| 90 |
+
+ # Multi-valued defaults render each value the way the same
|
| 91 |
+
+ # value renders for a single-valued option.
|
| 92 |
+
+ default_string = _format_default_value(default_value)
|
| 93 |
+
elif self.is_bool_flag and self.secondary_opts:
|
| 94 |
+
# For boolean flags that have distinct True/False opts,
|
| 95 |
+
# use the opt without prefix instead of the value.
|
| 96 |
+
diff --git a/src/click/termui.py b/src/click/termui.py
|
| 97 |
+
index 8fe0085..0caa7cd 100644
|
| 98 |
+
--- a/src/click/termui.py
|
| 99 |
+
+++ b/src/click/termui.py
|
| 100 |
+
@@ -15,6 +15,8 @@ from gettext import gettext as _
|
| 101 |
+
from . import _compat
|
| 102 |
+
from ._compat import isatty
|
| 103 |
+
from ._compat import strip_ansi
|
| 104 |
+
+from ._utils import _format_choice
|
| 105 |
+
+from ._utils import _format_default_value
|
| 106 |
+
from .exceptions import Abort
|
| 107 |
+
from .exceptions import UsageError
|
| 108 |
+
from .globals import resolve_color_default
|
| 109 |
+
@@ -115,7 +117,9 @@ def _build_prompt(
|
| 110 |
+
) -> str:
|
| 111 |
+
prompt = text
|
| 112 |
+
if type is not None and show_choices and isinstance(type, Choice):
|
| 113 |
+
- prompt += f" ({', '.join(map(str, type.choices))})"
|
| 114 |
+
+ # Each choice is listed the way it can be typed back, which for an
|
| 115 |
+
+ # Enum member is its name, as the help and the error message show it.
|
| 116 |
+
+ prompt += f" ({', '.join(_format_choice(choice) for choice in type.choices)})"
|
| 117 |
+
default_preview = ""
|
| 118 |
+
if show_default:
|
| 119 |
+
if isinstance(show_default, str):
|
| 120 |
+
@@ -132,7 +136,9 @@ def _format_default(default: V) -> V | str:
|
| 121 |
+
if name is not None:
|
| 122 |
+
return str(name)
|
| 123 |
+
|
| 124 |
+
- return default
|
| 125 |
+
+ # The default is previewed the way the help renders it, so that what is
|
| 126 |
+
+ # shown is what the user can type back.
|
| 127 |
+
+ return _format_default_value(default)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@t.overload
|
| 131 |
+
@@ -250,6 +256,15 @@ def prompt(
|
| 132 |
+
prompt = _build_prompt(
|
| 133 |
+
text, prompt_suffix, show_default, default, show_choices, type
|
| 134 |
+
)
|
| 135 |
+
+ # The default exactly as the prompt shows it. Typing that text back
|
| 136 |
+
+ # selects the default itself, as pressing Enter does, so that a value
|
| 137 |
+
+ # rendered for display (a quoted empty string, a list of values) can be
|
| 138 |
+
+ # typed back as shown.
|
| 139 |
+
+ shown_default = (
|
| 140 |
+
+ str(_format_default(default))
|
| 141 |
+
+ if default is not None and show_default and not isinstance(show_default, str)
|
| 142 |
+
+ else None
|
| 143 |
+
+ )
|
| 144 |
+
|
| 145 |
+
if confirmation_prompt:
|
| 146 |
+
if confirmation_prompt is True:
|
| 147 |
+
@@ -269,7 +284,9 @@ def prompt(
|
| 148 |
+
value = t.cast("str", default)
|
| 149 |
+
break
|
| 150 |
+
try:
|
| 151 |
+
- result = value_proc(value)
|
| 152 |
+
+ result = value_proc(
|
| 153 |
+
+ default if shown_default is not None and value == shown_default else value
|
| 154 |
+
+ )
|
| 155 |
+
except UsageError as e:
|
| 156 |
+
message = _mask_hidden_input(e.message, value) if hide_input else e.message
|
| 157 |
+
echo(_("Error: {message}").format(message=message), err=err)
|
| 158 |
+
diff --git a/tests/test_help_defaults_multiple.py b/tests/test_help_defaults_multiple.py
|
| 159 |
+
new file mode 100644
|
| 160 |
+
index 0000000..cb6eb77
|
| 161 |
+
--- /dev/null
|
| 162 |
+
+++ b/tests/test_help_defaults_multiple.py
|
| 163 |
+
@@ -0,0 +1,69 @@
|
| 164 |
+
+import enum
|
| 165 |
+
+
|
| 166 |
+
+import click
|
| 167 |
+
+from click.testing import CliRunner
|
| 168 |
+
+
|
| 169 |
+
+
|
| 170 |
+
+class Color(enum.Enum):
|
| 171 |
+
+ Red = "r"
|
| 172 |
+
+ Blue = "b"
|
| 173 |
+
+
|
| 174 |
+
+
|
| 175 |
+
+def _help(**kwargs):
|
| 176 |
+
+ @click.command()
|
| 177 |
+
+ @click.option("--opt", show_default=True, **kwargs)
|
| 178 |
+
+ def cmd(opt):
|
| 179 |
+
+ pass
|
| 180 |
+
+
|
| 181 |
+
+ return CliRunner().invoke(cmd, ["--help"]).output
|
| 182 |
+
+
|
| 183 |
+
+
|
| 184 |
+
+def test_multiple_enum_default_shows_names():
|
| 185 |
+
+ assert "[default: Red, Blue]" in _help(
|
| 186 |
+
+ type=click.Choice(Color), multiple=True, default=[Color.Red, Color.Blue]
|
| 187 |
+
+ )
|
| 188 |
+
+
|
| 189 |
+
+
|
| 190 |
+
+def test_multiple_empty_string_default_is_quoted():
|
| 191 |
+
+ assert '[default: "", x]' in _help(multiple=True, default=["", "x"])
|
| 192 |
+
+
|
| 193 |
+
+
|
| 194 |
+
+def test_nargs_with_multiple_renders_every_value():
|
| 195 |
+
+ assert "[default: 1, 2, 3, 4]" in _help(nargs=2, multiple=True, default=[(1, 2), (3, 4)])
|
| 196 |
+
+
|
| 197 |
+
+
|
| 198 |
+
+def _prompt_line(input_text="\n", **kwargs):
|
| 199 |
+
+ @click.command()
|
| 200 |
+
+ @click.option("--opt", prompt="Value", **kwargs)
|
| 201 |
+
+ def cmd(opt):
|
| 202 |
+
+ pass
|
| 203 |
+
+
|
| 204 |
+
+ return CliRunner().invoke(cmd, [], input=input_text).output.split("\n", 1)[0]
|
| 205 |
+
+
|
| 206 |
+
+
|
| 207 |
+
+def test_prompt_lists_enum_choices_and_default_by_name():
|
| 208 |
+
+ line = _prompt_line(type=click.Choice(Color), default=Color.Blue)
|
| 209 |
+
+ assert "(Red, Blue)" in line
|
| 210 |
+
+ assert "[Blue]" in line
|
| 211 |
+
+
|
| 212 |
+
+
|
| 213 |
+
+def test_prompt_previews_empty_string_default_quoted():
|
| 214 |
+
+ assert '[""]' in _prompt_line(default="")
|
| 215 |
+
+
|
| 216 |
+
+
|
| 217 |
+
+def test_prompt_default_typed_back_as_shown():
|
| 218 |
+
+ line = CliRunner().invoke(
|
| 219 |
+
+ _typed_back_cmd(multiple=True, default=["", "x"]), [], input='"", x\n'
|
| 220 |
+
+ ).output
|
| 221 |
+
+ assert "GOT=('', 'x')" in line
|
| 222 |
+
+ line = CliRunner().invoke(_typed_back_cmd(default=""), [], input='""\n').output
|
| 223 |
+
+ assert "GOT=''" in line
|
| 224 |
+
+
|
| 225 |
+
+
|
| 226 |
+
+def _typed_back_cmd(**kwargs):
|
| 227 |
+
+ @click.command()
|
| 228 |
+
+ @click.option("--opt", prompt="Value", **kwargs)
|
| 229 |
+
+ def cmd(opt):
|
| 230 |
+
+ click.echo(f"GOT={opt!r}")
|
| 231 |
+
+
|
| 232 |
+
+ return cmd
|
harbor/tasks/help_defaults/solution/solve.sh
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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set -eu
|
| 3 |
+
cd /workspace/repo
|
| 4 |
+
git apply <<'REFERENCE_PATCH'
|
| 5 |
+
diff --git a/CHANGES.md b/CHANGES.md
|
| 6 |
+
index 8853860..4976b6c 100644
|
| 7 |
+
--- a/CHANGES.md
|
| 8 |
+
+++ b/CHANGES.md
|
| 9 |
+
@@ -11,6 +11,10 @@ Unreleased
|
| 10 |
+
|
| 11 |
+
Unreleased
|
| 12 |
+
|
| 13 |
+
+- The `[default: ...]` shown in help for an option with `multiple=True`
|
| 14 |
+
+ renders each value the way a single value is rendered: `Enum` members by
|
| 15 |
+
+ name, empty strings as `""`. The prompt of an option lists its choices and
|
| 16 |
+
+ previews its default the same way, so what it shows can be typed back.
|
| 17 |
+
- Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`
|
| 18 |
+
- A `KeyboardInterrupt` arriving while `Command.main()` reports an abort or an error,
|
| 19 |
+
or while it exits, no longer escapes as an unhandled traceback. The command still
|
| 20 |
+
diff --git a/src/click/_utils.py b/src/click/_utils.py
|
| 21 |
+
index 2d4e8f2..e2811bb 100644
|
| 22 |
+
--- a/src/click/_utils.py
|
| 23 |
+
+++ b/src/click/_utils.py
|
| 24 |
+
@@ -1,7 +1,9 @@
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import enum
|
| 28 |
+
+import inspect
|
| 29 |
+
import typing as t
|
| 30 |
+
+from gettext import gettext as _
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Sentinel(enum.Enum):
|
| 34 |
+
@@ -43,3 +45,33 @@ T_UNSET: t.TypeAlias = t.Literal[Sentinel.UNSET]
|
| 35 |
+
|
| 36 |
+
T_FLAG_NEEDS_VALUE: t.TypeAlias = t.Literal[Sentinel.FLAG_NEEDS_VALUE]
|
| 37 |
+
"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
|
| 38 |
+
+
|
| 39 |
+
+
|
| 40 |
+
+def _format_default_value(value: t.Any) -> str:
|
| 41 |
+
+ """Render a value the way ``[default: ...]`` and prompts show it.
|
| 42 |
+
+
|
| 43 |
+
+ A list or tuple renders as its values, comma separated, each rendered by
|
| 44 |
+
+ the same rules as a single value: an Enum member by its name, an empty
|
| 45 |
+
+ string as ``""``, a plain function as ``(dynamic)``, anything else with
|
| 46 |
+
+ ``str()``.
|
| 47 |
+
+
|
| 48 |
+
+ :meta private:
|
| 49 |
+
+ """
|
| 50 |
+
+ if isinstance(value, (list, tuple)):
|
| 51 |
+
+ return ", ".join(_format_default_value(item) for item in value)
|
| 52 |
+
+ if isinstance(value, enum.Enum):
|
| 53 |
+
+ return value.name
|
| 54 |
+
+ if inspect.isfunction(value):
|
| 55 |
+
+ return _("(dynamic)")
|
| 56 |
+
+ if isinstance(value, str) and value == "":
|
| 57 |
+
+ return '""'
|
| 58 |
+
+ return str(value)
|
| 59 |
+
+
|
| 60 |
+
+
|
| 61 |
+
+def _format_choice(choice: t.Any) -> str:
|
| 62 |
+
+ """Render one choice the way prompts and help list it: an Enum member by
|
| 63 |
+
+ its name, anything else with ``str()``.
|
| 64 |
+
+
|
| 65 |
+
+ :meta private:
|
| 66 |
+
+ """
|
| 67 |
+
+ return choice.name if isinstance(choice, enum.Enum) else str(choice)
|
| 68 |
+
diff --git a/src/click/core.py b/src/click/core.py
|
| 69 |
+
index 1f9323a..e82eaa0 100644
|
| 70 |
+
--- a/src/click/core.py
|
| 71 |
+
+++ b/src/click/core.py
|
| 72 |
+
@@ -23,6 +23,7 @@ from types import TracebackType
|
| 73 |
+
|
| 74 |
+
from . import types
|
| 75 |
+
from ._utils import FLAG_NEEDS_VALUE
|
| 76 |
+
+from ._utils import _format_default_value
|
| 77 |
+
from ._utils import UNSET
|
| 78 |
+
from .exceptions import Abort
|
| 79 |
+
from .exceptions import BadParameter
|
| 80 |
+
@@ -3564,12 +3565,13 @@ class Option(Parameter):
|
| 81 |
+
):
|
| 82 |
+
if show_default_is_str:
|
| 83 |
+
default_string = f"({self.show_default})"
|
| 84 |
+
- elif isinstance(default_value, (list, tuple)):
|
| 85 |
+
- default_string = ", ".join(str(d) for d in default_value)
|
| 86 |
+
- elif isinstance(default_value, enum.Enum):
|
| 87 |
+
- default_string = default_value.name
|
| 88 |
+
- elif inspect.isfunction(default_value):
|
| 89 |
+
- default_string = _("(dynamic)")
|
| 90 |
+
+ elif isinstance(default_value, (list, tuple)) or (
|
| 91 |
+
+ isinstance(default_value, enum.Enum)
|
| 92 |
+
+ or inspect.isfunction(default_value)
|
| 93 |
+
+ ):
|
| 94 |
+
+ # Multi-valued defaults render each value the way the same
|
| 95 |
+
+ # value renders for a single-valued option.
|
| 96 |
+
+ default_string = _format_default_value(default_value)
|
| 97 |
+
elif self.is_bool_flag and self.secondary_opts:
|
| 98 |
+
# For boolean flags that have distinct True/False opts,
|
| 99 |
+
# use the opt without prefix instead of the value.
|
| 100 |
+
diff --git a/src/click/termui.py b/src/click/termui.py
|
| 101 |
+
index 8fe0085..0caa7cd 100644
|
| 102 |
+
--- a/src/click/termui.py
|
| 103 |
+
+++ b/src/click/termui.py
|
| 104 |
+
@@ -15,6 +15,8 @@ from gettext import gettext as _
|
| 105 |
+
from . import _compat
|
| 106 |
+
from ._compat import isatty
|
| 107 |
+
from ._compat import strip_ansi
|
| 108 |
+
+from ._utils import _format_choice
|
| 109 |
+
+from ._utils import _format_default_value
|
| 110 |
+
from .exceptions import Abort
|
| 111 |
+
from .exceptions import UsageError
|
| 112 |
+
from .globals import resolve_color_default
|
| 113 |
+
@@ -115,7 +117,9 @@ def _build_prompt(
|
| 114 |
+
) -> str:
|
| 115 |
+
prompt = text
|
| 116 |
+
if type is not None and show_choices and isinstance(type, Choice):
|
| 117 |
+
- prompt += f" ({', '.join(map(str, type.choices))})"
|
| 118 |
+
+ # Each choice is listed the way it can be typed back, which for an
|
| 119 |
+
+ # Enum member is its name, as the help and the error message show it.
|
| 120 |
+
+ prompt += f" ({', '.join(_format_choice(choice) for choice in type.choices)})"
|
| 121 |
+
default_preview = ""
|
| 122 |
+
if show_default:
|
| 123 |
+
if isinstance(show_default, str):
|
| 124 |
+
@@ -132,7 +136,9 @@ def _format_default(default: V) -> V | str:
|
| 125 |
+
if name is not None:
|
| 126 |
+
return str(name)
|
| 127 |
+
|
| 128 |
+
- return default
|
| 129 |
+
+ # The default is previewed the way the help renders it, so that what is
|
| 130 |
+
+ # shown is what the user can type back.
|
| 131 |
+
+ return _format_default_value(default)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@t.overload
|
| 135 |
+
@@ -250,6 +256,15 @@ def prompt(
|
| 136 |
+
prompt = _build_prompt(
|
| 137 |
+
text, prompt_suffix, show_default, default, show_choices, type
|
| 138 |
+
)
|
| 139 |
+
+ # The default exactly as the prompt shows it. Typing that text back
|
| 140 |
+
+ # selects the default itself, as pressing Enter does, so that a value
|
| 141 |
+
+ # rendered for display (a quoted empty string, a list of values) can be
|
| 142 |
+
+ # typed back as shown.
|
| 143 |
+
+ shown_default = (
|
| 144 |
+
+ str(_format_default(default))
|
| 145 |
+
+ if default is not None and show_default and not isinstance(show_default, str)
|
| 146 |
+
+ else None
|
| 147 |
+
+ )
|
| 148 |
+
|
| 149 |
+
if confirmation_prompt:
|
| 150 |
+
if confirmation_prompt is True:
|
| 151 |
+
@@ -269,7 +284,9 @@ def prompt(
|
| 152 |
+
value = t.cast("str", default)
|
| 153 |
+
break
|
| 154 |
+
try:
|
| 155 |
+
- result = value_proc(value)
|
| 156 |
+
+ result = value_proc(
|
| 157 |
+
+ default if shown_default is not None and value == shown_default else value
|
| 158 |
+
+ )
|
| 159 |
+
except UsageError as e:
|
| 160 |
+
message = _mask_hidden_input(e.message, value) if hide_input else e.message
|
| 161 |
+
echo(_("Error: {message}").format(message=message), err=err)
|
| 162 |
+
diff --git a/tests/test_help_defaults_multiple.py b/tests/test_help_defaults_multiple.py
|
| 163 |
+
new file mode 100644
|
| 164 |
+
index 0000000..cb6eb77
|
| 165 |
+
--- /dev/null
|
| 166 |
+
+++ b/tests/test_help_defaults_multiple.py
|
| 167 |
+
@@ -0,0 +1,69 @@
|
| 168 |
+
+import enum
|
| 169 |
+
+
|
| 170 |
+
+import click
|
| 171 |
+
+from click.testing import CliRunner
|
| 172 |
+
+
|
| 173 |
+
+
|
| 174 |
+
+class Color(enum.Enum):
|
| 175 |
+
+ Red = "r"
|
| 176 |
+
+ Blue = "b"
|
| 177 |
+
+
|
| 178 |
+
+
|
| 179 |
+
+def _help(**kwargs):
|
| 180 |
+
+ @click.command()
|
| 181 |
+
+ @click.option("--opt", show_default=True, **kwargs)
|
| 182 |
+
+ def cmd(opt):
|
| 183 |
+
+ pass
|
| 184 |
+
+
|
| 185 |
+
+ return CliRunner().invoke(cmd, ["--help"]).output
|
| 186 |
+
+
|
| 187 |
+
+
|
| 188 |
+
+def test_multiple_enum_default_shows_names():
|
| 189 |
+
+ assert "[default: Red, Blue]" in _help(
|
| 190 |
+
+ type=click.Choice(Color), multiple=True, default=[Color.Red, Color.Blue]
|
| 191 |
+
+ )
|
| 192 |
+
+
|
| 193 |
+
+
|
| 194 |
+
+def test_multiple_empty_string_default_is_quoted():
|
| 195 |
+
+ assert '[default: "", x]' in _help(multiple=True, default=["", "x"])
|
| 196 |
+
+
|
| 197 |
+
+
|
| 198 |
+
+def test_nargs_with_multiple_renders_every_value():
|
| 199 |
+
+ assert "[default: 1, 2, 3, 4]" in _help(nargs=2, multiple=True, default=[(1, 2), (3, 4)])
|
| 200 |
+
+
|
| 201 |
+
+
|
| 202 |
+
+def _prompt_line(input_text="\n", **kwargs):
|
| 203 |
+
+ @click.command()
|
| 204 |
+
+ @click.option("--opt", prompt="Value", **kwargs)
|
| 205 |
+
+ def cmd(opt):
|
| 206 |
+
+ pass
|
| 207 |
+
+
|
| 208 |
+
+ return CliRunner().invoke(cmd, [], input=input_text).output.split("\n", 1)[0]
|
| 209 |
+
+
|
| 210 |
+
+
|
| 211 |
+
+def test_prompt_lists_enum_choices_and_default_by_name():
|
| 212 |
+
+ line = _prompt_line(type=click.Choice(Color), default=Color.Blue)
|
| 213 |
+
+ assert "(Red, Blue)" in line
|
| 214 |
+
+ assert "[Blue]" in line
|
| 215 |
+
+
|
| 216 |
+
+
|
| 217 |
+
+def test_prompt_previews_empty_string_default_quoted():
|
| 218 |
+
+ assert '[""]' in _prompt_line(default="")
|
| 219 |
+
+
|
| 220 |
+
+
|
| 221 |
+
+def test_prompt_default_typed_back_as_shown():
|
| 222 |
+
+ line = CliRunner().invoke(
|
| 223 |
+
+ _typed_back_cmd(multiple=True, default=["", "x"]), [], input='"", x\n'
|
| 224 |
+
+ ).output
|
| 225 |
+
+ assert "GOT=('', 'x')" in line
|
| 226 |
+
+ line = CliRunner().invoke(_typed_back_cmd(default=""), [], input='""\n').output
|
| 227 |
+
+ assert "GOT=''" in line
|
| 228 |
+
+
|
| 229 |
+
+
|
| 230 |
+
+def _typed_back_cmd(**kwargs):
|
| 231 |
+
+ @click.command()
|
| 232 |
+
+ @click.option("--opt", prompt="Value", **kwargs)
|
| 233 |
+
+ def cmd(opt):
|
| 234 |
+
+ click.echo(f"GOT={opt!r}")
|
| 235 |
+
+
|
| 236 |
+
+ return cmd
|
| 237 |
+
|
| 238 |
+
REFERENCE_PATCH
|
harbor/tasks/help_defaults/task.toml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
artifacts = ["/workspace/submissions/submitted.patch"]
|
| 3 |
+
[metadata]
|
| 4 |
+
task = "help_defaults"
|
| 5 |
+
validation_revision = "coding-rubric-v2"
|
| 6 |
+
[agent]
|
| 7 |
+
timeout_sec = 1800
|
| 8 |
+
user = "1000:1000"
|
| 9 |
+
[environment]
|
| 10 |
+
build_timeout_sec = 1800
|
| 11 |
+
cpus = 2
|
| 12 |
+
memory_mb = 8192
|
| 13 |
+
network_mode = "no-network"
|
| 14 |
+
[verifier]
|
| 15 |
+
timeout_sec = 7200
|
| 16 |
+
user = "0"
|
| 17 |
+
environment_mode = "separate"
|
| 18 |
+
env = { JUDGE_API_KEY = "${JUDGE_API_KEY:-}", JUDGE_BASE_URL = "${JUDGE_BASE_URL:-https://openrouter.ai/api/v1}", JUDGE_MODEL = "${JUDGE_MODEL:-anthropic/claude-sonnet-5.5}" }
|
| 19 |
+
[verifier.environment]
|
| 20 |
+
build_timeout_sec = 1800
|
| 21 |
+
cpus = 2
|
| 22 |
+
memory_mb = 8192
|
| 23 |
+
network_mode = "allowlist"
|
| 24 |
+
allowed_hosts = ["openrouter.ai"]
|
| 25 |
+
[[verifier.collect]]
|
| 26 |
+
command = "/opt/task-tools/python -I /opt/task-tools/capture.py"
|
| 27 |
+
user = "0"
|
| 28 |
+
timeout_sec = 900
|
harbor/tasks/help_defaults/tests/Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-click:source-v9
|
| 2 |
+
USER root
|
| 3 |
+
RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
|
| 4 |
+
ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
|
| 5 |
+
RUN rm -f /hud/gold.diff
|
| 6 |
+
COPY verify.py evidence.py judge.py config.json test.sh /tests/
|
| 7 |
+
RUN chmod 755 /tests/test.sh
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/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
"arguments": {},
|
| 5 |
+
"grader_version": "0.6.13",
|
| 6 |
+
"source_image": "ec-swe-click:source-v9",
|
| 7 |
+
"source_image_id": "sha256:e8e795f66f12a38f30b7e9be2e430e4b4f8b6c2d11c0b9685a5b7f597dac403f",
|
| 8 |
+
"provenance": {
|
| 9 |
+
"repository": "pallets/click",
|
| 10 |
+
"environment_id": "29c14648-17d9-42d0-8d59-724a9c0d0feb",
|
| 11 |
+
"build": 9,
|
| 12 |
+
"build_id": "4505ff57-3be4-4ecc-aa01-decc9c8d8dce",
|
| 13 |
+
"hosted_task": "click-help-defaults",
|
| 14 |
+
"task_version": 5,
|
| 15 |
+
"source_archive_sha256": "19246fda734704552a40171add83070a3e3181c11aad73b24eff2244939a2400",
|
| 16 |
+
"hosted_revision_argument": "not recorded; the scenario does not read it"
|
| 17 |
+
},
|
| 18 |
+
"criteria": [
|
| 19 |
+
[
|
| 20 |
+
"multi_enum",
|
| 21 |
+
0.1875,
|
| 22 |
+
true,
|
| 23 |
+
"bash",
|
| 24 |
+
600
|
| 25 |
+
],
|
| 26 |
+
[
|
| 27 |
+
"multi_empty_string",
|
| 28 |
+
0.125,
|
| 29 |
+
true,
|
| 30 |
+
"bash",
|
| 31 |
+
600
|
| 32 |
+
],
|
| 33 |
+
[
|
| 34 |
+
"nested_values",
|
| 35 |
+
0.0625,
|
| 36 |
+
false,
|
| 37 |
+
"bash",
|
| 38 |
+
600
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
"prompt_rendering",
|
| 42 |
+
0.125,
|
| 43 |
+
true,
|
| 44 |
+
"bash",
|
| 45 |
+
600
|
| 46 |
+
],
|
| 47 |
+
[
|
| 48 |
+
"untouched_paths",
|
| 49 |
+
0.125,
|
| 50 |
+
true,
|
| 51 |
+
"bash",
|
| 52 |
+
600
|
| 53 |
+
],
|
| 54 |
+
[
|
| 55 |
+
"prompt_function",
|
| 56 |
+
0.0625,
|
| 57 |
+
false,
|
| 58 |
+
"bash",
|
| 59 |
+
600
|
| 60 |
+
],
|
| 61 |
+
[
|
| 62 |
+
"typeback_single",
|
| 63 |
+
0.0625,
|
| 64 |
+
false,
|
| 65 |
+
"bash",
|
| 66 |
+
600
|
| 67 |
+
],
|
| 68 |
+
[
|
| 69 |
+
"typeback_multi",
|
| 70 |
+
0.0625,
|
| 71 |
+
false,
|
| 72 |
+
"bash",
|
| 73 |
+
600
|
| 74 |
+
],
|
| 75 |
+
[
|
| 76 |
+
"no_regression",
|
| 77 |
+
0.0625,
|
| 78 |
+
false,
|
| 79 |
+
"bash",
|
| 80 |
+
900
|
| 81 |
+
],
|
| 82 |
+
[
|
| 83 |
+
"test_quality",
|
| 84 |
+
0.0625,
|
| 85 |
+
false,
|
| 86 |
+
"bash",
|
| 87 |
+
600
|
| 88 |
+
],
|
| 89 |
+
[
|
| 90 |
+
"maintainer_review",
|
| 91 |
+
0.0625,
|
| 92 |
+
false,
|
| 93 |
+
"judge",
|
| 94 |
+
0
|
| 95 |
+
]
|
| 96 |
+
],
|
| 97 |
+
"gates": [],
|
| 98 |
+
"reward_rule": "authored",
|
| 99 |
+
"local_hostname": false,
|
| 100 |
+
"fault_exit": 2,
|
| 101 |
+
"grader_readable": [],
|
| 102 |
+
"grader_writable": [],
|
| 103 |
+
"blocker_cap": 0.1,
|
| 104 |
+
"empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 105 |
+
"verifier_files": {
|
| 106 |
+
"/app/tasks.py": "b0751721c15f44919283b1b0f82bc72711fa8ee79e0c441f8e6d2fc479c6d970",
|
| 107 |
+
"/app/env.py": "bacecba58799114163fb06badab8923c430fb577123b647d8ef6844231b9d770",
|
| 108 |
+
"/app/task/prompt.md": "bdcc4b7a286451ba09dfa4460d3e30e6097f05425c68b39974b1700ee15f864b",
|
| 109 |
+
"/app/coding/github.py": "5111a2264c70710a90ea6ecf154147eb7757311bca4f1bce7ea975c0da9525ae",
|
| 110 |
+
"/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
|
| 111 |
+
"/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
|
| 112 |
+
"/app/coding/repo.py": "f9b001028bb965a50740cdf90f84ba1dc93fda3daa831c42e58d712c6af74113",
|
| 113 |
+
"/hud/grader/maintainer_review.judge.json": "374ab90b38347f2dd0c2b4678b83ed443f20163ce9e94babfc4b1c435eb7173f",
|
| 114 |
+
"/hud/grader/run_grading.sh": "8cdaddf00bc1ba76f226900f2bb892724ea5707027cca0f0f2ae1998d52e382d",
|
| 115 |
+
"/hud/grader/tests/__hidden__nested_values.py": "0742b77e0b55f80c2f02fcc7ce1aa743baa589f79dc067b18c24c5ce7ae3f394",
|
| 116 |
+
"/hud/grader/tests/__hidden__multi_empty_string.py": "cc20a835b8c55766f7b62588bf3689b7ca63bc94cbfd106ec28cc736a02aa212",
|
| 117 |
+
"/hud/grader/tests/_fixtures.py": "77464690ab977f8c39e0704b061920a72ddd7982c54171b52ff9f6393a5b2202",
|
| 118 |
+
"/hud/grader/tests/__hidden__untouched_paths.py": "72f44182a4f38e5e7607b60ffd18f5b0f3c48086617f61d8725669428aa820f6",
|
| 119 |
+
"/hud/grader/tests/__hidden__multi_enum.py": "bc06c08b5f8fb9829bb65a1db01fc9ad1a885acbd3c6357303f94a5e67aa2ef9",
|
| 120 |
+
"/hud/grader/tests/__hidden__prompt_rendering.py": "2b98173cb8cd1618e1c9cad58838807863bce2c08ec92726d8c7521e016d74fe",
|
| 121 |
+
"/hud/grader/tests/__hidden__typeback_single.py": "707588128bd9a211a391add23f3512f2b3755f35356f12520a0a8def156e4f05",
|
| 122 |
+
"/hud/grader/tests/__hidden__typeback_multi.py": "ddcbf8a78634741148b509800221f4fa6b7f7281327cfb028be99a4f59a454cd",
|
| 123 |
+
"/hud/grader/tests/__hidden__prompt_function.py": "cc044df56a1bc062b7d4974c8b786b811fd6012be97a4de1a028b58d2fe90fb3"
|
| 124 |
+
},
|
| 125 |
+
"preflight": [
|
| 126 |
+
[
|
| 127 |
+
"/bin/bash",
|
| 128 |
+
"--version"
|
| 129 |
+
],
|
| 130 |
+
[
|
| 131 |
+
"setpriv",
|
| 132 |
+
"--version"
|
| 133 |
+
],
|
| 134 |
+
[
|
| 135 |
+
"git",
|
| 136 |
+
"--version"
|
| 137 |
+
],
|
| 138 |
+
[
|
| 139 |
+
"bash",
|
| 140 |
+
"-c",
|
| 141 |
+
"bash -lc 'python --version' || python --version"
|
| 142 |
+
]
|
| 143 |
+
],
|
| 144 |
+
"judge": {
|
| 145 |
+
"base_url": "https://openrouter.ai/api/v1",
|
| 146 |
+
"model": "anthropic/claude-sonnet-5.5",
|
| 147 |
+
"criteria": [
|
| 148 |
+
"maintainer_review"
|
| 149 |
+
],
|
| 150 |
+
"fractional_rows": false
|
| 151 |
+
}
|
| 152 |
+
}
|
harbor/tasks/help_defaults/tests/docker-compose.yaml
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
pids_limit: 512
|
| 4 |
+
security_opt:
|
| 5 |
+
- no-new-privileges:true
|
harbor/tasks/help_defaults/tests/evidence.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate complete coding-rubric evidence without importing the grader library or Harbor."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
REVISION = "coding-rubric-v2"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _number(value: Any) -> float:
|
| 12 |
+
if isinstance(value, bool) or not isinstance(value, (float, int)):
|
| 13 |
+
raise ValueError("Expected numeric rubric evidence")
|
| 14 |
+
if not math.isfinite(value) or not 0 <= value <= 1:
|
| 15 |
+
raise ValueError("Rubric values must be finite and within [0, 1]")
|
| 16 |
+
return float(value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
|
| 20 |
+
"""Check provenance, criterion coverage, weights, caps and command outcomes.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
report, config : dict
|
| 25 |
+
Fresh verifier evidence and the trusted prepared task configuration.
|
| 26 |
+
digest : str
|
| 27 |
+
SHA-256 of the submission collected by Harbor.
|
| 28 |
+
|
| 29 |
+
Raises
|
| 30 |
+
------
|
| 31 |
+
ValueError
|
| 32 |
+
If evidence is missing, inconsistent or reports infrastructure failure.
|
| 33 |
+
"""
|
| 34 |
+
if (
|
| 35 |
+
report.get("revision") != REVISION
|
| 36 |
+
or report.get("task_id") != config["task_id"]
|
| 37 |
+
or report.get("patch_sha256") != digest
|
| 38 |
+
or report.get("grader_version") != config["grader_version"]
|
| 39 |
+
):
|
| 40 |
+
raise ValueError("Verifier evidence provenance mismatch")
|
| 41 |
+
result = report.get("result", {})
|
| 42 |
+
reward = _number(result.get("reward"))
|
| 43 |
+
# A rubric may flag its own result when a grader could not judge. That is
|
| 44 |
+
# admitted only together with proof, checked below, that the same grader
|
| 45 |
+
# reaches a verdict on the untouched repository.
|
| 46 |
+
fault_exit = config.get("fault_exit")
|
| 47 |
+
faults = {
|
| 48 |
+
row["name"]
|
| 49 |
+
for row in report.get("commands", [])
|
| 50 |
+
if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
|
| 51 |
+
}
|
| 52 |
+
flagged = result.get("isError", False)
|
| 53 |
+
if (flagged and not faults) or result.get("done", True) is not True:
|
| 54 |
+
raise ValueError("Grader returned an incomplete or failed evaluation")
|
| 55 |
+
status = report.get("status")
|
| 56 |
+
if status == "rejected_patch":
|
| 57 |
+
if reward != 0 or not report.get("patch_error") or result.get("subscores"):
|
| 58 |
+
raise ValueError("Invalid rejected-patch evidence")
|
| 59 |
+
return
|
| 60 |
+
if status == "empty_patch":
|
| 61 |
+
credited = any(_number(row["value"]) for row in result.get("subscores") or [])
|
| 62 |
+
if reward != 0 or digest != config["empty_sha256"] or report.get("commands") or credited:
|
| 63 |
+
raise ValueError("Invalid empty-patch evidence")
|
| 64 |
+
return
|
| 65 |
+
if status != "graded":
|
| 66 |
+
raise ValueError("Verifier did not complete")
|
| 67 |
+
scores = result.get("subscores")
|
| 68 |
+
expected = {row[0]: row for row in config["criteria"]}
|
| 69 |
+
if not isinstance(scores, list) or len(scores) != len(expected):
|
| 70 |
+
raise ValueError("Missing rubric criteria")
|
| 71 |
+
names = [row["name"] for row in scores]
|
| 72 |
+
if len(set(names)) != len(names) or set(names) != set(expected):
|
| 73 |
+
raise ValueError("Duplicate or unexpected rubric criteria")
|
| 74 |
+
raw = 0.0
|
| 75 |
+
values = {}
|
| 76 |
+
for score in scores:
|
| 77 |
+
name = score["name"]
|
| 78 |
+
value, weight = _number(score["value"]), _number(score["weight"])
|
| 79 |
+
if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
|
| 80 |
+
raise ValueError("Criterion weights changed")
|
| 81 |
+
raw += value * weight
|
| 82 |
+
values[name] = value
|
| 83 |
+
commands = report.get("commands", [])
|
| 84 |
+
command_names = [row["name"] for row in commands]
|
| 85 |
+
expected_commands = set(expected) | set(config["gates"])
|
| 86 |
+
if len(command_names) != len(set(command_names)) or set(command_names) != expected_commands:
|
| 87 |
+
raise ValueError("Missing or duplicate grader command evidence")
|
| 88 |
+
for command in commands:
|
| 89 |
+
info = command.get("info") or {}
|
| 90 |
+
code = info.get("exit_code")
|
| 91 |
+
verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
|
| 92 |
+
if not verdict or info.get("timed_out"):
|
| 93 |
+
raise ValueError("Grader command failed outside its verdict contract")
|
| 94 |
+
if _number(command["value"]) != float(code == 0):
|
| 95 |
+
raise ValueError("Command exit code disagrees with score")
|
| 96 |
+
probes = {row["name"]: row for row in report.get("fault_probes") or []}
|
| 97 |
+
if set(probes) != faults or any(
|
| 98 |
+
row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
|
| 99 |
+
):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"A grader could not judge and the untouched repository does not explain it"
|
| 102 |
+
)
|
| 103 |
+
if any(values.get(name, 0) for name in faults):
|
| 104 |
+
raise ValueError("A criterion its grader could not judge is credited")
|
| 105 |
+
info = result.get("info") or {}
|
| 106 |
+
if info.get("aggregate_mismatch") or info.get("git_apply"):
|
| 107 |
+
raise ValueError("Grader reported inconsistent grading")
|
| 108 |
+
if config.get("reward_rule") == "authored":
|
| 109 |
+
# The task's own function decides the reward. It may take credit away
|
| 110 |
+
# (a cap, a criterion that pays only with progress) but never add any.
|
| 111 |
+
passed = {row["name"]: row["value"] for row in commands}
|
| 112 |
+
if any(values[name] > passed[name] for name in expected):
|
| 113 |
+
raise ValueError("A criterion is credited although its command failed")
|
| 114 |
+
if reward > raw + 1e-9:
|
| 115 |
+
raise ValueError("Grader reward exceeds its weighted criteria")
|
| 116 |
+
return
|
| 117 |
+
failed = {name for name, row in expected.items() if row[2] and values[name] < 1}
|
| 118 |
+
gate_failed = {
|
| 119 |
+
row["name"] for row in commands if row["name"] in config["gates"] and row["value"] < 1
|
| 120 |
+
}
|
| 121 |
+
expected_reward = min(raw, config["blocker_cap"]) if failed or gate_failed else raw
|
| 122 |
+
if not math.isclose(reward, expected_reward, abs_tol=1e-9):
|
| 123 |
+
raise ValueError("Grader reward disagrees with original weights and blocker cap")
|
harbor/tasks/help_defaults/tests/judge.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verifier entry for a coding rubric with criteria judged by a language model.
|
| 2 |
+
|
| 3 |
+
The packaged verifier (verify.py) grades offline. A rubric with a judged
|
| 4 |
+
criterion runs this file instead, which runs the same grading with three
|
| 5 |
+
differences:
|
| 6 |
+
|
| 7 |
+
- the verifier container reaches the judge's endpoint through Harbor's host
|
| 8 |
+
allowlist, and the judge's key, model and endpoint come from the verifier's
|
| 9 |
+
environment (``JUDGE_API_KEY``, ``JUDGE_MODEL``, ``JUDGE_BASE_URL``);
|
| 10 |
+
- the key is held by this process only. Grader commands run the submission's
|
| 11 |
+
code, so no environment they inherit carries it;
|
| 12 |
+
- the evidence check accepts a criterion the judge answered. A judge that does
|
| 13 |
+
not answer makes the attempt invalid: there is no reward, as for any grader
|
| 14 |
+
that cannot reach a verdict.
|
| 15 |
+
|
| 16 |
+
verify.py and evidence.py are unchanged; this file wraps them.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import importlib
|
| 22 |
+
import math
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
from typing import Any
|
| 26 |
+
from urllib.parse import urlsplit
|
| 27 |
+
|
| 28 |
+
# The key leaves the environment before anything can start a subprocess.
|
| 29 |
+
_KEY = os.environ.pop("JUDGE_API_KEY", "")
|
| 30 |
+
for _name in ("HUD_API_KEY", "OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"):
|
| 31 |
+
os.environ.pop(_name, None)
|
| 32 |
+
_BASE_URL = os.environ.get("JUDGE_BASE_URL") or "https://openrouter.ai/api/v1"
|
| 33 |
+
os.environ["JUDGE_MODEL"] = os.environ.get("JUDGE_MODEL") or "anthropic/claude-sonnet-5.5"
|
| 34 |
+
|
| 35 |
+
import evidence # noqa: E402
|
| 36 |
+
import verify # noqa: E402
|
| 37 |
+
|
| 38 |
+
_preflight = verify._preflight
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _scenario_grade(task: Any) -> Any:
|
| 42 |
+
# A task whose scenario both prompts and grades (druid): its second item is the result.
|
| 43 |
+
async def _grade(validate_mode: str | None) -> Any:
|
| 44 |
+
steps = task._scenario(validate_mode)
|
| 45 |
+
await steps.__anext__()
|
| 46 |
+
return await steps.__anext__()
|
| 47 |
+
|
| 48 |
+
return _grade
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _prepare_task(config: dict[str, Any]) -> None:
|
| 52 |
+
"""Check the verifier as verify.py does, then point the judge at its endpoint."""
|
| 53 |
+
_preflight(config)
|
| 54 |
+
from hud.settings import settings
|
| 55 |
+
|
| 56 |
+
# The judge's client reads these when it is built, from this process alone.
|
| 57 |
+
settings.api_key = _KEY or None
|
| 58 |
+
settings.hud_gateway_url = _BASE_URL
|
| 59 |
+
sys.path.insert(0, "/app")
|
| 60 |
+
task = importlib.import_module("tasks")
|
| 61 |
+
if not hasattr(task, "_setup"):
|
| 62 |
+
task._setup = importlib.import_module("env")._setup
|
| 63 |
+
if not hasattr(task, "_grade"):
|
| 64 |
+
task._grade = _scenario_grade(task)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _judge_error(score: dict[str, Any], result: dict[str, Any]) -> str | None:
|
| 68 |
+
for field in ("metadata", "info"):
|
| 69 |
+
error = (score.get(field) or {}).get("judge_error")
|
| 70 |
+
if error:
|
| 71 |
+
return str(error)
|
| 72 |
+
return ((result.get("info") or {}).get("judge_errors") or {}).get(score["name"])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def validate_judged_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
|
| 76 |
+
"""Check judged evidence as evidence.validate_report checks the rest.
|
| 77 |
+
|
| 78 |
+
Parameters
|
| 79 |
+
----------
|
| 80 |
+
report, config : dict
|
| 81 |
+
Fresh verifier evidence and the trusted prepared task configuration.
|
| 82 |
+
digest : str
|
| 83 |
+
SHA-256 of the submission collected by Harbor.
|
| 84 |
+
|
| 85 |
+
Raises
|
| 86 |
+
------
|
| 87 |
+
ValueError
|
| 88 |
+
If evidence is missing or inconsistent, or the judge did not answer.
|
| 89 |
+
|
| 90 |
+
Notes
|
| 91 |
+
-----
|
| 92 |
+
Judged criteria have no grader command. Every other criterion keeps the
|
| 93 |
+
checks of evidence.py, under its rule for a task's own reward function:
|
| 94 |
+
the reward stays within the weighted criteria, and a criterion whose
|
| 95 |
+
command failed earns nothing unless the task scores that criterion from
|
| 96 |
+
its command's output (``fractional_rows``).
|
| 97 |
+
"""
|
| 98 |
+
report["judge"] = {"model": os.environ["JUDGE_MODEL"], "endpoint": urlsplit(_BASE_URL).hostname}
|
| 99 |
+
if report.get("status") != "graded":
|
| 100 |
+
evidence.validate_report(report, config, digest)
|
| 101 |
+
return
|
| 102 |
+
if (
|
| 103 |
+
report.get("revision") != evidence.REVISION
|
| 104 |
+
or report.get("task_id") != config["task_id"]
|
| 105 |
+
or report.get("patch_sha256") != digest
|
| 106 |
+
or report.get("grader_version") != config["grader_version"]
|
| 107 |
+
):
|
| 108 |
+
raise ValueError("Verifier evidence provenance mismatch")
|
| 109 |
+
result = report.get("result", {})
|
| 110 |
+
reward = evidence._number(result.get("reward"))
|
| 111 |
+
commands = report.get("commands", [])
|
| 112 |
+
fault_exit = config.get("fault_exit")
|
| 113 |
+
faults = {
|
| 114 |
+
row["name"]
|
| 115 |
+
for row in commands
|
| 116 |
+
if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
|
| 117 |
+
}
|
| 118 |
+
if (result.get("isError", False) and not faults) or result.get("done", True) is not True:
|
| 119 |
+
raise ValueError("Grader returned an incomplete or failed evaluation")
|
| 120 |
+
scores = result.get("subscores")
|
| 121 |
+
expected = {row[0]: row for row in config["criteria"]}
|
| 122 |
+
judged = {name for name, row in expected.items() if row[3] == "judge"}
|
| 123 |
+
if not isinstance(scores, list) or len(scores) != len(expected):
|
| 124 |
+
raise ValueError("Missing rubric criteria")
|
| 125 |
+
names = [row["name"] for row in scores]
|
| 126 |
+
if len(set(names)) != len(names) or set(names) != set(expected):
|
| 127 |
+
raise ValueError("Duplicate or unexpected rubric criteria")
|
| 128 |
+
raw = 0.0
|
| 129 |
+
values = {}
|
| 130 |
+
for score in scores:
|
| 131 |
+
name = score["name"]
|
| 132 |
+
error = _judge_error(score, result) if name in judged else None
|
| 133 |
+
if error:
|
| 134 |
+
raise ValueError(f"The judge did not answer for {name}: {error}")
|
| 135 |
+
value, weight = evidence._number(score["value"]), evidence._number(score["weight"])
|
| 136 |
+
if name in judged and value > 0 and not score.get("children"):
|
| 137 |
+
raise ValueError(f"{name} is credited without the judge's verdicts")
|
| 138 |
+
if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
|
| 139 |
+
raise ValueError("Criterion weights changed")
|
| 140 |
+
raw += value * weight
|
| 141 |
+
values[name] = value
|
| 142 |
+
command_names = [row["name"] for row in commands]
|
| 143 |
+
if len(command_names) != len(set(command_names)) or set(command_names) != (
|
| 144 |
+
set(expected) - judged
|
| 145 |
+
) | set(config["gates"]):
|
| 146 |
+
raise ValueError("Missing or duplicate grader command evidence")
|
| 147 |
+
for command in commands:
|
| 148 |
+
info = command.get("info") or {}
|
| 149 |
+
code = info.get("exit_code")
|
| 150 |
+
verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
|
| 151 |
+
if not verdict or info.get("timed_out"):
|
| 152 |
+
raise ValueError("Grader command failed outside its verdict contract")
|
| 153 |
+
if evidence._number(command["value"]) != float(code == 0):
|
| 154 |
+
raise ValueError("Command exit code disagrees with score")
|
| 155 |
+
probes = {row["name"]: row for row in report.get("fault_probes") or []}
|
| 156 |
+
if set(probes) != faults or any(
|
| 157 |
+
row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
|
| 158 |
+
):
|
| 159 |
+
raise ValueError("A grader could not judge and the untouched repository does not explain it")
|
| 160 |
+
if any(values.get(name, 0) for name in faults):
|
| 161 |
+
raise ValueError("A criterion its grader could not judge is credited")
|
| 162 |
+
info = result.get("info") or {}
|
| 163 |
+
if info.get("aggregate_mismatch") or info.get("git_apply"):
|
| 164 |
+
raise ValueError("Grader reported inconsistent grading")
|
| 165 |
+
passed = {row["name"]: row["value"] for row in commands}
|
| 166 |
+
if not config["judge"]["fractional_rows"] and any(
|
| 167 |
+
values[name] > passed[name] for name in expected if name not in judged
|
| 168 |
+
):
|
| 169 |
+
raise ValueError("A criterion is credited although its command failed")
|
| 170 |
+
if reward > raw + 1e-9:
|
| 171 |
+
raise ValueError("Grader reward exceeds its weighted criteria")
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
verify._preflight = _prepare_task
|
| 175 |
+
verify.validate_report = validate_judged_report
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
verify.main()
|
harbor/tasks/help_defaults/tests/test.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the original trusted coding rubric in a fresh, offline verifier container."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import hashlib
|
| 7 |
+
import importlib
|
| 8 |
+
import importlib.metadata
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shlex
|
| 12 |
+
import shutil
|
| 13 |
+
import signal
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
from evidence import REVISION, validate_report
|
| 20 |
+
|
| 21 |
+
OUT = Path("/logs/verifier")
|
| 22 |
+
PRIVATE = Path("/var/lib/task-evidence")
|
| 23 |
+
CONFIG = Path("/tests/config.json")
|
| 24 |
+
PATCH = Path("/workspace/submissions/submitted.patch")
|
| 25 |
+
GRADER_HOME = "/tmp/agent-home"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
|
| 29 |
+
return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _preflight(config: dict[str, Any]) -> None:
|
| 33 |
+
if importlib.metadata.version("hud") != config["grader_version"]:
|
| 34 |
+
raise RuntimeError("Grader library version does not match the task")
|
| 35 |
+
for filename, expected in config["verifier_files"].items():
|
| 36 |
+
if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
|
| 37 |
+
raise RuntimeError(f"Verifier source changed: {filename}")
|
| 38 |
+
for command in config["preflight"]:
|
| 39 |
+
completed = _run(command, cwd="/workspace/repo")
|
| 40 |
+
if completed.returncode:
|
| 41 |
+
raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _readable_mode(path: Path) -> int:
|
| 45 |
+
# World-readable, keeping what is executable so: a grader may ship tools.
|
| 46 |
+
return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _permissions() -> None:
|
| 50 |
+
# The orchestrator owns reports and rubric definitions. Grader commands,
|
| 51 |
+
# and so the candidate's code, run as uid 1000: the user the task installed
|
| 52 |
+
# its toolchain and caches for. They cannot read gold/vault or overwrite
|
| 53 |
+
# the rubric or the result files, which stay root's.
|
| 54 |
+
Path("/hud").chmod(0o711)
|
| 55 |
+
for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
|
| 56 |
+
if root.exists():
|
| 57 |
+
root.chmod(0o755)
|
| 58 |
+
for path in root.rglob("*"):
|
| 59 |
+
if not path.is_symlink():
|
| 60 |
+
path.chmod(_readable_mode(path))
|
| 61 |
+
home = Path(GRADER_HOME)
|
| 62 |
+
home.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
os.chown(home, 1000, 1000)
|
| 64 |
+
for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
|
| 65 |
+
path = Path(directory)
|
| 66 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
for item in (path, *path.rglob("*")):
|
| 68 |
+
if not item.is_symlink():
|
| 69 |
+
os.chown(item, 1000, 1000)
|
| 70 |
+
item.chmod(_readable_mode(item))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _hand_over_checkout() -> None:
|
| 74 |
+
# The original grader runs as root and may run the candidate's own suite in
|
| 75 |
+
# place, which writes into the tree. The rubric resets and re-applies the
|
| 76 |
+
# candidate as root, so give what root touched back to the grading user.
|
| 77 |
+
# Installed dependency trees are large and already that user's.
|
| 78 |
+
subprocess.run(
|
| 79 |
+
[
|
| 80 |
+
"find",
|
| 81 |
+
"/workspace/repo",
|
| 82 |
+
"-path",
|
| 83 |
+
"*/node_modules",
|
| 84 |
+
"-prune",
|
| 85 |
+
"-o",
|
| 86 |
+
"!",
|
| 87 |
+
"-user",
|
| 88 |
+
"1000",
|
| 89 |
+
"-exec",
|
| 90 |
+
"chown",
|
| 91 |
+
"-h",
|
| 92 |
+
"1000:1000",
|
| 93 |
+
"{}",
|
| 94 |
+
"+",
|
| 95 |
+
],
|
| 96 |
+
check=True,
|
| 97 |
+
capture_output=True,
|
| 98 |
+
timeout=3600,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
|
| 103 |
+
_preflight(config)
|
| 104 |
+
sys.path.insert(0, "/app")
|
| 105 |
+
task: Any = importlib.import_module("tasks")
|
| 106 |
+
await task._setup()
|
| 107 |
+
_permissions()
|
| 108 |
+
patch = PATCH.read_bytes()
|
| 109 |
+
if patch:
|
| 110 |
+
checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
|
| 111 |
+
if checked.returncode:
|
| 112 |
+
record.update(
|
| 113 |
+
status="rejected_patch",
|
| 114 |
+
patch_error=checked.stderr[-4000:],
|
| 115 |
+
result={"reward": 0.0, "subscores": None},
|
| 116 |
+
)
|
| 117 |
+
return
|
| 118 |
+
_run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
|
| 119 |
+
original = task.BashGrader
|
| 120 |
+
fault_exit = config.get("fault_exit")
|
| 121 |
+
faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []
|
| 122 |
+
|
| 123 |
+
class ObservedGrader:
|
| 124 |
+
@classmethod
|
| 125 |
+
async def grade(cls, *args: Any, **kwargs: Any) -> Any:
|
| 126 |
+
command = kwargs["command"]
|
| 127 |
+
_hand_over_checkout()
|
| 128 |
+
kwargs["command"] = (
|
| 129 |
+
"setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
|
| 130 |
+
f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
|
| 131 |
+
)
|
| 132 |
+
score = await original.grade(*args, **kwargs)
|
| 133 |
+
snapshot = score.model_dump(mode="json")
|
| 134 |
+
record["commands"].append(snapshot)
|
| 135 |
+
(PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
|
| 136 |
+
info = snapshot.get("info") or {}
|
| 137 |
+
if info.get("timed_out") or type(info.get("exit_code")) is not int:
|
| 138 |
+
raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
|
| 139 |
+
if fault_exit is not None and info["exit_code"] == fault_exit:
|
| 140 |
+
# The grader says it could not judge. Whether the submission or
|
| 141 |
+
# the environment is the reason is settled after grading.
|
| 142 |
+
faulted.append((args, dict(kwargs), snapshot["name"]))
|
| 143 |
+
elif info["exit_code"] not in (0, 1):
|
| 144 |
+
raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
|
| 145 |
+
return score
|
| 146 |
+
|
| 147 |
+
task.BashGrader = ObservedGrader
|
| 148 |
+
result = await task._grade(None)
|
| 149 |
+
if faulted:
|
| 150 |
+
# Ask the same commands about the untouched repository. A verdict there
|
| 151 |
+
# means the grader works here and the submission is what it could not
|
| 152 |
+
# judge, so the criterion stays unmet. No verdict there means the
|
| 153 |
+
# environment is at fault, and the attempt is invalid.
|
| 154 |
+
await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
|
| 155 |
+
await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
|
| 156 |
+
# Graders keep state between criteria, some of them a copy of the tree
|
| 157 |
+
# they judged. It describes the submission, so it goes too.
|
| 158 |
+
for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
|
| 159 |
+
if leftover.is_dir() and not leftover.is_symlink():
|
| 160 |
+
shutil.rmtree(leftover)
|
| 161 |
+
else:
|
| 162 |
+
leftover.unlink()
|
| 163 |
+
record["fault_probes"] = []
|
| 164 |
+
for args, kwargs, name in faulted:
|
| 165 |
+
_hand_over_checkout()
|
| 166 |
+
probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
|
| 167 |
+
info = probe.get("info") or {}
|
| 168 |
+
record["fault_probes"].append(
|
| 169 |
+
{
|
| 170 |
+
"name": name,
|
| 171 |
+
"exit_code": info.get("exit_code"),
|
| 172 |
+
"timed_out": info.get("timed_out"),
|
| 173 |
+
"stdout": (info.get("stdout") or "")[-2000:],
|
| 174 |
+
}
|
| 175 |
+
)
|
| 176 |
+
(PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
|
| 177 |
+
if info.get("timed_out") or info.get("exit_code") not in (0, 1):
|
| 178 |
+
raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
|
| 179 |
+
record["result"] = result.model_dump(mode="json")
|
| 180 |
+
# A rubric may answer an empty change without running any criterion.
|
| 181 |
+
record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _stop_candidate_processes() -> None:
|
| 185 |
+
# A candidate may fork. End its UID's processes before publishing evidence
|
| 186 |
+
# to a host bind mount, whose permissions may differ on Docker Desktop.
|
| 187 |
+
for directory in Path("/proc").iterdir():
|
| 188 |
+
if not directory.name.isdecimal():
|
| 189 |
+
continue
|
| 190 |
+
try:
|
| 191 |
+
status = (directory / "status").read_text()
|
| 192 |
+
uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
|
| 193 |
+
if uid == "1000":
|
| 194 |
+
os.kill(int(directory.name), signal.SIGKILL)
|
| 195 |
+
except (FileNotFoundError, ProcessLookupError):
|
| 196 |
+
pass
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def main() -> None:
|
| 200 |
+
"""Persist structured evidence and publish reward only after validation."""
|
| 201 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 203 |
+
PRIVATE.chmod(0o700)
|
| 204 |
+
reward_path = OUT / "reward.txt"
|
| 205 |
+
reward_path.unlink(missing_ok=True)
|
| 206 |
+
config = json.loads(CONFIG.read_text())
|
| 207 |
+
shutil.copy2(CONFIG, OUT / "config.json")
|
| 208 |
+
record: dict[str, Any] = {
|
| 209 |
+
"revision": REVISION,
|
| 210 |
+
"task_id": config["task_id"],
|
| 211 |
+
"grader_version": importlib.metadata.version("hud"),
|
| 212 |
+
"commands": [],
|
| 213 |
+
"status": "error",
|
| 214 |
+
}
|
| 215 |
+
try:
|
| 216 |
+
if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
|
| 217 |
+
raise ValueError("Missing, oversized or symlink submission")
|
| 218 |
+
record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
|
| 219 |
+
try:
|
| 220 |
+
asyncio.run(_grade(config, record))
|
| 221 |
+
finally:
|
| 222 |
+
_stop_candidate_processes()
|
| 223 |
+
reward_path.unlink(missing_ok=True)
|
| 224 |
+
validate_report(record, config, record["patch_sha256"])
|
| 225 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 226 |
+
reward_path.write_text(str(record["result"]["reward"]) + "\n")
|
| 227 |
+
except BaseException as error:
|
| 228 |
+
reward_path.unlink(missing_ok=True)
|
| 229 |
+
record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
|
| 230 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 231 |
+
raise
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|
harbor/tasks/manifest.json
CHANGED
|
@@ -1,12 +1,16 @@
|
|
| 1 |
{
|
| 2 |
"revision": "coding-rubric-v2",
|
| 3 |
"tasks": [
|
|
|
|
| 4 |
"journal_recovery_after_unclean_stop",
|
| 5 |
"bazel_remote_disk_eviction_accounting_contract",
|
| 6 |
"celery_retry_expires_countdown_contract",
|
|
|
|
|
|
|
| 7 |
"epicyon_deleted_post_announce_cache_contract",
|
| 8 |
"geode_oql_index_null_semantics_contract",
|
| 9 |
"go_mysql_mariadb_compressed_columns",
|
|
|
|
| 10 |
"kratos_cleanup_stale_flows_courier_contract",
|
| 11 |
"microblogpub_deleted_object_resurrect_lookup_contract",
|
| 12 |
"mongoose_syncindexes_contract",
|
|
@@ -16,6 +20,7 @@
|
|
| 16 |
"pomerium_route_order_contract",
|
| 17 |
"rope_rename_all_reexport_owners_contract",
|
| 18 |
"shared_handle_abandoned_operations",
|
|
|
|
| 19 |
"retained_top_level_names_keep_their_values",
|
| 20 |
"xandikos_itip_recurrence_id_override_contract",
|
| 21 |
"zettlr_clickable_keywords",
|
|
|
|
| 1 |
{
|
| 2 |
"revision": "coding-rubric-v2",
|
| 3 |
"tasks": [
|
| 4 |
+
"babylonjs_scene_remove_owner_refs_contract",
|
| 5 |
"journal_recovery_after_unclean_stop",
|
| 6 |
"bazel_remote_disk_eviction_accounting_contract",
|
| 7 |
"celery_retry_expires_countdown_contract",
|
| 8 |
+
"help_defaults",
|
| 9 |
+
"druid_lenient_script",
|
| 10 |
"epicyon_deleted_post_announce_cache_contract",
|
| 11 |
"geode_oql_index_null_semantics_contract",
|
| 12 |
"go_mysql_mariadb_compressed_columns",
|
| 13 |
+
"ahooks_request_cache_races",
|
| 14 |
"kratos_cleanup_stale_flows_courier_contract",
|
| 15 |
"microblogpub_deleted_object_resurrect_lookup_contract",
|
| 16 |
"mongoose_syncindexes_contract",
|
|
|
|
| 20 |
"pomerium_route_order_contract",
|
| 21 |
"rope_rename_all_reexport_owners_contract",
|
| 22 |
"shared_handle_abandoned_operations",
|
| 23 |
+
"bulkcreate_ignore_duplicates",
|
| 24 |
"retained_top_level_names_keep_their_values",
|
| 25 |
"xandikos_itip_recurrence_id_override_contract",
|
| 26 |
"zettlr_clickable_keywords",
|