Better Company

I’ve been using company mode, which is a great completion framework for years now, and in genreal, it’s phenomenal. For a while, however, I’ve had the feeling that I’m not getting completion options at exactly the right frequency that I’d like. And a completion framework that’s a bit sluggish or that won’t offer completions that you’d expect is a drag. I dug in a bit, and got a much better, because of some poor configuration choices I’d made, and I thought I write up my configuration.

Backend Configuration

Company allows for configurable backends, which are just functions that provide completions, many of which are provided in the main company package, but also provided by many third (fourth?) party packages. These backends, then, are in a list which is stored in the company-backends, that company uses to try and find completions. When you get to a moment when you might want to complete things, emacs+company iterate through this list and build a list of expansions. This is pretty straight forward, at least in principle.

Now company is pretty good at making these backends fast, or trying, particularly when the backend might be irrelevant to whatever you’re currently editing--except in some special cases--but it means that the order of things in the list matters sometimes. The convention for configuring company backends is to load the module that provides the backend and then push the new backend onto the list. This mostly works fine, but there are some backends that either aren’t very fast or have the effect of blocking backends that come later (because they’re theoretically applicable to all modes.) These backends to be careful of are: company-yasnippet, company-ispell, and company-dabbrev.

I’ve never really gotten company-ispell to work (you have to configure a wordlist,) and I’ve never been a dabbrev user, but I’ve definitely made the mistake to putting the snippet expansion near the front of the list rather than the end. I’ve been tweaking things recently, and have settled on the following value for company-backends: :

(setq company-backends '(company-capf
             company-keywords
             company-semantic
             company-files
             company-etags
             company-elisp
             company-clang
             company-irony-c-headers
             company-irony
             company-jedi
             company-cmake
             company-ispell
             company-yasnippet))

The main caveat is that everything has to be loaded or have autoloads registered appropriately, particularly for things like jedi (python,) clang, and irony. The “capf” backend is the integration with emacs' default completion-at-point facility, and is the main mechanism by which lap-mode interacts with company, so it’s good to keep that at the top.

Make it Fast

I think there’s some fear that a completion framework like company could impact the perceived responsiveness of emacs as a whole, and as a result there are a couple of knobs for how to tweak things. Having said that, I’ve always run things more aggressively, because I like seeing possible completions fast, and I’ve never seen any real impact on apparent performance or battery utilization. use these settings: :

(setq company-tooltip-limit 20)
(setq company-show-numbers t)
(setq company-idle-delay 0)
(setq company-echo-delay 0)

Configure Prompts

To be honest, I mostly like the default popup, but it’s nice to be able to look at more completions and spill over to helm when needed. It’s a sometimes thing, but it’s quite nice: :

