Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(teamhub): bind Humans' new My pages one at a time before Wiki refresh
LeoXing6e74b85dac4b
diff --git a/apps/teamhub/internal/document/README.md b/apps/teamhub/internal/document/README.mdindex a11badff..7386532a 100644--- a/apps/teamhub/internal/document/README.md+++ b/apps/teamhub/internal/document/README.md@@ -57,7 +57,10 @@ needs neither.Every refresh request of a Human, from Memory or the Web, is admitted in a `REPEATABLE READ` transaction that startsonly after it holds that Human's admission lock, so it sees the previous admission and joins or replays it. Admissionsof different Humans neither wait for nor abort each other, so Memory's nightly requests for every Human can run at-once; a settlement or dispatch status change of the same Wiki is a write conflict, and the admission retries.+once; a settlement or dispatch status change of the same Wiki is a write conflict, and the admission retries. Before+admission, every request except a meeting refresh binds the Human's new My pages as Wiki sources. That binding stays `SERIALIZABLE`, so+the bindings of all Humans run one at a time under one database-wide lock, taken before each binding transaction+starts, and each retries a serialization failure.## History pointsdiff --git a/apps/teamhub/internal/document/bindings.go b/apps/teamhub/internal/document/bindings.goindex ee9cfc2b..d705e3ba 100644--- a/apps/teamhub/internal/document/bindings.go+++ b/apps/teamhub/internal/document/bindings.go@@ -318,7 +318,7 @@ func compactUniqueStrings(values []string) []string {}func (s *Service) BindToWorkItem(ctx context.Context, input BindDocumentToWorkItemInput) (BindDocumentResult, error) {- return s.bindToContext(ctx, bindingCommandInput{+ return s.bindToContext(ctx, s.pool, bindingCommandInput{accountID: input.AccountID, documentID: input.DocumentID, contextID: input.WorkItemID,idempotencyKey: input.IdempotencyKey, kind: "task", operation: "document.bind.task",})@@ -327,7 +327,15 @@ func (s *Service) BindToWorkItem(ctx context.Context, input BindDocumentToWorkIt// BindToPersonalWiki adds a Document to the caller's Wiki sources; binding a// bound source changes nothing.func (s *Service) BindToPersonalWiki(ctx context.Context, input BindDocumentToPersonalWikiInput) (BindDocumentResult, error) {- return s.bindToContext(ctx, bindingCommandInput{+ return s.bindToPersonalWiki(ctx, s.pool, input)+}++func (s *Service) bindToPersonalWiki(+ ctx context.Context,+ starter transactionStarter,+ input BindDocumentToPersonalWikiInput,+) (BindDocumentResult, error) {+ return s.bindToContext(ctx, starter, bindingCommandInput{accountID: input.AccountID, documentID: input.DocumentID, tenantID: input.TenantID,kind: "wiki_source", operation: "document.bind.wiki",})@@ -339,7 +347,13 @@ type bindingCommandInput struct {accountID, documentID, contextID, tenantID, idempotencyKey, kind, operation string}-func (s *Service) bindToContext(ctx context.Context, input bindingCommandInput) (BindDocumentResult, error) {+// transactionStarter opens a binding's transaction: the pool, or a session+// that already holds a lock the binding must run under.+type transactionStarter interface {+ BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)+}++func (s *Service) bindToContext(ctx context.Context, starter transactionStarter, input bindingCommandInput) (BindDocumentResult, error) {if input.accountID == "" || input.documentID == "" ||len(input.idempotencyKey) > 128 || input.operation == "" ||(input.kind != "task" && input.kind != "wiki_source") ||@@ -348,7 +362,7 @@ func (s *Service) bindToContext(ctx context.Context, input bindingCommandInput)return BindDocumentResult{}, ErrInvalidInput}requestHash := bindingRequestHash(input)- tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})+ tx, err := starter.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.Serializable})if err != nil {return BindDocumentResult{}, err}diff --git a/apps/teamhub/internal/document/wiki_refresh_admission.go b/apps/teamhub/internal/document/wiki_refresh_admission.goindex 486e0402..387a1aba 100644--- a/apps/teamhub/internal/document/wiki_refresh_admission.go+++ b/apps/teamhub/internal/document/wiki_refresh_admission.go@@ -5,6 +5,7 @@ import ("time""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool""github.com/simplexai-labs/linger/apps/teamhub/internal/store")@@ -22,6 +23,25 @@ import (// conflicts that retry on a fresh snapshot.func (s *Service) admitWikiRefresh(ctx context.Context, tenantID, accountID string, admit func(pgx.Tx) error) error {key := "wiki-refresh-admission|" + tenantID + "|" + accountID+ return s.withAdvisorySessionLock(ctx, key, func(connection *pgxpool.Conn) error {+ return retryWikiTransaction(ctx, func() error {+ tx, err := connection.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})+ if err != nil {+ return err+ }+ defer func() { _ = tx.Rollback(ctx) }()+ if err := admit(tx); err != nil {+ return err+ }+ return tx.Commit(ctx)+ })+ })+}++// withAdvisorySessionLock runs work while a pooled session holds the advisory+// lock key. Work may open its transactions on that session, so they start only+// after the lock is held.+func (s *Service) withAdvisorySessionLock(ctx context.Context, key string, work func(*pgxpool.Conn) error) error {connection, err := s.pool.Acquire(ctx)if err != nil {return err@@ -41,15 +61,5 @@ func (s *Service) admitWikiRefresh(ctx context.Context, tenantID, accountID stri}connection.Release()}()- return retryWikiTransaction(ctx, func() error {- tx, err := connection.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})- if err != nil {- return err- }- defer func() { _ = tx.Rollback(ctx) }()- if err := admit(tx); err != nil {- return err- }- return tx.Commit(ctx)- })+ return work(connection)}diff --git a/apps/teamhub/internal/document/wiki_sources.go b/apps/teamhub/internal/document/wiki_sources.goindex 9f74ff06..c7a4eab3 100644--- a/apps/teamhub/internal/document/wiki_sources.go+++ b/apps/teamhub/internal/document/wiki_sources.go@@ -6,6 +6,7 @@ import ("time""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool")// Upload runs its native import inline, so a pending import normally@@ -120,17 +121,35 @@ func (s *Service) bindWikiSources(ctx context.Context, input RequestWikiRefreshI"importing_count", len(importing), "importing_document_ids", importing,"textless_count", len(textless), "textless_document_ids", textless)}+ var unbound []stringfor _, value := range sources {- if value.bound {- continue- }- if _, err := s.BindToPersonalWiki(ctx, BindDocumentToPersonalWikiInput{- AccountID: input.AccountID, TenantID: input.TenantID, DocumentID: value.id,- }); err != nil {- return false, err+ if !value.bound {+ unbound = append(unbound, value.id)}}- return true, nil+ if len(unbound) == 0 {+ return true, nil+ }+ // Memory refreshes every Human's Wiki at once. Binding runs SERIALIZABLE,+ // and bindings of different Humans share index pages, so concurrent ones+ // abort each other although they touch different rows. One lock for the+ // whole database, taken before each binding transaction starts, keeps+ // them from overlapping; a binding takes milliseconds and only new pages+ // need one. The bindings run on the locked session, so a request needs one+ // pooled connection however many wait for the lock.+ return true, s.withAdvisorySessionLock(ctx, "wiki-source-binding", func(connection *pgxpool.Conn) error {+ for _, documentID := range unbound {+ if err := retryWikiTransaction(ctx, func() error {+ _, err := s.bindToPersonalWiki(ctx, connection, BindDocumentToPersonalWikiInput{+ AccountID: input.AccountID, TenantID: input.TenantID, DocumentID: documentID,+ })+ return err+ }); err != nil {+ return err+ }+ }+ return nil+ })}// lockWikiSourceHeads holds the bound source Documents and their texts whilediff --git a/apps/teamhub/tests/integration/wiki_refresh_admission_concurrency_test.go b/apps/teamhub/tests/integration/wiki_refresh_admission_concurrency_test.goindex 3d32b61c..dcb56cb3 100644--- a/apps/teamhub/tests/integration/wiki_refresh_admission_concurrency_test.go+++ b/apps/teamhub/tests/integration/wiki_refresh_admission_concurrency_test.go@@ -9,6 +9,7 @@ import ("sync""sync/atomic""testing"+ "time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn"@@ -25,7 +26,7 @@ import (func TestWikiRefreshAdmissionsOfDifferentHumansDoNotConflict(t *testing.T) {allowParallelIntegrationTest(t)const humans = 12- service, _, tracer := newWikiRefreshAdmissionFixture(t, humans)+ service, _, tracer := newWikiRefreshAdmissionFixture(t, humans, humans+4)results := make([]document.MemoryWikiRefreshResult, humans)errs := make([]error, humans)runWikiAdmissionsTogether(humans, func(index int) {@@ -43,10 +44,56 @@ func TestWikiRefreshAdmissionsOfDifferentHumansDoNotConflict(t *testing.T) {}}+func TestWikiSourceBindingsOfDifferentHumansDoNotConflict(t *testing.T) {+ allowParallelIntegrationTest(t)+ const humans = 12+ // Fewer pooled connections than requests: a request waiting for the+ // binding lock must not hold the connection the lock holder binds on.+ service, pool, tracer := newWikiRefreshAdmissionFixture(t, humans, 8)+ // Each Human has a Wiki and two new My pages that the refresh binds first.+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO personal_wikis(id,tenant_id,owner_actor_id)+ SELECT 'wiki_admission_'||i,'tenant_document_a','actor_admission_human_'||i+ FROM generate_series(0,$1::int-1) i;+ INSERT INTO documents(+ id,tenant_id,title,format,owner_actor_id,owner_actor_kind,creator_actor_id,creator_actor_kind,status+ ) SELECT 'document_admission_'||i||'_'||page,'tenant_document_a','Page','blocknote',+ 'actor_admission_human_'||i,'human','actor_admission_human_'||i,'human','active'+ FROM generate_series(0,$1::int-1) i,generate_series(1,2) page;+ INSERT INTO document_placements(id,tenant_id,document_id,scope_kind,owner_human_actor_id,node_kind,sort_key)+ SELECT 'placement_admission_'||i||'_'||page,'tenant_document_a','document_admission_'||i||'_'||page,+ 'personal','actor_admission_human_'||i,'document','document_admission_'||i||'_'||page+ FROM generate_series(0,$1::int-1) i,generate_series(1,2) page`,+ pgx.QueryExecModeSimpleProtocol, humans); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)+ defer cancel()+ errs := make([]error, humans)+ runWikiAdmissionsTogether(humans, func(index int) {+ _, errs[index] = service.RequestMemoryWikiRefresh(ctx, document.RequestMemoryWikiRefreshInput{+ TenantID: "tenant_document_a", OwnerActorID: wikiAdmissionHuman(index), Date: "2026-11-16",+ })+ })+ for index, err := range errs {+ if err != nil {+ t.Fatalf("Human %d refresh: %v", index, err)+ }+ }+ var bound int+ if err := pool.QueryRow(t.Context(), `SELECT count(*) FROM document_context_bindings+ WHERE binding_kind='wiki_source' AND status='active' AND document_id LIKE 'document_admission_%'`).Scan(&bound); err != nil || bound != humans*2 {+ t.Fatalf("bound My pages=%d err=%v, want %d", bound, err, humans*2)+ }+ if failures := tracer.failures.Load(); failures != 0 {+ t.Fatalf("bindings of different Humans aborted each other %d times", failures)+ }+}+func TestConcurrentWikiRefreshRequestsOfOneHumanAdmitOneRefresh(t *testing.T) {allowParallelIntegrationTest(t)const requests = 8- service, pool, tracer := newWikiRefreshAdmissionFixture(t, 1)+ service, pool, tracer := newWikiRefreshAdmissionFixture(t, 1, 5)// The Web request refreshes an existing Wiki; Memory creates one only for// a Human's first refresh.if _, err := pool.Exec(t.Context(), `INSERT INTO personal_wikis(id,tenant_id,owner_actor_id)@@ -102,9 +149,9 @@ func (tracer *serializationFailureTracer) TraceQueryEnd(_ context.Context, _ *pg}// newWikiRefreshAdmissionFixture seeds Humans that each have an Another Me-// and one indexed Room Session, and returns a Document service whose pool-// counts serialization failures.-func newWikiRefreshAdmissionFixture(t *testing.T, humans int) (*document.Service, *pgxpool.Pool, *serializationFailureTracer) {+// and one indexed Room Session, and returns a Document service whose pool of+// maxConns connections counts serialization failures.+func newWikiRefreshAdmissionFixture(t *testing.T, humans int, maxConns int32) (*document.Service, *pgxpool.Pool, *serializationFailureTracer) {t.Helper()ctx := t.Context()_, pool := newUnifiedDocumentActionsFixture(t)@@ -148,7 +195,7 @@ func newWikiRefreshAdmissionFixture(t *testing.T, humans int) (*document.Serviceconfig := pool.Config()tracer := &serializationFailureTracer{}config.ConnConfig.Tracer = tracer- config.MaxConns = int32(humans + 4)+ config.MaxConns = maxConnstraced, err := pgxpool.NewWithConfig(ctx, config)if err != nil {t.Fatal(err)