Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/writing-a-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ A living page (a deprecations page, a feed: a `notices` source) only shows its l

### The `apisurface` kind: reading a package's API without running it

`plugins/apisurface` downloads a release's wheel (or sdist) through `env.Get`, opens it in memory (`archive/zip`, `archive/tar`: nothing is written to disk) and hands the `.py` and `.pyi` files to `plugins/apisurface/pysurface`, which reads them as text: logical lines, indentation, and the headers of `def`, `class`, `__all__` and `from … import`. Nothing in the package is imported, compiled or run. That's the safest way to read code someone else publishes, and it needs no dependency: a Python interpreter (the `ast` module) would mean running a second runtime next to the plugins, and the pure-Go Python parsers available follow old grammars and pull in a large module for what is a few hundred lines here. The cost is that only signatures are read, never what a body does, and anything the reader can't be sure of is left out (see `providers/openai-python-sdk.md`). Archive and file sizes are capped (`MaxFileBytes`, `MaxSourceBytes`), so a crafted release can't exhaust the runner.
`plugins/apisurface` downloads a release's wheel (or sdist) through `env.Get`, opens it in memory (`archive/zip`, `archive/tar`: nothing is written to disk) and hands the `.py` and `.pyi` files to `plugins/apisurface/pysurface`, which reads them as text: logical lines, indentation, and the headers of `def`, `class`, `__all__` and `from … import`. Nothing in the package is imported, compiled or run. That's the safest way to read code someone else publishes, and it needs no dependency: a Python interpreter (the `ast` module) would mean running a second runtime next to the plugins, and the pure-Go Python parsers available follow old grammars and pull in a large module for what is a few hundred lines here. The cost is that only signatures are read, never what a body does, and anything the reader can't be sure of is left out (see `providers/openai-python-surface.md`). Archive and file sizes are capped (`MaxFileBytes`, `MaxSourceBytes`), so a crafted release can't exhaust the runner.

An event cites the newer release's file, and its excerpt quotes the definition's path and line in both releases. npm packages (`.d.ts` files) are next.

Expand Down
12 changes: 8 additions & 4 deletions internal/pluginlist/pluginlist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pluginlist

import (
"encoding/json"
"slices"
"strings"
"testing"

Expand Down Expand Up @@ -42,8 +43,9 @@ func TestBuildListsEveryRegisteredSource(t *testing.T) {
}
}

