diff --git a/eval.go b/eval.go index 0870836..5770b05 100644 --- a/eval.go +++ b/eval.go @@ -1357,13 +1357,5 @@ func powValues(a, b Value) Value { } func valuesEqual(a, b Value) bool { - // Cross-type numeric comparison. - if a.IsNumber() && b.IsNumber() { - return toFloat64(a) == toFloat64(b) - } - // None == None. - if a.IsNone() && b.IsNone() { - return true - } return a.Equals(b) } diff --git a/jinjafix_regression_test.go b/jinjafix_regression_test.go new file mode 100644 index 0000000..617837f --- /dev/null +++ b/jinjafix_regression_test.go @@ -0,0 +1,141 @@ +package jinja + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "runtime/debug" + "testing" + "time" +) + +type jinjaFixResult struct { + ID string `json:"id"` + Stage string `json:"stage"` + Output string `json:"output,omitempty"` + Error string `json:"error,omitempty"` +} + +func jinjaFixEvaluate(source string) (r jinjaFixResult) { + defer func() { + if p := recover(); p != nil { + r = jinjaFixResult{Stage: "panic", Error: fmt.Sprint(p)} + } + }() + template, err := Compile(source) + if err != nil { + return jinjaFixResult{Stage: "compile_error", Error: err.Error()} + } + output, err := template.Render(nil) + if err != nil { + return jinjaFixResult{Stage: "render_error", Error: err.Error()} + } + return jinjaFixResult{Stage: "render", Output: output} +} + +// Child processes bound nontermination and stack exhaustion in broken revisions. +func TestJinjaFixWorker(t *testing.T) { + if os.Getenv("JINJAFIX_WORKER") != "1" { + return + } + debug.SetMaxStack(2 << 20) + source, err := io.ReadAll(os.Stdin) + if err != nil { + os.Exit(2) + } + if json.NewEncoder(os.Stdout).Encode(jinjaFixEvaluate(string(source))) != nil { + os.Exit(2) + } + os.Exit(0) +} + +func jinjaFixReferenceMissing(found bool) bool { + return !found +} + +func TestJinjaFixRegression(t *testing.T) { + var cases []struct { + ID string `json:"id"` + Source string `json:"source"` + GoStage string `json:"go_stage,omitempty"` + Reason string `json:"reason,omitempty"` + } + var python struct { + Cases []jinjaFixResult `json:"cases"` + } + read := func(path string, v any) { + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if err = json.Unmarshal(b, v); err != nil { + t.Fatal(err) + } + } + read("testdata/jinjafix/cases.json", &cases) + read("testdata/jinjafix/python-result.json", &python) + expected := map[string]jinjaFixResult{} + for _, r := range python.Cases { + expected[r.ID] = r + } + var results []jinjaFixResult + for _, c := range cases { + t.Run(c.ID, func(t *testing.T) { + want, ok := expected[c.ID] + if jinjaFixReferenceMissing(ok) { + t.Fatal("missing Python result") + } + if c.GoStage != "" { + if c.Reason == "" { + t.Fatal("undocumented parity exception") + } + want.Stage = c.GoStage + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestJinjaFixWorker$") + cmd.Env = append(os.Environ(), "JINJAFIX_WORKER=1", "GOMEMLIMIT=64MiB", "GOTRACEBACK=none") + cmd.Stdin = bytes.NewBufferString(c.Source) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err := cmd.Run() + var got jinjaFixResult + switch { + case ctx.Err() != nil: + got = jinjaFixResult{Stage: "timeout", Error: ctx.Err().Error()} + case err != nil: + got = jinjaFixResult{Stage: "process_error", Error: err.Error()} + default: + if err = json.Unmarshal(stdout.Bytes(), &got); err != nil { + t.Fatal(err) + } + } + got.ID = c.ID + results = append(results, got) + if jinjaFixResultsDiffer(got, want) { + t.Errorf("Go: stage=%s output=%q; expected: stage=%s output=%q; error=%s", got.Stage, got.Output, want.Stage, want.Output, got.Error) + } + }) + } + if path := os.Getenv("JINJAFIX_RESULT_PATH"); path != "" { + b, err := json.MarshalIndent(results, "", " ") + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(path, append(b, '\n'), 0644); err != nil { + t.Fatal(err) + } + } +} + +func jinjaFixResultsDiffer(got, want jinjaFixResult) bool { + if got.Stage != want.Stage { + return true + } + return want.Stage == "render" && got.Output != want.Output +} diff --git a/testdata/jinjafix/README.txt b/testdata/jinjafix/README.txt new file mode 100644 index 0000000..6bce140 --- /dev/null +++ b/testdata/jinjafix/README.txt @@ -0,0 +1,9 @@ +Reproduce the Python reference: + python3 testdata/jinjafix/reference.py + +Run the shared-input Go regression: + go test -count=1 -v -run ^TestJinjaFixRegression$ . + +The test commit records Python results and failing Go results from the same +inputs. The fix commit records passing Go results and the full Go test suite. +Worker processes bound panics, stack exhaustion and nontermination. diff --git a/testdata/jinjafix/cases.json b/testdata/jinjafix/cases.json new file mode 100644 index 0000000..23e8be4 --- /dev/null +++ b/testdata/jinjafix/cases.json @@ -0,0 +1,32 @@ +[ + { + "id": "B009-01", + "source": "{{ 9007199254740992 == 9007199254740993 }}", + "origin": "testdata/provisioning/5g-network.jinja", + "source_line": 725 + }, + { + "id": "B009-02", + "source": "{{ 9007199254740993 == 9007199254740992.0 }}", + "origin": "testdata/provisioning/5g-network.jinja", + "source_line": 729 + }, + { + "id": "B010-01", + "source": "{{ [{'qfi': 1}] == [{'qfi': 1.0}] }}", + "origin": "testdata/provisioning/5g-network.jinja", + "source_line": 733 + }, + { + "id": "B010-02", + "source": "{{ 1.0 in [1] }}", + "origin": "testdata/provisioning/5g-network.jinja", + "source_line": 737 + }, + { + "id": "B010-03", + "source": "{{ true == 1 }}", + "origin": "testdata/provisioning/5g-network.jinja", + "source_line": 741 + } +] diff --git a/testdata/jinjafix/go-after.json b/testdata/jinjafix/go-after.json new file mode 100644 index 0000000..5b3bc1f --- /dev/null +++ b/testdata/jinjafix/go-after.json @@ -0,0 +1,27 @@ +[ + { + "id": "B009-01", + "stage": "render", + "output": "False" + }, + { + "id": "B009-02", + "stage": "render", + "output": "False" + }, + { + "id": "B010-01", + "stage": "render", + "output": "True" + }, + { + "id": "B010-02", + "stage": "render", + "output": "True" + }, + { + "id": "B010-03", + "stage": "render", + "output": "True" + } +] diff --git a/testdata/jinjafix/go-after.txt b/testdata/jinjafix/go-after.txt new file mode 100644 index 0000000..12ce450 --- /dev/null +++ b/testdata/jinjafix/go-after.txt @@ -0,0 +1,14 @@ +=== RUN TestJinjaFixRegression +=== RUN TestJinjaFixRegression/B009-01 +=== RUN TestJinjaFixRegression/B009-02 +=== RUN TestJinjaFixRegression/B010-01 +=== RUN TestJinjaFixRegression/B010-02 +=== RUN TestJinjaFixRegression/B010-03 +--- PASS: TestJinjaFixRegression (0.02s) + --- PASS: TestJinjaFixRegression/B009-01 (0.00s) + --- PASS: TestJinjaFixRegression/B009-02 (0.00s) + --- PASS: TestJinjaFixRegression/B010-01 (0.00s) + --- PASS: TestJinjaFixRegression/B010-02 (0.00s) + --- PASS: TestJinjaFixRegression/B010-03 (0.00s) +PASS +ok github.com/ardanlabs/jinja 0.025s diff --git a/testdata/jinjafix/go-before.json b/testdata/jinjafix/go-before.json new file mode 100644 index 0000000..8ad1eb8 --- /dev/null +++ b/testdata/jinjafix/go-before.json @@ -0,0 +1,27 @@ +[ + { + "id": "B009-01", + "stage": "render", + "output": "True" + }, + { + "id": "B009-02", + "stage": "render", + "output": "True" + }, + { + "id": "B010-01", + "stage": "render", + "output": "False" + }, + { + "id": "B010-02", + "stage": "render", + "output": "False" + }, + { + "id": "B010-03", + "stage": "render", + "output": "False" + } +] diff --git a/testdata/jinjafix/go-before.txt b/testdata/jinjafix/go-before.txt new file mode 100644 index 0000000..089df55 --- /dev/null +++ b/testdata/jinjafix/go-before.txt @@ -0,0 +1,20 @@ +=== RUN TestJinjaFixRegression +=== RUN TestJinjaFixRegression/B009-01 + jinjafix_regression_test.go:121: Go: stage=render output="True"; expected: stage=render output="False"; error= +=== RUN TestJinjaFixRegression/B009-02 + jinjafix_regression_test.go:121: Go: stage=render output="True"; expected: stage=render output="False"; error= +=== RUN TestJinjaFixRegression/B010-01 + jinjafix_regression_test.go:121: Go: stage=render output="False"; expected: stage=render output="True"; error= +=== RUN TestJinjaFixRegression/B010-02 + jinjafix_regression_test.go:121: Go: stage=render output="False"; expected: stage=render output="True"; error= +=== RUN TestJinjaFixRegression/B010-03 + jinjafix_regression_test.go:121: Go: stage=render output="False"; expected: stage=render output="True"; error= +--- FAIL: TestJinjaFixRegression (0.02s) + --- FAIL: TestJinjaFixRegression/B009-01 (0.00s) + --- FAIL: TestJinjaFixRegression/B009-02 (0.00s) + --- FAIL: TestJinjaFixRegression/B010-01 (0.00s) + --- FAIL: TestJinjaFixRegression/B010-02 (0.00s) + --- FAIL: TestJinjaFixRegression/B010-03 (0.00s) +FAIL +FAIL github.com/ardanlabs/jinja 0.024s +FAIL diff --git a/testdata/jinjafix/go-suite-after.txt b/testdata/jinjafix/go-suite-after.txt new file mode 100644 index 0000000..2d5a7d2 --- /dev/null +++ b/testdata/jinjafix/go-suite-after.txt @@ -0,0 +1,4 @@ +ok github.com/ardanlabs/jinja 9.297s +? github.com/ardanlabs/jinja/examples/basic [no test files] +? github.com/ardanlabs/jinja/examples/chat [no test files] +? github.com/ardanlabs/jinja/examples/toolcall [no test files] diff --git a/testdata/jinjafix/provenance.json b/testdata/jinjafix/provenance.json new file mode 100644 index 0000000..51b4961 --- /dev/null +++ b/testdata/jinjafix/provenance.json @@ -0,0 +1,9 @@ +{ + "base_commit": "b1bf3a06adcade12b59a1dfaa2edef6f4a7d6e09", + "selected_fix_commit": "0b251fc8a5f5e9c9f6c81840c0aeef5d6b021df9", + "original_branch": "cd-fix-numeric-equality", + "corpus_sha256": "e844754b9724b93fd2fc162d3d756cca40a57d6ed07188b02d02b2bcbe834bb9", + "comparison": "Exact successful output; compile/render error stage agreement. Error strings are recorded, not equated.", + "previous_test_commit": "c7c6fb93366268557b958972db7e92ab35a52f74", + "previous_fix_commit": "6e539b2b2ef834d7d6f98ad154cba2792fff4b21" +} diff --git a/testdata/jinjafix/python-result.json b/testdata/jinjafix/python-result.json new file mode 100644 index 0000000..ef06c1b --- /dev/null +++ b/testdata/jinjafix/python-result.json @@ -0,0 +1,39 @@ +{ + "python": "3.14.4", + "jinja2": "3.1.6", + "settings": { + "trim_blocks": true, + "lstrip_blocks": true, + "keep_trailing_newline": true + }, + "extensions": [ + "fromjson=json.loads" + ], + "cases": [ + { + "id": "B009-01", + "stage": "render", + "output": "False" + }, + { + "id": "B009-02", + "stage": "render", + "output": "False" + }, + { + "id": "B010-01", + "stage": "render", + "output": "True" + }, + { + "id": "B010-02", + "stage": "render", + "output": "True" + }, + { + "id": "B010-03", + "stage": "render", + "output": "True" + } + ] +} diff --git a/testdata/jinjafix/reference.py b/testdata/jinjafix/reference.py new file mode 100644 index 0000000..550ee08 --- /dev/null +++ b/testdata/jinjafix/reference.py @@ -0,0 +1,42 @@ +"""Recompute Python results for the exact inputs used by the Go unit test.""" +import json +import pathlib +import platform +import sys + +import jinja2 + + +def evaluate(source): + env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True, + keep_trailing_newline=True) + # fromjson is a repository extension; tojson remains stock Jinja2. + env.filters['fromjson'] = json.loads + try: + template = env.from_string(source) + except Exception as error: + return dict(stage='compile_error', error=str(error), exception=type(error).__name__) + try: + return dict(stage='render', output=template.render()) + except Exception as error: + return dict(stage='render_error', error=str(error), exception=type(error).__name__) + + +if __name__ == '__main__': + if len(sys.argv) > 1 and sys.argv[1] == '--worker': + print(json.dumps(evaluate(sys.stdin.read()), ensure_ascii=False)) + else: + import subprocess + here = pathlib.Path(__file__).resolve().parent + cases = json.loads((here / 'cases.json').read_text()) + results = [] + for case in cases: + child = subprocess.run([sys.executable, __file__, '--worker'], + input=case['source'], capture_output=True, + text=True, timeout=5, check=True) + results.append(dict(id=case['id'], **json.loads(child.stdout))) + print(json.dumps(dict(python=platform.python_version(), jinja2=jinja2.__version__, + settings=dict(trim_blocks=True, lstrip_blocks=True, + keep_trailing_newline=True), + extensions=['fromjson=json.loads'], cases=results), + ensure_ascii=False, indent=2)) diff --git a/testdata/jinjafix/requirements.txt b/testdata/jinjafix/requirements.txt new file mode 100644 index 0000000..f7c9608 --- /dev/null +++ b/testdata/jinjafix/requirements.txt @@ -0,0 +1 @@ +Jinja2==3.1.6 diff --git a/value.go b/value.go index 8128f57..7cdfd04 100644 --- a/value.go +++ b/value.go @@ -5,6 +5,7 @@ package jinja import ( "encoding/json" "fmt" + "math" "reflect" "sort" "strings" @@ -226,8 +227,50 @@ func (v Value) String() string { return "Undefined" } +func isNumericEqualityValue(v Value) bool { return v.IsNumber() || v.IsBool() } +func isIntegralValue(v Value) bool { return v.IsInt() || v.IsBool() } +func isNaNValue(v Value) bool { return v.IsFloat() && math.IsNaN(v.AsFloat()) } + +func compareIntFloat(i int64, f float64) int { + if f >= 0x1p63 { + return -1 + } + if f < -0x1p63 { + return 1 + } + fi := int64(f) + if i < fi { + return -1 + } + if i > fi { + return 1 + } + if float64(fi) < f { + return -1 + } + if float64(fi) > f { + return 1 + } + return 0 +} + // Equals reports whether v and other hold the same value. func (v Value) Equals(other Value) bool { + if isNumericEqualityValue(v) && isNumericEqualityValue(other) { + if isNaNValue(v) || isNaNValue(other) { + return false + } + if isIntegralValue(v) && isIntegralValue(other) { + return toInt64(v) == toInt64(other) + } + if v.IsFloat() && other.IsFloat() { + return v.AsFloat() == other.AsFloat() + } + if v.IsFloat() { + return compareIntFloat(toInt64(other), v.AsFloat()) == 0 + } + return compareIntFloat(toInt64(v), other.AsFloat()) == 0 + } if v.kind != other.kind { return false }