Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(go): calls never wait to enter, and --check compares answer structure

Adeshina Lasisi8944b02f6560
diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml
index 712dc702..4b24327a 100644
--- a/.github/workflows/go.yml
+++ b/.github/workflows/go.yml
@@ -127,11 +127,11 @@ jobs:
LAYA_GO_FIXTURES: ${{ github.workspace }}/.go-goldens
LAYA_CHECKPOINTS: ${{ github.workspace }}/laya-java/.work/checkpoints
run: go test -race -count=1 -json ./... > "$RUNNER_TEMP/go-test.json"
- # Exactly the measured count (1307 tests and subtests, on both Go versions): dropping a
+ # Exactly the measured count (1321 tests and subtests, on both Go versions): dropping a
# case fails here, and adding one means raising this number.
- name: No test was skipped
if: ${{ !cancelled() }}
- run: python laya-go/scripts/check_test_json.py "$RUNNER_TEMP/go-test.json" --min-tests 1307
+ run: python laya-go/scripts/check_test_json.py "$RUNNER_TEMP/go-test.json" --min-tests 1321
# go.mod declares go 1.22, so that is what a consumer may build with.
- name: Run the tests on the oldest supported Go
@@ -143,7 +143,7 @@ jobs:
run: go test -count=1 -json ./... > "$RUNNER_TEMP/go-test-oldest.json"
- name: No test was skipped on the oldest Go either
if: ${{ !cancelled() }}
- run: python laya-go/scripts/check_test_json.py "$RUNNER_TEMP/go-test-oldest.json" --min-tests 1307
+ run: python laya-go/scripts/check_test_json.py "$RUNNER_TEMP/go-test-oldest.json" --min-tests 1321
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: ${{ failure() }}
diff --git a/laya-go/agent/agent.go b/laya-go/agent/agent.go
index 48788796..0512528a 100644
--- a/laya-go/agent/agent.go
+++ b/laya-go/agent/agent.go
@@ -6,6 +6,7 @@ import (
"fmt"
"io/fs"
"reflect"
+ "strings"
"sync"
"sync/atomic"
@@ -28,7 +29,14 @@ type StateError struct {
}
// Error names the state and the cause.
-func (e *StateError) Error() string { return fmt.Sprintf("agent: state %d: %v", e.Index, e.Err) }
+func (e *StateError) Error() string {
+ if e.Err == nil {
+ return fmt.Sprintf("agent: state %d", e.Index)
+ }
+ // The cause is a complete message ("agent: state is nil; ..."); keep one prefix and one subject.
+ msg := strings.TrimPrefix(strings.TrimPrefix(e.Err.Error(), "agent: "), "state ")
+ return fmt.Sprintf("agent: state %d: %s", e.Index, msg)
+}
// Unwrap returns the cause.
func (e *StateError) Unwrap() error { return e.Err }
@@ -43,8 +51,12 @@ type Agent struct {
temps *decode.Temperatures
sess infer.Session
- mu sync.RWMutex // held for reading by every call, for writing by Close
- closed atomic.Bool // set when Close starts, so new and queued calls return at once
+ mu sync.Mutex // guards shut, so a call enters or is refused without waiting
+ shut bool // set by Close under mu
+ inflight sync.WaitGroup // calls that entered
+ closed atomic.Bool // mirrors shut, for the check between chunks
+ once sync.Once // runs Close's body
+ closeErr error // the session's Close error, read after once.Do
}
// Option adjusts an Agent at Open. No options exist yet; the parameter is here so adding one is
@@ -58,7 +70,7 @@ type options struct{}
// The tokenizer must name the pad, CLS, SEP and mask tokens. The session must run the graph
// exported from that same checkpoint; nothing here can tell.
func Open(checkpoint fs.FS, s infer.Session, opts ...Option) (*Agent, error) {
- if s == nil {
+ if hasNilValue(s) {
return nil, errors.New("agent: Open needs a session")
}
var o options
@@ -109,19 +121,38 @@ func (a *Agent) Config() Config {
return cfg
}
-// Close marks the agent closed, so new and queued calls return ErrClosed at once, then waits for
-// calls in flight and closes the session. Close blocks until calls in flight return; cancel
-// their contexts to bound it. It is idempotent.
+// Close marks the agent closed, waits for calls in flight and closes the session. Close blocks
+// until calls in flight return; cancel their contexts to bound it. A call that has not yet
+// entered returns ErrClosed without waiting. Close is idempotent: a second call, concurrent or
+// not, waits for the first and returns the same error.
func (a *Agent) Close() error {
- first := a.closed.CompareAndSwap(false, true)
+ a.once.Do(func() {
+ a.mu.Lock()
+ a.shut = true
+ a.closed.Store(true)
+ a.mu.Unlock()
+ a.inflight.Wait()
+ if a.sess != nil {
+ a.closeErr = a.sess.Close()
+ }
+ })
+ return a.closeErr
+}
+
+// enter registers a call, or reports ErrClosed. It never waits for a call in flight. Every
+// successful enter is paired with leave.
+func (a *Agent) enter() error {
a.mu.Lock()
defer a.mu.Unlock()
- if !first || a.sess == nil {
- return nil
+ if a.shut || a.sess == nil {
+ return ErrClosed
}
- return a.sess.Close()
+ a.inflight.Add(1)
+ return nil
}
+func (a *Agent) leave() { a.inflight.Done() }
+
// CallOption adjusts one Predict or PredictBatch call.
type CallOption func(*call)
@@ -150,8 +181,7 @@ func WithSortByLength(on bool) CallOption { return func(c *call) { c.sort = on }
func (a *Agent) Predict(ctx context.Context, state any, qs schema.Questions, opts ...CallOption) (schema.Prediction, error) {
preds, err := a.PredictBatch(ctx, []any{state}, qs, opts...)
if err != nil {
- var se *StateError
- if errors.As(err, &se) {
+ if se, ok := err.(*StateError); ok { // the top-level error only, never one inside a RunError
err = se.Err
}
return schema.Prediction{}, err
@@ -182,17 +212,13 @@ func (a *Agent) PredictBatch(ctx context.Context, states []any, qs schema.Questi
if err := ctx.Err(); err != nil {
return nil, err
}
- if a.sess == nil || a.closed.Load() {
- return nil, ErrClosed
- }
- a.mu.RLock()
- defer a.mu.RUnlock()
- if a.closed.Load() {
- return nil, ErrClosed
+ if err := a.enter(); err != nil {
+ return nil, err
}
+ defer a.leave()
for i, state := range states {
if isNil(state) {
- return nil, &StateError{Index: i, Err: fmt.Errorf("is nil; pass a string, a map or a slice: %w", sequence.ErrUnsupportedState)}
+ return nil, &StateError{Index: i, Err: fmt.Errorf("agent: state is nil; pass a string, a map or a slice: %w", sequence.ErrUnsupportedState)}
}
}
if len(states) == 0 {
@@ -217,3 +243,16 @@ func isNil(state any) bool {
rv := reflect.ValueOf(state)
return rv.Kind() == reflect.Pointer && rv.IsNil()
}
+
+// hasNilValue reports an untyped nil or an interface holding a nil pointer, map, slice, func or
+// chan, which a method call would trip over.
+func hasNilValue(v any) bool {
+ if v == nil {
+ return true
+ }
+ switch rv := reflect.ValueOf(v); rv.Kind() {
+ case reflect.Pointer, reflect.Interface, reflect.Map, reflect.Slice, reflect.Func, reflect.Chan:
+ return rv.IsNil()
+ }
+ return false
+}
diff --git a/laya-go/agent/batch.go b/laya-go/agent/batch.go
index ece9514f..a698dfb8 100644
--- a/laya-go/agent/batch.go
+++ b/laya-go/agent/batch.go
@@ -122,7 +122,7 @@ func (a *Agent) run(ctx context.Context, qs schema.Questions, encoded [][]sequen
}
b, err := collate.Collate(rows, a.padID)
if err != nil {
- return nil, fmt.Errorf("agent: %w", err)
+ return nil, fmt.Errorf("agent: %w", err) // unreachable through the API: questions are valid when built
}
fail := func(err error) error { return &RunError{Rows: b.Rows, Length: b.Length, Markers: b.Markers, Err: err} }
out, err := a.sess.Run(ctx, b)
diff --git a/laya-go/agent/config.go b/laya-go/agent/config.go
index 300b6f62..0dba2af0 100644
--- a/laya-go/agent/config.go
+++ b/laya-go/agent/config.go
@@ -44,6 +44,8 @@ func (e *ConfigError) Error() string {
if e.Err != nil {
cause = e.Err.Error()
}
+ // One prefix: a cause may carry its own package's ("agent: " from a sentinel, "decode: ").
+ cause = strings.TrimPrefix(strings.TrimPrefix(cause, "agent: "), "decode: ")
switch e.Field {
case "":
return "agent: " + configFile + ": " + cause
@@ -178,7 +180,8 @@ func loadConfig(checkpoint fs.FS) (Config, *decode.Temperatures, error) {
}
// sameNumber is float(raw) == applied: false for anything float() refuses. A string is read as
-// decode.Clamp reads it: stripped, and without the hex and underscore spellings Python rejects.
+// the string rule of decode's toFloat (internal/decode/temperature.go), which this mirrors: stripped,
+// and without the x and p spellings of a Go hex float, which Python's float() rejects.
func sameNumber(raw any, applied float64) bool {
switch x := raw.(type) {
case string:
diff --git a/laya-go/agent/doc.go b/laya-go/agent/doc.go
index 00b1b714..0c6c8801 100644
--- a/laya-go/agent/doc.go
+++ b/laya-go/agent/doc.go
@@ -17,17 +17,18 @@
//
// # Differences from Python
//
-// With no questions, Python writes a usage of two keys (input_tokens, output_tokens); schema.Usage
-// writes all seven, and so does this package.
+// With no questions, Python writes a usage of two keys (input_tokens, output_tokens); this package
+// writes six: input_tokens, output_tokens, state_tokens, state_tokens_dropped, truncated and
+// truncated_questions. The seventh, options, is omitted when empty.
//
-// A nil state is refused, with or without questions, where Python raises a TypeError only when
-// there are questions. A nil slice or map is an empty list or dict, as in Python.
+// A nil slice or map is an empty list or dict, as in Python; a nil state is refused, as there.
//
// max_len and head_max_len are checked at load and must be positive integers; Python reads them
// with cfg.get and checks nothing until a call uses them.
//
-// A temperature that is not a list of exactly 3 numbers is refused at load, as Python's torch
-// Agent refuses it; ONNXAgent loads it.
+// A temperature that is not a list of exactly 3 numbers is refused at Open. Python's ONNXAgent
+// loads a list of the wrong length, a string or a dict and fails later or falls back (a scalar
+// such as 1.5 raises a TypeError at load); this package refuses all of them.
//
// A NaN or infinite logit is refused, including a -Inf for a real option, where Python would
// answer probability 0 for that option. A model that emits one is broken.
diff --git a/laya-go/agent/lifecycle_test.go b/laya-go/agent/lifecycle_test.go
new file mode 100644
index 00000000..fc63f7e9
--- /dev/null
+++ b/laya-go/agent/lifecycle_test.go
@@ -0,0 +1,286 @@
+package agent_test
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/NandhaKishorM/laya/laya-go/agent"
+ "github.com/NandhaKishorM/laya/laya-go/infer"
+ "github.com/NandhaKishorM/laya/laya-go/schema"
+ "github.com/NandhaKishorM/laya/laya-go/sequence"
+)
+
+// TestEnteringNeverWaitsForACallInFlight is the scenario of the second review: a Run is blocked,
+// predictors with a short context arrive as Close begins, and none may wait for that Run.
+func TestEnteringNeverWaitsForACallInFlight(t *testing.T) {
+ s := &fakeSession{}
+ a, err := agent.Open(toyCheckpoint(`{}`), s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ qs := questions(t)
+ started, release := make(chan struct{}), make(chan struct{})
+ s.before = func(n int) error {
+ if n == 0 {
+ close(started)
+ <-release
+ }
+ return nil
+ }
+ first := make(chan error, 1)
+ go func() { _, err := a.Predict(context.Background(), "state", qs); first <- err }()
+ <-started
+
+ const predictors = 16
+ var wg sync.WaitGroup
+ var slow atomic.Int32
+ gate := make(chan struct{})
+ for i := 0; i < predictors; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-gate
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ begin := time.Now()
+ a.Predict(ctx, "state", qs)
+ if time.Since(begin) > 500*time.Millisecond {
+ slow.Add(1)
+ }
+ }()
+ }
+ closed := make(chan error, 1)
+ close(gate)
+ go func() { closed <- a.Close() }()
+ wg.Wait()
+ if n := slow.Load(); n != 0 {
+ t.Errorf("%d of %d predictors waited for the blocked Run", n, predictors)
+ }
+ select {
+ case <-closed:
+ t.Fatal("Close returned while a Run was blocked")
+ default:
+ }
+ close(release)
+ if err := <-first; err != nil {
+ t.Errorf("the call in flight = %v", err)
+ }
+ if err := <-closed; err != nil {
+ t.Errorf("Close = %v", err)
+ }
+}
+
+// waitRefused polls until a is refusing calls, which is when Close has begun. The probe is an
+// empty batch: it enters and leaves without reaching the session, so it adds no run of its own.
+func waitRefused(t *testing.T, a *agent.Agent, qs schema.Questions) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for time.Now().Before(deadline) {
+ if _, err := a.PredictBatch(context.Background(), nil, qs); errors.Is(err, agent.ErrClosed) {
+ return
+ }
+ time.Sleep(time.Millisecond)
+ }
+ t.Fatal("the agent never started refusing calls")
+}
+
+func TestCallsAfterCloseBeganNeverReachTheSession(t *testing.T) {
+ qs := questions(t)
+ t.Run("a new call", func(t *testing.T) {
+ s := &fakeSession{}
+ a, _ := agent.Open(toyCheckpoint(`{}`), s)
+ started, release := make(chan struct{}), make(chan struct{})
+ s.before = func(n int) error {
+ if n == 0 {
+ close(started)
+ <-release
+ }
+ return nil
+ }
+ go a.Predict(context.Background(), "state", qs)
+ <-started
+ go a.Close()
+ waitRefused(t, a, qs)
+ if _, err := a.PredictBatch(context.Background(), []any{"a", "b"}, qs); !errors.Is(err, agent.ErrClosed) {
+ t.Errorf("PredictBatch = %v, want ErrClosed", err)
+ }
+ close(release)
+ a.Close()
+ if n := len(s.seen()); n != 1 {
+ t.Errorf("the session ran %d times, want only the call in flight", n)
+ }
+ })
+ t.Run("the next chunk of a call in flight", func(t *testing.T) {
+ s := &fakeSession{}
+ a, _ := agent.Open(toyCheckpoint(`{}`), s)
+ s.before = func(n int) error {
+ if n == 0 {
+ go a.Close()
+ waitRefused(t, a, qs)
+ }
+ return nil
+ }
+ _, err := a.PredictBatch(context.Background(), varied(), qs, agent.WithBatchSize(2))
+ if !errors.Is(err, agent.ErrClosed) {
+ t.Errorf("PredictBatch = %v, want ErrClosed", err)
+ }
+ if n := len(s.seen()); n != 1 {
+ t.Errorf("%d runs, want 1", n)
+ }
+ })
+}
+
+type closeFails struct {
+ *fakeSession
+ err error
+}
+
+func (c closeFails) Close() error { c.fakeSession.Close(); return c.err }
+
+func TestConcurrentClosesShareTheError(t *testing.T) {
+ boom := errors.New("boom")
+ fs := &fakeSession{}
+ a, err := agent.Open(toyCheckpoint(`{}`), closeFails{fs, boom})
+ if err != nil {
+ t.Fatal(err)
+ }
+ var wg sync.WaitGroup
+ errs := make([]error, 8)
+ for i := range errs {
+ wg.Add(1)
+ go func() { defer wg.Done(); errs[i] = a.Close() }()
+ }
+ wg.Wait()
+ for i, err := range errs {
+ if !errors.Is(err, boom) {
+ t.Errorf("Close #%d = %v, want the session's error", i, err)
+ }
+ }
+ if fs.closes != 1 {
+ t.Errorf("session closed %d times, want once", fs.closes)
+ }
+}
+
+func TestNilStateText(t *testing.T) {
+ a, _ := open(t, `{}`)
+ _, err := a.Predict(context.Background(), nil, questions(t))
+ if want := "agent: state is nil; pass a string, a map or a slice: " + sequence.ErrUnsupportedState.Error(); err == nil || err.Error() != want {
+ t.Errorf("Predict(nil) = %v\nwant %q", err, want)
+ }
+ if !errors.Is(err, sequence.ErrUnsupportedState) {
+ t.Errorf("Predict(nil) = %v, want it to wrap ErrUnsupportedState", err)
+ }
+ _, err = a.PredictBatch(context.Background(), []any{"ok", nil}, questions(t))
+ var se *agent.StateError
+ if !errors.As(err, &se) || se.Index != 1 || !strings.HasPrefix(err.Error(), "agent: state 1: is nil;") {
+ t.Errorf("PredictBatch = %v", err)
+ }
+}
+
+// TestPredictUnwrapsOnlyItsOwnStateError: a session error that wraps a *StateError must still
+// come back as the *RunError around it.
+func TestPredictUnwrapsOnlyItsOwnStateError(t *testing.T) {
+ a, s := open(t, `{}`)
+ inner := &agent.StateError{Index: 3, Err: errors.New("from the session")}
+ s.before = func(int) error { return inner }
+ _, err := a.Predict(context.Background(), "state", questions(t))
+ var re *agent.RunError
+ if _, top := err.(*agent.RunError); !top || !errors.As(err, &re) || !errors.Is(err, inner) {
+ t.Fatalf("Predict = %T %v, want the *RunError around the session's error", err, err)
+ }
+}
+
+type nilMapSession map[string]int
+
+func (nilMapSession) Run(context.Context, infer.Batch) (infer.Output, error) {
+ return infer.Output{}, nil
+}
+func (nilMapSession) Close() error { return nil }
+
+func TestOpenRefusesATypedNilSession(t *testing.T) {
+ var ptr *fakeSession
+ var m nilMapSession
+ _, untyped := agent.Open(toyCheckpoint(`{}`), nil)
+ for name, s := range map[string]infer.Session{"nil pointer": ptr, "nil map": m} {
+ a, err := agent.Open(toyCheckpoint(`{}`), s)
+ if a != nil || err == nil || err.Error() != untyped.Error() {
+ t.Errorf("%s: Open = %v, %v, want %v", name, a, err, untyped)
+ }
+ }
+ if a, err := agent.Open(toyCheckpoint(`{}`), nilMapSession{}); err != nil || a == nil {
+ t.Errorf("an empty, non-nil map session was refused: %v", err)
+ }
+}
+
+func TestConfigErrorTexts(t *testing.T) {
+ for config, want := range map[string]string{
+ `{"option_layout": "dual"}`: "agent: rl_agent_config.json: option_layout: option_layout is not supported by the ONNX runtime: 'dual'",
+ `{"temperature": [1, 1]}`: "agent: rl_agent_config.json: temperature: temperature must list 3 values, one per question type, got 2",
+ } {
+ _, err := agent.LoadConfig(toyCheckpoint(config))
+ if err == nil || err.Error() != want {
+ t.Errorf("%s: got %v\nwant %q", config, err, want)
+ }
+ }
+ if _, err := agent.LoadConfig(toyCheckpoint(`{"option_layout": "dual"}`)); !errors.Is(err, agent.ErrUnsupportedLayout) {
+ t.Errorf("the sentinel is lost: %v", err)
+ }
+}
+
+// ctxCancelsAfter is a context whose Err turns to Canceled after n calls that found it live.
+type ctxCancelsAfter struct {
+ context.Context
+ left int
+}
+
+func (c *ctxCancelsAfter) Err() error {
+ if c.left <= 0 {
+ return context.Canceled
+ }
+ c.left--
+ return nil
+}
+
+// TestContextIsCheckedBeforeEachState cancels while the states are being encoded: the entry check
+// and the first state's pass, the second state's does not, and nothing may run.
+func TestContextIsCheckedBeforeEachState(t *testing.T) {
+ a, s := open(t, `{}`)
+ ctx := &ctxCancelsAfter{Context: context.Background(), left: 3}
+ got, err := a.PredictBatch(ctx, varied(), questions(t))
+ if !errors.Is(err, context.Canceled) || got != nil {
+ t.Fatalf("PredictBatch = %v, %v, want Canceled", got, err)
+ }
+ if n := len(s.seen()); n != 0 {
+ t.Fatalf("the session ran %d times after the cancel", n)
+ }
+}
+
+// TestHexTemperaturesAreNotNumbers pins sameNumber's guard against Go's hex floats. Python 3's
+// float() on the same strings, run with the reference's clamp_temperature:
+//
+// float('0x10') raises ValueError float('0x1p0') raises ValueError float('1_0') -> 10.0
+//
+// so "0x1p0" is applied as 1.0 and reported as rejected, though Go parses it as 1. The "1_0"
+// spelling is never a Go float, so the underscore half of the guard cannot change a result.
+func TestHexTemperaturesAreNotNumbers(t *testing.T) {
+ for _, raw := range []string{"0x1p0", "0x10", "0X1P0"} {
+ cfg, err := agent.LoadConfig(toyCheckpoint(`{"temperature": ["` + raw + `", 1, 1]}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(cfg.Warnings) != 1 || !strings.Contains(cfg.Warnings[0], "temperature[0]='"+raw+"' -> 1") {
+ t.Errorf("%s: warnings = %q, want the entry reported as rejected", raw, cfg.Warnings)
+ }
+ }
+}
+
+func TestStateErrorWithoutACause(t *testing.T) {
+ if got := (&agent.StateError{Index: 2}).Error(); got != "agent: state 2" {
+ t.Errorf("got %q", got)
+ }
+}
diff --git a/laya-go/infer/infer.go b/laya-go/infer/infer.go
index 4d4e0b51..8dcec64a 100644
--- a/laya-go/infer/infer.go
+++ b/laya-go/infer/infer.go
@@ -68,7 +68,8 @@ func (e *ShapeError) Error() string {
// - every slice's length matches Rows, Length and Markers, else a *ShapeError;
// - every MarkerPos lies in [0, Length).
//
-// All but the ShapeError are plain errors.
+// All but the ShapeError are plain errors. Token ids, question types and mask values are not
+// checked: a backend passes them to the graph, which rejects an out-of-range index.
func (b Batch) Validate() error {
if b.Rows < 0 || b.Length < 0 || b.Markers < 0 {
return fmt.Errorf("infer: batch has negative dimensions %d x %d x %d", b.Rows, b.Length, b.Markers)
diff --git a/laya-go/infer/infer_test.go b/laya-go/infer/infer_test.go
index fd7d8c19..6c19f056 100644
--- a/laya-go/infer/infer_test.go
+++ b/laya-go/infer/infer_test.go
@@ -127,3 +127,42 @@ func TestValidateNamesTheEmptyRow(t *testing.T) {
t.Fatalf("Validate = %v", err)
}
}
+
+// TestNegativeDimensionsAreRefusedWithoutRows pins that the sign check does not depend on Rows.
+func TestNegativeDimensionsAreRefusedWithoutRows(t *testing.T) {
+ for name, b := range map[string]infer.Batch{
+ "markers": {Markers: -1},
+ "length": {Length: -1},
+ "both": {Length: 4, Markers: -3},
+ "rows": {Rows: -1, Length: 4, Markers: 2},
+ } {
+ err := b.Validate()
+ var se *infer.ShapeError
+ if err == nil || errors.As(err, &se) || !strings.Contains(err.Error(), "negative") {
+ t.Errorf("%s: Validate = %v, want the negative-dimensions error", name, err)
+ }
+ }
+}
+
+// TestOverflowGuardBoundary pins the exact edge: the largest dimension whose product with Rows
+// does not overflow passes the guard, and is then refused by the slice-length check.
+func TestOverflowGuardBoundary(t *testing.T) {
+ cases := []struct {
+ name string
+ b infer.Batch
+ want string // the ShapeError's tensor
+ }{
+ {"length at the edge, 1 row", infer.Batch{Rows: 1, Length: math.MaxInt, Markers: 2}, infer.NameInputIDs},
+ {"length at the edge, 2 rows", infer.Batch{Rows: 2, Length: math.MaxInt / 2, Markers: 2}, infer.NameInputIDs},
+ {"markers at the edge, 1 row", infer.Batch{Rows: 1, Length: 1, Markers: math.MaxInt,
+ InputIDs: make([]int64, 1), AttentionMask: make([]int64, 1)}, infer.NameMarkerPos},
+ {"markers at the edge, 2 rows", infer.Batch{Rows: 2, Length: 1, Markers: math.MaxInt / 2,
+ InputIDs: make([]int64, 2), AttentionMask: make([]int64, 2)}, infer.NameMarkerPos},
+ }
+ for _, c := range cases {
+ var se *infer.ShapeError
+ if err := c.b.Validate(); !errors.As(err, &se) || se.Name != c.want {
+ t.Errorf("%s: Validate = %v, want a ShapeError for %s", c.name, err, c.want)
+ }
+ }
+}
diff --git a/laya-go/scripts/gen_go_fixtures.py b/laya-go/scripts/gen_go_fixtures.py
index fc64125f..22bd8da1 100644
--- a/laya-go/scripts/gen_go_fixtures.py
+++ b/laya-go/scripts/gen_go_fixtures.py
@@ -974,24 +974,53 @@ def _unnumber(value):
return value
+def _key(value):
+ """value spelled as json.dumps writes it as an object key, or None if it cannot be a key."""
+ if isinstance(value, str):
+ return value
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, (int, float)):
+ return json.dumps(value)
+ return None
+
+
+def _answer_shape(answer):
+ """One answer's type, key sets and order and legend, with no number and no chosen option.
+
+ A choice is blanked only when it is one of the answer's options, so a choice that names no
+ option, or is not a scalar, still differs. Anything that is not an answer is kept as it is.
+ """
+ if not isinstance(answer, dict):
+ return answer
+ shaped = _unnumber(answer)
+ probabilities = answer.get("probabilities")
+ if "choice" in answer and isinstance(probabilities, dict) and _key(answer["choice"]) in probabilities:
+ shaped["choice"] = None
+ return shaped
+
+
def _answers_shape(answers):
- """Each answer's type, key sets and order, legend and ids; no number, and no chosen value."""
- out = {}
- for question_id, answer in answers.items():
- shaped = _unnumber(answer)
- if "choice" in shaped:
- shaped["choice"] = None
- out[question_id] = shaped
- return out
+ if not isinstance(answers, dict):
+ return answers
+ return {question_id: _answer_shape(answer) for question_id, answer in answers.items()}
+
+
+def _text_shape(text):
+ """answer_text, parsed and shaped; text that is not JSON is kept, so it differs."""
+ try:
+ return render(_answer_shape(json.loads(text))).rstrip("\n")
+ except (TypeError, ValueError):
+ return text
def portable(payload):
out = dict(payload)
for name in EXP_DEPENDENT:
- out[name] = {"cases": [{k: v for k, v in case.items() if k != "answer_text"}
+ out[name] = {"cases": [{**case, "answer_text": _text_shape(case.get("answer_text"))}
for case in payload[name]["cases"]]}
out["predict_plan"] = {
- name: ({"cases": [{**case, "results": [{**r, "answers": _answers_shape(r["answers"])}
+ name: ({"cases": [{**case, "results": [{**r, "answers": _answers_shape(r.get("answers"))}
for r in case["results"]]}
for case in value["cases"]]} if name != "questions" else value)
for name, value in payload["predict_plan"].items()}
@@ -1016,7 +1045,7 @@ def main(argv=None):
try:
with open(path, encoding="utf-8") as handle:
current = render(portable(json.load(handle)))
- except (OSError, ValueError, KeyError, TypeError):
+ except (OSError, ValueError, KeyError, TypeError, AttributeError, IndexError):
current = None
if current != render(portable(payload)):
print("gen_go_fixtures: %s is stale or missing; run laya-go/scripts/gen_go_fixtures.py"