// One provider, several sources: Algolia's three APIs.
func TestAlgoliaIsOneProviderWithThreeSources(t *testing.T) {
// One provider, several sources: Algolia's three APIs (and its other
// sources), merged across kinds into one provider.
func TestAlgoliaIsOneProviderWithItsSources(t *testing.T) {
b, err := Marshal(Build("v1.2.3"))
if err != nil {
t.Fatal(err)
Expand All @@ -63,8 +65,10 @@ func TestAlgoliaIsOneProviderWithThreeSources(t *testing.T) {
t.Errorf("%s: page %s isn't at the release", s.ID, s.Page)
}
}
if got := strings.Join(ids, " "); got != "algolia/ingestion-api algolia/recommend-api algolia/search-api" {
t.Errorf("algolia's sources: %s", got)
for _, want := range []string{"algolia/ingestion-api", "algolia/recommend-api", "algolia/search-api"} {
if !slices.Contains(ids, want) {
t.Errorf("algolia's sources %v lack %s", ids, want)
}
}
return
}
Expand Down
59 changes: 29 additions & 30 deletions plugins/apisurface/apisurface.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@
// both releases. npm (.d.ts) is a follow-up.
//
// What isn't read, on purpose (precision over recall): private names (a
// leading underscore, a private module, a name left out of __all__),
// classes nested in classes, overloaded functions' parameters, a removed
// leading underscore, a module under a private one or one named internal
// or vendor, a name left out of __all__), classes nested in classes,
// overloaded functions' and properties' parameters, self and cls, a removed
// parameter when the function now takes **kwargs (passing it still works),
// and a parameter newly added without a default (patch-it's change-event
// contract has no subject for it yet: logged).
// a name its module still binds (an alias, an import, a star import or a
// module __getattr__ that can't be listed), and a parameter newly added
// without a default (patch-it's change-event contract has no subject for it
// yet: logged).
package apisurface

import (
Expand All @@ -33,30 +36,14 @@ import (
"github.com/patch-it-dev/patch-it-plugins/plugins/apisurface/pysurface"
)

func init() {
plugin.RegisterProvider(plugin.Provider{
ID: "openai", Name: "OpenAI", Category: plugin.CategoryAI, Homepage: "https://openai.com",
Sources: []plugin.Source{{
ID: "python-sdk", Layer: plugin.LayerSDK, Page: "providers/openai-python-sdk.md",
Watches: "Classes, functions, methods and parameters removed or renamed in the public API of the openai Python package, release by release, read from each release's wheel",
URLs: []string{"https://pypi.org/project/openai/", "https://github.com/openai/openai-python"},
Packages: []string{"pypi:openai"},
Plugin: Plugin{Package: OpenAIPython},
}},
})
}

// Package is one published package.
type Package struct {
ID string // the source id the events carry: "openai/python-sdk"
ID string // the source id the events carry: "openai/python-surface"
Name string // on the registry: "openai"
Ecosystem string // "pypi"
Module string // the top-level import name: "openai"
}

// OpenAIPython is the openai package on PyPI.
var OpenAIPython = Package{ID: "openai/python-sdk", Name: "openai", Ecosystem: "pypi", Module: "openai"}

// Plugin reads one package's releases.
type Plugin struct {
Package Package
Expand All @@ -77,10 +64,11 @@ func (p Plugin) ListVersions(ctx context.Context, env plugin.Env) ([]plugin.Vers
// Release is what ReadAt keeps of a release: its public surface, the
// classes a method could move to, and what couldn't be read.
type Release struct {
Artifact string `json:"artifact"`
Surface pysurface.Surface `json:"surface"`
Classes pysurface.Classes `json:"classes,omitempty"`
Skipped []string `json:"skipped,omitempty"` // files over the size limit
Artifact string `json:"artifact"`
Surface pysurface.Surface `json:"surface"`
Classes pysurface.Classes `json:"classes,omitempty"`
Bindings pysurface.Bindings `json:"bindings,omitempty"` // what each public module binds
Skipped []string `json:"skipped,omitempty"` // files over the size limit
}

// ReadAt downloads the release's wheel (or sdist) and reads its public
Expand All @@ -106,7 +94,7 @@ func (p Plugin) ReadAt(ctx context.Context, env plugin.Env, v plugin.Version) (p
for _, s := range skipped {
log.Printf("%s %s: %s skipped: over %d bytes", pkg.Name, v.ID, s, MaxFileBytes)
}
content, err := json.Marshal(Release{Artifact: a.Filename, Surface: pysurface.Read(files), Classes: pysurface.ReadClasses(files), Skipped: skipped})
content, err := json.Marshal(Release{Artifact: a.Filename, Surface: pysurface.Read(files), Classes: pysurface.ReadClasses(files), Bindings: pysurface.ReadBindings(files), Skipped: skipped})
if err != nil {
return plugin.Snapshot{}, err
}
Expand Down Expand Up @@ -230,7 +218,9 @@ type Change struct {
// them besides self or cls; anything less sure is a removal.
//
// What looks removed but may not be is a note, not an event: a symbol
// defined in a file b couldn't read (over the size limit), and a method
// defined in a file b couldn't read (over the size limit), a name its
// module still binds in b (an alias, an import, a star import from where
// names can't be listed), and a method
// whose class is still there but whose bases changed, which one of its
// bases (or theirs) now defines, or which the class now defines as an
// attribute (create = _create, a property made a plain attribute).
Expand Down Expand Up @@ -288,9 +278,9 @@ func Compare(ra, rb Release) []Change {
}
before, after := old, now
kwargs := slices.ContainsFunc(now.Params, func(p pysurface.Param) bool { return p.Kind == "kwargs" })
for _, op := range old.Params {
if op.Kind == "args" || op.Kind == "kwargs" {
continue
for i, op := range old.Params {
if op.Kind == "args" || op.Kind == "kwargs" || (i == 0 && (op.Name == "self" || op.Name == "cls")) {
continue // a caller never passes self or cls
}
i := slices.IndexFunc(now.Params, func(p pysurface.Param) bool { return p.Name == op.Name })
switch {
Expand Down Expand Up @@ -332,6 +322,15 @@ func notGone(k string, before pysurface.Symbol, a, b Release) string {
if slices.Contains(b.Skipped, before.File) {
return fmt.Sprintf("%s, where it was defined, was too big to read", before.File)
}
if mod, ok := b.Bindings[parentOf(k)]; ok {
name := k[strings.LastIndexByte(k, '.')+1:]
switch {
case slices.Contains(mod.Names, name):
return fmt.Sprintf("%s still binds the name (an alias, an import or a value now)", parentOf(k))
case mod.Star:
return fmt.Sprintf("%s star-imports names that can't be listed", parentOf(k))
}
}
if before.Kind != "method" {
return ""
}
Expand Down
46 changes: 45 additions & 1 deletion plugins/apisurface/apisurface_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func pair(t *testing.T) []event.Event {
// same class.)
func TestGolden(t *testing.T) {
got := pair(t)
kittest.Golden(t, "testdata/golden/openai-1.1.2.json", got)
kittest.Golden(t, "testdata/golden/openai-python-surface.json", got)
for _, e := range got {
if e.PreviousVersion != "1.1.1" || e.Version != "1.1.2" || e.SourceURL != wheel112 || !strings.Contains(e.SourceExcerpt, "openai/types/beta/asssitant_deleted.py line ") {
t.Errorf("%v: %s<-%s, excerpt %q", e.Subject.Symbols, e.Version, e.PreviousVersion, e.SourceExcerpt)
Expand Down Expand Up @@ -255,3 +255,47 @@ func TestSourceFilesStayInThePackage(t *testing.T) {
}

var _ plugin.Versioned = Plugin{}

// A class or function gone from a module's surface while the module still
// binds the name is still importable: the class made an alias of another
// (anthropic 2.5.0: DeadlineExceededError = GatewayTimeoutError), names
// re-exported from a private module (google-genai 3.4.0's interactions),
// or a module that star-imports from where names can't be listed. A note,
// not an event. A name the module no longer binds at all is gone.
func TestANameTheModuleStillBindsIsNotRemoved(t *testing.T) {
read := func(files map[string]string) Release {
var fs []pysurface.File
for p, text := range files {
fs = append(fs, pysurface.File{Path: p, Text: text})
}
return Release{Surface: pysurface.Read(fs), Classes: pysurface.ReadClasses(fs), Bindings: pysurface.ReadBindings(fs)}
}
a := read(map[string]string{
"acme/__init__.py": "from ._exceptions import DeadlineExceededError, Gone\n",
"acme/_exceptions.py": "class DeadlineExceededError(Exception): pass\nclass Gone(Exception): pass\n",
"acme/interactions.py": "class Webhook:\n def __init__(self, url): pass\n",
"acme/starred.py": "class Agent:\n def __init__(self, name): pass\n",
})
b := read(map[string]string{
"acme/__init__.py": "from ._exceptions import DeadlineExceededError\n",
"acme/_exceptions.py": "class GatewayTimeoutError(Exception): pass\nDeadlineExceededError = GatewayTimeoutError\n",
"acme/interactions.py": "from ._gen.webhooks import Webhook\n",
"acme/starred.py": "from ._gen.agents import *\n",
})
want := "note acme.DeadlineExceededError\nremoved_symbol acme.Gone \nnote acme.interactions.Webhook\nnote acme.starred.Agent"
if got := strings.Join(changes(a, b), "\n"); got != want {
t.Errorf("got\n%s\nwant\n%s", got, want)
}
}

// A method made a staticmethod loses self, which no caller passes:
// supabase 1.0.0's SupabaseRealtimeClient.get_payload_records. Not a removed
// parameter. (cls likewise, for a classmethod made static.)
func TestSelfGoneIsNoRemovedParameter(t *testing.T) {
self := prm("self", "either", "")
a := Release{Surface: pysurface.Surface{"acme.C": cls("class C:"), "acme.C.records": sym("method", self, prm("payload", "either", ""))}}
b := Release{Surface: pysurface.Surface{"acme.C": cls("class C:"), "acme.C.records": sym("method", prm("payload", "either", ""))}}
if got := changes(a, b); len(got) != 0 {
t.Errorf("got %v, want nothing", got)
}
}
58 changes: 58 additions & 0 deletions plugins/apisurface/pypi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package apisurface

import (
"strings"

"github.com/patch-it-dev/patch-it-plugins/core/plugin"
)

// The PyPI packages whose public API this kind reads, one source each,
// registered with their provider. A package's Module is the top-level
// directory its wheel installs (checked by hand on each package's newest
// wheel, 2026-11-21).
var (
OpenAIPython = Package{ID: "openai/python-surface", Name: "openai", Ecosystem: "pypi", Module: "openai"}
AnthropicPython = Package{ID: "anthropic/python-surface", Name: "anthropic", Ecosystem: "pypi", Module: "anthropic"}
StripePython = Package{ID: "stripe/python-surface", Name: "stripe", Ecosystem: "pypi", Module: "stripe"}
GoogleGenAI = Package{ID: "google/genai-python-surface", Name: "google-genai", Ecosystem: "pypi", Module: "google"}
SentryPython = Package{ID: "sentry/python-surface", Name: "sentry-sdk", Ecosystem: "pypi", Module: "sentry_sdk"}
PyMongo = Package{ID: "mongodb/pymongo-surface", Name: "pymongo", Ecosystem: "pypi", Module: "pymongo"}
RedisPy = Package{ID: "redis/redis-py-surface", Name: "redis", Ecosystem: "pypi", Module: "redis"}
NumPy = Package{ID: "numpy/python-surface", Name: "numpy", Ecosystem: "pypi", Module: "numpy"}
SupabasePython = Package{ID: "supabase/python-surface", Name: "supabase", Ecosystem: "pypi", Module: "supabase"}
AlgoliaPython = Package{ID: "algolia/python-surface", Name: "algoliasearch", Ecosystem: "pypi", Module: "algoliasearch"}
ElasticPython = Package{ID: "elastic/python-surface", Name: "elasticsearch", Ecosystem: "pypi", Module: "elasticsearch"}
DDTrace = Package{ID: "datadog/ddtrace-python-surface", Name: "ddtrace", Ecosystem: "pypi", Module: "ddtrace"}
CloudflarePython = Package{ID: "cloudflare/python-surface", Name: "cloudflare", Ecosystem: "pypi", Module: "cloudflare"}
Textual = Package{ID: "textual/python-surface", Name: "textual", Ecosystem: "pypi", Module: "textual"}
URLLib3 = Package{ID: "urllib3/python-surface", Name: "urllib3", Ecosystem: "pypi", Module: "urllib3"}
)

func init() {
pypi := func(p plugin.Provider, pkg Package, layer plugin.Layer, repo string) {
_, src, _ := strings.Cut(pkg.ID, "/")
p.Sources = []plugin.Source{{
ID: src, Layer: layer, Page: "providers/" + p.ID + "-" + src + ".md",
Watches: "Classes, functions, methods and parameters removed or renamed in the public API of the " + pkg.Name + " Python package, release by release, read from each release's wheel",
URLs: []string{"https://pypi.org/project/" + pkg.Name + "/", repo},
Packages: []string{"pypi:" + pkg.Name},
Plugin: Plugin{Package: pkg},
}}
plugin.RegisterProvider(p)
}
pypi(plugin.Provider{ID: "openai", Name: "OpenAI", Category: plugin.CategoryAI, Homepage: "https://openai.com"}, OpenAIPython, plugin.LayerSDK, "https://github.com/openai/openai-python")
pypi(plugin.Provider{ID: "anthropic", Name: "Anthropic", Category: plugin.CategoryAI, Homepage: "https://www.anthropic.com"}, AnthropicPython, plugin.LayerSDK, "https://github.com/anthropics/anthropic-sdk-python")
pypi(plugin.Provider{ID: "stripe", Name: "Stripe", Category: plugin.CategoryPayments, Homepage: "https://stripe.com"}, StripePython, plugin.LayerSDK, "https://github.com/stripe/stripe-python")
pypi(plugin.Provider{ID: "google", Name: "Google", Category: plugin.CategoryAI, Homepage: "https://cloud.google.com"}, GoogleGenAI, plugin.LayerSDK, "https://github.com/googleapis/python-genai")
pypi(plugin.Provider{ID: "sentry", Name: "Sentry", Category: plugin.CategoryMonitoring, Homepage: "https://sentry.io"}, SentryPython, plugin.LayerSDK, "https://github.com/getsentry/sentry-python")
pypi(plugin.Provider{ID: "mongodb", Name: "MongoDB", Category: plugin.CategoryDatabases, Homepage: "https://www.mongodb.com"}, PyMongo, plugin.LayerSDK, "https://github.com/mongodb/mongo-python-driver")
pypi(plugin.Provider{ID: "redis", Name: "Redis", Category: plugin.CategoryDatabases, Homepage: "https://redis.io"}, RedisPy, plugin.LayerSDK, "https://github.com/redis/redis-py")
pypi(plugin.Provider{ID: "numpy", Name: "NumPy", Category: plugin.CategoryPackages, Homepage: "https://numpy.org"}, NumPy, plugin.LayerPackage, "https://github.com/numpy/numpy")
pypi(plugin.Provider{ID: "supabase", Name: "Supabase", Category: plugin.CategoryDatabases, Homepage: "https://supabase.com"}, SupabasePython, plugin.LayerSDK, "https://github.com/supabase/supabase-py")
pypi(plugin.Provider{ID: "algolia", Name: "Algolia", Category: plugin.CategorySearch, Homepage: "https://www.algolia.com"}, AlgoliaPython, plugin.LayerSDK, "https://github.com/algolia/algoliasearch-client-python")
pypi(plugin.Provider{ID: "elastic", Name: "Elastic", Category: plugin.CategorySearch, Homepage: "https://www.elastic.co"}, ElasticPython, plugin.LayerSDK, "https://github.com/elastic/elasticsearch-py")
pypi(plugin.Provider{ID: "datadog", Name: "Datadog", Category: plugin.CategoryMonitoring, Homepage: "https://www.datadoghq.com"}, DDTrace, plugin.LayerSDK, "https://github.com/DataDog/dd-trace-py")
pypi(plugin.Provider{ID: "cloudflare", Name: "Cloudflare", Category: plugin.CategoryInfrastructure, Homepage: "https://www.cloudflare.com"}, CloudflarePython, plugin.LayerSDK, "https://github.com/cloudflare/cloudflare-python")
pypi(plugin.Provider{ID: "textual", Name: "Textual", Category: plugin.CategoryPackages, Homepage: "https://textual.textualize.io"}, Textual, plugin.LayerPackage, "https://github.com/Textualize/textual")
pypi(plugin.Provider{ID: "urllib3", Name: "urllib3", Category: plugin.CategoryPackages, Homepage: "https://urllib3.readthedocs.io"}, URLLib3, plugin.LayerPackage, "https://github.com/urllib3/urllib3")
}
Loading
Loading