diff --git a/botanical357_test_harness/README.md b/botanical357_test_harness/README.md new file mode 100644 index 0000000..fe81195 --- /dev/null +++ b/botanical357_test_harness/README.md @@ -0,0 +1 @@ +These portable tests execute exact extracted production functions with boundaries stubbed. Camera tests stub app, logging and camJobStatus. Download tests stub final file replace with os.Rename and SHA file helper. No physical camera, UI, driver, real package setup or neural inference is exercised. The full Windows test source compilation is separately recorded and is not execution. diff --git a/botanical357_test_harness/camera/actual.go b/botanical357_test_harness/camera/actual.go new file mode 100644 index 0000000..f930beb --- /dev/null +++ b/botanical357_test_harness/camera/actual.go @@ -0,0 +1,48 @@ +package main +import("context";"sync";"sync/atomic";"time") +type app struct{} +var cameraCommandMu sync.Mutex +var calibrationMutationMu sync.Mutex +var cameraCommandWanted,cameraCommandActive atomic.Uint64 +var camHandoverCancel func(string,string) +func camJobStatus()(string,bool){return "fixture",false} +func logf(string,...interface{}){} +func cameraCommandSuperseded() bool { + a := cameraCommandActive.Load() + return a != 0 && a != cameraCommandWanted.Load() +} +func (a *app) cameraCommandContext(ctx context.Context, run func()) { a.cameraCommandContextExpected(ctx,nil,run) } +func (a *app) cameraCommandContextIfCurrent(ctx context.Context,expected uint64,run func()){a.cameraCommandContextExpected(ctx,&expected,run)} +func (a *app) cameraCommandContextExpected(ctx context.Context,expected *uint64,run func()) { + if ctx.Err() != nil { + return + } + calibrationMutationMu.Lock() + if expected!=nil&&cameraCommandWanted.Load()!=*expected{calibrationMutationMu.Unlock();return} + ticket := cameraCommandWanted.Add(1) + calibrationMutationMu.Unlock() + deadline := time.Now().Add(30 * time.Second) + noted := false + for !cameraCommandMu.TryLock() { + if ctx.Err() != nil || ticket != cameraCommandWanted.Load() { + return + } + if !noted && camHandoverCancel != nil { + noted = true + busy, _ := camJobStatus() + camHandoverCancel(busy, "new camera command") + } + if time.Now().After(deadline) { + logf("New camera command stopped: previous workflow has not finished cleanup. No new command started; try again when it stops.") + return + } + time.Sleep(200 * time.Millisecond) + } + defer cameraCommandMu.Unlock() + if ctx.Err() != nil || ticket != cameraCommandWanted.Load() { + return + } + cameraCommandActive.Store(ticket) + defer cameraCommandActive.Store(0) + run() +} diff --git a/botanical357_test_harness/camera/actual_test.go b/botanical357_test_harness/camera/actual_test.go new file mode 100644 index 0000000..069a965 --- /dev/null +++ b/botanical357_test_harness/camera/actual_test.go @@ -0,0 +1,25 @@ +package main +import("context";"testing";"time") +func Test357ExpectedOwnerDoesNotOverwriteLaterCameraCommand(t *testing.T){ + a:=&app{};old:=cameraCommandWanted.Load();cameraCommandWanted.Add(1);later:=cameraCommandWanted.Load();ran:=false + a.cameraCommandContextIfCurrent(context.Background(),old,func(){ran=true}) + if ran||cameraCommandWanted.Load()!=later{t.Fatal("late setup stole camera command")} +} +func Test357CurrentOwnerRunsAndReleases(t *testing.T){ + a:=&app{};old:=cameraCommandWanted.Load();ran:=false + a.cameraCommandContextIfCurrent(context.Background(),old,func(){ran=true;if cameraCommandActive.Load()==0||cameraCommandSuperseded(){t.Error("wrong active owner")}}) + if !ran||cameraCommandActive.Load()!=0{t.Fatal("current owner not run/released")} +} +func Test357CancelledSetupDoesNotReserveCamera(t *testing.T){ + old:=cameraCommandWanted.Load();ctx,cancel:=context.WithCancel(context.Background());cancel() + (&app{}).cameraCommandContextIfCurrent(ctx,old,func(){t.Error("cancelled work ran")}) + if cameraCommandWanted.Load()!=old{t.Fatal("cancelled setup reserved camera")} +} +func Test357WaitingSetupCancelledWithoutRunning(t *testing.T){ + cameraCommandMu.Lock();ctx,cancel:=context.WithTimeout(context.Background(),10*time.Millisecond);defer cancel();done:=make(chan bool,1) + go func(){(&app{}).cameraCommandContextIfCurrent(ctx,cameraCommandWanted.Load(),func(){t.Error("queued cancelled work ran")});done<-true}() + select{case <-done:case <-time.After(time.Second):t.Error("cancel did not interrupt wait")};cameraCommandMu.Unlock() +} +func Test357NewerCommandSupersedesActiveOwner(t *testing.T){ + (&app{}).cameraCommandContext(context.Background(),func(){cameraCommandWanted.Add(1);if !cameraCommandSuperseded(){t.Error("supersession not visible")}}) +} diff --git a/botanical357_test_harness/fetch/actual.go b/botanical357_test_harness/fetch/actual.go new file mode 100644 index 0000000..af3924c --- /dev/null +++ b/botanical357_test_harness/fetch/actual.go @@ -0,0 +1,33 @@ +package main +import("context";"crypto/sha256";"encoding/hex";"fmt";"io";"net/http";"os") +func sha256File(path string)(string,error){raw,e:=os.ReadFile(path);h:=sha256.Sum256(raw);return hex.EncodeToString(h[:]),e} +func humanReplaceModel(from,to string)error{return os.Rename(from,to)} +func humanFetchPinned(ctx context.Context, url, path, sha string, max int64) error { + if h, e := sha256File(path); e == nil && h == sha { + return nil + } + req, e := http.NewRequestWithContext(ctx, "GET", url, nil) + if e != nil { + return e + } + resp, e := http.DefaultClient.Do(req) + if e != nil { + return e + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return fmt.Errorf("runtime download HTTP%d", resp.StatusCode) + } + f, e := os.Create(path + ".part") + if e != nil { + return e + } + h := sha256.New() + n, e := io.Copy(io.MultiWriter(f, h), io.LimitReader(resp.Body, max+1)) + ce := f.Close() + if e != nil || ce != nil || n > max || hex.EncodeToString(h.Sum(nil)) != sha { + os.Remove(path + ".part") + return fmt.Errorf("runtime checksum/download failure") + } + return humanReplaceModel(path+".part", path) +} \ No newline at end of file diff --git a/botanical357_test_harness/fetch/actual_test.go b/botanical357_test_harness/fetch/actual_test.go new file mode 100644 index 0000000..7f92381 --- /dev/null +++ b/botanical357_test_harness/fetch/actual_test.go @@ -0,0 +1,25 @@ +package main +import("context";"crypto/sha256";"encoding/hex";"net/http";"net/http/httptest";"os";"path/filepath";"testing") +func Test357PinnedDownload(t *testing.T){ + raw:=[]byte("synthetic downloadable fixture, never model weights");h:=sha256.Sum256(raw);sha:=hex.EncodeToString(h[:]);calls:=0 + server:=httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){calls++;w.Write(raw)}));defer server.Close() + dest:=filepath.Join(t.TempDir(),"weights.pt") + if e:=humanFetchPinned(context.Background(),server.URL,dest,sha,1000);e!=nil{t.Fatal(e)} + if e:=humanFetchPinned(context.Background(),server.URL,dest,sha,1000);e!=nil||calls!=1{t.Fatal("verified cache not reused",e,calls)} +} +func Test357BadHashNeverReplacesPreviousFile(t *testing.T){ + dest:=filepath.Join(t.TempDir(),"weights.pt");os.WriteFile(dest,[]byte("previous"),0600) + server:=httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){w.Write([]byte("bad"))}));defer server.Close() + if e:=humanFetchPinned(context.Background(),server.URL,dest,"wrong",1000);e==nil{t.Fatal("bad hash accepted")} + raw,_:=os.ReadFile(dest);if string(raw)!="previous"{t.Fatal("previous changed")};if _,e:=os.Stat(dest+".part");!os.IsNotExist(e){t.Fatal("bad partial left")} +} +func Test357OversizeAndHTTPFailureRejected(t *testing.T){ + for _,status:=range []int{200,500}{ + server:=httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request){w.WriteHeader(status);w.Write(make([]byte,32))})) + dest:=filepath.Join(t.TempDir(),"weights.pt");if e:=humanFetchPinned(context.Background(),server.URL,dest,"wrong",8);e==nil{t.Fatal("bad response accepted")};server.Close() + } +} +func Test357CancelledDownloadDoesNotCreateModel(t *testing.T){ + ctx,cancel:=context.WithCancel(context.Background());cancel();dest:=filepath.Join(t.TempDir(),"weights.pt") + if e:=humanFetchPinned(ctx,"http://127.0.0.1:1",dest,"wrong",1000);e==nil{t.Fatal("cancel ignored")};if _,e:=os.Stat(dest);!os.IsNotExist(e){t.Fatal("model created")} +} diff --git a/botanical_install357.py b/botanical_install357.py new file mode 100644 index 0000000..62c526d --- /dev/null +++ b/botanical_install357.py @@ -0,0 +1,54 @@ +"""App-owned runtime installer: inspect the resolver plan before any change. +Never uninstall or replace an installed distribution, including on resume. +""" +import importlib.metadata as metadata +import json +import os +import runpy +import sys +import tempfile + + +def validate_plan(report, installed): + for item in report.get("install", []): + name = item.get("metadata", {}).get("name", "").lower().replace("_", "-") + if not name: + raise RuntimeError("Package plan is missing a distribution identity") + if name in installed: + raise RuntimeError("Setup would replace an existing package: " + name + ". Nothing installed.") + + +def main(args): + installed = {d.metadata["Name"].lower().replace("_", "-"): d.version for d in metadata.distributions()} + fd, path = tempfile.mkstemp(suffix=".json") + os.close(fd) + try: + base = [sys.executable, "-m", "pip", "install", "--disable-pip-version-check", "--only-binary=:all:"] + def pip_run(options): + sys.argv = ["pip"] + options + try: + runpy.run_module("pip", run_name="__main__") + except SystemExit as e: + if e.code not in (0, None): + raise RuntimeError("pip failed: " + str(e.code)) + pip_run(base[3:] + ["--dry-run", "--report", path] + args) + with open(path, encoding="utf-8") as f: + report = json.load(f) + validate_plan(report, installed) + # Install the exact resolved wheel URLs, never a second dependency solve. + requirements = [] + for item in report.get("install", []): + info = item.get("download_info", {}) + url = info.get("url", "") + sha = info.get("archive_info", {}).get("hashes", {}).get("sha256", "") + if not url.startswith("https://") or len(sha) != 64: + raise RuntimeError("Resolved package has no HTTPS URL and SHA256") + requirements.append(url + "#sha256=" + sha) + if requirements: + pip_run(base[3:] + ["--no-deps"] + requirements) + finally: + os.remove(path) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/botanical_motion_ui_windows.go b/botanical_motion_ui_windows.go index 578d3ea..08fc5bb 100644 --- a/botanical_motion_ui_windows.go +++ b/botanical_motion_ui_windows.go @@ -76,14 +76,19 @@ func (a *app) botanicalSync() { } } func (a *app) botanicalCommand(id int) bool { - switch id { - case idBotanicalLoadLocal: + switch id { + case idBotanicalStop: + botanicalCancelSetup357() + botanicalInputStop() + return a.fxStdBarCommand(botanicalBar,a.botanicalHooks(),id) + case idBotanicalLoadLocal: a.botanicalLoadLocal() return true case idBotanicalInput: - a.botanicalInputStart() + a.botanicalOnePress357() return true case idBotanicalInputStop: + botanicalCancelSetup357() botanicalInputStop() return true } @@ -107,12 +112,12 @@ func (a *app) botanicalLayout(add func(widget) int, rx, rw, y, bh, pad int) { label(botanicalSelected().Desc, 44) add(widget{kind: kBtn, id: idBotanicalLoadLocal, text: "Load trusted local YOLO segmentation weights (.pt)", l: rx + sc(16), t: y, r: rx + rw - sc(16), b: y + bh, enabled: !botanicalModelLoading.Load() && !botanicalArmed.Load()}) y += bh + pad - add(widget{kind: kBtn, id: idBotanicalInput, text: "Start already-running local silhouette input", l: rx + sc(16), t: y, r: rx + rw - sc(16), b: y + bh, enabled: !botanicalRunning.Load()}) + add(widget{kind: kBtn, id: idBotanicalInput, text: "Start Botanical (set up missing free pieces)", l: rx + sc(16), t: y, r: rx + rw - sc(16), b: y + bh, enabled: !botanicalRunning.Load() && !botanicalModelLoading.Load()}) y += bh + pad - add(widget{kind: kBtn, id: idBotanicalInputStop, text: "Stop silhouette input / clear body artwork", l: rx + sc(16), t: y, r: rx + rw - sc(16), b: y + bh, enabled: botanicalArmed.Load()}) + add(widget{kind: kBtn, id: idBotanicalInputStop, text: "Stop silhouette input / clear body artwork", l: rx + sc(16), t: y, r: rx + rw - sc(16), b: y + bh, enabled: botanicalArmed.Load() || botanicalModelLoading.Load()}) y += bh + pad label(botanicalStatus(), 78) - label("Start the installed person detector on Detect first. Load a trusted local segmentation .pt here, then open the camera and Start input. No model downloads or cloud API. Box-only or >650 ms-old input stays black. Depth shading is optional and uses only the existing validated saved-depth sampler; missing depth is flat.", 100) + label("Start sets up missing free local components, verifies segmentation weights, opens the selected camera and previews this effect. Existing Detect packages are not replaced. First setup may download CPU PyTorch and takes several minutes. Ultralytics uses AGPL-3.0. No cloud/photo upload or paid API. Box-only or >650ms-old input stays black; missing depth is flat.", 120) a.fxStdBarLayout(add, botanicalBar, fxStdBarOpts{Enabled: func(id int) bool { if id == idBotanicalStop { if a.pl == nil || a.pl.R == nil { diff --git a/botanical_setup357_windows.go b/botanical_setup357_windows.go new file mode 100644 index 0000000..14beb08 --- /dev/null +++ b/botanical_setup357_windows.go @@ -0,0 +1,326 @@ +//go:build windows + +package main + +import ( + "bytes" + "context" + _ "embed" + "encoding/json" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "sync" + "sync/atomic" + "time" +) + +//go:embed botanical_install357.py +var botanicalInstaller357 string + +const botanicalSegURL357 = "https://github.com/ultralytics/assets/releases/download/v8.3.0/yolo11n-seg.pt" +const botanicalSegSHA357 = "55ed65c56c91713d23e8402371c6c49a6fd84f257f7dce452e8d70e41dcbe152" + +var botanicalSetupURL357 = pgURL +var botanicalSetupGen357 atomic.Uint64 +var botanicalSetupMu357 sync.Mutex +var botanicalSetupCancel357 context.CancelFunc + +func botanicalCancelSetup357() { + botanicalSetupGen357.Add(1) + botanicalSetupMu357.Lock() + if botanicalSetupCancel357 != nil { + botanicalSetupCancel357() + } + botanicalSetupMu357.Unlock() +} +func botanicalRun357(ctx context.Context, py string, args ...string) error { + cmd := exec.CommandContext(ctx, py, args...) + cmd.Env = modelStorageEnv(os.Environ()) + hideWin(cmd) + raw, e := cmd.CombinedOutput() + if e != nil { + return fmt.Errorf("local setup failed: %v: %s", e, cut(string(raw), 1400)) + } + return nil +} +func botanicalPreparePython357(ctx context.Context, dir string) (string, error) { + // Existing working segmentation runtime is read-only. Never pip into it. + for _, py := range pgVenvCandidates() { + if ctx.Err() != nil { + return "", ctx.Err() + } + if _, e := os.Stat(py); e == nil { + probe, stop := context.WithTimeout(ctx, 20*time.Second) + e = botanicalRun357(probe, py, "-c", "import ultralytics, torch, PIL, numpy") + stop() + if e == nil { + return py, nil + } + } + } + runtime := filepath.Join(dir, "runtime") + py := filepath.Join(runtime, "python.exe") + ready := filepath.Join(dir, "runtime.ready") + if _, e := os.Stat(ready); e == nil { + if e = botanicalRun357(ctx, py, "-c", "import ultralytics, torch, PIL, numpy"); e != nil { + return "", fmt.Errorf("existing Botanical runtime failed its import check; no packages replaced: %w", e) + } + return py, nil + } + // Resume only this dedicated, not-yet-ready Botanical installation. + botanicalPublishEmptyStatus("Preparing free private Botanical Python. Existing Detect packages are not changed.") + if e := os.MkdirAll(dir, 0700); e != nil { + return "", e + } + for _, v := range []struct { + url, path, sha string + max int64 + }{{humanPythonURL, filepath.Join(dir, "python.zip"), humanPythonSHA, 16 << 20}, {humanPipURL, filepath.Join(dir, "pip.whl"), humanPipSHA, 4 << 20}} { + if e := humanFetchPinned(ctx, v.url, v.path, v.sha, v.max); e != nil { + return "", e + } + } + if _, e := os.Stat(py); os.IsNotExist(e) { + if e = humanExtractZip(filepath.Join(dir, "python.zip"), runtime); e != nil { + return "", e + } + } + if _, e := os.Stat(filepath.Join(runtime, "Lib", "site-packages", "pip", "__main__.py")); os.IsNotExist(e) { + if e = humanExtractZip(filepath.Join(dir, "pip.whl"), filepath.Join(runtime, "Lib", "site-packages")); e != nil { + return "", e + } + } + if e := os.WriteFile(filepath.Join(runtime, "python313._pth"), []byte("python313.zip\n.\nLib/site-packages\nimport site\n"), 0600); e != nil { + return "", e + } + installer := filepath.Join(dir, "install-no-replace.py") + if e := writeFileAtomic(installer, []byte(botanicalInstaller357)); e != nil { + return "", e + } + botanicalPublishEmptyStatus("Downloading free Botanical CPU runtime and dependencies into its own folder. Existing Detect/CUDA packages are untouched. This can take several minutes.") + if e := botanicalRun357(ctx, py, installer, "--index-url", "https://download.pytorch.org/whl/cpu", "torch==2.11.0+cpu", "torchvision==0.26.0+cpu"); e != nil { + return "", e + } + if e := botanicalRun357(ctx, py, installer, "ultralytics==8.4.174"); e != nil { + return "", e + } + if e := botanicalRun357(ctx, py, "-c", "import ultralytics, torch, PIL, numpy"); e != nil { + return "", e + } + if e := writeFileAtomic(ready, []byte("Botanical private runtime357\n")); e != nil { + return "", e + } + return py, nil +} +func botanicalLoadPath357(ctx context.Context, path string) error { + body, _ := json.Marshal(map[string]string{"path": path}) + req, e := http.NewRequestWithContext(ctx, "POST", botanicalSetupURL357+"/load-seg-local", bytes.NewReader(body)) + if e != nil { + return e + } + req.Header.Set("Content-Type", "application/json") + res, e := (&http.Client{Timeout: 90 * time.Second}).Do(req) + if e != nil { + return e + } + defer res.Body.Close() + raw, e := io.ReadAll(io.LimitReader(res.Body, 16384)) + if e != nil { + return e + } + var got struct { + OK bool `json:"ok"` + Error string `json:"error"` + } + if json.Unmarshal(raw, &got) != nil || res.StatusCode != 200 || !got.OK { + return fmt.Errorf("segmentation load not confirmed: %s", got.Error) + } + return nil +} +func (a *app) botanicalOnePress357() { + if botanicalArmed.Load() || botanicalRunning.Load() || !botanicalModelLoading.CompareAndSwap(false, true) { + return + } + if a.pl == nil || a.pl.R == nil { + botanicalModelLoading.Store(false) + botanicalPublishEmptyStatus("Open a mapped project first.") + return + } + if !a.ensureModelStorage() { + botanicalModelLoading.Store(false) + return + } + if free := freeDiskGB(fsamAIDir()); free < 0 || free < 2 { + botanicalModelLoading.Store(false) + botanicalPublishEmptyStatus("Botanical setup needs at least 2GB verified free space on the selected AI drive. No downloads started.") + return + } + gen := botanicalSetupGen357.Add(1) + renderer := a.pl.R + camera := camActiveID() + epoch := calibrationStopEpoch.Load() + ticket := cameraCommandWanted.Load() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Minute) + botanicalSetupMu357.Lock() + botanicalSetupCancel357 = cancel + botanicalSetupMu357.Unlock() + botanicalPublishEmptyStatus("Starting Botanical setup. Free local components only. Stop input cancels pending setup.") + go func() { + defer cancel() + releasedLoading := false + defer func() { + if !releasedLoading { + botanicalModelLoading.Store(false) + } + }() + fail := func(e error) { + if botanicalSetupGen357.Load() == gen { + botanicalPublishEmptyStatus("Botanical did not start: " + e.Error() + ". Nothing is projected from missing or stale masks. Press Start to retry.") + } + } + dir := filepath.Join(fsamAIDir(), "botanical-local") + if e := os.MkdirAll(dir, 0700); e != nil { + fail(e) + return + } + py, e := botanicalPreparePython357(ctx, dir) + if e != nil { + fail(e) + return + } + botanicalPublishEmptyStatus("Checking/downloading official free segmentation weights (about 6MB). Hash verified before local load.") + weights := filepath.Join(dir, "yolo11n-seg.pt") + if e = humanFetchPinned(ctx, botanicalSegURL357, weights, botanicalSegSHA357, 8<<20); e != nil { + fail(e) + return + } + pg.mu.Lock() + warm := pg.warm + running := pg.proc != nil + pg.mu.Unlock() + if !warm { + if running { + fail(fmt.Errorf("person detector is still starting or stopping; wait for its cleanup")) + return + } + script := filepath.Join(dir, "detect_person.py") + if e = writeFileAtomic(script, []byte(pgScript)); e != nil { + fail(e) + return + } + cmd := modelStorageCommand(py, "-u", script) + cmd.Dir = dir + cmd.Env = append(modelStorageEnv(os.Environ()), "PG_MODEL="+weights, "PG_SEG_MODEL="+weights, "YOLO_AUTOINSTALL=false") + hideWin(cmd) + pg.mu.Lock() + if pg.proc != nil { + pg.mu.Unlock() + fail(fmt.Errorf("another detector started during setup")) + return + } + e = cmd.Start() + if e == nil { + pg.proc = cmd + } + pg.mu.Unlock() + if e != nil { + fail(e) + return + } + deadline := time.Now().Add(30 * time.Second) + for !pgPing() { + if ctx.Err() != nil || time.Now().After(deadline) { + pg.mu.Lock() + if pg.proc == cmd { + cmd.Process.Kill() + cmd.Wait() + pg.proc = nil + pg.warm = false + } + pg.mu.Unlock() + fail(fmt.Errorf("detector startup timed out or was cancelled")) + return + } + time.Sleep(250 * time.Millisecond) + } + pg.mu.Lock() + pg.warm = true + pg.up = true + pg.mu.Unlock() + go func() { + cmd.Wait() + pg.mu.Lock() + if pg.proc == cmd { + pg.proc = nil + pg.warm = false + pg.up = false + } + pg.mu.Unlock() + }() + } + botanicalPublishEmptyStatus("Loading verified local segmentation weights; preparing real silhouette input.") + if e = botanicalLoadPath357(ctx, weights); e != nil { + fail(e) + return + } + if ctx.Err() != nil || botanicalSetupGen357.Load() != gen { + return + } + // Setup must not supersede a camera workflow the user started later. + if cameraCommandWanted.Load() != ticket { + return + } + a.cameraCommandContextIfCurrent(ctx, ticket, func() { + if ctx.Err() != nil || botanicalSetupGen357.Load() != gen || a.pl == nil || a.pl.R != renderer || camActiveID() != camera || calibrationStopEpoch.Load() != epoch { + return + } + if !camJobStartWait("Botanical camera start", 5*time.Second) { + return + } + if ctx.Err() != nil || cameraCommandSuperseded() || botanicalSetupGen357.Load() != gen { + camJobEnd() + return + } + session, opened, e := startCameraLease() + camJobEnd() + if e != nil { + fail(e) + return + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + camMu.Lock() + fresh := camOwner == session && !camTime.IsZero() && time.Since(camTime) < 650*time.Millisecond + camMu.Unlock() + if fresh { + break + } + if ctx.Err() != nil { + break + } + time.Sleep(50 * time.Millisecond) + } + accepted := false + a.studioOnUI(func() { + if ctx.Err() != nil || cameraCommandSuperseded() || botanicalSetupGen357.Load() != gen || a.pl == nil || a.pl.R != renderer || camActiveID() != camera || calibrationStopEpoch.Load() != epoch { + return + } + // Internal start is allowed only after this worker's model load completed. + releasedLoading = true + botanicalModelLoading.Store(false) + a.botanicalInputStart() + if botanicalArmed.Load() { + a.fxStdBarCommand(botanicalBar, a.botanicalHooks(), idBotanicalTest) + accepted = true + } + }) + if !accepted && opened { + stopCameraOwned(session) + } + }) + }() +} diff --git a/botanical_setup357_windows_test.go b/botanical_setup357_windows_test.go new file mode 100644 index 0000000..34a12c0 --- /dev/null +++ b/botanical_setup357_windows_test.go @@ -0,0 +1,74 @@ +//go:build windows + +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func Test357ActualLocalModelLoadReceipt(t *testing.T) { + old := botanicalSetupURL357 + defer func() { botanicalSetupURL357 = old }() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/load-seg-local" || r.Method != "POST" { + t.Error("wrong local load route") + } + var body map[string]string + if json.NewDecoder(r.Body).Decode(&body) != nil || body["path"] != "C:/trusted/model.pt" { + t.Error("wrong path transport") + } + w.Write([]byte(`{"ok":true}`)) + })) + defer server.Close() + botanicalSetupURL357 = server.URL + if e := botanicalLoadPath357(context.Background(), "C:/trusted/model.pt"); e != nil { + t.Fatal(e) + } +} +func Test357ActualLoadRejectsFailureAndMalformedReceipt(t *testing.T) { + old := botanicalSetupURL357 + defer func() { botanicalSetupURL357 = old }() + for _, body := range []string{`{"ok":false,"error":"test failure"}`, `not json`, `{}`} { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(body)) })) + botanicalSetupURL357 = server.URL + if e := botanicalLoadPath357(context.Background(), "C:/trusted/model.pt"); e == nil { + t.Fatal("unconfirmed load accepted", body) + } + server.Close() + } +} +func Test357ActualLoadCancellation(t *testing.T) { + old := botanicalSetupURL357 + defer func() { botanicalSetupURL357 = old }() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + case <-time.After(150 * time.Millisecond): + } + })) + defer server.Close() + botanicalSetupURL357 = server.URL + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) + defer cancel() + if e := botanicalLoadPath357(ctx, "C:/trusted/model.pt"); e == nil { + t.Fatal("cancelled load accepted") + } +} +func Test357StopInvalidatesPendingSetup(t *testing.T) { + before := botanicalSetupGen357.Load() + ctx, cancel := context.WithCancel(context.Background()) + botanicalSetupMu357.Lock() + prior := botanicalSetupCancel357 + botanicalSetupCancel357 = cancel + botanicalSetupMu357.Unlock() + defer func() { botanicalSetupMu357.Lock(); botanicalSetupCancel357 = prior; botanicalSetupMu357.Unlock() }() + botanicalCancelSetup357() + if botanicalSetupGen357.Load() == before || ctx.Err() == nil { + t.Fatal("Stop did not revoke pending setup") + } +} diff --git a/camcommand_windows.go b/camcommand_windows.go index 4c0488a..f013f41 100644 --- a/camcommand_windows.go +++ b/camcommand_windows.go @@ -18,12 +18,15 @@ func cameraCommandSuperseded() bool { return a != 0 && a != cameraCommandWanted.Load() } func (a *app) cameraCommand(run func()) { a.cameraCommandContext(context.Background(), run) } -func (a *app) cameraCommandContext(ctx context.Context, run func()) { - if ctx.Err() != nil { +func (a *app) cameraCommandContext(ctx context.Context, run func()) { a.cameraCommandContextExpected(ctx,nil,run) } +func (a *app) cameraCommandContextIfCurrent(ctx context.Context,expected uint64,run func()){a.cameraCommandContextExpected(ctx,&expected,run)} +func (a *app) cameraCommandContextExpected(ctx context.Context,expected *uint64,run func()) { + if ctx.Err() != nil { return } - calibrationMutationMu.Lock() - ticket := cameraCommandWanted.Add(1) + calibrationMutationMu.Lock() + if expected!=nil&&cameraCommandWanted.Load()!=*expected{calibrationMutationMu.Unlock();return} + ticket := cameraCommandWanted.Add(1) calibrationMutationMu.Unlock() deadline := time.Now().Add(30 * time.Second) noted := false @@ -71,6 +74,7 @@ func (a *app) queueCameraCommand(run func()) { }() } func (a *app) stopAllCalibrations() { + botanicalCancelSetup357() dualCancel() calibrationMutationMu.Lock() calibrationStopEpoch.Add(1) diff --git a/common.go b/common.go index c40fb10..cd4b479 100644 --- a/common.go +++ b/common.go @@ -11,7 +11,7 @@ import ( "time" ) -const version = "0.98.356-experimental1" +const version = "0.98.357-experimental1" const appDisplayName = "Projection Mapper - Built by Instinct" diff --git a/test_botanical_install357.py b/test_botanical_install357.py new file mode 100644 index 0000000..cc2a53a --- /dev/null +++ b/test_botanical_install357.py @@ -0,0 +1,22 @@ +import importlib.util +import pathlib +import unittest + +spec = importlib.util.spec_from_file_location("botanical_installer", pathlib.Path(__file__).with_name("botanical_install357.py")) +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) + +class InstallerPolicy(unittest.TestCase): + def test_new_only(self): + installer.validate_plan({"install": [{"metadata": {"name": "new-module"}}]}, {"torch": "existing"}) + def test_existing_normalized_name_rejected(self): + with self.assertRaises(RuntimeError): + installer.validate_plan({"install": [{"metadata": {"name": "Torch_Vision"}}]}, {"torch-vision": "existing"}) + def test_unknown_identity_rejected(self): + with self.assertRaises(RuntimeError): + installer.validate_plan({"install": [{}]}, {}) + def test_empty_resume_plan(self): + installer.validate_plan({"install": []}, {"torch": "existing"}) + +if __name__ == "__main__": + unittest.main() diff --git a/test_botanical_offline357.py b/test_botanical_offline357.py new file mode 100644 index 0000000..c2f7e21 --- /dev/null +++ b/test_botanical_offline357.py @@ -0,0 +1,79 @@ +import ast +import os +import pathlib +import socket +import subprocess +import sys +import tempfile +import types +import unittest + +source = pathlib.Path(__file__).with_name("detect_person.py") +tree = ast.parse(source.read_text()) +# Execute the exact production definitions, excluding only its server entrypoint. +assert isinstance(tree.body[-1], ast.Expr) +assert ast.unparse(tree.body[-1]).startswith("HTTPServer(") +tree.body.pop() +m = types.ModuleType("detector") +exec(compile(tree, str(source), "exec"), m.__dict__) + +class OfflineGuards(unittest.TestCase): + def setUp(self): + self.old = sys.modules.get("ultralytics") + self.connect, self.popen = socket.socket.connect, subprocess.Popen + self.prior = m.seg_model + self.tmp = tempfile.TemporaryDirectory() + self.path = os.path.join(self.tmp.name, "model.pt") + pathlib.Path(self.path).write_bytes(b"test fixture, never a real model") + def tearDown(self): + self.tmp.cleanup() + m.seg_model = self.prior + if self.old is None: + sys.modules.pop("ultralytics", None) + else: + sys.modules["ultralytics"] = self.old + self.assertIs(socket.socket.connect, self.connect) + self.assertIs(subprocess.Popen, self.popen) + def set_constructor(self, constructor): + sys.modules["ultralytics"] = types.SimpleNamespace(YOLO=constructor) + def test_local_load_and_restoration(self): + candidate = types.SimpleNamespace(task="segment") + self.set_constructor(lambda path, task: candidate) + self.assertTrue(m.load_seg_local(self.path)["ok"]) + self.assertIs(m.seg_model, candidate) + def test_load_network_denied_keeps_previous(self): + old = object() + m.seg_model = old + def constructor(*a, **kw): + with socket.socket() as s: + s.connect(("127.0.0.1", 1)) + self.set_constructor(constructor) + self.assertIn("error", m.load_seg_local(self.path)) + self.assertIs(m.seg_model, old) + def test_installer_denied(self): + self.set_constructor(lambda *a, **kw: subprocess.Popen(["never-execute"])) + self.assertIn("error", m.load_seg_local(self.path)) + def test_nonsegment_keeps_previous(self): + old = object() + m.seg_model = old + self.set_constructor(lambda *a, **kw: types.SimpleNamespace(task="detect")) + self.assertIn("error", m.load_seg_local(self.path)) + self.assertIs(m.seg_model, old) + def test_named_url_missing_path_rejected_before_constructor(self): + self.set_constructor(lambda *a, **kw: self.fail("constructor reached")) + for path in ("yolo11n-seg.pt", "https://invalid/model.pt", self.path + "missing"): + self.assertIn("error", m.load_seg_local(path)) + def test_frame_missing_model_never_constructs(self): + m.seg_model = None + self.set_constructor(lambda *a, **kw: self.fail("constructor reached")) + self.assertIn("error", m.segment_ready(None)) + def test_frame_inference_network_denied(self): + class FakeModel: + def predict(self, *a, **kw): + with socket.socket() as s: + s.connect(("127.0.0.1", 1)) + m.seg_model = FakeModel() + self.assertIn("error", m.segment_ready(None)) + +if __name__ == "__main__": + unittest.main()