(use-package helm-company
   :ensure t
   :after (helm company)
   :bind (("C-c C-;" . helm-company))
   :commands (helm-company)
   :init
   (define-key company-mode-map (kbd "C-;") 'helm-company)
   (define-key company-active-map (kbd "C-;") 'helm-company))

Full Configuration

Some of the following is duplicated above, but here’s the full configuration that I run with: :

(use-package company
  :ensure t
  :delight
  :bind (("C-c ." . company-complete)
         ("C-c C-." . company-complete)
         ("C-c s s" . company-yasnippet)
         :map company-active-map
         ("C-n" . company-select-next)
     ("C-p" . company-select-previous)
     ("C-d" . company-show-doc-buffer)
     ("M-." . company-show-location))
  :init
  (add-hook 'c-mode-common-hook 'company-mode)
  (add-hook 'sgml-mode-hook 'company-mode)
  (add-hook 'emacs-lisp-mode-hook 'company-mode)
  (add-hook 'text-mode-hook 'company-mode)
  (add-hook 'lisp-mode-hook 'company-mode)
  :config
  (eval-after-load 'c-mode
    '(define-key c-mode-map (kbd "[tab]") 'company-complete))

  (setq company-tooltip-limit 20)
  (setq company-show-numbers t)
  (setq company-dabbrev-downcase nil)
  (setq company-idle-delay 0)
  (setq company-echo-delay 0)
  (setq company-ispell-dictionary (f-join tychoish-config-path "aspell-pws"))

  (setq company-backends '(company-capf
               company-keywords
               company-semantic
               company-files
               company-etags
               company-elisp
               company-clang
               company-irony-c-headers
               company-irony
               company-jedi
               company-cmake
               company-ispell
               company-yasnippet))

  (global-company-mode))

(use-package company-quickhelp
  :after company
  :config
  (setq company-quickhelp-idle-delay 0.1)
  (company-quickhelp-mode 1))

(use-package company-irony
  :ensure t
  :after (company irony)
  :commands (company-irony)
  :config
  (add-hook 'irony-mode-hook 'company-irony-setup-begin-commands))

(use-package company-irony-c-headers
  :ensure t
  :commands (company-irony-c-headers)
  :after company-irony)

(use-package company-jedi
  :ensure t
  :commands (company-jedi)
  :after (company python-mode))

(use-package company-statistics
  :ensure t
  :after company
  :config
  (company-statistics-mode))

Distributed Systems Problems and Strategies

At a certain scale, most applications end up having to contend with a class of “distributed systems” problems: when a single computer or a single copy of an application can’t support the required throughput of an application there’s not much to do except to distribute it, and therein lies the problem. Taking one of a thing and making many of the thing operate similarly can be really fascinating, and frankly empowering. At some point, all systems become distributed in some way, to a greater or lesser extent. While the underlying problems and strategies are simple enough, distributed systems-type bugs can be gnarly and having some framework for thinking about these kinds of systems and architectures can be useful, or even essential, when writing any kind of software.

Concerns

Application State

Applications all have some kind of internal state: configuration, runtime settings, in addition to whatever happens in memory as a result of running the application. When you have more than one copy of a single logical application, you have to put state somewhere. That somewhere is usually a database, but it can be another service or in some kind of shared file resource (e.g. NFS or blob storage like S3.)

The challenge is not “where to put the state,” because it probably doesn’t matter much, but rather in organizing the application to remove the assumption that state can be stored in the application. This often means avoiding caching data in global variables and avoiding storing data locally on the filesystem, but there are a host of ways in which application state can get stuck or captured, and the fix is generally “ensure this data is always read out of some centralized and authoritative service,” and ensure that any locally cached data is refreshed regularly and saved centrally when needed.

In general, better state management within applications makes code better regardless of how distributed the system is, and when we use the “turn it off and turn it back on,” we’re really just clearing out some bit of application state that’s gotten stuck during the runtime of a piece of software.

Startup and Shutdown

Process creation and initialization, as well as shutdown, is difficult in distributed systems. While most configuration and state is probably stored in some remote service (like a database,) there’s a bootstrapping process where each process gets enough local configuration required to get that configuration and startup from the central service, which can be a bit delicate.

Shutdown has its own problems set of problems, as specific processes need to be able to complete or safely abort in progress operations.

For request driven work (i.e. HTTP or RPC APIs) without statefull or long-running requests (e.g. many websockets and most streaming connections), applications have to stop accepting new connections and let all in progress requests complete before terminating. For other kinds of work, the process has to either complete in progress work or provide some kind of “checkpointing” approach so that another process can pick up the work later.

Horizontal Scalability

Horizontal scalability, being able to increase the capability of an application by adding more instances of the application rather than creasing the resources allotted to the application itself, is one of the reasons that we build distributed systems in the first place,1 but simply being able to run multiple copies of the application at once isn’t always enough, the application needs to be able to effectively distribute it’s workloads. For request driven work this is genreally some kind of load balancing layer or strategy, and for other kinds of workloads you need some way to distribute work across the application.

There are lots of different ways to provide loadbalancing, and a lot depends on your application and clients, there is specialized software (and even hardware) that provides loadbalancing by sitting “in front of” the application and routing requests to a backend, but there are also a collection of client-side solutions that work quite well. The complexity of load balancing solutions varies a lot: there are some approaches that just distribute responses “evenly” (by number) to a single backend one-by-one (“round-robin”) and some approaches that attempt to distribute requests more “fairly” based on some reporting of each backend or an analysis of the incoming requests, and the strategy here depends a lot on the requirements of the application or service.

For workloads that aren’t request driven, systems require some mechanism of distributing work to workers, ususally with some kind of messaging system, though it’s possible to get pretty far using a just a normal general purpose database to store pending work. The options for managing, ordering, and distributing the work, is the meat of problem.

Challenges

When thinking about system design or architecture, I tend to start with the following questions.

  • how does the system handle intermittent failures of particular components?
  • what kind of downtime is acceptable for any given component? for the system as a whole?
  • how do operations timeout and get terminated, and how to clients handle these kinds of failures?
  • what are the tolerances for the application in terms of latency of various kinds of operations, and also the tolerances for “missing” or “duplicating” an operation?
  • when (any single) node or component of the system aborts or restarts abruptly, how does the application/service respond? Does work resume or abort safely?
  • what level of manual intervention is acceptable? Does the system need to node failure autonomously? If so how many nodes?

Concepts like “node” or “component” or “operation,” can mean different things in different systems, and I use the terms somewhat vaguely as a result. These general factors and questions apply to systems that have monolithic architectures (i.e. many copies of a single type of process which performs many functions,) and service-based architectures (i.e. many different processes performing specialized functions.)

Solutions

Ignore the Problem, For Now

Many applications run in a distributed fashion while only really addressing parts of their relevant distributed systems problems, and in practice it works out ok. Applications may store most of their data in a database, but have some configuration files that are stored locally: this is annoying, and sometimes an out-of-sync file can lead to some unexpected behavior. Applications may have distributed application servers for all request-driven workloads, but may still have a separate single process that does some kind of coordinated background work, or run cron jobs.

Ignoring the problem isn’t always the best solution in the long term, but making sure that everything is distributed (or able to be distributed,) isn’t always the best use of time, and depending the specific application it works out fine. The important part, isn’t always to distribute things in all cases, but to make it possible to distribute functions in response to needs: in some ways I think about this as the “just in time” approach.

Federation

Federated architectures manage distributed systems protocols at a higher level: rather than assembling a large distributed system, build very small systems that can communicate at a high level using some kind of established protocol. The best example of a federated system is probably email, though there are others.2

Federated systems have more complex protocols that have to be specification based, which can be complicated/difficult to build. Also, federated services have to maintain the ability to interoperate with previous versions and even sometimes non-compliant services, which can be difficult to maintain. Federated systems also end up pushing a lot of the user experience into the clients, which can make it hard to control this aspect of the system.

On the upside, specific implementations and instances of a federated service can be quite simple and have straight forward and lightweight implementations. Supporting email for a few users (or even a few hundred) is a much more tractable problem than supporting email for many millions of users.

Distributed Locks

Needing some kind of lock (for mutual exclusion or mutex) is common enough in programming, and provide some kind of easy way to ensure that only a single actor has access to a specific resource. Doing this within a single process involves using kernel (futexes) or programming language runtime implementations, and is simple to conceptualize, and while the concept in a distributed system is functionally the same, the implementation of distributed locks are more complicated and necessarily slower (both the lock themselves, and their impact on the system as a whole).

All locks, local or distributed can be difficult to use correctly: the lock must be acquired before using the resource, and it must fully protect the resource, without protecting too much and having a large portion of functionality require the lock. So while locks are required sometimes, and conceptually simple, using them correctly is hard. With that disclaimer, to work, distributed locks require:3

  • some concept of an owner, which must be sufficiently specific (hostname, process identifier,) but that should be sufficiently unique to protect against process restarts, host renaming and collision.
  • lock status (locked/link) and if the lock has different modes, such as a multi-reader/single-writer lock, then that status.
  • a timeout or similar mechanism to prevent deadlocks if the actor holding a lock halts or becomes inaccessible, the lock is eventually released.
  • versioning, to prevent stale actors from modifying the same lock. In the case that actor-1 has a lock and stalls for longer than the timeout period, such that actor-2 gains the lock, when actor-1 runs again it must know that its been usurped.

Not all distributed systems require distributed locks, and in most cases, transactions in the data layer, provide most of the isolation that you might need from a distributed lock, but it’s a useful concept to have.

Duplicate Work (Idempotency)

For a lot of operations, in big systems, duplicating some work is easier and ultimately faster than coordinating and isolating that work in a single location. For this, having idempotent operations4 is useful. Some kinds of operations and systems make idempotency easier to implement, and in cases where the work is not idempotent (e.g. as in data processing or transformation,) the operation can be, by attaching some kind of clock to the data or operation.5

Using clocks and idempotency makes it possible to maintain data consistency without locks. At the same time, some of the same considerations apply. Having all operations duplicated is difficult to scale so having ways for operations to abort early can be useful.

Consensus Protocols

Some operations can’t be effectively distributed, but are also not safe to duplicate. Applications can use consensus protocols to do “leader election,” to ensure that there’s only one node “in charge” at a time, and the protocol. This is common in database systems, where “single leader” systems are useful for balancing write performance in distributed context. Consensus protocols have some amount of overhead, and are good for systems of a small to moderate size, because all elements of the system must communicate with all other nodes in the system.

The two prevailing consensus protocols are Paxos and Raft--pardoning the oversimplification here--with Raft being a simpler and easier to implement imagination of the same underlying principles. I’ve characterized consensus as being about leader election, though you can use these protocols to allow a distributed system to reach agreement on any manner of operations or shared state.

Queues

Building a fully generalized distributed application with consensus is a very lofty proposition, and commonly beyond the scope of most applications. If you can characterize the work of your system as discrete units of work (tasks or jobs,) and can build or access a queue mechanism within your application that supports workers on multiple processes, this might be enough to support a great deal of your distributed requirements for the application.

Once you have reliable mechanisms and abstractions for distributing work to a queue, scaling the system can be managed outside of the application by using different backing systems, or changing the dispatching layer, and queue optimization is pretty well understood. There are lots of different ways to schedule and distribute queued work, but perhaps this is beyond the scope of this article.

I wrote one of these, amboy, but things like gearman and celery do this as well, and many of these tools are built on messaging systems like Kafka or AMPQ, or just use general purpose databases as a backend. Keeping a solid abstraction between the applications queue and then messaging system seems good, but a lot depends on your application’s workload.

Delegate to Upstream Services

While there are distributed system problems that applications must solve for themselves, in most cases no solution is required! In practice many applications centralize a lot of their concerns in trusted systems like databases, messaging systems, or lock servers. This is probably correct! While distributed systems are required in most senses, distributed systems themselves are rarely the core feature of an application, and it makes sense to delegate these problem to services that that are focused on solving this problem.

While multiple external services can increase the overall operational complexity of the application, implementing your own distributed system fundamentals can be quite expensive (in terms of developer time), and error prone, so it’s generally a reasonable trade off.

Conclusion

I hope this was as useful for you all as it has been fun for me to write!


  1. In most cases, some increase in reliability, by adding redundancy is a strong secondary motivation. ↩︎

  2. xmpp , the protocol behind jabber which powered/powers many IM systems is another federated example, and the fediverse points to others. I also suspect that some federation-like features will be used at the infrastructure layer to coordinate between constrained elements (e.g. multiple k8s clusters will use federation for coordination, and maybe multi-cloud/multi-region orchestration as well…) ↩︎

  3. This article about distributed locks in redis was helpful in summarizing the principles for me. ↩︎

  4. An operation is idempotent if it can be performed more than once without changing the outcome. For instance, the operation “increment the value by 10” is not idempotent because it increments a value every time it runs, so running the operation once is different than running it twice. At the same time the operation “set the value to 10” is idempotent, because the value is always 10 at the end of the operation. ↩︎

  5. Clocks can take the form of a “last modified timestamp,” or some kind of versioning integer associated with a record. Operations can check their local state against a canonical record, and abort if their data is out of date. ↩︎

Yarn Thoughts: HD Shetland

I’ve been knitting a sweater out of HD (Harrisville Designs) Shetland yarn for the past week or so and it’s been great, but there’s not a lot to look at because it’s just a plain sweater in black yarn, but I thought I’d write a bit about the experience.

I’ve knit a lot out of this yarn, mostly in stranded color work, and it’s probably the yarn that I have the most of in my possesion, but I’ve never really used it alone until recently, and hadn’t really knit anything with it in years. I’m a bit more than half way through a plain sweater in this yarn, and I find myself entranced.

It’s a simple 2-ply yarn, woolen spun, dyed before spinning, and it comes in hanks (which I’ve never used,) and on half pound cones. In color work, I tend to get 8 or 8.5 stitches to the inch (US 2.5/3mm), against a plain 7 stitches to the inch (US 0/2mm), and the fabric is light but solid. There are a bunch of colors, which is why I started using it for color work, including a number of heathers as well as natural colors. I would by a pound (2 cones) of each color to make a stranded sweater, but I always ended up with a lot of left overs. A plain sweater (for me) is under a pound, though I expect fewer left overs.

The name “Shetland” describes the weight, not the fiber contribution: the wool is a blend of unspecified breeds (probably some collection of Corriedale, another Merino cross, and/or Merino), but the effect is quite similar to actual Shetland Wool. While the wool is imported, the Mill is in New England, and the yarn is stocked by many yarn stores that supply weavers (though you can buy directly from the mill as well.) There’s something classic about the yarn: it smells like wool (probably the spinning oil, but still,) and the way that the fibers cling to each other makes it a jot to knit with.

HD Shetland isn’t exactly soft, but it isn’t rough either. I think part of this is about expectation management: because we know that this isn’t going to be yarn to wear against more sensitive skin (wrists, etc.), the fact that it’s actually pretty soft is a pleasant surprise. I also think that because the yarn is lofty and woolen spun the ends of the individual fibers end up less likely to be irritating or trigger reactions in the same way that smoother yarns can.

Conclusion: heartily recommend!

Epic Knitting

One of the things I’ve realized about myself is a knitter is that I really like epic projects, or sequences of projects.

Before my knitting hiatus, I bought a kilo of undyed sock yarn--because I liked the fiber content, and I wanted to explore knitting sweaters at finer gauges, because heavier weight yarns always made sweaters that felt too warm. Seemed like a good project. Due to a sizing error, I was only really able to get 2 sweaters out of the cone of yarn, but I think in the future three sweaters from a kilo seems useful. There’s something epic about this as a project, and I definitely intend to knit more sweaters in this vein. I was thinking about “epic knitting projects,” and came up with the following ideas:

  • 10 identical socks: After many years of having a somewhat hodgepodge and recently well worn collection of socks, this year, I purchased 14 pairs of new socks and it’s been great, both because nothing is teetering on the edge of being worn out, and I decided to buy 5 pairs of two different kinds of socks that I like a lot, plus 4 of a heavier weight, and I like that every day is a “good sock” day. I also like that having a bunch of identical socks socks makes it easier to wash and pair them up. I’ve never really knit more than one pair of socks that matched so it seems like a fun challenge.
  • Knit all of Elizabeth Zimmerman’s Yoke Sweater shaping variations. I think I’ve made about three of them, and none of these yoke sweaters have really ever entered more regular rotation. I think knitting them in lighter weights, and reducing the yoke depth a bit to fit more could help a lot.
  • Knit a collection of sweater’s inspired by classic Alice Starmore patterns, but modified for modern sensibilities in terms of fit and shaping. I’ve knit three patterns (Henry VIII, Norway, and Faroe) and would gladly knit them all again and I’d love to try the cabled sweaters as well. While the designs and stitch patterns of these sweaters are compelling the fit is not, which is probably a feature of these patterns being written in the late 80s and early 90s. I think the changes would be mostly to knit things at a finer gauge (Faroe, Norway, and the cabled sweaters,) but also to modify the shaping for better fits at the shoulder, and maybe modify neck shape for v-necks or open necklines.

I’ve also thought about knitting a bunch of lace, but I lack the floor space in my current apartment to actually block any kind of lace shawl reasonably.

Anyone else have Epic-scale knitting projects for this list?

Pandemic New Years

It seems obligatory to mark the new year, and what a year it was, for me and everyone else: pandemic, quarantine, changing jobs, new hobbies, totally different routines. The backdrop of the pandemic makes looking back (and forward!) so weird, and I find myself asking: will the things that changed in my life still be true when there’s less quarantine? did the things that happen in 2020 happen because of the pandemic or would they have happened anyway? The certainty that most (but not all!) of 2021 will, in practical terms, look a lot like 2020 is intense and makes this whole “obligatory new years” thing a bit harder. Instead of doing something like “resolutions”/“goals”--which are always fraught--or some kind of lofty synthetic review of the last year, I think I’d like to muse on features of 2020 that I hope and expect to continue in 2021

  • Knitting: I took a lot of time off of knitting, but I found that I’d been missing it, and I think there are ways that it fits well into my life quarantine or no. It’s also been quite fun to write about knitting and knitting projects, and become more engaged with other knitters, and I look forward to knitting things for friends and family. I have list in my head of some nifty ideas for sweaters and some other things to knit, so I expect this to stay.
  • Blogging: I’ve been writing blog posts for years and while I’ve always found it rewarding, but everything else related to blogging has been hard. During the summer, while I was interviewing for jobs, I wrote blog posts most days, and sort of fell down on posting them, and still have 25 (or so) in the draft folder. Writing is the easy part, it’s editing (or letting go!) promotion, and remembering to move things out of draft. I’ve spruced up the blog and done some work to automate regular publishing, and it seems like I might be able to make this work! I definitely want to.
  • Pickling: I’ve really enjoyed pickling things, and if anything I expect that I’ll enjoy doing this more after quarnainte when it’s easier to share these things. Right now I have some cranberries on the go, and a lot of sauerkraut in the fridge that I’m slowly eating. It’ll be fun to have more people to share it with! I’m excited to explore radishes as well as nappa cabbage.
  • Coffee: I started drinking coffee in 2014 and have mostly had coffee made by other people: tech jobs in NYC have pretty great office coffee, and the process was something of a mystery to me at the beginning. While I had a Chemex and made coffee for myself sometimes, it was definitely a special occasion sort of thing and not part of my regular routine. Now making a pot of coffee is part of my morning routine, and I find it pretty satisfying, and while I definitely look forward to drinking coffee that other people make more often in the future, I really like getting up making a pot of coffee and sitting down to write nearly every morning.

Sweater Backlog

While I’ve been working on this knitting book project, I’ve realized that I’ve developed something of a backlog of sweaters that I want to knit (for this project, and others,) and I thought I’d write them all down for our collective enjoyment.

  • A second version of the favorite sweater I knit during college: a plain sweater with a black body, gray at shoulders, drop shoulder, steeks, and gray sleeves. I want to do this out of fingering weight wool, probably HD Shetland. [in progress]
  • The same sweater as above, except with set in sleeves, and probably light blue as the contrasting color at the sleeve.
  • Sock yarn sweater, superwash, with v-neck, and some kind of textrued stitch pattern at the yoke that would be knitted without. I made one of these sweaters already, but it came out a touch smaller than I think I really want, and there are a collection of small modifications that I’d like to make, again for verification purposes.
  • A fully gray sweater, also out of HD Shetland, with the sleeves knit cuff-up, and with the yoke knit with “set-in sleeves,” in the round. I knit a sweater like this in the fall, and I want to verify that a basic a set of changes would make the sweater really wearable.
  • I have the first 3-5 inches of a color work cardigan that I started before my hiatus from knitting: I think there are a number of flaws with this sweater: the sizing is off, I didn’t handle the bottom hem correctly, and I don’t think I have enough yarn in these specific collors, but I think I’d like to attempt the pattern again.
  • A color work sweater with set in sleeves. Because knitting rows (back and forth) in stranded is annoying and a bit fussy, most patterns use drop shoulder shaping, but I’d like to experiment and see if I can perfect the technique a more fitted style for these sweaters.
  • Using a “garter rib” stitch for the full body of a sweater, both because I like the idea of a gentle rib pulling in to provide more fit, while also being fun and keeping a fairly simple shape over the entire length of the sweater.

I think that’s enough for now!

Towards Faster Emacs Start Times

While I mostly run emacs as a daemon managed by systemd I like to keep my configuration nimble enough that I can just start emacs and have an ad-hoc session for editing some files.1 Or that’s the goal. This has been a long running project for me, but early on in quarantine times, I’ve gotten things tightened up to the point that I feel comfortable using EDITOR=emacs just about all the time. On my (very old) computers, emacs starts and in well under 1 or 2 seconds, and does better on faster machines. If your emacs setup takes a long time to start up, this article is for you! Let’s see if we can get the program to start faster.

Measure!

The emacs-init-time function in emacs will tell you how long it took emacs to start up. This tends to be a bit under the actual start time, because some start-up activity gets pushed into various hooks, after startup. Just to keep an eye on things, I have a variant of the following as the first line in my config file: :

(add-to-list 'after-init-hook
      (lambda ()
        (message (concat "emacs (" (number-to-string (emacs-pid)) ") started in " (emacs-init-time)))))

It’s also possible to put additional information in this hook (and in reality I use something that pushes to a desktop notification tool, rather than just to message/logging.

You can also lower this number by putting more work into the after-init hook, but that sort of defeats the purpose: if you get the init time down to a second, but have 10 seconds of init-hook runtime, then that’s probably not much of a win, particularly if the init-hook tasks are blocking.

The second thing to do is have a macro2 available for use that allows to measure the runtime of a block of code, something like: :

(defmacro with-timer (name &rest body)
  `(let ((time (current-time)))
 ,@body
 (message "%s: %.06f" ,name (float-time (time-since time)))))

You can then do something like: :

(with-timer "mode-line-setup"
  (set-up-mode-line))

And then look in the *Message* buffer to see how long various things take so you know where focus your efforts.

Strategies

  • use-package makes it possible to do much less during applciation startup, and makes it possible to load big lisp packages only when you’re going to use them, and registers everything so you never feel the difference. Audit your use-package forms and ensure that they all declare one of the following forms, which insures that things are loaded upon use, rather than at start time:
    • :bind registers specific keybindings, but as autoloads so that the pacakge is only loaded when you use the keybinding.
    • :command registers function names as autoloads, like keybinding, so the commands/functions are available but again the package isn’t loaded until it’s used.
    • :mode attaches the package to a specific file extension or extensions so again, the package doesn’t get loaded until you open a file of that type.
    • :after for loading a package after another package it depends on or is only used after.
    • :hook this allows you to associate something from this package into another package’s hook, with the same effect of deferring loading of one package until after another is used.
  • Avoid having the default-scratch buffer trigger loading as much as possible. It’s very tempting to have *scratch* default to org-mode or something, but if you keep it in fundamental-mode you can avoid loading most of your packages until you actually use them, or can avoid pulling in too much too quickly.
  • Keep an eye on startup both for GUI, terminal, and if you use daemons, daemon instances of emacs. There are some subtleties that may be useful or important. It’s also the case that terminal startup times are often much less than GUI times.
  • Think about strategies for managing state-management (e.g. recentf session-mode and desktop-mode.) I’ve definitley had times when I really wanted emacs to be able to restart and leave me exactly where I was when I shut down. These session features are good, but often it’s just crufty, and causes a lot of expense at start up time. I still use desktop and session, but less so.
  • Fancy themes and modelines come at some cost. I recently was able to save a lot of start up time by omiting a call to spaceline-compile in my configuration. Theme setup also can take a bit of time in GUI mode (I think!), but I dropped automatic theme configuration so that my instances would play better with terminal mode.3

Helpful Settings

I think of these four settings as the “start up behavior” settings from my config: :

(setq inhibit-startup-echo-area-message "tychoish")
(setq inhibit-startup-message 't)
(setq initial-major-mode 'fundamental-mode)
(setq initial-scratch-message 'nil)

I’ve had the following jit settings in my config for a long time, and they tend to make things more peppy, which can only help during startup. This may also just be cargo-cult, stuff: :

(setq jit-lock-stealth-time nil)
(setq jit-lock-defer-time nil)
(setq jit-lock-defer-time 0.05)
(setq jit-lock-stealth-load 200)

If you use desktop-mode to save state and re-open buffers, excluding some modes from this behavior is good. In my case, avoiding reopening (and rereading) potentially large org-mode buffers was helpful for me. The desktop-modes-not-to-save value is useful here, as in the following snippet from my configuration: :

(add-to-list 'desktop-modes-not-to-save 'dired-mode)
(add-to-list 'desktop-modes-not-to-save 'Info-mode)
(add-to-list 'desktop-modes-not-to-save 'org-mode)
(add-to-list 'desktop-modes-not-to-save 'info-lookup-mode)
(add-to-list 'desktop-modes-not-to-save 'fundamental-mode)

Notes


  1. Ok, ok, I live with a vim user and the “quick startup time,” situation is very appealing. ↩︎

  2. I tweaked this based on what I found this on stack overflow which stole it from this listserv post↩︎

  3. Mixed GUI/Terminal mode with themes can be kind of finicky because theme settings are global and color backgrounds often won’t play well with terminal frames. You can say “if this is a gui mode,” but that doesn’t play well with daemons, and hooking into frame-creation has never worked as seamlessly as I would expect, because the of the execution context the hook functions (and slowing down frame creation can defeat part of the delight of the daemon.) ↩︎

New Project: Gestalt Knitting

A couple of months ago I started writing a thing that I think will be a book, or something close, about knitting. A few weeks ago, I jokingly called it “Gestalt Knitting,” and the name stuck, at least for myself for now. The idea is to write a book, that’s mostly about knitting, that’s less a collection of patterns, and more of a meditation on the process of designing and knitting some sweaters, hats, and socks.

As a knitter, I’ve never really followed patterns: even when I see a design that I like, I always end up changing it somehow: changing the process to be something that I’d enjoy more (e.g. knitting in the round,) or modifying the size a bit (I’ve always been slim and I know I like to avoid wearing things that feel like tents,) or adding features that I know increase the comfort (e.g. making the neckline more open, or the sleeves a touch wider.) Patterns, thus, for me are sort of an opening volley in a conversation about a project rather than a description of a project, and I think in practice this is pretty common, though I think that often, knitters think about their modification as minor and inconsequential when really they’re super cool and important.

I’m less interested in any specific design or pattern, and more interested in these kinds of basic patterns that we can reach to when faced with a pile of yarn and a desire to knit a sweater (or socks, etc.). Sort of the knitting equivalent of a family recipe that you can make without looking at any instructions and maybe without really measuring the ingredients. After a while, I suspect many knitters have a few things that they can just make on their own--like a hat or some simple socks--and one of my goals of this project is to help expand the collection of “house patterns” by explaining and exploring some of the basic garments that I tend to knit.

As a writer, I have a lot of practice writing about the details of complicated ideas and processes in unambiguous and clear terms. I’m interested in seeing if I can take my style for writing about procedures and concepts can translate to another subject area. Knitting patterns are, by convention, super concise and linear in a way that gives people just enough information to reproduce a specific garment, but ends up leaving out so much useful information about why you would knit something in a specific way, options for modification, or interactions between the pattern, the shape, and the process of knitting. When I’m knitting I get a lot of delight from the way all of details of a project come together, and I want to frame and present knitting projects in ways that really highlight that aspect of knitting. I also want to write something that’s knitters would find engaging to read all on its own, even without overlapping any of my specific knitting projects.

While I’ve made a lot of progress on the draft, I still have a bunch of work to do on this project: both in terms of more writing and also knitting “research.” I suspect I’ll write a bit about it here. Stay tuned!


I made a new instagram account, because that seems to be a thing, for knitting specific things: @gestaltknitting

Knitting Hiatus and Knitting Again

While I knit a lot in college, and for a few years afterwords, my attention to knitting as a hobby kind of trailed off, and I have basically not knit at all in the last five years, but suddenly a bit before Thanksgiving, I found myself listening to an audio book and playing a silly game on my phone really wishing that I could knit, and given that it was 2020 I did, and it’s been a lot of fun and pretty satisfying to get back into knitting.

There were lots of reasons for the hiatus, but the leading reasons were:

  • My professional work, first technical writing for software engineers, and then software engineering itself, was actually quite similar to knitting at least conceptually: knitting and software require lots of problem solving and similar kinds of iterative math. Particularly for the first few years where I was teaching myself how to program, I felt like knitting ended up being more like work than I wanted.
  • I lived in southern Wisconsin in college, and it was actually cold. Between climate change, and ending up living in New York City--being a huge city that holds heat, and being on a island with the harbor as a heat sink, most buildings in the City have very aggressive heating systems--it felt like I never really wanted to wear wool, because I was often too warm.

These problems seem solveable: my learning curve as a programmer has become less steep, and my day-to-day engineering work tends has shifted to be higher level and organizational in some ways that feel less like knitting. I think the “always too warm” feeling about my city has changed a bit as I’ve acclimated and I think it will be possible to just knit very light weight things and combine them with light weight jackets for increased wearability.

So I’m back.

I’ve finished the sweater I started in 2015 (it’s not exceptional, but I know how to fix it for the future,) knit another sweater that I’m pretty pleased with, and I’ve started a third and I’ve been working on a book about knitting that I’m quite excited about. I never kept a really extensive collection of yarn, but I have enough to keep me busy for a while, and using the yarn I already have has been interesting as a constraining function in planning new projects.

I suspect I’ll be blogging about knitting a bit more over the next little bit, about both specific projects and maybe some higher level things. I hope you don’t mind!

Staff Engineering

In August of 2019 I became a Staff Engineer, which is what a lot of companies are calling their “level above Senior Engineer” role these days. Engineering leveling is a weird beast, which probably a post onto itself. Despite my odd entry into a career in tech, my path in the last 4 or 5 years has been pretty conventional; however, somehow, despite having an increasingly normal career trajectory, explaining what I do on a day to day basis has not gotten easier.

Staff Engineers are important for scaling engineering teams, but lots of teams get by with out them, and unlike more junior engineers who have broadly similar job roles, there are a lot of different ways to be a Staff Engineer, which only muddies things. This post is a reflection on some key aspects of my experience organized in to topics that I hope will be useful for people who may be interested in becoming staff engineers or managing such a person. If you’re also a Staff Engineer and your experience is different, I wouldn’t be particularly surprised.

Staff Engineers Help Teams Build Great Software

Lots of teams function just fine without Staff Engineers and teams can build great products without having contributors in Staff-type roles. Indeed, because Staff Engineers vary a lot, the utility of having more senior individual contributors on a team depends a lot of the specific engineer and the team in question: finding a good fit is even harder than usual. In general, having Senior Technical leadership can help teams by:

  • giving people managers more space and time to focus on the team organization, processes, and people. Particularly in small organizations, team managers often pick up technical leadership.
  • providing connections and collaborations between groups and efforts. While almost all senior engineers have a “home team” and are directly involved in a few specific projects, they also tend to have broader scope, and so can help coordinate efforts between different projects and groups.
  • increasing the parallelism of teams, and can provide the kind of infrastructure that allows a team to persue multiple streams of development at one time.
  • supporting the career path and growth of more junior engineers, both as a result of direct mentoring, but also by enabling the team to be more successful by having more technical leadership capacity creates opportunities for growth for everyone on the team.

Staff Promotions Reflect Organizational Capacity

In addition to experience and a history of effusiveness, like other promotions, getting promoted to Staff Engineer is less straight forward than other promotions. This is in part because the ways we think about leveling and job roles (i.e. to describe the professional activities and capabilities along several dimensions for each level,) become complicated when there are lots of different ways to be a Staff Engineer. Pragmatically, these kind of promotions often depend on other factors:

  • the existence of other Staff Engineers in the organization make it more likely that there’s an easy comparison for a candidate.
  • past experience of managers getting Staff+ promotions for engineers. Enginering Managers without this kind of experience may have difficulty creating the kinds of opportunities within their organizations and for advocating these kinds of promotions.
  • organizational maturity and breadth to support the workload of a Staff Engineer: there are ways to partition teams and organizations that preclude some of the kinds of higher level concerns that justify having Staff Engineers, and while having senior technical leadership is often useful, if the organization can’t support it, it won’t happen.
  • teams with a sizable population of more junior engineers, particularly where the team is growing, will have more opportunity and need for Staff Engineers. Teams that are on the balance more senior, or are small and relatively static tend to have less opportunity for the kind of broadly synthetic work that tends to lead to Staff promotions.

There are also, of course, some kinds of technical achievements and professional characteristics that Staff Engineers often have, and I’m not saying that anyone in the right organizational context can be promoted, exactly. However, without the right kind of organizational support and context, even the most exceptional engineers will never be promoted.

Staff Promotions are Harder to Get Than Equivalent Management Promotions

In many organizations its true that Staff promotions are often much harder to get than equivalent promotions to peer-level management postions: the organizational contexts required to support the promotion of Engineers into management roles are much easier to create, particularly as organizations grow. As you hire more engineers you need more Engineering Managers. There are other factors:

  • managers control promotions, and it’s easier for them to recapitulate their own career paths in their reports than to think about the Staff role, and so more Engineers tend to be pushed towards management than Senior IC roles. It’s also probably that meta-managers benefit organizationally from having more front-line managers in their organizations than more senior ICs, which exacerbates this bias.
  • from an output perspective, Senior Engineers can write the code that Staff Engineers would otherwise write, in a way that Engineering Management tends to be difficult to avoid or do without. In other terms, management promotions are often more critical from the organization’s perspective and therefore prioritized over Staff promotions, particularly during growth.
  • cost. Staff Engineers are expensive, often more expensive than managers particularly at the bottom of the brackets, and it’s difficult to imagine that the timing of Staff promotions are not impacted by budgetary requirements.

Promoting a Staff Engineer is Easier than Hiring One

Because there are many valid ways to do the Staff job, and so much of the job is about leveraging context and building broader connections between different projects, people with more organizational experience and history often have an advantage over fresh industry hires. In general:

  • Success as a Staff Engineer in one organization does not necessarily translate to success at another.
  • The conventions within the process for industry hiring, are good at selecting junior engineers, and there are fewer conventions for more Senior roles, which means that candidates are not assessed for skills and experiences that are relevant to their day-to-day while also being penalized for (often) being unexceptional at the kind of problems that junior engineering interviews focus on. While interview processes are imperfect assessment tools in all cases, they’re particularly bad at more senior levels.
  • Senior engineering contributors have a the potential to have huge impact on product development, engineering outcomes, all of which requires a bunch of trust on the part of the organization, and that kind of trust is often easier to build with someone who already has organizational experience

This isn’t to say that it’s impossible to hire Staff engineers, I’m just deeply dubious of the hiring process for these kinds of roles having both interviewed for these kinds of roles and also interviewed candidates for them. I’ve also watched more than one senior contributor not really get along well with a team or other leadership after being hired externally, and for reasons that end up making sense in retrospect. It’s really hard.

Staff Engineers Don’t Not Manage

Most companies have a clear distinction between the career trajectories of people involved in “management” and senior “individual contributor” roles (like Staff Engineers,) with managers involved in leadership for teams and humans, with ICs involved in technical aspects. This seems really clear on paper but incredibly messy in practice. The decisions that managers make about team organization and prioritization have necessary technical implications; while it’s difficult to organize larger scale technical initiatives without awareness of the people and teams. Sometimes Staff Engineers end up doing actual management on a temporary basis in order to fill gaps as organizations change or cover parental leave

It’s also the case that a huge part of the job for many Staff Engineer’s involves direct mentorship of junior engineers, which can involve leading specific projects, conversations about career trajectories and growth, as well as conversations about specific technical topics. This has a lot of overlap with management, and that’s fine. The major differences is that senior contributors share responsibility for the people they mentor with their actual managers, and tend to focus mentoring on smaller groups of contributors.

Staff Engineers aren’t (or shouldn’t be!) managers, even when they are involved in broader leadership work, even if the specific engineer is capable of doing management work: putting ICs in management roles, takes time away from their (likely more valuable) technical projects.

Staff Engineers Write Boring and Tedious But Easy Code

While this is perhaps not a universal view, I feel pretty safe in suggesting that Staff Engineers should be directly involved in development projects. While there are lots of ways to be involved in development: technical design, architecture, reviewing code and documents, project planning and development, and so fort, I think it’s really important that Staff Engineers be involved with code-writing, and similar activies. This makes it easy to stay grounded and relevant, and also makes it possible to do a better job at all of the other kinds of engineering work.

Having said that, it’s almost inevitable that the kinds of contribution to the code that you make as a Staff Engineer are not the same kinds of contributions that you make at other points in your career. Your attention is probably pulled in different directions. Where a junior engineer can spend most of their day focusing on a few projects and writing code, Staff Engineers:

  • consult with other teams.
  • mentor other engineers.
  • build long and medium term plans for teams and products.
  • breaking larger projects apart and designing APIs between components.

All of this “other engineering work” takes time, and the broader portfolio of concerns means that more junior engineers often have more time and attention to focus on specific programming tasks. The result is that the kind of code you end up writing tends to be different:

  • fixing problems and bugs in systems that require a lot of context. The bugs are often not very complicated themselves, but require understanding the implication of one component with regards to other components, which can make them difficult.
  • projects to enable future development work, including building infrastructure or designing an interface and connecting an existing implementation to that interface ahead of some larger effort. This kind of “refactor things to make it possible to write a new implementation.”
  • writing small isolated components to support broader initiatives, such as exposing existing information via new APIs, and building libraries to facilitate connections between different projects or components.
  • projects that support the work of the team as a whole: tools, build and deployment systems, code clean up, performance tuning, test infrastructure, and so forth.

These kinds of projects can amount to rather a lot of development work, but they definitely have their own flavor. As I approached Staff and certainly since, the kind of projects I had attention for definitely shifted. I actually like this kind of work rather a lot, so that’s been quite good for me, but the change is real.

There’s definitely a temptation to give Staff Engineers big projects that they can go off and work on alone, and I’ve seen lots of teams and engineers attempt this: sometimes these projects work out, though more often the successes feel like an exception. There’s no “right kind” of way to write software as a Staff Engineer, sometimes senior engineer’s get to work on bigger “core projects.” Having said that, if a Staff Engineer is working on the “other engineering” aspects of the job, there’s just limited time to do big development projects in a reasonable time frame.

Related Reading